instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>ColdFusion 8 Standard Edition on OS X Leopard.</p>
<p>Developing a new website.</p>
<p>What is the best database to use in conjunction with ColdFusion?</p>
<p>Will be storing simple Credit Card operations, registration information, CRM info for an indie software company</p>
|
<p>I would look into MySQL and/or PostgreSQL. </p>
<p>I'm more familiar with MySQL. I rather like it a lot. It is solid, with good administration tools. I've used it on OSX servers (years ago) with PHP, and it delivered performance that was more than adequate for our small operation. Definitely worth looking in to.</p>
|
<p>If you go with MySQL, check out <strong>MAMP</strong> for your development environment. It will install Apache, MySQL and PHP on your machine. Then you can easily add Coldfusion on top if it. I did that on my Macbook and it works like a charm. I would guess that you could link in PostgreSQL to work as well. </p>
<p><strong>MAMP Website</strong>: <a href="http://www.mamp.info/" rel="nofollow noreferrer">http://www.mamp.info/</a></p>
<p>For an EXTREMELY helpful video on getting CF8 working on WAMP, check out the following link:
<a href="http://flashalisious.com/2007/12/14/installing-coldfusion8-on-leopard-using-mamp/" rel="nofollow noreferrer">http://flashalisious.com/2007/12/14/installing-coldfusion8-on-leopard-using-mamp/</a></p>
<p><em>(if you use windows, click the following link: <a href="http://www.wampserver.com/" rel="nofollow noreferrer">http://www.wampserver.com/</a><br>
FYI, I have never tried installing Coldfusion on WAMP, but I am sure it will work)</em></p>
| 26,826
|
<p>I've worked on several PHP projects and always I have problems with organizing my work. Where do you develop your application - on localhost, remote server or maybe production one(!) ?
When I work on my localhost after making some major path I send new files by ftp - but sometimes it happens to forget about one file and it is just tiring to browse several directiores to copy changed files.
What best practises do you propose?</p>
|
<p>This is how we manage our commercial site:</p>
<ol>
<li>Develop in a local sand box</li>
<li>Check-in to SVN</li>
<li>Automated build/test from SVN onto internal
dev server</li>
<li>Scripted deploy using rsync to staging
server for QA/UAT</li>
<li>Scripted deploy onto production
servers.</li>
</ol>
<p>Staging and production servers are both hosted by the ISP and are hardware and version matched and run RHEL, internal Dev server is version matched CentOS.</p>
<p>This way, when code hits the production servers there shouldn't be any nasty surprises as even the deploy scripts get checked in stage 4. </p>
|
<p>I'm developing on a development machine which has an identical enviroment like the production one - that prevents some different behaviour because of different versions or configs. after finishing i just move all the files on to the production server.</p>
<p><a href="http://www.winmerge.org/" rel="nofollow noreferrer">Winmerge</a> is a nice and free windows tool to diff your files between development and production machine.</p>
| 31,931
|
<p>I want to generate some formatted output of data retrieved from an MS-Access database and stored in a <em>DataTable</em> object/variable, myDataTable. However, some of the fields in myDataTable cotain <em>dbNull</em> data. So, the following VB.net code snippet will give errors if the value of any of the fields <em>lastname</em>, <em>intials</em>, or <em>sID</em> is <em>dbNull</em>.</p>
<pre><code> dim myDataTable as DataTable
dim tmpStr as String
dim sID as Integer = 1
...
myDataTable = myTableAdapter.GetData() ' Reads the data from MS-Access table
...
For Each myItem As DataRow In myDataTable.Rows
tmpStr = nameItem("lastname") + " " + nameItem("initials")
If myItem("sID")=sID Then
' Do something
End If
' print tmpStr
Next
</code></pre>
<p>So, how do i get the above code to work when the fields may contain <em>dbNull</em> without having to check each time if the data is dbNull as in <a href="https://stackoverflow.com/questions/105671/any-systemdbnullvalue-vs-any-is-systemdbnull">this question</a>?</p>
|
<p>The only way that i know of is to test for it, you can do a combined if though to make it easy.</p>
<pre><code>If NOT IsDbNull(myItem("sID")) AndAlso myItem("sID") = sId Then
'Do success
ELSE
'Failure
End If
</code></pre>
<p>I wrote in VB as that is what it looks like you need, even though you mixed languages.</p>
<p><strong>Edit</strong></p>
<p>Cleaned up to use IsDbNull to make it more readable</p>
|
<p><strong>Hello Friends</strong></p>
<p><strong>This is the shortest method to check db Null in DataGrid and convert to string</strong></p>
<ol>
<li>create the cell validating event and write this code</li>
<li>If Convert.ToString(dgv.CurrentCell.Value) = "" Then</li>
<li>CurrentCell.Value = ""</li>
<li>End If </li>
</ol>
| 27,501
|
<p>is there a way to abort threads created with QueueUserWorkItem?</p>
<p>Or maybe I don't need to? What happens if the main application exits? Are all thread created from it aborted automatically?</p>
|
<p>You don't need to abort them. When your application exits, .NET will kill any threads with IsBackground = true. The .NET threadpool has all its threads set to IsBackground = true, so you don't have to worry about it.</p>
<p>Now if you're creating threads by newing up the Thread class, then you'll either need to abort them or set their IsBackground property to true.</p>
|
<p>yeah, they are background, but f.ex if you have application where you use ThreadPool for some kinda multiple downloading or stuff, and you want to stop them, how do you stop ? my suggestion would be:
exit thread asap, f.ex </p>
<pre><code>bool stop = false;
void doDownloadWork(object s)
{
if (!stop)
{
DownloadLink((String)s, location);
}
}
</code></pre>
<p>and if you set stop = true, second (currently in queue) threads automatically exit, after queue threads finishes it process.</p>
| 4,641
|
<p>Does anybody have an implementation of <a href="http://en.wikipedia.org/wiki/Cuckoo_hashing" rel="noreferrer">Cuckoo hashing</a> in C? If there was an Open Source, non GPL version it would be perfect!</p>
<p>Since Adam mentioned it in his comment, anyone knows why it is not much used? Is it just a matter of implementation or the good theoretical properties do not materialize in practice?</p>
|
<p><a href="http://www.mpi-inf.mpg.de/~sanders/programs/cuckoo/" rel="noreferrer">http://www.mpi-inf.mpg.de/~sanders/programs/cuckoo/</a></p>
<p>HTH</p>
|
<p>The IO language has one, in PHash.c. You can find the <a href="http://github.com/stevedekorte/io" rel="nofollow noreferrer">code for IO</a> on Github. IO is BSD licensed.</p>
| 28,652
|
<p>How would one go about adding a submenu item to the windows explorer context menu (like for example 7-Zip does) for a Java application?</p>
|
<p>I am aware of two ways to do it. The fancy way is to write a windows shell extension, which is how powerarchiver, winzip etc do it I believe (this involves running code to determine what the context menu items will be dependent on the file chosen).</p>
<p>The simple way, for simple functionality, is you can add an entry in the registry :</p>
<pre><code>HKEY_CLASSES_ROOT\<file type>\shell\<display text>\command
</code></pre>
<p>Where <code><file type></code> is the files that this context menu should apply to i.e. *, .mdb, .doc</p>
<p>and</p>
<p><code><display text></code> what you want to show in the context menu.</p>
<p>Then add the default string as a path to the application you want to launch from the context menu, and you can use %1 to refer to the currently selected file i.e. for MS Access I use :</p>
<pre><code>HKEY_CLASSES_ROOT\*\shell\MS Access 2000\command
"C:\Program Files\Microsoft Office\Office\MSACCESS.EXE" "%1"
</code></pre>
<p>This then adds a context menu item for any file I select (hence the *), which allows me to launch it in MS Access 2000.</p>
<p>Of course, always back up your registry before hacking it.</p>
<p>Your program could do this during install, or on first run.</p>
|
<p>You could also package the java program in an installer like NSIS and you could use NSIS script to generate explorer context menu</p>
| 48,345
|
<p>I need to do a lot of searches of certain patterns in source files while the user is changing them, so I need to do regexp matching that is efficient in time and memory. The pattern repeats itself so should be compiled once, but I need to be able to retrieve subparts (rather than just confirm a match)</p>
<p>I'm considering using java.util.regexp or the Jakarta perl5util (if it still exists, been a few years since I used it), or perhaps the Eclipse search engine though I doubt that ti's smarter. </p>
<p>Is there any significant performance difference between the two?</p>
|
<p>I am not sure there is a huge performance gap in term of the different regexp java engines.</p>
<p>But there sure is a performance issue when constructing a regexp (and that is, if the data is large enough, as <a href="http://blog.codinghorror.com/regex-performance/" rel="nofollow noreferrer">noted by Jeff Atwood</a>)</p>
<p>The only thing you should avoid is <a href="http://www.regular-expressions.info/catastrophic.html" rel="nofollow noreferrer">catastrophic backtracking</a>, better avoided when using <a href="http://www.regular-expressions.info/atomic.html" rel="nofollow noreferrer">atomic grouping</a>.</p>
<p>So, by default I would use the java.utils.regexp engine, unless you have specific perl-compliant sources of regexp you need to reuse in your program.</p>
<p>Then I would carefully construct the regexp I intend to use.</p>
<p>But in term of choosing one engine or another... as it <a href="https://stackoverflow.com/questions/48732/what-are-your-top-design-consideration#48737">has been</a> <a href="https://stackoverflow.com/questions/42383/java-object-allocation-overhead#42410">said</a> in <a href="https://stackoverflow.com/questions/30754/performance-vs-readability#30789">many</a> <a href="https://stackoverflow.com/questions/2750/data-verifications-in-gettersetter-or-elsewhere#2761">other questions</a>...:</p>
<ul>
<li>"make it work, make it fast - in that order"</li>
<li>beware of "premature optimization".</li>
</ul>
|
<p>As VonC says, you need to know your regexps. It doesn't hurt to compile the Regexes beforehand OTHERWISE, the cost of compiling regex each time can hurt the performance badly.</p>
<p>For some categories, there are alternate libraries : <a href="http://jint.sourceforge.net/jint.html" rel="nofollow noreferrer">http://jint.sourceforge.net/jint.html</a> which might have better performance. Then again, it depends upon which version of java you're using.</p>
<p>JDK 1.6 shows the maturity of the regex engine with good features and performance combined.</p>
| 23,079
|
<p>Is there a way to monitor processes starting in the system before they start?</p>
<p>Example:<br>
On programs like ZoneAlarm or Antivirus programs, when you run a program it asks you if you allow running this program or not before it runs...<br></p>
|
<p>You should check out the <a href="http://code.google.com/p/easyhook-continuing-detours/" rel="noreferrer">easyhook-continuing-detours</a> project, which is a .NET port of the <a href="http://research.microsoft.com/sn/detours/" rel="noreferrer">Microsoft Detours</a> project. It will allow you to hook unmanaged APIs (such as CreateProcess). Check out code examples for a simple FileMon-like program <a href="http://code.google.com/p/easyhook-continuing-detours/wiki/Introduction" rel="noreferrer">here</a>.</p>
|
<p>You can find out when processes start via using a real-time ETW consumer - however, to be able to take some action that could possibly <em>cancel</em> the process from starting, you'll have to do something shady / undocumented, like hooking CreateProcess, or using a kernel filter driver to block reads to the EXE.</p>
| 37,477
|
<p>I need to write a web application using SQL Server 2005, asp.net, and ado.net. Much of the user data stored in this application must be encrypted (read HIPAA).</p>
<p>In the past for projects that required encryption, I encrypted/decrypted in the application code. However, this was generally for encrypting passwords or credit card information, so only a handful of columns in a couple tables. For this application, far more columns in several tables need to be encrypted, so I suspect pushing the encryption responsibilities into the data layer will be better performing, especially given SQL Server 2005's native support for several encryption types. (I could be convinced otherwise if anyone has real, empirical evidence.)</p>
<p>I've consulted BOL, and I'm fairly adept at using google. So I don't want links to online articles or MSDN documentation (its likely I've already read it).</p>
<p>One approach I've wrapped my head around so far is to use a symmetric key which is opened using a certificate.</p>
<p>So the one time setup steps are (performed by a DBA in theory):</p>
<ol>
<li>Create a Master Key </li>
<li>Backup the Master Key to a file, burn to CD and store off site.</li>
<li>Open the Master Key and create a certificate.</li>
<li>Backup the certificate to a file, burn to CD and store off site.</li>
<li>Create the Symmetric key with encryption algorithm of choice using the certificate.</li>
</ol>
<p>Then anytime a stored procedure (or a human user via Management Studio) needs to access encrypted data you have to first open the symmetric key, execute any tsql statements or batches, and then close the symmetric key.</p>
<p>Then as far as the asp.net application is concerned, and in my case the application code's data access layer, the data encryption is entirely transparent.</p>
<p>So my questions are:</p>
<ol>
<li><p>Do I want to open, execute tsql statements/batches, and then close the symmetric key all within the sproc? The danger I see is, what if something goes wrong with the tsql execution, and code sproc execution never reaches the statement that closes the key. I assume this means the key will remain open until sql kills the SPID that sproc executed on.</p></li>
<li><p>Should I instead consider making three database calls for any given procedure I need to execute (only when encryption is necessary)? One database call to open the key, a second call to execute the sproc, and a third call to close the key. (Each call wrapped in its own try catch loop in order to maximize the odds that an open key ultimately is closed.)</p></li>
<li><p>Any considerations should I need to use client side transactions (meaning my code is the client, and initiates a transaction, executes several sprocs, and then commits the transaction assuming success)?</p></li>
</ol>
|
<p>1) Look into using TRY..CATCH in SQL 2005. Unfortunately there is no FINALLY, so you'll have to handle both the success and error cases individually.</p>
<p>2) Not necessary if (1) handles the cleanup.</p>
<p>3) There isn't really a difference between client and server transactions with SQL Server. Connection.BeginTransaction() more or less executes "BEGIN TRANSACTION" on the server (and System.Transactions/TransactionScope does the same, until it's promoted to a distributed transaction). As for concerns with open/closing the key multiple times inside a transaction, I don't know of any issues to be aware of.</p>
|
<ol>
<li><p>you can use @@error to see if any errors occured during the call to a sproc in SQL.</p></li>
<li><p>No to complicated.</p></li>
<li><p>You can but I prefer to use transactions in SQL Server itself.</p></li>
</ol>
| 8,468
|
<p>I have a strongly-typed MVC View Control which is responsible for the UI where users can create and edit Client items. I'd like them to be able to define the <code>ClientId</code> on creation, but not edit, and this to be reflected in the UI.</p>
<p>To this end, I have the following line:</p>
<pre><code><%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, new
{ @readonly =
(ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0
? "readonly" : "false")
} )
%>
</code></pre>
<p>It seems that no matter what value I give the readonly attribute (even "false" and ""), Firefox and IE7 make the input read-only, which is annoyingly counter-intuitive. Is there a nice, ternary-operator-based way to drop the attribute completely if it is not required?</p>
|
<p>Tough problem... However, if you want to define only the <code>readonly</code> attribute, you can do it like this:</p>
<pre><code><%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId,
ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0
? new { @readonly = "readonly" }
: null)
%>
</code></pre>
<p>If you want to define more attributes then you must define two anonymous types and have multiple copies of the attributes. For example, something like this (which I don't like anyway):</p>
<pre><code>ClientId.Length > 0
? (object)new { @readonly = "readonly", @class = "myCSS" }
: (object)new { @class = "myCSS" }
</code></pre>
|
<p>I tried most of the suggestions above and now I have arrived at the simplest with a single line. Combine 2 anonymous html attributes object by declaring wither one of it as "object" type.</p>
<pre><code>@Html.TextBoxFor(m => m.Email, !isEdit ? new { id = "email_box" } : new { id = "email_box", @readonly = isEdit ? "readonly" : "false" } as object)
</code></pre>
| 21,405
|
<pre><code> String fullName = PATH + "." + name;
Class cl= Class.forName(fullName);
if(name.equalsIgnoreCase("MobileSearch")){
if(msearchType==null){
msearchType=(SearchInterface)cl.newInstance();
}
return msearchType;
}
if(name.equalsIgnoreCase("BookSearch")){
if(bsearchType==null){
bsearchType=(SearchInterface)cl.newInstance();
}
return bsearchType;
}
</code></pre>
<p>How do I get rid of the <code>if</code> statements here.<br>
I am using reflection.<br>
Please help. Thanks in advance.</p>
|
<p>Use a Map:</p>
<pre><code>if (!searchInstances.containsKey(name))
{
searchInstances.put(
name,
(SearchInterface)Class.forName(PATH + "." + name).newInstance()
);
}
return searchInstances.get(name);
</code></pre>
|
<p>Are you just returning an instance of a SearchInterface? If so why not:</p>
<pre><code>String fullName = PATH + "." + name;
Class cl= Class.forName(fullName);
if(searchType==null){
searchType=(SearchInterface)cl.newInstance();
}
return searchType;
</code></pre>
<p>Hope that helps.</p>
| 46,393
|
<p>Does anyone know what is wrong with this query?</p>
<pre><code> SELECT DISTINCT c.CN as ClaimNumber,
a.ItemDate as BillReceivedDate, c.DTN as
DocTrackNumber
FROM ItemData a,
ItemDataPage b,
KeyGroupData c
WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
AND a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC;
</code></pre>
<p>I have done T-Sql most of my career and this looks correct to me, however this query is for an Oracle database and Toad just places the cursor on the a.DateStored in the Order By section. I'm sure this is elementary for anyone doing PL/SQL.</p>
<p>Thanks!</p>
<p>[EDIT] For future reference, the error given by SQL*Plus was: "ORA-01791: not a SELECTed expression" </p>
|
<p>You will need to modify the query as such:</p>
<pre><code>SELECT DISTINCT c.CN as ClaimNumber,
a.ItemDate as BillReceivedDate, c.DTN as
DocTrackNumber, a.DateStored
FROM ItemData a,
ItemDataPage b,
KeyGroupData c
WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
AND a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC;
</code></pre>
<p>When doing a DISTINCT your order by needs to be one of the selected columns.</p>
|
<p>Nevermind, executing in SQL Plus gave me a more informative answer. The DateStored needs to be in the select statement so this works:</p>
<pre><code> SELECT DISTINCT c.CN as ClaimNumber,
a.ItemDate as BillReceivedDate,
c.DTN as DocTrackNumber,
a.DateStored
FROM ItemData a,
ItemDataPage b,
KeyGroupData c
WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
AND a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC;
</code></pre>
| 30,168
|
<p>Management is thinking of changing out Content Management Systems. What do you use/recommend?</p>
<ol>
<li>What UCM solution is your company using?</li>
<li>How big is your company?</li>
<li>Are you happy with the implementation?</li>
</ol>
<p>Current setup:</p>
<ol>
<li>The company I work for uses <code>Oracle ECM</code> (formerly Stellent UCM).</li>
<li>We have somewhere over 10,000 employees across Australia, New
Zealand and Indonesia.</li>
<li>It works! Having worked with the system for a while now. I can see
where the initial implementation went wrong. Its 3 years later and
it is <em>Rewrite Time!</em> (Three year itch?)</li>
</ol>
|
<p>1) CMS: <a href="http://www.bea.com/framework.jsp?CNT=index.htm&FP=/content/products/aqualogic/" rel="nofollow noreferrer">Oracle's BEA Aqualogic</a><br>
2) Size: 10,000+<br>
3) Experience: As an end user with full community and content admin privileges, I find the tool to be outdated and stifling in terms of knowledge sharing and trying to get the benefits that exist in social networks. Perhaps this is due to the implementation, and not an inherent weakness in the product. Not sure of the future direction of the product either, since Oracle recently acquired it. </p>
|
<ol>
<li><p>We use the Alterian Content Manager application. It is very robust and suites our needs well.</p></li>
<li><p>20000 staff+</p></li>
<li><p>Very happy. Developers and business team find the application very easy to work with.</p></li>
</ol>
| 3,990
|
<p>I'm writing an HTML form generation library. There's a top-level Form class, and at the bottom there are classes for each type of HTML form input object (Select, Textfield, Radio, etc.). There's a class in between, that holds groupings of 1 or more semantically related input objects.</p>
<p>For example, one type of this class could be called 'Login', and would contain a Textfield input and a Password input. As another example, the primary usage of the form library will be to generate online surveys, so the intermediate classes will be survey questions of various sorts.</p>
<p>My question is what to generically call these intermediate level classes. Some of the things that have been suggested within our working group are 'Set', 'Fieldset', 'Group', 'Block', 'Chunk', and 'Conglomeration'. </p>
<p>Several of these suggestions are "okay", but none of them have tripped the "that's it!" interrupt. (The one that came closest is the latter, but that's (a) far too long and (b) too subject to mispeling.) Does anyone have any better suggestions?</p>
|
<p>Component, as in the "Login Component" or the "Multivalued Response Component".</p>
<p>FYI. I find <a href="http://thesaurus.reference.com" rel="nofollow noreferrer">http://thesaurus.reference.com</a> very helpful for problems like this.</p>
|
<p>Component, as in the "Login Component" or the "Multivalued Response Component".</p>
<p>FYI. I find <a href="http://thesaurus.reference.com" rel="nofollow noreferrer">http://thesaurus.reference.com</a> very helpful for problems like this.</p>
| 41,774
|
<p>There are lot of advices on the web how to paint the 3D printed objects, but generally they are advices for manual painting and this required special skills, especially if the object is small. My guess is that maybe 3D printer can lay the color layers as well? I am especially interested in the layering of enamel paints (which can be transparent and which can required high temperature heating afterwards). Medieval art has fine examples how detailed enamel art was created on the metal. Maybe something like this can be achieved with 3D printers as well?</p>
<p>If 3D priner with the paint-printing capability is not available generally then what are the prospects when such printer can be available? Maybe there are some early, experimental efforts to create such printer and maybe test devices are available?</p>
|
<p>So, there's not really anything like a 3D painting machine/robot like I think you're looking for, but there are printers that do fine detail with actual paint, usually oils, but not on 3D materials.</p>
<p>I found a <a href="https://studioartist.ning.com/forum/topics/paint-printers-do-they-exist" rel="nofollow noreferrer">thread</a> that talks about canvas printing about 8 years ago, along with a couple of videos that show <a href="https://www.youtube.com/watch?v=vj3NKmIKErE" rel="nofollow noreferrer">current machines</a> doing <a href="https://www.youtube.com/watch?v=0Ri7sa90EVk" rel="nofollow noreferrer">just that</a>, but that's still not what I think you're looking for.</p>
<p>There are also <a href="https://www.youtube.com/watch?v=SK0r7PfMUwQ" rel="nofollow noreferrer">CNC machines</a> that print with enamel paints, but these are usually for 2D again, and not very precise, as they are used for lapel pins that have cavities to hole the paint while it dries. I'm sure something like this could be used without the cavities, but you'd have to do a lot of testing to make sure the paint stays put or mixes as you want it.</p>
<p>Just like the oil printers, these enamel printers are likely very large and costly.</p>
<h2>Alternatively</h2>
<p>What might work for you is hydrodipping. There's a variety of methods to this, but one company has done a bunch of research on this and can do extremely accurate detail printing to "paint" 3D objects. The below video shows a variety of these hydrodipping techniques, but I've skipped to the most relevant part.</p>
<p><div class="youtube-embed"><div>
<iframe width="640px" height="395px" src="https://www.youtube.com/embed/3y40JWmlU3E?start=240"></iframe>
</div></div></p>
<p>Here's the original video of what I think you're most interested in. It's not 3D printing in the way most of us think, but it's definitely a fantastic outcome.</p>
<p><div class="youtube-embed"><div>
<iframe width="640px" height="395px" src="https://www.youtube.com/embed/YlUhPrAqiY0?start=0"></iframe>
</div></div></p>
<p>To explain, if these videos are ever deleted: detailed prints are made of a 3D model to color it exactly the way it needs to be, sometimes using multiple steps and computer positioning to get the object colored/"painted" correctly and seamlessly. One part of the video shows how the software can accurately make straight lines on a human-contoured face mask, while another part shows how a blank, fully 3D cat model can have spots or stripes added in 3 steps with the seams being completely invisible as well as it detailed enough to be mistaken for a real housecat beyond first glance.</p>
<p>As it turns out, you can do (some of) this yourself. After doing some research, I've found that you can actually get blank (instead of pre-printed) films and use an off the shelf printer, as long as it meets certain requirements. (I'm not recommending a site, brand, or anything else, this is just the first/only option I can find. If you do more research, I'm sure there's more options out there.)</p>
<p><a href="https://www.tsautop.com/blank-hydrographic-film/" rel="nofollow noreferrer">https://www.tsautop.com/blank-hydrographic-film/</a></p>
<p><a href="https://www.tsautop.com/blank-hydrographic-water-transfer-printing-inkjet-printer-6-color-inks/" rel="nofollow noreferrer">https://www.tsautop.com/blank-hydrographic-water-transfer-printing-inkjet-printer-6-color-inks/</a></p>
|
<h2>Painting Prints</h2>
<p>Yes, you can paint your models with <a href="https://en.wikipedia.org/wiki/Enamel_paint" rel="nofollow noreferrer">enamel paints</a>. Actually, most paints will work. You might need to roughen the surface with sandpaper a tiny bit. Note that some spray paints might contain solvents that might soften or melt the prints, so read your ingredients!</p>
<h3>...not with vitreous enamel</h3>
<p>However, you can't use <a href="https://en.wikipedia.org/wiki/Vitreous_enamel" rel="nofollow noreferrer">proper enamel</a>, as that needs to be sintered after the paints have dried, and that will destroy your print unless you have used a metal-printer.</p>
<h2>Printing Color</h2>
<p>Now, if you want a printer to print a paste of vitreous enamel, you are looking for a <strong>paste printer</strong>. However, the paint for such a device needs to be very viscous, and the print quality (due to the large nozzle) will be far below what a skilled artisan can achieve. Also, you'd need one paste extruder per color.</p>
<h2>Foils?</h2>
<p>One could possibly work with foils, cutting them on a plotter and then carefully transferring them to the printed object. This would allow much finer details than a paste printer currently is able to create. Such a foil can also be printed upon by special printers - possibly achieving the full spectrum in a single application step.</p>
<p>Alternatively, one would use a "puzzle" of smaller pieces and apply each piece separately. The result might actually be somewhat similar to the <em>Chromolith</em> (Colored Stone) stonewares that had been created by Villeroy & Boch starting 1876.</p>
| 1,779
|
<p>Our security manager dynamically inserts a bit of javascript at the top of every html page when a page is requested by the client. It is inserted above the DOCTYPE statement. I think this might be the cause of the layout problems I am having.</p>
<p>Ideas anyone?</p>
|
<p>Yes, the DOCTYPE must come first.</p>
<p>The definition is here: <a href="http://www.w3.org/TR/REC-html40/struct/global.html" rel="noreferrer">http://www.w3.org/TR/REC-html40/struct/global.html</a>. Note that it says a document consists of three parts, and the DTD must be first.</p>
|
<p>It’s not a tag, but yup. Mainly because that’s the only way to get Internet Explorer (pre-version 8, I think) into standards mode.</p>
| 9,520
|
<p>I'm struggling with my new printer, and I just want to make sure that I have the basic configured correctly. </p>
<p>What motherboard ID in <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration.h" rel="nofollow noreferrer"><code>configuration.h</code></a> is appropriate for MKS BASE V1.5 in Marlin Firmware?</p>
|
<p>Marlin appears to support older versions of the board (and possibly this one) according to this line </p>
<pre><code>#define BOARD_MKS_13 47 // MKS v1.3 or 1.4 (maybe higher)
</code></pre>
<p>in <code>boards.h</code> which can be found <a href="https://github.com/MarlinFirmware/Marlin/blob/RC/Marlin/boards.h" rel="nofollow noreferrer">here</a>. </p>
<p>The company also has a <a href="https://web.archive.org/web/20180223090126/http://osoyoo.com/2016/06/30/mks-1-4-3d-printer-board-marlin-firmware-installation-guide/" rel="nofollow noreferrer">guide</a> and looks to provide pre-configured (but not fully configured?) downloads of Marlin. They have different links for different displays but then ask you to change lines manually but don't mention changing the board so I have no idea what they are doing or what is different between the downloads.</p>
<p>It appears either way you go (Marlin from Github or from Osoyoo) you will need to change some lines to get each axis to behave correctly.</p>
|
<p>A more recent version of Marlin Firmware (<em>version 1.1.9 is the last release of this branch, new developments are done in the 2.x branch</em>) nowadays has a separate board constant for the MKS BASE v1.5 board (<code>BOARD_MKS_BASE_15</code>) as can be found in <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/boards.h" rel="nofollow noreferrer">boards.h</a>.</p>
<p>The following line quotes the constant for this board from the file:</p>
<blockquote>
<p><code>#define BOARD_MKS_BASE_15 405 // MKS v1.5 with Allegro A4982 stepper drivers</code></p>
</blockquote>
| 583
|
<p>In some languages you can override the "new" keyword to control how types are instantiated. You can't do this directly in .NET. However, I was wondering if there is a way to, say, handle a "Type not found" exception and manually resolve a type before whoever "new"ed up that type blows up?</p>
<p>I'm using a serializer that reads in an xml-based file and instantiates types described within it. I don't have any control over the serializer, but I'd like to interact with the process, hopefully without writing my own appdomain host.</p>
<p>Please don't suggest alternative serialization methods. </p>
|
<p>You can attach an event handler to AppDomain.CurrentDomain.AssemblyResolve to take part in the process.</p>
<p>Your EventHandler should return the assembly that is responsible for the type passed in the ResolveEventArgs.</p>
<p>You can read more about it at <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx" rel="nofollow noreferrer">MSDN</a></p>
|
<p>You should check out Reflection and the Activator class. They will allow you to create objects from strings. Granted, the object has to be in one of the assemblies that you have access to.</p>
| 10,246
|
<p>I talked to a friend of mine and he told me that it's possible to create an image in an image editor (gimp/photoshop) and then use it as a button . He said that's the way applications that have great GUIs do it. </p>
<p>He also said that there is a file describing which parts of the image make up the button.</p>
<p>Is this possible , or is he "crazy"? :)</p>
|
<p>This needs to be clarified with a language of choice, etc. In general, most languages (WinForms, Java AWT/SWT, etc) have an image or background image property that allows you to use images for buttons. There are even skinning frameworks that will let you use images for all controls in an easy-to-define manner.</p>
<p>If you are talking about HTML, there is a button input type that can allow an image to be used as a button for a form.</p>
<p>@Vhaerun<br/>
<a href="http://www.codeproject.com" rel="nofollow noreferrer">CodeProject</a> is a good place to find lots of skinning libraries. I used <a href="http://www.codeproject.com/KB/library/SkinCtrl.aspx" rel="nofollow noreferrer">this one</a> a long time ago. <a href="http://www.winamp.com" rel="nofollow noreferrer">Winamp</a> is a great example of a skinned application, where users can actually create their own templates to completely change the look of the application without changing code whatsoever. Actually, most media players have some sort of skinning available.</p>
|
<p>Imagemaps I guess.
No seperate file describes the map, it is all part of the html document.</p>
<p><a href="http://www.w3schools.com/TAGS/tag_map.asp" rel="nofollow noreferrer">http://www.w3schools.com/TAGS/tag_map.asp</a></p>
| 9,940
|
<p>So, I've been tasked with making a kiosk for the office for showing statistics about our SCRUM progress, build server status, rentability and so forth. It should ideally run a slideshow with bunch of different pages, some of them showing text, some showing graphs and so on. </p>
<p>What is the best approach for this? I first thought of powerpoint, but It should be able to take the images from a webserver so I can automate the graph generation procedure. I would also like to take text from an external source when showing "Who broke the build" or some page like that.</p>
<p>I have no doubt that ready-made systems exist, but I don't really know where to look for them.</p>
<p>Is this easy/hard in powerpoint? Or are there an ubiquous app that everybody but me knows about?</p>
|
<p>I would recommend creating it as a series of web-pages, which uses Javascript or the meta refresh tag to cycle though the different pages. Simply full-screen the browser on a spare machine, and connect it to a projector/monitor/big TV.</p>
<p>This has lots of benefits:</p>
<ul>
<li>it's <em>trivial</em> to display images from an external server (an <code><img></code> tag)</li>
<li>it will cost nothing to setup (it can run on basically any functioning machine), and runs in a browser</li>
<li>it is quick to do (you do not have to worry about cross-browser compatibility, or different screen resolutions as you know the exact machine you are developing for</li>
<li>it's expandable - while what you describe is probably possible within Powerpoint, but if you do it as a web-page, you can use Javascript (or a JS framework like jQuery), and it's very easy to serve the pages via a web-server, then you can use any server-side scripting language.</li>
</ul>
<p>Basically, you would have a series of files, say <code>slide001.htm</code>, <code>slide002.htm</code> and <code>slide003.htm</code>. Slide 1 would redirect to slide002 after 30 seconds, slide002 to slide 003, and slide003 would redirect to slide001..</p>
<p>The specific things you mention: graph generation and "Who broke the build" text:</p>
<p>Not sure which CI tool you use, but many of them generate graphs anyway, so that would be required is having one "slide" with something like <code><img src="http://hudson.abc/job/proj042/buildTimeGraph"></code></p>
<p>For the who-broke-the-build text, you would be easiest to run the slides as <code>.php</code> files served though a web-server, using <a href="http://www.apachefriends.org/en/xampp.html" rel="nofollow noreferrer">XAMMP</a>.</p>
<p>Then you would have a function that scrapes your CI server for whoever broke the last build, and in one of the slides, you would have <code><?PHP echo(who_broke_build()); ?></code></p>
<p>(Obviously if you know some other language/system better, use that!)</p>
<p>The final benefit I can think of is that, if you serve the files through a web-server, you can allow people display it locally, say as their browsers home-page.</p>
|
<p>Thanks. I found jqS5 which did most of what you mentioned.</p>
<p>It requires 1 document where every h2 becomes a new slide.
I can then use the meta-refresh to reload to next page every 10 seconds. When I reach the end of the slides, I pull data from an aggregated RSS feed from all the different systems in order to pull information.</p>
<p><a href="http://staticfree.info/projects/jqs5/" rel="nofollow noreferrer">http://staticfree.info/projects/jqs5/</a></p>
| 36,647
|
<p>I have a Windows application written in C++ that occasionally evaporates. I use the word evaporate because there is nothing left behind: no "we're sorry" message from Windows, no crash dump from the Dr. Watson facility...</p>
<p>On the one occasion the crash occurred under the debugger, the debugger did not break---it showed the application still running. When I manually paused execution, I found that my process no longer had any threads.</p>
<p>How can I capture the reason this process is terminating?</p>
|
<p>You could try using the adplus utility in the <a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx" rel="noreferrer">windows debugging tool package</a>.</p>
<pre><code>adplus -crash -p yourprocessid
</code></pre>
<p>The auto dump tool provides mini dumps for exceptions and a full dump if the application crashes.</p>
|
<p>Have you tried PC Lint etc and run it over your code?
Try compiling with maximum warnings
If this is a .NET app - use FX Cop.</p>
| 49,558
|
<p>Trying to make a <a href="http://en.wikipedia.org/wiki/Web_service" rel="noreferrer">web service</a> call to an <a href="http://en.wikipedia.org/wiki/HTTP_Secure" rel="noreferrer">HTTPS</a> endpoint in my <a href="http://en.wikipedia.org/wiki/Microsoft_Silverlight" rel="noreferrer">Silverlight</a> application results in this error: "Could not find a base address that matches scheme https for the endpoint with binding WSHttpBinding. Registered base address schemes are [http]"</p>
<p>The same problem as was posted here:</p>
<p><a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/4c19271a-f5e6-4659-9e06-b556dbdcaf82/" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/4c19271a-f5e6-4659-9e06-b556dbdcaf82/</a></p>
<p>So, one of the suggestions was this: "The other issue might be that the cert name and the machine name don't agree, and this is causing <a href="http://en.wikipedia.org/wiki/Windows_Communication_Foundation" rel="noreferrer">WCF</a> to have fits. If this is the case, you can tell WCF to skip verification of the cert."</p>
<p>Well, I <strong>do</strong> get a certificate error because this is just a demo server.</p>
<p>Here's how I set up my client:</p>
<pre><code>BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Transport;
_ws = new AnnotationService.AnnotationClient(binding, new EndpointAddress(myAddress));
</code></pre>
<p>How can I tell WCF to skip the verification?</p>
|
<p>You might be able to achieve this in Silverlight by <strong>allowing cross-domain communication</strong> between the web server the hosts the Silverlight application and the remote WCF service.</p>
<p>In that case you need to place a <a href="http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html" rel="noreferrer"><strong>clientaccesspolicy.xml</strong></a> file at the root of the domain where the WCF service is hosted:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="SOAPAction">
<domain uri="http://*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
</code></pre>
<p>Here's what <a href="http://msdn.microsoft.com/en-us/library/cc197955(v=vs.95).aspxhttp://msdn.microsoft.com/en-us/library/cc197955(v=vs.95).aspx" rel="noreferrer">MSDN states about this approach</a>:</p>
<blockquote>
<p>To allow access to an HTTPS service
from any Silverlight control hosted
over HTTP application, you need to put
the <em><domain uri=”http://</em>” />* element
inside your <em><allow-from></em> element.</p>
</blockquote>
<p>I haven't tried this myself but it could be worth a shot. Also be sure to check out the following resources for more details:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/cc197955(v=vs.95).aspxhttp://msdn.microsoft.com/en-us/library/cc197955(v=vs.95).aspx" rel="noreferrer">Making a Service Available Across Domain Boundaries</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/cc197941(v=vs.95).aspx" rel="noreferrer">Configuring Web Service Usage in Silverlight Clients</a></li>
</ul>
<hr>
<h2>Disabling X.509 certificate validation in .NET</h2>
<p>For .NET applications this sample WCF configuration will disable validation of both whether the certificate is trusted and whether it is still valid on the client:</p>
<pre><code><system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="DisableServiceCertificateValidation">
<clientCredentials>
<serviceCertificate>
<authentication certificateValidationMode="None"
revocationMode="NoCheck" />
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://localhost/MyService"
behaviorConfiguration="DisableServiceCertificateValidation"
binding="wsHttpBinding"
contract="MyNamespace.IMyService"
name="MyServiceWsHttp" />
</client>
</system.serviceModel>
</code></pre>
<p><strong>An alternative solution</strong> is to provide custom logic to validate the X.509 certificate provided by the service. In that case you will have to modifiy the configuration file according to the following:</p>
<pre><code><system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="DisableServiceCertificateValidation">
<clientCredentials>
<serviceCertificate>
<authentication certificateValidationMode="Custom"
customCertificateValidatorType="MyCertificateValidator, Client"
revocationMode="NoCheck" />
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://localhost/MyService"
behaviorConfiguration="DisableServiceCertificateValidation"
binding="wsHttpBinding"
contract="MyNamespace.IMyService"
name="MyServiceWsHttp" />
</client>
</system.serviceModel>
</code></pre>
<p>Then create a class that derives from <a href="http://msdn.microsoft.com/en-us/library/system.identitymodel.selectors.x509certificatevalidator.aspx" rel="noreferrer">X509CertificateValidator</a> to implement your custom validation logic.</p>
<pre><code>public class MyCertificateValidator : X509CertificateValidator
{
public override void Validate(X509Certificate2 certificate)
{
// Add custom validation logic
// Throw an exception to fail validation
}
}
</code></pre>
<p>As always, you can find <a href="http://msdn.microsoft.com/en-us/library/aa354512.aspx" rel="noreferrer">a more detailed example</a> up on MSDN.</p>
|
<p>This does not look like an certificate validation error. It looks like a webservice configuration error. Can you post the config for your endpoint on the server?</p>
<p>WCF services don't support SSL by default, you need to enable transport security by creating a binding configuration and pointing your endpoint to it with the bindingConfiguration attribute.</p>
<p>Here is a sample binding configuration that supports SSL:</p>
<pre><code><bindings>
<basicHttpBinding>
<binding name="SecureTransport">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
</code></pre>
<p>and your endpoint config would look like this:</p>
<pre><code><endpoint address=""
binding="basicHttpBinding"
bindingConfiguration="SecureTransport"
contract="MyServices.IWebService" />
</code></pre>
| 43,921
|
<p>Long story short, I have a substantial Python application that, among other things, does outcalls to "losetup", "mount", etc. on Linux. Essentially consuming system resources that must be released when complete.</p>
<p>If my application crashes, I want to ensure these system resources are properly released.</p>
<p>Does it make sense to do something like the following?</p>
<pre><code>def main():
# TODO: main application entry point
pass
def cleanup():
# TODO: release system resources here
pass
if __name__ == "__main__":
try:
main()
except:
cleanup()
raise
</code></pre>
<p>Is this something that is typically done? Is there a better way? Perhaps the destructor in a singleton class?</p>
|
<p>I like top-level exception handlers in general (regardless of language). They're a great place to cleanup resources that may not be immediately related to resources consumed inside the method that throws the exception.</p>
<p>It's also a fantastic place to <strong>log</strong> those exceptions if you have such a framework in place. Top-level handlers will catch those bizarre exceptions you didn't plan on and let you correct them in the future, otherwise, you may never know about them at all.</p>
<p>Just be careful that your top-level handler doesn't throw exceptions!</p>
|
<p>That seems like a reasonable approach, and more straightforward and reliable than a destructor on a singleton class. You might also look at the "<a href="http://docs.python.org/lib/module-atexit.html" rel="nofollow noreferrer">atexit</a>" module. (Pronounced "at exit", not "a tex it" or something like that. I confused that for a long while.)</p>
| 12,119
|
<p>What is the added value for learning F# when you are already familiar with LISP?</p>
|
<ul>
<li><a href="http://research.microsoft.com/fsharp/manual/quicktour.aspx#QuickTourTypes" rel="noreferrer">Static typing</a> (with type inference)</li>
<li><a href="http://research.microsoft.com/fsharp/manual/quicktour.aspx#QuickTourDiscriminatedUnions" rel="noreferrer">Algebraic data types</a></li>
<li><a href="http://research.microsoft.com/fsharp/manual/quicktour.aspx#QuickTourPatterns" rel="noreferrer">Pattern matching</a></li>
<li><a href="http://blogs.msdn.com/dsyme/archive/2007/04/07/draft-paper-on-f-active-patterns.aspx" rel="noreferrer">Extensible pattern matching</a> with active patterns.</li>
<li>Currying (with a nice syntax)</li>
<li><a href="http://blogs.msdn.com/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx" rel="noreferrer">Monadic programming</a>, called 'workflows', provides a nice way to do asynchronous programming.</li>
</ul>
<p>A lot of these are relatively recent developments in the programming language world. This is something you'll see in F# that you won't in Lisp, especially Common Lisp, because the F# standard is still under development. As a result, you'll find there is a quite a bit to learn. Of course things like ADTs, pattern matching, monads and currying can be built as a library in Lisp, but it's nicer to learn how to use them in a language where they are conveniently built-in.</p>
<p>The biggest advantage of learning F# for real-world use is its integration with .NET.</p>
|
<p>I know this thread is old but since I stumbled on this one I just wanted to comment on my reasons. I am learning F# simply for professional opportunities since .NET carries a lot of weight in a category of companies that dominate my field. The functional paradigm has been growing in use among more quantitatively and data oriented companies and I'd like to be one of the early comers to this trend. Currently there doesn't an exist a strong functional language that fully and safely integrates with the .NET library. I actually attempted to port some .NET from Lisp code and it's really a pain b/c the FFI only supports C primitives and .NET interoperability requires an 'interface' construct and even though I know how to do this in C it's really a huge pain. It would be really, really, good if Lisp went the extra mile in it's next standard and required a c++ class (including virtual functions w/ vtables), and a C# style interface type in it's FFI. Maybe even throw in a Java interface style type too. This would allow complete interoperability with the .NET library and make Lisp a strong contender as a large-scale language. However with that said, coming from a Lisp background made learning F# rather easy. And I like how F# has gone the extra mile to provide types that you would commonly see it quantitative type work. I believe F# was created with mathematical work in mind and that in itself has value over Lisp. </p>
| 15,424
|
<p>Can <code>Thread.getContextClassLoader()</code> be null ? The javadoc is not really clear.<br>
Should a library take this case into account ?</p>
<p>Update: the reason I asked is that <code>beansbinding.dev.java.net</code> does <em>not</em> work in this case (and my code does <code>setContextClassLoader(null)</code></p>
|
<p>Java threads created from JNI code in a non-java thread have null ContextClassloader unless the creator explicitly sets it. </p>
<p>Also in such context Thread.currentThread() returns null.</p>
|
<p>Yes you should, someone could have called <code>Thread.setContextClassLoader(null)</code> and your library IMO should be able to deal with that.</p>
| 27,884
|
<p>I need to get all dlls in my application root directory. What is the best way to do that?</p>
<pre><code>string root = Application.StartupPath;
</code></pre>
<p>Or,</p>
<pre><code>string root = new FileInfo(Assembly.GetExecutingAssembly().Location).FullName;
</code></pre>
<p>And after that,</p>
<pre><code>Directory.GetFiles(root, "*.dll");
</code></pre>
<p>Which way is better? Are there better ways?</p>
|
<p><code>AppDomain.CurrentDomain.BaseDirectory</code> is my go to way of doing so.</p>
<p>However:</p>
<p><code>Application.StartupPath</code> gets the directory of your executable</p>
<p><code>AppDomain.BaseDirectory</code> gets the directory used to resolve assemblies</p>
<p>Since they can be different, perhaps you want to use Application.StartupPath, unless you care about assembly resolution.</p>
|
<p>I use</p>
<p><code>Path.GetDirectoryName(new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath)
</code></p>
<p>The Assembly.Location will point to the shadow copy if you use shadow copying, so using CodeBase is a better option, but CodeBase is a Url.</p>
| 47,354
|
<p>I have a project right now where I'd like to be able to pull rows out of an Access database that a 3rd party product uses to store its information. There will likely be a small number of users hitting this database at the same time my "export" process does, so I'm a little concerned about data integrity and concurrent access.</p>
<p>Will I likely run into problems with my .NET import process (using LINQ/ADO.NET/?) when it is trying to pull data out of the MDB at the same time someone else is saving a row? How does Access's locking work?</p>
|
<p>There should no problem. Problems can occur only on concurrent write operations. The locking from MS Access based on file locks in the ldb file. The locks occur only on pages and not on the completely file. Because the locks are in the ldb file and not in the mdb file that there are no problems with parallel reading.</p>
|
<p>When you open the database, do not attempt to open in read-only mode (although you might think it makes sense). When you are the first user in, Access opens the mdb file in read-only mode and does not create an ldb, forcing all subsequent users to be in read-only mode as well.</p>
| 16,374
|
<p>While running through the cheat sheet "create a navigation rule" for the <a href="http://www.linuxtopia.org/online_books/eclipse_documentation/eclipse_javaserver_faces_tooling_user_guide/topic/org.eclipse.jst.jsf.doc.user/html/gettingstarted/wpe/eclipse_jsf_user_wpe_getting_started.html" rel="nofollow noreferrer">Eclipse JavaServer Faces tooling</a> it says "select the page control from the palette and ...". But where's this "palette"?</p>
|
<p>It turns out, in <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29#Releases" rel="nofollow noreferrer">Ganymede</a> at least, on the right-hand border of the JavaServer Faces configuration editor tab there is a subtle left arrow head. clicking that shows palette.</p>
|
<p>Just incase anyone is struggling now to find it I have added a screenshot showing exactly where it is:</p>
<p><a href="http://i.stack.imgur.com/o63WS.png" rel="nofollow">palette image</a></p>
| 23,732
|
<p>The hover "joke" in #505 <a href="http://en.wikipedia.org/wiki/Xkcd" rel="noreferrer">xkcd</a> touts "I call rule 34 on Wolfram's Rule 34".</p>
<p>I know <a href="http://www.urbandictionary.com/define.php?term=Rule%2034" rel="noreferrer">what rule 34 is in Internet terms</a> and I've googled up <a href="http://en.wikipedia.org/wiki/Stephen_Wolfram" rel="noreferrer">who Wolfram is</a> but I'm having a hard time figuring out what Wolfram's Rule 34 is.</p>
<p>So what exactly is this "Rule 34"?</p>
<p>Here's the comic: <a href="http://xkcd.com/505/" rel="noreferrer">http://xkcd.com/505/</a>.</p>
|
<p>Wolfram has organized the 256 possible 1-D cellular automata based on nearest neighbors in this way:</p>
<pre><code>RULES:
0: 0 0 0
1: 0 0 1
2: 0 1 0
3: 0 1 1
4: 1 0 0
5: 1 0 1
6: 1 1 0
7: 1 1 1
</code></pre>
<p>If you're evaluating a stage in a cellular automaton (CA) that follows rule 2, then whenever a three-bit string matches rule 2's configuration, the center bit becomes (or stays, in this case) true on the next iteration.</p>
<p>A CA's rules are described as a bitstring. Say it's rule 110 (my favorite). In binary, 110 is 01101110. The digit of least significance is zero. This means that if the cell and its neighbors match rule 0 above, it turns white/negative/0/false/whatever. The second least significant digit is one, so if the cell and its neighbors match rule 1 above, it turns black/positive/1/true/whatever`, etc. etc. until you see that, for rule 110, if a cell and its neighbors match rules 1,2,3,5,6, then the cell turns black. Otherwise, it turns white. A while back, I wrote some JS code to allow me to play around with these unique CA:</p>
<p><a href="http://lucasoman.com/files/projects/caeditor/caed.php" rel="noreferrer">http://lucasoman.com/files/projects/caeditor/caed.php</a></p>
<p>As you can see by playing with it, you can randomly toggle any block, which alters every
block below it according to the rules. It's kind of a neat way to see the chain reaction
caused by aberrations in the process.</p>
<p>Hope this helps.</p>
|
<p>Rule 34</p>
<p><a href="http://xkcd.com/305/" rel="nofollow noreferrer">http://xkcd.com/305/</a></p>
| 38,821
|
<p>I have an aspx page with a gridview. In my page load event, I load a datatable with all the data like so:</p>
<pre><code>HistoricalPricing historicalPricing = new HistoricalPricing();
DataTable dtHistoricalPricing = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dtHistoricalPricing = historicalPricing.GetAuctionData();
}
}
</code></pre>
<p>The above loades the data into the datatable fine. I also have a listbox which contains a list of auctions. When I click on an auction, I use the RowFilter on a DataView to display a Gridview with the data that was selected, but the DataTable seems to loose its value and I can't figure out why. Here is the code below:</p>
<pre><code>protected void lstAuctions_SelectedIndexChanged(object sender, EventArgs e)
{
DataView dvPricing = new DataView(dtHistoricalPricing); // Loses Value
dvPricing.RowFilter = "Auction = 1"; //Hard-Coded for Test
gvPricing.DataSource = dvPricing.ToTable();
gvPricing.DataBind();
}
</code></pre>
|
<p>Every time you do a postback you're dealing with a new instance of your page class. That means a new datatable object as well.</p>
<p>If you <em>really</em> want to persist it between postbacks (and make sure you consider the memory implications for that when you may have 1000 people hitting this web server at the same time) then you can put the datatable in the Session, ViewState, or other location that persists state.</p>
|
<p>I think I figured it out, is it because when I click on the ListBox, it does a postback and I am only loading the data on the first load of the Page? If this is correct, I think I answered my own question.</p>
<p>I put the datatable in Session after loading it on the first Page Load and this seemed to solve my problem. Not sure if this is the best way though.</p>
| 49,249
|
<p>I have a xsl file that is grabbing variables from xml and they seem to not be able to see each other. I know it is a scope issue, I just do not know what I am doing wrong.</p>
<pre><code><xsl:template match="one">
<xsl:variable name="varOne" select="@count" />
</xsl:template>
<xsl:template match="two">
<xsl:if test="$varOne = 'Y'">
<xsl:value-of select="varTwo"/>
</xsl:if>
</xsl:template>
</code></pre>
<p>This has been simplified for here.</p>
<p>Any help is appreciated.</p>
|
<p>Remembering that xsl variables are immutable...</p>
<pre><code><!-- You may want to use absolute path -->
<xsl:variable name="varOne" select="one/@count" />
<xsl:template match="one">
<!-- // do something -->
</xsl:template>
<xsl:template match="two">
<xsl:if test="$varOne = 'Y'">
<xsl:value-of select="varTwo"/>
</xsl:if>
</xsl:template>
</code></pre>
|
<p>I'm fairly certain that variables are scoped and therefore you can't declare a variable in one and then use it in the other. You're going to have to move your variable declaration out of the template so that it's in a higher scope than both of them.</p>
| 17,076
|
<p>I have the following shell script registered in my "Login Items" preferences but it does not seem to have any effect. It is meant to launch the moinmoin wiki but only works when it is run by hand from a terminal window, after which it runs until the machine is next shut down.</p>
<pre><code>#!/bin/bash
cd /Users/stuartcw/Documents/Wiki/moin-1.7.2
/usr/bin/python wikiserver.py >> logs/`date +"%d%b%Y"`.log 2>&1 &
</code></pre>
<p>I would really like the Wiki to be available after restarting so any help in understanding this would be appreciated.</p>
|
<p>launchd is one of the best parts of MacOS X, and it causes me great pain to not be able to find it on other systems.</p>
<p>Edit and place this in <code>/Library/LaunchDaemons</code> as <code>com.you.wiki.plist</code></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.you.wiki</string>
<key>LowPriorityIO</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>RunAtLoad</key>
<true/>
<key>Nice</key>
<integer>1</integer>
<key>WorkingDirectory</key>
<string>/Users/stuartcw/Documents/Wiki/moin-1.7.2</string>
<key>UserName</key>
<string>user to run this as</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/python</string>
<string>wikiserver.py</string>
</array>
</dict>
</plist>
</code></pre>
|
<p>I don't know much about it, since I don't use login items. Just a suggestion, maybe try with applescript that calls those shell commands, and put that in Login Items.</p>
| 43,578
|
<p>I'd like to know what stored procedures are currently running to diagnose some performance problems. How can I find that out?</p>
|
<p>Very useful script for analyzing locks and deadlocks: <a href="http://www.sommarskog.se/sqlutil/aba_lockinfo.html" rel="nofollow noreferrer">http://www.sommarskog.se/sqlutil/aba_lockinfo.html</a></p>
<p>It shows procedure or trigger and current statement.</p>
|
<p>Using Enterprise Manager, you can open the Management tree section, and choose Current Activity -> Process Info. Double clicking on a Process ID will show you what that process is running. If it's a stored procedure, it will not show you the parameters. For that it would be better to use Brian Kim's suggestion of using the SQL Profiler.</p>
| 15,698
|
<p>I have a site that creates images for some bit of content after the content is created. I'm trying to figure out what to do in between the time the content is created and the image is created. My thought is that I might be able to set a custom image to display on a 404 error on the original image. However, I'm not sure how to do this with lighttpd. Any ideas or alternatives?</p>
<p>EDIT: The issue is the user isn't the one creating the content, it's being created by a process. Basically we are adding items to a catalog and we want to create a standardized catalog image from an image supplied by the product provider. However, I don't want a slow server on the provider end to slow down the addition of new products. So a separate process goes through and creates the image later, where available. I guess I could have the system create a default image when we create the product and then overwrite it later when we create the image from the provider supplied image.</p>
|
<p>Another alternative on the client side is to do:</p>
<pre><code><img src="/images/generated_image_xyz.png"
onerror="this.src='/images/default_image.png'; this.title='Loading...';" />
</code></pre>
|
<p>As I understand your problem: You want to show an intermediate image until the <em>real</em> image has been generated?</p>
<p>You could display a <em>loading image</em> and use AJAX to change that DOM node into the <em>real</em> image when it's been created. You could write it from scratch or use any of the well known and stable AJAX libraries out there, if you have no preference of your own take a look at <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a>.</p>
| 31,391
|
<p>I'm trying to convert some code that uses datasets to LINQ. Some of the code passes column names into other functions as strings.</p>
<p>Is there anyway I can easily rewrite this into LINQ?</p>
<pre><code>string s = getElement(tr, elementName);
private string getElement (tableRow re, string elementName){
if(tr[elementName] != null){
return tr[elementName].toString()
}
}
</code></pre>
<p>OR:</p>
<pre><code>private void copy (tableRow trFrom, tableRow trTo){
foreach (DataColumn c in trFrom.Table.Columns) {
trTo[c.ColumnName] = trFrom[c.ColumnName];
}
}
</code></pre>
<p>Answer to GVS:
The reason to convert to LINQ is because it in many situations are easier to code LINQ and get better performance. It's related to another question here on stackoverflow:
<a href="https://stackoverflow.com/questions/295291/programming-pattern-using-typed-datasets-in-vs-2008">programming pattern using typed datasets</a></p>
<p>The reason I need to use the column name as a string is mainly because the column names are passed as a ID for input fields, they are then sent back to the program using AJAX (jquery).</p>
|
<ol>
<li><p><strong>Simple way</strong> </p>
<p>1.1. <strong>Using IEnumerable</strong> (Linq to Objects or similar)
Change the elementName parameter for a Func and pass lambdas instead (you will get compile time checking as well!)</p>
<p>1.2. <strong>Using IQueryable</strong> (Linq to SQL or similar)
Same, but use Expression> instead. </p></li>
<li><p><strong>Complex way:</strong>
If for some reason you need to keep the parameter as an string (maybe is introduced by user) You can use reflection to build an expression tree at runtime <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx</a>. </p>
<p>2.1. <strong>Using IEnumerable</strong> Then Compile, and use it as a parameter in a where, select... </p>
<p>2.2. <strong>Using IQueryable</strong> Use it as a parameter in the where, select, </p></li>
</ol>
<p>If you need to compose the lambda with other lambdas use this cool technique <a href="http://tomasp.net/blog/linq-expand.aspx" rel="nofollow noreferrer">http://tomasp.net/blog/linq-expand.aspx</a></p>
|
<p>Why would you convert working and clear code into something using LINQ?</p>
<p>Edit: LINQ is nice, cool stuff. But don't make the same errors as many XML fans did (specially first-adapters), by applying it to everything.</p>
| 39,293
|
<p>What is the best way to sanitize user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="noreferrer">XSS</a> or SQL injection attack?</p>
|
<p>Here is a snippet that will remove all tags not on the white list, and all tag attributes not on the attribues whitelist (so you can't use <code>onclick</code>).</p>
<p>It is a modified version of <a href="http://www.djangosnippets.org/snippets/205/" rel="noreferrer">http://www.djangosnippets.org/snippets/205/</a>, with the regex on the attribute values to prevent people from using <code>href="javascript:..."</code>, and other cases described at <a href="http://ha.ckers.org/xss.html" rel="noreferrer">http://ha.ckers.org/xss.html</a>.<br>
(e.g. <code><a href="ja&#x09;vascript:alert('hi')"></code> or <code><a href="ja vascript:alert('hi')"></code>, etc.)</p>
<p>As you can see, it uses the (awesome) <a href="http://www.crummy.com/software/BeautifulSoup/" rel="noreferrer">BeautifulSoup</a> library.</p>
<pre><code>import re
from urlparse import urljoin
from BeautifulSoup import BeautifulSoup, Comment
def sanitizeHtml(value, base_url=None):
rjs = r'[\s]*(&#x.{1,7})?'.join(list('javascript:'))
rvb = r'[\s]*(&#x.{1,7})?'.join(list('vbscript:'))
re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE)
validTags = 'p i strong b u a h1 h2 h3 pre br img'.split()
validAttrs = 'href src width height'.split()
urlAttrs = 'href src'.split() # Attributes which should have a URL
soup = BeautifulSoup(value)
for comment in soup.findAll(text=lambda text: isinstance(text, Comment)):
# Get rid of comments
comment.extract()
for tag in soup.findAll(True):
if tag.name not in validTags:
tag.hidden = True
attrs = tag.attrs
tag.attrs = []
for attr, val in attrs:
if attr in validAttrs:
val = re_scripts.sub('', val) # Remove scripts (vbs & js)
if attr in urlAttrs:
val = urljoin(base_url, val) # Calculate the absolute url
tag.attrs.append((attr, val))
return soup.renderContents().decode('utf8')
</code></pre>
<p>As the other posters have said, pretty much all Python db libraries take care of SQL injection, so this should pretty much cover you.</p>
|
<p>If you are using a framework like <a href="http://www.djangoproject.com/" rel="nofollow noreferrer">django</a>, the framework can easily do this for you using standard filters. In fact, I'm pretty sure django automatically does it unless you tell it not to.</p>
<p>Otherwise, I would recommend using some sort of regex validation before accepting inputs from forms. I don't think there's a silver bullet for your problem, but using the re module, you should be able to construct what you need.</p>
| 3,756
|
<p>I've had a FTP server (Mac OS X, but not the server version) set up for a while where the users are virtual, i.e. they are not actual user accounts in the server's OS, but accounts handled by the FTP server software -- to the OS they all look like the <code>ftp</code> user account. I'd like to retire the FTP server software and go SFTP instead.</p>
<p>Is there a way to set up SFTP/SSH so that I can create virtual users and at the same time sandbox them?</p>
<p>The reason I want virtual users is because I add and remove accounts from time to time, and doing that with proper user accounts tend to get messy, and I don't know of a good way to sandbox them. There's always some files left and each user has their own user directory (with a lot of files only relevant if they would actually log on to the machine when sitting in front of it), which is quarantined when the account is removed, so you have to remove it by hand yourself, and so on.</p>
|
<p>The usual generic Unix answer to this is 'PAM'. If you want plain old OpenSSH SSHD to handle your SFTP, you need something plugged in to SSHD's PAM stack (/etc/pam.d/sshd) that does what you need and leaves out what you don't need. This might be a general-purpose directory server (probably LDAP) that maps all your virtual users to one home directory and gives them a restricted or scponly kind of shell.</p>
<p>If you want to look at FTP servers that can also do FTP-ssl (which is not the same as SFTP), good ftp servers like Pure-ftpd or vsftp will do that. FTP-ssl servers have simpler virtual user support.</p>
<p><a href="http://www.bsdguides.org/guides/freebsd/networking/pure-ftpd_virtual_users.php" rel="nofollow noreferrer">http://www.bsdguides.org/guides/freebsd/networking/pure-ftpd_virtual_users.php</a></p>
|
<p>If you're open to commercial products, VShell Server from Van Dyke Software is available on Unix/Linux/Windows, supports virtual users (multiple backends) with SSH and SFTP protocols:</p>
<p><a href="http://www.vandyke.com/products/vshell/index.html" rel="nofollow">VShell Server</a></p>
| 6,023
|
<p>Can anyone advise on how to crop an image, let's say jpeg, without using any .NET framework constructs, just raw bytes? Since this is the only* way in Silverlight...</p>
<p>Or point to a library?</p>
<p>I'm not concerned with rendering i'm wanting to manipulate a jpg before uploading.</p>
<p>*There are no GDI+(System.Drawing) or WPF(System.Windows.Media.Imaging) libraries available in Silverlight.</p>
<p>Lockbits requires GDI+, clarified question</p>
<p>Using fjcore: <a href="http://code.google.com/p/fjcore/" rel="nofollow noreferrer">http://code.google.com/p/fjcore/</a> to resize but no way to crop :(</p>
|
<p><a href="http://www.imagemagick.org/script/index.php" rel="nofollow noreferrer">ImageMagick</a> does a pretty good job. If you're ok with handing off editing tasks to your server...</p>
<p>(Seriously? The recommended way of manipulating images in Silverlight is to work with <em>raw bytes</em>? That's... incredibly lame.)</p>
|
<p>where is silverlight executed?
Is there any reason at all to send an complete picture to the client to make the client crop it?
Do it on the server... (if you are not creating an image editor that is..)</p>
| 5,769
|
<p>How to create new PCL file similar to existing MS doc. I have MS doc template and replacing it with actual data. I need to achieve same for PCL format (Create PCL file as template and replacing it with actual value from database and send it to fax).</p>
|
<ol>
<li>install a new printer</li>
<li>when asked for a port, create a new port of type "Local Port"</li>
<li>as name of the port, enter some file name, e.g. <code>c:\temp\print.pcl</code></li>
<li>select some PCL-compatible printer, e.g. HP LaserJet 4, or whatever your fax is comptaible with</li>
</ol>
<p>When you print to this printer, Windows will write the output to that file.</p>
<p>Many programs allow you to redirect printing to a file; in this case, you'd be able to select a different file name for each print job.</p>
|
<p>I found the simple solution and it works. convert the .doc file tamplete to PCL using tool (available on net). open it in edit plus and study... i relize i can modify it according to my need. if u check it u wil see each charector is with its position Example:
<em>p0Y</em>p796Y*p1582Xn -- means charector n at position (x-axis 1582 and y-axis 796) at screen. so what now i can change anything, add new object, line etc at position acording to my need.
I know its tedious but works for me.... </p>
| 11,576
|
<p>I have an iPhone app that hides the status bar. However, my main view doesn't get any touch events when I tap in the status bar area. Is there something I can do to fix this?</p>
<p>Here are a few details of my app's setup (in case it matters):</p>
<ul>
<li>It's an OpenGL-based application.</li>
<li>The app launches in landscape mode. However, the touch events are missing when I tap in the area near the "top" of the portrait-mode area. (In other words, I don't get touch events on the left edge when I have the device held in landscape orientation.)</li>
<li>My info.plist has UIStatusBarHidden set true, and in my application delegate's applicationDidFinishLaunching method I have "application.statusBarHidden = YES;"</li>
<li>The main view has exclusiveTouch set to YES.</li>
<li>The view's touchesBegan:withEvent method is called when I tap anywhere else on the screen.</li>
<li>My view draws fine within the status-bar area.</li>
</ul>
<p>(Please refrain from whining about the NDA. Thank you.)</p>
<hr>
<p><strong>Update:</strong> It turns out that this problem only manifests itself on the iPhone Simulator. When the app is run on an actual iPhone, touches are detected everywhere.</p>
<p>I'm still interested to know if there is a way to make it work on the Simulator, but it's no big deal.</p>
|
<p>Found my own answer (of sorts):</p>
<p>This behavior only happens in the iPhone Simulator. When I run the application on an actual iPhone, it works fine.</p>
<p>I'd still be interested to know if there is a way to make it work on the simulator.</p>
|
<p>I haven't had this problem, but then again, I'm not using OpenGL views. When you launch in Landscape mode, are you setting the StatusBarHidden property of the appropriate ViewController?</p>
| 17,608
|
<p>I'm working on a college assignment where I must verify if a certain clause (as a fact or as a rule) exists in the current clause database.</p>
<p>The idea is to use a rule whose head is verify(+name, +arguments). This rule should be true if in the database exists another rule whose head is name(arguments)</p>
<p>Any help would be greatly appreciated...</p>
|
<p>Using <code>call/1</code> is not a good idea because <code>call/1</code> actually calls the goal, but you just want to find out if the fact/rule <em>exists</em>, and you don't want to wait after a long calculation that the call might trigger, and you don't want to have something printed on the screen if the called rule in turn calls e.g. <code>writeln/1</code>. In addition, you would want <code>verify/2</code> to succeed even if the call failed (but the fact/rule is otherwise there).</p>
<p>As a solution, SWI-Prolog offers <code>callable/1</code></p>
<pre><code>callable(+Term)
True if Term is bound to an atom or a compound term,
so it can be handed without type-error to call/1, functor/3 and =../2.
</code></pre>
<p>Here are two version of <code>verify/2</code>, one using <code>call/1</code> and the other using <code>callable/1</code>.</p>
<pre><code>verify1(Name, Arguments) :-
Term =.. [Name | Arguments],
call(Term).
verify2(Name, Arguments) :-
Term =.. [Name | Arguments],
callable(Term).
father(abraham, isaac) :-
writeln('hello').
father(abraham, adam) :-
fail.
</code></pre>
|
<p>Are you familiar with the concept of unification? What you have to do is: just call a predicate that looks like the one you're trying to find.</p>
<p>So, say in your database is:</p>
<pre><code>father(abraham,isaac).
</code></pre>
<p>Now you want to call something like:</p>
<pre><code>verify(father,[abraham,isaac]).
</code></pre>
<p>Your predicate body will then have to contain a mechanism of calling <code>father(abraham,isaac).</code> which should then return <code>true.</code> Calling <code>father(abraham,adam)</code> should fail.</p>
<p>You will need two predicates for this: <code>=../2</code> and <code>call/2</code>. If you are using SWI-Prolog, call <code>help(=..).</code> and <code>help(call)</code> from the interpreter's command line to access the documentation.</p>
<p>I hope I didn't spoil the assignment for you. You still have to find out what to do with partially instantiated predicates (so, say something like <code>verify(father,[abraham,X]).</code> on your own, but it shouldn't be hard from here.</p>
<p>Good luck.</p>
| 41,677
|
<p>Is there any way to make sure that a table and cells it contains have a border only when the cells are not empty?
If all the cells of the table are empty, then no border should be visible.</p>
|
<p>See the <a href="http://www.w3.org/TR/CSS2/tables.html#empty-cells" rel="nofollow noreferrer">empty-cells</a> CSS property.</p>
|
<p>Give the empty cells one class name and the non-empty ones another. One class specifies a border, the other without.</p>
| 41,650
|
<p>Many examples of macros seem to be about hiding lambdas, e.g. with-open-file in CL. I'm looking for some more exotic uses of macros, particularly in PLT Scheme. I'd like to get a feel for when to consider using a macro vs. using functions.</p>
|
<p>I only use Scheme macros (<code>define-syntax</code>) for tiny things like better lambda syntax:</p>
<pre><code>(define-syntax [: x]
(syntax-case x ()
([src-: e es ...]
(syntax-case (datum->syntax-object #'src-: '_) ()
(_ #'(lambda (_) (e es ...)))))))
</code></pre>
<p>Which lets you write</p>
<pre><code>[: / _ 2] ; <-- much better than (lambda (x) (/ x 2))
</code></pre>
<p>Dan Friedman has a mind-bending implementation of OO using macros: <a href="http://www.cs.indiana.edu/~dfried/ooo.pdf" rel="noreferrer">http://www.cs.indiana.edu/~dfried/ooo.pdf</a></p>
<p>But honestly, all the <em>useful</em> macros I've defined are stolen from <a href="http://paulgraham.com/onlisp.html" rel="noreferrer">Paul Graham's On Lisp</a> and are generally easier to write with <code>defmacro</code> (<code>define-macro</code> in PLT Scheme). For example, <code>aif</code> is pretty ugly with <code>define-syntax</code>.</p>
<pre><code>(define-syntax (aif x)
(syntax-case x ()
[(src-aif test then else)
(syntax-case (datum->syntax-object (syntax src-aif) '_) ()
[_ (syntax (let ([_ test]) (if (and _ (not (null? _))) then else)))])]))
</code></pre>
<p><code>define-syntax</code> is odd in that it's only easy to use for very simple macros, where you are glad of the inability to capture variables; and very complicated macro DSLs, where you are glad of the inability to capture variables <em>easily</em>. In the first case you want to write the code without thinking about it, and in the second case you have thought enough about the DSL that you are willing to write part of it in the <code>syntax-rules</code>/<code>syntax-case</code> language which is not Scheme in order to avoid mystifying bugs.</p>
<hr>
<p>But I don't use macros that much in Scheme. Idiomatic Scheme is so functional that many times you just want to write a functional program and then hide a few lambdas. I got on the functional train and now believe that if you have a lazy language or a good syntax for lambda, even that isn't necessary, so macros are not all that useful in a purely functional style.</p>
<p>So I'd recommend <a href="http://gigamonkeys.com/book/" rel="noreferrer">Practical Common Lisp</a> and <a href="http://paulgraham.com/onlisp.html" rel="noreferrer">On Lisp</a>. If you want to use PLT Scheme, I think most of their <code>defmacro</code> macros will work with <code>define-macro</code>. Or just use Common Lisp.</p>
|
<p>I use them when procedures do not suffice. </p>
| 30,474
|
<p>I am printing Benchies at high speed, I successfully printed one at 300 mm/s. If I set the speed to 400 mm/s, the Y axis begins shifting around. This is usually accompanied by a banging sound.</p>
<p>In addition, the extruder motor occasionally clicks. When it clicks, the filament shoots back out a little bit.</p>
<p>Print settings:</p>
<ul>
<li>Infill: 100 %</li>
<li>Hotend: 200 °C</li>
<li>Bed: 60 °C</li>
<li>Material: PLA</li>
<li>Infill: Lines</li>
<li>Walls: 2</li>
<li>Top/bottom layers: 2</li>
<li>Speed: 400 mm/s</li>
<li>Jerk: 400 mm/s</li>
<li>Acceleration: 1000000</li>
</ul>
<p>I am running custom Marlin-based firmware on the stock mainboard.</p>
<p>The printer shakes my desk when printing like this.</p>
|
<p>TL;DR: Don't do that.</p>
<p>Detailed answer: You need motion limit parameters that actually make physical sense, and firmware capable of executing a motion plan according to them. Your jerk and acceleration settings absolutely don't. Marlin's whole implementation of jerk is wacky (note: modern Marlin versions don't even use it but an alternative they call "junction deviation" instead) and likely to cause problems above very low values; I never was able to take it above 25 or so on Marlin without layer shifts. Acceleration is dependent on the stepper motor torque and the mass you'll be accelerating. For the Y axis, that's the bed, and it has enough mass you won't accelerate it above 12000 mm/s² or so, much less the requested 1 km/s² plus near-infinite acceleration from the extreme near-instantaneous 400 mm/s velocity change ("jerk").</p>
<p>The speed of 400 mm/s is achievable if you don't do it instantaneously. Stepper motors begin to rapidly lose torque beyond a certain speed due to limits on how fast the magnetic field can build up and be reversed, which has to happen for each step. <a href="https://www.daycounter.com/Calculators/Stepper-Motor-Calculator.phtml" rel="noreferrer">This calculator</a> can compute the limits if you know the properties of your motor. For the Ender 3 Y axis motor, the limit is around 425 mm/s or so if I'm remembering right.</p>
<p>For actual print speed, though, the hotend and extruder cannot keep up with anything nearly that high. 150 mm/s is about the limit with that hotend, and it might even be lower with a stock extruder. Fortunately, Benchy is mostly acceleration-bound, not top-speed-bound, so if you can get your acceleration profile right, you can still print quite fast.</p>
<p>Now the next limit you'll hit is Marlin. Marlin is... not good at high speeds and accelerations. Often the layer shifts you hit with Marlin aren't even physical limits but Marlin bugs. If you want to go fast, you need Klipper, not only because it lacks these step timing bugs, but because you need its Input Shaper feature to keep the high acceleration from tearing your printer apart (literally, vibrating all the screws out!).</p>
|
<p>Ok, so you are having multiple problems, lets break it down:</p>
<p>At the speed you are pushing, it would not be weird to have the Y belt slipping around. Also inertia comes into play, so please, dont do that.</p>
<p>What you are mentioning about the filament going out a bit, also makes sense. You are exceeding the max volumetric flowrate for the ender 3. I would recommend going for a higher flow nozzle/Hotend combo.</p>
| 2,028
|
<p>I'm trying to get a PHP site working in IIS on Windows Server with MySQL.</p>
<p>I'm getting this error…</p>
<p>Fatal error: Call to undefined function mysql_connect() in C:\inetpub...\adodb\drivers\adodb-mysql.inc.php on line 363</p>
<hr />
<p>Update…</p>
<p>This link outlines the steps I followed to install PHP on my server:<br />
<a href="https://stackoverflow.com/questions/11919/how-do-i-get-php-and-mysql-working-on-iis-70#94341">How do I get PHP and MySQL working on IIS 7.0 ?</a><br />
(note especially steps 6 and 8 regarting php.ini and php_mysql.dll).</p>
<p>Only two lines in the phpinfo report reference SQL:</p>
<pre><code><?php
phpinfo();
?>
</code></pre>
<blockquote>
<p>Configure Command:<br />
cscript /nologo configure.js "--enable-snapshot-build" "--enable-mysqlnd"</p>
<p>sql.safe_mode:<br />
Local Value Off, Master Value Off</p>
</blockquote>
<p><a href="http://img79.imageshack.us/img79/2373/configurecommandmw8.gif" rel="nofollow noreferrer">PHP Configure Command http://img79.imageshack.us/img79/2373/configurecommandmw8.gif</a></p>
<p><a href="http://img49.imageshack.us/img49/3066/sqlsafemoderu6.gif" rel="nofollow noreferrer">PHP sql.safe_mode http://img49.imageshack.us/img49/3066/sqlsafemoderu6.gif</a></p>
<hr />
<p>Update…</p>
<p>I found the solution: <a href="https://stackoverflow.com/questions/158279/how-do-i-install-mysql-modules-within-php#160746">How do I install MySQL modules within PHP?</a></p>
|
<p>Check out phpinfo to see if the mysql functions are compiled with your PHP</p>
<pre><code><?php
phpinfo();
?>
</code></pre>
<p>Since in some versions of php, its not default with the install.</p>
<p><b>Edit for the Update:</b></p>
<p>You should have a full MySQL category in your phpinfo();</p>
<p>See this for example: <a href="https://secure18.easycgi.com/phpinfo.php" rel="nofollow noreferrer">https://secure18.easycgi.com/phpinfo.php</a> (googled example)</p>
|
<p>It sounds like the version of PHP you are using has not been compiled with MySQL support, or has not been enabled in the php.ini.</p>
| 18,780
|
<p>I have some decimal data that I am pushing into a SharePoint list where it is to be viewed. I'd like to restrict the number of significant figures displayed in the result data based on my knowledge of the specific calculation. Sometimes it'll be 3, so 12345 will become 12300 and 0.012345 will become 0.0123. Occasionally it will be 4 or 5. Is there any convenient way to handle this?</p>
|
<p>See: <a href="https://stackoverflow.com/questions/374316/round-a-double-to-x-significant-figures-after-decimal-point/374470#374470">RoundToSignificantFigures</a> by "P Daddy".<br>
I've combined his method with another one I liked. </p>
<p>Rounding to significant figures is a lot easier in TSQL where the rounding method is based on rounding position, not number of decimal places - which is the case with .Net math.round. You could round a number in TSQL to negative places, which would round at whole numbers - so the scaling isn't needed.</p>
<p>Also see this <a href="https://stackoverflow.com/questions/202302/rounding-to-an-arbitrary-number-of-significant-digits">other thread</a>. Pyrolistical's method is good.</p>
<p>The trailing zeros part of the problem seems like more of a string operation to me, so I included a ToString() extension method which will pad zeros if necessary. </p>
<pre><code>using System;
using System.Globalization;
public static class Precision
{
// 2^-24
public const float FLOAT_EPSILON = 0.0000000596046448f;
// 2^-53
public const double DOUBLE_EPSILON = 0.00000000000000011102230246251565d;
public static bool AlmostEquals(this double a, double b, double epsilon = DOUBLE_EPSILON)
{
// ReSharper disable CompareOfFloatsByEqualityOperator
if (a == b)
{
return true;
}
// ReSharper restore CompareOfFloatsByEqualityOperator
return (System.Math.Abs(a - b) < epsilon);
}
public static bool AlmostEquals(this float a, float b, float epsilon = FLOAT_EPSILON)
{
// ReSharper disable CompareOfFloatsByEqualityOperator
if (a == b)
{
return true;
}
// ReSharper restore CompareOfFloatsByEqualityOperator
return (System.Math.Abs(a - b) < epsilon);
}
}
public static class SignificantDigits
{
public static double Round(this double value, int significantDigits)
{
int unneededRoundingPosition;
return RoundSignificantDigits(value, significantDigits, out unneededRoundingPosition);
}
public static string ToString(this double value, int significantDigits)
{
// this method will round and then append zeros if needed.
// i.e. if you round .002 to two significant figures, the resulting number should be .0020.
var currentInfo = CultureInfo.CurrentCulture.NumberFormat;
if (double.IsNaN(value))
{
return currentInfo.NaNSymbol;
}
if (double.IsPositiveInfinity(value))
{
return currentInfo.PositiveInfinitySymbol;
}
if (double.IsNegativeInfinity(value))
{
return currentInfo.NegativeInfinitySymbol;
}
int roundingPosition;
var roundedValue = RoundSignificantDigits(value, significantDigits, out roundingPosition);
// when rounding causes a cascading round affecting digits of greater significance,
// need to re-round to get a correct rounding position afterwards
// this fixes a bug where rounding 9.96 to 2 figures yeilds 10.0 instead of 10
RoundSignificantDigits(roundedValue, significantDigits, out roundingPosition);
if (Math.Abs(roundingPosition) > 9)
{
// use exponential notation format
// ReSharper disable FormatStringProblem
return string.Format(currentInfo, "{0:E" + (significantDigits - 1) + "}", roundedValue);
// ReSharper restore FormatStringProblem
}
// string.format is only needed with decimal numbers (whole numbers won't need to be padded with zeros to the right.)
// ReSharper disable FormatStringProblem
return roundingPosition > 0 ? string.Format(currentInfo, "{0:F" + roundingPosition + "}", roundedValue) : roundedValue.ToString(currentInfo);
// ReSharper restore FormatStringProblem
}
private static double RoundSignificantDigits(double value, int significantDigits, out int roundingPosition)
{
// this method will return a rounded double value at a number of signifigant figures.
// the sigFigures parameter must be between 0 and 15, exclusive.
roundingPosition = 0;
if (value.AlmostEquals(0d))
{
roundingPosition = significantDigits - 1;
return 0d;
}
if (double.IsNaN(value))
{
return double.NaN;
}
if (double.IsPositiveInfinity(value))
{
return double.PositiveInfinity;
}
if (double.IsNegativeInfinity(value))
{
return double.NegativeInfinity;
}
if (significantDigits < 1 || significantDigits > 15)
{
throw new ArgumentOutOfRangeException("significantDigits", value, "The significantDigits argument must be between 1 and 15.");
}
// The resulting rounding position will be negative for rounding at whole numbers, and positive for decimal places.
roundingPosition = significantDigits - 1 - (int)(Math.Floor(Math.Log10(Math.Abs(value))));
// try to use a rounding position directly, if no scale is needed.
// this is because the scale mutliplication after the rounding can introduce error, although
// this only happens when you're dealing with really tiny numbers, i.e 9.9e-14.
if (roundingPosition > 0 && roundingPosition < 16)
{
return Math.Round(value, roundingPosition, MidpointRounding.AwayFromZero);
}
// Shouldn't get here unless we need to scale it.
// Set the scaling value, for rounding whole numbers or decimals past 15 places
var scale = Math.Pow(10, Math.Ceiling(Math.Log10(Math.Abs(value))));
return Math.Round(value / scale, significantDigits, MidpointRounding.AwayFromZero) * scale;
}
}
</code></pre>
|
<p>As I remember it "significant figures" means the number of digits after the dot separator so 3 significant digits for 0.012345 would be 0.012 and not 0.0123, but that really doesnt matter for the solution.
I also understand that you want to "nullify" the last digits to a certain degree if the number is > 1. You write that 12345 would become 12300 but im not sure whether you want 123456 to become 1230000 or 123400 ? My solution does the last. Instead of calculating the factor you could ofcourse make a small initialized array if you only have a couple of variations.</p>
<pre><code>private static string FormatToSignificantFigures(decimal number, int amount)
{
if (number > 1)
{
int factor = Factor(amount);
return ((int)(number/factor)*factor).ToString();
}
NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
nfi.NumberDecimalDigits = amount;
return(number.ToString("F", nfi));
}
private static int Factor(int x)
{
return DoCalcFactor(10, x-1);
}
private static int DoCalcFactor(int x, int y)
{
if (y == 1) return x;
return 10*DoCalcFactor(x, y - 1);
}
</code></pre>
<p>Kind regards
Carsten</p>
| 19,122
|
<p>I have an application where I have a <code>main.m</code> that returns <code>NSApplicationMain(argc, (const char **) argv);</code>.</p>
<p>I want to run code on <code>-applicationDidFinishLaunching:</code>, but I just dont see how to do it. </p>
<p>Can anyone help or have an example? </p>
<p>Thanks!
-Jason</p>
|
<p>The applicationDidFinishLaunching: method of the NSApplication delegate will be called when the app has finished loading. Many of the project templates setup a delegate. If you are using one just add the appropriate method to it.</p>
<p>If your project does not have an app delegate set up you will need to do that yourself. First, make a new class to act as your delegate (you can use an exiting one if there is something logically appropriate). Now make sure that class is instantiated in your MainMenu.nib. Finally, hook the delegate property of the "File's Owner" object to the instantiate delegate in IB.</p>
|
<p>Louis' answer is concise and spot-on. However, if the concept of delegate methods is new to you, you'd do well to check out the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/chapter_6_section_4.html" rel="nofollow noreferrer" title="Cocoa Fundamentals Guide: Delegates and Data Sources">relevent documenation</a>.</p>
| 30,442
|
<p>Is it possible to use 2 CSS classes that have the same name for the selectors, etc. in the same HTML file? If so, how do you differentiate between the two when styling elements?</p>
|
<p>Yes this is possible, simply include two css files in the HEAD section of the document. Any styles set in the first will be overwritten in the second, so say you have this:<br>
First file:</p>
<pre class="lang-css prettyprint-override"><code> #something{
background-color: #F00;
color: #FFF;
}
</code></pre>
<p>And then in the second file:</p>
<pre class="lang-css prettyprint-override"><code> #something{
background-color: #000;
}
</code></pre>
<p>Then the background color for #something will be overwritten in the second file to black but the color will stay the same since the second file doesn't say anything about it.</p>
|
<p>do you mean 2 definitions for the same class? or 2 class names on an element?</p>
<p>The first case, no.</p>
<pre><code><style>
.foo{
border:1px solid blue;
color:red;
}
.foo{
border:4px solid orange;
}
</style>
<div class="foo">this will have an orange border and red text (no blue border)</div>
</code></pre>
<p>The second case, yes</p>
<pre><code><div class="class1 class2">this is valid</div>
</code></pre>
| 48,711
|
<p>Any free alternative to Robohelp? Prefer open source</p>
<p>Need some sort of online help authoring tool for an open source project.</p>
|
<p>Check out this <a href="http://www.thefreecountry.com/programming/helpauthoring.shtml" rel="nofollow noreferrer">list of free help authoring tools</a>, bound to be something useful there.</p>
|
<p>If you are trying to build .chm based help, try <a href="http://sourceforge.net/projects/chm-build/" rel="nofollow noreferrer"><strong>chm-build</strong></a></p>
| 11,665
|
<p>How can I show a web page in a transparent window and have the white part of the web page also transparent.</p>
|
<p>The solution is as follows.</p>
<p>Use Python module <a href="https://docs.python.org/3/library/zipfile.html" rel="noreferrer">zipfile</a> to create zip archive, but as the file specify <a href="https://docs.python.org/3/library/io.html#io.StringIO" rel="noreferrer">StringIO</a> object (ZipFile constructor requires file-like object). Add files you want to compress. Then in your Django application return the content of StringIO object in <code>HttpResponse</code> with mimetype set to <code>application/x-zip-compressed</code> (or at least <code>application/octet-stream</code>). If you want, you can set <code>content-disposition</code> header, but this should not be really required.</p>
<p>But beware, creating zip archives on each request is bad idea and this may kill your server (not counting timeouts if the archives are large). Performance-wise approach is to cache generated output somewhere in filesystem and regenerate it only if source files have changed. Even better idea is to prepare archives in advance (eg. by cron job) and have your web server serving them as usual statics.</p>
|
<p>Can't you just write a link to a "zip server" or whatnot? Why does the zip archive itself need to be served from Django? A 90's era CGI script to generate a zip and spit it to stdout is really all that's required here, at least as far as I can see.</p>
| 9,300
|
<p>Is there a way to track which window currently has keyboard focus. I could handle WM_SETFOCUS for every window but I'm wondering if there's an alternative, simpler method (i.e. a single message handler somewhere).</p>
<p>I could use OnIdle() in MFC and call GetFocus() but that seems a little hacky.</p>
|
<p>So from the way you worded the question I'm inferring that you want to have an event handler which is invoked whenever focus switches between windows. You want to be notified, rather than having to poll.</p>
<p>I actually don't think calling GetFocus from OnIdle is that much of a hack - sure it's polling, but it's low-overhead polling without side effects - but if you really want to track this, <a href="http://msdn.microsoft.com/en-us/library/ms997537.aspx" rel="noreferrer">Windows Hooks</a> are probably your best choice. Specifically you can install a CBT hook (WH_CBT) and listen for the HCBT_SETFOCUS notification.</p>
<blockquote>
<p>Windows calls the WH_CBT hook with this hook code when Windows is about to set the focus to any window. In the case of thread-specific hooks, the window must belong to the thread. If the filter function returns TRUE, the focus does not change.</p>
</blockquote>
<p>You could also do with with a WH_CALLWNDPROC hook and listen for the WM_SETFOCUS message.</p>
<p>Depending on whether you make it a global hook, or app-local, you can track focus across all windows on the system, or only the windows owned by your process.</p>
|
<p>You could monitor messages for the <a href="http://msdn.microsoft.com/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputmessages/wm_activate.asp?frame=true" rel="nofollow noreferrer">WM_ACTIVATE</a> event.</p>
<p><a href="http://blogs.msdn.com/jfoscoding/archive/2006/08/02/686141.aspx" rel="nofollow noreferrer">ref</a></p>
| 6,595
|
<p>I'm trying to do some async stuff in a webservice method. Let say I have the following API call: <a href="http://www.example.com/api.asmx" rel="nofollow noreferrer">http://www.example.com/api.asmx</a></p>
<p>and the method is called <em>GetProducts()</em>.</p>
<p>I this GetProducts methods, I do some stuff (eg. get data from database) then just before i return the result, I want to do some async stuff (eg. send me an email).</p>
<p>So this is what I did.</p>
<pre><code>[WebMethod(Description = "Bal blah blah.")]
public IList<Product> GetProducts()
{
// Blah blah blah ..
// Get data from DB .. hi DB!
// var myData = .......
// Moar clbuttic blahs :) (yes, google for clbuttic if you don't know what that is)
// Ok .. now send me an email for no particular reason, but to prove that async stuff works.
var myObject = new MyObject();
myObject.SendDataAsync();
// Ok, now return the result.
return myData;
}
}
public class TrackingCode
{
public void SendDataAsync()
{
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += BackgroundWorker_DoWork;
backgroundWorker.RunWorkerAsync();
//System.Threading.Thread.Sleep(1000 * 20);
}
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
SendEmail();
}
}
</code></pre>
<p>Now, when I run this code the email is never sent. If I uncomment out the Thread.Sleep .. then the email is sent.</p>
<p>So ... why is it that the background worker thread is torn down? is it dependant on the parent thread? Is this the wrong way I should be doing background or forked threading, in asp.net web apps?</p>
|
<p><code>BackgroundWorker</code> is useful when you need to synchronize back to (for example) a UI* thread, eg for affinity reasons. In this case, it would seem that simply using <code>ThreadPool</code> would be more than adequate (and much simpler). If you have high volumes, then a producer/consumer queue may allow better throttling (so you don't drown in threads) - but I suspect <code>ThreadPool</code> will be fine here...</p>
<pre><code>public void SendDataAsync()
{
ThreadPool.QueueUserWorkItem(delegate
{
SendEmail();
});
}
</code></pre>
<p>Also - I'm not quite sure what you want to achieve by sleeping? This will just tie up a thread (not using CPU, but doing no good either). Care to elaborate? It <em>looks</em> like you are pausing your actual web page (i.e. the Sleep happens on the web-page thread, not the e-mail thread). What are you trying to do here?</p>
<p>*=actually, it will use whatever sync-context is in place</p>
|
<p>It may torn down because after 20 seconds, that BackgroundWorker instance may be garbage collected because it has no references (gone out of scope).</p>
| 28,312
|
<p>I'm currently planning the migration of a Microsoft Content Management Server (MCMS) website to a SharePoint 2007 publishing site.</p>
<p>The top-level site is a public facing, anonymously-accessible website. It will contain two areas which need to be protected with forms-based authentication - each of which will have a distinct set of users. </p>
<p>There is content in the current MCMS site which uses "Connected Postings", which is the ability to use content in multiple places without duplicating it. In SharePoint, a similar concept is supported via the Reusable Content list, but this doesn't span site collections. </p>
<p>I'm thinking that this should be a single web application with three site collections. 1 for the public facing site, and the others for the two protected areas. However, I'm not sure if 1 site collection can be anonymous, with the other 2 implementing different FBA authentication providers. </p>
<p>I'd like my Urls to be something like:</p>
<p>www.whatever.com<br/>
www.whatever.com/protectedarea1<br/>
www.whatever.com/protectedarea2<br/></p>
<p>Without Url rewriting, this would be difficult to do with separate web applications. </p>
<p>If I end up having to go with 3 separate web applications in order to get authentication to work as desired, I will probably have to get creative with content deployment so as not to duplicate content during authoring. </p>
<p>Would appreciate any thoughts, thank you!</p>
|
<p>Don't do MCMS so cannot answer specific to that, see <a href="http://www.andrewconnell.com/blog/" rel="nofollow noreferrer">http://www.andrewconnell.com/blog/</a> for alot of info.</p>
<p>Microsoft has a bunch of different designs for extranets, <a href="http://technet.microsoft.com/en-us/library/cc263513.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/cc263513.aspx</a> depending on your needs. You can set it up as you are describing, forms are a little weak put their is some a better version available on CodePlex.</p>
<p>For the URLS, Sharepoint has a feature called "Manged Paths" that will do what you want. No URL rewriting needed.</p>
<p>Our setup is a site collection for extranet and internal, where most work is done. When finished they can publish it(does make an extra copy) to the public site. Some public sites are publish only sites where they have no interaction with non-account people, some are sites were they actually do most of their work and non-account people can make contributions. All are available under MOSS.</p>
|
<p>Don't do MCMS so cannot answer specific to that, see <a href="http://www.andrewconnell.com/blog/" rel="nofollow noreferrer">http://www.andrewconnell.com/blog/</a> for alot of info.</p>
<p>Microsoft has a bunch of different designs for extranets, <a href="http://technet.microsoft.com/en-us/library/cc263513.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/cc263513.aspx</a> depending on your needs. You can set it up as you are describing, forms are a little weak put their is some a better version available on CodePlex.</p>
<p>For the URLS, Sharepoint has a feature called "Manged Paths" that will do what you want. No URL rewriting needed.</p>
<p>Our setup is a site collection for extranet and internal, where most work is done. When finished they can publish it(does make an extra copy) to the public site. Some public sites are publish only sites where they have no interaction with non-account people, some are sites were they actually do most of their work and non-account people can make contributions. All are available under MOSS.</p>
| 34,930
|
<p>I'm supporting/enhancing a web application written in Classic ASP/VBScript. It has been about 10 years since I have used either in a day to day capacity. I just ran across an issue that I would consider a "gotcha" and was wondering if others had similar things that I should learn to be aware of.</p>
<p>My issue:<br>
I had to convert a Column in a SQL Table from float to decimal. It turns out that decimal isn't a type that is really supported (or supported well) in vbscript. So the following code:</p>
<pre><code>Dim var1, var2
var1 = rs("DecimalField1").Value
var2 = rs("DecimalField2").Value
If (var1 <> var2) Then
'Do Something'
End If
</code></pre>
<p>Would blow up with a Type Mismatch error on the line:</p>
<pre><code>If (var1 <> var2) Then
</code></pre>
<p>After much searching I found out that:</p>
<pre><code>var1 = CDBL(rs("DecimalField1").Value)
var2 = CDBL(rs("DecimalField2").Value)
</code></pre>
<p>resolves the issue. But that didn't seem like an obvious thing and it took me a while to figure out why the heck I was getting a Type Mismatch on that line.</p>
<p>So my question to everyone is, what other little quirks like this have you run across? What are some things within ASP/vbscript that you would think of as "gotchas" that I should be on the lookout for?</p>
|
<p><strong>Repeat after me:</strong> All good VB programmers use <code>Option Explicit</code></p>
<p>It will keep you from accidentally declaring a new variable and using it - thus throwing off whatever you are doing.</p>
<p>Beyond that, it depends on what you're doing.</p>
|
<p>Automatic variable allocation is probably one of the biggest gotchas.</p>
<pre><code>Dim varA, varB
varA = varA + varV
</code></pre>
<p>Oops! What's <code>varV</code> you ask? Well.. I just mistyped B for V and everything still works perfectly.. that must be a good thing!</p>
<p>Except why isn't varB gets added to varA ?? That must be Microsoft's bug!</p>
| 36,552
|
<p>Modern ATL/MFC applications now have access to a new shared pointer class called CAutoPtr, and associated containers (CAutoPtrArray, CAutoPtrList, etc.).</p>
<p>Does the CAutoPtr class implement reference counting?</p>
|
<p>Having checked the CAutoPtr source, no, reference counting is not supported. Using boost::shared_ptr instead if this ability is required.</p>
|
<p>The documentation for <a href="http://msdn.microsoft.com/en-us/library/txda4x5t(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/txda4x5t(VS.80).aspx</a></p>
<p>From reading this it looks like it tries to provides the same functionality as std::auto_ptr <b>i.e.</b> It uses ownership semantics. Only one CAutoPtr object holds the pointer and assignment transfers ownership from one CAutoPtr object to another.</p>
| 16,887
|
<p>I have two elements:</p>
<pre><code><input a>
<input b onclick="...">
</code></pre>
<p>When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so <code>document.getElementsByName</code> is out. Looking into the event object, I thought <code>event.target.parentNode</code> would have some function like <code>getElementsByName</code>, but this does not seem to be the case with <td>s. Is there any simple way to do this?</p>
|
<p>If <code>a</code> and <code>b</code> are next to each other and have the same parent, you can use the <code>prevSibling</code> property of <code>b</code> to find <code>a</code>.</p>
|
<p>Leave your plain vanilla JavaScript behind. Get JQuery--it will save you a ton of time.</p>
<p><a href="http://docs.jquery.com/Selectors" rel="nofollow noreferrer">http://docs.jquery.com/Selectors</a></p>
| 7,668
|
<p>Does someone have any tips/advice on database design for a web application? The kind of stuff that can save me a lot of time/effort in the future when/if the application I'm working on takes off and starts having a lot of usage.</p>
<p>To be a bit more specific, the application is a strategy game (browser based, just text) that will mostly involve players issuing "orders" that will be stored in the database and processed later, with the results also being stored there (the history of "orders" and the corresponding results will probably get quite big).</p>
<p><strong>Edited to add more details</strong> (as requested):</p>
<p>platform: Django</p>
<p>database engine: I was thinking of using MySQL (unless there's a big advantage in using another)</p>
<p>the schema: all I have now are some Django models, and that's far too much detail to post here. And if I start posting schemas this becomes too specific, and I was looking for general tips. For example, consider that I issue "orders" that will be later processed and return a result that I have to store to display some kind of "history". In this case is it better to have a separate table for the "history" or just one that aggregates both the "orders" and the result? I guess I could cache the "history" table, but this would take more space in the database and also more database operations because I would have to constantly create new rows instead of just altering them in the aggregate table.</p>
|
<p>You have probably touched on a much larger issue of designing for high scalability and performance in general.</p>
<p>Essentially, for your database design I would follow good practices such as adding foreign keys and indexes to data you expect to be used frequently, normalise your data by splitting it into smaller tables and identify which data is to be read frequently and which is to be written frequently and optimise.</p>
<p>Much more important than your database design for high performance web applications, is your effective use of caching both at the client level through HTML page caching and at the server level through cached data or serving up static files in place of dynamic files.</p>
<p>The great thing about caching is that it can be added as it is needed, so that when your application does take off then you evolve accordingly.</p>
<p>As far as your historical data is concerned, this is a great thing to cache as you do not expect it to change frequently. If you wish to produce regular and fairly intensive reports from your data, then it is good practise to put this data into another database so as not to bring your web application to a halt whilst they run.</p>
<p>Of course this kind of optimisation really isn't necessary unless you think your application will warrant it.</p>
|
<p>Why don't you post the schema you have now? It's too broad a question to answer usefully without some detail of what platform and database you're going to use and the table structure you're proposing...</p>
| 6,975
|
<p>I have problems with how to design some classes. I have three classes. One superclass, and two subclasses. </p>
<p>One subclass (AnimatedCharacter) is made by flash, and is used to display the object on screen. The other (CharacterPhysics) is made by myself to extend the superclass.</p>
<p>The problem is that the object I use, is of the type AnimatedCharacter, so I can't just put it in a variable of type CharacterPhysics.</p>
<p>What I tried is some sort of Decorator pattern, by giving the object of type CharacterPhysics a reference to the other object. But now I have to override all the methods of the superclass and pass the methodcalls to the reference. Not an ideal situation.</p>
<p>Does someone know how to solve this kind of problem?</p>
<p><a href="http://www.freeimagehosting.net/uploads/7a95f8352c.png" rel="nofollow noreferrer">alt text http://www.freeimagehosting.net/uploads/7a95f8352c.png</a></p>
|
<p>I don't quite understand the purpose of this class structure you describe (the class names confuse me), but in general a few things come to mind that might help you:</p>
<p>Almost always the best solution is to try and rethink your class model by evaluating whether you should for example break up the <em>responsibilities</em> of classes in an alternate way so that you could utilize inheritance and polymorphism in a better way.</p>
<blockquote>
<p><em>"The problem is that the object I use,
is of the type AnimatedCharacter, so I
can't just put it in a variable of
type CharacterPhysics."</em></p>
</blockquote>
<p>If you want to put an <code>AnimatedCharacter</code> into a variable of type <code>CharacterPhysics</code>, the former should extend the latter, or you should have a common interface (or superclass) for both and then type the variable as such. If this is not possible, my opinion is that you should probably try to rethink and refactor your whole class structure, assuming that you have a solid "object-oriented" reason for wanting to do this in the first place ;).</p>
<p>If the above is not possible, there are some other tricks you can evaluate in your context:</p>
<ul>
<li>The use of <a href="http://en.wikipedia.org/wiki/Mixin" rel="nofollow noreferrer">mixins</a> can work as a "poor man's multiple inheritance". Derek Wischusen has some examples on how to implement them in AS3 at <a href="http://flexonrails.net/?p=79" rel="nofollow noreferrer">flexonrails.net</a>.</li>
<li>"Kind of" implementing the decorator pattern with <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/Proxy.html" rel="nofollow noreferrer">flash.utils.Proxy</a>. The problem with this approach is that you defer a lot of error checking from compile time to runtime, but the good thing is that you don't have to manually write the "proxying" implementations of all of the methods of the "decorated" object, but write just one (<a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/Proxy.html#callProperty()" rel="nofollow noreferrer"><code>callProperty()</code></a>) instead.</li>
</ul>
|
<p>You can interpret a sublass as an instance of a superclass but not vice sersa. Did you state this backwards?</p>
<p>If so, you could use: </p>
<p>vas cp:CharacterPhysics;</p>
<p>...</p>
<p>var ac:AnimatedCharacter = cp As AnimatedCharacter</p>
| 34,120
|
<p>I built a cheap Delta printer with ATMega board and 1.8° motors. The micro stepping is limitied to 1/16. Beside a decent print quality, I observe a moire effect on flat surfaces. The moire is clearly caused by a combination of both, the 1.8° motors steps and the low microstepping. </p>
<p>I thought about using 0.9° stepper motors together with a combination of board and drivers which support < 1/32 micro stepping. Is there a comparison somewhere illustrating potential quality differences on larger delta printers and is this the way to remove the moire effect? For cartesian printers I would not bother using such motors, but I noticed that a higher holding torque at smaller steps is desirable for delta printers.</p>
<p><strong>Example</strong> </p>
<p>Not one of my prints, but this is how it looks
<a href="https://i.stack.imgur.com/ao5PD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ao5PD.png" alt="enter image description here"></a></p>
|
<p>Delta bots always need all motors to step to maintain a straight level. <a href="https://3dprinting.stackexchange.com/questions/5796/full-steps-mode-for-z-axis-stepper-controller">Microstepping</a>, is not magic, the <strong>incremental torque</strong> decreases per step so that you will be more likely to miss a few micro-steps. Furthermore, the signal that creates voltages for the micro-step positioning is usually not perfectly sinusoidal (pulse-width voltage modulation is used to achieve micro-stepping by controlling the current; the driver sends two voltage sine waves, 90 degrees out of phase to the motor windings), micro-stepping drives can only <strong>approximate</strong> a <strong>true sine wave</strong>. This means that some torque ripples, resonance, and noise remains and hence resulting in odd stepper behavior, like seen below from <a href="https://hackaday.com/2016/08/29/how-accurate-is-microstepping-really/" rel="nofollow noreferrer">this ref.</a> (after the half step the stepper jumps to the full step and maintains that value for a while):</p>
<p><a href="https://i.stack.imgur.com/ICxJV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ICxJV.jpg" alt="enter image description here"></a></p>
<p>This is seen as a <a href="https://en.wikipedia.org/wiki/Moir%C3%A9_pattern" rel="nofollow noreferrer">Moiré</a> pattern in your printed products. As an example, if the head is moved in Z direction by micro-step, you will almost certainly notice that the head doesn't move on every micro-step, but only every 3rd or 4th micro-step (as an example). When using higher resolution steppers like the 0.9° stepper motors, you will still miss micro-steps (e.g. the same, so also on every 3rd or 4th micro-step the head moves), but as the micro-step is half the size of that one of a 1.8° stepper motor, the accuracy as in precision and resolution is higher.</p>
<p>In that sense, if you change your stepper drivers for higher micro-stepping drivers (from 1/16 to 1/32 as you mention), it will not help you improve the resolution much because the incremental torque from one to another 1/32 micro-step is lower than for 1/16 micro-steps as can be seen in the figure below (taken from <a href="https://www.micromo.com/media/wysiwyg/Technical-library/Stepper/6_Microstepping%20WP.pdf" rel="nofollow noreferrer">this ref.</a>). </p>
<p><a href="https://i.stack.imgur.com/mBonI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mBonI.png" alt="Incremental stepper torque as function of micro-step size"></a></p>
<p>So, using 0.9° motors (and keeping 1/16 micro-stepping) improves positioning accuracy as described above, it will also reduce the noise, because the torque per unit angular error is nearly doubled. Also remember that if you are using 8-bit electronics (you hint to an ATMega board), then even 1/32 micro-stepping burdens the processor to achieve reasonable travel speeds. With 8-bit electronics, it is usually suggested to use 1/16 stepping.</p>
<p>Upgrading an existing printer from 1.8° to 0.9° stepper motors is probably not worth for the majority of users (note that the maximum allowable speed also reduces when using 0.9° stepper motors). Unless you are designing and building a new delta, or aren't on a tight budget you could opt for the additional costs of buying 0.9° stepper motors.</p>
<p>Note that updating to higher micro-stepping values not necessarily implies that the quality of your products also increase. See e.g. <a href="https://3dprinting.stackexchange.com/a/159/5740">this reference</a>.</p>
|
<p>I am looking at the example print you supplied and trying to understand the defects. Was the object printed vertically, so that the object Z-axis is running from top to bottom in the picture? </p>
<p>If so, then the horizontal defects look like resonance artifacts, which could be caused by the issue you raise of the stepper motor not responding to small movement commands. The only thing that will prevent the motor from responding is stiction, or difficulty starting a movement. Stiction is a non-linear aspect of friction in which the "starting" friction is higher than the "sliding" friction. It might be worth checking for surfaces which must slide against each other, and assure they are lubricated with a dry, non-tacky lubricant.</p>
<p>A typical delta machine behaves the same way on each layer. The equations which govern how high on the tower the top of the delta-leg should be for each x,y, and z point is linear in Z, but non-linear in X and Y. With that in mind, I have no hypothesis to describe the defects that would be described as cathedrals if they were wood grain.</p>
<p>Or, perhaps the object was printed so that the surface shown is parallel to the bed? If so, the defects looks like more than a couple of microsteps. Is it possible that one drive is not working correctly? If so, I would suggest that the motor on the tower pointed to (or pointed from) by the cathedrals is not working like the others. It could be binding too tightly to the tower, or the pully may be loose, or the driver isn't working correctly for one of the two coils.</p>
| 1,114
|
<p>I have a content management application in the root of my website, and I'm trying to use a different app (a billing application) under a sub-folder. Unfortunately, the web.config of the root site is interfering with the sub-app.</p>
<p>Is there a way to just disable web.config inheritance for a sub-folder?</p>
<p><strong>Update:</strong>
As linked by <a href="https://stackoverflow.com/users/31474/stephen-b-burris-jr">Stephen Burris</a>, using the <code><location></code> tag can prevent inheritance for part of the web config, as follows:</p>
<pre><code><?xml version="1.0"?>
<configuration>
<configSections>
....
</configSections>
<location path="." inheritInChildApplications="false">
<appSettings>
....
</appSettings>
<connectionStrings/>
<system.web>
....
</system.web>
<system.codedom>
....
</system.codedom>
<system.webServer>
....
</system.webServer>
</location>
<runtime>
....
</runtime>
</configuration>
</code></pre>
<p>The <code><configSections></code> and <code><runtime></code> sections will not accept being enclosed in the tag...so I guess this only does most of the job. Anybody know how to do it better?</p>
|
<p>There is an attribute that you can use in the root web.config file to cause it not to have its contents become inherited by child applications.</p>
<p>inheritInChildApplications</p>
<p><a href="http://www.kowitz.net/archive/2007/05/16/stopping-asp.net-web.config-inheritance.aspx" rel="nofollow noreferrer">Blog about inheritInChildApplications</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms178685.aspx" rel="nofollow noreferrer">MSDN article on ASP.NET Configuration File Hierarcy and Inheritance</a></p>
<p>Put the part of the config that is not for inheritance inside</p>
<pre><code><location inheritInChildApplications="false">
<NotInheritedConfigPart/>
</location>
</code></pre>
<p>Config sections seem to be impossible to not inherit, but other parts of configuration can be "commented" out like this and don't get inherited.</p>
|
<p>I have faced this situation a few times. It seems that the parent poster's instincts are in the ball park. I have found that adding two entries seem to have solved it—both a <code><location></code> entry.</p>
<ol>
<li><p>Find your <code><system.web></code>…<code></system.web></code>. Wrap it with a <code><location path="." inheritInChildApplications="false"></code>.</p>
<p>Now check the parent site and make sure it still works.
Check the child: does it work or give an error?</p>
</li>
<li><p>If you still have an error, do the same thing with <code><system.webserver></code>; wrap the same <code><location></code> tag around it.</p>
</li>
</ol>
<p>In summary - in the <strong>PARENT</strong>:</p>
<pre class="lang-xml prettyprint-override"><code><location path="." inheritInChildApplications="false">
<system.web>
...
</system.web>
</location>
</code></pre>
<p>and maybe:</p>
<pre class="lang-xml prettyprint-override"><code><location path="." inheritInChildApplications="false">
<system.webserver>
...
</system.webserver>
</location>
</code></pre>
| 47,940
|
<p>I've got a timer running in my Delphi MDI application and I'd like to use it to pop up a message if something changes in the background. But I don't want that message to pop up when the the application has a modal dialog in the foreground because the user couldn't do anything about it. </p>
<p>So what I'd like to know is how can I check for the existence of a modal dialog in my application?</p>
|
<p>You could try with this code:</p>
<pre><code>var
ActForm: TCustomForm;
begin
ActForm := Screen.ActiveForm;
if (ActForm = nil) or not (fsModal in ActForm.FormState) then begin
end;
end;
</code></pre>
<p>I tested with Delphi 4, works for me.</p>
<p>[EDIT]: But you should really think about whether popping up a form and stealing focus is a good idea. It depends on your application, but if a user is currently entering something into an edit field, or doing something with the mouse, then this might break their workflow.</p>
|
<p>Today user <a href="https://stackoverflow.com/users/180353/histrio">histrio</a> correctly answered in <a href="https://stackoverflow.com/questions/3306260/delphi-detecting-if-my-app-has-a-modal-dialog-open">another thread</a> that just monitoring modal Delphi forms is not enough; Windows can also have modal dialogs.</p>
<p>His <a href="https://stackoverflow.com/questions/3306260/delphi-detecting-if-my-app-has-a-modal-dialog-open/3306514#3306514">answer in another thread</a> shows you how to check for that.</p>
<p>--jeroen</p>
| 36,110
|
<p>I'm using Java 6, Tomcat 6, and Metro. I use WebService and WebMethod annotations to expose my web service. I would like to obtain information about the request. I tried the following code, but wsCtxt is always null. What step must I take to <em>not</em> get null for the WebServiceContext.</p>
<p>In other words: how can I execute the following line to get a non-null value for wsCtxt?</p>
<p>MessageContext msgCtxt = wsCtxt.getMessageContext();</p>
<pre><code>@WebService
public class MyService{
@Resource
WebServiceContext wsCtxt;
@WebMethod
public void myWebMethod(){
MessageContext msgCtxt = wsCtxt.getMessageContext();
HttpServletRequest req = (HttpServletRequest)msgCtxt.get(MessageContext.SERVLET_REQUEST);
String clientIP = req.getRemoteAddr();
}
</code></pre>
|
<p>I recommend you either rename your variable from wsCtxt to wsContext or assign the name attribute to the @Resource annotation. The <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/bncjk.html" rel="noreferrer">J2ee tutorial on @Resource</a> indicates that the name of the variable is used as part of the lookup. I've encountered this same problem using resource injection in Glassfish injecting a different type of resource.</p>
<p>Though your correct name may not be wsContext. I'm following this <a href="http://www.java-tips.org/java-ee-tips/java-api-for-xml-web-services/using-jax-ws-based-web-services-wit.html" rel="noreferrer">java tip</a>. If you like the variable name wsCtxt, then use the name attribute in the variable declaration:</p>
<blockquote>
<p><code>@Resource(name="wsContext") WebServiceContext wsCtxt;</code></p>
</blockquote>
|
<p>Maybe the javax.ws.rs.core.Context annotation is for what you are looking for, instead of Resource?</p>
| 16,154
|
<p>An <a href="https://stackoverflow.com/questions/15241/does-anyone-have-any-real-world-experience-of-csla#15357">answer</a> to a Stack Overflow question stated that a particular framework violated a plain and simple OOP rule: Single Responsibility Principle (SRP).</p>
<p><strong>Is the Single Responsibility Principle <em>really</em> a rule of OOP?</strong></p>
<p>My understanding of the definition of Object Orientated Programming is "a paradigm where objects and their behaviour are used to create software". This includes the following techniques: Encapsulation, Polymorphism & Inheritance.</p>
<p>Now don't get me wrong - I believe SRP to be the key to most good OO designs, but I feel there are cases where this principle can and should be broken (just like database normalization rules). I aggressively push the benefits of SRP, and the great majority of my code follows this principle. </p>
<p><em>But, is it a rule, and thus implies that it shouldn't be broken?</em></p>
|
<p>Very few rules, if any, in software development are without exception. Some people think there are no place for <em>goto</em> but they're wrong. </p>
<p>As far as OOP goes, there isn't a single definition of object-orientedness so depending on who you ask you'll get a different set of hard and soft principles, patterns, and practices.</p>
<p>The classic idea of OOP is that messages are sent to otherwise opaque objects and the objects interpret the message with knowledge of their own innards and then perform a function of some sort.</p>
<p>SRP is a software engineering principle that can apply to the role of a class, or a function, or a module. It contributes to the cohesion of something so that it behaves well put together without unrelated bits hanging off of it or having multiple roles that intertwine and complicate things.</p>
<p>Even with just one responsibilty, that can still range from a single function to a group of loosely related functions that are part of a common theme. As long as you're avoiding jury-rigging an element to take the responsibilty of something it wasn't primarily designed for or doing some other ad-hoc thing that dilute the simplicity of an object, then violate whatever principle you want.</p>
<p>But I find that it's easier to get SRP correct then to do something more elaborate that is just as robust.</p>
|
<p>SRP is just another expression of ISP :-) . </p>
<p>And the "P" means "principle" , not "rule" :D </p>
| 3,624
|
<p>I'm reading through K&R and came to the small section on register variables, and was wondering if people here have some good examples of this put into practice.</p>
<p>From section 4.7 in K&R:</p>
<blockquote>
<p>The register declaration looks like<br>
register int x;<br>
register char c;</p>
</blockquote>
<p>To be clear, I'm just hoping to see some cool code samples. I (am pretty sure that I) understand the subject matter so don't feel the need to type up a verbose explanation (unless you want to).</p>
|
<p>There is no good example of register usage when using modern compilers (read: last 15+ years, and note that this answer is from 2008) because it almost never does any good and can do some bad. When you use register, you are telling the compiler "I know how to optimize my code better than you do" which is almost never the case. One of three things can happen when you use register:</p>
<ul>
<li>The compiler ignores it, this is most likely. In this case the only harm is that you cannot take the address of the variable in the code.</li>
<li>The compiler honors your request and as a result the code runs slower.</li>
<li>The compiler honors your request and the code runs faster, this is the least likely scenario.</li>
</ul>
<p>Even if one compiler produces better code when you use register, there is no reason to believe another will do the same. If you have some critical code that the compiler is not optimizing well enough your best bet is probably to use assembler for that part anyway but of course do the appropriate profiling to verify the generated code is really a problem first.</p>
|
<p>Well This is a Question that needs multiple answers because there are multiple coding contexes: from the high level language perspective, the mid level and low level (down to assembly) since the C language can call assembly routines.</p>
<p>The reason for using assembly instead of C is exavtly because of performance issues encountered during development soz yes there is a need for the register keyword but no it is not working as intended by developer in many cases</p>
| 40,658
|
<p>So I got started with PHP at version 4, and had to make the switch to 5. Now I understand that version 6 is on the way, and that a lot of things have been re-thought.</p>
<p>The changes may be good ones, but in the future, does anyone know about PHP's roadmap? Does it look like it will flatten out?</p>
|
<p>The history of PHP is that they don't implement breaking changes without good reason. I've always seen the benefits of the work I had to do porting to new PHP versions. So, I would actually consider it a good thing that the developers aren't afraid of breaking things when it needs to be done.</p>
|
<p>I am really scared with this. I like php and have put a great deal of time in becoming good with php. It's sad and scary to see the developers don't know what the hell they are doing or why they implement this or that in this or that manner. I hope in the future they have a clear vision of php. I do really like php 5 and all it's oop capabilities :)
I am doing a little framework just to try to understand more of php. Hope I achieve something with all my work on this little framework :) </p>
| 31,027
|
<p>I get the concept of automatic bed leveling...the printer moves around the bed and uses a sensor to identify high and low spots, then "software compensates for differences". </p>
<p>But what exactly does "compensates" mean? </p>
<p>It is extruding more material in the low spots to build them up and thinning out the high spots? Is it adding or removing layers? Is it shifting layers as it goes up to compensate tilt? Or...? </p>
<p>In what ways will this affect the final outcome? Would it be valid to say that if you wanted an automatically leveled bed and dimensional accuracy you should always print to a raft?</p>
|
<p>Last first: use of a raft has nothing to do with bed levelling. It depends only on the features/shape/etc of the object being printed.</p>
<p>Now, as to what the auto-levelling does: the answer is, sadly "it depends." A simple algorithm will just find the Z-height of the four corners and apply a bilinear correction to Z as a function of {x,y} coordinates. A really good algorithm would map the entire build plate to some designated precision (perhaps 5 mm) and create a 2-dimensional lookup table to adjust Z over a curved build plate. What your printer's levelling software does is more likely the former. </p>
<p>Why? because if you try to correct over curves & bumps, then you will end up distorting your entire printed object (basically forcing every layer to follow those distorted axes). Far better to have some flattened or "fat" spots in the first layer printed, and then print proper planar layers after that. </p>
<p>Example: I know my bed (AnetA8 aluminum) is slightly bowed, peak in the center; so after levelling the overall bed I try to set the Z-zero so the outer extremes of my object have good adhesion, even if the center region of the first couple layers ends up non-extruding because the nozzle touches the bed. </p>
|
<p>A probe or even manual (e.g. through LCD panel) leveling results in either a reference plane or mesh. This depends on the firmware and the options set in the firmware. Basically, this process maps the geometry of your build plate. Once it knows this geometry, printing an object results in the head following the height contours of the mapped build plate. Generally the following of the height contours is levelled out in the first few millimeters, which is also set in the firmware. This means that after a few millimeters of printing the height is not adjusted anymore, but is kept at a single level.</p>
| 1,017
|
<p>I have 3 points (A, B and X) and a distance (d). I need to make a function that tests if point X is closer than distance d to any point on the line segment AB. </p>
<p>The question is firstly, is my solution correct and then to come up with a better (faster) solution.</p>
<p>My first pass is as follows</p>
<pre><code>AX = X-A
BX = X-B
AB = A-B
// closer than d to A (done squared to avoid needing to compute the sqrt in mag)
If d^2 > AX.mag^2 return true
// closer than d to B
If d^2 > BX.mag^2 return true
// "beyond" B
If (dot(BX,AB) < 0) return false
// "beyond" A
If (dot(AX,AB) > 0) return false
// find component of BX perpendicular to AB
Return (BX.mag)^2 - (dot(AB,BX)/AB.mag)^2 < d^2
</code></pre>
<p>This code will end up being run for a large set of P's and a large set of A/B/d triplets with the intent of finding all P's that pass for at least one A/B/d so I suspect that there is a way to reduce overall the cost based on that but I haven't looked into that yet.</p>
<p>(BTW: I am aware that some reordering, some temporary values and some algebraic identities could decrease the cost of the above. I just omitted them for clarity.)</p>
<hr>
<p><em>EDIT: this is a 2D problem (but solution that generalizes to 3D would be cool</em></p>
<p>Edit: On further reflection, I expect the hit rate to be around 50%. The X point can be formed in a nested hierarchy so I expect to be able to prune large subtrees as all-pass and all-fail. The A/B/d limiting the triplets will be more of a trick.</p>
<p>Edit: d is in the same order of magnitude as AB.</p>
<hr>
<p>edit: Artelius posted a nice solution. I'm not sure I understand exactly what he's getting at as I got off on a tangent before I fully understood it. Anyway another thought came to mind as a result:</p>
<ul>
<li>First Artelius' bit, pre-cacluate a matrix that will place AB centered ate the origin and aligned with the X-axis. (2 adds, 4 muls and 2 adds)</li>
<li>fold it all into the 1st quadrant (2 abs)</li>
<li>scale in X&Y to make the central portion of the zone into a unit square (2 mul)</li>
<li>test if the point is in that square (2 test) is so quit</li>
<li>test the end cap (go back to the unscaled values
<ul>
<li>translate in x to place the end at the origin (1 add)</li>
<li>square and add (2 mul, 1 add)</li>
<li>compare to d^2 (1 cmp)</li>
</ul></li>
</ul>
<p>I'm fairly sure this beats my solution.</p>
<p>(if nothing better comes along sone Artelius gets the "prize" :)</p>
|
<p>If your set of (A,B,d) in fixed, you can calculate a pair of matrices for each to translate the co-ordinate system, so that the line AB becomes the X axis, and the midpoint of AB is the origin.</p>
<p>I <em>think</em> this is a simple way to construct the matrices:</p>
<pre><code>trans = - ((A + B) / 2) // translate midpoint of AB to origin
rot.col1 = AB / AB.mag // unit vector in AB direction
0 -1
rot.col2 = rot.col1 * ( ) // unit vector perp to AB
1 0
rot = rot.inverse() // but it needs to be done in reverse
</code></pre>
<p>Then you just take each X and do <code>rot * (X + trans)</code>.</p>
<p>The region in question is actually symmetric in both the x and y axes now, so you can take the absolute value of the x co-ordinate, and of the y co-ordinate.</p>
<p>Then you just need to check:</p>
<pre><code>y < d && x < AB.mag/2 //"along" the line segment
|| (x - AB.mag/2)^2 + y^2 < d^2 // the "end cap".
</code></pre>
<p>You can do another trick; the matrix can scale down by a factor of <code>AB.mag/2</code> (remember the matrices are only calculated once per (A,B) meaning that it's better that finding them is slower, than the actual check itself). This means your check becomes:</p>
<pre><code>y < 2*d/AB.mag && x < 1
|| (x - 1)^2 + y^2 < (2*d/AB.mag)^2
</code></pre>
<p>Having replaced two instances of AB.mag/2 with the constant 1, it might be a touch faster. And of course you can precalculate <code>2*d/AB.mag</code> and <code>(2*d/AB.mag)^2</code> as well.</p>
<p>Whether this will work out faster than other methods depends on the inputs you give it. But if the length of AB is long compared to d, I think it will turn out considerably faster than the method you posted.</p>
|
<blockquote>
<p>This code will end up being run for a large set of P's and a large set of A/B/d triplets with the intent of finding all P's that pass for at least one A/B/d so I suspect that there is a way to reduce overall the cost based on that but I haven't looked into that yet.</p>
</blockquote>
<p>In the case when d ~ AB, for a given point X, you can first test whether X belongs to one of the many spheres of radius d and center Ai or Bi. Look at the picture:</p>
<pre><code> ...... .....
........... ...........
...........................
.......A-------------B.......
...........................
........... ...........
..... .....
</code></pre>
<p>The first two tests</p>
<pre><code>If d^2 > AX.mag^2 return true
If d^2 > BX.mag^2 return true
</code></pre>
<p>are the fastest ones, and if d ~ AB they are also the ones with highest probability to succeed (given that the test succeeds at all). Given X, you can do all the "sphere tests" first, and then all the final ones:</p>
<pre>Return (BX.mag)^2 - (dot(AB,BX)/AB.mag)^2 </pre>
| 31,812
|
<p>Anticipating the day when multi-touch interfaces become more pervasive, are there libraries in Java that can be used for developing touch applications? I'm looking for interfaces similar to MouseListener / MouseMotionListener / MouseWheelListener.</p>
|
<p>The MT4j project has everything you need to develop multitouch applications in java.
All the well known multitouch gestures are already built in and can be accessed as simple
as listening to mouse events (for example: component.addGestureListener(..)).
It also features a hardware accelerated scene graph, similar to JavaFX.
You can even simulate multitouch input by connecting one ore more mice to your machine.
Check it out at <a href="http://www.mt4j.org" rel="noreferrer">http://www.mt4j.org</a></p>
|
<p>I am primarily working in Processing and designing my UI from the ground up. I've been looking for a solution which doesn't prescribe a UI framework which both MT4J and JavaFX appear to do. Furthermore, MT4J appears to be abandoned.</p>
<p>This looks like a promising solution at least for Windows but I'm unsure if it's actually released yet:
<a href="http://wiki.gestureworks.com/index.php/GestureWorksCore%3aGestureworks_Core_Tutorials" rel="nofollow">http://wiki.gestureworks.com/index.php/GestureWorksCore:Gestureworks_Core_Tutorials</a></p>
<p>This is specifically for Processing, cross-platform, open-source and active:
<a href="https://github.com/vialab/SMT" rel="nofollow">https://github.com/vialab/SMT</a></p>
| 48,233
|
<p>I know the use of server-side controls is a no-no in ASP.NET MVC, however we have a long list of crystal reports that the company has already produced for a previous application that I would like to utilize for our new ASP.NET MVC application.</p>
<p>Is there an appropriate way to use crystal reports in ASP.NET MVC? If so, how?</p>
|
<p>It is pretty simple actually. just add following references to your MVC project:</p>
<ul>
<li>CrystalDecisions.CrystalReports.Engine</li>
<li>CrystalDecisions.ReportSource </li>
<li>CrystalDecisions.Shared</li>
</ul>
<p>use Action method like below:</p>
<ul>
<li><p>C# :</p>
<pre><code>using CrystalDecisions.CrystalReports.Engine;
public ActionResult Report()
{
ReportClass rptH = new ReportClass();
rptH.FileName = Server.MapPath("[reportName].rpt");
rptH.Load();
rptH.SetDataSource([datatable]);
Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
return File(stream, "application/pdf");
}
</code></pre></li>
<li><p>VB.NET : </p>
<pre><code> Imports CrystalDecisions.CrystalReports.Engine
Public Function Report() As ActionResult
Dim rptH As New ReportClass()
rptH.FileName = Server.MapPath("[reportName].rpt")
rptH.Load()
rptH.SetDataSource([datatable])
Dim stream As IO.Stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat)
Return File(stream, "application/pdf")
End Function
</code></pre></li>
</ul>
|
<p><strong>Just add this reference : using CrystalDecisions.CrystalReports.Engine;<br>
than do this action :</strong> </p>
<pre><code>using CrystalDecisions.CrystalReports.Engine;
public ActionResult Report()
{
List<Table> table = new List<Table>();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Repport/CrystalReport1.rpt")));
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Suivie Historique.pdf");
}
</code></pre>
| 45,382
|
<p>I am trying to have Apache follow a symlink to a raid array server that will contain some large data files. I have tried modifying <code>httpd.conf</code> to have an entry like this</p>
<pre><code><Directory "/Users/imagine/Sites">
Options FollowSymLinks
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</code></pre>
<p>to have Apache follow any sym link in the Sites folder.</p>
<p>I keep getting an error return that seems to indicate I don't have any permissions to access the files. The error is:</p>
<blockquote>
<p>Forbidden</p>
<p>You don't have permission to access
/~imagine/imageLibraryTest/videoClips/imageLibraryVideos/imageLibraryVideos/Data13/0002RT-1.mov
on this server.</p>
</blockquote>
<p>The sys link file is the last "imageLibraryVideos" in the line with the Data13 being the sub dir on the server containing the file. </p>
<p>The 0002RT-1.mov file hase these permissions:</p>
<pre><code>-rwxrwxrwx 1 imagine staff 1138757 Sep 15 17:01 0002RT-1.mov
</code></pre>
<p>and is in this path:</p>
<pre><code>cd /Volumes/ImagineProducts-1/Users/imagine/Sites/imageLibraryVideos/Data13
</code></pre>
<p>the link points to:</p>
<pre><code>lrwxr-xr-x 1 imagine staff 65 Sep 15 16:40 imageLibraryVideos -> /Volumes/ImagineProducts-1/Users/imagine/Sites/imageLibraryVideos
</code></pre>
|
<p>I had the same problem last week and the solution was pretty simple for me.</p>
<p>Run:</p>
<pre><code>sudo -i -u www-data
</code></pre>
<p>And then try navigating the path, directory by directory. You will notice at some point that you don't have access to open the dir.
If you get into the last directory, check that you can read the file (with head for example).</p>
|
<p>This is a permissions problem where the user that your web server is running under does not have read and/or execute permissions to the necessary directories in the symbolic link path. The quick and easy way to check is to <code>su - web-user</code> (where <code>web-user</code> is the user account that the web server is running under) and then try to cd into the path and view the file. When you come across a directory that you don't have permission to enter, you'll have to change the permissions and/or ownership to make it accessible by the web server user account.</p>
| 11,161
|
<p>I have a directory full (~10<sup>3</sup>, 10<sup>4</sup>) of XML files from which I need to extract the contents of several fields.
I've tested different xml parsers, and since I don't need to validate the contents (expensive) I was thinking of simply using xml.parsers.expat (the fastest one) to go through the files, one by one to extract the data. </p>
<ol>
<li>Is there a more efficient way? (simple text matching doesn't work)</li>
<li>Do I need to issue a new ParserCreate() for each new file (or string) or can I reuse the same one for every file?</li>
<li>Any caveats?</li>
</ol>
<p>Thanks!</p>
|
<p>The quickest way would be to match strings (with, e.g., regular expressions) instead of parsing XML - depending on your XMLs this could actually work.</p>
<p>But the most important thing is this: instead of thinking through several options, just implement them and time them on a small set. This will take roughly the same amount of time, and will give you real numbers do drive you forward.</p>
<p>EDIT:</p>
<ul>
<li>Are the files on a local drive or network drive? Network I/O will kill you here.</li>
<li>The problem parallelizes trivially - you can split the work among several computers (or several processes on a multicore computer).</li>
</ul>
|
<p>If you know that the XML files are generated using the ever-same algorithm, it might be more efficient to not do any XML parsing at all. E.g. if you know that the data is in lines 3, 4, and 5, you might read through the file line-by-line, and then use regular expressions.</p>
<p>Of course, that approach would fail if the files are not machine-generated, or originate from different generators, or if the generator changes over time. However, I'm optimistic that it <em>would</em> be more efficient.</p>
<p>Whether or not you recycle the parser objects is largely irrelevant. Many more objects will get created, so a single parser object doesn't really count much.</p>
| 44,818
|
<p>I have an app with the following basic architecture:</p>
<p>A windows service (Service) that registers a .NET type (RemoteObject) for remote access (.NET Remoting). RemoteObject creates non-ThreadPool threads that use the ThreadPool to do IO processing. The size of the ThreadPool must be restricted to a limit for a particular reason. A GUI app uses .NET Remoting to access RemoteObject. </p>
<p>I've noticed that if the size of the ThreadPool is too low, the GUI app will hang when making a call to RemoteObject.</p>
<p>My question is, how can I figure out why this is hanging, and why would the RemoteObject thread be affected by the ThreadPool?</p>
<p>This is driving me crazy; thank you for your help!</p>
|
<p>It turns out that the .NET remoting infrastructure uses the .NET ThreadPool (or shares the underlying resource), so remoting calls can hang if all ThreadPool threads are in use by your app.</p>
|
<p>A few years ago, I designed and implemented a critical business system that used .NET Remoting. We had a client implemented as a Windows Forms GUI, a server implemented as a Windows Service, and a SQL Server database.</p>
<p>I designed for troubleshooting/debugging/development, so one of my first design criteria was that I could trivially remove the entire .NET Remoting implementation and run the whole system on my desktop. So, I could deactivate the remoting by changing a single boolean configuration setting to "false" = off. I could then troubleshoot, debug, develop completely without the overhead or interference of .NET Remoting.</p>
<p>It seems that this would be valuable for your situation as well. As a matter of fact, I can't imagine a situation in which that is not a desirable feature, especially since it is easy to implement.</p>
<p>So, to implement it, the configuration setting was used by each of the client and the server code to decide which implementation class to instantiate for communication with the other side. All communication occurred through a custom C# interface which had two concrete implementation classes on each side: one class implemented the communication using .NET Remoting, the other class implemented the communication as a direct in-process passthrough (direct calls).</p>
<p>Only the one pair of classes (one on each side) knew anything about .NET Remoting, so the isolation was total. Most of the time, all the developers worked with the remoting turned off, which was faster and simpler. When they needed to, on rare occasion, they turned it on (mostly just me, or when someone connected to test/production for troubleshooting).</p>
<p>By the way, I made the remoting interface dead simple:
public Response execute(Request)</p>
<p>Beyond that, I also used the debugger launching tip mentioned above, and I agree that you need to be mindful of the impact to the GUI threading.</p>
| 33,885
|
<p>I recently rolled an application that automatically encrypted a file output from another internal system using PGP and then sftp’d to a foreign target server directory where it was to be consumed by a third-party application. I have been trying to trouble shoot the whole process for about a week and was getting no response from the third-party until this morning in an email....</p>
<p>“<em>Turns out, the file is named incorrectly so the system didn’t think you submitted it. There was a capital “T” that should have been lower cased.</em>”</p>
<p>Ok. After an aggravated sigh (since nobody else has access to that directory and no other files named in a similar fashion), I started to wonder, “<strong>When should an application honor case sensitivity from user input <em>outside of passwords</em>?</strong>” I am running through my brain here trying to think of a time when I would want "fileName" and "FileName" to mean something different intentionally.</p>
<p><a href="http://www.codinghorror.com/blog/archives/000458.html" rel="nofollow noreferrer">I am not talking about in-application variable naming conventions here, btw.</a> I'm actually very much for case-sensitive in-language. </p>
|
<p>I suppose it would depend on what platform it is on. In Linux case sensitivity is the default so that would bring case sensitivity to the file system calls nessacary to find a file in a directory. But other than that it shouldn't.</p>
|
<p>I suppose it would depend on what platform it is on. In Linux case sensitivity is the default so that would bring case sensitivity to the file system calls nessacary to find a file in a directory. But other than that it shouldn't.</p>
| 31,267
|
<p>I have a URI here in which a simple document.cookie query through the console is resulting in three cookies being displayed. I verified this with trivial code such as the following as well:</p>
<pre><code>var cookies = document.cookie.split(';');
console.log(cookies.length);
</code></pre>
<p>The variable cookies does indeed come out to the number 3. Web Developer on the other hand is indicating that a grand total of 8 cookies are in use.</p>
<p>I'm slightly confused to believe which is inaccurate. I believe the best solution might involve just reiterating the code above without the influence of Firebug. However, I was wondering if someone might suggest a more clever alternative to decipher which tool is giving me the inaccurate information.</p>
|
<p>The alternative to template style meta-programming is Macro-style that you see in various Lisp implementations. I would suggest downloading <a href="http://www.paulgraham.com/onlisp.html" rel="noreferrer">Paul Graham's <em>On Lisp</em></a> and also taking a look at <a href="http://clojure.org" rel="noreferrer">Clojure</a> if you're interested in a Lisp with macros that runs on the JVM.</p>
<p>Macros in Lisp are much more powerful than C/C++ style and constitute a language in their own right -- they are meant for meta-programming.</p>
|
<p>It does not matter what language you are using -- any of them is able to do Heterogeneous Generative Metaprogramming. <strong>Take any dynamic language</strong> such as Python or Clojure, or Haskell if you are a type-fan, <strong>and write models</strong> in this host language that are <em>able to compile themself into some mainstream language</em> you want or forced to use by your team/employer.</p>
<p>I found object graphs a good model for internal model representation. This graph can mix attributes and ordered subgraphs in a single node, which is native to attribute grammar and AST. So, object graph interpretation can be an effective layer between your host and target languages and can act itself as some sort of no-syntax language defined over data structures.</p>
<p>The closest model is an AST: describe AST trees in Python (host language) targets to C++ syntax (target language):</p>
<pre class="lang-py prettyprint-override"><code># from metaL import *
class Object:
def __init__(self, V):
self.val = V
self.slot = {}
self.nest = []
class Module(Object):
def cc(self):
c = '// \ %s\n' % self.head(test=True)
for i in self.nest:
c += i.cc()
c += '// / %s\n' % self.head(test=True)
return c
hello = Module('hello')
# <module:hello> #a04475a2
class Include(Object):
def cc(self):
return '#include <%s.h>\n' % self.val
stdlib = Include('stdlib')
hello // stdlib
# <module:hello> #b6efb657
# 0: <include:stdlib> #f1af3e21
class Fn(Object):
def cc(self):
return '\nvoid %s() {\n}\n\n' % self.val
main = Fn('main')
hello // main
print(hello.cc())
</code></pre>
<pre><code>// \ <module:hello>
#include <stdlib.h>
void main() {
}
// / <module:hello>
</code></pre>
<p>But you are not limited with the level of abstraction of constructed object graph: you not only can freely add your own types but object graph can interpret itself, can thus can modify itself the same way as lists in a Lisp can do.</p>
| 14,216
|
<p>Does anyone have any good links for developing custom field and content types that doesn't involve using VSeWSS? Most of the stuff I have seen on the web requires installing VSeWSS, I would rather build them from scratch with just VS2005.</p>
<p>Thanks</p>
|
<p>I understand the idea of doing it by hand first without a tool to help.</p>
<p>But, you will end up creating a lot of xml by hand. It will really hurt and take a long time.</p>
<p>I would recommend <a href="http://www.codeplex.com/stsdev" rel="nofollow noreferrer">STSDev</a> personally. Use it to create the solution and features for the custom content types and fields, including any custom controls. </p>
<p>Once the package has been created, you can then reverse engineer it to find out the nuts and bolts of how the whole thing holds together.</p>
<p>If you do it on a virtual machine, you can still keep a virgin 2005 install to roll back to when you want to.</p>
<p>I believe this will increase the time to understand what is going on with Content Types and Fields.</p>
|
<p>Check out rapid tools and SPDeploy:</p>
<p><a href="http://rapid-tools.googlecode.com" rel="nofollow noreferrer">http://rapid-tools.googlecode.com</a></p>
<p>SPDeploy allows you to locally dev a solution using visual studio and deploy a automatically generated wsp remotely.</p>
| 31,280
|
<p>How do you pass "this" to the constructor for ObjectDataProvider in XAML.</p>
<p>Lets say my presenter class is:</p>
<pre><code>public class ApplicationPresenter(IView view){}
</code></pre>
<p>and that my UserControl implements IView.</p>
<p>What do I pass to the ConstructorParameters in the code below so that the UserControl can create the ApplicationPresenter using the default constructor? </p>
<pre><code><ObjectDataProvider x:Key="ApplicationPresenterDS"
ObjectType="{x:Type Fenix_Presenters:ApplicationPresenter}"
ConstructorParameters="{ ?? what goes here ??}" d:IsDataSource="True" />
</code></pre>
<p>I only need to do this so that I can use Blend 2. I know that I can do this in the code behind, but if I do I can't instantiate the class from within Blend. I also know that I can create a parameterless constructor for ApplicationPresenter and pass it a dummy class that implements IView, but I would rather do this in markup if at all possible.</p>
<p>My code behind at the moment is:</p>
<pre><code>public MyUserControl()
{
InitializeComponent();
DataContext = new ApplicationPresenter(this);
}
</code></pre>
|
<p>I'm just starting with Wpf and was under the misapprehension that I should be trying to do everything in XAML. I've just watched a few videos from <a href="http://windowsclient.net/" rel="nofollow noreferrer">WindowsClient.net</a> which are starting to clear some things up. But boy is this a complex technology!!!</p>
|
<p>i don't know if it works, but you could give your user control a name , e.g.</p>
<pre><code>x:Name="myUserCotrol"
</code></pre>
<p>and then use it in a binding:</p>
<pre><code>... ConstructorParameters="{Binding ElementName=myUserControl}" ...
</code></pre>
<p>this could work</p>
| 30,159
|
<p>I am trying to dynamically load the contents of a div tag with a .cfm page that contains a cfchart in png format. When the user clicks on a link, I am using the load function to put the .cfm page into the div.</p>
<pre><code>$("#bank").bind("click", function(){
$("#chartx").load("bank.cfm");
});
</code></pre>
<p>I can get this to come up perfectly in Firefox, but not in IE6. It gives no error messages.</p>
|
<p>Weirdest thing, but the cfdebug information in the classic style appended on the page is what causes it to break.</p>
|
<p>Have you tried jQuery.get? Maybe something like:</p>
<pre><code>$("#bank").bind("click", function(){
$.get("bank.cfm", function(data){
$("#chartx").html(data);
});
});
</code></pre>
<p>It's not as clean but it's more specific. Maybe it will take a different course from whatever is breaking.</p>
| 28,102
|
<p>I have the following xml I'd like to deserialize into a class</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<root>
<element1>String1</element1>
<element2>String2</element2>
</root>
</code></pre>
<p>I am trying to serialize it into the following class:</p>
<pre class="lang-csharp prettyprint-override"><code> [XmlRoot("root")]
public class root
{
[XmlElement("element1")]
internal string element1 { get; set; }
[XmlElement("element2")]
internal string element2 { get; set; }
}
</code></pre>
<p>When I try deserializing it using the following code, the config object is instantiated, but the strings are null.</p>
<pre class="lang-csharp prettyprint-override"><code> using (TextReader reader = new StreamReader(configFile))
{
XmlSerializer serializer = new XmlSerializer(typeof(root));
this.config = (root)serializer.Deserialize(reader);
}
</code></pre>
<p>I've tried using xsd.exe to create an xsd, and then create a class based off of that, but there is too much clutter generated by that tool. I think I'm close here. What am I missing?</p>
|
<p>You can't serialise/deserialise internal properties - They have to be public.</p>
|
<p>To follow up on my implementation... I ended up abandoning using the XmlSerializer class all together. The classes I was deserializing were pretty complex and contained lists of other objects that needed to be serialized. The amount of attributes I had to add to my classes made the <a href="http://en.wikipedia.org/wiki/Code_smell" rel="nofollow noreferrer">code stink</a></p>
<p>I ended up using Linq to XML to do the deserialization.... the complexity of the class delcarations went down, but the linq statement eneded up being rather complex.</p>
<p>If I were to do it again, I might have thought about using WCF and the datacontract serializer... That might have also been difficult to do also. </p>
<p>I'm curious how people are deserializing xml docs into objects these days. After getting my head around Linq statements, I think this might be the way to go. The objects are much simpler to create, and they don't need to be public. It also seems like the XmlSerializer is "old-school" while Linq to XML is more "new-school".</p>
<p>I'd love to hear what others had to say.</p>
| 34,043
|
<p>I recently took my Db initiating code out of the __construct of my Page class and placed it just after I initiate the Page class. I removed it from within the Page class because I want to be able to access it from anywhere (other classes for example). It also takes server, username, password and database arguments to it when initiated, and I don't wish to enter these every time.</p>
<p>Is there a way I can access it from under the Page class now? I've tried a few methods, even global (which I have been told is an awful way to do things) and so far no avail. I am still new to OO, but I am teaching myself as best as I can.</p>
<p>Should I make it a static class? Will this affect the lazy connector to the Db I have setup?</p>
<p>Any help would be much appreciated.</p>
<p>Thank you</p>
<p><strong>[EDIT]</strong></p>
<p>Similar Question: <a href="https://stackoverflow.com/questions/130878/global-or-singleton-for-database-connection">Global or Singleton for database connection?</a></p>
|
<p>A global of some sort (Be that global variables, singleton or some other variant) is an improvement over your previous approach, and as such you're on the right track. Generally speaking though, you should try to minimise the scope of program state (For a number of reasons, which I won't get into here). Having a global variable is in conflict with this principle. There are different solutions to this problem, but the most powerful and often overlooked approach, is to use inversion of control; Instead of obtaining a dependency, your class should receive it. For example, let's say you currently have this</p>
<pre><code>class EditUserController {
function saveUser() {
$db = Database::GetInstance();
$db->execute("update users set ...", ...);
}
}
</code></pre>
<p>You could change this into:</p>
<pre><code>class EditUserController {
function saveUser($db) {
$db->execute("update users set ...", ...);
}
}
</code></pre>
<p>Passing dependencies on the function-parameter level can be a bit unwieldy though, so a compromise could be to pass it on a per-object level:</p>
<pre><code>class EditUserController {
protected $db;
function __construct($db) {
$this->db = $db;
}
function saveUser() {
$this->db->execute("update users set ...", ...);
}
}
</code></pre>
<p>This is a fairly common pattern in OO programming. In addition to being more practical than passing in function parameters, it has the additional benefit of separating construction (Where shared dependencies are wired up to each other), from runtime (Where they are used). This makes a lot of things simpler.</p>
|
<p>Global variables do have a use, and this would be one of them. Unless it's likely that you're going to be needing multiple database connections, (or even still), then I don't see a problem with setting up a global $db object.</p>
<p>An alternative way is to have a static "Factory" class which you can use to get the object. In Joomla 1.5, the way you access the DB object is like this:</p>
<pre><code>$db =& JFactory::getDBO();
</code></pre>
<p>the getDBO function checks if the DB object has been created: if it has, return a reference to it, otherwise connect and initialise, and then return it.</p>
<p>This could equally apply to other "could-be-made-global" objects, like the current User object.</p>
| 49,343
|
<p>I was reading a post by Brad Wilson (<a href="http://bradwilson.typepad.com/blog/2008/08/partial-renderi.html" rel="nofollow noreferrer">http://bradwilson.typepad.com/blog/2008/08/partial-renderi.html</a>) on the new ViewEngine changes to MVC Preview 5 and thought that it would be great to be able to render a view to string for use in tests. I get the impression from the article that it may be possible to achieve this but cannot figure out how. </p>
<p>I believe this would enable us to do away with some of our WatIn tests (which are slow and unreliable) as it would allow us to check that the View has rendered correctly by simply checking the string for expected values/text.</p>
<p>Has anyone implemented something like this?</p>
|
<p>It's tricky. What you have to do is set the Response.Filter property to a custom stream class that you implement. The MVC Contrib project actually has examples of doing this. I'd poke around in there.</p>
|
<p>Moreover testing, it can be useful for components such as HTML to PDF converters.
These components usually uses 2 ways of transformation.</p>
<ul>
<li>Passing a URL to the conversion method</li>
<li>Passing a HTML content (and you can optionally specify the baseUrl to resolve virtual paths)</li>
</ul>
<p>I am using an Authorize filter inside the controller, so if I redirect to the URL the rendered HTML is the login page one (I use a custom authentication).</p>
<p>If I use Server.Execute(Url) to keep the context, the method fails (HttpUnhandledException: Error executing child request for /Template/Pdf/1.).</p>
<p>So I tried to retrieve the HTML of the rendered ViewResult but I didn't succeed.</p>
| 14,035
|
<p>Is there a method to get all of the .aspx files in my website? Maybe iterate through the site's file structure and add to an array?</p>
|
<pre><code>Directory.GetFiles(HttpContext.Current.Server.MapPath(@"/"), "*.aspx", SearchOption.AllDirectories);
</code></pre>
|
<p>using Directory.GetFiles("*.aspx"), you can get all the files in the directory. And you can make it recursive to grab any sub directories and their files.</p>
| 23,281
|
<p>How do I generate all the permutations of a list? For example:</p>
<pre><code>permutations([])
[]
permutations([1])
[1]
permutations([1, 2])
[1, 2]
[2, 1]
permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
</code></pre>
|
<p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.permutations" rel="noreferrer"><code>itertools.permutations</code></a> from the <strong>standard library</strong>:</p>
<pre><code>import itertools
list(itertools.permutations([1, 2, 3]))
</code></pre>
<hr />
<p>Adapted from <a href="http://code.activestate.com/recipes/252178/" rel="noreferrer">here</a> is a demonstration of how <code>itertools.permutations</code> might be implemented:</p>
<pre><code>def permutations(elements):
if len(elements) <= 1:
yield elements
return
for perm in permutations(elements[1:]):
for i in range(len(elements)):
# nb elements[0:1] works in both string and list contexts
yield perm[:i] + elements[0:1] + perm[i:]
</code></pre>
<p>A couple of alternative approaches are listed in the documentation of <code>itertools.permutations</code>. Here's one:</p>
<pre><code>def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
</code></pre>
<p>And another, based on <code>itertools.product</code>:</p>
<pre><code>def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
for indices in product(range(n), repeat=r):
if len(set(indices)) == r:
yield tuple(pool[i] for i in indices)
</code></pre>
|
<p>for Python we can use itertools and import both permutations and combinations to solve your problem</p>
<pre><code>from itertools import product, permutations
A = ([1,2,3])
print (list(permutations(sorted(A),2)))
</code></pre>
| 13,001
|
<p>I have been trying to parse Java exceptions that appear in a log for some code I'm working with. My question is, do you parse the exception trace from the top down, or the bottom up? It looks something like this:</p>
<pre><code>ERROR [main]</b> Nov/04 11:03:19,440 [localhost].[/BookmarksPortlet].[] - Exception sending context...
org.springframework.beans.factory.BeanCreationException: Error creating bean...: Cannot Resolve reference...: Error creating bean... nested exception... nested exception is org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.Oracle10gDialect
Caused by:
... [similar exceptions and nested exceptions]
...
at [start of stack trace]
</code></pre>
<p>Something like that. Obviously, I'm not looking for the answer to this specific exception, but how do you go about parsing an exception trace like this? Do you start at the top level error, or do you start at the inner most error (under the "caused by" clauses)?</p>
<p>The problem is more difficult for me because I'm not working with code I wrote. I'm editing the XML configurations, so I'm not really even looking the Java code. In my own code, I would recognize locations in the trace and would know what sort of things to look for. So how do you approach an exception like this in general?</p>
|
<p>This stuff is a little hard to explain, but my first step is nearly always starting from the top and skimming down until I see the familiar <code>com.mycompany.myproject</code>.</p>
<p>Given the line number attached to that you have a place to work from in your own code, which is often a good start.</p>
<p><strong>Edit:</strong> But, re-reading your question you say it's not your code.. so this may not be a useful answer at all..</p>
|
<p>In your example, it looks like you need to add some Oracle JDBC driver or something to your project's classpath. </p>
<p>But in the spirit of the question, I think it depends. In this example Spring isn't being very helpful on it's own - error creating bean. Gee, thanks for that information. However, it tells you exactly WHY there was an error creating a bean. The "inner most" exception. </p>
<p>I've seen other examples where the inner most exception will be too specific (like an NPE) while on the outside the exception that was actually thrown had the most useful error message. It varies from project to project.</p>
| 33,905
|
<p>Someone is trying to sell Lisp to me, as a super powerful language that can do everything ever, and then some.</p>
<p>Is there a <em>practical</em> code example of Lisp's power?<br/>(Preferably alongside equivalent logic coded in a regular language.)</p>
|
<p>I like macros.</p>
<p>Here's code to stuff away attributes for people from LDAP. I just happened to have that code lying around and fiigured it'd be useful for others.</p>
<p>Some people are confused over a supposed runtime penalty of macros, so I've added an attempt at clarifying things at the end.</p>
<h1>In The Beginning, There Was Duplication</h1>
<pre><code>(defun ldap-users ()
(let ((people (make-hash-table :test 'equal)))
(ldap:dosearch (ent (ldap:search *ldap* "(&(telephonenumber=*) (cn=*))"))
(let ((mail (car (ldap:attr-value ent 'mail)))
(uid (car (ldap:attr-value ent 'uid)))
(name (car (ldap:attr-value ent 'cn)))
(phonenumber (car (ldap:attr-value ent 'telephonenumber))))
(setf (gethash uid people)
(list mail name phonenumber))))
people))
</code></pre>
<p>You can think of a "let binding" as a local variable, that disappears outside the LET form. Notice the form of the bindings -- they are very similar, differing only in the attribute of the LDAP entity and the name ("local variable") to bind the value to. Useful, but a bit verbose and contains duplication.</p>
<h1>On the Quest for Beauty</h1>
<p>Now, wouldn't it be nice if we didn't have to have all that duplication? A common idiom is is WITH-... macros, that binds values based on an expression that you can grab the values from. Let's introduce our own macro that works like that, WITH-LDAP-ATTRS, and replace it in our original code.</p>
<pre><code>(defun ldap-users ()
(let ((people (make-hash-table :test 'equal))) ; equal so strings compare equal!
(ldap:dosearch (ent (ldap:search *ldap* "(&(telephonenumber=*) (cn=*))"))
(with-ldap-attrs (mail uid name phonenumber) ent
(setf (gethash uid people)
(list mail name phonenumber))))
people))
</code></pre>
<p>Did you see how a bunch of lines suddenly disappeared, and was replaced with just one single line? How to do this? Using macros, of course -- code that writes code! Macros in Lisp is a totally different animal than the ones you can find in C/C++ through the use of the pre-processor: here, you can run <em>real</em> Lisp code (not the <code>#define</code> fluff in cpp) that generates Lisp code, before the other code is compiled. Macros can use any real Lisp code, i.e., ordinary functions. Essentially no limits.</p>
<h1>Getting Rid of Ugly</h1>
<p>So, let's see how this was done. To replace one attribute, we define a function.</p>
<pre><code>(defun ldap-attr (entity attr)
`(,attr (car (ldap:attr-value ,entity ',attr))))
</code></pre>
<p>The backquote syntax looks a bit hairy, but what it does is easy. When you call LDAP-ATTRS, it'll spit out a list that contains the <em>value</em> of <code>attr</code> (that's the comma), followed by <code>car</code> ("first element in the list" (cons pair, actually), and there is in fact a function called <code>first</code> you can use, too), which receives the first value in the list returned by <code>ldap:attr-value</code>. Because this isn't code we want to run when we compile the code (getting the attribute values is what we want to do when we <em>run</em> the program), we don't add a comma before the call.</p>
<p>Anyway. Moving along, to the rest of the macro.</p>
<pre><code>(defmacro with-ldap-attrs (attrs ent &rest body)
`(let ,(loop for attr in attrs
collecting `,(ldap-attr ent attr))
,@body))
</code></pre>
<p>The <code>,@</code>-syntax is to put the contents of a list somewhere, instead of the actual list. </p>
<h1>Result</h1>
<p>You can easily verify that this will give you the right thing. Macros are often written this way: you start off with code you want to make simpler (the output), what you want to write instead (the input), and then you start molding the macro until your input gives the correct output. The function <code>macroexpand-1</code> will tell you if your macro is correct:</p>
<pre><code>(macroexpand-1 '(with-ldap-attrs (mail phonenumber) ent
(format t "~a with ~a" mail phonenumber)))
</code></pre>
<p>evaluates to</p>
<pre><code>(let ((mail (car (trivial-ldap:attr-value ent 'mail)))
(phonenumber (car (trivial-ldap:attr-value ent 'phonenumber))))
(format t "~a with ~a" mail phonenumber))
</code></pre>
<p>If you compare the LET-bindings of the expanded macro with the code in the beginning, you'll find that it is in the same form!</p>
<h1>Compile-time vs Runtime: Macros vs Functions</h1>
<p>A macro is code that is run at <em>compile-time</em>, with the added twist that they can call any <em>ordinary</em> function or macro as they please! It's not much more than a fancy filter, taking some arguments, applying some transformations and then feeding the compiler the resulting s-exps.</p>
<p>Basically, it lets you write your code in verbs that can be found in the problem domain, instead of low-level primitives from the language! As a silly example, consider the following (if <code>when</code> wasn't already a built-in)::</p>
<pre><code>(defmacro my-when (test &rest body)
`(if ,test
(progn ,@body)))
</code></pre>
<p><code>if</code> is a built-in primitive that will only let you execute <em>one</em> form in the branches, and if you want to have more than one, well, you need to use <code>progn</code>::</p>
<pre><code>;; one form
(if (numberp 1)
(print "yay, a number"))
;; two forms
(if (numberp 1)
(progn
(assert-world-is-sane t)
(print "phew!"))))
</code></pre>
<p>With our new friend, <code>my-when</code>, we could both a) use the more appropriate verb if we don't have a false branch, and b) add an implicit sequencing operator, i.e. <code>progn</code>::</p>
<pre><code>(my-when (numberp 1)
(assert-world-is-sane t)
(print "phew!"))
</code></pre>
<p>The compiled code will never contain <code>my-when</code>, though, because in the first pass, all macros are expanded so there is <em>no runtime penalty</em> involved!</p>
<pre><code>Lisp> (macroexpand-1 '(my-when (numberp 1)
(print "yay!")))
(if (numberp 1)
(progn (print "yay!")))
</code></pre>
<p>Note that <code>macroexpand-1</code> only does one level of expansions; it's possible (most likely, in fact!) that the expansion continues further down. However, eventually you'll hit the compiler-specific implementation details which are often not very interesting. But continuing expanding the result will eventually either get you more details, or just your input s-exp back.</p>
<p>Hope that clarifies things. Macros is a powerful tool, and one of the features in Lisp I like.</p>
|
<p>John Ousterhout made this interesting observation regarding Lisp in 1994:</p>
<blockquote>
<p>Language designers love to argue about why this language or that language
<strong>must</strong> be better or worse a priori, but none of these arguments really
matter a lot. Ultimately all language issues get settled when users vote
with their feet.</p>
<p><strong><em>If [a language] makes people more productive then they will use
it; when some other language comes along that is better (or if it is
here already), then people will switch to that language. This is The
Law, and it is good. The Law says to me that Scheme (or any other Lisp
dialect) is probably not the "right" language: too many people have
voted with their feet over the last 30 years.</em></strong></p>
</blockquote>
<p><a href="http://www.vanderburg.org/OldPages/Tcl/war/0009.html" rel="nofollow noreferrer">http://www.vanderburg.org/OldPages/Tcl/war/0009.html</a></p>
| 13,157
|
<p>I'm porting some <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow noreferrer">MATLAB</a> functions to <a href="https://en.wikipedia.org/wiki/Scilab" rel="nofollow noreferrer">Scilab</a>. The cool thing is that there is a <a href="http://ralyx.inria.fr/2004/Raweb/scilab/uid96.html" rel="nofollow noreferrer">conversion toolbox</a> that make things very easy.</p>
<p>The problem is I did not find the counterpart to the <strong>syms</strong> function, and the symbolic toolbox in general. (I'd like a port of the <em>Control System Toolbox</em> too, amd I'm still searching for some functions I'd may need).</p>
<p>The only thing about symbolic toolbox I've found is <a href="http://www.cert.fr/dcsd/idco/perso/Magni/s_sym/doc/index.html" rel="nofollow noreferrer">this</a>, but it was a little trcky and not so easy (actually I was not able to set up it correctly in 30 minutes, and I gave up for now. I'm going to try later), and it needs Maxima to be installed. Does anyone know anything about that?</p>
<p>Scilab is not exactly a must. The project aims to give a more <em>free</em> and <em>open source</em> alternative to MATLAB. I saw there is <a href="http://code.google.com/p/sympy/" rel="nofollow noreferrer">SymPy</a> for <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow noreferrer">Python</a>, and I just could use it with <a href="http://www.scipy.org/" rel="nofollow noreferrer">SciPy</a>, but I'd lost the <a href="http://ralyx.inria.fr/2004/Raweb/scilab/uid96.html" rel="nofollow noreferrer">conversion toolbox</a> thing :\</p>
<p>That said, what should be better? Get SciLab and Maxima work together or move to Python & co.? This is the start of the project, so the earlier I choose this, the better.</p>
|
<p>See <a href="http://vnoel.wordpress.com/2008/05/03/bye-matlab-hello-python-thanks-sage/" rel="nofollow noreferrer">Bye MATLAB, hello Python, thanks Sage</a> for a first-hand experience of migrating from <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow noreferrer">MATLAB</a> to Python.</p>
|
<p>Not to discourage your project, but if you just want a <em>free</em> and <em>open source</em> alternative to <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow noreferrer">MATLAB</a>, have you looked at the <a href="http://en.wikipedia.org/wiki/GNU_Octave" rel="nofollow noreferrer">Octave</a> project? Contributing there might be more productive than building your own MATLAB alternative.</p>
<p>If your project requires the functionality of MATLAB's Symbolic then take a look at</p>
<ul>
<li><a href="http://wiki.octave.org/wiki.pl?CategorySymbolic" rel="nofollow noreferrer">http://wiki.octave.org/wiki.pl?CategorySymbolic</a></li>
</ul>
<p>From my quick Google search I didn't find anything comparable to MATLAB's Simulink.</p>
<p>Also, Python and SciPy do have most of the functionality of MATLAB, and I guess Scilab's conversion utility would be useful in porting your own M-Files into Scilab code.</p>
<p>Your question seems to imply you want to port over MATLAB Toolboxes</p>
<blockquote>
<p>The only thing about symbolic toolbox I've found is this...</p>
</blockquote>
<p>I hope I am just misinterpreting you. If you are then there might be licensing issues if you were to distribute your system because the MATLAB Toolbox. Just a thought. But perhaps you wish to port your MATLAB code to, so that it doesn't not have the MATLAB dependency.</p>
<h3>Update</h3>
<p>For Control System functionality Octave, I just found that Octave does have a toolbox, see:</p>
<ul>
<li><a href="http://www.obihiro.ac.jp/~suzukim/masuda/octave/html/octave_125.html" rel="nofollow noreferrer">Octave Control Systems Toolbox</a></li>
</ul>
<p>Which has some of the functionality of Simulink, but it doesn't seem to have the graphical interface for building block diagrams.</p>
| 30,359
|
<p>I just came across <a href="https://stackoverflow.com/questions/139686/should-local-variable-initialisation-be-mandatory#283127">this question</a> about initializing local variables. Many of the answers debated simplicity/readability <em>vs.</em> robustness. As a developer of (remotely deployed) embedded systems, I always favor robustness and tend to follow several seemingly conflicting rules:</p>
<ul>
<li><p>Handle every error to the best of your ability in a way that allows the device to continue running.</p></li>
<li><p>Design the code to fail <em>as soon as possible</em> after a programming or fatal error occurs.</p></li>
</ul>
<p>We've all been trained to validate input to prevent the device from breaking as a result of user (or other external) input; always assume data may be invalid and test it accordingly.</p>
<p><strong>What other <em>specific</em> practices do you follow to ensure robustness?</strong> Examples are helpful, but I'm also interested in <em>techniques</em> that are universally applicable.</p>
|
<p>I'm a fan of the techniques described in "<a href="http://www.pragprog.com/the-pragmatic-programmer/extracts/tips" rel="nofollow noreferrer">The Pragmatic Programmer</a>". I also use <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="nofollow noreferrer">TDD</a>, rather than DBC as I find it more flexible and productive. For example some of the techniqes described in 'pragprog' include:</p>
<ul>
<li>Test often. Test early. Test automatically</li>
<li>Don't repeat yourself</li>
<li>Use saboteurs to test your testing</li>
<li>Use exceptions for exceptional problems</li>
<li>Don't live with broken windows</li>
<li>Don't use manual procedures</li>
</ul>
<p>They all seem like common sense, but its amazing how quickly teams deviate from these underpinning principles when faced with deadlines.</p>
|
<p>The systems I write (in C) have high requirements as to performance and reliability. Designing for fail is fine. When it comes to design for safe things become more complicated.</p>
<p>Hardware can always fail and apart from that you have the issue of invalid data entering the system from outside. My solutions in those areas will usually be elaborate (design for safe) and in practically all other areas design for fail by essentially having extremely simple code and no data validation at all.</p>
<p>So you could say that I design for fail when the risks are small and for safe when they are high.</p>
<p>For debugging I sometimes write conditional code which should never be entered which contains a divide by zero or some such so that when processing enters there the debugger will be invoked immediately.</p>
<p>I usually don't initialize local stack variables since the compiler tells me which need to be initialized and which can be omitted completely.</p>
<p>Code reviews are great but not fool-proof. I once spent several hours looking at a small (infinite) loop (embarassing, isn't it?) and couldn't see that the index wasn't incremented. My colleague didn't see it either. When I finally looked at the generated code listing I saw that the loop testing had been optimized to a single unconditional jump and only then did I understand what the problem was.</p>
| 35,877
|
<p>I've had some discussions recently at work about switching from Subversion to a DVCS like bazaar, and I would like to get other people's opinion.</p>
<p>I've managed to crystallize my reluctance to do so into a simple parallel.</p>
<blockquote>
<p>Version Control can be used well or badly. </p>
</blockquote>
<p>The 'light side' of version control is when you use it to keep track of your changes, are able to go back to older versions when you break stuff, and when you publish your changes so your peers can see your work-in-progress.</p>
<p>The 'dark side' of version control is when you don't use it properly so you don't 'checkpoint' your work by committing regularly, you keep a bunch of changes in your local checkout, and you don't share your changes with others as you make them.</p>
<p>Subversion makes both the light side and the dark side relatively hard. All the basics work, but few people really use branching in Subversion (beyond tagging and releasing) because merging is not straightforward at all. The support for it in Subversion itself is terrible, and there are scripts like svnmerge that make it better, but it's still not very good. So, these days, with good branching and merging support considered more and more like the necessity it is for collaborative development, Subversion doesn't match up.</p>
<p>On the other hand, the 'dark side' is pretty tough to follow too. You only need to be bitten once by not having your local changes commited once in a while to the online repository, and breaking your code with a simple edit you don't even remember making. So you end up making regular commits and people can see the work you're doing.</p>
<p>So, in the end Subversion ends up being a good middle-of-the-road VCS that, while a bit cumbersome for implementing the best practices, still makes it hard to get things very wrong.</p>
<p>In contrast, with a DVCS the cost of either going completely light side or dark side is a lot lower. Branching and merging is a lot simpler with these modern VCS systems. But the distributed aspect makes it easy to work in a set of local branches on your own machine, giving you the granular commits you need to checkpoint your work, possibly without ever publishing your changes so others can see, review, and collaborate. The friction of keeping your changes in your local branches and not publishing them is typically lower than publishing them in some branch on a publically available server.</p>
<p>So in a nutshell, here's the question: if I give our developers at work a DVCS, how can I make sure they use it to go to the 'light side', still publish their changes in a central location regularly, and make them understand that their one week local hack they didn't want to share yet might be just the thing some other developer could use to finish a feature while the first one is on holiday? </p>
<p>If both the light side and the dark side of DVCS are so easy to get to, how do I keep them away from the dark side?</p>
|
<p>If there are developers on your team that don't want to share their "one week local hack" then thats the problem, not the source control tool you are using. A better term for the "dark side" you are describing is "the wrong way" of coding for a team. Source control is a tool used to facilitate collaborative work. If your team is not clear about the fact that the goal is to share the work, then the best reason to use source control is not even applicable.</p>
<p>Also, I think you might be a little confused about distributed source control. There is no publishing to a central locations. Some branches are more important than others and there exists many many branches. Keeping that in mind, I think that distributed source control really works best for popular open source projects. I'm under the perception that centralized source control is still better for development withing a company or some other clearly defined entity.</p>
|
<p>I believe svn's merging has been somewhat overhauled in the latest release.</p>
| 4,670
|
<p>I am trying to write my first real python function that does something real. What i want to accomplish is searching a given folder, and then open all images and merging them together so they make a filmstrip image. Imagine 5 images stacked on top of eachother in one image.</p>
<p>I have this code now, which should be pretty much ok, but propably needs some modification:</p>
<pre><code>import os
import Image
def filmstripOfImages():
imgpath = '/path/here/'
files = glob.glob(imgpath + '*.jpg')
imgwidth = files[0].size[0]
imgheight = files[0].size[1]
totalheight = imgheight * len(files)
filename = 'filmstrip.jpg'
filmstrip_url = imgpath + filename
# Create the new image. The background doesn't have to be white
white = (255,255,255)
filmtripimage = Image.new('RGB',(imgwidth, totalheight),white)
row = 0
for file in files:
img = Image.open(file)
left = 0
right = left + imgwidth
upper = row*imgheight
lower = upper + imgheight
box = (left,upper,right,lower)
row += 1
filmstripimage.paste(img, box)
try:
filmstripimage.save(filename, 'jpg', quality=90, optimize=1)
except:
filmstripimage.save(miniature_filename, 'jpg', quality=90)")
</code></pre>
<p>How do i modify this so that it saves the new filmstrip.jpg in the same directory as I loaded the images from? And it probably has some things that are missing or wrong, anybody got a clue?</p>
<p>Related question: <a href="https://stackoverflow.com/questions/334827/how-to-generate-a-filmstrip-image-in-python-from-a-folder-of-images">How to generate a filmstrip image in python from a folder of images?</a></p>
|
<p>It is not an answer to your question, but It might be helpful:</p>
<pre><code>#!/usr/bin/env python
from PIL import Image
def makefilmstrip(images, mode='RGB', color='white'):
"""Return a combined (filmstripped, each on top of the other) image of the images.
"""
width = max(img.size[0] for img in images)
height = sum(img.size[1] for img in images)
image = Image.new(mode, (width, height), color)
left, upper = 0, 0
for img in images:
image.paste(img, (left, upper))
upper += img.size[1]
return image
if __name__=='__main__':
# Here's how it could be used:
from glob import glob
from optparse import OptionParser
# process command-line args
parser = OptionParser()
parser.add_option("-o", "--output", dest="file",
help="write combined image to OUTPUT")
options, filepatterns = parser.parse_args()
outfilename = options.file
filenames = []
for files in map(glob, filepatterns):
if files:
filenames += files
# construct image
images = map(Image.open, filenames)
img = makefilmstrip(images)
img.save(outfilename)
</code></pre>
<p>Example:</p>
<pre><code>$ python filmstrip.py -o output.jpg *.jpg
</code></pre>
|
<p>I think if you change your <code>try</code> section to this:</p>
<pre><code>filmstripimage.save(filmstrip_url, 'jpg', quality=90, optimize=1)
</code></pre>
| 43,579
|
<p>How can you determine the performance consequences of your PHP code if you are not familiar with the internals? Are there ways to figure out how your code is being executed (besides simply load testing it)? I am looking for things like memory usage, the execution time for algorithms.</p>
<p>Perhaps Joel would say, "learn C, then read the internals", but I really don't have time to learn C right now (though I'd love to, actually). </p>
|
<p>Use the <a href="http://www.xdebug.org/" rel="nofollow noreferrer">Xdebug</a> extension to profile PHP code.</p>
|
<p>Even if you are familiar with the internals, you should still load test your assumptions. I like to use the <a href="http://pear.php.net/package/Benchmark" rel="nofollow noreferrer">PEAR Benchmark</a> package to compare different code.</p>
<p>If you can isolate your code, you can keep your load testing simple. A typical technique is to run each option some number of times and see which one is faster. For example, if you have a class, you can write a test case and that puts it through it's paces and run it several times.</p>
| 7,385
|
<p>What is the difference between HTML <code><input type='button' /></code> and <code><input type='submit' /></code>?</p>
|
<p><code><input type="button" /></code> buttons will not submit a form - they don't do anything by default. They're generally used in conjunction with JavaScript as part of an AJAX application.</p>
<p><code><input type="submit"></code> buttons will submit the form they are in when the user clicks on them, unless you specify otherwise with JavaScript.</p>
<p>The first submit button of the form is also the one being clicked for <a href="https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#implicit-submission" rel="nofollow noreferrer">implicit submission</a>, f.e. by pressing enter in a text input.</p>
|
<p>IE 8 actually uses the first button it encounters submit or button. Instead of easily indicating which is desired by making it a input type=submit the order on the page is actually significant.</p>
| 36,985
|
<p>Is it possible to clone a virtual machine using VMware Fusion on Mac OS X? I'm trying the 30 day evaluation version but there doesn't appear to be a clone feature. I tried using the Finder to copy a VM's package structure but the copy didn't appear in the Virtual Machine Library.</p>
|
<p>Just use File->open to open the copy of the VM. It will probably ask you if you want to change the VM's unique ID. If you plan to run both the original and the clone at the same time, and it's not a Windows OS that needs activation, you should say yes. </p>
|
<p>I don't know fusion in detail, but in VMWare Server you can just copy the files somewhere else.</p>
| 13,415
|
<p>I've been wondering what exactly are the principles of how the two properties work. I know the second one is universal and basically doesn't deal with time zones, but can someone explain in detail how they work and which one should be used in what scenario?</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.datetime.utcnow.aspx" rel="noreferrer">DateTime.UtcNow</a> tells you the date and time as it would be in Coordinated Universal Time, which is also called the Greenwich Mean Time time zone - basically like it would be if you were in London England, but not during the summer. <a href="http://msdn.microsoft.com/en-us/library/system.datetime.now.aspx" rel="noreferrer">DateTime.Now</a> gives the date and time as it would appear to someone in your current locale. </p>
<p>I'd recommend using <code>DateTime.Now</code> whenever you're displaying a date to a human being - that way they're comfortable with the value they see - it's something that they can easily compare to what they see on their watch or clock. Use <code>DateTime.UtcNow</code> when you want to store dates or use them for later calculations that way (in a client-server model) your calculations don't become confused by clients in different time zones from your server or from each other.</p>
|
<p>When you need a local time for the machine your application runs at (like CEST for Europe), use Now. If you want a universal time - UtcNow. It's just matter of your preferences - probably making a local website / standalone application you'd want to use the time user has - so affected by his/her timezone setting - DateTime.Now.</p>
<p>Just remember, for a website it's the timezone setting of the server. So if you're displaying the time for the user, either get his prefered timezone and shift the time (just save Utc time to database then, and modify it) or specify it's UTC. If you forget to do so, user can see something like: <em>posted 3 minuses ago</em> and then a time in the future near it :)</p>
| 8,751
|
<p>I am starting again with c++ and was thinking about the scope of variables.
If I have a variable inside a function and then I return that variable will the variable not be "dead" when it's returned because the scope it was in has ended?</p>
<p>I have tried this with a function returning a string and it did work.
Can anyone explain this? Or at least point me to some place that can explain this to me please.</p>
<p>Thanks</p>
|
<blockquote>
<p>When the function terminates, the
following steps happen:</p>
<ul>
<li><p>The function’s return value is
copied into the placeholder that was
put on the stack for this purpose.</p></li>
<li><p>Everything after the stack frame
pointer is popped off. This destroys
all local variables and arguments.</p></li>
<li><p>The return value is popped off the
stack and is assigned as the value
of the function. If the value of the
function isn’t assigned to anything,
no assignment takes place, and the
value is lost.</p></li>
<li><p>The address of the next instruction
to execute is popped off the stack,
and the CPU resumes execution at
that instruction.</p></li>
</ul>
</blockquote>
<p><a href="http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/" rel="noreferrer">The stack and the heap</a></p>
|
<p>The local variable is copied to the return value. Copy constructors are called for non-trivial classes.</p>
<p>If you return a pointer or reference to a local variable you will have trouble---just as your intuition suggested.</p>
| 34,687
|
<p>Has anyone here had any experience with running OpenBD or Railo in production? We have some legacy CF6.1 apps that need to be hosted somewhere and I'm wondering if OpenBD or Railo is stable enough for production use, won't require a great deal effort to migrate to, etc.</p>
|
<p>I'll chime in as the 'Adobe' guy and say that yes, both OpenBD and Railo are viable CFML engines. The main hurdles are around CFML compatibility. For the last decade Allaire/Macomedia/Adobe has been driving the CFML standard, but we've formed an open CFML Advisory board made up of various experts in the field to help drive the future of the language.</p>
<p>Today it seems that ColdFusion 7 is the foundational standard. From there the CFML standard seems to splinter between vendors. ColdFusion 8 added a number of exclusive features that haven't been added to the other engines and vice-versa with Railo and OpenBD. In the future, the CFML Advisory should solve this problem.</p>
<p>Using ColdFusion as the standard, I find the following two link to be the best places to understand the compatibility differences.</p>
<p><a href="http://en.wikipedia.org/wiki/BlueDragon#Compatibility" rel="noreferrer">OpenBD Compatibility</a></p>
<p><a href="http://www.railo-technologies.com/en/index.cfm?treeID=107" rel="noreferrer">Railo Compatability</a></p>
<p>Here is the url for the CFML Advisory group. They just started the site so there isn't too much info up there yet.</p>
<p><a href="http://www.opencfml.org" rel="noreferrer">OpenCFML.org</a></p>
|
<p>I think replacedirect.nl recently migrated their webshop to railo.</p>
| 48,618
|
<p>Let's say I have a model like this</p>
<pre><code>class Foo(db.Model):
id = db.StringProperty()
bar = db.StringProperty()
baz = db.StringProperty()
</code></pre>
<p>And I'm going a GqlQuery like this</p>
<pre><code>foos = db.GqlQuery("SELECT * FROM Foo")
</code></pre>
<p><strong>I want to take the results of the GqlQuery and turn into some sort of JSON string that I can manipulate from different languages.</strong></p>
<hr>
<p>Here's how I'm doing it now</p>
<ol>
<li><p>Add a method to the <strong>Foo</strong> class that converts it into a dictionary</p>
<pre><code>def toDict(self):
return {
'id': self.id,
'bar': self.bar,
'baz': self'baz
}
</code></pre></li>
<li><p>Loop through the GqlQuery results and manually add each Foo instance to a dictionary</p>
<pre><code>fooDict = {}
for foo in foos:
fooDict[foo.id] = foo.toDict()
return simplejson.dumps(fooDict)
</code></pre></li>
</ol>
<hr>
<p>My approach above works but it feels kind of gross.</p>
<p>Is there a cleaner, more "Pythonic" way to handle this?</p>
<p><strong>The end format doesn't have to be exactly what I've done above. It just has to be something that converts nicely to JSON so I can deal with it from Javascript/PHP/whatever.</strong></p>
|
<p>Take a look at <a href="http://code.google.com/p/googleappengine/source/browse/trunk/google/appengine/api/datastore.py" rel="nofollow noreferrer">google.appengine.api.datastore</a>. It's the lower level datastore API that google.appengine.ext.db builds on, and it returns Entity objects, which subclass dict. You can query it using GQL with <a href="http://code.google.com/p/googleappengine/source/browse/trunk/google/appengine/ext/gql/__init__.py" rel="nofollow noreferrer">google.appengine.ext.gql</a>, or (my personal preference) use the Query class, which avoids the need for you to construct text strings for the GQL parser to parse. The Query class in api.datastore behaves exactly like the one <a href="http://code.google.com/appengine/docs/datastore/queryclass.html" rel="nofollow noreferrer">documented here</a> (but returns the lower level Entity objects instead of Model instances).</p>
<p>As an example, your query above can be reformulated as "datastore.Query("Foo").all()".</p>
|
<p>You can use web2py on GAE and do:</p>
<pre><code>db.define_table('foo',SQLField('bar'),SQLField('baz'))
rows=db(db.foo.id>0).select()
### rows is a list, rows.response is a list of tuples
for row in rows: print dict(row)
</code></pre>
<p>Runs on Oracle, Postgresql, Mssql, mysql, etc... too.</p>
| 26,071
|
<p>What is the Ruby idiomatic way for retrieving a single character from a string as a one-character string? There is the <code>str[n]</code> method of course, but (as of Ruby 1.8) it returns a character code as a fixnum, not a string. How do you get to a single-character string?</p>
|
<p>In Ruby 1.9, it's easy. In Ruby 1.9, Strings are encoding-aware sequences of characters, so you can just index into it and you will get a single-character string out of it:</p>
<pre><code>'µsec'[0] => 'µ'
</code></pre>
<p>However, in Ruby 1.8, Strings are sequences of bytes and thus completely unaware of the encoding. If you index into a string and that string uses a multibyte encoding, you risk indexing right into the middle of a multibyte character (in this example, the 'µ' is encoded in UTF-8):</p>
<pre><code>'µsec'[0] # => 194
'µsec'[0].chr # => Garbage
'µsec'[0,1] # => Garbage
</code></pre>
<p>However, Regexps and some specialized string methods support at least a small subset of popular encodings, among them some Japanese encodings (e.g. Shift-JIS) and (in this example) UTF-8:</p>
<pre><code>'µsec'.split('')[0] # => 'µ'
'µsec'.split(//u)[0] # => 'µ'
</code></pre>
|
<pre><code>'abc'[1].chr # => "b"
</code></pre>
| 48,527
|
<p>I've just started developing a WPF application. This is not my first WPF app, but it will be the first that needs some polish. I know quite a bit about the "plumbing" of WPF such as binding, etc., but very little about how to polish it up. I don't need a snazzy UI. I just need something that looks like a native Windows app. For instance, if the app runs on XP, I want it to look like an XP app and pick up the user's UI theme. Same thing on Vista, etc.</p>
<p>How can I do this?</p>
|
<p>You should be able to put this into the application's OnLoad event to use the Vista theme, for example:</p>
<pre><code>Uri uri = new Uri("PresentationFramework.Aero;V3.0.0.0;31bf3856ad364e35;component\\themes/aero.normalcolor.xaml", UriKind.Relative);
Resources.MergedDictionaries.Add(Application.LoadComponent(uri) as ResourceDictionary);
</code></pre>
<p>or for the Windows XP theme:
themes/Royale.normalcolor.xaml</p>
|
<p>You should be able to put this into the application's OnLoad event to use the Vista theme, for example:</p>
<pre><code>Uri uri = new Uri("PresentationFramework.Aero;V3.0.0.0;31bf3856ad364e35;component\\themes/aero.normalcolor.xaml", UriKind.Relative);
Resources.MergedDictionaries.Add(Application.LoadComponent(uri) as ResourceDictionary);
</code></pre>
<p>or for the Windows XP theme:
themes/Royale.normalcolor.xaml</p>
| 49,814
|
<p>I wonder if <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.aspx" rel="nofollow noreferrer">MailMessage</a> class is protected from <a href="http://en.wikipedia.org/wiki/E-mail_injection" rel="nofollow noreferrer">e-mail injection</a>. For example, should I check values before passing them to its constructor:</p>
<pre><code>MailMessage message = new MailMessage(fromTextBox.Text, toTextBox.Text);
</code></pre>
|
<p>The <code>MailAddress</code> class checks its addresses against the full BNF grammar from RFC822. (See <code>MailBnfHelper</code>).</p>
<p>There is no risk of injection when using <code>MailMessage</code>s. (Except HTML injection in your own content)</p>
|
<p>There seems to be only a simple check in the MailAddress class which checks if the address contains an @.</p>
| 38,649
|
<p>I'm using tortoise svn in Windows.</p>
<p>How can I branch in SVN and have it branch my svn:external folders as well?</p>
|
<p>You should use <code>svn:externals</code> as <strong>external</strong> references from different repositories. So <code>svn:externals</code> should refer to components, modules, 3rd party tools, etc.</p>
<p>You should <strong>not</strong> use <code>svn:externals</code> to emulate a "symbolic link"-behaviour by using externals to point into the same repository.
You can solve such issues most of the time by modifying your build-structure, or use checkout-scripts and sparse checkout feature.</p>
<p>svn:externals have a lot of problems most of them are difficult to see, track and repair:
<a href="https://stackoverflow.com/questions/223355/i-cannot-commit-changes-after-merge-in-svn">see an example here</a></p>
<ul>
<li>commits cannot span over externals(no atomic commits)</li>
<li>branches will not branch their externals(as you pointed out)</li>
<li>tags will not "freeze" their externals so latter builds may result in different/broken builds</li>
<li>merging and reeintegrate merge will not work on externals</li>
</ul>
<p>If you use externals to point to other repositories, you will most of the time do not have these problems.</p>
|
<p>When you create a branch within Subversion you are simply creating a cheap copy of the trunk, branch, or tag that you are branching from. This cheap copy will contain all of the same files and properties as the trunk, branch, or tag that you branched from until you begin to modify the properties or files of the new branch. </p>
<p>However, you may be able to modify one of the 'commit' hooks to modify settings automatically once you commit your branch. <a href="http://svnbook.red-bean.com/en/1.1/ch05s02.html" rel="nofollow noreferrer"><a href="http://svnbook.red-bean.com/en/1.1/ch05s02.html" rel="nofollow noreferrer">http://svnbook.red-bean.com/en/1.1/ch05s02.html</a></a></p>
<p>Otherwise if you want your externals to be modified on the branch you will need to do so manually.</p>
| 30,431
|
<p>I'm experimenting with JavaFX making a small game. </p>
<p>I want to add sound.
How?</p>
<p>I tried <code>MediaPlayer</code> with <code>media</code> defined with relative <code>source</code> attribute like:</p>
<pre><code>attribute media = Media{
source: "{__FILE__}/sound/hormpipe.mp3"
}
attribute player = MediaPlayer{
autoPlay:true
media:media
}
</code></pre>
<p>It doesn't play.
I get </p>
<blockquote>
<p><code>FX Media Object caught Exception com.sun.media.jmc.MediaUnavailableException: Media unavailable: file: ... Sound.class/sound/hormpipe.mp3</code></p>
</blockquote>
|
<p>Just a guess, but is that file "hornpipe.mp3" and not "hormpipe.mp3" (with an m)?</p>
|
<p>Just a guess, but I think your <code>{__FILE__}</code> will expand to the name of your file. Try replacing it with <code>{__DIR__}</code>.</p>
| 29,887
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.