instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm looking to have a couple of plugins in a Flex project I'm working on. I know I can load a SWF using the SWFLoader, but I thought in Flex3 you can now have Runtime Shared Libraries or something. Does anyone have any good documentation on loading a plugin at runtime? Ideally I'd like to be able to load a plugin from a URL, then execute some code from within the plugin (e.g. add a control to the page).</p>
<p>You can use either Modules or RSL.</p> <p>RSLs have the advantage of getting cached by flash rather than the browser so they stick around longer.</p> <p>Modules are easier to create and use. I have used modules and had issues with modules failing to load (code needs to handle that case). I haven't tried RSLs yet.</p> <p>Here is some documentation on creating RSLs <a href="http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:Flex_3_RSLs" rel="nofollow noreferrer">http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:Flex_3_RSLs</a></p>
<p>Note that, currently, loaded RSLs must be compiled against the very same version of the Flex framework.. if you plan for a "binary" plugin system, probably you want to wait for the <a href="http://opensource.adobe.com/wiki/display/flexsdk/Marshall+Plan" rel="nofollow noreferrer">Marshall plan</a> feature to be implemented, in the next Flex version.</p>
11,991
<p>I am struggling with a creating a query. It is related to a large and complicated database but for the sake of this post I have boiled the problem down to something simpler.</p> <p>I have three tables X, Y, Z defined as</p> <pre><code>CREATE TABLE [dbo].[X]( [ID] [bigint] NOT NULL ) CREATE TABLE [dbo].[Y]( [ID] [nchar](10) NOT NULL ) CREATE TABLE [dbo].[Z]( [IDX] [bigint] NOT NULL, [IDY] [nchar](10) NOT NULL ) </code></pre> <p>They contain the following data</p> <pre><code>Table X Table Y Table Z ID ID IDX IDY -- -- --- --- 1 A 1 A 2 B 1 B 3 C 1 A </code></pre> <p>I want to create a query that produces the following result</p> <pre><code>Count IDX IDY ===== === === 2 1 A 1 1 B 0 1 C 0 2 A 0 2 B 0 2 C 0 3 A 0 3 B 0 3 C </code></pre> <p>My initial thought was</p> <pre><code>SELECT COUNT(*), X.ID, Y.ID FROM X CROSS JOIN Y FULL OUTER JOIN Z ON X.ID = Z.IDX AND Y.ID = Z.IDY GROUP BY X.ID, Y.ID </code></pre> <p>but this turns out to be on the wrong road.</p> <p>Any ideas?</p>
<pre><code>SELECT (SELECT COUNT(*) FROM Z WHERE IDX = X.ID AND IDY = Y.ID), X.ID, Y.ID FROM X,Y </code></pre> <p>That's your answer... why do you possibly want that query, no clue :)</p>
<pre><code>SELECT COUNT(z.idx) count, x.id idx, y.id idy FROM (x CROSS JOIN y) LEFT JOIN z ON z.idx = x.id AND z.idy = y.id GROUP BY x.id, y.id ORDER BY COUNT(z.idx) DESC, x.id, y.id </code></pre>
35,956
<p>I would like to know where can I find the code which eclipse uses to display the forms in the plugin.xml file. In particular I am looking for the form layout used in the extension tab in the plugin.xml</p>
<p>You should use the derived tables on your SQL. For example if you want to pick up the most recent row for an specific activity you're attempt to use:</p> <pre><code>select * from activities group by id_customer order by creation_date </code></pre> <p>but it doesn't work. Try instead:</p> <pre><code>SELECT * FROM ( select * from activities order by creation_date desc ) sorted_list GROUP BY id_customer </code></pre>
<p><code>ORDER BY foo DESC</code>?</p>
11,691
<p>I need to implement a queue using table. The business requirement is to have a single queue which will be accessed by 5-10 boxes to get the next job/jobs. There will not be more than 5000 jobs per day. Also, a batch of jobs should be "dequeued" at one time.</p> <p>Just wondering what are the problem areas and issues I might run into as I havent done it before. If anyone has faced this/done this before, can you please point me to a design/sample implementation or issues that need to be taken care of.</p> <p>Thanks</p>
<p>There are a lot of general purpose queuing or messaging services. Even if you want to implement your own system, you could try to have a look at a few others. The first thing that come to mind is JMS (<a href="http://java.sun.com/products/jms/" rel="nofollow noreferrer">Java Message Service</a>) with implementations like <a href="http://activemq.apache.org/" rel="nofollow noreferrer">Apache ActiveMQ</a>, <a href="http://openjms.sourceforge.net/" rel="nofollow noreferrer">OpenJMS</a> or <a href="http://www.jboss.org/jbossmessaging/" rel="nofollow noreferrer">JBoss Messaging</a>. Then you have a lot of non-opensource offering as well.</p> <p>Second thing that comes to mind is <a href="http://aws.amazon.com/sqs/" rel="nofollow noreferrer">Amazon Simple Queue Service</a>. There is a couple of products that implement the same kind of interface, like <a href="http://code.google.com/p/django-queue-service/" rel="nofollow noreferrer">django-queue-service</a>.</p> <p>Good luck !</p> <hr>
<p>Thanks Vegard.</p> <p>But the approach that you suggested will result in loss of job requests in case the system which took job fails/crashes.</p> <p>I was thinking of a Queue table with following columns</p> <ul> <li>RequestID/MessageID (Primary Key)</li> <li>LockedBy (who is working on the request)</li> <li>LockedTime (when request is locked for processing)</li> <li>RequestedTime (when request gets added to queue)</li> <li>CompletionTime (when is request completed)</li> <li>Status (Pending/Processed) </li> <li>RequestMessage (serialized java object in my case)</li> <li>Requestor (who enqueued the request)</li> </ul> <p>I can write a stored procedure <code>[GetNextItemsInQueue]</code> which returns a list of lets say 10 requests, sets the Locked By and Locked Time. If Locked Time increases a specified limit, the record can be put back to Pending state.</p> <p>Any problems with this one?</p>
35,476
<p>How do you escape the forward slash character (<code>/</code>) in VBScript? For example, in the following string:</p> <pre><code>bob = "VU administration/front desk" </code></pre>
<p>You don't escape it: it doesn't mean anything special in php or vbscript, and therefore doesn't need to be escaped. The only character you need to escape in vbscript is the double quote, which escapes itself:</p> <pre><code>MyString = "He said, ""Here's how you escape a double quote in vbscript. Slash characters -- both forward (/) and back (\) -- don't mean anything, even when used with common control characters like \n or \t.""" </code></pre> <p>Similarly, in php a <em>backslash</em> escapes itself, but a forward slash doesn't need any special handling.</p>
<p>This is so wrong I have to comment on it. The question is about VBScript, not PHP, so who cares what PHP does with a slash? In VB, the forward slash <strong>/</strong> does have special meaning. The character <strong>/</strong> represents <strong>DOUBLE</strong>. If your code editor displays this character as <strong>DOUBLE</strong> or you get an error about converting to <strong>DOUBLE</strong> when you don't mean to convert to <strong>DOUBLE</strong> then you probably need to fix something in your string. </p> <p>For instance, VB treats the forward slash <strong>/</strong> in this query string as <strong>DOUBLE</strong> and the program would fail here because you cant convert select <em>replace(convert(char(10),pih.updateon,111),</em> from text to double. </p> <pre><code>Dim sQuery As String = "select replace(convert(char(10),pih.updateon,111),"/","-") as stopdate from myTable" </code></pre> <p>The problem however will not likely be an issue with escaping a slash. Chances are you goofed somewhere else. In this case, if you typed the string correctly, it would look like this:</p> <pre><code>Dim sQuery As String = "select replace(convert(char(10),pih.updateon,111),'/','-') as stopdate from myTable" </code></pre> <p>Hope that example helps understand where you might be going wrong if you are having issues with slashes. </p> <p>Addendum: In VBScript and VB, the chief difference being VB is compiled and VBScript is interpreted, the syntax in this case is handled the same way. </p> <p>d-bo</p>
45,713
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p>
<p>The following code should do the job, it is cross-platform and runs on Python 2.4-3.2. I tested it on Windows, OS X and Linux.</p> <pre><code>from tendo import singleton me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running </code></pre> <p>The latest code version is available <a href="https://github.com/pycontribs/tendo/blob/master/tendo/singleton.py" rel="noreferrer">singleton.py</a>. Please <a href="https://github.com/pycontribs/tendo/issues" rel="noreferrer">file bugs here</a>.</p> <p>You can install tend using one of the following methods:</p> <ul> <li><code>easy_install tendo</code></li> <li><code>pip install tendo</code></li> <li>manually by getting it from <a href="http://pypi.python.org/pypi/tendo" rel="noreferrer">http://pypi.python.org/pypi/tendo</a></li> </ul>
<pre><code>import sys,os # start program try: # (1) os.unlink('lock') # (2) fd=os.open("lock", os.O_CREAT|os.O_EXCL) # (3) except: try: fd=os.open("lock", os.O_CREAT|os.O_EXCL) # (4) except: print "Another Program running !.." # (5) sys.exit() # your program ... # ... # exit program try: os.close(fd) # (6) except: pass try: os.unlink('lock') except: pass sys.exit() </code></pre>
49,911
<p>If it's harder to explain using words, let's look at an example I have a generic function like this</p> <pre><code>void FunctionA&lt;T&gt;() where T : Form, new() { } </code></pre> <p>If I have a reflected type, how do I use it with the above function? I'm looking forward to do this</p> <pre><code>Type a = Type.GetType("System.Windows.Forms.Form"); FunctionA&lt;a&gt;(); </code></pre> <p>Of cause the above method doesn't work.</p>
<p><s>You can't. Generics in .NET must be resolved at compile time. You're trying to do something that would resolve them at runtime. </p> <p>The only thing you can do is to provide an overload for FunctionA that takes a type object.</s></p> <hr> <p>Hmmm... the commenter is right.</p> <pre><code>class Program { static void Main(string[] args) { var t = typeof(Foo); var m = t.GetMethod("Bar"); var hurr = m.MakeGenericMethod(typeof(string)); var foo = new Foo(); hurr.Invoke(foo, new string[]{"lol"}); Console.ReadLine(); } } public class Foo { public void Bar&lt;T&gt;(T instance) { Console.WriteLine("called " + instance); } } </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx" rel="nofollow noreferrer">MakeGenericMethod</a>.</p>
<p>I solved this problem in a different way. I have a list class that encapsulates the (real) Dapper functionality. It inherits from a base class that is the dummy class for mocking. Every method in the base class is overridden by the real class. Then I don't need to do anything special. If in the future, I want to do something special with <code>SQLite</code> or a home-grown in-memory database, I can always add that to the base class later if I wish.</p>
38,861
<p>What are my options for programmatically accessing a Microsoft Project file? What are the pros and cons of each approach?</p> <p>I will basically need to import all data from the file into another data structure. Using the Office Interop assembies is low on the preference scale. </p>
<p>Here are the options:</p> <ol> <li>Interop (messy and horribly slow for large projects)</li> <li>Save project in XML and work with it (messy)</li> <li>Save project in the database (that's not publishing and it is available for project 2003 only - see ODBC option while saving). I've seen it being used a lot in the integration scenarios</li> <li><a href="http://www.highlydeveloped.net/" rel="nofollow noreferrer">Projette</a> (commercial, $10 per license)</li> <li><a href="http://www.ilog.com/products/ganttnet/projectviewer/" rel="nofollow noreferrer">ILog Project Viewer</a> (also commercial)</li> </ol>
<p>Sourcefourge.net offers a component in Java which can be integrated with .net applications to read MPP files upto MPP 2007 the link is <a href="http://mpxj.sourceforge.net/getting-started.html" rel="nofollow">http://mpxj.sourceforge.net/getting-started.html</a></p>
18,545
<p>It there any article/book that defines upper bounded design limits for WS timeouts? Do you timeout at the server or recommend the client specific timeouts too?</p> <p>Is there a common best practice like "never design WS that can take longer than 60 seconds, use an asynchronous token pattern"</p> <p>I am interested in knowing what you do or your opinion too. </p>
<p>This question, and the ones linked to in answers to it, might help: <a href="https://stackoverflow.com/questions/184814/is-there-some-industry-standard-for-unacceptable-webapp-response-time">Is there some industry standard for unacceptable webapp response time?</a></p> <p>Somewhat tangential to your question (no time intervals, sorry), but I suspect useful for your work: A common approach to timeouts is to balance them with "back-off" timers.<br> It goes something like this: The first time a service times out, don't worry about it. The second time in a row a service times out, don't bother calling it for N seconds. The third time in a row a service times out, don't call it for N+1 seconds. Then N+2, N+3, N+5, N+8, etc, until you reach some maximum limit M.</p> <p>The timeout counter is reset when you get a valid response.</p> <p>I am using a Fibbonacci sequence to increase the "back-off" time period here, but of course you can use any other suitable function -- the point being, if the service you are trying keeps timing you, you "belief" in it get smaller and smaller, so you spend fewer resources trying to get to it, and knock on the door more rarely. This might help the service on the other end, which could simply be overloaded and re-requesting just makes matters worse, and it will increase your response time since you won't be waiting around for a service that is unlikely to answer. </p>
<p>Take the amount of data you are transfering via your web service an see how long the process takes. </p> <p>Add 60 secs to that number and test. </p> <p>If you can get it to timeout on a good connection then add 30 more seconds.</p> <p>rinse and repeat.</p>
33,385
<p>We have a Java Applet built using AWT. This applet lets you select pictures from your hard drive and upload them to a server. The applet includes a scrollable list of pictures, which works fine in Windows, Linux and Mac OS X 10.5. We launch this applet via Java Web Start or within a web page. </p> <p>Our applet does not behave properly in Mac OS X 10.4, regardless of the version of Java (1.4 or 1.5). You can find a screenshot of the incorrect behaviour, when scrolling, here:</p> <p><a href="http://www.lavablast.com/tmp/ui_error.png" rel="nofollow noreferrer">http://www.lavablast.com/tmp/ui_error.png</a></p> <p>Simply put, sometimes when scrolling the pictures end up overlapping the header or footer of the application. This behaviour does not occur on other platforms. On Mac OS X 10.4, it shows the pictures in the incorrect location when scrolling, which would not be so bad if it refreshed the screen after painting the image at that location. However, it does not appear that the application knows it painted it incorrectly and thus does not refresh.</p> <p>If the window is minimized, resized or even moved, the application is refreshed and the incorrectly positioned elements vanish and the application resumes normally. I spent quite some time trying to force a refresh of the background image unsuccessfully. (the repaint the image directly, repaint all children of a few panels, etc. ) Thus, I am looking for any tips that would help me resolve this problem under Mac OS X 10.4 or, in the worst case, simply simulate a full applet refresh. </p> <p>Until recently, everything was compatible with Java 1.1 but this has changed in a few locations which now require 1.4. I don't feel these changes created the issue, I am just providing this as extra information. If you are interested in implementation details of the scroll panel, I will investigate, but I am assuming this is a common platform bug for which workarounds must be known.</p> <p>To replicate the problem, open the following Java Web Start application: <a href="http://www.lavablast.com/tmp/opal-webstart.php.jnlp" rel="nofollow noreferrer">http://www.lavablast.com/tmp/opal-webstart.php.jnlp</a></p> <p>Select a folder containing lots of images and play with the scrollbar. At some point (fairly quickly), you should get the refresh problem. </p> <p>Edit: I followed the first suggestion here and replaced all my controls that feature background images with a Swing equivalent and the issue is still there. (Plus, there are numerous other fixes I would need to do to do a complete change). Any other ideas? A simple one line of code that forces a full refresh would be great :)</p> <p>Edit2: The main thread creates the panels and launches X threads. Using an observer/notifier pattern, the threads complete and notify the main control, which adds a panel to the page. This is done via an EventQueue.invokeLater which, unless I am mistaken, should run on the right thread. The issue is at its most severe when scrolling even if no extra threads are running (as during the loading). </p>
<p>Assuming :</p> <ul> <li>you are using the Microsoft client (<code>System.Data.OracleClient</code>).</li> <li>you have a proper <code>OracleConnection</code> instance (<code>connection</code>).</li> <li>you have an <code>OracleCommand</code> ready (<code>command</code>, based on <code>SELECT my_blob FROM my_table WHERE id=xx</code>).</li> </ul> <p>This should go like this :</p> <pre><code>using (OracleDataReader odr=command.ExecuteReader()) { reader.Read(); if (!dr.IsDBNull(0)) using (Stream s=(Stream)dr.GetOracleValue(0)) using (Image image=Image.FromStream(s)) return Copy(image); } </code></pre> <p>where Copy is </p> <pre><code>public static Image Copy(Image original) { Image ret=new Bitmap(original.Width, original.Height); using (Graphics g=Graphics.FromImage(ret)) { g.DrawImageUnscaled(original, 0, 0); g.Save(); } return ret; } </code></pre> <p>See <a href="http://macinsoft.blogspot.com/2009/09/beware-image-object.html" rel="nofollow noreferrer">my blog post</a> and/or <a href="http://support.microsoft.com/?id=814675" rel="nofollow noreferrer">KB 814675</a> for why a Copy is necessary.</p>
<p>I know this uses sql but it should be similar for your needs</p> <pre><code>Dim cn As SqlConnection = Nothing Dim cmd As SqlCommand = Nothing Dim da As SqlDataAdapter = Nothing Dim ms As MemoryStream = Nothing Dim dsImage As Data.DataSet = Nothing Dim myBytes() As Byte = Nothing Dim imgJPG As System.Drawing.Image = Nothing Dim msOut As MemoryStream = Nothing Try cn = New SqlConnection(ConnectionStrings("conImageDB").ToString) cmd = New SqlCommand(AppSettings("sprocGetImage").ToString, cn) cmd.CommandType = Data.CommandType.StoredProcedure cmd.Parameters.AddWithValue("@dmhiRowno", irowno) da = New SqlDataAdapter(cmd) dsImage = New Data.DataSet da.Fill(dsImage, "image") If dsImage.Tables(0).Rows.Count = 0 Then Throw New Exception("No results returned for rowno") End If myBytes = dsImage.Tables(0).Rows(0)("Frontimage") ms = New MemoryStream ms.Write(myBytes, 0, myBytes.Length) imgJPG = System.Drawing.Image.FromStream(ms) 'Export to JPG Stream msOut = New MemoryStream imgJPG.Save(msOut, System.Drawing.Imaging.ImageFormat.Jpeg) imgJPG.Dispose() imgJPG = Nothing ms.Close() sFrontImage = Convert.ToBase64String(msOut.ToArray()) dsImage = New Data.DataSet da.Fill(dsImage, "image") myBytes = dsImage.Tables(0).Rows(0)("Backimage") ms = New MemoryStream ms.Write(myBytes, 0, myBytes.Length) imgJPG = System.Drawing.Image.FromStream(ms) sBackImage = Convert.ToBase64String(ms.ToArray) Catch ex As System.IO.IOException ' : An I/O error occurs. Throw ex Catch ex As System.ArgumentNullException ': buffer is null. Throw ex Catch ex As System.NotSupportedException ': The stream does not support writing. For additional information see System.IO.Stream.CanWrite.-or- The current position is closer than count bytes to the end of the stream, and the capacity cannot be modified. Throw ex Catch ex As System.ArgumentOutOfRangeException ': offset or count are negative. Throw ex Catch ex As System.ObjectDisposedException ' : The current stream instance is closed. Throw ex Catch ex As System.ArgumentException Throw ex Catch ex As System.Runtime.InteropServices.ExternalException ': The image was saved with the wrong image format Throw ex Catch ex As Exception Throw ex Finally If cn IsNot Nothing Then cn.Close() cn.Dispose() cn = Nothing End If If cmd IsNot Nothing Then cmd.Dispose() cmd = Nothing End If If da IsNot Nothing Then da.Dispose() da = Nothing End If If ms IsNot Nothing Then ms.Dispose() ms = Nothing End If If msOut IsNot Nothing Then msOut.Close() msOut.Dispose() msOut = Nothing End If If dsImage IsNot Nothing Then dsImage.Dispose() dsImage = Nothing End If If myBytes IsNot Nothing Then myBytes = Nothing End If If imgJPG IsNot Nothing Then imgJPG.Dispose() imgJPG = Nothing End If End Try </code></pre> <p>This code pulls back a tiff wrapped jpeg for the front image so the code is a bit different than for the back image.</p>
22,307
<p>I have found that skin files only work if they are placed at the root theme folder in the App_Themes folder.</p> <p>For example, if you have 2 themes in the App_Themes folder, you cannot add another sub folder to the theme folder and place a seperate skin file in that subfolder. </p> <p>It's not much of a limitation, but it would give you more flexibility to further customize an app.</p> <p>Can anyone shed light on why this behavior occurs as it does in 2.0?</p>
<p>Has your skin file should have the extension .skin? I always call them theme.skin and give them the same name as the folder. Eg in Theme col2, the folder is </p> <p>App_Themes\col2 and contains the css and col2.skin</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms247256(VS.80).aspx" rel="nofollow noreferrer">Microsoft</a> is your best reference:</p>
<p>The only way to change this behavior is via a <strong>VirtualPathProvider</strong> - something along the lines of: <a href="http://www.neovolve.com/page/ASPNet-Virtual-Theme-Provider-10.aspx" rel="nofollow noreferrer">http://www.neovolve.com/page/ASPNet-Virtual-Theme-Provider-10.aspx</a></p>
9,303
<p>We're in the process of redesigning the customer-facing section of our site in .NET 3.5. It's been going well so far, we're using the same workflow and stored procedures, for the most part, the biggest changes are the UI, the ORM (from dictionaries to LINQ), and obviously the language. Most of the pages to this point have been trivial, but now we're working on the heaviest workflow pages.</p> <p>The main page of our offer acceptance section is 1500 lines, about 90% of that is ASP, with probably another 1000 lines in function calls to includes. I think the 1500 lines is a bit deceiving too since we're working with gems like this</p> <pre><code>function GetDealText(sUSCurASCII, sUSCurName, sTemplateOptionID, sSellerCompany, sOfferAmount, sSellerPremPercent, sTotalOfferToSeller, sSellerPremium, sMode, sSellerCurASCII, sSellerCurName, sTotalOfferToSeller_SellerCurr, sOfferAmount_SellerCurr, sSellerPremium_SellerCurr, sConditions, sListID, sDescription, sSKU, sInv_tag, sFasc_loc, sSerialNoandModel, sQTY, iLoopCount, iBidCount, sHTMLConditions, sBidStatus, sBidID, byRef bAlreadyAccepted, sFasc_Address1, sFasc_City, sFasc_State_id, sFasc_Country_id, sFasc_Company_name, sListingCustID, sAskPrice_SellerCurr, sMinPrice_SellerCurr, sListingCur, sOrigLocation) </code></pre> <p>The standard practice I've been using so far is to spend maybe an hour or so reading over the app both to familiarize myself with it, but also to strip out commented-out/deprecated code. Then to work in a depth-first fashion. I'll start at the top and copy a segment of code in the <code>aspx.cs</code> file and start rewriting, making obvious refactorings as I go especially to take advantage of our ORM. If I get a function call that we don't have, I'll write out the definition.</p> <p>After I have everything coded I'll do a few passes at refactoring/testing. I'm just wondering if anyone has any tips on how to make this process a little easier/more efficient.</p>
<p>Believe me, I know <em>exactly</em> where you are coming from.. I am currently migrating a large app from ASP classic to .NET.. And I am still learning ASP.NET! :S (yes, I am terrified!).</p> <p>The main things I have kept in my mind is this:</p> <ul> <li>I dont stray <em>too</em> far from the current design (i.e. no massive "lets rip ALL of this out and make it ASP.NET magical!) due to the incredibly high amount of coupling that ASP classic tends to have, this would be very dangerous. Of course, if you are confident, fill your boots :) This can always be refactored later.</li> <li>Back everything up with tests, tests and more tests! I am really trying hard to get into TDD, but its very difficult to test existing apps, so every time I remove a chunk of classic and replace with .NET, I ensure I have as much green-light tests backing me as possible.</li> <li>Research a lot, there are some MAJOR changes between classic and .NET and sometimes what can be many lines of code and includes in classic can be achieved in a few lines of code, <em>think</em> before coding.. I've learnt this the hard way, several times :D</li> </ul> <p>Its very much like playing <a href="http://www.amazon.co.uk/Hasbro-14569186-Jenga/dp/B00004XQW9" rel="nofollow noreferrer">Jenga</a> with your code :)</p> <p>Best of luck with the project, any more questions, then please ask :)</p>
<p>Sounds like you have a pretty good handle on things. I've seen a lot of people try to do a straight-line transliteration, includes and all, and it just doesn't work. You need to have a good understanding of how ASP.Net wants to work, because it's <em>much</em> different from Classic ASP, and it sounds like maybe you have that. </p> <p>For larger files, I'd try to get a higher level view first. For example, one thing I've noticed is that Classic ASP was horrible about function calls. You'd be reading through some code and find a call to a function with no clue as to where it might be implemented. As a result, Classic ASP code tended to have long functions and scripts to avoid those nasty jumps. I remember seeing a function that printed out to 40 pages! Parsing straight through that much code is no fun. </p> <p>ASP.Net makes it easier to follow function calls around, so you might start by breaking out your larger code blocks into several smaller functions.</p>
5,109
<p>I have a client who is in need of a file based encryption / decryption application to be used between Linux / Windows 2003 Server. The goal is to have a single file compressed nightly on a linux platform and secured using a script, transmitted over FTP, decrypted on the Windows 2003 server and available for other import routines such as SSIS, etc. </p> <p>The file can remain unencrypted on each end after transport, the desire is mainly to keep the file secure during transport. Firewall rules and the fact that IIS6 doesn't support SFTP eliminate SFTP as an option. Simplicity is the primary focus here, so complex security options or heavyweight libraries cannot be used.</p>
<p>You could try <a href="http://gnupg.org/" rel="noreferrer">GnuPG</a>, it's cross platform and since you are only sending files internally you don't really need a certificate signed by a big-name certificate authority.</p>
<p>Try R10Cipher. Cross Platform, 384 Bit, Handles Text and Files, <em>Very</em> Simple to use and inexpensive <a href="http://www.r10cipher.com" rel="nofollow noreferrer">http://www.r10cipher.com</a></p> <p>Disclaimer: It's produced by my company, Arten Science.</p>
24,307
<p>What I currently do is I link the project to another location and give it the same name, then check the box where it says "Branch after share." And then I would Check out the shared project and work off it. And finally merge with the original project.</p> <p>This works okay, but it feels very clunky: I have multiple instances of the project on my drive; I have to change physical address of the website (i use asp.net 1.1) every time I work on a different branch; </p> <p>That doesn't feel like the right way to do it. How do you branch your projects with VSS?</p>
<p>I think the way you describe in the question is the only way you can do it in sourceSafe.</p> <p>I usually name the copied directory "V1.0" (or whatever is appropriate) and keep them all in a folder that is the main project name.</p>
<p>The way you described is the only supported way to do "branching". And as you pointed out it is rather clunky. In VSS it's best to avoid branching alltogether as it will destroy your source history.</p>
9,369
<p>I am in the process of designing a daily build routine for my project. We are using Flex 3 and SQL Server 2005. I am unsure to what degree I should be rebuilding the database on a daily build. Should I be dropping all tables and stored procedures and adding them back in? Then I would have to have a script that put all the default data back into the tables.</p> <p>Or should I have the DBA write Alter scripts that only run when changes are made and concentrate on building the code on a daily basis?</p>
<p>This really depends on your current stage of project development. </p> <p>While in active development without any production deployments the simple thing to do is just drop and re-create your database every time. This way your code and database should be in sync, especially if you are doing unit testing. This is basically doing a trunk build i.e. latest and greatest. It is much simpler to maintain. Scripting your default data is easy and a great way to have a clean setup when you need one. Check out the <a href="http://vyaskn.tripod.com/code.htm" rel="nofollow noreferrer"><code>sp_ generate_inserts</code></a> stored procedure for a nice utility to script the data from an existing database.</p> <p>Once you have production databases and will be altering you database with code releases, it's important to test change scripts also. Change scripts tend to be a bit tougher to write due to dependencies and data manipulation considerations.</p>
<p>Drop and recreate them. With alter there's always a possibility to forget an intermediate change.</p>
34,882
<p>I was wondering in C++ if I have an enum can I access the value at the second index? For example I have</p> <pre><code>enum Test{hi, bye}; </code></pre> <p>if I want 'hi', can I do something like Test[0], thanks.</p>
<p>Yes and no. If your Enum does not have explicit values then it is possible. Without an explicit values, enum values are given numeric values 0-N in order of declaration. For example ...</p> <pre><code>enum Test { hi, // 0 bye // 1 } </code></pre> <p>This means that indexes just translates into a literal value.</p> <pre><code>Test EnumOfIndex(int i) { return static_cast&lt;Test&gt;(i); } </code></pre> <p>This of course does 0 validation at runtime and as soon as you add an explicit value it will break down. But it will work in the default scenario. </p>
<p>Your best option might be something like this:</p> <pre><code>enum Test{hi = 0, bye}; </code></pre> <p>Then you can simply refer to 'hi' with the number 0, and 'bye' with 1.</p> <p>Although this really defeats the whole purpose of using an enumeration in the first place.</p>
41,654
<p>I have two computers. Both running WinXP SP2 (I don't really know ho similar they are beyond that). I am running MS Visual C# 2008 express edition on both and that's what I'm currently using to program.</p> <p>I made an application that loads in an XML file and displays the contents in a DataGridView.</p> <p>The first line of my xml file is:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; </code></pre> <p>...and really... it's utf-8 (at least according to MS VS C# when I just open the file there).</p> <p>I compile the code and run it on one computer, and the contents of my DataGridView appears normal. No funny characters. I compile the code and run it on the other computer (or just take the published version from computer #1 and install it on computer #2 - I tried this both ways) and in the datagridview, where there are line breaks/new lines in the xml file, I see funny square characters.</p> <p>I'm a novice to encoding... so the only thing I really tried to troubleshoot was to use that same program to write the contents of my xml to a new xml file (but I'm actually writing it to a text file, with the xml tags in it) since the default writing to a text file seems to be utf-8. Then I read this new file back in to my program. I get the same results.</p> <p>I don't know what else to do or how to troubleshoot this or what I might fundamentally be doing wrong in the first place.</p> <p>-Adeena</p>
<p>This doesn't have to do with UTF-8 or character encodings - this problem has to do with <a href="http://en.wikipedia.org/wiki/Line_ending" rel="nofollow noreferrer">line endings</a>. In Windows, each line of a text file ends in the two characters carriage-return (CR) and newline (LF, for line feed), which are code points U+000D and U+000A respectively. In ASCII and UTF-8, these are encoded as the two bytes <code>0D 0A</code>. Most non-Windows systems, including Linux and Mac OS X, on the other hand, uses just a newline character to signal end-of-line, so it's not uncommon to see line ending problems when transferring text files between Windows and non-Windows systems.</p> <p>However, since you're using just Windows on both systems, this is more of a mystery. One application is correctly interpreting the CRLF combination as a newline, but the other application is confused by the CR. Carriage returns are not printable characters, so it replaces the CR with a placeholder box, which is what you see; it then correctly interprets the line feed as the end-of-line.</p>
<p>@ Adam: Sorry! Missed your earlier statement. </p> <p>To load the document into the program and display in the DataGridView, I am currently doing (I say "currently", because I tried other things like use XDocument instead of Xelement):</p> <pre><code>XElement xe1 = XElement.Load(filePath); DataTable myTable = new DataTable(); myTable = mkTable(); // calls a function that makes the table var _categories = (from p1 in xe1.Descendants("category") select p1); int numCat = _categories.Count(); int i = 0; while (i &lt; numCat) { DataRow newrow; newrow = myTable.NewRow(); if (_categories.ElementAt(i).Parent.Name == "topic") { string att1 = _categories.ElementAt(i).Parent.Attribute("name").Value.ToString(); newrow["topic"] = att1.ToString(); } // repeat the above for the different things in my document myTable.Rows.Add(newrow); i++; } myDataSet.Merge(myTable); bindingSourceIn.DataSource = myDataSet; myDataGridView.DataSource = bindingSourceIn; myDataGridView.DataMember = "xmlthing"; </code></pre> <p>(obviously things are a little abbreviated here... i.e., my bindingsource/datagridview etc is declared elsewhere.... but hopefully this is enough to make sense)</p> <p>-Adeena</p>
46,702
<p>There was a contest to develop 3D printable files for the International Space Station's 3D printer. The winner got a 3D printer ... runners up got Fluke DVOM's and all entrants got a t-shirt.</p> <p>ISS 3D Print Contest</p> <p>They offer 3 materials: ABS, HDPE, and PEI+PC ... I'm not familiar with the last one. Anyone know?</p> <p>If found this material on Matweb: <a href="http://www.matweb.com/search/DataSheet.aspx?MatGUID=949ca0fa6b1742bea8e8d26ea2fd3d48t" rel="nofollow noreferrer">PEI+PC Alloy</a></p> <p>These links are thought to last a very long time. I hope many of you decide to upload a project into contest site and compete for the grand prize ... A sweet John Fluke DVOM. If nothing else a free awesome T-shirt.</p>
<p>Ultem 9085, the most common ultem resin used for AM, is a blend of PEI-PC, as seen here <a href="https://www.sabic-ip.com/gepapp/Plastics/servlet/ProductsAndServices/Product/series?sltPrdline=ULTEM&amp;sltPrdseries=Aerospace%20and%20Transportation&amp;search=Search#searchresults" rel="nofollow">https://www.sabic-ip.com/gepapp/Plastics/servlet/ProductsAndServices/Product/series?sltPrdline=ULTEM&amp;sltPrdseries=Aerospace%20and%20Transportation&amp;search=Search#searchresults</a>.</p> <p>Ultem is a trade name for PEI alloys made by Sabic and 9085, used in filaments made by both Stratasys and 3dXtech as the two most visible suppliers are both made with this same alloy. It is used for high temperature resistance and strength and needs to be printed at upwards of 300C in a contained environment.</p> <p>Source-Intern at Made in Space.</p>
<p>PEI - polyethermide is a "common" coating for heated print beds. PC is so many different things, but in this context, it's likely to mean polycarbonate plastic. From what I've read, it's challenging to print with and especially challenging to get a good bond on the build plate. One reference suggests to use a PEI coated bed with a slurry of ABS applied prior to printing. As with so many things 3d printer related, many people have many different methods. The above one appears to be well received as a successful method.</p>
350
<p>With previous versions of flash, entering the full screen mode increased the height and width of the stage to the dimensions of the screen. Now that hardware scaling has arrived, the height and width are set to the dimensions of the video (plus borders if the aspect ratio is different).</p> <p>That's fine, unless you have controls placed over the video. Before, you could control their size; but now they're blown up by the same scale as the video, and pixellated horribly. Controls are ugly and subtitles are unreadable.</p> <p>It's possible for the user to turn off hardware scaling, but all that achieves is to turn off anti-aliasing. The controls are still blown up to ugliness.</p> <p>Is there a way to get the old scaling behaviour back?</p>
<p>I've eventually found the answer to this. The problem is that the FLVPlayback component is now using the stage.fullScreenSourceRect property to enter a hardware-scaled full screen mode. When it does that, it stretches the rendered area given by stage.fullScreenSourceRect to fill the screen, rather than increasing the size of the stage or any components.</p> <p>To stop it, you have to create a subclass of FLVPlayback that uses a subclass of UIManager, and override the function that's setting stage.fullScreenSourceRect. On the down side, you lose hardware scaling; but on the up side, your player doesn't look like it's been drawn by a three-year-old in crayons.</p> <p>CustomFLVPlayback.as:</p> <pre><code>import fl.video.*; use namespace flvplayback_internal; public class CustomFLVPlayback { public function CustomFLVPlayback() { super(); uiMgr = new CustomUIManager(this); } } </code></pre> <p>CustomUIManager.as:</p> <pre><code>import fl.video.*; import flash.display.StageDisplayState; public class CustomUIManager { public function CustomUIManager(vc:FLVPlayback) { super(vc); } public override function enterFullScreenDisplayState():void { if (!_fullScreen &amp;&amp; _vc.stage != null) { try { _vc.stage.displayState = StageDisplayState.FULL_SCREEN; } catch (se:SecurityError) { } } } } </code></pre> <p>We add the FLVPlayback to our movie using actionscript, so we just have to replace</p> <pre><code>var myFLVPLayback:FLVPlayback = new FLVPlayback(); </code></pre> <p>with</p> <pre><code>var myFLVPLayback:CustomFLVPlayback = new CustomFLVPlayback(); </code></pre> <p>I don't know whether there's a way to make the custom class available in the component library.</p>
<pre><code>stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; stage.addEventListener(Event.RESIZE, onStageResize); function onStageResize(event:Event):void { //do whatever you want to re-position your controls and scale the video // here's an example myFLVPlayback.width = stage.stageWidth; myFLVPlayback.height = stage.stageHeight - controls.height; controls.y = stage.stageHeight - controls.height; } </code></pre> <p>Or, and I'm not entirely sure about this, you might try to do some 9 slice scaling on the FLVPlayback, but I don't know if that'll work.</p> <p>9-slice scaling tutorial: <a href="http://www.sephiroth.it/tutorials/flashPHP/scale9/" rel="nofollow noreferrer">http://www.sephiroth.it/tutorials/flashPHP/scale9/</a></p>
12,761
<p>I work at a company that, for some reason, insists that all our development documentation should be in MS Word format. Which, being a binary format, means we cannot:</p> <ul> <li>Diff versions of a document against each other (so peer reviewing them is a pain - because of the domain we work in, peer reviews for all changes are essential)</li> <li>Grep a folder-full of documents for keywords</li> </ul> <p>What do you use to write documentation in and why?</p> <p>Please also give me ammo to change this situation with...</p>
<p>I recently started using DocBook XML to author my documentation.</p> <p>On the upside, it's a pure text format. You can break a large document into multiple files, and use nodes to bring them all together into a single book. Table of contents and index are automatically generated. Intra-document links (within arbitrary text, pointing to chapters or sections) are very easy. And with a push of a button, I can create a single-html-file version, a chunked-html version (one file per chapter), and a PDF version.</p> <p>After some tweaking and customization, I'm very happy with the output. The documents look <em>great</em>!!</p> <p>DocBook is used extensively by real publishers (most notably, O'Reilly), and it's been around for more than fifteen years, so it's reached a certain level of maturity.</p> <p>On the other hand, all of the processing is done with XSLT, using an ad-hoc collection of tools. (My own docbook pipeline includes Python, Java, Xerces, Xalan, Apache FOP, and PDF-SAM. Plus the official XSLT stylesheet distribution, and my own XSLT customizations.)</p> <p>DocBook is not a turnkey solution. You won't be able to get going quickly, without reading the manual. And if you don't know anything about XSLT, you'll have to learn.</p> <p>On the other hand, there are only a dozen or two XML tags that you really need to know to <em>write</em> the documents. (The real expertise comes into play during doc generation from the XML sources.) If one person on your team was willing to be responsible for writing the doc build script, then everyone else on the team could just learn the DTD and do a decent job contributing.</p> <p>Anyhow... DocBook definitely has some faults. It's not the easiest system for tech authorship. But it's the best open source tool I know of.</p> <p>The "Subversion Book" is written in DocBook. Here's a page with links to the different book versions (single-html, chunked-html, and PDF):</p> <p><a href="http://svnbook.red-bean.com/" rel="nofollow noreferrer">http://svnbook.red-bean.com/</a></p> <p>And here's a link to the DocBook XML sources for the first chapter, so that you can get an idea for how it works:</p> <p><a href="http://sourceforge.net/p/svnbook/source/HEAD/tree/branches/1.7/en/book/ch01-fundamental-concepts.xml" rel="nofollow noreferrer">http://sourceforge.net/p/svnbook/source/HEAD/tree/branches/1.7/en/book/ch01-fundamental-concepts.xml</a></p>
<p>Not to defend MS products here, but MS word can diff documents.</p>
22,036
<p>For an ASP.NET application, what is the Best Practice implementation method for a custom swear word remover/replacer?</p> <p>If this is a data table solution, is there free resource to get the data? (Similar to finding a public dictionary table that you can import to your system for spellchecking)</p>
<p><a href="https://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/" rel="nofollow noreferrer" title="Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?">Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?</a> ^_^</p> <p>Also see <a href="https://stackoverflow.com/questions/273516/how-do-you-implement-a-good-profanity-filter" title="How do you implement a good profanity filter?">How do you implement a good profanity filter?</a>.</p>
<p>Well, what we (*) did is to create a two-tiered list of "bad words" (using regex to hopefully catch some variations). Using a Tier 1 word will get you a warning saying that you are violating the Terms of Service, and you cannot save that message until you fix it. If you use a Tier 2 word, the message is posted, but an objection is automatically filed against it. All message with an objection flagged (either system or user generated) are reviewed by a human who determined if it stays or goes.</p> <p>(*) "We" being the e-commerce arm of a large, staid brick-and-mortar chain-store, which has just started allowing user-generated content on it's website.</p>
38,364
<p>Is there anything similar to getElementById in actionscript? </p> <p>I'm trying to make a prototype of a flash page wich gets it's data from a xhtml file. I want to have both an accessible html version (for search engines, textreaders and people without flash) and a flash version (because the customer insists to use flash even though a html-css-ajax solution would do quite nicely). </p> <p>What I need is a simple way of getting the text or attributes from the html with a certain id, like <code>&lt;h1 id="flashdataTitle"&gt;This is the title&lt;/h1&gt;</code> etc. I'm guessing a few ways it might be possible:</p> <ul> <li>Somehow use an ExternalInterface.call and do the DOM trickery in JavaScript (wich is probably what I will do, because I'm very familiar with JS and a complete newbie with flash/actionscript, unless you have a better solution)</li> <li>Load the xhtml with the Actionscript XML class, and manually traverse the XML looking for the correct id attribute (but this is probably very slow)</li> <li>Use XPath with the XML class in actionscript. (I'd like some hints on how to do this, if this is the reccomended way)</li> <li>There is actually an Actionscript equivalent to getElementById to use with the XML?</li> <li>Allthough my employer hope we don't have to do this: I could rewrite the server side code to output the relevant texts and image urls in a flash-friendly format.</li> </ul> <p>What is the most effective, easiest to implement, and robust-crossbrowser way of doing this? Any totally different ideas?</p> <p>Please post any ideas even if you think the question have been answered, I'd like to explore all the different possibilities, and allso what disadvantages the proposed solutions have.</p>
<p>Since you said your input would be XHTML, you can do it with XPath:</p> <pre><code>import mx.xpath.XPathAPI; var elementId:String = "flashdataTitle"; var elementPath:String = "//h1[@id'" + elementId + "']"; found_elements = XPathAPI.selectNodeList(xhtml.firstChild, elementPath); if (found_elements.length == 1) { trace(found_elements[0]); } </code></pre> <p>The code example is inspired from <a href="http://www.robgonda.com/blog/index.cfm/2005/7/10/Xpath-for-ActionScript" rel="nofollow noreferrer">here</a>, where you also can find some mode detail on XPath and ActionScript.</p> <p>AS3 has it's own <a href="http://code.google.com/p/xpath-as3/" rel="nofollow noreferrer">XPath Library</a>, the general approach would be the same.</p>
<p>Is there anything like the prototype.js function <a href="http://www.prototypejs.org/api/object/inspect" rel="nofollow noreferrer">inspect()</a> in Actionscript? I've tried testing the xpath solution but it just won't work. I've tested that the xpath is correct using scetchpad (I think that's what it's called), so I beleave theres a problem with the XML object... It seems to contain the xhtml file when viewing it in the debugger, though it seems quite chaotic, but if I could "inspect" the variables and trace them it would help locating the problem. (Thanks Tomalak, I will upvote your answer as soon as my "reputation" is high enough.)</p> <p>BTW, I still want to hear other ideas.</p>
35,943
<p>We are looking for a way to automate windows forms for acceptance testing. Our requirements are:</p> <ul> <li><strong>Must be usable by non-developers</strong> (ie: people with no development environment installed)</li> <li>Must have a recorder</li> <li>Must support third-party controls</li> <li>Must have basic functionality (allow clicking on buttons, inputing text, validating results, accros multiple windows if necessary)</li> </ul> <p>Basically, something like <a href="http://selenium.openqa.org/" rel="nofollow noreferrer">Selenium</a>, but for windows forms.</p>
<blockquote> <p>Must be usable by non-developers</p> </blockquote> <p>Any not-web test automation tool will need either dev`s well-known ide (Eclipse etc.) or test tool ide. SilkTest, TestComplete etc. will also make u to write some code.</p> <p>U can separate work between devs and testers using tool for creating "executable requirements" like <a href="http://fitnesse.org" rel="nofollow noreferrer">"Fitnesse"</a> or <a href="http://www.concordion.org/" rel="nofollow noreferrer">Concordion</a></p>
<p>The Vermont HighTest: <a href="http://www.vtsoft.com/vcsproducts/index.html" rel="nofollow noreferrer">http://www.vtsoft.com/vcsproducts/index.html</a></p> <p>The 30 day trial looked pretty good!</p>
9,758
<p>I have a decimal number (let's call it <strong>goal</strong>) and an array of other decimal numbers (let's call the array <strong>elements</strong>) and I need to find all the combinations of numbers from <strong>elements</strong> which sum to goal.</p> <p>I have a preference for a solution in C# (.Net 2.0) but may the best algorithm win irrespective.</p> <p>Your method signature might look something like:</p> <pre><code>public decimal[][] Solve(decimal goal, decimal[] elements) </code></pre>
<p>Interesting answers. Thank you for the pointers to Wikipedia - whilst interesting - they don't actually solve the problem as stated as I was looking for exact matches - more of an accounting/book balancing problem than a traditional bin-packing / knapsack problem.</p> <p>I have been following the development of stack overflow with interest and wondered how useful it would be. This problem came up at work and I wondered whether stack overflow could provide a ready-made answer (or a better answer) quicker than I could write it myself. Thanks also for the comments suggesting this be tagged homework - I guess that is reasonably accurate in light of the above.</p> <p>For those who are interested, here is my solution which uses recursion (naturally) I also changed my mind about the method signature and went for List> rather than decimal[][] as the return type:</p> <pre><code>public class Solver { private List&lt;List&lt;decimal&gt;&gt; mResults; public List&lt;List&lt;decimal&gt;&gt; Solve(decimal goal, decimal[] elements) { mResults = new List&lt;List&lt;decimal&gt;&gt;(); RecursiveSolve(goal, 0.0m, new List&lt;decimal&gt;(), new List&lt;decimal&gt;(elements), 0); return mResults; } private void RecursiveSolve(decimal goal, decimal currentSum, List&lt;decimal&gt; included, List&lt;decimal&gt; notIncluded, int startIndex) { for (int index = startIndex; index &lt; notIncluded.Count; index++) { decimal nextValue = notIncluded[index]; if (currentSum + nextValue == goal) { List&lt;decimal&gt; newResult = new List&lt;decimal&gt;(included); newResult.Add(nextValue); mResults.Add(newResult); } else if (currentSum + nextValue &lt; goal) { List&lt;decimal&gt; nextIncluded = new List&lt;decimal&gt;(included); nextIncluded.Add(nextValue); List&lt;decimal&gt; nextNotIncluded = new List&lt;decimal&gt;(notIncluded); nextNotIncluded.Remove(nextValue); RecursiveSolve(goal, currentSum + nextValue, nextIncluded, nextNotIncluded, startIndex++); } } } } </code></pre> <p>If you want an app to test this works, try this console app code:</p> <pre><code>class Program { static void Main(string[] args) { string input; decimal goal; decimal element; do { Console.WriteLine("Please enter the goal:"); input = Console.ReadLine(); } while (!decimal.TryParse(input, out goal)); Console.WriteLine("Please enter the elements (separated by spaces)"); input = Console.ReadLine(); string[] elementsText = input.Split(' '); List&lt;decimal&gt; elementsList = new List&lt;decimal&gt;(); foreach (string elementText in elementsText) { if (decimal.TryParse(elementText, out element)) { elementsList.Add(element); } } Solver solver = new Solver(); List&lt;List&lt;decimal&gt;&gt; results = solver.Solve(goal, elementsList.ToArray()); foreach(List&lt;decimal&gt; result in results) { foreach (decimal value in result) { Console.Write("{0}\t", value); } Console.WriteLine(); } Console.ReadLine(); } } </code></pre> <p>I hope this helps someone else get their answer more quickly (whether for homework or otherwise).</p> <p>Cheers...</p>
<pre><code>public class Logic1 { static int val = 121; public static void main(String[] args) { f(new int[] {1,4,5,17,16,100,100}, 0, 0, "{"); } static void f(int[] numbers, int index, int sum, String output) { System.out.println(output + " } = " + sum); //System.out.println("Index value1 is "+index); check (sum); if (index == numbers.length) { System.out.println(output + " } = " + sum); return; } // include numbers[index] f(numbers, index + 1, sum + numbers[index], output + " " + numbers[index]); check (sum); //System.out.println("Index value2 is "+index); // exclude numbers[index] f(numbers, index + 1, sum, output); check (sum); } static void check (int sum1) { if (sum1 == val) System.exit(0); } } </code></pre>
10,916
<p>I'm using XPath in .NET to parse an XML document, along the lines of:</p> <pre class="lang-cs prettyprint-override"><code>XmlNodeList lotsOStuff = doc.SelectNodes("//stuff"); foreach (XmlNode stuff in lotsOStuff) { XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild"); // ... etc } </code></pre> <p>The issue is that the XPath Query for <code>stuffChild</code> is always returning the child of the first <code>stuff</code> element, never the rest. Can XPath not be used to query against an individual <code>XMLElement</code>?</p>
<p><code>//</code> at the beginning of an XPath expression starts from the document root. Try ".//stuffChild". . is shorthand for self::node(), which will set the context for the search, and // is shorthand for the descendant axis.</p> <p>So you have:</p> <pre><code>XmlNode stuffChild = stuff.SelectSingleNode(".//stuffChild"); </code></pre> <p>which translates to:</p> <p><strike>xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");</strike></p> <pre><code>xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant-or-self::stuffChild"); </code></pre> <p>In the case where the child node could have the same name as the parent, you would want to use the slightly more verbose syntax that follows, to ensure that you don't re-select the parent:</p> <pre><code>xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild"); </code></pre> <p>Also note that if "stuffChild" is a direct descendant of "stuff", you can completely omit the prefixes, and just select "stuffChild".</p> <pre><code>XmlNode stuffChild = stuff.SelectSingleNode("stuffChild"); </code></pre> <p>The <a href="http://www.w3schools.com/xsl/xpath_syntax.asp" rel="nofollow noreferrer">W3Schools</a> tutorial has helpful info in an easy to digest format.</p>
<p>Selecting single node means you need only the first element. So, the best solution is:</p> <pre><code>XmlNode stuffChild = stuff.SelectSingleNode("descendant::stuffChild[1]"); </code></pre>
4,639
<p>Has someone experiment RDF storage solution like <a href="http://www.openrdf.org/" rel="nofollow noreferrer">Sesame</a>? I'm looking for performance review of this kind of solution compared to the traditional database solution.</p>
<p>There are plenny scalabity reports and benchmarks on the web about various triple-stores. </p> <p>Here is a fine <a href="http://simile.mit.edu/reports/stores/" rel="noreferrer">scalability report</a>.</p> <p>W3C itself maintain a wiki with lots of information about <a href="http://esw.w3.org/topic/LargeTripleStores" rel="noreferrer">Large Triplestores</a> and <a href="http://esw.w3.org/topic/RdfStoreBenchmarking" rel="noreferrer">Benchmarks</a>.</p> <p>Follow these 3 links and take a time to read it. It's very informative. :)</p>
<p>One intuition is that if you have a very large number of entities, tuple stores can save yourself the trouble of having your indexes routinely knocked out of memory as you switch between tables, and instead always have the first couple levels of the tuple index in RAM.</p>
3,844
<p>I would like to match &quot;approximate&quot; matches in Web.SiteMap</p> <p>The Web.Sitemap static sitemap provider works well, except for one thing. IT'S STATIC!</p> <p>So, if I would have to have a sitemapnode for each of the 10,000 articles on my page like so :</p> <ul> <li>site.com/articles/1/article-title</li> <li>site.com/articles/2/another-article-title</li> <li>site.com/articles/3/another-article-again</li> <li>...</li> <li>site.com/articles/9999/the-last-article</li> </ul> <p>Is there some kind of Wildcard mapping I can do with the SiteMap to match Anything under Articles?</p> <p>Or perhaps in my Webforms Page, is there a way to Manually set the current node?</p> <p>I've found a &quot;bit&quot; of help on <a href="https://web.archive.org/web/20200925074743/http://geekswithblogs.net/Patware/archive/2008/11/12/126987.aspx" rel="nofollow noreferrer">this page</a> when doing this with the ASP.Net MVC Framework, but still looking for a good solution for Webforms.</p> <p>I think what I'm going to have to do is create a custom SiteMap Provider</p>
<p>This is in response to the comment above. I can't post the full code, but this is basically how my provider works.</p> <p>Suppose you have a page article.aspx, and it uses query string parameter "id" to retrieve and display an article title and body. Then this is in Web.sitemap:</p> <pre><code>&lt;siteMapNode url="/article.aspx" title="(this will be replaced)" param="id" /&gt; </code></pre> <p>Then, you create this class:</p> <pre><code>public class DynamicSiteMapPath : SiteMapPath { protected override void InitializeItem(SiteMapNodeItem item) { if (item.ItemType != SiteMapNodeItemType.PathSeparator) { string url = item.SiteMapNode.Url; string param = item.SiteMapNode["param"]; // get parameter value int id = System.Web.HttpContext.Current.Request.QueryString[param]; // retrieve article from database using id &lt;write your own code&gt; // override node link HyperLink link = new HyperLink(); link.NavigateUrl = url + "?" + param + "=" + id.ToString(); link.Text = &lt;the article title from the database&gt;; link.ToolTip = &lt;the article title from the database&gt;; item.Controls.Add(link); } else { // if current node is a separator, initialize as usual base.InitializeItem(item); } } } </code></pre> <p>Finally, you use this provider in your code just like you would use the static provider.</p> <pre><code>&lt;mycontrols:DynamicSiteMapPath ID="dsmpMain" runat="server" /&gt; </code></pre> <p>My class is more complicated than this, but these are the basics. Instead of using a querystring parameter, you could just analyze the friendly url you're using, and use that instead to retrieve the correct content. To minimize the additional db lookups with every request, you can add a caching mechanism to the provider (article title usually won't change often).</p> <p>Hope this helps.</p>
<p>This is not entirely an answer to your question I think, but maybe it gives you an idea. I once wrote a DynamicSiteMapPath class inheriting SiteMapPath. I use a custom attribute in each <code>&lt;siteMapNode&gt;</code> tag in Web.sitemap, like this:</p> <pre><code>&lt;siteMapNode url="dynamicpage.aspx" title="blah" params="id" /&gt; </code></pre> <p>Then the DynamicSiteMapPath class gets the "id" parameter value, retrieves the content from the database, and overrides the currently rendered sitemap item node with the correct title and link. It's gonna take a little work, but when done correctly this is a very neat way of providing dynamic page support.</p>
37,241
<p>When trying to implement an asynchronous API calls / Non-blocking calls, I know a little in a All Plain-C application I have, I read a about APM (Asynchronous Programming Model) by 'Delegates'. Basically what I want to do is call one API <code>f1()</code> to do a functionality(which takes long time 8-10 seconds), So I call that API <code>f1()</code>, forget about it, and continue doing some other work, e.g. I/O for to fetch data for next call of the <code>f1()</code> or some functionality not dependent on result of <code>f1()</code>.</p> <p>If any one has used that APM model of programming, I am looking at some concise explanation for implementing non-blocking calls. </p> <p>Is there any other way of implementing asynchronous APIs , any other library/framework which might help in this?</p>
<p>You basically need to create a multi-threaded (or multi-process) application. The f1() API needs to spawn a thread (or process) to process the data in a separate execution space. When it completes, the f1() routine needs to signal the main process that the execution is done (signal(), message queues, etc).</p>
<p>Replace delegates with pointers to functions in C, everything else is basically same to what you have read.</p>
8,770
<p>As it was made clear in my <a href="https://stackoverflow.com/questions/212009/do-i-have-to-explicitly-call-systemexit-in-a-webstart-application">recent question</a>, Swing applications need to explicitly call System.exit() when they are ran using the Sun Webstart launcher (at least as of Java SE 6).</p> <p>I want to restrict this hack as much as possible and I am looking for a reliable way to detect whether the application is running under Webstart. Right now I am checking that the value of the system property "webstart.version" is not null, but I couldn't find any guarantees in the documentation that this property should be set by future versions/alternative implementations.</p> <p>Are there any better ways (preferably ones that do not ceate a dependency on the the webstart API?)</p>
<p>When your code is launched via javaws, javaws.jar is loaded and the JNLP API classes that you don't want to depend on are available. Instead of testing for a system property that is not guaranteed to exist, you could instead see if a JNLP API class exists:</p> <pre><code>private boolean isRunningJavaWebStart() { boolean hasJNLP = false; try { Class.forName("javax.jnlp.ServiceManager"); hasJNLP = true; } catch (ClassNotFoundException ex) { hasJNLP = false; } return hasJNLP; } </code></pre> <p>This also avoids needing to include javaws.jar on your class path when compiling.</p> <p>Alternatively you could switch to compiling with javaws.jar and catching NoClassDefFoundError instead:</p> <pre><code>private boolean isRunningJavaWebStart() { try { ServiceManager.getServiceNames(); return ds != null; } catch (NoClassDefFoundError e) { return false; } } </code></pre> <p>Using ServiceManager.lookup(String) and UnavailableServiceException is trouble because both are part of the JNLP API. The ServiceManager.getServiceNames() is not documented to throw. We are specifically calling this code to check for a NoClassDefFoundError.</p>
<p>You can check whether the current classloader is an instance of com.sun.jnlp.JNLPClassLoader (Java plugin 1) or sun.plugin2.applet.JNLP2ClassLoader (Java plugin 2). Despite the "applet" package, an applet using JNLP with the Java plugin 2 uses another classloader, sun.plugin2.applet.Applet2ClassLoader. It works with OpenJDK too.</p>
26,594
<p>I setup phpMyID on one of my machines, and I'm trying to get apache to redirect to HTTPS only when a password is being submitted. I am doing this as my original setup of redirecting all openid traffic didn't work stackoverflow doesn't like my self signed certificate. This is the new rule I've written, but its not working:</p> <pre><code>RewriteRule http://%{SERVER_NAME}/openid/index.php(\?.+)$ https://%{SERVER_NAME}/openid/index.php$1 </code></pre>
<p>You need to use a Cond to test for both port (http or httpd) and query string:</p> <pre><code>RewriteCond %{SERVER_PORT} 80 RewriteCond %{QUERY_STRING} (.+) RewriteRule /openid/index.php https://%{SERVER_NAME}/openid/index.php?%1 </code></pre> <p>if on .htaccess you must use instead</p> <pre><code>RewriteCond %{SERVER_PORT} 80 RewriteCond %{QUERY_STRING} (.+) RewriteRule openid/index.php https://%{SERVER_NAME}/openid/index.php?%1 </code></pre>
<p>A better solution would be:</p> <pre> RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^openid/index\.php$ https://%{SERVER_NAME}/openid/index.php </pre> <p>Explaination: <code>RewriteCond %{SERVER_PORT} 80</code> does also match ports that just include <code>80</code>. The same applies to the pattern <code>openid/index.php</code> (where “<code>.</code>” also can be any character). And appending the query is not necessary since mod_rewrite automatically appends the originally requested query to the substitute unless the query of the substitute is given.</p>
16,651
<p>I deployed an update to my ASP.NET application and started seeing this error on my page that used foo.dll:</p> <blockquote> <p>Unable to load foo.dll. The specified module could not be found. (Exception from HRESULT: 0x8007007E)</p> </blockquote> <p>foo.dll is in my system32 and application bin directory (which are in the path environment variable). </p> <p>What gives?</p>
<p>Any time you have issues loading assemblies, reach for the <a href="http://msdn.microsoft.com/en-us/library/e74a18c4(VS.71).aspx" rel="nofollow noreferrer">fusion log.</a></p>
<p>Fuslogvw, as Will said. Often the issue is not that foo.dll is not found, but that one if foo.dll's dependencies is missing. This is often the C Runtime library if this is an unmanaged DLL (you need the correct version for the Visual Studio version you are building with, as well as the corresponding debug or release version depending on your build configuration).</p>
44,277
<p>I have a Solaris daemon written in Java6. Clients can connect to it using a telnet style interface. They telnet to a particular port, and I read lines of input and act on them.</p> <p>At one point in I need to prompt the user to enter a password, and while they're entering that I want to disable the echoing of characters back to the telnet client.</p> <p>The code has a Socket object and creates an InputStream from the socket's getInputStream() result, then reads and buffers characters from the InputStream, breaking them up on cr/lf boundaries.</p> <p>I can't see any attributes on either the InputStream or the Socket to disable the echoing of characters back to the client.</p> <p>Can someone nudge me in the right direction?</p>
<p>Sounds like you need to build a simple Network Virtual Terminal that supports the no echo etc commands. There is already a good answer you should refer to on SO : <a href="https://stackoverflow.com/questions/267538/telnet-server">Telnet Server</a></p>
<p>You should understand where the echo is coming from. TCP connections and java InputStreams don't provide echo on their own. The telnet program that the user runs normally starts in "local echo" mode, meaning that it echoes everything typed by the user to the user's screen. When the telnet client connects to an actual telnet server, it commonly negotiates "remote echo" mode in which case the remote system provides the echo. When telnet connects to something else, like an HTTP or SMTP server, it just stays in local echo mode.</p> <p>The user can issue a command to turn off local echo in the client, but it wouldn't be very user-friendly to require your users to do that. As the other answer says, if you want to switch echoing on and off, you will need to enhance your server to support the telnet protocol, then negotiate remote echo with clients.</p> <p>If you do this, you'll also encounter the issue of line-at-a-time vs. character-at-a-time. Telnet starts in line-at-a-time mode. It honors line-editing keys like backspace locally, and only sends the line to the server when the user hits return. If you're doing remote echo, then you need to echo characters as the user types them, not after he hits return. So you'll have to support character-at-a-time and implement line editing in the server.</p> <p>You should look closely at the telnet server program on your server host. It might be possible to use the existing telnet server as a frontend for your program, rather than reimplementing everything that it does. Good luck.</p>
47,984
<p>What is the difference between the concepts of <strong>"Code Re-entrancy"</strong> and <strong>"Thread Safety"</strong>? As per the link mentioned below, a piece of code can be either of them, both of them or neither of them. </p> <p><a href="http://encyclopedia.thefreedictionary.com/reentrant+code" rel="noreferrer">Reentrant and Thread safe code</a></p> <p>I was not able to understand the explaination clearly. Help would be appreciated. </p>
<p>Re-entrant code has no state in a single point. You can call the code while something is executing in the code. If the code uses global state, one call can conceivably overwrite the global state, breaking the computation in the other call.</p> <p>Thread safe code is code with no race conditions or other concurrency issues. A race condition is where the order in which two threads do something affects the computation. A typical concurrency issue is where a change to a shared data structure can be partially completed and left in an inconsistent state. In order to avoid this, you have to use concurrency control mechanisms such as semaphores of mutexes to ensure that nothing else can access the data structure until the operation is completed.</p> <p>For example, a piece of code can be non re-entrant but thread-safe if it is guarded externally by a mutex but still has a global data structure where the state must be consistent for the entire duration of the call. In this case, the same thread could initiate a call-back into the procedure while still protected by an external coarse-grained mutex. If the call-back occured from within the non re-entrant procedure the call could leave the data structure in a state that could break the computation from the caller's point of view.</p> <p>A piece of code can be re-entrant but non thread-safe if it can make a non-atomic change to a shared (and sharable) data structure that could be interrupted in the middle of the update leaving the data structure in an incosistent state. In this case another thread accessing the data structure could be affected by the half-changed data structure and either crash or perform an operation that corrupts the data.</p>
<p>That article says:</p> <p>"a function can be either reentrant, thread-safe, both, or neither."</p> <p>It also says:</p> <p>"Non-reentrant functions are thread-unsafe".</p> <p>I can see how this may cause a muddle. They mean that standard functions documented as not required to be re-entrant are also not required to be thread-safe, which is true of the POSIX libraries iirc (and POSIX declares it to be true of the ANSI/ISO libraries too, ISO having no concept of threads and hence no concept of thread-safety). In other words, "if a function says it is non-reentrant, then it is saying it's thread-unsafe too". That's not a logical necessity, it's just a convention.</p> <p>Here's some pseudo-code which is thread-safe (well, there's plenty of opportunity for callbacks to create deadlocks due to locking inversion, but let's assume the documentation contains sufficient information for users to avoid that) but not re-entrant. It is supposed to increment the global counter, and perform the callback:</p> <pre><code>take_global_lock(); int i = get_global_counter(); do_callback(i); set_global_counter(i+1); release_global_lock(); </code></pre> <p>If the callback calls this routine again, resulting in another callback, then both levels of callback will get the same parameter (which might be OK, depending on the API), but the counter will only be incremented once (which is almost certainly not the API you want, so it would have to be banned).</p> <p>That's assuming the lock is recursive, of course. If the lock is non-recursive, then of course the code is non-reentrant anyway, since taking the lock the second time won't work.</p> <p>Here's some pseudo-code which is "weakly re-entrant" but not thread-safe:</p> <pre><code>int i = get_global_counter(); do_callback(i); set_global_counter(get_global_counter()+1); </code></pre> <p>Now it's fine to call the function from the callback, but it's not safe to call the function concurrently from different threads. It's also not safe to call it from a signal handler, because re-entrancy from a signal handler could likewise break the count if the signal happened to occur at the right time. So the code is non-re-entrant by the proper definition.</p> <p>Here's some code which arguably is fully re-entrant (except I think the standard distinguishes between reentrant and 'non-interruptible by signals', and I'm not sure where this falls), but still isn't thread-safe:</p> <pre><code>int i = get_global_counter(); do_callback(i); disable_signals(); // and any other kind of interrupts on your system set_global_counter(get_global_counter()+1); restore_signal_state(); </code></pre> <p>On a single-threaded app, this is fine, assuming that the OS supports disabling everything that needs to be disabled. It prevents re-entrancy from occurring at the critical point. Depending how signals are disabled, it may be safe to call from a signal handler, although in this particular example there's still the issue of the parameter passed to the callback being the same for separate calls. It can still go wrong multi-threaded, though.</p> <p>In practice, non-thread-safe often implies non-re-entrant, since (informally) anything that can go wrong due to the thread being interrupted by the scheduler, and the function called again from another thread, can also go wrong if the thread is interrupted by a signal, and the function is called again from the signal handler. But then the "fix" to prevent signals (disabling them) is different from the "fix" to prevent concurrency (locks, usually). This is at best a rule of thumb.</p> <p>Note that I've implied globals here, but exactly the same considerations would apply if the function took as a parameter a pointer to the counter and the lock. It's just that the various cases would be thread-unsafe or non-re-entrant when called with the same parameter, rather than when called at all.</p>
45,880
<p>This is an excerpt of code from a class I am working with in Java (below). Obviously the code is defining a static variable named EPSILON with the data type double. What I don't understand is the "1E-14" part. What kind of number is that? What does it mean?</p> <p>final double EPSILON = 1E-14;</p>
<p>In your case, this is equivalent to writing:</p> <pre><code>final double EPSILON = 0.00000000000001; </code></pre> <p>except you don't have to count the zeros. This is called <a href="http://en.wikipedia.org/wiki/Scientific_notation" rel="noreferrer">scientific notation</a> and is helpful when writing very large or very small numbers.</p>
<p>1E-14 is 1 times 10 to the power of -14</p>
19,949
<p>I would like to break a long line of text assigned to the standard Label widget in GWT. I was experimenting with inline <code>&lt;br /&gt;</code> elements but with no success.</p> <p>Something like this: </p> <pre><code>label = "My very very very long&lt;br /&gt;long long text" </code></pre>
<p>You need to use the HTML widget, which extends the standard Label widget, and adds support for interpreting HTML tags.</p> <p>See the <a href="http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/user/client/ui/HTML.html" rel="noreferrer">JavaDoc</a>.</p>
<p>I would use CSS to style the label to fit a given with and drop the <code>&lt;br/&gt;</code> all together.</p>
26,058
<p>Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.</p> <p><a href="http://wiki.wxpython.org/LongRunningTasks" rel="noreferrer">Here's a good discussion</a> of how to do this in wxPython. To summarize, there are 3 ways:</p> <ol> <li>Use threads</li> <li>Use wxYield</li> <li>Chunk the work and do it in the IDLE event handler</li> </ol> <p>Which method have <em>you</em> found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.</p>
<p>Threads. They're what I always go for because you can do it in every framework you need. </p> <p>And once you're used to multi-threading and parallel processing in one language/framework, you're good on all frameworks.</p>
<p>Working with Qt/C++ for Win32.</p> <p>We divide the major work units into different processes. The GUI runs as a separate process and is able to command/receive data from the "worker" processes as needed. Works nicely in todays multi-core world.</p>
17,948
<p>I'm playing around with ASP.net MVC and JQuery at the moment. I've come across behavour which doesn't seem to make sense. </p> <p>I'm calling JQuery's <code>$.getJSON</code> function to populate some div's. The event is triggered on the <code>$(document).ready</code> event. This works perfectly.</p> <p>There is a small <code>AJAX.BeginForm</code> which adds another value to be used when populating the divs. It calls the remote function correctly and upon success calls the original javascript function to repopulate the divs.</p> <p>Here is the weird part: In FireFox and Chrome - Everything works. BUT In IE8 (Beta) this second call to the populate Div script (which calls the $.getJSON function) gets cached data and does not ask the server!</p> <p>Hope this question makes sense: In a nut shell - Why is <code>$.getJSON</code> getting cached data? And why is it only effecting IE8?</p>
<p>Just to let you know, Firefox and Chrome consider all Ajax request as non-cachable. IE (all versions) treat Ajax call just as other web request. That's why you see this behavior.<br> How to force IE to download data at each request:</p> <ul> <li>As you said, use 'cache' or 'nocache' option in JQuery</li> <li>Add a random parameter to the request (ugly, but works :))</li> <li>On server side, set cachability (for example using an attribute, see below)</li> </ul> <p>Code:</p> <pre><code>public class NoCacheAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext context) { context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache); } } </code></pre>
<p>You may need to send a cache-breaker. </p> <p>I would recommend using $.ajax( { cache: no }) just in case ( adds a random suffix to the get request) </p> <p>( I tend to use $.ajax everywhere these days, more tuneable ) </p>
33,086
<p>Here I had build a HTML page with an <code>iFrame</code>. I had an id within the <code>iFrame</code> src page. Is it possible to access the id from my current page through JavaScript.</p> <p>Please help me.</p>
<p>You must be careful if you are accessing an iframe's script from your parent page, to make sure that your iframe has already finished loading before requesting from it. Here is an example:</p> <pre><code>window.onload = function () { document.getElementById('iframeId').onload = function () { //Attach an onload function to the iframe //Do the stuff you want to do with the iframe here //because this function is executed once the iframe has finished loading }; }; </code></pre>
<p>This is a small example I put through,</p> <pre><code>&lt;title&gt;Untitled Page&lt;/title&gt; &lt;script type="text/javascript" &gt; function ShowVal() { alert(myIframe.document.getElementById('nameText').value); } &lt;/script&gt; </code></pre> <p>'myIfrmae' is the id of the iframe. and 'nameText' is a textbox control in the page contained in the iframe.</p> <p>I was calling this ShowVal function from the parent page on a button click.</p> <p>Thanks.</p> <p>P.S. Sorry could not post the whole example. Having trouble with posting Html.</p>
47,640
<p>In Java, is there a way to control the TTL of the IP header for packets sent on a socket? </p>
<p>Apparently only on Multicast sockets, which have:</p> <pre><code>MulticastSocket.setTimeToLive(int ttl); </code></pre>
<p>Setting the TTL using </p> <pre><code>MulticastSocket.setTimeToLive(int ttl); </code></pre> <p>is only going to work if you have enabled the IPV4Stack as outlined by this other question</p> <p><a href="https://stackoverflow.com/questions/139909/java-multicast-time-to-live-is-always-0">Java Multicast Time To Live is always 0</a></p> <pre><code>-Djava.net.preferIPv4Stack=true </code></pre>
36,500
<p>I have a DataGrid that looks like this (slightly simplified here):</p> <pre><code>&lt;asp:DataGrid ID="grdQuotas" runat="server" AutoGenerateColumns="False"&gt; &lt;HeaderStyle CssClass="quotas-header" /&gt; &lt;Columns&gt; &lt;asp:TemplateColumn&gt; &lt;HeaderTemplate&gt; Max order level&lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;asp:DropDownList ID="ddlMaxOrderLevel" runat="server" DataSourceID="xdsOrderLevel" DataTextField="Text" DataValueField="Value" SelectedValue='&lt;%# Bind("MaxOrderLevel") %&gt;'&gt; &lt;/asp:DropDownList&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateColumn&gt; &lt;/Columns&gt; &lt;/asp:DataGrid&gt; &lt;asp:XmlDataSource ID="xdsOrderLevel" runat="server" DataFile="~/App_Data/OrderLevels.xml"&gt; &lt;/asp:XmlDataSource&gt; </code></pre> <p>In my <code>Page_Load</code> event handler I am creating a <code>DataTable</code> containing default values and <code>DataBind</code>ing it to the <code>DataGrid</code>.</p> <p>The problem is that this is taking place <em>before</em> the <code>DropDownList</code> <strong>ddlMaxOrderLevel</strong> has been bound to its <code>DataSource</code>, so I get a runtime error telling me that the <code>SelectedValue</code> cannot be set.</p> <p>If <strong>ddlMaxOrderLevel</strong> was not in a <code>DataGrid</code> I could just call <code>DataBind()</code> on it. However I cannot do that in this scenario - since it is in an <code>ItemTemplate</code>.</p> <p>Can anyone suggest a workaround or alternate approach?</p>
<p>You could do the Databinding of the DropDownlist in the Databound event of the DataGrid.</p> <p>Edit: I will give you an example that i have tested:</p> <pre><code> protected void dg_ItemDataBound(object sender, DataGridItemEventArgs e) { if (e.Item.ItemType != ListItemType.Header &amp;&amp; e.Item.ItemType != ListItemType.Footer) { DropDownList dl = (DropDownList)((DataGridItem)e.Item).FindControl("ddlMaxOrderLevel"); dl.DataSource = levels; dl.DataBind(); dl.SelectedValue = ((DataRowView)e.Item.DataItem)["number"].ToString(); } } </code></pre>
<p>You could do the Databinding of the DropDownlist in the Databound event of the DataGrid.</p> <p>Edit: I will give you an example that i have tested:</p> <pre><code> protected void dg_ItemDataBound(object sender, DataGridItemEventArgs e) { if (e.Item.ItemType != ListItemType.Header &amp;&amp; e.Item.ItemType != ListItemType.Footer) { DropDownList dl = (DropDownList)((DataGridItem)e.Item).FindControl("ddlMaxOrderLevel"); dl.DataSource = levels; dl.DataBind(); dl.SelectedValue = ((DataRowView)e.Item.DataItem)["number"].ToString(); } } </code></pre>
42,826
<p>Given an arbitrary string, what is an efficient method of finding duplicate phrases? We can say that phrases must be longer than a certain length to be included.</p> <p>Ideally, you would end up with the number of occurrences for each phrase.</p>
<p>Like the earlier folks mention that suffix tree is the best tool for the job. My favorite site for suffix trees is <a href="http://www.allisons.org/ll/AlgDS/Tree/Suffix/" rel="nofollow noreferrer">http://www.allisons.org/ll/AlgDS/Tree/Suffix/</a>. It enumerates all the nifty uses of suffix trees on one page and has a test <code>js</code> applicaton embedded to test strings and work through examples.</p>
<p>Like jmah said, you can use suffix trees/suffix arrays for this.</p> <p>There is a description of an algorithm you could use <a href="http://pine.cs.yale.edu/pinewiki/StringAlgorithms" rel="nofollow noreferrer">here</a> (see Section 3.1).</p> <p>You can find a more in-depth description in the book they cite (Gusfield, 1997), which is <a href="http://books.google.com/books?id=STGlsyqtjYMC&amp;pg=PA152&amp;lpg=PA152&amp;dq=gusfield+7.14.4&amp;source=web&amp;ots=kiN7ABH-u9&amp;sig=j5h8GJmUUWvlzehTUrP2QJjx4Ns&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=1&amp;ct=result#PPA151,M1" rel="nofollow noreferrer">on google books</a>.</p>
11,428
<p>I want to create my Rails application with MySQL, because I like it so much. How can I do that in the latest version of Rails instead of the default SQLite?</p>
<p>Normally, you would create a new Rails app using</p> <pre><code>rails ProjectName </code></pre> <p>To use MySQL, use</p> <pre><code>rails new ProjectName -d mysql </code></pre>
<p><strong>Use following command to create new app for API with mysql database</strong></p> <pre><code>rails new &lt;appname&gt; --api -d mysql adapter: mysql2 encoding: utf8 pool: 5 username: root password: socket: /var/run/mysqld/mysqld.sock </code></pre>
2,566
<p>I am looking to create symlinks (soft links) from Java on a Windows Vista/ 2008 machine. I'm happy with the idea that I need to call out to the JNI to do this. I am after help on the actual C code though. What is the appropriate system call to create the link? Pointers to some good documentation on this subject would be very much appreciated.</p>
<p>Symbolic links in Windows are created using the <a href="http://msdn.microsoft.com/en-us/library/aa363866.aspx" rel="noreferrer">CreateSymbolicLink API Function</a>, which takes parameters very similar to the command line arguments accepted by <a href="http://technet.microsoft.com/en-us/library/cc753194.aspx" rel="noreferrer">the Mklink command line utility</a>.</p> <p>Assuming you're correctly referencing the JNI and Win32 SDK headers, your code could thus be as simple as:</p> <pre><code>JNIEXPORT jboolean JNICALL Java_ClassName_MethodName (JNIEnv *env, jstring symLinkName, jstring targetName) { const char *nativeSymLinkName = env-&gt;GetStringUTFChars(symLinkName, 0); const char *nativeTargetName = env-&gt;GetStringUTFChars(targetName, 0); jboolean success = (CreateSymbolicLink(nativeSymLinkName, nativeTargetName, 0) != 0); env-&gt;ReleaseStringUTFChars(symLinkName, nativeSymLinkName); env-&gt;ReleaseStringUTFChars(targetName, nativeTargetName); return success; } </code></pre> <p>Note that this is just off the top of my head, and I haven't dealt with JNI in ages, so I may have overlooked some of the finer points of making this work...</p>
<p>Couldn't you just call out to the command line and use <strong>mklink</strong>?</p>
24,016
<p>RDBMS packages today offer a tremendous amount of functionality beyond standard data storage and retrieval. SQL Server for example can send emails, expose web service methods, and execute CLR code amongst other capabilities. However, I have always tried to limit the amount of processing my database server does to just data storage and retrieval as much as possible, for the following reasons:</p> <ul> <li>A database server is harder to scale than web servers</li> <li>In a lot of projects I've worked on, the DB server is a lot busier than the web servers, and thus has less spare capacity</li> <li>It potentially exposes your database server to a security attack (web services for example)</li> </ul> <p>My question is, how do you decide how much functionality or code should be implemented directly on your database server versus other servers in your architecture? What recommendations do you have for people starting new projects?</p>
<p>I know Microsoft SQL Server and Oracle really push using stored procedures for everything, which helps to encapsulate the relational architecture and creates a more procedural interface for the software developers, who typically aren't as facile writing SQL queries.</p> <p>But then half your application logic is written in PL/SQL (or T-SQL or whatever) and the other half is written in your application language, Java or PHP or C#, etc. The DBA is typically responsible for coding the procedures, and the developers are responsible for everything else. No one has visibility and access to the full application logic. This tends to slow down development, testing, and future revisions to the project.</p> <p>Also software development tools tend to be poor for stored procedures. Tools and best practices for debugging, source control, and testing all seem to be about 10-15 years behind the state of the art for application languages.</p> <p>So I tend to stay away from stored procedures and triggers if at all possible. Except in certain cases when a well-placed stored procedure can make a complex SQL operation happen entirely in the server instead of shuffling data back and forth. This can be very effective at eliminating performance bottlenecks.</p> <p>It's possible to go too far in the other direction as well. People who prefer the application manage data versus metadata, and employ designs like Entity-Attribute-Value or Polymorphic Associations, get themselves into trouble. Let the database manage that. Use referential integrity constraints (foreign keys). Use transactions.</p>
<p>The vendors have one set of best practices. You, however, voice concerns with that.</p> <p>Years ago I supported a <strong>Major Software Product</strong>. Major.</p> <p>They said "The database is relational storage. Nothing more." Every user conference people would ask about stored procedure, triggers, and all that malarkey.</p> <p>Their architect was firm. As soon as you get away from plain-old-SQL, you've got a support and maintenance nightmare. They did object-relational mapping from the DB into their product, and everything else was in their product.</p> <p>This scales well. Multiple application servers can easily share a single database server. </p>
22,414
<p>I have a setup project for a .NET Service Application which uses a .NET component which exposes a COM interface (COM callable wrapper / CCW). To get the component working on a target machine, it has to be registered with</p> <blockquote> <p>regasm.exe /tlb /codebase component.dll</p> </blockquote> <p>The /tlb switch to generate the typelib is mandatory in this case, otherwise I can't create objects from that assembly.</p> <p>The question is, how can I configure my Visual Studio 2008 Setup-Project to register this assembly with a call to regasm /tlb ?</p>
<p>You can lose the manual call to regasm.exe by using System.Runtime.InteropServices.RegistrationServices instead:</p> <pre><code>[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Install(IDictionary stateSaver) { base.Install(stateSaver); RegistrationServices regsrv = new RegistrationServices(); if (!regsrv.RegisterAssembly(GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase)) { throw new InstallException("Failed to register for COM Interop."); } } [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Uninstall(IDictionary savedState) { base.Uninstall(savedState); RegistrationServices regsrv = new RegistrationServices(); if (!regsrv.UnregisterAssembly(GetType().Assembly)) { throw new InstallException("Failed to unregister for COM Interop."); } } </code></pre> <p>This also unregisters the library upon uninstall.</p>
<p>Visual Studio installer makes only COM class registration, but does not make the type library generation and registration (this is what <code>/tlb</code> switch at <code>regasm.exe does</code>) by default. At least in Visual Studio 2017 it is enough to generate the type library in the post-build steps of DLL to be registered using <code>Tlbexp.exe</code> utility. </p> <p>If the installer project discovers a file with extension <code>.tlb</code> in the same directory and with the same name as the library you are installing, it automatically includes it to the setup project and makes the registration steps during the installation. Of course it is also possible to generate the <code>.tlb</code> file by hand and include it in the setup project (and set its Register property to <code>vsdrfCOM</code>).</p> <p>Here is a <a href="https://www.red-gate.com/simple-talk/dotnet/visual-studio/build-and-deploy-a-.net-com-assembly/" rel="nofollow noreferrer">great article</a> about C# and COM interface and the information above come from its section called Deployment.</p>
29,631
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
<p>It is generally a bad pattern to kill a thread abruptly, in Python, and in any language. Think of the following cases:</p> <ul> <li>the thread is holding a critical resource that must be closed properly</li> <li>the thread has created several other threads that must be killed as well.</li> </ul> <p>The nice way of handling this, if you can afford it (if you are managing your own threads), is to have an exit_request flag that each thread checks on a regular interval to see if it is time for it to exit.</p> <p><strong>For example:</strong></p> <pre><code>import threading class StoppableThread(threading.Thread): &quot;&quot;&quot;Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition.&quot;&quot;&quot; def __init__(self, *args, **kwargs): super(StoppableThread, self).__init__(*args, **kwargs) self._stop_event = threading.Event() def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set() </code></pre> <p>In this code, you should call <code>stop()</code> on the thread when you want it to exit, and wait for the thread to exit properly using <code>join()</code>. The thread should check the stop flag at regular intervals.</p> <p>There are cases, however, when you really need to kill a thread. An example is when you are wrapping an external library that is busy for long calls, and you want to interrupt it.</p> <p>The following code allows (with some restrictions) to raise an Exception in a Python thread:</p> <pre><code>def _async_raise(tid, exctype): '''Raises an exception in the threads with id tid''' if not inspect.isclass(exctype): raise TypeError(&quot;Only types can be raised (not instances)&quot;) res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype)) if res == 0: raise ValueError(&quot;invalid thread id&quot;) elif res != 1: # &quot;if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect&quot; ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None) raise SystemError(&quot;PyThreadState_SetAsyncExc failed&quot;) class ThreadWithExc(threading.Thread): '''A thread class that supports raising an exception in the thread from another thread. ''' def _get_my_tid(self): &quot;&quot;&quot;determines this (self's) thread id CAREFUL: this function is executed in the context of the caller thread, to get the identity of the thread represented by this instance. &quot;&quot;&quot; if not self.isAlive(): raise threading.ThreadError(&quot;the thread is not active&quot;) # do we have it cached? if hasattr(self, &quot;_thread_id&quot;): return self._thread_id # no, look for it in the _active dict for tid, tobj in threading._active.items(): if tobj is self: self._thread_id = tid return tid # TODO: in python 2.6, there's a simpler way to do: self.ident raise AssertionError(&quot;could not determine the thread's id&quot;) def raiseExc(self, exctype): &quot;&quot;&quot;Raises the given exception type in the context of this thread. If the thread is busy in a system call (time.sleep(), socket.accept(), ...), the exception is simply ignored. If you are sure that your exception should terminate the thread, one way to ensure that it works is: t = ThreadWithExc( ... ) ... t.raiseExc( SomeException ) while t.isAlive(): time.sleep( 0.1 ) t.raiseExc( SomeException ) If the exception is to be caught by the thread, you need a way to check that your thread has caught it. CAREFUL: this function is executed in the context of the caller thread, to raise an exception in the context of the thread represented by this instance. &quot;&quot;&quot; _async_raise( self._get_my_tid(), exctype ) </code></pre> <p>(Based on <a href="http://tomerfiliba.com/recipes/Thread2/" rel="noreferrer">Killable Threads</a> by Tomer Filiba. The quote about the return value of <code>PyThreadState_SetAsyncExc</code> appears to be from an <a href="https://svn.python.org/projects/stackless/Python-2.4.3/dev/Python/pystate.c" rel="noreferrer">old version of Python</a>.)</p> <p>As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption.</p> <p>A good usage pattern of this code is to have the thread catch a specific exception and perform the cleanup. That way, you can interrupt a task and still have proper cleanup.</p>
<blockquote> <p><strong>This is a bad answer, see the comments</strong></p> </blockquote> <p>Here's how to do it:</p> <pre><code>from threading import * ... for thread in enumerate(): if thread.isAlive(): try: thread._Thread__stop() except: print(str(thread.getName()) + ' could not be terminated')) </code></pre> <p>Give it a few seconds then your thread should be stopped. Check also the <code>thread._Thread__delete()</code> method.</p> <p>I'd recommend a <code>thread.quit()</code> method for convenience. For example if you have a socket in your thread, I'd recommend creating a <code>quit()</code> method in your socket-handle class, terminate the socket, then run a <code>thread._Thread__stop()</code> inside of your <code>quit()</code>.</p>
41,943
<p>I want to start a new project with Java; </p> <p>In the past I used to start with Struts + Tiles; but tiles was very complicated; I don't know the latest version of Tiles; </p> <p>I need your recommendations in details for a good GUI framework; </p> <p>Thanks.</p> <p><strong>Duplicate of <a href="https://stackoverflow.com/questions/24596/what-web-application-framework-for-java-is-recommended">this question</a>.</strong></p>
<p>There is no "best" framework... Indeed, "best" really depends on your needs, on your knwoledges (it can cost a lot of time to learn a new framework)...</p>
<p>I personally like <a href="http://tapestry.apache.org/" rel="nofollow noreferrer">Tapestry</a>. I've only used version 4.1 but development time is way faster than JSP or JSF. It allows you to simply refresh pages to immediately see the changes you made without doing a deployment and uses actual HTML for the templates/pages so you can preview them without deploying any code at all. There is a little bit of a learning curve up front but its well worth it. Version 5.0 is in its final beta with a release candidate due out soon but I haven't tried it yet. It's also got pretty good and easy AJAX built in.</p>
33,207
<p>I have found an example for encrypting a web.config during installation <a href="http://madtechnology.wordpress.com/2007/05/04/using-wix-to-secure-a-connection-string/" rel="nofollow noreferrer">here</a>, but my app is a windows service. The <code>aspnetreg_iis</code> method works only for web.config files.</p> <p>I know how to programatically encrypt the config file, but I don't think I can do that using WiX. Am I wrong? Any ideas?</p>
<p>You should be able to do it within a custom action. The catch that I've found is that loading an assembly for an ExeConfigurationFileMap will throw an exception, but you can handle that by adding an AssemblyResolve handler to the AppDomain. This is kind of a hack-up from a rich-client app I wrote to encrypt/decrypt protected configuration sections using a machine encryption key. It's probably not the prettiest code, but I'm hoping you can get the picture from it. This code assumes that you have the ProtectionProvider you want to use defined in the config file.</p> <pre><code>//class global static System.Reflection.Assembly DefiningAssembly; AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler); static System.Reflection.Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) { return DefiningAssembly; } </code></pre> <p>Then, you can load your configuration like this:</p> <pre><code>DefiningAssembly = System.Reflection.Assembly.LoadFrom("path to defining assembly for config"); //Set the Configuration using an ExeConfigurationFileMap - This works for any .config file. ExeConfigurationFileMap CfgMap = new ExeConfigurationFileMap(); CfgMap.ExeConfigFilename = "path to config file"; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(CfgMap, ConfigurationUserLevel.None); List&lt;string&gt; DefiningAssemblyTypes = new List&lt;string&gt;(); foreach (System.Type type in DefiningAssembly.GetExportedTypes()) { DefiningAssemblyTypes.Add(type.Name); } foreach (ConfigurationSection tempSection in config.Sections) { if (DefiningAssemblyTypes.Contains(tempSection.ElementInformation.Type.Name)) { section = tempSection; break; } } ProtectionProviderName = section.SectionInformation.ProtectionProvider.Name; section.SectionInformation.ProtectSection(ProtectionProviderName); config.Save(ConfigurationSaveMode.Minimal, true); </code></pre> <p>I hope this helps you, best of luck.</p>
<p>You should be able to do it within a custom action. The catch that I've found is that loading an assembly for an ExeConfigurationFileMap will throw an exception, but you can handle that by adding an AssemblyResolve handler to the AppDomain. This is kind of a hack-up from a rich-client app I wrote to encrypt/decrypt protected configuration sections using a machine encryption key. It's probably not the prettiest code, but I'm hoping you can get the picture from it. This code assumes that you have the ProtectionProvider you want to use defined in the config file.</p> <pre><code>//class global static System.Reflection.Assembly DefiningAssembly; AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler); static System.Reflection.Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) { return DefiningAssembly; } </code></pre> <p>Then, you can load your configuration like this:</p> <pre><code>DefiningAssembly = System.Reflection.Assembly.LoadFrom("path to defining assembly for config"); //Set the Configuration using an ExeConfigurationFileMap - This works for any .config file. ExeConfigurationFileMap CfgMap = new ExeConfigurationFileMap(); CfgMap.ExeConfigFilename = "path to config file"; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(CfgMap, ConfigurationUserLevel.None); List&lt;string&gt; DefiningAssemblyTypes = new List&lt;string&gt;(); foreach (System.Type type in DefiningAssembly.GetExportedTypes()) { DefiningAssemblyTypes.Add(type.Name); } foreach (ConfigurationSection tempSection in config.Sections) { if (DefiningAssemblyTypes.Contains(tempSection.ElementInformation.Type.Name)) { section = tempSection; break; } } ProtectionProviderName = section.SectionInformation.ProtectionProvider.Name; section.SectionInformation.ProtectSection(ProtectionProviderName); config.Save(ConfigurationSaveMode.Minimal, true); </code></pre> <p>I hope this helps you, best of luck.</p>
39,494
<p>I need to implement auto-capitalization inside of a Telerik RadEditor control on an ASPX page as a user types.</p> <p>This can be an IE specific solution (IE6+).</p> <p>I currently capture every keystroke (down/up) as the user types to support a separate feature called "macros" that are essentially short keywords that expand into formatted text. i.e. the macro "so" could auto expand upon hitting spacebar to "stackoverflow".</p> <p>That said, I have access to the keyCode information, as well I am using the TextRange methods to select a word ("so") and expanding it to "stackoverflow". Thus, I have some semblence of context.</p> <p>However, I need to check this context to know whether I should auto-capitalize. This also needs to work regardless of whether a macro is involved.</p> <p>Since I'm monitoring keystrokes for the macros, should I just monitor for punctuation (it's more than just periods that signal a capital letter) and auto-cap the next letter typed, or should I use TextRange and analyze context?</p>
<p>Have you tried to apply the <a href="http://www.w3.org/TR/CSS2/text.html#caps-prop" rel="noreferrer">text-transform</a> CSS style to your controls?</p>
<p>You pose an interesting question. Acting upon each key press may be more limiting because you will not know what comes immediately after a given keycode (the complexity of undoing a reaction that turns out to be incorrect could mean having to go to a TextRange-based routine anyway). Granted, I haven't wrestled with code on this problem to date, so this is a hypothesis in my head.</p> <p>At any length, here's a Title Casing function (java implementation inspired by a John Gruber blogging automation) which may spur ideas when it comes to handling the actual casing code:</p> <blockquote> <p><a href="http://individed.com/code/to-title-case/" rel="nofollow noreferrer">http://individed.com/code/to-title-case/</a></p> </blockquote>
13,296
<p>My Craftbot Plus Craftware slicer estimates cost per job based on filament prices I add as parameters. What costs per meter would you use? I created spreadsheets to calculate this for 1.75mm diameter filament and arrived at PLA = 6.6 cents per meter, ABS = 6.1 and PET XT = 18.6 cents per meter.</p> <p>Edit: thanks for feedback! I paid \$22 per kilogram for PLA and ABS. I paid \$57 for .75 kilogram of Colorfab XT Black.</p>
<p>This strongly depends on the cost of the spool in question. Prices are not consistent among materials at all; a spool of ABS can cost anywhere from \$15 to \$60 and the same price range applies to pretty much all other plastic.</p> <p>For the purpose of this question I am going to assume that a 1 kilogram spool costs \$25 (regardless of material) but you can scale the figures to what is appropriate for your brand of filament.</p> <p><a href="https://www.toybuilderlabs.com/blogs/news/13053117-filament-volume-and-length" rel="nofollow noreferrer">ToyBuilder Labs</a> lists the density of ABS at 1.04g/ml, whereas PLA is somewhat more dense at 1.25g/ml. As such, a 1kg spool of ABS would be 400 meters (1.75mm filament) or 156 meters (2.85mm filament). PLA would come out to 333 meters (125 meters for 2.85mm filament)</p> <p>We thus have the following costs (cost per meter for 2.85mm filament in parenthesis):</p> <ul> <li><p>ABS: 6.25 cents/meter (16)</p></li> <li><p>PLA: 7.5 cents/meter (20)</p></li> </ul> <p>The density of PETG is roughly the same as PLA, so they have the same cost per meter (for similarly priced spools).</p> <p>In general, to compute the cost per meter, you would use the following formula:</p> <p><span class="math-container">$$[\text{\$/m}]=[\text{cost of 1 }kg] \times [\text{density in }g/mm^3] \times \frac{[\text{diameter in }mm]^2\ \times \pi }{4000}$$</span></p>
<p>The simplest method is to divide spool price by its length. That's obvious I think. If PLA 1.75 (1kg net) has about 120m length and it costs 16usd then it looks like 1m costs arount 13c. =price/length</p> <p>I think everyone can buy different filament at different price from different vendors so there is no good general price to enter into your slicer app. It has to be calculated each time you use new filament.</p> <p>There are also other parts of the price. Electricity, time, wear, depreciation, know-how even the rent is some part of the ending price of the final product. Of course most of them are incalculable as they are permiles or so. But if you don't plan to sell it you can base on the filament price only.</p>
333
<p>which library better for faster java application swt or swing?</p>
<p>Several years ago Swing was slow so SWT was developed to make native API calls on systems. However, Swing performance has greatly improved and this is no longer the case. SWT is non-standard, while Swing is officially part of the Java spec. JavaFX will also be built on top of Swing. Unless your job requires writing Eclipse plugins, I would use Swing.</p> <p>To see a really good app developed in Swing, take a look at Jetbrain's Java IDE. You can try it for 30 days.</p> <p><a href="http://www.jetbrains.com/idea/" rel="noreferrer">http://www.jetbrains.com/idea/</a></p> <p>Of course, Sun's Netbeans is a pure Swing app too and it's free.</p> <p><a href="http://www.netbeans.org/" rel="noreferrer">http://www.netbeans.org/</a></p>
<p>there are more applications written using swing than SWT over the years. But the user-friendliness of SWT on windows is superior compared to Swing. But, there are exceptions(<a href="https://rads.stackoverflow.com/amzn/click/com/0132354802" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/Rich-Client-Programming-Plugging-NetBeans/dp/0132354802</a>) .</p> <p>There is a bigger community of RCP apps developed using SWT. Although the RCP applications using Netbeans is NOT as big, that is considerable.</p> <p>With Java 6 UPDATE 10 coming up soon, the performance of Swing apps should be pretty good. That said, that performance improvement might apply to SWT apps as well.</p> <p>BR,<BR> ~A</p>
23,816
<p>I'm working on what I think is a pretty standard django site, but am having trouble getting my admin section to display the proper fields.</p> <p>Here's my models.py:</p> <pre><code>class Tech(models.Model): name = models.CharField(max_length = 30) class Project(models.Model): title = models.CharField(max_length = 50) techs = models.ManyToManyField(Tech) </code></pre> <p>In other words, a Project can have different Tech objects and different tech objects can belong to different Projects (Project X was created with Python and Django, Project Y was C# and SQL Server)</p> <p>However, the admin site doesn't display any UI for the Tech objects. Here's my admin.py:</p> <pre><code>class TechInline(admin.TabularInline): model = Tech extra = 5 class ProjectAdmin(admin.ModelAdmin): fields = ['title'] inlines = [] list_display = ('title') admin.site.register(Project, ProjectAdmin) </code></pre> <p>I've tried adding the <code>TechInline</code> class to the <code>inlines</code> list, but that causes a </p> <pre><code>&lt;class 'home.projects.models.Tech'&gt; has no ForeignKey to &lt;class 'home.projects.models.Project'&gt; </code></pre> <p>Error. Also tried adding <code>techs</code> to the <code>fields</code> list, but that gives a </p> <blockquote> <p>no such table: projects_project_techs</p> </blockquote> <p>Error. I verified, and there is no <code>projects_project_techs</code> table, but there is a <code>projects_tech</code> one. Did something perhaps get screwed up in my syncdb? </p> <p>I am using Sqlite as my database if that helps.</p>
<blockquote> <p>I've tried adding the TechInline class to the inlines list, but that causes a</p> <p>'TechInLine' not defined</p> </blockquote> <p>Is that a straight copy-paste? It looks like you just made a typo -- try <code>TechInline</code> instead of <code>TechInLine</code>.</p> <p>If your syncdb didn't create the proper table, you can do it manually. Execute this command:</p> <pre><code>python manage.py sqlreset &lt;myapp&gt; </code></pre> <p>And look for the definition for the <code>projects_project_techs</code> table. Copy and paste it into the client for your database.</p>
<p>Assuming your app is called "projects", the default name for your techs table will be projects_tech and the projects table will be projects_project.</p> <p>The many-to-many table should be something like projects_project_techs</p>
19,445
<p>The JPEG compression encoding process splits a given image into blocks of 8x8 pixels, working with these blocks in future lossy and lossless compressions. <a href="http://en.wikipedia.org/wiki/Jpeg#JPEG_codec_example" rel="noreferrer">[source]</a></p> <p>It is also mentioned that if the image is a multiple 1MCU block (defined as a Minimum Coded Unit, 'usually 16 pixels in both directions') that lossless alterations to a JPEG can be performed. <a href="http://en.wikipedia.org/wiki/Jpeg#Lossless_editing" rel="noreferrer">[source]</a></p> <p>I am working with product images and would like to know both if, and how much benefit can be derived from using multiples of 16 in my final image size (say, using an image with size 480px by 360px) vs. a non-multiple of 16 (such as 484x362). In this example I am not interested in further alterations, editing, or recompression of the final image.</p> <p>To try to get closer to a specific answer where I know there must be largely generalities: Given a 480x360 image that is 64k and saved at maximum quality in Photoshop <a href="http://enstxzrnsprxt.6hops.net/Random_Bill_Blass_Pen_and_Pencil_Set___2_PacklewStandard.jpg" rel="noreferrer">[example]</a>:</p> <ul> <li>Can I expect any quality loss from an image that is 484x362</li> <li>What amount of file size addition can I expect (for this example, the additional space would be white pixels)</li> <li>Are there any other disadvantages to growing larger than the 8px grid?</li> </ul> <p>I know it's arbitrary to use that specific example, but it would still be helpful (for me and potentially any others pondering an image size) to understand what level of compromise I'd be dealing with in breaking the non-8px grid.</p> <p>The key issue here is a debate I've had is whether 8-pixel divisible images are higher quality than images that are not divisible by 8-pixels.</p>
<p>8 pixels is the cutoff. The reason is because JPEG images are simply an array of 8x8 DCT blocks; if the image resolution isn't mod8 in both directions, the encoder has to pad the sides up to the next mod8 resolution. This in practice is not very expensive bit-wise; what's much worse are the cases when an image has sharp black lines (such as a letterboxed image) that don't lie on block boundaries. This is especially problematic in video encoding. The reason for this being a problem is that the frequency transform of a sharp line is a Gaussian distribution of coefficients--resulting in an enormous number of bits to code.</p> <p>For those curious, the most common method of padding edges in intra compression (such as JPEG images) is to mirror the lines of pixels before the edge. For example, if you need to pad three lines and line X is the edge, line X+1 is equal to line X, line X+2 is equal to line X-1, and line X+3 is equal to line X-2. This quite effectively minimizes the cost in transform coefficients of the extra lines.</p> <p>In inter coding, however, the padding algorithms generally simply duplicate the last line, because the mirror method does not work well for inter compression, such as in video compression.</p>
<p>What <a href="https://stackoverflow.com/questions/74892/is-there-a-quality-file-size-or-other-benefit-to-jpeg-sizes-being-multiples-of#84213">Tometzky</a> said. If you don't have the correct multiple, the lossless flip and rotate algorithms don't work. That's because the padding on the right/bottom that can be safely ignored now ends up on the left/top, where it can't.</p>
10,053
<p>we have a lot of users running in different shared and solo-owned repositories in Subversion. As part of our work, we do project-shared code and individual work, and we need to control access, ideally on a group basis. Currenly, we use <a href="http://svnmanager.sourceforge.net/" rel="noreferrer">SVNManager</a> to allow users to manage access and create repositories. However, in order to get that working we had to do quite a bit of hacking. </p> <p>Does anyone know of a free, open-source, linux-compatible SVN management system?</p> <p>Thanks for your help.</p>
<p>I would recommend SVN Access: <a href="http://www.jaj.com/projects/svnaccess/" rel="nofollow noreferrer">http://www.jaj.com/projects/svnaccess/</a> or <a href="http://freshmeat.net/projects/svnaccess/" rel="nofollow noreferrer">http://freshmeat.net/projects/svnaccess/</a> I have used it as is, and have modified it for an enterprise-wide solution at my day job.</p>
<p>I use KDESVN. Once it's set up it works great, but you only get one chance to set up your branch structure, so plan to create a test repository first.</p>
3,601
<p>There seem to be so many color wheel, color picker, and color matcher web apps out there, where you give one color and the they'll find a couple of other colors that will create a harmonic layout when being used in combination. However most of them focus on background colors only and any text printed on each background color (if text is printed at all in the preview) is either black or white.</p> <p>My problem is different. I know the background color I want to use for a text area. What I need help with is choosing a couple of colors (the more, the merrier) I can use as font colors on this background. Most important is that the color will make sure the font is readable (contrast not being too low, also maybe not being too high to avoid that eyes are stressed) and of course that the combination of foreground and background just looks good.</p> <p>Anyone being aware of such an application? I'd prefer a web application to anything I have to download. Thanks.</p>
<p>If you need an algorithm, try this: Convert the color from RGB space to HSV space (Hue, Saturation, Value). If your UI framework can't do it, check this article: <a href="http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV" rel="noreferrer">http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV</a></p> <p>Hue is in [0,360). To find the "opposite" color (think colorwheel), just add 180 degrees: </p> <pre><code>h = (h + 180) % 360; </code></pre> <p>For saturation and value, invert them:</p> <pre><code>l = 1.0 - l; v = 1.0 - v; </code></pre> <p>Convert back to RGB. This should always give you a high contrast even though most combinations will look ugly.</p> <p>If you want to avoid the "ugly" part, build a table with several "good" combinations, find the one with the least difference</p> <pre><code>def q(x): return x*x def diff(col1, col2): return math.sqrt(q(col1.r-col2.r) + q(col1.g-col2.g) + q(col1.b-col2.b)) </code></pre> <p>and use that.</p>
<p>Have you considered letting the user of your application select their own color scheme? Without fail you won't be able to please all of your users with your selection but you can allow them to find what pleases them.</p>
38,746
<p>I've noticed that the wmd editor can either output HTML or markdown. Does it make more sense to store the user input (in a database) as markdown or HTML? If as markdown, what is the best way to display it on a webpage later on (any examples would be greatly appreciated).</p> <p>Given that the recommendation is store it as markdown, are there any standard converters / stylesheets / anything else to actually display it afterwards?</p>
<p>I would say it's easier to store the markdown in the database, and process it into HTML when you display it.</p> <p>You <em>could</em> store the input as HTML, then when the user wants to edit it, use something like <a href="http://milianw.de/projects/markdownify/" rel="noreferrer">markdownify</a> to convert it back to markdown - but you don't really gain anything, and lose a lot (the original markdown formatting, for one). It's also rather round-a-bout (you convert the markdown to HTML, store it. Then convert the HTML to markdown, allow the user to edit it, convert it back to HTML, and store that..)</p> <p>If you are worried about performance of parsing markdown on every page-view: cache the output HTML somewhere temporary (in memory, or on disc). The HTML is easier to recreate than the source markdown</p>
<p>It looks like there are details on how to generate the corresponding HTML for saved markdown on <a href="https://stackoverflow.com/questions/125911/saving-contents-of-the-wmd-editor-control">another thread</a>.</p>
31,874
<p>Using reflection, I need to investigate a user DLL and create an object of a class in it.</p> <p>What is the simple way of doing it?</p>
<p>Try <a href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx" rel="noreferrer">Activator.CreateInstance</a>. </p>
<p>You can create an instance of a class from a Type object using Activator.CreateInstance, to get all types in a dll you can use Assembly.GetTypes</p>
7,718
<p>I have a class that contains a bunch of properties. It is a mistake by a programmer if they call ToString() on an object of that type. Take this example code:</p> <pre><code>using System; public class Foo { public int ID = 123; public string Name = "SomeName"; private string ToString() { return null; } } public class MyClass { public static void Main() { Foo myObj = new Foo(); WL("I want this to be a compiler error: {0}", myObj.ToString()); RL(); } #region Helper methods private static void WL(object text, params object[] args) { Console.WriteLine(text.ToString(), args); } private static void RL() { Console.ReadLine(); } #endregion } </code></pre> <p>You could reason that if ID is what most people want written out as a string, then I should implement ToString so that it returns the ID. However, I believe that is a bad practice because programmers will "accidentally" get working code. A programmer using my class should specify what they want.</p> <p>Instead, what I would like is if someone calls myObj.ToString() to have that show up as a compile time error. I thought I could do that by creating a private ToString() function, but that doesn't work.</p> <p>The reason I brought this up is that we ended up with a query string that contained the fully qualified class name rather then an ID. </p> <p>So the question is: <strong>Is there any way to "hide" the ToString() function so that calling it on an object of my class causes a compiler error?</strong></p>
<p><strong>I cannot stress enough how bad an idea this design is.</strong> </p> <p><code>ToString()</code> is part of the object contract in .Net. If you don't want to implement it then don't override it, and just let it return the type info. What harm could that possible cause?</p> <p>I don't mean to be so negative, but I am absolutely floored that someone would want to get rid of <code>ToString()</code>.</p> <p><strong>Some additional points:</strong></p> <ol> <li><p>Why do the programmers using this class assume that <code>ToString()</code> will return an ID? Are other classes in your ecosystem doing this? One can argue that <code>ToString()</code> should return some meaningful data. But you really shouldn't be programming against the results of a <code>ToString()</code> call. <code>ToString()</code> is for a string representations of the class, period. This sounds like an education or communication issue between programmers or departments.</p></li> <li><p>Crippling <code>ToString()</code> in any way, whether you can figure out how to at compile time or by throwing an exception at run time, will have ripples. I have <em>never</em> seen this done, and would not expect any class I am using to exhibit this behavior. I think most programmers would have the same expectations. Will future programmers that use your class expect this? What bugs and maintenance nightmares are you causing down the road?</p></li> <li><p>What impact does this have in the IDE or debugger, which rely on <code>ToString()</code>?</p></li> <li><p>What impact will this have when using databinding technologies that don't bind against a specific type, but use reflection at run-time to pull out values? Most databinding will fall back to calling <code>ToString()</code> on an object if a member is not specified to use.</p></li> </ol>
<p>Please, consider your design/opinion to be changed :)</p> <p>First of all, definition of Foo.ToString does not define an override for Object.ToString() but a new one and should be prefixed with "new" keyword to prevent misunderstanding of semantics. Or explicitly declare an "override". IMHO, compiler issues corresponding warning.</p> <p>Even if you'll find a way to prohibit a call to Foo.ToString, it will be prohibited at compile time only when type of "this" is known to be Foo or descendant, but ((object) foo).ToString() will be a <em>correct</em> workaround, because ToString is a method of Object interface.</p> <p>Also, preventing a call of ToString is undesirable since Debugger uses it to present a value. SY, Jake</p>
26,934
<p>In order to create the proper queries I need to be able to run a query against the same datasource that the report is using. How do I get that information <strong>programatically</strong>? Preferably the connection string or pieces of data used to build the connection string.</p>
<pre><code>DataSourceDefinition dataSourceDefinition = reportingService.GetDataSourceContents("DataSourceName"); string connectionString = dataSourceDefinition.ConnectString; </code></pre>
<p>If you have the right privileges you can can go to <a href="http://servername/reports/" rel="nofollow noreferrer">http://servername/reports/</a> and view the data source connection details through there. </p>
14,848
<p>Installed Tomcat 6 on WinXP 64. It installed just fine. But when I try to launch it ( from Windows Services) I get the following error : "Can not start an the Apache Tomcat Service on Local computer." error 216:0xd8</p>
<p>It's well known issue.</p> <p>Tomcat wrapper for windows service is compiled for 32 bits JDK.</p> <p>Steps that should allow you to install Tomcat as windows service under JDK64bits.</p> <ol> <li><p>Download Tomcat binary installation (zip file; exe file will not find 64 bits JDK/JRE).</p></li> <li><p>Extract files from the archive.</p></li> <li><p>Rename tomcat5.exe (tomcat6.exe) to tomcat5.exe.32bits to (tomcat6.exe.32bits)</p></li> <li><p>Extract 64 bits Tomcat wrapper from tomcat5_5_64bits_wrapper.zip and rename it to tomcat5.exe (tomcat6.exe). See <a href="http://blog.datajelly.com/company/blog/35-running-tomcat-as-a-64-bit-windows-service.html" rel="noreferrer">details are here</a>. (Update: The Bugzilla post seems to be down, but I believe an updated exe file can be found in the <a href="http://svn.apache.org/viewvc/tomcat/tc6.0.x/tags/TOMCAT_6_0_16/res/procrun/amd64/" rel="noreferrer">Tomcat SVN Repository</a>).</p></li> <li><p>Install it as Windows service executing "service.bat install [Tomcat instance name]", where [Tomcat instance name] is optional windows service name.</p></li> <li><p>Under certain conditions tomcat is not correctly configure service registry values. It points out itself to 32 bits version of JRE/JDK instead of 64 bits. It can be done explicitly (path to wrong JDK/JRE) or implicitly ("auto" value that imply using of JAVA_HOME or JRE_HOME that point out to 32 bits version). Anyway, it's highly recommented check registry value that define which version of JDK/JRE will be used for tomcat windows service, see key HKEY_LOCAL_MACHINE\SOFTWARE\Apache Software Foundation\Procrun 2.0[Tomcat instance name]\Parameters\Log\jvm and point it out to correct 64 bits JDK/JRE (e.g. jvm=C:\Program Files\Java\jdk1.5.0_15\jre\bin\server\jvm.dll).</p></li> </ol>
<p>Just modify step 6 so you put it in java instead of log in the registry value</p> <ol start="6"> <li>Under certain conditions tomcat is not correctly configure service registry values. It points out itself to 32 bits version of JRE/JDK instead of 64 bits. It can be done explicitly (path to wrong JDK/JRE) or implicitly ("auto" value that imply using of JAVA_HOME or JRE_HOME that point out to 32 bits version). Anyway, it's highly recommented check registry value that define which version of JDK/JRE will be used for tomcat windows service, see key HKEY_LOCAL_MACHINE\SOFTWARE\Apache Software Foundation\Procrun 2.0[Tomcat instance name]\Parameters*java*\jvm and point it out to correct 64 bits JDK/JRE (e.g. jvm=C:\Program Files\Java\jdk1.5.0_15\jre\bin\server\jvm.dll).</li> </ol>
25,982
<p>Trying to write a PowerShell cmdlet that will mute the sound at start, unless already muted, and un-mute it at the end (only if it wasn't muted to begin with). Couldn't find any PoweShell or WMI object I could use. I was toying with using Win32 functions like <a href="http://msdn.microsoft.com/en-us/library/ms706237(VS.85).aspx" rel="noreferrer">auxGetVolume</a> or <a href="http://msdn.microsoft.com/en-us/library/ms706237(VS.85).aspx" rel="noreferrer">auxSetVolume</a>, but couldn't quite get it to work (how to read the values from an IntPtr?).</p> <p>I'm using V2 CTP2. Any ideas folks?</p> <p>Thanks!</p>
<p>Use the following commands on a ps1 powershell script:</p> <pre><code>$obj = new-object -com wscript.shell $obj.SendKeys([char]173) </code></pre>
<p>In the second script above, to work in PowerShell 7 or PowerShell Core in the 1st line change:</p> <pre><code>-Language CsharpVersion3 </code></pre> <p>to...</p> <pre><code>-Language Csharp </code></pre> <p>Working on W10</p>
31,866
<p>I'm trying to use multiple attributes in my custom tag, e.g.:</p> <pre><code>&lt;mytaglib:mytag firstname="Thadeus" lastname="Jones" /&gt; </code></pre> <p>How can I access the attributes in the TagHandler code?</p>
<p>In order to access the parameters your TagHandler class should define the private members and provide accessor methods.</p> <pre><code>public class TagHandler extends TagSupport { private String firstName; private String lastName; public void setFirstName(String firstname) { firstName = firstname; } public void setLastName(String lastname) { lastName = lastname;} } </code></pre> <p>you can then access the parameters through the TagHandler variables.</p> <pre><code>public int doStartTag() throws JspException { pageContext.getOut().print(lastName + ", " + firstName); } </code></pre> <p>If you still have problems double check your naming conventions, the Java interpeter is trying to guess what the setter method is. So if your parameter is "FirstName" than the set method must be "setFirstName" if the parameter is "lastname" the set parameter must be "setlastname". I perfer to follow the former, since it is the standard Java naming convention.</p>
<p>To demonstrate the solution of this problem lets take an analogy . Suppose we have "userName" and "password" which is retrieved from index.jsp and we have to pass our data in custom tag attribute. In my case its working</p> <pre><code>&lt;body&gt; &lt;% String name=request.getParameter("name"); String password=request.getParameter("password"); %&gt; &lt;%@ taglib prefix="c" uri="/WEB-INF/mytag.tld" %&gt; &lt;c:logintag name="&lt;%=name %&gt;" password="&lt;%=password %&gt;"/&gt; </code></pre> <p></p>
27,759
<p>I'm trying to do a Data Binding in the C# code behind rather than the XAML. The XAML binding created in Expression Blend 2 to my CLR object works fine. My C# implementation only updates when the application is started after which subsequent changes to the CLR doesn't update my label content. </p> <p>Here's the working XAML binding. First a ObjectDataProvider is made in my Window.Resources.</p> <pre><code>&lt;ObjectDataProvider x:Key="PhoneServiceDS" ObjectType="{x:Type kudu:PhoneService}" d:IsDataSource="True"/&gt; </code></pre> <p>And the label content binding:</p> <pre><code>&lt;Label x:Name="DisplayName" Content="{Binding Path=MyAccountService.Accounts[0].DisplayName, Mode=OneWay, Source={StaticResource PhoneServiceDS}}"/&gt; </code></pre> <p>Works great. But we want this set up in C# so we can independently change the XAML (ie. new skins). My one time working C# as follows:</p> <pre><code> Binding displayNameBinding = new Binding(); displayNameBinding.Source = PhoneService.MyAccountService.Accounts[0].DisplayName; displayNameBinding.Mode = BindingMode.OneWay; this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding); </code></pre> <p>This is inside my MainWindow after InitializeComponent();</p> <p>Any insight why this only works on startup?</p>
<p>Your C# version does not match the XAML version. It should be possible to write a code version of your markup, though I am not familiar with ObjectDataProvider.</p> <p>Try something like this:</p> <pre><code>Binding displayNameBinding = new Binding( "MyAccountService.Accounts[0].DisplayName" ); displayNameBinding.Source = new ObjectDataProvider { ObjectType = typeof(PhoneService), IsDataSource = true }; displayNameBinding.Mode = BindingMode.OneWay; this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding); </code></pre>
<p>Write this inside Loaded event instead of Constructor. Hope you implmented INotifyPropertyChanged triggered on the DisplayName property setter? </p>
46,556
<p>I'd like to use the <a href="https://developer.mozilla.org/en/Rhino_JavaScript_Compiler" rel="nofollow noreferrer">Rhino JavaScript</a> compiler to compile some JavaScript to .class bytecode files for use in a project. It seems like this should already exist, since there are groovyc, netrexxc, and jythonc tasks for Groovy, NetREXX(!) and Jython, respectively. Has anyone used or written such an Ant task, or can anyone provide some tips on how to write one?</p> <p>Ideally it would have some way to resolve dependencies among JavaScript or Java classes.</p>
<p>Why not simply use java task?</p> <pre><code>&lt;java fork="yes" classpathref="build.path" classname="org.mozilla.javascript.tools.jsc.Main" failonerror="true"&gt; &lt;arg value="-debug"/&gt; ... &lt;arg value="file.js"/&gt; &lt;/java&gt; </code></pre> <p>Any objections?</p>
<p>Here is a sample build.xml I use for my rhino applications. If you have lots of javascript files you just need to keep adding more tags<br /> ~:ant compile jar run</p> <pre><code>&lt;project&gt; &lt;target name="compile"&gt; &lt;mkdir dir="build/classes"/&gt; &lt;java fork="yes" classpath="js.jar" classname="org.mozilla.javascript.tools.jsc.Main" failonerror="true"&gt; &lt;arg value="-nosource"/&gt; &lt;arg value="-opt"/&gt; &lt;arg value="9"/&gt; &lt;arg value="-version"/&gt; &lt;arg value="170"/&gt; &lt;arg value="src/SwingApplication.js"/&gt; &lt;/java&gt; &lt;move todir="build/classes"&gt; &lt;fileset dir="src"&gt; &lt;include name="**/*.class"/&gt; &lt;/fileset&gt; &lt;/move&gt; &lt;/target&gt; &lt;target name="jar"&gt; &lt;mkdir dir="build/jar"/&gt; &lt;jar destfile="build/jar/SwingApplication.jar" basedir="build/classes"&gt; &lt;zipfileset src="js.jar" includes="**/*.class"/&gt; &lt;manifest&gt; &lt;attribute name="Main-Class" value="SwingApplication"/&gt; &lt;/manifest&gt; &lt;/jar&gt; &lt;/target&gt; &lt;target name="run"&gt; &lt;exec executable="java"&gt; &lt;arg valUe="-jar"/&gt; &lt;arg value="build/jar/SwingApplication.jar"/&gt; &lt;/exec&gt; &lt;/target&gt; &lt;/project&gt; </code></pre> <p>~ </p>
28,665
<p>I'm trying to parse a simple string in C++. I know the string contains some text with a colon, followed immediately by a space, then a number. I'd like to extract just the number part of the string. I can't just tokenize on the space (using sstream and &lt;&lt;) because the text in front of the colon may or may not have spaces in it.</p> <p>Some example strings might be:</p> <blockquote> <p>Total disk space: 9852465</p> <p>Free disk space: 6243863</p> <p>Sectors: 4095</p> </blockquote> <p>I'd like to use the standard library, but if you have another solution you can post that too, since others with the same question might like to see different solutions.</p>
<pre><code>std::string strInput = "Total disk space: 9852465"; std::string strNumber = "0"; size_t iIndex = strInput.rfind(": "); if(iIndex != std::string::npos &amp;&amp; strInput.length() &gt;= 2) { strNumber = strInput.substr(iIndex + 2, strInput.length() - iIndex - 2) } </code></pre>
<pre><code>const std::string pattern(": "); std::string s("Sectors: 4095"); size_t num_start = s.find(pattern) + pattern.size(); </code></pre>
45,132
<p>I am working with a generic data structure, say <code>MyGeneric&lt;Type&gt;</code>. There is a case where I have to iterate over all the values it holds </p> <p>The code I am trying to do.</p> <pre><code>for ( all the keys in myGeneric ) { // do lot of stuff here } </code></pre> <p>Now the generic can hold base type as double and string and it can hold some user-defined type also. There is a particular situation where I have to some specific work depending upon the type of the generic. </p> <p>so the final code block looks something like this</p> <pre><code>for( all the keys in myGeneric ) { if key is type foo then //do foo foo else if key is of type bar //do bar bar } </code></pre> <p>Now, as complexity sensitive as I am I do not like to have an if condition in the for loop. So the next solution I did was </p> <pre><code>if myGeneric is of type foo call fooIterator(myGeneric) if myGenric is of type bar call barItetrator(myGeneric) function FooIterator() { // ..... // foo work //...... } function BarItetrator() { // ..... // bar work //...... } </code></pre> <p>Then again when somebody sees my code then I am quite sure that they will shout where is the "refactoring".</p> <p>What is the ideal thing to do in this situation ?</p> <p>Thanks.</p>
<p>Well, you could use the Linq <code>OfType&lt;T&gt;</code> method, and multiple loops?</p> <pre><code>foreach(Foo foo in list.OfType&lt;Foo&gt;()) { // } foreach(Bar bar in list.OfType&lt;Bar&gt;()) { // } </code></pre> <p>Beyond that, you're into conditional statements. I did look at this <a href="https://stackoverflow.com/questions/156467/switch-pattern-matching-idea">here</a> in relation to F#, which does this more cleanly.</p> <p>As an aside; if this was using PushLINQ (in <a href="http://www.pobox.com/~skeet/csharp/miscutil/" rel="nofollow noreferrer">MiscUtil</a>) you could do this in a single iteration, by pushing the different types through different branches - not sure it warrants it just for this, though.</p>
<p>I think your second option reads a little better. Specially if the foo/bar work contains a lot of code. In terms of performance, I expect a marginal lost in calling a method but I don't think it will affect you.</p>
49,890
<p>Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elements? In other words, assuming you have an array <code>@myarray</code> and a hash <code>%myhash</code>, why do you need to do:</p> <pre><code>$x = $myarray[1]; $y = $myhash{'foo'}; </code></pre> <p>instead of just doing :</p> <pre><code>$x = myarray[1]; $y = myhash{'foo'}; </code></pre> <p>Why are the above ambiguous? </p> <p>Wouldn't it be illegal Perl code if it was anything but a $ in that place? For example, aren't all of the following illegal in Perl?</p> <pre><code>@var[0]; @var{'key'}; %var[0]; %var{'key'}; </code></pre>
<p>Slices aren't illegal:</p> <pre><code>@slice = @myarray[1, 2, 5]; @slice = @myhash{qw/foo bar baz/}; </code></pre> <p>And I suspect that's part of the reason why you need to specify if you want to get a single value out of the hash/array or not. </p>
<p>The sigil provides the context for the access:</p> <ul> <li><code>$</code> means scalar context (a scalar variable or a single element of a hash or an array)</li> <li><code>@</code> means list context (a whole array or a slice of a hash or an array)</li> <li><code>%</code> is an entire hash</li> </ul>
18,553
<p>How to implement multi-threading in visual basic 6.0. It would be great if someone can give an example.</p>
<p>VB6 is not a really good environment for multi-threaded applications. There is no out-of-the-box support, you need to delve into standard <strong>WinAPI</strong> functions. Take a look at this article, which provides quite a comprehensive sample:</p> <p><a href="http://www.freevbcode.com/ShowCode.Asp?ID=1287" rel="noreferrer">http://www.freevbcode.com/ShowCode.Asp?ID=1287</a></p>
<p>You can use the Interop Forms Toolkit 2.0 for multithreading in VB6. The Toolkit allows you to take advantage of .NET features without being forced onto an upgrade pat. Thus you can also use .NET User Controls as ActiveX controls in VB6.</p>
13,517
<p>I build websites for a small-ish media company. Unfortunately, around 45-50% of our client base uses IE6, while the other half are pretty much equally split between Firefox and Webkit-based browsers, with a sprinkling of Opera users.</p> <p>I start every one of my sites with a reset stylesheet similar to Eric Meyer's, with a few modificaions. I've been using the Blueprint CSS "framework" a lot recently, and it's made my life a lot easier, though I am not especially attached to it.</p> <p>Roughly 60% of my development time is spent making sure the sites I create don't look incredibly different in each browser. I code for Firefox 3 then tweak from there.</p> <p>Does anyone know of any stylesheets/frameworks out there that attempt to preemptively account for all of those stupid little browser quirks? I know that nothing out there can totally account for all the browser weirdness, but it would be nice to have something a little more solid to start with.</p> <p>I'm working on creating my own, but it would be nice to have something to start with.</p>
<p>Take a look at <a href="http://www.yaml.de/en/home.html" rel="nofollow noreferrer">YAML</a>.</p>
<p>Have you looked at the Yahoo YUI stuff? They have a cross-browser CSS Framework.</p>
10,244
<p>I have an int array as a property of a Web User Control. I'd like to set that property inline if possible using the following syntax:</p> <pre><code>&lt;uc1:mycontrol runat="server" myintarray="1,2,3" /&gt; </code></pre> <p>This will fail at runtime because it will be expecting an actual int array, but a string is being passed instead. I can make <code>myintarray</code> a string and parse it in the setter, but I was wondering if there was a more elegant solution.</p>
<p>Implement a type converter, here is one, warning : quick&amp;dirty, not for production use, etc :</p> <pre><code>public class IntArrayConverter : System.ComponentModel.TypeConverter { public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { string val = value as string; string[] vals = val.Split(','); System.Collections.Generic.List&lt;int&gt; ints = new System.Collections.Generic.List&lt;int&gt;(); foreach (string s in vals) ints.Add(Convert.ToInt32(s)); return ints.ToArray(); } } </code></pre> <p>and tag the property of your control :</p> <pre><code>private int[] ints; [TypeConverter(typeof(IntsConverter))] public int[] Ints { get { return this.ints; } set { this.ints = value; } } </code></pre>
<p>Do do what Bill was talking about with the list you just need to create a List property on your user control. Then you can implement it as Bill described.</p>
14,229
<p>Grails vs Rails. Which has better support? And which one is a better choice to develop medium size apps with? Most importantly which one has more plug-ins?</p>
<p>One other thing worth mentioning: the design philosophy of both framework is somewhat different when it comes to the model. Grails is more "domain-oriented" while Rails is more "database-oriented".<br> In Rails, you essentially start by defining your tables (with field names and their specifics). Then ActiveRecord will map them to Ruby classes or models.<br> In Grails, it's the reverse: you start by defining your models (Groovy classes) and when you hit run, GORM (Grails ActiveRecord equivalent) will create the related database and tables (or update them). Which may also be why you don't have the concept of 'migrations' in Grails (although I think it will come in some future release).<br> I don't know if one is better than the other. I guess it depends on your context.</p> <p>This being said, I'm still myself wondering which one to choose. As Tom was saying, if you're dependent on Java you can still go for JRuby - so Java reuse shouldn't be your sole criterion.</p>
<p>I have used turbogears and rails a little bit. Before using rails, I tried using grails because I was using groovy for my scripting. Grails was a difficult experience. </p> <p>The groovy call stack is difficult to read for a small program, but when you add in several heavy weight frameworks a simple error can yield 100s of lines. Unlike rails the grails version that I was using didn't have tools to help me determine what was mine and what belonged to the framework.</p> <p>I eventually switched to using the Google Web toolkit since I really didn't need the database.</p> <p>I think Grails and Groovy hold promise, but the user experience of working with them is cumbersome at present (present being last spring).</p>
10,755
<p>How do you check if a one-character String is a letter - including any letters with accents?</p> <p>I had to work this out recently, so I'll answer it myself, after the recent VB6 question reminded me.</p>
<p>Just checking if a letter is in A-Z because that doesn't include letters with accents or letters in other alphabets.</p> <p>I found out that you can use the regular expression class for 'Unicode letter', or one of its case-sensitive variations:</p> <pre><code>string.matches("\\p{L}"); // Unicode letter string.matches("\\p{Lu}"); // Unicode upper-case letter </code></pre> <p>You can also do this with <em>Character</em> class:</p> <pre><code>Character.isLetter(character); </code></pre> <p>but that is less convenient if you need to check more than one letter.</p>
<p>Character.isLetter() is much faster than string.matches(), because string.matches() compiles a new Pattern every time. Even caching the pattern, I think isLetter() would still beat it.</p> <hr> <p><strong>EDIT:</strong> Just ran across this again and thought I'd try to come up with some actual numbers. Here's my attempt at a benchmark, checking all three methods (<code>matches()</code> with and without caching the <code>Pattern</code>, and <code>Character.isLetter()</code>). I also made sure that there were both valid and invalid characters checked, so as not to skew things.</p> <pre><code>import java.util.regex.*; class TestLetter { private static final Pattern ONE_CHAR_PATTERN = Pattern.compile("\\p{L}"); private static final int NUM_TESTS = 10000000; public static void main(String[] args) { long start = System.nanoTime(); int counter = 0; for (int i = 0; i &lt; NUM_TESTS; i++) { if (testMatches(Character.toString((char) (i % 128)))) counter++; } System.out.println(NUM_TESTS + " tests of Pattern.matches() took " + (System.nanoTime()-start) + " ns."); System.out.println("There were " + counter + "/" + NUM_TESTS + " valid characters"); /*********************************/ start = System.nanoTime(); counter = 0; for (int i = 0; i &lt; NUM_TESTS; i++) { if (testCharacter(Character.toString((char) (i % 128)))) counter++; } System.out.println(NUM_TESTS + " tests of isLetter() took " + (System.nanoTime()-start) + " ns."); System.out.println("There were " + counter + "/" + NUM_TESTS + " valid characters"); /*********************************/ start = System.nanoTime(); counter = 0; for (int i = 0; i &lt; NUM_TESTS; i++) { if (testMatchesNoCache(Character.toString((char) (i % 128)))) counter++; } System.out.println(NUM_TESTS + " tests of String.matches() took " + (System.nanoTime()-start) + " ns."); System.out.println("There were " + counter + "/" + NUM_TESTS + " valid characters"); } private static boolean testMatches(final String c) { return ONE_CHAR_PATTERN.matcher(c).matches(); } private static boolean testMatchesNoCache(final String c) { return c.matches("\\p{L}"); } private static boolean testCharacter(final String c) { return Character.isLetter(c.charAt(0)); } } </code></pre> <p>And my output:</p> <pre>10000000 tests of Pattern.matches() took 4325146672 ns. There were 4062500/10000000 valid characters 10000000 tests of isLetter() took 546031201 ns. There were 4062500/10000000 valid characters 10000000 tests of String.matches() took 11900205444 ns. There were 4062500/10000000 valid characters</pre> <p>So that's almost 8x better, even with a cached <code>Pattern</code>. (And uncached is nearly 3x worse than cached.)</p>
11,959
<p>How to get to know DNS name of the server where ASP.NET application is run?</p> <p>I want to get string "www.somehost.com" if my application URL is <a href="http://www.somehost.com/somepath/application.aspx" rel="nofollow noreferrer">http://www.somehost.com/somepath/application.aspx</a></p> <p>Is there some property of Server, Contex, Session or Request objects for this?</p> <p>Thanks!</p>
<p>This will get you the DNS IP for the server that is hosting the web site</p> <pre><code>void GetDNSServerAddress() { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface ni in nics) { if (ni.OperationalStatus == OperationalStatus.Up) { IPAddressCollection ips = ni.GetIPProperties().DnsAddresses; foreach (System.Net.IPAddress ip in ips) { Console.Write(ip.ToString()); } } } } </code></pre> <p>However, while writing this ive just seen your edited post, so i think this is what you are after is simply:</p> <pre><code>string host = Request.Url.Scheme + "://" + Request.Url.Host; </code></pre> <p>Hope this helps!</p>
<p>The HTTP_HOST server variable can give you what you need.</p> <pre><code>Request.ServerVariables("HTTP_HOST") </code></pre>
36,466
<ul> <li>I am curious, what is the purpose of printing a single-height outline around the objects to be printed?</li> <li>Also, how would it affect the outline if the object to be printed extends to (very near) the very edge of the print area?</li> </ul> <p><a href="https://i.stack.imgur.com/vEr8Z.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vEr8Z.png" alt="finished print on print bed, with outlines annotated"></a></p> <p>Update, I received a hint that an existing question has the answer; that link was not really to my satisfaction -- but it did link to another one that did: <a href="https://3dprinting.stackexchange.com/questions/20/what-are-main-differences-between-rafts-skirts-and-brims">What are main differences between rafts, skirts and brims?</a></p>
<blockquote> <p>I am curious, what is the purpose of printing a single-height outline around the objects to be printed?</p> </blockquote> <p>The (equidistant) lines at distance from the print object is called the "skirt", the skirt is an option found under the "Build Plate Adhesion" options in your slicer. The primary function of the skirt is to get the flow going, but there are more benefits you can get from the skirt:</p> <ul> <li>You can find out whether the bed is correctly levelled, or if the bed has concave or convex areas (the skirt should be a line, I prefer at least 2 lines, of consistent thickness, if not, this may hint to incorrect levelling;</li> <li>You can find out if there is enough or a sufficient amount of adhesive (e.g. glue stick, hair spray, specific print adhesion sprays like 3DLAC or DimaFix, etc), if not the bed might be greasy or lacking the adhesion product;</li> <li>You can configure the skirt height to use the skirt as a shield for draft or ooze and distance to product);</li> </ul> <blockquote> <p>Also, how would it affect the outline if the object to be printed extends to (very near) the very edge of the print area?</p> </blockquote> <p>Do note that a skirt limits the useable build area by the distance and width of the skirt.</p> <hr> <p><em>Basically this has been answered (see <a href="/a/11303">this answer</a> and <a href="/a/11304">this answer</a>) in a different question (<a href="https://3dprinting.stackexchange.com/questions/11300/random-lines-are-being-printed">"Random lines are being printed?"</a>), but it might be beneficial to answer this question rather than closing this for a dupe. This question is focussed on the skirt, the equidistant lines around the print object, while the other question focuses on the priming line.</em></p> <hr>
<p>My understand is that's is basically a purging extrusion, so that you get flow through the extruder before you start printing the object, as filament that's been inside the hotend during warm-up might have been "overcooked" by spending too much time in the hotend at temperature. It also helps stabilise the PID loop controlling the extruder temperature by allowing the PID loop to stabilise the temperature of the hotend as it's got filament flowing through it compared to it being idle. </p> <p>It also shows the user where it intends to start printing, which is a useful check if something went wrong with Gcode generation. </p>
1,640
<p>I was wondering if it is possible to not attach Excel sheet if it is empty, and maybe write a different comment in the email if empty.</p> <p>When I go to report delivery options, there's no such configuration.</p> <p><strong>Edit</strong>: I'm running SQL Server Reporting Services 2005.</p> <p>Some possible workarounds as mentioned below:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms152934(SQL.90).aspx" rel="nofollow noreferrer">MSDN: Reporting Services Extensions</a></p> <p><a href="http://technet.microsoft.com/es-es/library/microsoft.reportingservices.reportrendering.table.norows(SQL.90).aspx" rel="nofollow noreferrer">NoRows and NoRowsMessage properties</a></p> <p>I should look into these things.</p>
<p>I believe the answer is no, at least not out of the box. It shouldn't be difficult to write your own delivery extension given the printing delivery extension sample included in RS.</p>
<p>I have had success with using a Data-Driven Subscription and a table containing my subscribers, with the data-driven subscription query looking like this:</p> <pre><code>SELECT * FROM REPORT_SUBSCRIBERS WHERE EXISTS (SELECT QUERY_FROM_YOUR_REPORT) </code></pre> <p>In the delivery settings, the recipient is the data column containing my email addresses.<br> If the inner query returns no rows, then no emails will be sent.</p> <hr> <p>For your purposes, you can take advantage of the "Include Report" and "Comment" delivery settings.<br> I imagine that a data-driven subscription query like this will work for you:</p> <pre><code>SELECT 'person1@domain.com; person2@domain.com' AS RECIPIENTS, CASE WHEN EXISTS (REPORT_QUERY) THEN 'TRUE' ELSE 'FALSE' END AS INCLUDE_REPORT, CASE WHEN EXISTS (REPORT_QUERY) THEN 'The report is attached' ELSE 'There was no data in this report' END AS COMMENT </code></pre> <p>Then use those columns in the appropriate fields when configuring the delivery settings for the subscription.</p>
19,159
<p>Does anyone know of any reverse proxy solutions that allow the content/data of an HTTP response to be directly modified before being relayed to the requesting client?</p> <p>As an example:</p> <p>Proxy relays client request for pdf document to another server, response received by proxy, watermark added to pages of pdf, watermarked pdf is returned to client.</p> <p>Regards, Mike </p>
<p>Apache has <a href="http://httpd.apache.org/docs/2.0/mod/mod_proxy.html" rel="nofollow noreferrer"><code>mod_proxy</code></a> and <a href="http://apache.webthing.com/mod_proxy_html/" rel="nofollow noreferrer"><code>mod_proxy_html</code></a>, which is used to rewrite links, headers, etc. I've only ever seen HTML or XML filters, but you should be able to write your own binary one for your PDF needs. The possible difficulty I could see is that Apache treats webpages as a stream, rather than a file. I'm not sure how to watermark a PDF doc, but if you need access to the entire file to do it, it might get complicated quickly.</p> <p>Note that it would seem far easier to me to do the watermarking on the server, where you have access to the file, rather than a proxy. If server load is a concern, either a batch process, or a separate server could be an alternative solution.</p>
<p>I've had success with <a href="http://www.apsis.ch/pound/" rel="nofollow noreferrer">Pound</a>.</p>
23,986
<p>I'm trying to write a simple game/utility to calculate poker odds. I know there's plenty of <a href="http://wikipedia.org/wiki/Poker_probability_(Texas_hold_&#39;em)" rel="noreferrer">resources</a> that talk about the formulas to do so, but I guess I'm having trouble translating that to code. Particularly, I'm interested in Texas Hold-em ...</p> <p>I understand that there are several different approaches, one being that you can calculate the odds that you will draw some hand based on the cards you can see. The other approach is calculating the odds that you will win a certain hand. The second approach seems much more complex as you'd have to enter more data (how many players, etc.)</p> <p>I'm not asking that you write it for me, but some nudges in the right direction would help :-)</p>
<p>Here are some links to articles, which could help as starting points: <a href="http://www.codeproject.com/KB/game/pokerlogic.aspx" rel="noreferrer">Poker Logic in C#</a> and <a href="http://www.codeproject.com/KB/game/pokerhandevaldoc.aspx" rel="noreferrer">Fast, Texas Holdem Hand Evaluation and Analysis</a></p> <p><em>"This code snippet will let you calculate poker probabilities the hard way, using C# and .NET."</em> </p> <p>The theoretical fundamentals are given in this <a href="http://en.wikipedia.org/wiki/Poker_probability_(Texas_hold_%27em)" rel="noreferrer">Wikipedia article about Poker Probabilities</a> and in this excellent <a href="http://www.tightpoker.com/poker_odds.html" rel="noreferrer">statistical tutorial</a>.</p> <p>An example of a complete project written in Objective-C, Java, C/C++ or Python is found at <a href="http://code.google.com/p/specialkpokereval/" rel="noreferrer">SpecialKEval</a>. Further links and reading can be found therein.</p>
<p>We may also be able use combinatorics, calculating the odds with combinations and the number of ways each combination can appear. This way we don't have to iterate over all the possible hands.</p>
23,566
<p>I'm just starting to learn C++ so excuse me for this simple question. What I'm doing is reading in numbers from a file and then trying to add them to an array. My problem is how do you increase the size of the array? For example I thought might be able to just do:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { double *x; x = new double[1]; x[0]=5; x = new double[1]; x[1]=6; cout &lt;&lt; x[0] &lt;&lt; "," &lt;&lt; x[1] &lt;&lt; endl; return 0; } </code></pre> <p>But this obviously just overwrites the value, 5, that I initially set to x[0] and so outputs 0,6. How would I make it so that it would output 5,6?<br /><br />Please realize that for the example I've included I didn't want to clutter it up with the code reading from a file or code to get numbers from a user. In the actual application I won't know how big of an array I need at compile time so please don't tell me to just make an array with two elements and set them equal to 5 and 6 respectively.<br /><br />Thanks for your help.</p>
<p>You don't want to work with arrays directly. Consider using a <code>vector</code>, instead. Then, you can call the <code>push_back</code> function to add things to the end, and it will automatically resize the vector for you.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; int main() { double value; std::vector&lt;double&gt; values; // Read in values while (std::cin &gt;&gt; value) { values.push_back(value); } // Print them back out for (std::size_t i(0), len(values.size()); i != len; ++i) { std::cout &lt;&lt; values[i]; } } </code></pre>
<p>An array always needs a contiguous block of memory. In a situation where you might need to resize the array later on, reallocation is probably the only solution. This is what Moishe and Shadow2531 do above. </p> <p>The problem with reallocation is that it can be a costly operation. So if you need adding 5 more elements to a 5000 element array, you might end up copying all the 5000 elements across memory.</p> <p>Using a linked list instead can be considered for such a scenario.</p>
28,763
<p>Anybody know of a plugin, or a built in function to make the columns in a table sortable? i.e. I click on the column header and it sorts the rows by that column?</p>
<p><a href="http://tablesorter.com/docs/" rel="noreferrer" title="This">http://tablesorter.com/docs/</a> is very simple to use with a wide range of options to suit your needs. :)</p>
<p>The <a href="http://extjs.com/" rel="nofollow noreferrer">Ext JavaScript library</a> is very good at that.</p>
24,723
<p>I'm developping a small UML Class editor in Java, mainly a personal project, it might end up on SourceForge if I find the time to create a project on it.</p> <p>The project is quite advanced : I can create classes, move them around, create interfaces, create links, etc.</p> <p>What I'm working on is the dialog box for setting class/interface properties and creating new classes/interfaces.</p> <p>For example, I have a class that extends JDialog. This is the main "window" for editing classes and interfaces (well, there a class for each). It contains a JTabbedPane which in turn contain JPanels.</p> <p>This JPanel are actually custom ones. I created an abstract class that extends JPanel. This class uses components (defined by its subclasses) and add their values to a JTable (also contained in the JPanel).</p> <p>For example, if I want to edit a class' attributes, the JPanel will contain a JTextField for entering the name of the attribute as well as another one for entering its type. There is also a set of button for processing the data entered in these fields. When I click "Save", the data I entered in the JTextFields are added into the JTable (à la Enterprise Architect). The concreted class that extends the abstract one are responsible for defining control and deciding what do to with the data when a line is added or deleted from the JTable. The JTable management is, however, the responsability of the abstract class.</p> <p>Here is my problem : in OO, a class has methods, and an interface has methods too. I told myself : I could use the same concrete custom JPanel (AttributesPanel (which extends the abstract JPanel class I created)) to store the methods for a class or and interface.</p> <p>However, the class needs to keep a copy (as an attribute) of the class or interface I am working on. That way, when a method is added to it, I can call editedClass.addMethod() (or editedInterface.addMethod()). The problem is that I have no way of telling whether I work on a Class or and Interface.</p> <p>The solution I found is ugly : keep an attribute editedClass and an attribute editedInterface in the AttributesPanel class. According to whether I am editing a class or interface, one of these attributes will be null while to other will not.</p> <p>It is quite ugly if you ask me. In fact, I can hear my software engineering teachers in my head screaming in agony while burning (well, actually, freezing) in the ninth circle of Hell.</p> <p>The quick way to fix this design problem would be to create an interface called "ObjectWithMethods", which my Class and Interface classes will implement. That way, I will only have to put an ObjectWithMethods parameter in my AttributesPanel class.</p> <p>But does that mean that I should create a class named "ObjectWithAttributes", or "ObjectWithBlahBlah" ? I see some good "TheDailyWTF" potential here... Besides, I don't think I should modify my domain objects (a Class, Interface, Note, Relationship (for my UML editor)) or create an new Interface just for the sake of some UI consideration....</p> <p>What do you think?</p> <p>I you need more clarifications (because I am very tired right now and I tend to right quite badly (especially in English - my mother tongue is French) while in this state of mind...), just ask and I'll edit this question.</p> <p>Cheers,</p> <p>Guillaume.</p>
<p>When I read your question it really seems like you are describing a place to use the <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="nofollow noreferrer">visitor pattern</a>.</p> <p>The reason the visitor pattern should work here is an idea known as double dispatch. Your UI code will make a call and pass a reference to itself, then the class or interface ends up calling the original caller. Since the class or interface is the one making the method call it knows its own type and how to do the work specific to its type.</p> <p>Of course, my description is insufficient to implement this technique so you'll want to read up on it. I think it is well documented. For example, I found this in about 2 seconds in java that should get you started: <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip98.html" rel="nofollow noreferrer">http://www.javaworld.com/javaworld/javatips/jw-javatip98.html</a></p>
<p>Usually, I just do the most straightforward thing, and start thinking of factoring out interfaces, when I start to see too many <code>if( .. instanceof ..)</code>-like constructs in my code. It doesn't cost me much with modern IDE code-refactoring capabilities.</p> <p>In your specific case, I would consider implementing diagrams provided in <a href="http://www.omg.org/spec/UML/" rel="nofollow">UML specification</a>, because they were so kind to specify UML using UML-notation!</p>
15,250
<p>At my new workplace, they represent a lot of dates as "days since epoch" (which I will hereafter call DSE). I'm running into issues in JavaScript converting from DSE to seconds since epoch (UNIX timestamps). Here's my function to do the conversion:</p> <pre><code>function daysToTimestamp(days) { return Math.round(+days * 86400); } </code></pre> <p>By way of example, when I pass in 13878 (expecting that this represents January 1, 2008), I get back 1199059200, not 1199098800 as I expect. Why?</p>
<p>It is because it is neither a linear representation of time nor a true representation of UTC (though it is frequently mistaken for both) as the times it represents are UTC but it has no way of representing UTC leap seconds</p> <p><a href="http://en.wikipedia.org/wiki/Unix_time" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Unix_time</a></p>
<p>You should multiply by 86400000</p> <p>1 day = 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 86400000</p>
16,585
<p>I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent:</p> <pre><code>t =&gt; t.SomeProperty.Contains("stringValue"); </code></pre> <p>So far I have got:</p> <pre><code> private static Expression.Lambda&lt;Func&lt;string, bool&gt;&gt; GetContainsExpression&lt;T&gt;(string propertyName, string propertyValue) { var parameterExp = Expression.Parameter(typeof(T), "type"); var propertyExp = Expression.Property(parameter, propertyName); var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :) ... return Expression.Lambda&lt;Func&lt;string, bool&gt;&gt;(containsMethodExp, parameterExp); //then something like this } </code></pre> <p>I just don't know how to reference the String.Contains() method.</p> <p>Help appreciated. </p>
<p>Something like:</p> <pre><code>class Foo { public string Bar { get; set; } } static void Main() { var lambda = GetExpression&lt;Foo&gt;("Bar", "abc"); Foo foo = new Foo { Bar = "aabca" }; bool test = lambda.Compile()(foo); } static Expression&lt;Func&lt;T, bool&gt;&gt; GetExpression&lt;T&gt;(string propertyName, string propertyValue) { var parameterExp = Expression.Parameter(typeof(T), "type"); var propertyExp = Expression.Property(parameterExp, propertyName); MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); var someValue = Expression.Constant(propertyValue, typeof(string)); var containsMethodExp = Expression.Call(propertyExp, method, someValue); return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(containsMethodExp, parameterExp); } </code></pre> <p>You might find <a href="http://marcgravell.blogspot.com/2008/10/express-yourself.html" rel="noreferrer">this</a> helpful.</p>
<p>Here is how to create an expression tree of string.Contains.</p> <pre><code>var method = typeof(Enumerable) .GetRuntimeMethods() .Single(m =&gt; m.Name == nameof(Enumerable.Contains) &amp;&amp; m.GetParameters().Length == 2); var containsMethod = method.MakeGenericMethod(typeof(string)); var doesContain = Expression .Call(containsMethod, Expression.Constant(criteria.ToArray()), Expression.Property(p, "MyParam")); </code></pre> <p>Actual usage at <a href="https://raw.githubusercontent.com/xavierjohn/Its.Cqrs/e44797ef6f47424a1b145d69889bf940b5581eb8/Domain.Sql/CatchupEventFilter.cs" rel="nofollow noreferrer">https://raw.githubusercontent.com/xavierjohn/Its.Cqrs/e44797ef6f47424a1b145d69889bf940b5581eb8/Domain.Sql/CatchupEventFilter.cs</a></p>
35,191
<p>Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.</p> <p>(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)</p>
<p>While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.</p> <pre><code>&lt;select id="mySelect" multiple="multiple"&gt; &lt;option value="1"&gt;First&lt;/option&gt; &lt;option value="2"&gt;Second&lt;/option&gt; &lt;option value="3"&gt;Third&lt;/option&gt; &lt;option value="4"&gt;Fourth&lt;/option&gt; &lt;/select&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { if (!$("#mySelect option:selected").length) { $("#mySelect option[value='3']").attr('selected', 'selected'); } }); &lt;/script&gt; </code></pre>
<pre><code>$("option[value*='2']").attr('selected', 'selected'); // 2 for example, add * for every option </code></pre>
18,024
<p>when i use setDefaultLookAndFeelDecorated(true) method in Java why is the Frame appear FullScreen when i maximize the Frame ? and how can i disaple the FullScreen mode in this method ?</p>
<p>Setting <code>setDefaultLookAndFeelDecorated</code> to true causes the decorations to be handled by the look and feel; this means that a System look-and-feel on both Windows and Mac (I have no Linux at hand now) retains the borders you would expect them of a native window, e.g. staying clear of the taskbar in Windows.</p> <p>When using the Cross Platform look-and-feel, a.k.a. Metal, which is the default on Windows, the Windows version will take over the entire screen, making it look like a full-screen window. On Mac, the OS refuses to give away its own titlebar, and draws a complete Metal frame (including the title bar) in a Mac-native window.</p> <p>So, in short, if you want to make sure the taskbar gets respected, use the Windows system look-and-feel on Windows. You can set it by using something like</p> <pre><code>UIManager.setLookAndFeel((LookAndFeel) Class.forName(UIManager.getCrossPlatformLookAndFeelClassName()).newInstance()); </code></pre>
<p>If you don't want your JFrame to be maximize-able then then call .setResizable(false); on it. </p>
16,834
<p>Here's my issue, I'd like to mock a class that creates a thread at initialization and closes it at destruction. There's no reason for my mock class to actually create and close threads. But, to mock a class, I have inherit from it. When I create a new instance of my mock class, the base classes constructor is called, creating the thread. When my mock object is destroyed, the base classes destructor is called, attempting to close the thread. </p> <p>How does one mock an RAII class without having to deal with the actual resource?</p>
<p>You instead make an interface that describes the type, and have both the real class and the mock class inherit from that. So if you had:</p> <pre><code>class RAIIClass { public: RAIIClass(Foo* f); ~RAIIClass(); bool DoOperation(); private: ... }; </code></pre> <p>You would make an interface like:</p> <pre><code>class MockableInterface { public: MockableInterface(Foo* f); virtual ~MockableInterface(); virtual bool DoOperation() = 0; }; </code></pre> <p>And go from there.</p>
<p>One technique I've used is to use some form of decorator. Your final code has a method which creates its instance on the stack and then calls the same method, but on a member which is a pointer to your base class. When that call returns, your method returns destroying the instance you created.</p> <p>At test time, you swap in a mock which doesn't create any threads, but just forwards to the method you want to test.</p> <pre><code>class Base{ protected: Base* decorated; public: virtual void method(void)=0; }; class Final: public Base{ void method(void) { Thread athread; decorated-&gt;method(); } // I expect Final to do something with athread }; class TestBase: public Base{ void method(void) { decorated-&gt;method(); } }; </code></pre>
23,777
<p>Has anyone tested sorting with Selenium? I'd like to verify that sorting a table in different ways work (a-z, z-a, state, date, etc.). Any help would be very much appreciated.</p> <p>/Göran</p>
<p>Before checking it with <strong>selenium</strong>, You have to do small thing. Store the table values(which comes after sorting) in a <code>string</code> or <code>array</code>. </p> <p>Now perform the sorting using selenium and capture the new list as</p> <pre><code>string new_list= selenium.gettable("xpath"); </code></pre> <p>Now compare both the values and check whether they are same or not. </p>
<p>You can get value of fields like this:</p> <pre><code> //div[@id='sortResult']/div[1]/div (this'd be row 1 of the search result) //div[@id='sortResult']/div[2]/div ( row 2) </code></pre> <p>(I'm making some assumptions about the HTML structure here, but you get my drift...)</p> <p>These can be quite fragile assertions, I'd recommend you anchor these xpath references to an outer container element (not the root of your document, as lots of "automatic" tools do).</p> <p>When you click sort, the value changes. You'll have to find out what the values are supposed to be.</p> <p>Also watch out for browser compatibility with such xpaths. They're not always ;)</p>
31,051
<p>I knew I should never have started using c++ io, the whole "type safety" argument is a red herring (does anyone <em>really</em> find that it's one of their most pressing problems?). Anyhow, I did, and discovered a strange difference between ifstreams and FILE*s and plain old file descriptors: ifstreams cannot read from a device. Can anyone think of a reason why?</p> <pre><code>const char* path = "/dev/disk3"; char b; // this works FILE* f= fopen(path, "rb"); int i = fread(&amp;b, 1, 1, f); // returns 1, success! // this does not work ifstream cf(path, ios::binary); cf.read(&amp;b, 1); bool good = cf.good(); // returns false, failure. </code></pre>
<p>The device is unbuffered and must be read from in 512 byte multiples. ifstream does it's own buffering and strangely decided to read <em>1023</em> bytes ahead, which fails with "Invalid argument". Interestingly, this ifstream is implemented on top of a FILE*. However, FILE* left to its own devices was reading ahead using a nicer, rounder number of bytes. </p> <p>Thanks to dtrace for vital clues. I guess we'll never know if the folk who thought they knew answer but didn't want to say were right. </p>
<p>I have found random issues like this in C++ I/O for years. It has always seemed like a backwards step to me.</p> <p>I haven't tried it, but you might want to look at what Boost has to offer:</p> <p><a href="http://www.boost.org/doc/libs/1_36_0/libs/iostreams/doc/index.html" rel="nofollow noreferrer">http://www.boost.org/doc/libs/1_36_0/libs/iostreams/doc/index.html</a></p>
20,954
<p>I am currently designing an application that has one module which will load large amounts of data from a database and reduce it to a much smaller set by various calculations depending on the circumstances.</p> <p>Many of the more intensive operations behave deterministically and would lend themselves to parallel processing.</p> <p>Provided I have a loop that iterates over a large number of data chunks arriving from the db and for each one call a deterministic function without side effects, how would I make it so that the program does not wait for the function to return but rather sets the next calls going, so they could be processed in parallel? A naive approach to demonstrate the principle would do me for now.</p> <p>I have read Google's MapReduce paper and while I could use the overall principle in a number of places, I won't, for now, target large clusters, rather it's going to be a single multi-core or multi-CPU machine for version 1.0. So currently, I'm not sure if I can actually use the library or would have to roll a dumbed-down basic version myself.</p> <p>I am at an early stage of the design process and so far I am targeting C-something (for the speed critical bits) and Python (for the productivity critical bits) as my languages. If there are compelling reasons, I might switch, but so far I am contented with my choice.</p> <p>Please note that I'm aware of the fact that it might take longer to retrieve the next chunk from the database than to process the current one and the whole process would then be I/O-bound. I would, however, assume for now that it isn't and in practice use a db cluster or memory caching or something else to be not I/O-bound at this point.</p>
<p>I might be missing something here, but this this seems fairly straight forward using pthreads.</p> <p>Set up a small threadpool with N threads in it and have one thread to control them all.</p> <p>The master thread simply sits in a loop doing something like:</p> <ol> <li>Get data chunk from DB </li> <li>Find next free thread If no thread is free then wait </li> <li>Hand over chunk to worker thread</li> <li>Go back and get next chunk from DB</li> </ol> <p>In the meantime the worker threads they sit and do:</p> <ol> <li>Mark myself as free</li> <li>Wait for the mast thread to give me a chunk of data</li> <li>Process the chunk of data</li> <li>Mark myself as free again</li> </ol> <p>The method by which you implement this can be as simple as two mutex controlled arrays. One has the worked threads in it (the threadpool) and the other indicated if each corresponding thread is free or busy.</p> <p>Tweak N to your liking ...</p>
<p>The same thread pool is used in java. But the threads in threadpools are serialisable and sent to other computers and deserialised to run.</p>
8,086
<p>How do i parse a text file in c#?</p>
<p>Check this interesting approach, <a href="http://blogs.msdn.com/ericwhite/archive/2006/08/31/734383.aspx" rel="nofollow noreferrer">Linq To Text Files</a>, very nice, you only need a <code>IEnumerable&lt;string&gt;</code> method, that yields every <code>file.ReadLine()</code>, and you do the query.</p> <p><a href="http://schotime.net/blog/index.php/2008/03/18/importing-data-files-with-linq" rel="nofollow noreferrer">Here</a> is another article that better explains the same technique.</p>
<p>If you have more than a trivial language, use a parser generator. It drove <em>me</em> nuts but I've heard good things about <a href="http://www.antlr.org/" rel="nofollow noreferrer">ANTLR</a> (Note: get the manual and read it before you start. If you have used a parser generator other than it before you will not approach it correctly right off the bat, at least I didn't)</p> <p>Other tools also exist.</p>
38,554
<p>I'm building a custom property grid that displays the properties of items in a collection. What I want to do is show only the properties in the grid that are common amongst each item. I am assuming the best way to do this would be to find the the common base class of each type in the collection and display it's properties. Is there any easier way? Can you give me a code example of the best approach to do this?</p>
<p>You can do this with a method that keeps checking for common base classes. I wrote up this, quickly, using the BaseClass feature of the Type class. You don't have to use an array, a list or other IEnumerable can work with small modifications to this. </p> <p>I tested it with:</p> <pre><code>static void Main(string[] args) { Console.WriteLine("Common Types: " + GetCommonBaseClass(new Type[] {typeof(OleDbCommand), typeof(OdbcCommand), typeof(SqlCommand)}).ToString()); } </code></pre> <p>And got the right answer of DbCommand. Here is my code.</p> <pre><code> static Type GetCommonBaseClass(Type[] types) { if (types.Length == 0) return (typeof(object)); else if (types.Length == 1) return (types[0]); // Copy the parameter so we can substitute base class types in the array without messing up the caller Type[] temp = new Type[types.Length]; for (int i = 0; i &lt; types.Length; i++) { temp[i] = types[i]; } bool checkPass = false; Type tested = null; while (!checkPass) { tested = temp[0]; checkPass = true; for (int i = 1; i &lt; temp.Length; i++) { if (tested.Equals(temp[i])) continue; else { // If the tested common basetype (current) is the indexed type's base type // then we can continue with the test by making the indexed type to be its base type if (tested.Equals(temp[i].BaseType)) { temp[i] = temp[i].BaseType; continue; } // If the tested type is the indexed type's base type, then we need to change all indexed types // before the current type (which are all identical) to be that base type and restart this loop else if (tested.BaseType.Equals(temp[i])) { for (int j = 0; j &lt;= i - 1; j++) { temp[j] = temp[j].BaseType; } checkPass = false; break; } // The indexed type and the tested type are not related // So make everything from index 0 up to and including the current indexed type to be their base type // because the common base type must be further back else { for (int j = 0; j &lt;= i; j++) { temp[j] = temp[j].BaseType; } checkPass = false; break; } } } // If execution has reached here and checkPass is true, we have found our common base type, // if checkPass is false, the process starts over with the modified types } // There's always at least object return tested; } </code></pre>
<p>Well,</p> <p>You could create in interface similar to IComparable but instead call it something like IPropertyComparable and then have the classes that implement it use reflection to compare their property names as so...</p> <pre><code>public int Compare(T x, T y) { PropertyInfo[] props = x.GetType().GetProperties(); foreach(PropertyInfo info in props) { if(info.name == y.GetType().Name) .... } ... </code></pre> <p>I'll let you figure out the rest. It could probably be a little more elegant anyway, use LINQ maybe...</p> <ul> <li>Matt</li> </ul>
46,030
<p>Apparantly when users right-click in our WPF application, and they use the Windows Classic theme, the default ContextMenu of the TextBox (which contains Copy, Cut and Paste) has a black background.</p> <p>I know this works well:</p> <pre><code>&lt;Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;TextBox ContextMenu="{x:Null}"/&gt; &lt;/Page&gt; </code></pre> <p>But this doesn't work:</p> <pre><code>&lt;Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Page.Resources&gt; &lt;Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}"&gt; &lt;Setter Property="ContextMenu" Value="{x:Null}"/&gt; &lt;/Style&gt; &lt;/Page.Resources&gt; &lt;TextBox/&gt; &lt;/Page&gt; </code></pre> <p>Does anyone know how to style or disable the default ContextMenu for all TextBoxes in WPF?</p>
<p>To style ContextMenu's for all TextBoxes, I would do something like the following:</p> <p>First, in the resources section, add a ContextMenu which you plan to use as your standard ContextMenu in a textbox.<br /> e.g.</p> <pre><code>&lt;ContextMenu x:Key="TextBoxContextMenu" Background="White"&gt; &lt;MenuItem Command="ApplicationCommands.Copy" /&gt; &lt;MenuItem Command="ApplicationCommands.Cut" /&gt; &lt;MenuItem Command="ApplicationCommands.Paste" /&gt; &lt;/ContextMenu&gt; </code></pre> <p>Secondly, create a style for your TextBoxes, which uses the context menu resource:</p> <pre><code>&lt;Style TargetType="{x:Type TextBox}"&gt; &lt;Setter Property="ContextMenu" Value="{StaticResource TextBoxContextMenu}" /&gt; &lt;/Style&gt; </code></pre> <p>Finally, use your text box as normal:</p> <pre><code>&lt;TextBox /&gt; </code></pre> <p>If instead you want to apply this context menu to only some of your textboxes, do not create the style above, and add the following to your TextBox markup:</p> <pre><code>&lt;TextBox ContextMenu="{StaticResource TextBoxContextMenu}" /&gt; </code></pre> <p>Hope this helps!</p>
<p>Try removing the x:Key attribute from the Style resource, leaving TargetType. I know, you're supposed to have that x:Key for a resource, but if you have it along with your TargetType the Key prevails. </p> <p>Here's a sample style that I use in a project to skin all tooltips in one of my apps (this is in App.Resources--notice, no Key) </p> <pre><code> &lt;Style TargetType="{x:Type ToolTip}"&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ToolTip}"&gt; &lt;Grid Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"&gt; &lt;Rectangle RadiusX="9" RadiusY="9" Stroke="LightGray" StrokeThickness="2"&gt; &lt;Rectangle.Fill&gt; &lt;RadialGradientBrush&gt; &lt;GradientStop /&gt; &lt;GradientStop Color="FloralWhite" Offset="0" /&gt; &lt;GradientStop Color="Cornsilk" Offset="2" /&gt; &lt;/RadialGradientBrush&gt; &lt;/Rectangle.Fill&gt; &lt;/Rectangle&gt; &lt;ContentPresenter Margin="6 4 6 4" /&gt; &lt;/Grid&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre>
3,102
<p>In a WPF app, is there a object I can assign to FileSystemWatcher.SynchronizingObject?</p> <p>I can make my own, but if there is one available, I would like to use it.</p>
<p>Reflector shows that the only class that implements <code>ISynchronizeInvoke</code> (i.e., the type of the <code>FileSystemWatcher.SynchronizingObject</code> property) is <code>System.Windows.Form.Control</code> (and its subclasses); there do not appear to be any WPF objects that implement this interface.</p>
<p>Use the DispatcherTimer rather than the system timer. This will work fine for WPF. </p> <pre><code> DispatcherTimer t1 = new DispatcherTimer(); private void Window_Loaded(object sender, RoutedEventArgs e) { t1.Interval = new TimeSpan(0,0,0,0,200); t1.Tick += new EventHandler(t1_Tick); t1.Start(); ... void t1_Tick(object sender, EventArgs e) { //some work } </code></pre>
31,651
<p>If I have the following nvarchar variable - BTA200, how can I extract just the BTA from it?</p> <p>Also, if I have varying lengths such as BTA50, BTA030, how can I extract just the numeric part?</p>
<p>I would recommend a combination of PatIndex and Left. Carefully constructed, you can write a query that always works, no matter what your data looks like.</p> <p>Ex:</p> <pre><code>Declare @Temp Table(Data VarChar(20)) Insert Into @Temp Values('BTA200') Insert Into @Temp Values('BTA50') Insert Into @Temp Values('BTA030') Insert Into @Temp Values('BTA') Insert Into @Temp Values('123') Insert Into @Temp Values('X999') Select Data, Left(Data, PatIndex('%[0-9]%', Data + '1') - 1) From @Temp </code></pre> <p>PatIndex will look for the first character that falls in the range of 0-9, and return it's character position, which you can use with the LEFT function to extract the correct data. Note that PatIndex is actually using Data + '1'. This protects us from data where there are no numbers found. If there are no numbers, PatIndex would return 0. In this case, the LEFT function would error because we are using Left(Data, PatIndex - 1). When PatIndex returns 0, we would end up with Left(Data, -1) which returns an error.</p> <p>There are still ways this can fail. For a full explanation, I encourage you to read:</p> <p><a href="http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/extracting-numbers-with-sql-server" rel="noreferrer">Extracting numbers with SQL Server</a></p> <p>That article shows how to get numbers out of a string. In your case, you want to get alpha characters instead. However, the process is similar enough that you can probably learn something useful out of it.</p>
<pre><code>declare @data as varchar(50) set @data='ciao335' --get text Select Left(@Data, PatIndex('%[0-9]%', @Data + '1') - 1) ----&gt;&gt;ciao --get numeric Select right(@Data, len(@data) - (PatIndex('%[0-9]%', @Data )-1) ) ----&gt;&gt;335 </code></pre>
49,082
<p>I saw an extruder mod on Amazon <em>"EAONE 2 Pcs PTFE Teflon Tube (2 Meters) with 4 Pcs PC4-M6 Fittings for 3D Printer 1.75mm Filament (2.0mm ID/4.0mm OD)"</em> Anybody know how this is fitted? Is it simply tapping the feed hole on the top?</p>
<p>Is <a href="https://www.amazon.co.uk/EAONE-Teflon-Fittings-Printer-Filament/dp/B077X6FW97" rel="nofollow noreferrer">this</a> what you are referring to?</p> <p>If yes, the cold end of the extruder is nomally already tapped and you simply have to screw the new fitting in it. The PTFE tube itself needs just to be fed through the hole in the fitting <strong>until it cannot go any further</strong>.</p> <p>Failing to do so will most likely result in a clog and/or leaking.</p> <p>It is a self-locking mechanism, in order to release the tube you have to press <em>down</em> the plastic flange on top of the fitting while pulling <em>up</em> the PTFE tube.</p>
<p>that item is for a bowden setup. (the a8 does not come with a bowden setup, but can be modded to have one.) when installing the bowden setup on a a8, the first thing you will need to do is move the motor to somewhere else, there are tons of choices on thingiverse. then the PC4-M6 fitting will screw into the black aluminum piece that the throat used to screw into. and the other end will go into a customised hot end. again tons of choices</p> <p>now this is oversimplified, because installing a bowden extruder on a anet a8 is a lot more complicated than explained above due to the sheer number of options. just search anet a8 bowden and you will have lots of choices.</p> <p>but it works as mac said, the PTFE tube slides into self locking fittings, the PC4-M6. to release simply push the top of the fitting down and pull out the tube.</p> <p>source, my own anet a8 modded to have a bowden setup.</p>
809
<p>As I use the web, I regularly get runtime errors (usually javascript) being reported via popups. This can make for a really unsatisfying user experience on many otherwise excellent websites and also makes me wonder what functionality I am not getting access to.</p> <p>Why is this such a common issue? Is this down to a lack of testing or is it browser compatibility issues? What can be done to minimise this kind of issue?</p> <p>Incidently I don't have the 'Display a notification about every script error' checked.</p>
<p>Its a number of issues.</p> <ol> <li>Many web page creators copy and paste JavaScript code from the web. They are not programmers and may not appreciate the nuances of the language.</li> <li>Lack of good testing frameworks (At least I don't know any). For Java we have JUNIT and .NET NUNIT etc. Its difficult to automate JavaScript testing at this time.</li> <li>Poor IDE support. Until recently most IDE's did a poor job supporting JavaScript. Now I see more support but still not the kind that you get for the core languages.</li> </ol>
<p>It's easy to make mistakes in JavaScript. Until recently with Aptana, there weren't many good tools for coding JavaScript. Not have the benefit of syntax checking or compilation, small typing error can make it into pages. Beyond that, there are time where code that works fine in one browser will cause an error in another. For example, I saw a jQuery plugin that didn't work in IE, but it was fine in every other browser. It turned out to be a variable declared without the 'var' keyword. Firefox and Safari were OK with that, IE wasn't, so it's possible that whoever wrote the code didn't even know it was a problem.</p>
35,633
<p>Has anyone ever set up Cruise Control to build an OS X Cocoa/Objective-C project?</p> <p>If so, is there a preferred flavor of CruiseControl (CruiseControl.rb or just regular CruiseControl) that would be easier to do this with. </p> <p>I currently have a Ruby rake file that has steps for doing building and running tests, and wanted to automate this process after doing a checkin. </p> <p>Also, does CruiseControl have support for git? I couldn't find anything on the website for this.</p>
<p>Yes, you just run xcode builds via the command line (xcodebuild) which makes it simple to target from CC via an ant <code>&lt;exec&gt;</code>. I've been using just regular CC, not the ruby version and it works fine. Here's a barebones example:</p> <pre><code>&lt;project name="cocoathing" default="build"&gt; &lt;target name="build"&gt; &lt;exec executable="xcodebuild" dir="CocoaThing" failonerror="true"&gt; &lt;arg line="-target CocoaThing -buildstyle Deployment build" /&gt; &lt;/exec&gt; &lt;/target&gt; &lt;/project&gt; </code></pre> <p><a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/xcodebuild.1.html" rel="nofollow noreferrer">More info on xcodebuild</a></p> <p>And there does appear to be a standard git object <a href="http://cruisecontrol.sourceforge.net/main/api/net/sourceforge/cruisecontrol/sourcecontrols/Git.html" rel="nofollow noreferrer">here</a>, but I don't use git so I can't tell you much more than that!</p>
<p>Yes, CruiseControl has a <a href="http://cruisecontrol.sourceforge.net/main/configxml.html#git" rel="nofollow noreferrer">support for git</a>.</p>
5,048
<p>In the Java snippet:</p> <pre><code>SyndFeedInput fr = new SyndFeedInput(); SyndFeed sf = fr.build(new XmlReader(myInputStream)); List&lt;SyndEntry&gt; entries = sf.getEntries(); </code></pre> <p>the last line generates the warning </p> <p>"The expression of type <code>List</code> needs unchecked conversion to conform to <code>List&lt;SyndEntry&gt;</code>"</p> <p>What's an appropriate way to fix this? </p>
<p>Since <code>getEntries</code> returns a raw <code>List</code>, it could hold anything.</p> <p>The warning-free approach is to create a new <code>List&lt;SyndEntry&gt;</code>, then cast each element of the <code>sf.getEntries()</code> result to <code>SyndEntry</code> before adding it to your new list. <code>Collections.checkedList</code> does <em>not</em> do this checking for you&mdash;although it would have been possible to implement it to do so. </p> <p>By doing your own cast up front, you're "complying with the warranty terms" of Java generics: if a <code>ClassCastException</code> is raised, it will be associated with a cast in the source code, not an invisible cast inserted by the compiler. </p>
<p>If you don't want to put @SuppressWarning("unchecked") on each sf.getEntries() call, you can always make a wrapper that will return List.</p> <p>See <a href="https://stackoverflow.com/questions/115692/how-to-avoid-type-safety-warnings-with-hibernate-hql-results#118976">this other question</a></p>
47,981
<p>I wanted to know, while deciding which language or technology to use for implementing an idea; a design, what are the factors involved in making a decision? Specifically talking about popular scripting languages, why would one choose to use ruby over python or perl or vice-versa? All these scripting languages have proved their worth, so how does one decide?</p>
<p>I just came across <a href="http://shootout.alioth.debian.org/u32q/benchmark.php?test=all&amp;lang=python&amp;lang2=ruby" rel="nofollow noreferrer">this comparison</a>, b/w Ruby and Python, which is in terms of performance and memory management.</p> <p>A fair comparison can be found <a href="http://c2.com/cgi/wiki?PythonVsRuby" rel="nofollow noreferrer">here</a>. Further, I tend to agree with all the three answers above.</p>
<p>Besides any hype that one language receives and the other doesn't, I think two factors play a role: mastership of the language, and availability of libraries. If you know Ruby already, you are more likely to use it again, and also to recommend it when asked; likewise for Python. Wrt. libraries: if you want to use Ruby-on-Rails (which you may have chosen for some reason), you have to use Ruby; likewise, if you want to use Django, you have to use Python. Etc.</p>
49,363
<p>Is the Entity Framework aware of identity columns? </p> <p>I am using SQL Server 2005 Express Edition and have several tables where the primary key is an identity column. when I use these tables to create an entity model and use the model in conjunction with an entity datasource bond to a formview in order to create a new entity I am asked to enter a value for the identity column. Is there a way to make the framework not ask for values for identity columns?</p>
<p>I know this post is quite old, but this may help the next person arriving hear via a Google search for "Entitiy Framework" and "Identity".</p> <p>It seems that Entity Frameworks does respect server-generated primary keys, as the case would be if the "Identity" property is set. However, the application side model still requires a primary key to be supplied in the <code>CreateYourEntityHere</code> method. The key specified here is discarded upon the <code>SaveChanges()</code> call to the context.</p> <p>The page <a href="https://blogs.msdn.microsoft.com/dsimmons/2008/08/10/entity-services-metadata-mapping/#Section_17" rel="nofollow noreferrer">here</a> gives the detailed information regarding this.</p>
<p>What worked for me was setting the StoreGeneratedPattern to None, when it was an Identity column. Now it all works consistently. The main problem with this is editing the models is an extreme chore if you have many models.</p>
14,683
<p><a href="https://stackoverflow.com/questions/14410/why-are-there-so-few-modal-editors-that-arent-vi">Another question</a> asked why there are so few non-vi modal editors. A few of the comments in that question mentioned other modal editors in passing, but I think that it would be useful to develop a more comprehensive list. Searching for this information on Google is difficult, as vim-related information tends to drown out everything else.</p> <p>A few items to get things rolling:</p> <ul> <li>Divascheme (<a href="https://stackoverflow.com/questions/14410/why-are-there-so-few-modal-editors-that-arent-vi">From the previously mentioned question</a>)</li> <li>Ed (<a href="http://www.csd.uwo.ca/~moreno/cs211_moreno_2007/notes/unix-editors-W2007.pdf" rel="nofollow noreferrer">According to this</a>)</li> </ul>
<p>There have been many Non-vi modal editors over the years. Many of them tied to a single operating system.</p> <p>WordStar, edlin, and ISPF come to mind. Also EDIT from the HDOS system. There are probably at least a dozen others named EDIT or it's variants.</p>
<p>Elvis is one of these editors. Also, nvi could count as one.</p>
48,570