instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I have been attempting to write some routines to read RSS and ATOM feeds using the new routines available in System.ServiceModel.Syndication, but unfortunately the Rss20FeedFormatter bombs out on about half the feeds I try with the following exception:</p> <blockquote> <pre><code>An error was encountered when parsing a DateTime value in the XML. </code></pre> </blockquote> <p>This seems to occur whenever the RSS feed expresses the publish date in the following format:</p> <blockquote> <p>Thu, 16 Oct 08 14:23:26 -0700</p> </blockquote> <p>If the feed expresses the publish date as GMT, things go fine:</p> <blockquote> <p>Thu, 16 Oct 08 21:23:26 GMT</p> </blockquote> <p>If there's some way to work around this with XMLReaderSettings, I have not found it. Can anyone assist?</p>
<p>Based on the workaround posted in the <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=325421&amp;wa=wsignin1.0" rel="nofollow noreferrer">bug report to Microsoft about this</a> I made an XmlReader specifically for reading SyndicationFeeds that have non-standard dates. </p> <p>The code below is slightly different than the code in the workaround at Microsoft's site. It also takes <a href="https://stackoverflow.com/questions/210375/problems-reading-rss-with-c-and-net-3-5/263137#263137">Oppositional's advice</a> on using the RFC 1123 pattern.</p> <p>Instead of simply calling XmlReader.Create() you need to create the XmlReader from a Stream. I use the WebClient class to get that stream:</p> <pre><code>WebClient client = new WebClient(); using (XmlReader reader = new SyndicationFeedXmlReader(client.OpenRead(feedUrl))) { SyndicationFeed feed = SyndicationFeed.Load(reader); .... //do things with the feed .... } </code></pre> <p>Below is the code for the SyndicationFeedXmlReader:</p> <pre><code>public class SyndicationFeedXmlReader : XmlTextReader { readonly string[] Rss20DateTimeHints = { "pubDate" }; readonly string[] Atom10DateTimeHints = { "updated", "published", "lastBuildDate" }; private bool isRss2DateTime = false; private bool isAtomDateTime = false; public SyndicationFeedXmlReader(Stream stream) : base(stream) { } public override bool IsStartElement(string localname, string ns) { isRss2DateTime = false; isAtomDateTime = false; if (Rss20DateTimeHints.Contains(localname)) isRss2DateTime = true; if (Atom10DateTimeHints.Contains(localname)) isAtomDateTime = true; return base.IsStartElement(localname, ns); } public override string ReadString() { string dateVal = base.ReadString(); try { if (isRss2DateTime) { MethodInfo objMethod = typeof(Rss20FeedFormatter).GetMethod("DateFromString", BindingFlags.NonPublic | BindingFlags.Static); Debug.Assert(objMethod != null); objMethod.Invoke(null, new object[] { dateVal, this }); } if (isAtomDateTime) { MethodInfo objMethod = typeof(Atom10FeedFormatter).GetMethod("DateFromString", BindingFlags.NonPublic | BindingFlags.Instance); Debug.Assert(objMethod != null); objMethod.Invoke(new Atom10FeedFormatter(), new object[] { dateVal, this }); } } catch (TargetInvocationException) { DateTimeFormatInfo dtfi = CultureInfo.CurrentCulture.DateTimeFormat; return DateTimeOffset.UtcNow.ToString(dtfi.RFC1123Pattern); } return dateVal; } } </code></pre> <p>Again, this is copied almost exactly from the workaround posted on the Microsoft site in the link above. ...except that this one works for me, and the one posted at Microsoft did not.</p> <p><strong>NOTE</strong>: One bit of customization you may need to do is in the two arrays at the start of the class. Depending on any extraneous fields your non-standard feed might add, you may need to add more items to those arrays. </p>
<p>A similar problem still persists in .NET 4.0 and I decided to work with <strong>XDocument</strong> instead of directly invoking <strong>SyndicationFeed</strong>. I described the applied method (specific to my project <a href="http://dennisdel.com/?p=342" rel="nofollow noreferrer">here</a>). Can't say it is the best solution, but it certainly can be considered a "backup plan" in case <strong>SyndicationFeed</strong> fails.</p>
25,820
<p>I want to be able to get an estimate of how much code &amp; static data is used by my C++ program?</p> <p>Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?</p> <p>Will otool help?</p>
<ul> <li>"size" is the traditional tool and works on all unix flavors. </li> <li>"otool" has a bit finer grain control and has a lot of options.</li> </ul> <p>.</p> <pre><code>$ size python __TEXT __DATA __OBJC others dec hex 860160 159744 0 2453504 3473408 350000 </code></pre>
<p>I think otool can help. Specifically, "otool -s {segment} {section}" should print out the details. I'm not sure if you can get information about __DATA or __TEXT without specifying a section. Maybe those sizes are reported in the mach header: "otool -h"?</p> <pre><code>otool -s __DATA __data MyApp.bundle/Contents/MacOS/MyApp otool -s __TEXT __text MyApp.bundle/Contents/MacOS/MyApp </code></pre> <p>Anyway, Apple documents what gets copied into each section per-segment here: <a href="http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html#//apple_ref/doc/uid/TP40000895-CH248-95874" rel="nofollow noreferrer">Apple's mach-o format documentation</a></p>
5,599
<p>How do you embed a SWF file in an HTML page?</p>
<p>The best approach to embed a SWF into an HTML page is to use <a href="https://github.com/swfobject/swfobject/" rel="noreferrer">SWFObject</a>.</p> <p>It is a simple open-source JavaScript library that is easy-to-use and standards-friendly method to embed Flash content.</p> <p>It also offers Flash player version detection. If the user does not have the version of Flash required or has JavaScript disabled, they will see an alternate content. You can also use this library to trigger a Flash player upgrade. Once the user has upgraded, they will be redirected back to the page.</p> <p>An example from the documentation:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"&gt; &lt;head&gt; &lt;title&gt;SWFObject dynamic embed - step 3&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt; &lt;script type="text/javascript" src="swfobject.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; swfobject.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0"); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="myContent"&gt; &lt;p&gt;Alternative content&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>A good tool to use along with this is the SWFObject HTML and JavaScript <a href="https://github.com/swfobject/swfobject/wiki/SWFObject-Generator" rel="noreferrer">generator</a>. It basically generates the HTML and JavaScript you need to embed the Flash using SWFObject. Comes with a very simple UI for you to input your parameters.</p> <p>It Is highly recommended and very simple to use.</p>
<p>You can use JavaScript if you're familiar with, like that:</p> <pre><code>swfobject.embedSWF("filename.swf", "Title", "width", "height", "9.0.0"); </code></pre> <p>--the 9.0.0 is the flash version.</p> <p>Or you can use the <code>&lt;object&gt;</code> tag of HTML5.</p>
16,609
<p>My studio has a large codebase that has been developed over 10+ years. The coding standards that we started with were developed with few developers in house and long before we had to worry about any kind of standards related to C++.</p> <p>Recently, we started a small R&amp;D project in house and we updated our coding conventions to be more suitable for our environment. The R&amp;D work is going to be integrated into existing project code. One major problem facing us is that we now have two standards for the two areas of work, and now the code bases will cross. I don't want two standards at the studio, and I'm actually quite happy to move forward with a single standard. (The 'how' of how we got into this situation isn't important -- just that we are and I had hoped that we wouldn't be.)</p> <p>The problem is refactoring existing code. I'm not very keen on having two code bases (one relatively small and one very large) looking different. I am interested in doing some refactoring of one of the existing codebases to make it conform to the other standard. The problem is, the smaller code base is (IMO) the more desireable standard.</p> <p>I started looking around for a tool that could do large scale refactoring for me. I'm not interested in rearranging and tightening code. I'm interested in changing things like</p> <pre><code>class my_class {} .... class my_class A; </code></pre> <p>to</p> <pre><code>class MyClass {} .... class MyClass A; </code></pre> <p>Basically doing function/variable level renaming. I'd prefer not to use something like Visual Assist because that will take a long time. I have upwards of 10000 source/header files with hundreds of thousands of lines of code. Using VA one class at a time would be a time killer and not worth the effort.</p> <p>I did run across <a href="http://www.inspirel.com/vera/" rel="nofollow noreferrer">Vera</a> in another post on SO. That seems like it might do the job and do it well. I'd like to know if anyone has specific experience using Vera for the situation that I'm in, or has any other recommendations for tools that might get the job done. I think that it's important that this tool actually understand code structure so that we don't wind up just renaming variables in a search/replace manner because that will lead to subtle bugs if not done carefully.</p> <p>EDIT: While my example shows I'm going from using _ between names to camelcase type notation, it might be more beneficial for us to move the other way. I'm really looking for a generic solution that will help with large scale renaming.</p> <p>Thanks.</p>
<p>My process would be to rename each time someone touches a given module. Eventually, all modules would be refactored, but the incremental approach would result in less code breakage(assuming you have a complete set of tests. ;) ) </p>
<p>I think renaming variables is going to be tricky - fortunately you're going from _ convention to Capitalised so it won't be so hard (though _ is easier to read and better)</p> <p>I would take a code beautifier (eg <a href="http://astyle.sourceforge.net/astyle.html" rel="nofollow noreferrer">Artistic Style</a> or <a href="http://uncrustify.sourceforge.net/" rel="nofollow noreferrer">Uncrustify</a>) and modify them to do the conversion. You only need a few custom rules for this conversion so it won't be too hard.</p>
25,344
<p>We are all talking about the efficiency of the algorithms and it depends on input size -basically.</p> <p>How about the system specifications of current computer that runs the algorithm? does it make any difference to run a different sorting algorithm in a Core 2 Duo 2.6 GHZ, 4 GB RAM-computer or in a P-2, 256 MB RAM-computer?</p> <p>I am sure that there must be a performance difference. But, I want to know what is the real relationship between algorithms and system specifications...</p>
<p>An increase in hardware performance will give you a constant C times the running time of your algorithm. Meaning if you have computer A which is overall 2 times slower than computer B. Than your algorithm will be twice as fast on computer B. Twice as fast though really makes hardly no difference when you consider big input values to an algorithm though. </p> <p><a href="http://en.wikipedia.org/wiki/Big_O_notation" rel="nofollow noreferrer">In big O notation</a> that is to say you will have something like O(n) compared to C<em>O(n) = O(c</em>n) = O(n). The complexity of the algorithm and general running time for large values will be about the same on both Computer A and Computer B. </p> <p>If you analyze an algorithm's running time using something like big O notation, then you will have a much better idea about how the algorithm really works. Computer performance won't give you any kind of advantage when you are comparing an algorithm that is O(logn) compared to O(n^2). </p> <p>Take a look at some of the data values for n: </p> <p>I will assume 1 second per operation for the slow computer, and 2 operations for second for the fast computer. I will compare the better algorithm with the slow computer with the worse algorithm with the fast computer.</p> <p><strong>for n = 10:</strong></p> <blockquote> <p>Algorithm 1: O(logn): 4 operations Slow computer: 4 seconds </p> <p>Algorithm 2: O(n^2): 100 operations Fast computer: 50 seconds</p> </blockquote> <p><strong>for n = 100:</strong></p> <blockquote> <p>Algorithm 1: O(logn): 7 operations Slow computer: 7 seconds</p> <p>Algorithm 2: O(n^2): 10,000 operations Fast computer: 1.4 hours</p> </blockquote> <p>Large difference</p> <p><strong>for n = 1,000:</strong></p> <blockquote> <p>Algorithm 1: O(logn): 10 operations Slow computer: 10 seconds</p> <p>Algorithm 2: O(n^2): 1,000,000 operations Fast computer: 5.8 days</p> </blockquote> <p>Huge difference</p> <hr> <p>As n increases, the difference gets bigger and bigger. </p> <p>Now if you tried to run each of these algorithms on a faster/slower computer for a large input size. It wouldn't matter. Hands down the O(logn) would be faster.</p>
<p>The efficiency of an algorithm doesn't depend on the system specification. The efficiency is described by the Ordo number, which gives you a relation of the processing effort and the size of the input.</p>
26,728
<p>What is the best way to store a large amount of text in a table in SQL server?</p> <p>Is varchar(max) reliable?</p>
<p>In SQL 2005 and higher, VARCHAR(MAX) is indeed the preferred method. The TEXT type is still available, but primarily for backward compatibility with SQL 2000 and lower.</p>
<p>Use <code>nvarchar(max)</code> to store the whole chat conversation thread in a single record. Each individual text message (or block) is identified in the content text by inserting markers. </p> <p>Example:</p> <pre><code>{{UserId: Date and time}}&lt;Chat Text&gt;. </code></pre> <p>On display time UI should be intelligent enough to understand this markers and display it correctly. This way one record should suffice for a single conversation as long as size limit is not reached.</p>
16,991
<p>Well, maybe not with all 4 things, but here's my situation:</p> <p>I have an ActiveMQ backend (running on my desktop Mac). It's a stock Apache ActiveMQ server I have which I am basically using as an echo server to tail the logs and debug my client. The client is an iPhone project with a hacked up Stomp.framework implementation using AsyncSocket.</p> <p>I need to use AsyncSocket Cocoa library to talk to the Stomp server, which I more or less have working. I can send messages to queues, and read them back out, so I think I am good there.</p> <p>BUT, when I try to set everything up to use SSL (also a requirement) I get the following error description out of the NSError object I get back:</p> <pre><code>kCFStreamErrorDomainSSL error -9812. </code></pre> <p>I cannot for the life of me figure out what this error code is. Anyone have a clue?</p> <p>Here is how I setup the SSL stuff for AsyncSocket:</p> <p>EDIT: ADDED THE CORRECT CODE HERE. NOTE SELF-SIGNED CERTS.</p> <pre><code>//- (BOOL)onSocketWillConnect:(AsyncSocket *)sock { // Connecting to a secure server NSMutableDictionary * settings = [NSMutableDictionary dictionaryWithCapacity:2]; // Use the highest possible security [settings setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(NSString *)kCFStreamSSLLevel]; // Allow self-signed certificates [settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot]; CFReadStreamSetProperty([sock getCFReadStream], kCFStreamPropertySSLSettings, (CFDictionaryRef)settings); CFWriteStreamSetProperty([sock getCFWriteStream], kCFStreamPropertySSLSettings, (CFDictionaryRef)settings); return YES; </code></pre> <p>}</p> <p>Anyone have any ideas? I <em>think</em> I'm setting the stream properties correctly. Maybe it's something to do with the ActiveMQ setup? I didn't do any configuration other than to enable the SSL over Stomp protocol in ActiveMQ. I don't have a certificate or anything like that. Maybe that is the problem?</p> <p>Any insight is appreciated!</p>
<p>no idea on the specifics of the error code but I can tell you that the certs that ship with activemq are noddy, intended for testing only. They are self signed certs (essentially invalid) which can throw a client side ssl library that tries to validate their chain length. In the <a href="https://github.com/apache/activemq/blob/master/activemq-unit-tests/src/test/java/org/apache/activemq/transport/tcp/SslBrokerServiceTest.java" rel="nofollow noreferrer">ssl broker test</a> the cert is explicitly added to the trust store so that the client can accept it rather than attempting to validate it. A good start would be to generate valid certs for the broker or figure out a way to add the existing cert to the trust store used by AsyncSocket (have no idea how that is configured though, possibly the linked java test code will help)</p>
<p><a href="http://file:///Developer/Documentation/DocSets/com.apple.ADC_Reference_Library.CoreReference.docset/Contents/Resources/Documents/documentation/Security/Reference/secureTransportRef/Reference/reference.html" rel="nofollow noreferrer">Secure Transport reference on your Mac</a></p> <p>Scroll down to result codes to see the error codes. The one you're getting is <code>&quot;errSSLUnknownRootCert&quot;</code>. (Seems to confirm gtully's answer.)</p>
49,817
<p>I want to use <a href="http://code.google.com/apis/visualization/documentation/gallery/annotatedtimeline.html" rel="nofollow noreferrer">Google's Annotated Time Line Visualization</a>. It is very easy to make this work by manually adding the lines for column &amp; row data. This is all done through attributes of google.visualization.DataTable(). I would like to update this data table dynamically, but I do not know how. The data is on a server running MS SQL Server 2005. </p> <p>I found a <a href="http://groups.google.com/group/google-visualization-api/browse_thread/thread/4dc84221fbd3ade5/d57109c9b45fd741?lnk=raot&amp;pli=1" rel="nofollow noreferrer">post</a> to accomplish this with PHP and MySQL, but I do not know how to translate this to VB .NET or C# (either is fine).</p> <p>Does anyone know how to make this use MS SQL Server data in .NET or of a better way to have the code dynamically generated so new data does not have to have the lines manually added every day?</p> <p>Thanks!</p>
<p>I know this is an old post but take a look at <a href="http://www.panterlo.com/2010/10/17/google-visualization-api-gets-easy-with-net-mvc/" rel="nofollow">http://www.panterlo.com/2010/10/17/google-visualization-api-gets-easy-with-net-mvc/</a> which points out that I released out a class library available at github (GPL v3) that you can use for this purpose.</p>
<p>You could use the post you mentioned to help you write this code in PHP but use PHP's ODBC functions (<a href="http://us3.php.net/odbc" rel="nofollow noreferrer">http://us3.php.net/odbc</a>) to access the data in MSSQL Server instead of the examples shown in accessing a MySQL database.</p> <pre><code>$connectionstring = odbc_connect($db, $user, $pass) or die("Connection Failed"); $query = "..."; $result = odbc_do($connectionstring, $query) or die("Query Failed"); </code></pre> <p>Sorry that doesn't help you with .NET or C#.</p>
36,740
<p>(I asked this question <a href="https://stackoverflow.com/questions/72580/making-a-cwinform-application-cross-platform-should-i-use-air-mono-or-something">in another way</a>, and got some interesting responses but I'm not too convinced.)</p> <p>Is Mono's GtkSharp truly cross-platform? It seems to be Gnome based... how can that work with PC and Mac? </p> <p>Can someone give me examples of a working Mac/PC/Linux app that is written with a single codebase in Microsoft .Net?</p>
<p><a href="http://www.plasticscm.com/xpproducts/xpcore/xpmultiplatform.aspx" rel="nofollow noreferrer">Plastic SCM</a> is supported on Windows, Linux, Solaris, and Mac OS X. The link includes screenshots on Windows and Linux.</p>
<p>Gtk# is cross platform. However the only platform where it looks nice is Linux/BSD running GNOME. If possible somehow, separate frontend and backend and develop separate user interfaces for Linux, Windows and OS X. Even wx, which does a really good job in looking okay on all three platforms, has its limits.</p> <p>Working Mac/PC/Linux app in Gtk#? Tomboy runs on all three I think.</p>
14,185
<p>I am working with an order system that has two tables Order and OrderLine pretty standard stuff. I want to work out an order line number for the order lines with respect to the order e.g.</p> <p>Orderid Orderlineid linenumber<br> 1 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1<br> 2 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1<br> 2 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;3 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2<br> 3 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;4 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1<br> 4 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;5 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1<br> 4 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;6 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2</p> <p>The OrderLineId is an identity column. I don't want to store the line number as data in the database for two reasons. First there are already a great many existing orders and lines in the system and retrospectively adding the data is a headache I wish to avoid. Second if the user deletes a line then I would need to recalculate the line numbers for the whole order.</p> <p>In SQL 2005 I can do this easy peasy using the ROW_NUMBER function.</p> <pre><code>Select Orderid, OrderLineid, ROW_NUMBER() OVER(PARTITION BY Orderid ORDER BY Orderlineid) as LineNumber FROM OrderLine </code></pre> <p>Is there anyway I can do this in SQL 2000?</p> <p>The closest I found was a ranking function (see below) but this counts orders not lines.</p> <pre><code>SELECT x.Ranking, x.OrderId FROM (SELECT (SELECT COUNT( DISTINCT t1.Orderid) FROM orderline t1 WHERE z.Orderid &gt;= t1.Orderid)AS Ranking, z.orderid FROM orderline z ) x ORDER BY x.Ranking </code></pre>
<p>You can use something like this:</p> <pre><code>select ol1.orderId, ol1.orderLineId, count(*) as lineNumber from orderLine ol1 inner join orderLine ol2 on ol1.orderId = ol2.orderId and ol1.orderLineId &gt;= ol2.orderLineId group by ol1.orderId, ol1.orderLineId </code></pre>
<p>IMHO, calculating it every time you need it may end up being more of a headache than it's worth. And while it may be a pain to update the historical line numbers and save it to the database, you'd only be doing that once... and then would just need to write code to automate it later.</p> <p>To handle the deletes, you'd just need to add code into the existing delete procedure and have it recalculate the line numbers for it.</p>
43,742
<p>Can anyone guide me in the correct way to build a colored bubble/circle programmatically?</p> <p>I can't use images as I need it to be able to be any color depending on user interaction.</p> <p>My thought was maybe to make a white circle image and then overlay a color on top of it. However I am not sure if this would work, or how to really go about it.</p> <p>If someone could point me the right direction I would appreciate it.</p>
<p>There are a couple steps to drawing something in Cocoa.</p> <p>First you need a path that will be used to define the object that you are going to be drawing. Take a look here <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaDrawingGuide/Paths/Paths.html#//apple_ref/doc/uid/TP40003290-CH206-BBCHFJJG" rel="noreferrer">Drawing Fundamental Shapes</a> for a guide on creating paths in Cocoa. You will be most interested in sending the "appendBezierPathWithOvalInRect" message to an "NSBezierPath" object, this takes a rectangle that bounds the circle you want to draw.</p> <p>This code will create a 10x10 circle at coordinates 10,10:</p> <pre><code>NSRect rect = NSMakeRect(10, 10, 10, 10); NSBezierPath* circlePath = [NSBezierPath bezierPath]; [circlePath appendBezierPathWithOvalInRect: rect]; </code></pre> <p>Once you have your path you want to set the color for the current drawing context. There are two colors, stroke and fill; stroke is the outline of the path and the fill is the interior color. To set a color you send "set" to an "NSColor" object.</p> <p>This sets the stroke to black and the fill to red:</p> <pre><code>[[NSColor blackColor] setStroke]; [[NSColor redColor] setFill]; </code></pre> <p>Now that you have your path and you have your colors set just fill the path and then draw it:</p> <pre><code>[path stroke]; [path fill]; </code></pre> <p>All of this will need to be done in a graphics context like in drawRect of a view perhaps. All of this together with a graphics context would look like this:</p> <pre><code>- (void)drawRect:(NSRect)rect { // Get the graphics context that we are currently executing under NSGraphicsContext* gc = [NSGraphicsContext currentContext]; // Save the current graphics context settings [gc saveGraphicsState]; // Set the color in the current graphics context for future draw operations [[NSColor blackColor] setStroke]; [[NSColor redColor] setFill]; // Create our circle path NSRect rect = NSMakeRect(10, 10, 10, 10); NSBezierPath* circlePath = [NSBezierPath bezierPath]; [circlePath appendBezierPathWithOvalInRect: rect]; // Outline and fill the path [circlePath stroke]; [circlePath fill]; // Restore the context to what it was before we messed with it [gc restoreGraphicsState]; } </code></pre>
<p>Download sketch from apple. <a href="http://developer.apple.com/library/mac/#samplecode/Sketch" rel="nofollow noreferrer">http://developer.apple.com/library/mac/#samplecode/Sketch</a></p> <p>It can do a lot more, but one of the things is draw circles.</p>
46,195
<p>I am trying to build a homebrew web brower to get more proficient at Cocoa. I need a good way to validate whether the user has entered a valid URL. I have tried some regular expressions but NSString has some interesting quirks and doesn't like some of the back-quoting that most regular expressions I've seen use.</p>
<p>You could start with the <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/clm/NSURL/URLWithString:" rel="noreferrer"><code>+ (id)URLWithString:(NSString *)URLString</code></a> method of <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/clm/NSURL/URLWithString:" rel="noreferrer"><code>NSURL</code></a>, which returns <code>nil</code> if the string is malformed.</p> <p>If you need further validation, you can use the <code>baseURL</code>, <code>host</code>, <code>parameterString</code>, <code>path</code>, etc methods to give you particular components of the URL, which you can then evaluate in whatever way you see fit.</p>
<p>I've found that it is possible to enter some URLs that seem to be OK but are rejected by the NSURL creation methods. So we have a method to escape the string first to make sure it's in a good format. Here is the meat of it:</p> <pre> NSString *escapedURLString = NSMakeCollectable(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)URLString, (CFStringRef)@"%+#", // Characters to leave unescaped NULL, kCFStringEncodingUTF8)); </pre>
23,449
<p>You launch a java program from a console (maybe using a .bat script). I don't want the console to remain visible, I want to hide it.</p> <p>Is there a simple way to do this ? Without JNI ?</p>
<p>Use javaw.</p> <p><a href="http://java.sun.com/javase/6/docs/tooldocs/windows/java.html" rel="noreferrer">http://java.sun.com/javase/6/docs/tooldocs/windows/java.html</a></p> <blockquote> <p>The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear. The javaw launcher will, however, display a dialog box with error information if a launch fails for some reason. </p> </blockquote>
<p>In case fo running from but file your script should look like <code>start javaw start javaw -jar ***.jar</code></p>
33,162
<p>I'm testing the speed of some queries in MySQL. The database is caching these queries making it difficult for me to get reliable results when testing how fast these queries are.</p> <p>Is there a way to disable caching for a query?</p> <p>System: MySQL 4 on Linux webhosting, I have access to PHPMyAdmin.</p> <p>Thanks</p>
<p>Try using the <a href="https://dev.mysql.com/doc/refman/5.7/en/query-cache-in-select.html" rel="noreferrer">SQL_NO_CACHE</a> (MySQL 5.7) option in your query. (MySQL 5.6 users click <a href="https://dev.mysql.com/doc/refman/5.6/en/query-cache-in-select.html" rel="noreferrer">HERE</a> )</p> <p>eg.</p> <pre><code>SELECT SQL_NO_CACHE * FROM TABLE </code></pre> <p>This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.</p>
<p>You must change SQL string. Because SQL string is a cache key. For example, add a timestamp to a SQL comment.</p> <p>Function for PHP:</p> <pre><code>function db_RunSQL($SQL, $NoCacheMode=false) { $SQL = (($NoCacheMode) ? '/*'.time().'*/ ' : '') . $SQL; return mysqli_query(db_SavedConnect(), $SQL); } </code></pre>
21,966
<p>I have a script which calls <code>mysql_connect()</code> to connect to a MySQL DB. When I run the script in a browser, it works. However, when I run it from a command line I receive the following error:</p> <pre><code>Call to undefined function mysql_connect() </code></pre> <p>This seems completely paradoxical. Anyone have any ideas as how I can run it from the command line. Btw, I run it from a bash shell like so:</p> <pre><code>php /path/to/script.php </code></pre>
<p>It maybe using a default PHP configuration. I have found before that it doesn't use the same php.ini or doesn't use one at all. Therefore some of the extensions won't be enabled.</p> <p>Do this instead:</p> <pre><code>php -c /etc/php.ini /path/to/script.php </code></pre> <p>Where <code>/etc/php.ini</code> is the path to your ini file. You can find this by doing a <code>phpinfo();</code></p>
<p>My system is CentOS. In my case, the the path to mysql.so is incorrect.</p> <p>When I type </p> <pre><code>php -m </code></pre> <p>There is no mysql.</p> <p>In my original /etc/php.d/mysql.ini there is only one line:</p> <pre><code>extension=mysql.so </code></pre> <p>So I use command: </p> <pre><code>rpm -ql php-mysql | grep mysql.so </code></pre> <p>to find out the correct path, which is </p> <pre><code>/usr/lib64/php/modules/mysql.so </code></pre> <p>then I replaced the line to :</p> <pre><code>extension=/usr/lib64/php/modules/mysql.so </code></pre> <p>then </p> <pre><code>service httpd restart </code></pre> <p>and </p> <pre><code>php -m </code></pre> <p>mysql is now loaded.</p>
21,870
<p>Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such:</p> <pre><code>LimitedValue&lt; float, 0, 360 &gt; someAngle( 45.0 ); someTrigFunction( someAngle ); </code></pre> <p>so that 'someTrigFunction' knows that it is guaranteed to be supplied a valid input (The constructor would throw an exception if the parameter is invalid).</p> <p>Copy-construction and assignment are limited to exactly equal types, though. I'd like to be able to do:</p> <pre><code>LimitedValue&lt; float, 0, 90 &gt; smallAngle( 45.0 ); LimitedValue&lt; float, 0, 360 &gt; anyAngle( smallAngle ); </code></pre> <p>and have that operation checked at compile-time, so this next example gives an error:</p> <pre><code>LimitedValue&lt; float, -90, 0 &gt; negativeAngle( -45.0 ); LimitedValue&lt; float, 0, 360 &gt; postiveAngle( negativeAngle ); // ERROR! </code></pre> <p>Is this possible? Is there some practical way of doing this, or any examples out there which approach this?</p>
<p>You can do this using templates -- try something like this:</p> <pre><code>template&lt; typename T, int min, int max &gt;class LimitedValue { template&lt; int min2, int max2 &gt;LimitedValue( const LimitedValue&lt; T, min2, max2 &gt; &amp;other ) { static_assert( min &lt;= min2, "Parameter minimum must be &gt;= this minimum" ); static_assert( max &gt;= max2, "Parameter maximum must be &lt;= this maximum" ); // logic } // rest of code }; </code></pre>
<p>At the moment, that is impossible in a portable manner due to the C++ rules on how methods (and by extension, constructors) are called even with constant arguments.</p> <p>In the C++0x standard, you could have a const-expr that would allow such an error to be produced though. </p> <p>(This is assuming you want it to throw an error only if the actual value is illegal. If the ranges do not match, you can achieve this)</p>
17,891
<p>I've been learning Squeak Smalltalk &amp; have noticed that it's got a really faithful community and is used in some large academic and open-source projects, but I haven't found any examples of it being used commercially in any significant way. I'm curious about how this environment is doing in the world commercially. Maybe taking over older Smalltalk projects? Does anyone know?</p>
<p><a href="http://auctomatic.com/" rel="noreferrer">http://auctomatic.com/</a></p>
<p>I'd bet it won't play any "important" role any time soon. The whole programming model with "morhps" is "alien" to anything in the commercial "surrounding". Just try to implement a small example in some Smalltalk like VisualWorks and than the same in Squeak. There are tried to get more "traditonal" GUI toolkit running with Squeak (GTK) but that's in it's infancy and it does not even compiler out of the box. It won't take over other Smalltalk environments, because there's not incentieve for using it instead let's say VisualAge, VisualWorks or Smalltalk/X. </p> <p>Regards Friedrich</p>
12,427
<p>I am going through John Resig's excellent <a href="http://ejohn.org/apps/learn/#47" rel="noreferrer">Advanced javascript tutorial</a> and I do not thoroughly understand what's the difference between the following calls: (please note that 'arguments' is a builtin javascript word and is not exactly an array hence the hacking with the Array.slice instead of simply calling arguments.slice)</p> <pre><code>&gt;&gt;&gt; arguments [3, 1, 2, 3] &gt;&gt;&gt; Array.slice.call( arguments ) 3,1,2,3 0=3 1=1 2=2 3=3 &gt;&gt;&gt; Array.slice.call( arguments, 1 ) [] &gt;&gt;&gt; Array().slice.call( arguments ) 3,1,2,3 0=3 1=1 2=2 3=3 &gt;&gt;&gt; Array().slice.call( arguments, 1 ) 1,2,3 0=1 1=2 2=3 </code></pre> <p>Basically my misunderstanding boils down to the difference between Array.slice and Array().slice. What exactly is the difference between these two and why does not Array.slice.call behave as expected? (which is giving back all but the first element of the arguments list).</p>
<p>Not quite.</p> <p>Watch what happens when you call String.substring.call("foo", 1) and String().substring.call("foo", 2):</p> <pre><code>&gt;&gt;&gt; String.substring.call("foo", 1) "1" &gt;&gt;&gt; String().substring.call("foo", 1) "oo" </code></pre> <p>Array.slice is <em>neither</em> properly referencing the slice function attached to the Array prototype nor the slice function attached to any instantiated Array instance (such as Array() or []).</p> <p>The fact that Array.slice is even non-null at all is an incorrect implementation of the object (/function/constructor) itself. <strong>Try running the equivalent code in IE and you'll get an error that Array.slice is null</strong>.</p> <p>This is why Array.slice does not behave correctly (nor does String.substring).</p> <p>Proof (the following is something one should never expect based on the definition of slice()...just like substring() above):</p> <pre><code>&gt;&gt;&gt; Array.slice.call([1,2], [3,4]) 3,4 </code></pre> <p>Now, if you properly call slice() on either an instantiated object <em>or</em> the Array prototype, you'll get what you expect:</p> <pre><code>&gt;&gt;&gt; Array.prototype.slice.call([4,5], 1) [5] &gt;&gt;&gt; Array().slice.call([4,5], 1) [5] </code></pre> <p>More proof...</p> <pre><code>&gt;&gt;&gt; Array.prototype.slice == Array().slice true &gt;&gt;&gt; Array.slice == Array().slice false </code></pre>
<p>Well,</p> <p>Looking at <a href="http://www.devguru.com/Technologies/ecmascript/quickref/slice.html" rel="nofollow noreferrer">http://www.devguru.com/Technologies/ecmascript/quickref/slice.html</a> </p> <p>Array().slice is a function (constructor)in the array class, It cant be used as a data member. If you didn't want to use the '()' you would need to call it on the array. ie - arguments.slice(1)</p>
14,692
<p>When I refer to nested set model I mean what is described <a href="http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/" rel="nofollow noreferrer">here.</a></p> <p>I need to build a new system for storing "categories" (I can't think of better word for it) in a user defined hierarchy. Since the nested set model is optimized for reads instead of writes, I decided to use that. Unfortunately during my research and testing of nested sets, I ran into the problem of how do I display the hierarchical tree with sorted nodes. For example if I have the hierarchy:</p> <pre><code>root finances budgeting fy08 projects research fabrication release trash </code></pre> <p>I want that to be sorted so that it displays as:</p> <pre><code>root finances budgeting fy08 projects fabrication release research trash </code></pre> <p>Notice that the fabrication appears before research.</p> <p>Anyway, after a long search I saw answer such as "store the tree in a multi-dimensional array and sort it" and "resort the tree and serialized back into your nested set model" (I'm paraphrazing...). Either way, the first solution is a horrible waste of RAM and CPU, which are both very finite resources... The second solution just looks like a lot of painful code.</p> <p>Regardless, I was able to figure out how to (using the nested set model):</p> <ol> <li>Start a new tree in SQL</li> <li>Insert a node as a child of another node in tree</li> <li>Insert a node after a sibling node in the tree</li> <li>Pull the entire tree with the hierarchy structure from SQL</li> <li>Pull a subtree from a specific node (including root) in the hierarchy with or without a depth limit</li> <li>Find the parent of any node in the tree</li> </ol> <p>So I figured #5 and #6 could be used to do the sorting I wanted, and it could also be used to rebuild the tree in sorted order as well.</p> <p>However, now that I've looked at all of these things I've learned to do I see that #3, #5, and #6 could be used together to perform sorted inserts. If I did sorted inserts it always be sorted. However, if I ever change the sort criteria or I want a different sort order I'm back to square one.</p> <p>Could this just be the limitation of the nested set model? Does its use inhibit in query sorting of the output?</p>
<p>I think this is indeed a limitation of the nested set model. You can not easily sort the child nodes within their respective parent node, because the ordering of the result set is essential to reconstruct the tree structure.</p> <p>I think it is probably the best approach to keep the tree sorted when inserting, updating or deleting nodes. This even makes queries very fast, which is one of the main goals of this data structure. If you implement stored procedures for all operations, it is very easy to use.</p> <p>You can also reverse the sort order of a presorted tree. You just have to use <code>ORDER BY node.rgt DESC</code> instead of <code>ORDER BY node.lft ASC</code>.</p> <p>If you really need to support another sort criteria, you could possible implement it by adding a second <code>lft</code> and <code>rgt</code> index to each node and keep this sorted by the other criteria on every insert/update/delete.</p>
<p>Sorting Nested Sets has no limits and it's not difficult. Just sort by the LEFT bower (anchor, whatever) and it's done. If you have a LEVEL for each node, you can also pull-off correct indentation based on the Level.</p>
24,630
<p>Is there a way to view a SVG from either a file or webpage dynamically using Silver light or flash?</p> <p><strong>Edit:</strong> I am currently converting them on the server using inkscape. The only trouble with this is the time it takes to make all 60+ pages of the catalog is a little slow. It take 5 min to make it, and some customers (boss included) would like this process to be quicker.</p>
<p>Additionally Inkscape has support for exporting SVG images to XAML output. Neither of course is exactly what you are asking for as both "convert" in some manner, but to directly answer -- No, Silverlight does not interpret SVG directly. I'm not sure about Flash though.</p>
<p><strong>timheuer:</strong> Do you know if there is a command line option to make the XAML file?</p> <p><strong>EDIT:</strong> it seems that svg does not directly translate to the xaml format, as my diagrams will crash IE in XP and Vista. </p>
15,619
<p>I don't want to know how... Just how complicated....</p> <p>I'm thinking of securing a webservice or 2 based on the incoming client ipaddress of the caller. Is this in any way secure?</p> <p>Surely if the IPaddress was being spoofed then the result would have to be sent back to the address that was being spoofed and therefore not reach the spoofer?</p> <p>Update: Ok so from what I can tell.... I should create a Gettoken() method which checks the IPaddress and passes out a cryptographically significant token with a timeout to any valid IP address. This is then required by any other method before any kind of side effect is allowed.</p> <p>Since an Attacker can't (likely) get the token without having a valid IP, he will be unable to validly call any of my "dangerous" webmethods ? </p>
<p>If you're trying to do something more complex than DDoSing or triggering a security hole, then spoofing is not the answer. What you need is a system that will front for your request, thus hiding the true origin of the request. Since we're talking about HTTP traffic, an <a href="http://en.wikipedia.org/wiki/Anonymous_proxy" rel="nofollow noreferrer">Anonymous Proxy</a> will do the trick.</p> <p>For the purposes of security you're referring to, it depends on whether or not actions can be taken. If the site is purely informational, then you are safe. If the site allows actions to be performed (e.g. update this, delete that), then consider adding at least password authentication.</p> <p>Another issue to keep in mind is that anyone controlling routers between your server and the IP address you wish to allow can intercept the packets. That would allow them to have complete two-way spoofed communication without your server realizing it. If you want the information to be truly secure, use HTTPS and an authentication scheme to prevent such interceptions from happening.</p>
<p>Part of our web service security is to require clients to use public key / private key encryption (xml digital signatures) to ensure non-repudiation to ensure that only allowed clients can access the service.</p>
27,982
<p>Do you use a formal event to get people talking in your IT department? Like a <strong>monthly meetup</strong> in a social place, a <strong>internal wiki/chat</strong> space or just a regular "information market" with some <strong>presentations about technology or projects</strong> made by your staff for your staff? Do you invite Sales people to participate or is it a closed event for programmers only?</p> <p>How do you get people to participate in these events? Do you allow them to spent work time on knowledge transfer? Or do you understand it as an integral part of the work time?</p> <p>I wonder how to monitor the progress of knowledge transfer itself. How do you spot critical one-person spots of failure in your projects? There are several methods to avoid it, like staff swapping or the "fifo" attempt on bug fixing.</p> <p><em>Note:</em> Ok, this is a very very noisy question and I hope to fix it after a few comments. Sorry for the mixup.</p> <p><strong>edit</strong>: My personal experience is that there is a very high barrier for people to start contributing. It looks like they won't put in the (minimal) extra time to edit our wiki, or spend the hour in the afternoon to talk about technology topics with the developing staff. It's like people don't like our wiki, our document management system or the meeting. Maybe it's because it's all free-to-use and not forced by the management. But I don't like to force people into it - but is it the right way?</p> <p>One example: Our wiki holds pages about projects, telling who worked on it to get a first contact in case of questions. But nobody besides a colleague and me is creating this pages...</p>
<p>Knowledge Transfer and Knowledge Management have one drawback. They seem to cost an aweful lot: if everybody knows what I know, am I still needed? All the time I use to bring others up to speed, what do I gain from it?</p> <p>The best way to go about this is to be an example. Share your knowledge; in a wiki, blog about it, talk about it, make it easily accessible, and talk about the benefits you have from that: less people come to interupt and ask you stuff, as they can get an answer easily without even getting up. And show them that you are still there.</p> <p>This with all the other things mentioned will actually win out. One more thing: one of my employers kept on paying me 1/3 of my salary for another year after I left (on my own initiative), just to keep my knowledge-base up and running. Did he have to? No, it was his property anyway. But it motivated people still working for him to share their knowledge.</p>
<p>One word: Lunch</p>
7,440
<p>Does anyone have a regular expression handy that will match any legal DNS hostname or IP address?</p> <p>It's easy to write one that works 95% of the time, but I'm hoping to get something that's well tested to exactly match the latest RFC specs for DNS hostnames.</p>
<p>You can use the following regular expressions separately or by combining them in a joint OR expression.</p> <pre><code>ValidIpAddressRegex = &quot;^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$&quot;; ValidHostnameRegex = &quot;^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$&quot;; </code></pre> <p><strong>ValidIpAddressRegex</strong> matches valid IP addresses and <strong>ValidHostnameRegex</strong> valid host names. Depending on the language you use \ could have to be escaped with \.</p> <hr /> <p><strong>ValidHostnameRegex</strong> is valid as per <a href="https://www.rfc-editor.org/rfc/rfc1123" rel="noreferrer">RFC 1123</a>. Originally, <a href="https://www.rfc-editor.org/rfc/rfc952" rel="noreferrer">RFC 952</a> specified that hostname segments could not start with a digit.</p> <p><a href="http://en.wikipedia.org/wiki/Hostname" rel="noreferrer">http://en.wikipedia.org/wiki/Hostname</a></p> <blockquote> <p>The original specification of hostnames in <a href="https://www.rfc-editor.org/rfc/rfc952" rel="noreferrer">RFC 952</a>, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (<a href="https://www.rfc-editor.org/rfc/rfc1123" rel="noreferrer">RFC 1123</a>) permitted hostname labels to start with digits.</p> </blockquote> <pre><code>Valid952HostnameRegex = &quot;^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$&quot;; </code></pre>
<p>Checking for host names like... mywebsite.co.in, thangaraj.name, 18thangaraj.in, thangaraj106.in etc.,</p> <pre><code>[a-z\d+].*?\\.\w{2,4}$ </code></pre>
13,166
<p>Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about</p> <pre><code>for i in range(0, 20): for i in xrange(0, 20): </code></pre>
<p><strong>In Python 2.x:</strong></p> <ul> <li><p><code>range</code> creates a list, so if you do <code>range(1, 10000000)</code> it creates a list in memory with <code>9999999</code> elements.</p> </li> <li><p><code>xrange</code> is a sequence object that evaluates lazily.</p> </li> </ul> <p><strong>In Python 3:</strong></p> <ul> <li><code>range</code> does the equivalent of Python 2's <code>xrange</code>. To get the list, you have to explicitly use <code>list(range(...))</code>.</li> <li><code>xrange</code> no longer exists.</li> </ul>
<p>See this <a href="http://avinashv.net/2008/05/pythons-range-and-xrange/" rel="nofollow noreferrer">post</a> to find difference between range and xrange:</p> <p>To quote:</p> <blockquote> <p><code>range</code> returns exactly what you think: a list of consecutive integers, of a defined length beginning with 0. <code>xrange</code>, however, returns an <em>"xrange object"</em>, which acts a great deal like an iterator</p> </blockquote>
12,054
<p>Why is the <a href="http://www.networksorcery.com/enp/protocol/udp.htm#Checksum" rel="noreferrer">Pseudo header</a> prepended to the UDP datagram for the computation of the UDP checksum? What's the rational behind this?</p>
<p>From the TCP or UDP point of view, the packet does not contain IP addresses. (IP being the layer beneath them.)</p> <p>Thus, to do a proper checksum, a "pseudo header" is included. It's "pseudo", because it is not actaully part of the UDP datagram. It contains the most important parts of the IP header, that is, source and destination address, protocol number and data length. </p> <p>This is to ensure that the UDP checksum takes into account these fields.</p>
<p>Pseudo IP header contains the source IP, destination IP, protocol and Total length fields. Now, by including these fields in TCP checksum, we are verifying the checksum for these fields both at Network layer and Transport layer, thus doing a double check to ensure that the data is delivered to the correct host. </p>
46,825
<p>Does the C++ compiler optimize the multiply by two operation <code>x*2</code> to a bitshift operation <code>x&lt;&lt;1</code>?</p> <p>I would love to believe that yes.</p>
<p>Actually VS2008 optimizes this to x+x:</p> <pre><code>01391000 push ecx int x = 0; scanf("%d", &amp;x); 01391001 lea eax,[esp] 01391004 push eax 01391005 push offset string "%d" (13920F4h) 0139100A mov dword ptr [esp+8],0 01391012 call dword ptr [__imp__scanf (13920A4h)] int y = x * 2; 01391018 mov ecx,dword ptr [esp+8] 0139101C lea edx,[ecx+ecx] </code></pre> <p>In an x64 build it is even more explicit and uses:</p> <pre><code> int y = x * 2; 000000013FB9101E mov edx,dword ptr [x] printf("%d", y); 000000013FB91022 lea rcx,[string "%d" (13FB921B0h)] 000000013FB91029 add edx,edx </code></pre> <p>This is will the optimization settings on 'Maximize speed' (/O2)</p>
<p>It depends on what compiler you have. Visual C++ for example is notoriously poor in optimizing. If you edit your post to say what compiler you are using, it would be easier to answer. </p>
29,091
<p>I want to get a list of all Django auth user with a specific permission group, something like this:</p> <pre><code>user_dict = { 'queryset': User.objects.filter(permisson='blogger') } </code></pre> <p>I cannot find out how to do this. How are the permissions groups saved in the user model?</p>
<p>If you want to get list of users by permission, look at this variant:</p> <pre><code>from django.contrib.auth.models import User, Permission from django.db.models import Q perm = Permission.objects.get(codename='blogger') users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct() </code></pre>
<p>Based on @Augusto's answer, I did the following with a model manager and using the authtools library. This is in <code>querysets.py</code>:</p> <pre><code>from django.db.models import Q from authtools.models import UserManager as AuthUserManager class UserManager(AuthUserManager): def get_users_with_perm(self, perm_name): return self.filter( Q(user_permissions__codename=perm_name) | Q(groups__permissions__codename=perm_name)).distinct() </code></pre> <p>And then in <code>models.py</code>:</p> <pre><code>from django.db import models from authtools.models import AbstractEmailUser from .querysets import UserManager class User(AbstractEmailUser): objects = UserManager() </code></pre>
49,547
<p>I see in C++ there are multiple ways to allocate and free data and I understand that when you call <code>malloc</code> you should call <code>free</code> and when you use the <code>new</code> operator you should pair with <code>delete</code> and it is a mistake to mix the two (e.g. Calling <code>free()</code> on something that was created with the <code>new</code> operator), but I'm not clear on when I should use <code>malloc</code>/ <code>free</code> and when I should use <code>new</code>/ <code>delete</code> in my real world programs.</p> <p>If you're a C++ expert, please let me know any rules of thumb or conventions you follow in this regard.</p>
<p>Unless you are forced to use C, you should <strong>never use</strong> <code>malloc</code>. Always use <code>new</code>.</p> <p>If you need a big chunk of data just do something like:</p> <pre><code>char *pBuffer = new char[1024]; </code></pre> <p>Be careful though this is not correct:</p> <pre><code>//This is incorrect - may delete only one element, may corrupt the heap, or worse... delete pBuffer; </code></pre> <p>Instead you should do this when deleting an array of data:</p> <pre><code>//This deletes all items in the array delete[] pBuffer; </code></pre> <p>The <code>new</code> keyword is the C++ way of doing it, and it will ensure that your type will have its <strong>constructor called</strong>. The <code>new</code> keyword is also more <strong>type-safe</strong> whereas <code>malloc</code> is not type-safe at all. </p> <p>The only way I could think that would be beneficial to use <code>malloc</code> would be if you needed to <strong>change the size of your buffer</strong> of data. The <code>new</code> keyword does not have an analogous way like <code>realloc</code>. The <code>realloc</code> function might be able to extend the size of a chunk of memory for you more efficiently. </p> <p>It is worth mentioning that you cannot mix <code>new</code>/<code>free</code> and <code>malloc</code>/<code>delete</code>.</p> <p>Note: Some answers in this question are invalid. </p> <pre><code>int* p_scalar = new int(5); // Does not create 5 elements, but initializes to 5 int* p_array = new int[5]; // Creates 5 elements </code></pre>
<p>malloc() is used to dynamically assign memory in C while the same work is done by new() in c++. So you cannot mix coding conventions of 2 languages. It would be good if you asked for difference between calloc and malloc()</p>
22,311
<p>Most of the implementations I find require a hardware instruction to do this. However I strongly doubt this is required (if it is, I can't figure out why...)</p>
<p>You don't need a test and set instruction to get mutual exclusion locking, if thats what you're asking. Dijkstra described the first mutual exclusion algorithm I am aware of, in 1965. The title of the paper was "Solution of a problem in concurrent programming control", search Google for a copy near you. The original algorithm required no special support from the hardware at all, but providing an atomic instruction in the CPU dramatically improves the performance. </p> <p>Test-and-set, atomic swap, and load-linked + store-conditional are all common primitives for CPUs to provide. All can be used to implement mutual exclusion, which can then be used to implement whatever locking semantics you want.</p>
<p>If you'd like a cross-arch way to do so, and are using gcc, then you can use gcc's atomic builtins:</p> <p><a href="http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html" rel="nofollow noreferrer">http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html</a></p> <p>Calling these will result in a hardware specific machine instruction for the current build architecture. On those that do not support them, the compile will fail. (I think...)</p>
13,275
<p>Is anyone aware of any text editors with Visual Studio editor functionality? Specifically, I'm looking for the following features:</p> <p>CTRL+C anywhere on the line, no text selected -> the whole line is copied</p> <p>CTRL+X or SHIFT+DEL anywhere on the line, no text selected -> the whole line cut Thanks!</p>
<p><a href="http://www.activestate.com/Products/komodo_ide/komodo_edit.mhtml" rel="noreferrer">Komodo Edit</a> does the two things you specified.</p> <p>I use it all the time as a secondary editor, for various scripting and other programming tasks. Tons of features, free, open source.</p>
<p><a href="http://www.slickedit.com/" rel="nofollow noreferrer">Slickedit</a></p>
15,653
<p>I've been able to find <em>Xaml Object Mapping Specification</em>, <em>WPF Xaml Vocabulary Specification</em>, and <em>Silverlight Xaml Vocabulary Specification</em> documents online but no <em>WF Xaml Vocabulary Specification</em> document for Windows Workflows. I want to be able to specify workflows without using a Visual Studio IDE.</p> <p>Does anybody know if this specification exists and if so, where to find it?</p>
<p>WF vocabulary specification is not yet published.</p> <p>All other Xaml-related specifications can be found here:</p> <p><a href="http://www.microsoft.com/en-us/download/details.aspx?id=19600" rel="nofollow">http://www.microsoft.com/en-us/download/details.aspx?id=19600</a></p>
<p><a href="http://www.microsoft.com/whdc/xps/xpsspec.mspx" rel="nofollow noreferrer">xps spec</a></p> <p>may or may not be up to date with the ecma work</p> <p><a href="http://download.microsoft.com/download/0/A/6/0A6F7755-9AF5-448B-907D-13985ACCF53E/[MS-XAML].pdf" rel="nofollow noreferrer">XAML object spec</a> </p> <p><a href="http://download.microsoft.com/download/0/A/6/0A6F7755-9AF5-448B-907D-13985ACCF53E/[MS-WPFXV].pdf" rel="nofollow noreferrer">WPF XAML spec 2006</a></p> <p><a href="http://download.microsoft.com/download/0/A/6/0A6F7755-9AF5-448B-907D-13985ACCF53E/[MS-SLXV].pdf" rel="nofollow noreferrer">Silverlight xaml spec</a></p> <p>So far there is no WF spec. </p> <p>Douglas</p>
33,764
<p>I have some data stored as <code>ArrayList</code>. And when I want to backup this data,java bounds two objects forever. Which means when I change values in data <code>ArrayList</code> this changes come to backup. I tried to copy values from data separately to backup in the loop, tried to use method <code>data.clone()</code> — nothing helps.</p>
<p>I think you need to <code>.clone()</code> the individual objects. Cloning the <code>ArrayList</code> is not "deep"; it will only clone the references to the object.</p>
<p>You could write an object that wraps two ArrayLists. Anything write it so that it adds, removes, and modifies data in both at the same time.</p>
38,936
<p>I'd like to render to svg data in a swf at runtime (not in Flex - not using degrafa) - how would I go about doing that?</p>
<p>The Ajaxian blog had a post about this today.</p> <p><a href="http://ajaxian.com/archives/the-state-of-svg-browser-support-using-flash-for-svg-in-internet-explorer" rel="nofollow noreferrer">http://ajaxian.com/archives/the-state-of-svg-browser-support-using-flash-for-svg-in-internet-explorer</a></p>
<p>The Ajaxian blog had a post about this today.</p> <p><a href="http://ajaxian.com/archives/the-state-of-svg-browser-support-using-flash-for-svg-in-internet-explorer" rel="nofollow noreferrer">http://ajaxian.com/archives/the-state-of-svg-browser-support-using-flash-for-svg-in-internet-explorer</a></p>
5,291
<p>I am designing a system which will at some point require to send email notifications. So I am looking for a simple way to do this. Some background: the system will be running on Linux platform, there will be a working SMTP server somewhere on the network, the operator will configure its address, server credentials if required and a list of target email addresses (no, I am NOT working on a mass email system ;-). The process which will need to send the emails will be probably written in C, but super performance is not really a requirement, there won't be a lot of mails to send, so invoking some command-line tool is an acceptable option. Basically, what I tried in the past for similar tasks:</p> <ul> <li>Invoking local sendmail in command-line mode. This is a nightmare, because of the necessity to support the cryptic sendmail config. This is what I would really like to avoid.</li> <li>Talking to SMTP server port directly (EHLO, etc). This IS an option, but a bit too low-level for year 2008 ;-).</li> <li>Using some MUA which talks to local sendmail daemon acting as a mail relay. This is not nice exactly because it requires having local sendmail up and configured. </li> </ul> <p>So what I need is basically some library for C language or a simple command-line MUA which should be able to talk to remote sendmail (i.e. to talk to SMTP server that I tell it to), <b>but not requiring a local mail relay</b>. </p> <p>Any ideas are welcome!</p>
<p>mail(1) or mailx(1)<br> Also, since you have a local MTA you can pipe the message directly to sendmail(8) (which - despite its name - is a somewhat standard interface used by many MTA for injecting the mail)</p>
<p>Perl's <a href="http://search.cpan.org/~markov/MailTools-2.04/lib/Mail/Mailer.pod" rel="nofollow noreferrer">Mail::Mailer</a> provides a very easy way to generate mail through the local MTA (example from perldoc -q mail):</p> <pre><code>use Mail::Mailer; my $mailer = Mail::Mailer-&gt;new(); $mailer-&gt;open({ From =&gt; $from_address, To =&gt; $to_address, Subject =&gt; $subject, }) or die "Can’t open: $!\n"; print $mailer $body; $mailer-&gt;close(); </code></pre> <p>If you're using C, you can either write a script wrapper around something using Mail::Mailer, or directly invoke the MTA via the shell and write formatted message into it.</p>
44,435
<p>In general, is it a best practice to have simple POJO Java classes implement java.io.Serializable?</p>
<p>Generally not. Joshua Bloch says to <a href="http://my.safaribooksonline.com/0201310058/ch10lev1sec1" rel="noreferrer" title="Implement Serializable judiciously">implement Serializable judiciously</a>. A summary of drawbacks that he describes:</p> <ul> <li>decreases flexibility of changing class implementation later - the serialized form is part of the class's API</li> <li>makes some bugs and security holes more likely - an attacker can access class internals within the serialized byte stream</li> <li>increases test burden - now you have to test serialization!</li> <li>burdens authors of subclasses - they have to make their subclasses Serializable too</li> </ul> <p>Of course, sometimes you need a POJO to implement Serializable, say for RMI, but if the need isn't there, your code will be simpler and more secure without it.</p>
<p>One thing I've done to address the fact that the serialized form is not backwards compatible (say when dynamically reloading a class on a running system), is load the fields I want to save into a hashmap and then serializing that. That way, I can always deserialize in the data, even if there are missing fields. You might have to provide defaults for missing keys, but it's better than messing up field order.</p>
26,984
<p>I've got an HTML "select" element which I'm updating dynamically with code something like this:</p> <pre><code>var selector = document.getElementById('selectorId'); for (var i = 0; i &lt; data.length; ++i) { var opt = document.createElement('option'); opt.value = data[i].id; opt.text = data[i].name; selector.appendChild(opt); } </code></pre> <p>Works fine in Firefox, but IE7 doesn't resize the list box to fit the new data. If the list box is initially empty (which it is in my case), you can hardly see any of the options I've added. Is there a better way to do this? Or a way to patch it up to work in IE?</p>
<p>Set the <code>innerHTML</code> property of the option objects, instead of their <code>text</code>.</p> <pre><code>var selector = document.getElementById('selectorId'); for (var i = 0; i &lt; data.length; ++i) { var opt = document.createElement('option'); opt.value = data[i].id; opt.innerHTML = data[i].name; selector.appendChild(opt); } </code></pre> <p>Works on IE6, just tested. Does not break on FF3, so I guess this is it.</p> <p><em>(I chose "innerHTML" because this works across browsers. To set the literal text, you have to use "innerText" on IE, and "textContent" on FF, and you probably have to test it elsewhere as well. As long as there are no special characters (&amp;, &lt;, &gt;) in the "name" properties, "innerHTML" will be enough.)</em></p>
<p>You could try replacing the entire select element from generated html code, or as a hack removing the element from the DOM and readding it.</p>
32,673
<p>Every software development professional (and especially project managers) has to deal with a never ending stream of e-mails. What is the best way of organising them in MS Outlook?</p> <p>Obviously some fancy issue tracking tools give more flexibility but I am interested in plain vanilla approach that can be deployed within most organisations. </p> <p>P.S. Finding e-mails is generally the least of the problems that needs to be addressed. Search nowdays is pretty good.</p>
<p>Within my main inbox I have 3 sub folers: Do, Done, Defer and 3 macros to move the selected folder into the relevent folder. (alt-1 moves the selected mail to done and then selects the next mail). Each day I quickly filter my inbox into the three folders. I can process several hundred mails in 20 mins or so.</p> <p>Do, something I expect to process today. Done, something I don't care about/have read and understood, I dont expect to refer back to these today. Defer, something I will do something about but not today.</p> <p>At the end of processing I expect my inbox to be empty. </p> <p>At the end of the day all mail items in Do move to Defer (I dont want to keep things in Done overnight).</p> <p>At the start of the day all items in Defer are filtered using the rules above, I dont want to leave things in Defer for more then a day or 2. If stuff hangs around for too long I will add it to my diary to process later.</p> <p>At the end of the day all mail in Done is copied into an archive folder based on the month/year. Done is just a parking place for things to be archived.</p> <p>I use a tool to index my archive, I actually use X1 but google desktop is an excellent alternative.</p> <p>I filter out any important facts i would like to refer back to in outlook notes.</p> <p>I filter out any tasks I would like to recal into omni focus (<a href="http://www.omnigroup.com/applications/omnifocus/" rel="noreferrer">http://www.omnigroup.com/applications/omnifocus/</a>) the best GTD I have found.</p> <p>I DO NOT EVER use my inbox as a todo list or a mechanism for recording subtle facts I want to recall later. I know a lot of people do but IMHO its just a bad way to be. </p> <p>(cross posted to LJ).</p> <p>EDIT.</p> <p>Oh per a post above I also filter any mail not posted to me directly, by the mailing list the mail was sent to. I give different amounts of attention to each mailing list. I do follow the mechanism above for each mailing list but some I glance at and some I process in detail.</p> <p>ReEDIT</p> <p>In comments I was asked to provide the source for the macros I mentioned above. I DONT suggest this is seen as an example of good VBA, I am pretty sure it was sourced from the interweb and adapted for my purposes. It has worked reliably for many years.</p> <pre><code>Sub MoveToDone() On Error Resume Next Dim objFolder As Outlook.MAPIFolder, objInbox As Outlook.MAPIFolder Dim objNS As Outlook.NameSpace, objItem As Outlook.MailItem Set objNS = Application.GetNamespace("MAPI") Set objInbox = objNS.GetDefaultFolder(olFolderInbox) Set objFolder = objInbox.Folders("Done") 'Assume this is a mail folder If objFolder Is Nothing Then MsgBox "This folder doesn't exist!", vbOKOnly + vbExclamation, "INVALID FOLDER" End If If Application.ActiveExplorer.Selection.Count = 0 Then 'Require that this procedure be called only when a message is selected MsgBox "No msgs selected", vbOKOnly + vbExclamation, "NO_MSG_SELECTED" Exit Sub End If For Each objItem In Application.ActiveExplorer.Selection If objFolder.DefaultItemType = olMailItem Then If objItem.Class = olMail Then objItem.Move objFolder End If End If Next Set objItem = Nothing Set objFolder = Nothing Set objInbox = Nothing Set objNS = Nothing End Sub </code></pre>
<p>Folders! Nice and simple.</p> <p>I have found these to be invaluable over the years to help organise a separate emails on a customer or project basis. Even when there's multiple parties involved i only have to look in 2 folders at most to find what i'm after.</p> <p>Edit: Similar to what tloach said, i use the inbox essentailly as a todo list of things i still need to look at.</p>
21,987
<p>If the owner of a web site wants to track who their users are as much as possible, what things can they capture (and how). You might want to know about this in order to capture information on a site you create or, as a user, to <em>prevent</em> a site from capturing data on you.</p> <p>Here is a starting list, but I'm sure I have missed some important ones:</p> <ol> <li>Referrer (what web page had the link you followed to get here). This is a HTTP header.</li> <li>IP Address of the machine you are browsing from. This is available with the HTTP headers.</li> <li>User Agent (what browser you are using). This is a HTTP header.</li> <li>Cookie placed on a previous visit. This is a header, available only if a cookie was placed earlier and was not deleted by the user.</li> <li>Flash Cookie placed on a previous visit. Some users turn off cookies, but <em>very</em> few know how to turn off Flash cookies. Works like a normal cookie although it depends on Flash.</li> <li>Web Bugs. Place something small (like a transparent single-pixel GIF) on the page that's served up from a 3rd party. Some third parties (such as DoubleClick) will have their own cookies and can correlate with other visits the user makes (for a fee!).</li> </ol> <p>Those are the common ones I think of, but there have to be LOTS of unusual ones. For instance, this:</p> <ol> <li>Time on the user's clock. <a href="https://stackoverflow.com/questions/13/determining-web-users-time-zone">Use JavaScript</a> to transmit it.</li> </ol> <p>... which I had never heard of before reading it here.</p> <hr> <p>ADDED LATER (after reading <a href="http://www.joelonsoftware.com/items/2008/09/15.html" rel="nofollow noreferrer">this</a>):</p> <p><strong>Please try to put just ONE item per answer, then we can use voting up to sort out the better/more-interesting ones.</strong> The list below is probably less effective.</p> <p>Ah well... NEXT time I ask a question like this I'll set it up better.</p> <hr> <p>And here are some of the best answers I got:</p> <ol> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87413">James</a> points out that IE transmits the .NET framework version.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87454">AviewAnew</a> points out that one can <a href="http://ha.ckers.org/weird/CSS-history-hack.html" rel="nofollow noreferrer">find what sites you have visited</a>.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87529">Mecki</a> points out that Screen Resolution can be determined.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87529">Mecki</a> <em>also</em> points out that any auto-fill information your browser has cached can be determined, by creating a hidden field, then reading it with JavaScript.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87463">jjrv</a> points out that Flash can list the fonts on the user's machine.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87473">Kent</a> points out that you can find out <a href="http://weblogs.asp.net/jezell/archive/2006/08/25/Stealing-History.aspx" rel="nofollow noreferrer">what websites a person has visited</a>.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87493">Silver Dragon</a> points out you can determine the location of the mouse within the browsing window using Flash and AJAX.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87494">Jim</a> points out that you can tell what language the user has configured in their browser from a HTTP header.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87494">Jim</a> also mentions that you can detect whether people are using Greasemonkey or something similar to modify the page.</li> </ol>
<ul> <li>There's a header that can include information about a proxy server the user is using, and that can also include the user's IP address (in which case the other IP is the one of the proxy)</li> <li>Screen Resolution, Operating System, Color Depth, size of your taskbar (compare max and current resolution), if Java is enabled, Anti-Aliasing Fonts, Plugins Installed all via Javascript</li> <li>A Java applet can give you a bunch of information as well, but I don't know what.</li> <li><a href="http://ha.ckers.org/weird/CSS-history-hack.html" rel="nofollow noreferrer">Sites you've visited</a></li> <li><a href="http://www.slideshare.net/jeremiahgrossman/top-ten-hacks-of-2007" rel="nofollow noreferrer">Details of your local network</a> such as active hosts, web servers. Paper Also outlines drive-by printing, drive-by router modification</li> </ul> <p>And this is all assuming the attacker doesn't pull off arbitrary code execution</p>
<p>.NET framework versions are transmitted in IE, in the User Agent.</p>
11,290
<p>Why does using Fiddler break my site sometimes on page transitions.</p> <p>After a server side redirect -- in the http response (as found in Fiddler) I get this:</p> <p>Object moved</p> <h2>Object moved to here.</h2> <p></p> <p>The site is an ASP.NET 1.1 / VB.NET 1.1 [sic] site. </p> <p>Why doesnt Fiddler just go there for me? i dont get it.</p> <p>I'm fine with this issue when developing but I'm worried that other proxy servers might cause this issue for 'real customers'. Im not even clear exactly what is going on.</p>
<p>That's actually what Response.Redirect does. It sends a 302 - Object moved response to the user-agent. The user-agent then automatically goes to the URL specified in the 302 response. If you need a real server-side redirect without round-tripping to the client, try Server.Transfer.</p>
<p>Thanks user15310, it works with Server.Transfer</p> <pre><code>Server.Transfer("newpage.aspx", true); </code></pre> <hr> <p>Firstly, transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.</p> <p>But watch out: because the "transfer" process can work on only those sites running on the server, you can't use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.</p> <p>Secondly, Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.</p> <p>That's not all: The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.</p> <p><strong>Read more here:</strong> <a href="http://www.developer.com/net/asp/article.php/3299641/ServerTransfer-Vs-ResponseRedirect.htm" rel="nofollow">http://www.developer.com/net/asp/article.php/3299641/ServerTransfer-Vs-ResponseRedirect.htm</a></p>
30,518
<p>QA tester was reading HTML/JS code to write a functional test of a web form, and saw:</p> <pre><code>if (form_field == empty) { ...do stuff for empty field } else if (form_field != empty) { ...do stuff for non-empty field } else { ...do stuff that will never be done } </code></pre> <p>After a couple embarrassing attempts, tester realized that they couldn't trigger the alert strings hidden in the third block.</p> <p>Things I'm wondering are if this Is this problem more or less language specific (can non-JS people learn lessons here?) and are there legitimate reasons code ended up this way?</p> <p>How can I find/address the problem?</p>
<p>Although the third block can't trigger in Javascript, that is not true in all languages. In T-SQL:</p> <pre><code>declare @test as int set @test = null if @test = 1 print 1 else if not @test = 1 print 2 else print 3 </code></pre> <p>This will print 3, because NULL is neither equal to, nor not equal to any other value.</p>
<p>In the general form</p> <pre><code>if (a) //1 else if (!a) //2 else //3 </code></pre> <p>can always be reduced to </p> <pre><code>if (a) //1 else //2 </code></pre> <p>with no side-effects.</p>
28,039
<p>Here at work, we often need to find a string from the list of strings that is the closest match to some other input string. Currently, we are using Needleman-Wunsch algorithm. The algorithm often returns a lot of false-positives (if we set the minimum-score too low), sometimes it doesn't find a match when it should (when the minimum-score is too high) and, most of the times, we need to check the results by hand. We thought we should try other alternatives.</p> <p>Do you have any experiences with the algorithms? Do you know how the algorithms compare to one another?</p> <p>I'd really appreciate some advice.</p> <p>PS: We're coding in C#, but you shouldn't care about it - I'm asking about the algorithms in general.</p> <hr> <p>Oh, I'm sorry I forgot to mention that.</p> <p>No, we're not using it to match duplicate data. We have a list of strings that we are looking for - we call it search-list. And then we need to process texts from various sources (like RSS feeds, web-sites, forums, etc.) - we extract parts of those texts (there are entire sets of rules for that, but that's irrelevant) and we need to match those against the search-list. If the string matches one of the strings in search-list - we need to do some further processing of the thing (which is also irrelevant).</p> <p>We can not perform the normal comparison, because the strings extracted from the outside sources, most of the times, include some extra words etc.</p> <p>Anyway, it's not for duplicate detection.</p>
<p>OK, Needleman-Wunsch(NW) is a classic end-to-end ("global") aligner from the bioinformatics literature. It was long ago available as "align" and "align0" in the FASTA package. The difference was that the "0" version wasn't as biased about avoiding end-gapping, which often allowed favoring high-quality internal matches easier. Smith-Waterman, I suspect you're aware, is a local aligner and is the original basis of BLAST. FASTA had it's own local aligner as well that was slightly different. All of these are essentially heuristic methods for estimating Levenshtein distance relevant to a scoring metric for individual character pairs (in bioinformatics, often given by Dayhoff/"PAM", Henikoff&amp;Henikoff, or other matrices and usually replaced with something simpler and more reasonably reflective of replacements in linguistic word morphology when applied to natural language).</p> <p>Let's not be precious about labels: Levenshtein distance, as referenced in practice at least, is basically edit distance and you have to estimate it because it's not feasible to compute it generally, and it's expensive to compute exactly even in interesting special cases: the water gets deep quick there, and thus we have heuristic methods of long and good repute.</p> <p>Now as to your own problem: several years ago, I had to check the accuracy of short DNA reads against reference sequence known to be correct and I came up with something I called "anchored alignments".</p> <p>The idea is to take your reference string set and "digest" it by finding all locations where a given N-character substring occurs. Choose N so that the table you build is not too big but also so that substrings of length N are not too common. For small alphabets like DNA bases, it's possible to come up with a perfect hash on strings of N characters and make a table and chain the matches in a linked list from each bin. The list entries must identify the sequence and start position of the substring that maps to the bin in whose list they occur. These are "anchors" in the list of strings to be searched at which an NW alignment is likely to be useful.</p> <p>When processing a query string, you take the N characters starting at some offset K in the query string, hash them, look up their bin, and if the list for that bin is nonempty then you go through all the list records and perform alignments between the query string and the search string referenced in the record. When doing these alignments, you line up the query string and the search string <em>at</em> the anchor and extract a substring of the search string that is the same length as the query string and which contains that anchor at the same offset, K.</p> <p>If you choose a long enough anchor length N, and a reasonable set of values of offset K (they can be spread across the query string or be restricted to low offsets) you should get a subset of possible alignments and often will get clearer winners. Typically you will want to use the less end-biased align0-like NW aligner.</p> <p>This method tries to boost NW a bit by restricting it's input and this has a performance gain because you do less alignments and they are more often between similar sequences. Another good thing to do with your NW aligner is to allow it to give up after some amount or length of gapping occurs to cut costs, especially if you know you're not going to see or be interested in middling-quality matches.</p> <p>Finally, this method was used on a system with small alphabets, with K restricted to the first 100 or so positions in the query string and with search strings much larger than the queries (the DNA reads were around 1000 bases and the search strings were on the order of 10000, so I was looking for approximate substring matches justified by an estimate of edit distance specifically). Adapting this methodology to natural language will require some careful thought: you lose on alphabet size but you gain if your query strings and search strings are of similar length.</p> <p>Either way, allowing more than one anchor from different ends of the query string to be used simultaneously might be helpful in further filtering data fed to NW. If you do this, be prepared to possibly send overlapping strings each containing one of the two anchors to the aligner and then reconcile the alignments... or possibly further modify NW to emphasize keeping your anchors mostly intact during an alignment using penalty modification during the algorithm's execution.</p> <p>Hope this is helpful or at least interesting.</p>
<p>To expand on Cd-MaN's answer, it sounds like you're facing a normalization problem. It isn't obvious how to handle scores between alignments with varying lengths.</p> <p>Given what you are interested in, you may want to obtain p-values for your alignment. If you are using Needleman-Wunsch, you can obtain these p-values using Karlin-Altschul statistics <a href="http://www.ncbi.nlm.nih.gov/BLAST/tutorial/Altschul-1.html" rel="nofollow">http://www.ncbi.nlm.nih.gov/BLAST/tutorial/Altschul-1.html</a></p> <p>BLAST will can local alignment and evaluate them using these statistics. If you are concerned about speed, this would be a good tool to use.</p> <p>Another option is to use HMMER. HMMER uses Profile Hidden Markov Models to align sequences. Personally, I think this is a more powerful approach since it also provides positional information. <a href="http://hmmer.janelia.org/" rel="nofollow">http://hmmer.janelia.org/</a></p>
7,176
<p>I have a batch file that does this.</p> <p>ECHO A41,35,0,a,1,1,N,"Mr ZACHARY KAPLAN">> test.txt </p> <p>There are about 30k similar lines. It takes the batch file about 5 hours to run. </p> <p>Is there a way to speed this up?</p> <p>/Jeanre</p>
<p>Try this:</p> <p>Put an <code>ECHO OFF</code> at the top of the batch file.</p> <p>Then change each line to:</p> <pre><code>ECHO A41,35,0,a,1,1,N,"Mr ZACHARY KAPLAN" </code></pre> <p>and call your batch file:</p> <p>mybatch.bat >> test.txt</p> <p>Edit the first line to remove the echo off print out.</p>
<p>Here's an example using a Java program - with BufferedReader/PrintWriter</p> <p><a href="http://www.javafaq.nu/java-example-code-126.html" rel="nofollow noreferrer">http://www.javafaq.nu/java-example-code-126.html</a></p> <p>You can also use a BufferedReader and BufferedWriter</p> <p><a href="http://java.sun.com/docs/books/tutorial/essential/io/buffers.html" rel="nofollow noreferrer">http://java.sun.com/docs/books/tutorial/essential/io/buffers.html</a></p> <p><a href="http://leepoint.net/notes-java/io/10file/10readfile.html" rel="nofollow noreferrer">http://leepoint.net/notes-java/io/10file/10readfile.html</a></p>
40,877
<p>I have been trying to link to Pb (11.5) generated native Win32 dlls: both from a different Pb app and from a .net (2.0) app. I am aware that registered COM objects are visible to Pb. What I want to do is have Pb (running 11.5 Enterprise) call functions in a native Win32 dll--not COM. I also want to go the other way: I want a Win32 exe (both native and .net) to call a function in a Pb generated dll. I've had limited success.</p> <p><strong>Scenario 1: Pb generates native Win32 exe &amp; dll.</strong></p> <p>I created a simple app that includes separate pbl (called shared.pbl) with some trivial functions (including one that returns the string HelloWorld). The project builds to an exe and a separate dll. It works (clicking a button shows the text HelloWorld in a label).</p> <p>In a <em>separate</em> Pb workspace I create a near identical app, but <em>no</em> shared.pbl. I declare an external function to reference the shared.dll from the first workspace:</p> <pre><code> function int GetSystemMetrics( int index ) library "user32.dll"; function int f_rtn_int( int number ) library "shared.dll"; </code></pre> <p>running the app--clicking a button tied to GetSystemMetrics() works. Clicking a second button to access shared.dll fails with the "Error calling external function ..." message.</p> <p>The <em>only</em> way I have been able to get the second app to work is to <em>add</em> the shared.dll under the library list tab on the target properties. <em>However</em> this seems to cause the contents of the dll to be embedded in the generated exe--I can delete shared.dll and the second app runs just fine!</p> <p><strong><em>How do I reference an external Win32 dll in Pb w/o having the dll embedded in the generated Pb code?</em></strong> Remember, shared.dll was generated by Pb in a separate workspace.</p> <p><strong>Scenario 2: .Net exe accesses a Pb generated dll</strong></p> <p>I next created a simple .net app (.net v2.0, vs2005) with parallel functionality to the Pb apps. I reference shared.dll:</p> <pre><code> [DllImport( "user32.dll" )] static extern int GetSystemMetrics( int smIndex ); [DllImport( "shared.dll" )] static extern string f_get_hello_world(); </code></pre> <p>and try to call the HelloWorld function and I get the .net error:</p> <pre><code> Unable to find an entry point named 'f_get_hello_world' in DLL 'shared.dll' </code></pre> <p>Using an editor/dissasembler I discover that the function name has been mangled into "_getVtableInfo_f_get_hello_world@12". I tried different naming variations on the declaration and call w/o luck.</p> <p><strong><em>Is it possible to reference a native Win32 dll created by Pb from another language (c++, c#)? If so, how?</em></strong></p>
<p>Basically, you don't. You can create a COM object project, or with 11 or 11.5 you can create a .NET assembly. The DLLs created by "native" generation aren't standard Windows DLLs, so can't be called with normal DLL methods.</p> <p>Good luck,</p> <p>Terry.</p>
<p>If Pb obeys "extern C" on your function definitions, then it should export them with unmangled names.</p> <p>For your other question of why it seems to be OK to delete the dll and the program still runs, I can only give a slightly possible guess: Look to see if some tool made another copy of the dll and it still exists.</p>
46,609
<p>In C#.Net WPF During UserControl.Load -></p> <p>What is the best way of showing a whirling circle / 'Loading' Indicator on the UserControl until it has finished gathering data and rendering it's contents?</p>
<p>I generally would create a layout like this:</p> <pre><code>&lt;Grid&gt; &lt;Grid x:Name="MainContent" IsEnabled="False"&gt; ... &lt;/Grid&gt; &lt;Grid x:Name="LoadingIndicatorPanel"&gt; ... &lt;/Grid&gt; &lt;/Grid&gt; </code></pre> <p>Then I load the data on a worker thread, and when it's finished I update the UI under the "MainContent" grid and enable the grid, then set the LoadingIndicatorPanel's Visibility to Collapsed.</p> <p>I'm not sure if this is what you were asking or if you wanted to know how to show an animation in the loading label. If it's the animation you're after, please update your question to be more specific.</p>
<p>If you are running it on Vista, you could also just use the default wait cursor.</p> <p>this.Cursor = Cursors.Wait;</p>
11,983
<p>I'm writing a Flash game, pretty intensive on CPU.</p> <p>Besides optimizing it a lot, I would like to be able to play it as players on slow PC's will, because I have a good CPU and I would like to make it also playable on bad CPU's</p> <p>First I thought that virtualization would help, but I've tried vmware player with an ubunto image and I can't find anywhere how to do this.</p> <p>Buying an old PC is <a href="https://stackoverflow.com/questions/284051/emulate-old-pc#284316">not an option</a>, as I prefer not having machines around only for this.</p> <p>What I need is something like a software underclocker, or a virtual machine where I can specify low specs for CPU and RAM.</p> <p>Anyone know how to do this?</p>
<p><a href="http://www.microsoft.com/windows/downloads/virtualpc/default.mspx" rel="noreferrer">Microsoft Virtual PC</a> is VM software that allows you to determine the speed of the CPU, RAM settings, and Video Card settings for each virtual Machine you create. From the website:</p> <blockquote> <p><strong>Configurability</strong> - After installing Virtual PC, you can configure it to suit your requirements. Virtual PC has a number of settings that control how the product interacts with the physical computer, allocates resources, and so on.</p> </blockquote> <p>I've used it to emulate a 400mhz PC with 128 Megs of RAM before.</p> <p>Edit:</p> <p>A Virtual Machine on Virtual PC will be slower than your host PC. I remember in VPC 2004, it would even say what the mHz speed it was virtualising was. That is no longer in Virtual PC 2007, but some digging shows that the Microsoft guys have addressed this very issue.</p> <p>From their website's <a href="http://blogs.msdn.com/virtual_pc_guy/archive/2007/05/14/slowing-down-virtual-machines.aspx" rel="noreferrer">blog</a> (given that it may disappear one day):</p> <blockquote> <p>Well - maybe an emulation solution is better for your needs. Or, maybe you need to invest in some older hardware. Or - you could pursue the use of 'slow down' software inside of the virtual machine. Some programs that I have used with varying levels of success include:</p> <ul> <li>For DOS: <ul> <li><a href="http://members.aol.com/bretjohn/programs/slodn310.zip" rel="noreferrer">SlowDown</a> or <a href="http://www.hpaa.com/moslo/basic.asp" rel="noreferrer">MoSlo</a></li> </ul></li> <li>For Windows: <ul> <li><a href="http://wiw.org/~jess/turbo.html" rel="noreferrer">Turbo</a></li> </ul></li> </ul> <p>One final comment on this topic - some people have noticed that some older DOS programs that are known to crash on fast hardware actually run perfectly inside of Virtual PC / Virtual Server. The reason for this is that a long time ago in Virtual PC development, we put in some code to detect the problematic routines in some common DOS libraries (checkout this for an example reference) and to patch these binaries 'on the fly' so that they would run correctly inside of the virtual machine.</p> </blockquote> <p>I hope that helps.</p>
<p><a href="http://www.youtube.com/watch?v=dXQ_Y6u9IPw" rel="nofollow noreferrer">DOSBOX</a> emulates an old PC. It is intended to play old PC games. Some of these games must not run too fast and often does not work at all on modern hardware.</p>
36,032
<p>How can I encrypt and decrypt a string in C#?</p>
<p><strong>EDIT 2013-Oct</strong>: Although I've edited this answer over time to address shortcomings, please see <a href="https://stackoverflow.com/a/10366194/157247">jbtule's answer</a> for a more robust, informed solution.</p> <p><a href="https://stackoverflow.com/a/10366194/188474">https://stackoverflow.com/a/10366194/188474</a></p> <p><strong>Original Answer:</strong></p> <p>Here's a working example derived from the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged%28v=VS.90%29.aspx" rel="noreferrer">"RijndaelManaged Class" documentation</a> and the <a href="https://rads.stackoverflow.com/amzn/click/com/0735626197" rel="noreferrer" rel="nofollow noreferrer">MCTS Training Kit</a>. </p> <p><strong>EDIT 2012-April</strong>: This answer was edited to pre-pend the IV per jbtule's suggestion and as illustrated here:</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged%28v=vs.95%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged%28v=vs.95%29.aspx</a></p> <p>Good luck!</p> <pre><code>public class Crypto { //While an app specific salt is not the best practice for //password based encryption, it's probably safe enough as long as //it is truly uncommon. Also too much work to alter this answer otherwise. private static byte[] _salt = __To_Do__("Add a app specific salt here"); /// &lt;summary&gt; /// Encrypt the given string using AES. The string can be decrypted using /// DecryptStringAES(). The sharedSecret parameters must match. /// &lt;/summary&gt; /// &lt;param name="plainText"&gt;The text to encrypt.&lt;/param&gt; /// &lt;param name="sharedSecret"&gt;A password used to generate a key for encryption.&lt;/param&gt; public static string EncryptStringAES(string plainText, string sharedSecret) { if (string.IsNullOrEmpty(plainText)) throw new ArgumentNullException("plainText"); if (string.IsNullOrEmpty(sharedSecret)) throw new ArgumentNullException("sharedSecret"); string outStr = null; // Encrypted string to return RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data. try { // generate the key from the shared secret and the salt Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // Create a RijndaelManaged object aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); // Create a decryptor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { // prepend the IV msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)); msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length); using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } } outStr = Convert.ToBase64String(msEncrypt.ToArray()); } } finally { // Clear the RijndaelManaged object. if (aesAlg != null) aesAlg.Clear(); } // Return the encrypted bytes from the memory stream. return outStr; } /// &lt;summary&gt; /// Decrypt the given string. Assumes the string was encrypted using /// EncryptStringAES(), using an identical sharedSecret. /// &lt;/summary&gt; /// &lt;param name="cipherText"&gt;The text to decrypt.&lt;/param&gt; /// &lt;param name="sharedSecret"&gt;A password used to generate a key for decryption.&lt;/param&gt; public static string DecryptStringAES(string cipherText, string sharedSecret) { if (string.IsNullOrEmpty(cipherText)) throw new ArgumentNullException("cipherText"); if (string.IsNullOrEmpty(sharedSecret)) throw new ArgumentNullException("sharedSecret"); // Declare the RijndaelManaged object // used to decrypt the data. RijndaelManaged aesAlg = null; // Declare the string used to hold // the decrypted text. string plaintext = null; try { // generate the key from the shared secret and the salt Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // Create the streams used for decryption. byte[] bytes = Convert.FromBase64String(cipherText); using (MemoryStream msDecrypt = new MemoryStream(bytes)) { // Create a RijndaelManaged object // with the specified key and IV. aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); // Get the initialization vector from the encrypted stream aesAlg.IV = ReadByteArray(msDecrypt); // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } finally { // Clear the RijndaelManaged object. if (aesAlg != null) aesAlg.Clear(); } return plaintext; } private static byte[] ReadByteArray(Stream s) { byte[] rawLength = new byte[sizeof(int)]; if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length) { throw new SystemException("Stream did not contain properly formatted byte array"); } byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)]; if (s.Read(buffer, 0, buffer.Length) != buffer.Length) { throw new SystemException("Did not read byte array properly"); } return buffer; } } </code></pre>
<pre><code>using System; using System.Data; using System.Configuration; using System.Text; using System.Security.Cryptography; namespace Encription { class CryptorEngine { public static string Encrypt(string ToEncrypt, bool useHasing) { byte[] keyArray; byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(ToEncrypt); //System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); string Key = "Bhagwati"; if (useHasing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key)); hashmd5.Clear(); } else { keyArray = UTF8Encoding.UTF8.GetBytes(Key); } TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider(); tDes.Key = keyArray; tDes.Mode = CipherMode.ECB; tDes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tDes.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); tDes.Clear(); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } public static string Decrypt(string cypherString, bool useHasing) { byte[] keyArray; byte[] toDecryptArray = Convert.FromBase64String(cypherString); //byte[] toEncryptArray = Convert.FromBase64String(cypherString); //System.Configuration.AppSettingsReader settingReader = new AppSettingsReader(); string key = "Bhagwati"; if (useHasing) { MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider(); keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); hashmd.Clear(); } else { keyArray = UTF8Encoding.UTF8.GetBytes(key); } TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider(); tDes.Key = keyArray; tDes.Mode = CipherMode.ECB; tDes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tDes.CreateDecryptor(); try { byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length); tDes.Clear(); return UTF8Encoding.UTF8.GetString(resultArray,0,resultArray.Length); } catch (Exception ex) { throw ex; } } } } </code></pre>
24,688
<p>The ASP.NET team released the script combining feature in 3.5 SP1 as detailed here <a href="http://www.asp.net/Learn/3.5-SP1/video-296.aspx" rel="noreferrer">http://www.asp.net/Learn/3.5-SP1/video-296.aspx</a>. Is there a similar feature already for the MVC framework? If not, is this in scope or is it possible to somehow leverage the webforms capability in MVC? I see this site uses a custom jquery.package.master which, I assume, they have rolled themselves (maybe into the build cycle, however it is not all minified therefore I think they have manually appended the scripts together rather than some automated minify &amp; combine task). Would be interested in any ideas how to accomplish this in MVC but I dont want to begin rolling any of my own functionality in case I will be duplicating work in progress.</p>
<p>Here's what I do, in case it's helpful.</p> <p>In my postbuild I call a <a href="http://svn.offwhite.net/trac/SmallSharpTools.Packer/wiki" rel="nofollow noreferrer">command line version</a> of <a href="http://dean.edwards.name" rel="nofollow noreferrer">Dean Edwards's Packer</a>. It combines the scripts and packs them for me. </p> <p>For now though, I keep all of my stuff seperate and use a Helper method to include my scripts, and if the debug flag is not present it will include the packed versions, otherwise it includes the unpacked.</p>
<p>Another option is in the Telerik Native UI Extensions for MVC (free library and open source), called ScriptRegistar. It will combine and compress javascript for you, and is fairly feature rich. There is also a class for doing the same to css as well.</p> <p>I am using this to combine +20 javascript files into one file which is downloaded by the browser.</p> <p><a href="http://www.telerik.com/products/aspnet-mvc.aspx" rel="nofollow">http://www.telerik.com/products/aspnet-mvc.aspx</a> and you can get it via NuGet.</p>
34,586
<p>Is there a better way to keep the domain name unaltered in the adress bar besides using a main frame?</p>
<p>Using a frame (or some other inner window, via Flash or Silverlight, etc.) really is the only way to do it - if you try to modify the main window's location with JavaScript, it will change the page's location to the URL you specify, so that will not really work either.</p> <p>You should be mindful of <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" rel="nofollow noreferrer"><strong>RESTful</strong></a> principles - what is the intent for not allowing the URL in the address bar to reflect the true location of the user within the domain?</p>
<p>You can use AJAX to change the content of the page without changing the address.</p> <p>However, if the data is located on another domain then the address should change to point to that domain. Also, it is recommended that the address can be bookmarked so user's can easily return to the data. The address should reflect the content of the resource it points to.</p>
34,360
<p>I've recently had a need to do a bit of lisp editing and I found the nifty Ready Lisp package for OS X, which is great, except Aquamacs automatically uses a proportional font (which is idiotic, IMHO) and I want to change it to a monospace font. However, I'm not really much of an EMACS user, and the preferences menu in Aquamacs is less than clear on where and how one might make such a change. </p>
<p>This is what I have in my .emacs for OS X:</p> <pre><code>(set-default-font "-apple-bitstream vera sans mono-medium-r-normal--0-0-0-0-m-0-mac-roman") </code></pre> <p>Now, I'm not sure Bitstream Vera comes standard on OS X, so you may have to either download it or choose a different font. You can search the X font names by running <code>(x-list-fonts "searchterm")</code> in an ELisp buffer (e.g. <code>*scratch*</code> - to run it, type it in and then type <code>C-j</code> on the same line).</p>
<p>Fast forward a decade, for recent Aquamacs like ver 3.3 please see the nice solution for setting a fixed-width by default at <a href="https://emacs.stackexchange.com/questions/45135/change-permanently-font-size-in-aquamacs">https://emacs.stackexchange.com/questions/45135/change-permanently-font-size-in-aquamacs</a></p> <p>Here's the relevant bit for those who are REALLY impatient but please go upvote that answer, user @nega deserves credit here</p> <pre><code>(when window-system (setq initial-frame-alist nil) ;; Undo Aquamacs forced defaults (setq default-frame-alist nil) ;; Undo Aquamacs forced defaults (aquamacs-autoface-mode -1) ;; Use one face (font) everywhere (set-frame-font "Menlo-12") ;; Set the default font to Menlo size 12 ;;(set-default-font "Menlo-12") ;; This would do the same. ) </code></pre>
8,598
<p>I'm doing some research work into content aggregators, and I'm curious how some of the current craigslist aggregators get data into their mashups.</p> <p>For example, www.housingmaps.com and the now closed www.chicagocrime.org</p> <p>If there is a URL that can be used for reference, that would be perfect!</p>
<p>For <a href="http://AdRavage.com" rel="noreferrer">AdRavage.com</a> I use a combination of Magpie RSS (to extract the data returned from searches) and a custom screen scraping class to properly populate the city/category information used when building searches. </p> <p>For example, to extract the categories you could:</p> <pre><code>//scrape category data $h = new http(); $h-&gt;dir = "../cache/"; $url = "http://craigslist.org/"; if (!$h-&gt;fetch($url, 300)) { echo "&lt;h2&gt;There is a problem with the http request!&lt;/h2&gt;"; exit(); } //we need to get all category abbreviations (data looks like: &lt;option value="ccc"&gt;community) preg_match_all ("/&lt;option value=\"(.*)\"&gt;([^`]*?)\n/", $h-&gt;body, $categoryTemp); $catNames = $categoryTemp['2']; //return the array of abreviations if(sizeof($catNames) &gt; 0) return $catNames; else return $emptyArray = array(); </code></pre>
<p>While continuing to research this area, I found an awesome site that does partly what I'm interested in:</p> <p><a href="http://crazedlist.org" rel="nofollow noreferrer">Crazedlist</a></p> <p>It uses the HTTPReferer of the client browser, which is interesting but not ideal. The author of the site also claims to have royally ticked on CL, which I understand. It also gives clear example of business need, which are similar to my needs, and why I'm interested in this topic.</p>
29,343
<p>Is there any complete guidance on doing AppBar docking (such as locking to the screen edge) in WPF? I understand there are InterOp calls that need to be made, but I'm looking for either a proof of concept based on a simple WPF form, or a componentized version that can be consumed.</p> <p>Related resources:</p> <ul> <li><a href="http://www.codeproject.com/KB/dotnet/AppBar.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/AppBar.aspx</a></li> <li><a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/</a></li> </ul>
<p><strong>Please Note:</strong> This question gathered a good amount of feedback, and some people below have made great points or fixes. Therefore, while I'll keep the code here (and possibly update it), I've also <strong>created a <a href="https://github.com/PhilipRieck/WpfAppBar" rel="noreferrer">WpfAppBar project on github</a></strong>. Feel free to send pull requests. </p> <p>That same project also builds to a <a href="https://www.nuget.org/packages/WpfAppBar/" rel="noreferrer">WpfAppBar nuget package</a> </p> <hr> <p>I took the code from the first link provided in the question ( <a href="http://www.codeproject.com/KB/dotnet/AppBar.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/AppBar.aspx</a> ) and modified it to do two things:</p> <ol> <li>Work with WPF</li> <li>Be "standalone" - if you put this single file in your project, you can call AppBarFunctions.SetAppBar(...) without any further modification to the window.</li> </ol> <p>This approach doesn't create a base class.</p> <p>To use, just call this code from anywhere within a normal wpf window (say a button click or the initialize). Note that you can not call this until AFTER the window is initialized, if the HWND hasn't been created yet (like in the constructor), an error will occur.</p> <p>Make the window an appbar:</p> <pre><code>AppBarFunctions.SetAppBar( this, ABEdge.Right ); </code></pre> <p>Restore the window to a normal window:</p> <pre><code>AppBarFunctions.SetAppBar( this, ABEdge.None ); </code></pre> <p>Here's the full code to the file - <strong>note</strong> you'll want to change the namespace on line 7 to something apropriate.</p> <pre><code>using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using System.Windows.Threading; namespace AppBarApplication { public enum ABEdge : int { Left = 0, Top, Right, Bottom, None } internal static class AppBarFunctions { [StructLayout(LayoutKind.Sequential)] private struct RECT { public int left; public int top; public int right; public int bottom; } [StructLayout(LayoutKind.Sequential)] private struct APPBARDATA { public int cbSize; public IntPtr hWnd; public int uCallbackMessage; public int uEdge; public RECT rc; public IntPtr lParam; } private enum ABMsg : int { ABM_NEW = 0, ABM_REMOVE, ABM_QUERYPOS, ABM_SETPOS, ABM_GETSTATE, ABM_GETTASKBARPOS, ABM_ACTIVATE, ABM_GETAUTOHIDEBAR, ABM_SETAUTOHIDEBAR, ABM_WINDOWPOSCHANGED, ABM_SETSTATE } private enum ABNotify : int { ABN_STATECHANGE = 0, ABN_POSCHANGED, ABN_FULLSCREENAPP, ABN_WINDOWARRANGE } [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)] private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData); [DllImport("User32.dll", CharSet = CharSet.Auto)] private static extern int RegisterWindowMessage(string msg); private class RegisterInfo { public int CallbackId { get; set; } public bool IsRegistered { get; set; } public Window Window { get; set; } public ABEdge Edge { get; set; } public WindowStyle OriginalStyle { get; set; } public Point OriginalPosition { get; set; } public Size OriginalSize { get; set; } public ResizeMode OriginalResizeMode { get; set; } public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == CallbackId) { if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED) { ABSetPos(Edge, Window); handled = true; } } return IntPtr.Zero; } } private static Dictionary&lt;Window, RegisterInfo&gt; s_RegisteredWindowInfo = new Dictionary&lt;Window, RegisterInfo&gt;(); private static RegisterInfo GetRegisterInfo(Window appbarWindow) { RegisterInfo reg; if( s_RegisteredWindowInfo.ContainsKey(appbarWindow)) { reg = s_RegisteredWindowInfo[appbarWindow]; } else { reg = new RegisterInfo() { CallbackId = 0, Window = appbarWindow, IsRegistered = false, Edge = ABEdge.Top, OriginalStyle = appbarWindow.WindowStyle, OriginalPosition =new Point( appbarWindow.Left, appbarWindow.Top), OriginalSize = new Size( appbarWindow.ActualWidth, appbarWindow.ActualHeight), OriginalResizeMode = appbarWindow.ResizeMode, }; s_RegisteredWindowInfo.Add(appbarWindow, reg); } return reg; } private static void RestoreWindow(Window appbarWindow) { RegisterInfo info = GetRegisterInfo(appbarWindow); appbarWindow.WindowStyle = info.OriginalStyle; appbarWindow.ResizeMode = info.OriginalResizeMode; appbarWindow.Topmost = false; Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y, info.OriginalSize.Width, info.OriginalSize.Height); appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ResizeDelegate(DoResize), appbarWindow, rect); } public static void SetAppBar(Window appbarWindow, ABEdge edge) { RegisterInfo info = GetRegisterInfo(appbarWindow); info.Edge = edge; APPBARDATA abd = new APPBARDATA(); abd.cbSize = Marshal.SizeOf(abd); abd.hWnd = new WindowInteropHelper(appbarWindow).Handle; if( edge == ABEdge.None) { if( info.IsRegistered) { SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd); info.IsRegistered = false; } RestoreWindow(appbarWindow); return; } if (!info.IsRegistered) { info.IsRegistered = true; info.CallbackId = RegisterWindowMessage("AppBarMessage"); abd.uCallbackMessage = info.CallbackId; uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd); HwndSource source = HwndSource.FromHwnd(abd.hWnd); source.AddHook(new HwndSourceHook(info.WndProc)); } appbarWindow.WindowStyle = WindowStyle.None; appbarWindow.ResizeMode = ResizeMode.NoResize; appbarWindow.Topmost = true; ABSetPos(info.Edge, appbarWindow); } private delegate void ResizeDelegate(Window appbarWindow, Rect rect); private static void DoResize(Window appbarWindow, Rect rect) { appbarWindow.Width = rect.Width; appbarWindow.Height = rect.Height; appbarWindow.Top = rect.Top; appbarWindow.Left = rect.Left; } private static void ABSetPos(ABEdge edge, Window appbarWindow) { APPBARDATA barData = new APPBARDATA(); barData.cbSize = Marshal.SizeOf(barData); barData.hWnd = new WindowInteropHelper(appbarWindow).Handle; barData.uEdge = (int)edge; if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right) { barData.rc.top = 0; barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight; if (barData.uEdge == (int)ABEdge.Left) { barData.rc.left = 0; barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth); } else { barData.rc.right = (int)SystemParameters.PrimaryScreenWidth; barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth); } } else { barData.rc.left = 0; barData.rc.right = (int)SystemParameters.PrimaryScreenWidth; if (barData.uEdge == (int)ABEdge.Top) { barData.rc.top = 0; barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight); } else { barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight; barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight); } } SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData); SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData); Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top, (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top)); //This is done async, because WPF will send a resize after a new appbar is added. //if we size right away, WPFs resize comes last and overrides us. appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ResizeDelegate(DoResize), appbarWindow, rect); } } } </code></pre>
<p>Sorry, the last code I posted didn't work when the Taskbar is resized. The following code change seems to work better:</p> <blockquote> <pre><code> SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData); if (barData.uEdge == (int)ABEdge.Top) barData.rc.bottom = barData.rc.top + (int)Math.Round(appbarWindow.ActualHeight); else if (barData.uEdge == (int)ABEdge.Bottom) barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight); SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData); </code></pre> </blockquote>
10,144
<p>As I understand, the pimpl idiom is exists only because C++ forces you to place all the private class members in the header. If the header were to contain only the public interface, theoretically, any change in class implementation would not have necessitated a recompile for the rest of the program. </p> <p>What I want to know is why C++ is not designed to allow such a convenience. Why does it demand at all for the private parts of a class to be openly displayed in the header (no pun intended)?</p>
<p>This has to do with the size of the object. The h file is used, among other things, to determine the size of the object. If the private members are not given in it, then you would not know how large an object to new.</p> <p>You can simulate, however, your desired behavior by the following:</p> <pre><code>class MyClass { public: // public stuff private: #include "MyClassPrivate.h" }; </code></pre> <p>This does not enforce the behavior, but it gets the private stuff out of the .h file. On the down side, this adds another file to maintain. Also, in visual studio, the intellisense does not work for the private members - this could be a plus or a minus.</p>
<p>May be because the size of the class is required when passing its instance by values, aggregating it in other classes, etc ?</p> <p>If C++ did not support value semantics, it would have been fine, but it does.</p>
33,811
<p>Is there a way to automatically publish a website to multiple locations at once?</p> <p>Our website is load balanced across multiple servers, so when I want to publish I have to do it to each server individually.</p> <p>Thx, Trev</p>
<p>Perhaps with some build scripts, such as MSBuild? Or perhaps you could create a script (PowerShell, VBScript, whatever), which copies all contents of a directory, and invoke it in the post build event (configurable in Visual Studio), so that once your solution (or the last project, actually) is built the script will run and copy the output files to wherever you need them.</p>
<p>or just use multiple publish commands. one for each location.</p>
49,095
<p>I want to use the GridView mode of a ListView to display a set of data that my program will be receiving from an external source. The data will consist of two arrays, one of column names and one of strings values to populate the control.</p> <p>I don't see how to create a suitable class that I can use as the Item in a ListView. The only way I know to populate the Items is to set it to a class with properties that represent the columns, but I have no knowledge of the columns before run-time.</p> <p>I could create an ItemTemplate dynamically as described in: <a href="https://stackoverflow.com/questions/125638/create-wpf-itemtemplate-dynamically-at-runtime">Create WPF ItemTemplate DYNAMICALLY at runtime</a> but it still leaves me at a loss as to how to describe the actual data.</p> <p>Any help gratefully received.</p>
<p>You can add GridViewColumns to the GridView dynamically given the first array using a method like this:</p> <pre><code>private void AddColumns(GridView gv, string[] columnNames) { for (int i = 0; i &lt; columnNames.Length; i++) { gv.Columns.Add(new GridViewColumn { Header = columnNames[i], DisplayMemberBinding = new Binding(String.Format("[{0}]", i)) }); } } </code></pre> <p>I assume the second array containing the values will be of ROWS * COLUMNS length. In that case, your items can be string arrays of length COLUMNS. You can use Array.Copy or LINQ to split up the array. The principle is demonstrated here:</p> <pre><code>&lt;Grid&gt; &lt;Grid.Resources&gt; &lt;x:Array x:Key="data" Type="{x:Type sys:String[]}"&gt; &lt;x:Array Type="{x:Type sys:String}"&gt; &lt;sys:String&gt;a&lt;/sys:String&gt; &lt;sys:String&gt;b&lt;/sys:String&gt; &lt;sys:String&gt;c&lt;/sys:String&gt; &lt;/x:Array&gt; &lt;x:Array Type="{x:Type sys:String}"&gt; &lt;sys:String&gt;do&lt;/sys:String&gt; &lt;sys:String&gt;re&lt;/sys:String&gt; &lt;sys:String&gt;mi&lt;/sys:String&gt; &lt;/x:Array&gt; &lt;/x:Array&gt; &lt;/Grid.Resources&gt; &lt;ListView ItemsSource="{StaticResource data}"&gt; &lt;ListView.View&gt; &lt;GridView&gt; &lt;GridViewColumn DisplayMemberBinding="{Binding Path=[0]}" Header="column1"/&gt; &lt;GridViewColumn DisplayMemberBinding="{Binding Path=[1]}" Header="column2"/&gt; &lt;GridViewColumn DisplayMemberBinding="{Binding Path=[2]}" Header="column3"/&gt; &lt;/GridView&gt; &lt;/ListView.View&gt; &lt;/ListView&gt; &lt;/Grid&gt; </code></pre>
<p>Totally progmatic version:</p> <pre><code> var view = grid.View as GridView; view.Columns.Clear(); int count=0; foreach (var column in ViewModel.GridData.Columns) { //Create Column var nc = new GridViewColumn(); nc.Header = column.Field; nc.Width = column.Width; //Create template nc.CellTemplate = new DataTemplate(); var factory = new FrameworkElementFactory(typeof(System.Windows.Controls.Border)); var tbf = new FrameworkElementFactory(typeof(System.Windows.Controls.TextBlock)); factory.AppendChild(tbf); factory.SetValue(System.Windows.Controls.Border.BorderThicknessProperty, new Thickness(0,0,1,1)); factory.SetValue(System.Windows.Controls.Border.MarginProperty, new Thickness(-7,0,-7,0)); factory.SetValue(System.Windows.Controls.Border.BorderBrushProperty, Brushes.LightGray); tbf.SetValue(System.Windows.Controls.TextBlock.MarginProperty, new Thickness(6,2,6,2)); tbf.SetValue(System.Windows.Controls.TextBlock.HorizontalAlignmentProperty, column.Alignment); //Bind field tbf.SetBinding(System.Windows.Controls.TextBlock.TextProperty, new Binding(){Converter = new GridCellConverter(), ConverterParameter=column.BindingField}); nc.CellTemplate.VisualTree = factory; view.Columns.Add(nc); count++; } </code></pre>
46,435
<p>The print functionality of Excel (using VBA) is extremely slow. I'm hoping someone has a way of speeding the printing up (without using the Excel 4 Macro trick). Here's how I do it now:</p> <pre><code>Application.ScreenUpdating = False With ActiveSheet.PageSetup -various setup statements which I've already minimized- End With ActiveSheet.PrintOut Application.ScreenUpdating = True </code></pre>
<p>Yes, the PageSetup properties are very slow when you set them.</p> <p>You have already set <code>Application.ScreenUpdating = False</code>, which is good, but an equally (or more) important step in this case is to set <code>Application.Calculation = xlCalculationManual</code>. (It is best if you save these settings and then restore them to the original at the end.)</p> <p>Additionally, the property get for each PageSetup property is very fast, while it is only the property set that is so slow. Therefore, you should test the new property setting to make sure it isn't already the same as the existing property value in order to prevent an unnecessary (and expensive) call.</p> <p>With all this in mind, you should be able to use code that looks something like the following:</p> <pre><code>Dim origScreenUpdating As Boolean origScreenUpdating = Application.ScreenUpdating Application.ScreenUpdating = False Dim origCalcMode As xlCalculation origCalcMode = Application.Calculation Application.Calculation = xlCalculationManual With ActiveSheet.PageSetup If .PrintHeadings &lt;&gt; False Then .PrintHeadings = False If .PrintGridlines &lt;&gt; False Then .PrintGridlines = False If .PrintComments &lt;&gt; xlPrintNoComments Then .PrintComments = xlPrintNoComments ' Etc... End With Application.ScreenUpdating = origScreenUpdating Application.Calculation = origCalcMode </code></pre> <p><em>Edit: A couple of updates:</em> </p> <ol> <li><p>For Excel 2010 and above you can make use of the 'Application.PrintCommunication' property, while for Excel 2007 and below, you can make use of 'ExecuteExcel4Macro'. For more details, see <a href="http://blogs.msdn.com/excel/archive/2010/02/16/migrating-excel-4-macros-to-vba.aspx" rel="noreferrer">Migrating Excel 4 Macros to VBA</a>.</p></li> <li><p>For Excel 2007 and below, another interesting trick is to temporarily assign the printer driver to the 'Microsoft XPS Document Writer' and then set it back. Printing speed can improve by 3x. See: <a href="http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/8b2a0988-7d09-4abf-a4d3-76e81f708d40" rel="noreferrer">Slow Excel PageSetup Methods</a>.</p></li> </ol> <p>Hope this helps...</p>
<p>if you want to have basicly the same page settings for every tab in a workbook can you speed things up by setting up one workshet and then copying that worksheet's settings somehow to the other worksheets? Is this possible?</p>
28,521
<p>My domain (let's call it www.example.com) creates a cookie. On another site (let's say, www.myspace.com), my domain is loaded within an iFrame.</p> <p>On every browser (Firefox, Opera, Camino, Safari, etc...) except for Internet Explorer, I can access my own cookie. In IE, it doesn't give me access to the cookie from within the iFrame.</p> <p>Is there a way to get around this?</p> <p>Really, this makes no sense because the site trying to access the cookie is www.example.com and the cookie is owned by www.example.com. But for some reason, IE thinks the iFrame makes them unrelated. </p>
<p>Internet Explorer's default privacy setting means that 3rd-party cookies (e.g. those in iframes) are treated differently to 1st party cookies. (by default, 3rd party cookies are silently rejected).</p> <p>For IE6 to accept cookies in an iframe, you need to ensure your site is delivering a P3P compact header.</p> <p>See <a href="http://msdn.microsoft.com/en-us/library/ms537343.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms537343.aspx</a> for more.</p>
<p>That sounds like a privacy setting issue to me. Either increase your security settings in IE (which you won't be able to convince your users to do), or take another approach.</p>
12,362
<p>I have a internal website that users log into. This data is saved as a cookie. From there the users go on their merry way. Every so often the application(s) will query the authentication record to determine what permissions the user has. </p> <p>My question is this: Is it more efficent to just query the cookie for the user data when it is needed or to save the user information in viewstate? </p> <p>[Edit] As mentioned below, Session is also an option.</p>
<p>Viewstate is specific to the page they are viewing, so its gone once they go along thier merry way. Not a good way to persist data. </p> <p>Your best bet is to use Forms Authentication, its built in to ASP.NET and you can also shove any user-specific information into the Forms Authentication Ticket's Value. You can get 4000 bytes in (after encrypting) there that should hold whatever you need. It will also take care of allowing and denying users access to pages on the site, and you can set it to expire whenever you need.</p> <p>Storing in the session is a <strong>no-no</strong> because it scales VERY poorly (eats up resources on the server), and it can be annoying to users with multiple browser connections to the same server. It is sometimes unavoidable, but you should take great pains to avoid it if you can. </p>
<p>You can use session data - that way you know that once you have stored it there, users can't fool around with it by changing the query string.</p>
20,277
<p>I'm building a tool that automates a process then runs some tests on it's own results then goes to do some other stuff.</p> <p>In trying to clean up my code I have created a separate file that just has the test cases class. Now before I can run these tests, I have to pass the class a couple of parameters/objects before they can be run. Now the problem is that I can't seem to find a way to pass a parameter/object to the test class.</p> <p>Right now I am thinking to generate a Yaml file and read it in the test class but it feels "wrong" to use a temporary file for this. If anyone has a nicer solution that would be great!</p> <p>**************Edit************</p> <p>Example Code of what I am doing right now:</p> <pre><code>#!/usr/bin/ruby require 'test/unit/ui/console/testrunner' require 'yaml' require 'TS_SampleTestSuite' automatingSomething() importantInfo = getImportantInfo() File.open('filename.yml', 'w') do |f| f.puts importantInfo.to_yaml end Test::Unit::UI::Console::TestRunner.run(TS_SampleTestSuite) </code></pre> <p>Now in the example above TS_SampleTestSuite needs importantInfo, so the first "test case" is a method that just reads in the information from the Yaml file filname.yml. </p> <p>I hope that clears up some confusion.</p>
<p>I think the 'nearly unique' is probably a red herring. The data is either unique, or it's not, but that doesn't determine whether you would want to index it for performance reasons.</p> <h3>Answer:</h3> <p>5000 records is really not many at all, and regardless of whether you have an index, searches will still be fast. At that rate of inserts, it'll take you 3 years to get to 10000 records, which is still also not many.<br> I personally wouldn't bother with adding an index, but it wouldn't matter if you did.</p> <h3>Explanation:</h3> <p>What you have to think about when deciding to add an index is the trade-off between insertion speed, and selection speed.</p> <p>Without an index, doing a <code>select</code> on that field means MySQL has to walk over every single row and read every single field. Adding an index prevents this.</p> <p>The downside of the index is that each time data gets inserted, the DB has to update the index in addition to adding the data. This is usually a small overhead, but you'd really notice it if you had loads of indexes, and were doing a lot of writes. </p> <p>By the time you get this many rows in your database, you'd want an index anyway as otherwise your selects would take all day, but it's just something to be aware about so that you don't end up adding indexes on fields "just in case I need it"</p>
<p>From what you say, it doesn't sound like an index is necessary. Rule of thumb is index fields that are being used in SELECTS a lot to speed up the searching, which in turn (can) slows down INSERTS and UPDATES.</p> <p>On a recordset as small as yours, I don't think you will see much of a real world hit either way. </p>
36,217
<p>Let's say that I have a site where once the user selects a few options, the following (should) happen:</p> <ul> <li>Grabs files (in a directory) off of the local machine - works fine so far</li> <li>Moves them to a remote server - this is where I need help</li> </ul> <p>Details:</p> <ul> <li>The remote server will be found via UNC path (\servername\xyz)</li> <li>I have access to the username/password to access that UNC path, but since we are on a different domain and I don't control IT's decisions, I can't have a single user that has permissions in both domains.</li> </ul> <p>How do I go about setting up my site to do this? If I impersonate, then I might lose permissions to grab files on the local machine... </p> <p>Note: I also have FTP access to the remote server. If there is a good FTP API that I could use, that would work as well, but I don't want to have to iterate over each and every file.</p> <p>Oh, this is .NET 1.1 as well.</p> <hr> <p>This is a suggestion on a related question: <a href="https://stackoverflow.com/questions/233490/need-to-impersonate-user-foraccessing-network-resource-aspnet-account">Need to Impersonate user forAccessing Network resource, Asp.Net Account</a></p>
<p>I have done this cross domain before. All you need is for the username and password to be the same and this will work, even if they are in different domains. The thing to make sure of is that your .NET application is running as this user. </p> <p>For instance:</p> <ul> <li>In domain XYZ have a user "filesynch" with a password "pass"</li> <li>In domain PDQ have a user "filesynch" with a password "pass"</li> <li>Make sure user PDQ\filesynch has access to share on machine in PDQ domain</li> <li>Run application on a machine in the XYZ domain as the XYZ\filesynch user</li> <li>Copy files over network</li> </ul>
<p>This could be done either with the unc or ftp. For the earlier (unc) you could use File.Copy(source, target) - for the latter you can use a couple of techniques. If you store what the user wanted from the machine on the remote site you could use a webclient (System.Net.WebClient) to download the files via any accessible url (ie: turn file browsing on in IIS).</p> <p>If you can use .NET 2.0 you have better options with more reliable objects (ie: FtpRequest) - is there a reson why you cant use .NET 2.0?</p>
25,234
<p>I have an application database and an aspnetdb database (generated from the ASP.Net 2.0 framework). I have restored both database from production onto my development environment but I am unable to log on with any of the users credentials that work on production.</p> <p>So my question is is there anything that ties the aspnetdb database generated by ASP>NET 2.0 Framework to a specific machine?</p> <p>If anyone has ever restored an aspnetdb database from one machine to another successfully please can they shed light on the variables that need to be the same in order to access all the previous users.</p> <p>Many Thanks!</p> <hr> <p>Sure I have checked the connection string and double checked users and roles which I can confirm is working by being able to create new users on the development environment and log in with those credentials. </p> <p>The problem is I am unable to logon with any of the user credentials I use on the live environment. This I feel is related to the difference in the machine.config files on both machines. If anyone knows a variable I should look for in the machine.config then I could make sure they are the same in both environments i.e both machines.</p>
<p>The passwords are encrypted with a machine key AFAIK. So you needs to be the same on all places you will be testing this. From what I know, the machine key can set in the web.config.</p>
<p>I have checked the web.config and connection string and the membership section specifcally the application name as per Scott Gus blog link below:</p> <p><a href="http://weblogs.asp.net/scottgu/archive/2006/04/22/443634.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2006/04/22/443634.aspx</a></p>
21,449
<p>What is the minimum set of HTTP verbs that a server should allow for a web service to be classed as RESTful? </p> <p>What if my hoster doesn't permit <strong><em>PUT</em></strong> and <strong><em>DELETE</em></strong>?</p> <p>Is this actually important, can I live happily ever after with just <strong><em>GET</em></strong> and <strong><em>POST</em></strong> ?</p> <hr> <p><strong>Update:</strong> Thanks for the answers folks, <a href="https://stackoverflow.com/questions/23963/restful-web-services-and-http-verbs#23971">Roger's answer</a> was probably best because of the link to the Bill Venners and Elliotte Rusty Harold interview. I now get it.</p> <hr>
<p>Yes, you can live without PUT and DELETE. </p> <p>This article tells you why: <a href="http://www.artima.com/lejava/articles/why_put_and_delete.html" rel="noreferrer">http://www.artima.com/lejava/articles/why_put_and_delete.html</a></p> <p>While to true RESTafrians this may be heresy, in the real world you do what you can, with what you have. Be as rational as you can and as consistent with your own convention as you can, but you can definitely build a good RESTful system without P and D. </p> <p>rp</p>
<p>Today's web browsers only handle GETS + POSTS. In Rails, for example, PUTS + DELETES are "faked" through hidden form fields.</p> <p>Unless your framework has some workaround to "support" PUTS + DELETES, don't worry about them for now.</p>
4,376
<p>It is possible to get stacktrace using System.Diagnostics.StackTrace, but thread has to be suspended. Suspend and Resume function are obsolete, so I expect that better way exists.</p>
<p>According to <a href="http://www.albahari.com/nutshell/" rel="noreferrer">C# 3.0 in a Nutshell</a>, this is one of the few situations where it is okay to call Suspend/Resume. </p>
<p>I think that if you want to do this without the cooperation of the target thread (such as by having it call a method that blocks it on a Semaphore or something while your thread does the stacktrace) you'll need to use the deprecated APIs.</p> <p>A possible alternative is the use the <a href="https://learn.microsoft.com/en-us/archive/blogs/jmstall/" rel="nofollow noreferrer">COM-based ICorDebug</a> interface that the .NET debuggers use. The MDbg codebase might give you a start:</p> <ul> <li><a href="https://learn.microsoft.com/en-us/archive/blogs/jmstall/" rel="nofollow noreferrer"><code>http://blogs.msdn.com/jmstall/archive/2005/11/07/views_on_cordbg_and_mdbg.aspx</code></a></li> <li><a href="https://web.archive.org/web/20201202093410/http://geekswithblogs.net/johnsPerfBlog/archive/2008/10/13/mdbg-a-managed-wrapper-around-icordebug.aspx" rel="nofollow noreferrer"><code>http://geekswithblogs.net/johnsPerfBlog/archive/2008/10/13/mdbg-a-managed-wrapper-around-icordebug.aspx</code></a></li> </ul>
36,177
<p>I have a table like this:</p> <pre><code> Column | Type | Modifiers ---------+------+----------- country | text | food_id | int | eaten | date | </code></pre> <p>And for each country, I want to get the food that is eaten most often. The best I can think of (I'm using postgres) is:</p> <pre><code>CREATE TEMP TABLE counts AS SELECT country, food_id, count(*) as count FROM munch GROUP BY country, food_id; CREATE TEMP TABLE max_counts AS SELECT country, max(count) as max_count FROM counts GROUP BY country; SELECT country, max(food_id) FROM counts WHERE (country, count) IN (SELECT * from max_counts) GROUP BY country; </code></pre> <p>In that last statement, the GROUP BY and max() are needed to break ties, where two different foods have the same count.</p> <p>This seems like a lot of work for something conceptually simple. Is there a more straight forward way to do it?</p>
<p>It is now even simpler: PostgreSQL 9.4 introduced the <code>mode()</code> function:</p> <pre><code>select mode() within group (order by food_id) from munch group by country </code></pre> <p>returns (like user2247323's example):</p> <pre><code>country | mode -------------- GB | 3 US | 1 </code></pre> <p>See documentation here: <a href="https://wiki.postgresql.org/wiki/Aggregate_Mode" rel="noreferrer">https://wiki.postgresql.org/wiki/Aggregate_Mode</a></p> <p><a href="https://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-ORDEREDSET-TABLE" rel="noreferrer">https://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-ORDEREDSET-TABLE</a></p>
<p>Try something like this</p> <pre><code>select country, food_id, count(*) cnt into #tempTbl from mytable group by country, food_id select country, food_id from #tempTbl as x where cnt = (select max(cnt) from mytable where country=x.country and food_id=x.food_id) </code></pre> <p>This could be put all into a single select, but I don't have time to muck around with it right now.</p> <p>Good luck.</p>
44,831
<p>Is it possible to achieve better data transfer rate with multiple parallel TCP connections in high-latency environment (public internet with large geographical distance assuming no traffic shaping per connection or stuff like that) or can TCP utilize the whole bandwidth with a single connection?</p> <hr> <p>Is TCP sending data as fast as it cans if receiver doesn't report buffer congestion with 0 windows size? So if RTT is for example like 60 seconds it doesn't affect the rate at all? Is there some maximum window size or something else limiting the rate? </p>
<p>One advantage multiple concurrent connections <em>may</em> give you (subject to the same caveats mentioned by dove and Brian) is you will be able to better overcome the problem of having too small a TCP receive window.</p> <p>The principle this relates to is <a href="http://en.wikipedia.org/wiki/Bandwidth-delay_product" rel="nofollow noreferrer">bandwidth delay product</a>. (There's a more detailed explanation <a href="https://www.psc.edu/research/networking/tcp-tune/" rel="nofollow noreferrer">here</a>).</p> <p>A brief summary: in high-latency, high-bandwidth environments, reliable communications such as TCP are often limited by the amount of data in flight at any given time. Multiple connections are one way around this, as the bandwidth delay product applies to each connection individually.</p> <p>In more detail, consider the following: you have an end-to-end bandwidth of 10^8 bits per second (10 megabits/second), and a round-trip delay of 100ms (0.1 seconds). Therefore, there can be up to 10^7 bits (10 megabits = ~1.25 megabytes) of data sent before the acknowledgment of the first bit of data has gotten back to the sender.</p> <p>This will vary depending on the TCP stack of your OS, but a not-uncommon value for TCP receive window size is 64Kbytes. This is obviously far too small to allow you to make full use of the end to end bandwidth; once 64kbytes (512kbits) of data have been sent, your sending process will wait for a window update from the receiver indicating that some data has been consumed before putting any more data on the wire.</p> <p>Having multiple TCP sessions open gets around this by virtue of the fact that each TCP session will have its own send/receive buffers.</p> <p>Of course, on the internet it's difficult to determine the true available end-to-end bandwidth, due to TCP window size, contention, etc. If you're able to provide some sample figures, we may be able to assist more.</p> <p>The other option you should look into is setting a larger receive window when you create your socket, either globally using an OS setting, or on a per socket basis using socket options.</p>
<p>Yes, but not necessarily easy to implement. CDNs such as akamai make claim to part of their performance by compressing larger packets than would normally be sent because of their dedicated reliable pipe. Hard to give better detail without knowing more of your application.</p>
32,433
<p>I'm developing an application that is so far using HttpListener to provide a small standalone http server. However, I've recently discovered that HttpListener needs to be run as Administrator, which is not always going to be possible.</p> <p>What would the best alternative be? I need http GET and POST, both of which are not simply reading/writing files on the filesystem, they need to run custom .Net code.</p> <p>My research so far has brought up Cassini, but as far as I can tell, I would have to write a custom version. Is there anything else? In partiular something with the same interface as HttpListener, but that does not require Administrator privileges would be amazing!</p>
<p>One alternative that I've found is <a href="http://www.codeplex.com/webserver" rel="noreferrer">C# Webserver</a> on CodePlex.</p> <p><i>"... a flexible http server which can be embedded in any .Net application. It has a modular design where features are added using modules. The server also supports REST and all http verbs ..."</i></p> <p>It has an HttpListener class which I imagine is similar to System.Net.HttpListener, but I haven't used either one of them yet so I can't be certain.</p>
<p>Ok, so you have a regular desktop app that needs to allow inbound http connections - hmm - won't windows firewall be an issue?</p> <p>Assuming not, it sounds almost like a webservice - could you go that route - expose the URLs via that? Although my .Net knowledge is not deep enough to know if you still need to run a specific http server to answer requests. <a href="http://www.springframework.net/docs/1.2.0-M1/reference/html/webservices.html" rel="nofollow noreferrer">Spring.Net</a> is probably worth a look.</p>
35,500
<p>I have a listbox, and I have the following ItemTemplate for it:</p> <pre><code>&lt;DataTemplate x:Key="ScenarioItemTemplate"&gt; &lt;Border Margin="5,0,5,0" Background="#FF3C3B3B" BorderBrush="#FF797878" BorderThickness="2" CornerRadius="5"&gt; &lt;DockPanel&gt; &lt;DockPanel DockPanel.Dock="Top" Margin="0,2,0,0"&gt; &lt;Button HorizontalAlignment="Left" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="White" /&gt; &lt;Label Content="{Binding Path=Name}" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="white" /&gt; &lt;Label HorizontalAlignment="Right" Background="#FF3C3B3B" Content="X" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="White" /&gt; &lt;/DockPanel&gt; &lt;ContentControl Name="designerContent" Visibility="Collapsed" MinHeight="100" Margin="2,0,2,2" Content="{Binding Path=DesignerInstance}" Background="#FF999898"&gt; &lt;/ContentControl&gt; &lt;/DockPanel&gt; &lt;/Border&gt; &lt;/DataTemplate&gt; </code></pre> <p>As you can see the ContentControl has Visibility set to collapsed.</p> <p>I need to define a trigger that causes the Visibility to be set to "Visible"</p> <p>when the ListItem is selected, but I can't figure it out.</p> <p>Any ideas? </p> <p>UPDATE: Of course I could simply duplicate the DataTemplate and add triggers to the ListBox in question to use either one or the other, but I want to prevent duplicating this code.</p>
<p>You can style your ContentControl such that a trigger fires when its container (the ListBoxItem) becomes selected:</p> <pre><code>&lt;ContentControl x:Name="designerContent" MinHeight="100" Margin="2,0,2,2" Content="{Binding Path=DesignerInstance}" Background="#FF999898"&gt; &lt;ContentControl.Style&gt; &lt;Style TargetType="{x:Type ContentControl}"&gt; &lt;Setter Property="Visibility" Value="Collapsed"/&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True"&gt; &lt;Setter Property="Visibility" Value="Visible"/&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/ContentControl.Style&gt; &lt;/ContentControl&gt; </code></pre> <p>Alternatively, I think you can add the trigger to the template itself and reference the control by name. I don't know this technique well enough to type it from memory and assume it'll work, but it's something like this:</p> <pre><code>&lt;DataTemplate x:Key="ScenarioItemTemplate"&gt; &lt;DataTemplate.Triggers&gt; &lt;DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True"&gt; &lt;Setter TargetName="designerContent" Property="Visibility" Value="Visible"/&gt; &lt;/DataTrigger&gt; &lt;/DataTemplate.Triggers&gt; ... &lt;/DataTemplate&gt; </code></pre>
<p>@Matt, Thank you!!!</p> <p>Just had to add a trigger for IsSelected == false as well, and now it works like a charm!</p> <pre><code>&lt;ContentControl.Style&gt; &lt;Style TargetType="{x:Type ContentControl}"&gt; &lt;Setter Property="Visibility" Value="Collapsed"/&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}" Value="True"&gt; &lt;Setter Property="Visibility" Value="Visible"/&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}" Value="False"&gt; &lt;Setter Property="Visibility" Value="Collapsed"/&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; </code></pre> <p></p>
30,886
<p>I'm learning Rails and it's going well so far. My biggest question at the moment is: how do I go about manually inserting a row into my database? I've got the scaffolding in place for creating rows of DataTypeOne, but I want a row for DataTypeTwo to be created when the form for DataTypeOne is submitted (and have it reference the id of DataTypeOne...but I think I can work this out on my own).</p> <p>Thanks in advance.</p>
<p>You create rows in your database by creating and saving new ActiveRecord Objects (your models). </p> <p>So in your controller code you could create a new row of DataTypeTwo by doing</p> <pre><code>new_record = DataTypeTwo.new new_record.save! </code></pre>
<p>This is such a common thing to want to do that you should be able to do it through your models and not have to think about doing anything manually to the database.</p> <p>For example, if you want DataTypeTwo to reference DataTypeOne, is that because DataTypeTwo 'belongs to' DataTypeOne? Or does DataTypeOne 'have many' things of DataTypeTwo? Rails has conventions to express all these kinds of relationships and others. Saving the object and related items to the DB should then be automatic when you call the 'save!' method on the relevant object.</p> <p>You should take a look at a few more rails examples and tutorials to grok this. Unless you are doing something very unusual you shouldn't need to do more than annotate your models and follow the conventions, so that rails knows what belongs to what.</p>
47,892
<p>We have a custom collection of objects that we bind to a listbox control. When an item is added to the list the item appears in the listbox, however when one selects the item the currency manager position will not go to the position. Instead the currency manager position stays at the existing position. The listbox item is high lighted as long as the mouse is press however the cm never changes position.</p> <p>If I copy one of the collection objects the listbox operates properly.</p> <p>One additional note the collection also has collections within it, not sure if this would be an issue.</p>
<p>I found the issue, after spending way too much time....</p> <p>This issue was related to one of the propertys of the item(custom class) in the collection which was bound to a date picker control. The constructor for the class never set the value to a default value.</p> <p>This caused an issue with the currency manager not allowing the position to change as the specific property (bound to the date picker) was not valid.</p> <p>Me bad! I know better!</p>
<p>Collections don't have a sense of "current item". Perhaps your custom collection does, but the <code>ListBox</code> is not using that. It has its own "current item" index into the collection. You need to handle <code>SelectedIndexChanged</code> events to keep them in sync.</p>
23,265
<p>.NET Framework 3.5 SP1 installs the .NET Framework 2.0 SP2 and the .NET Framework 3.0 SP2 behind the scenes. These installation packages (especially .NET Framework 2.0 SP2) are not available directly from Microsoft.</p> <p>Is there a way to extract them from the .NET Framework 3.5 SP1 installation package?</p>
<p>Take a look on <a href="http://msdn.microsoft.com/en-us/vs2008/bb898654.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/vs2008/bb898654.aspx</a> or download <a href="http://go.microsoft.com/fwlink/?LinkID=127832" rel="nofollow noreferrer">.NET Frameworks 2.0 SP2 and 3.0 SP2 bootstrapper packages</a>. These packages give you separate .NET Framework 2.0 SP2 and .NET Framework 3.0 SP2 installation packages.</p>
<p>Here: <a href="http://msdn.microsoft.com/en-us/vs2008/bb898654.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/vs2008/bb898654.aspx</a></p> <p>Download Installer (Download Size: 325 MB)</p> <p>Extract it with the /x switch, there is a cab file called <strong>adtbs_sp2oob.cab</strong>, inside it is a file called <code>FL_FL_NetFx20SP2_x86.exe.3643236F_FC70_11D3_A536_0090278A1BB8</code>, you can rename it to <code>NetFx20SP2_x86.exe</code>, If you need 64-bit, it's probably <code>FL_NetFx20SP2_x64.3643236F_FC70_11D3_A536_0090278A1BB8</code>. It should be completely independent, works OK for me so far.</p>
23,344
<p>Suppose you have a collection of a few hundred in-memory objects and you need to query this List to return objects matching some SQL or Criteria like query. For example, you might have a List of Car objects and you want to return all cars made during the 1960s, with a license plate that starts with AZ, ordered by the name of the car model. </p> <p>I know about <a href="http://josql.sourceforge.net/" rel="noreferrer">JoSQL</a>, has anyone used this, or have any experience with other/homegrown solutions?</p>
<p>I have used <a href="http://commons.apache.org/jxpath/" rel="noreferrer">Apache Commons JXPath</a> in a production application. It allows you to apply XPath expressions to graphs of objects in Java.</p>
<p>The <code>Comparator</code> option is not bad, especially if you use anonymous classes (so as not to create redundant classes in the project), but eventually when you look at the flow of comparisons, it's pretty much just like looping over the entire collection yourself, specifying exactly the conditions for matching items:</p> <pre><code>if (Car car : cars) { if (1959 &lt; car.getYear() &amp;&amp; 1970 &gt; car.getYear() &amp;&amp; car.getLicense().startsWith("AZ")) { result.add(car); } } </code></pre> <p>Then there's the sorting... that might be a pain in the backside, but luckily there's class <code>Collections</code> and its <code>sort</code> methods, one of which receives a <code>Comparator</code>...</p>
11,892
<p>I am trying to get in place editing working but I am running into this error:</p> <p>ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken)</p> <p>I understand that rails now wants to protect against forgery and that I need to pass a form authenticity token but I am not clear on how to do this with the in_place_edit plugin.</p>
<p>This isn't a <strike>complete</strike> tested answer, but I took a look at the <a href="http://svn.rubyonrails.org/rails//plugins/in_place_editing/lib/in_place_macros_helper.rb" rel="nofollow noreferrer">plugin code</a>, and it looks like you could use the <code>:with</code> option to tack the authenticity token onto the end of the request parameters. Something along the lines of:</p> <pre><code>in_place_editor("my_element", :with =&gt; "form.serialize() + '&amp;authenticity_token=#{form_authenticity_token}';") </code></pre> <p>(I have not tested the above code).</p>
<p>This isn't a <strike>complete</strike> tested answer, but I took a look at the <a href="http://svn.rubyonrails.org/rails//plugins/in_place_editing/lib/in_place_macros_helper.rb" rel="nofollow noreferrer">plugin code</a>, and it looks like you could use the <code>:with</code> option to tack the authenticity token onto the end of the request parameters. Something along the lines of:</p> <pre><code>in_place_editor("my_element", :with =&gt; "form.serialize() + '&amp;authenticity_token=#{form_authenticity_token}';") </code></pre> <p>(I have not tested the above code).</p>
21,045
<p>I have the following code that creates two objects (ProfileManager and EmployerManager) where the object EmployerManager is supposed to inherit from the object ProfileManager. However, when I do alert(pm instanceof ProfileManager); it returns false.</p> <pre><code>function ProfileFactory(profileType) { switch(profileType) { case 'employer': return new EmployerManager(); break; } } function ProfileManager() { this.headerHTML = null; this.contentHTML = null; this.importantHTML = null; this.controller = null; this.actions = new Array(); this.anchors = new Array(); } ProfileManager.prototype.loadData = function(action, dao_id, toggleBack) { var step = this.actions.indexOf(action); var prv_div = $('div_' + step - 1); var nxt_div = $('div_' + step); new Ajax.Request(this.controller, { method: 'get', parameters: {action : this.actions[step], dao_id : dao_id}, onSuccess: function(data) { nxt_div.innerHTML = data.responseText; if(step != 1 &amp;&amp; !prv_div.empty()) { prv_div.SlideUp(); } nxt_div.SlideDown(); for(i = 1; i &lt;= step; i++) { if($('step_anchor_' + i).innerHTML.empty()) { $('step_anchor_' + i).innerHTML = this.anchors[i]; } } } } ) } EmployerManager.prototype.superclass = ProfileManager; function EmployerManager() { this.superclass(); this.controller = 'eprofile.php'; this.anchors[1] = 'Industries'; this.anchors[2] = 'Employer Profiles'; this.anchors[3] = 'Employer Profile'; this.actions[1] = 'index'; this.actions[2] = 'employer_list'; this.actions[3] = 'employer_display'; } var pm = new ProfileFactory('employer'); alert(pm instanceof ProfileManager); </code></pre> <p>BTW, this is my very first attempt at Object-Oriented JavaScript, so if you feel compelled to comment on the stupidity of my approach please feel free to do so, but offer suggestions on how to approach the problem better.</p>
<p>I've been using something similar to Dean Edward's Base.js model. <a href="http://dean.edwards.name/weblog/2006/03/base/" rel="nofollow noreferrer">http://dean.edwards.name/weblog/2006/03/base/</a></p>
<p>In your code, pm is an instance of EmployerManager that has a superclass of ProfileManager. That seems backwards to me. Shouldn't ProfileManager have a superclass of EmployerManager?</p>
39,896
<p>What algorithms are good for interactive/realtime graph-drawing for live data and direct-manipulation?</p> <p>Failing that - what libraries do you use to draw graphs? </p> <p>Suggestions; </p> <ul> <li><a href="http://prefuse.org/" rel="nofollow noreferrer">Prefuse</a> information-visualization toolkit</li> <li>any others?</li> </ul> <p>BTW- I mean graphs in the graph-theory sense - points and lines</p> <ul> <li>any language </li> <li>by live I mean the graph should be manipulatable once on screen.</li> </ul>
<p>I would recommend any library that Jeff Heer has worked on:</p> <ul> <li><a href="http://d3js.org/" rel="nofollow noreferrer">D3</a></li> <li><a href="http://vis.stanford.edu/protovis/" rel="nofollow noreferrer">Protovis</a></li> <li><a href="http://flare.prefuse.org/" rel="nofollow noreferrer">Flare</a> </li> <li><a href="http://prefuse.org/" rel="nofollow noreferrer">Prefuse</a> </li> </ul> <p>I believe all three projects are open source. Jeff Heer is pretty good at referencing papers in his code at least in the Prefuse library. Looking at the Prefuse source:</p> <p><strong>BalloonTreeLayout</strong>: The algorithm used is that of G. Melançon and I. Herman from their research paper Circular Drawings of Rooted Trees, Reports of the Centre for Mathematics and Computer Sciences, Report Number INS–9817, 1998. </p> <p><strong>ForceDirectedLayout.java</strong>: No reference mentioned, but there are lot of comments describing how it works.</p> <p><strong>FruchtermanReingoldLayout.java</strong>: references <a href="http://jung.sourceforge.net" rel="nofollow noreferrer">Jung</a>. On their website I found a <a href="http://jung.sourceforge.net/doc/JUNG_journal.pdf" rel="nofollow noreferrer">paper which has references to various algorithms</a></p> <p><strong>NodeLinkTreeLayout.java</strong>: The algorithm used is that of Christoph Buchheim, Michael Jünger, and Sebastian Leipert from their research paper <a href="http://citeseer.ist.psu.edu/buchheim02improving.html" rel="nofollow noreferrer">Improving Walker's Algorithm to Run in Linear Time</a>, Graph Drawing 2002. This algorithm corrects performance issues in Walker's algorithm, which generalizes Reingold and Tilford's method for tidy drawings of trees to support trees with an arbitrary number of children at any given node.</p> <p><strong>RadialTreeLayout.java</strong>: The algorithm used is that of Ka-Ping Yee, Danyel Fisher, Rachna Dhamija, and Marti Hearst in their research paper <a href="http://citeseer.ist.psu.edu/448292.html" rel="nofollow noreferrer">Animated Exploration of Dynamic Graphs with Radial Layout</a>, InfoVis 2001. This algorithm computes a radial layout which factors in possible variation in sizes, and maintains both orientation and ordering constraints to facilitate smooth and understandable transitions between layout configurations.</p> <p><strong>SquarifiedTreeMapLayout</strong>: This particular algorithm is taken from Bruls, D.M., C. Huizing, and J.J. van Wijk, "Squarified Treemaps" In <i>Data Visualization 2000, Proceedings of the Joint Eurographics and IEEE TCVG Sumposium on Visualization</i>, 2000, pp. 33-42. Available online at <a href="http://www.win.tue.nl/~vanwijk/stm.pdf" rel="nofollow noreferrer">http://www.win.tue.nl/~vanwijk/stm.pdf</a>. For more information on TreeMaps in general, see <a href="http://www.cs.umd.edu/hcil/treemap-history" rel="nofollow noreferrer">http://www.cs.umd.edu/hcil/treemap-history</a></p>
<p>Not sure what you are after ...</p> <p>sounds like maybe you are looking to do something similar to rrdtool?</p> <p>Maybe there is some info at their site that will help:</p> <p><a href="http://oss.oetiker.ch/rrdtool/" rel="nofollow noreferrer">http://oss.oetiker.ch/rrdtool/</a></p>
44,964
<p>I'm currently running Lucene.net in a web application and am wondering about the best method, performance-wise.</p> <p>I currently have it set up so that all index writes get processed together in a scheduled process, along with optimizing the index.</p> <p>However for searching - I'm currently opening and closing the searcher per search, which I know isn't ideal.</p> <p>What do you think would be the best approach in this situation?</p> <p>I'll need to close and reopen the index searcher once the updates/optimization is processed so the scheduled process (which is a windows console app) needs to communicate it's finished to the web application.</p>
<p>I just integrated Lucene.NET into BugTracker.NET. I'm not sure that what I did is the best, but it seems to be working well. </p> <p>I create the index at app startup.</p> <p>I create a searcher and keep it around so that the index isn't reloaded with each search. All threads share the same searcher. When the searcher searches, it grabs a lock. </p> <p>Meanwhile, I have an IndexWriter that updates the index when there is a data change. It is just changing a little bit so it does its task quick. When it runs, it grabs the same lock, destroys the searcher, updates the index, and the re-recreates the searcher. The new searcher stays around until the next update of the index. The searcher always is working with an up-to-date index.</p> <p>You can get the BugTracker.NET source and look at the files my_lucene.cs and search_text.aspx. It's all in those two files, and there isn't that much code.</p>
<p>You could call to the readers IsCurrent() method to check if there is a new version of the index available, and if it's then reopen it. Couldn't be the best way, but is easy enough and if your requirements are not very big it will be sufficient. </p>
31,213
<p>I'm building a listing/grid control in a <code>Flex</code> application and using it in a <code>.NET</code> web application. To make a really long story short I am getting XML from a webservice of serialized objects. I have a page limit of how many things can be on a page. I've taken a data grid and made it page, sort across pages, and handle some basic filtering. </p> <p>In regards to paging I'm using a Dictionary keyed on the page and storing the XML for that page. This way whenever a user comes back to a page that I've saved into this dictionary I can grab the XML from local memory instead of hitting the webservice. Basically, I'm caching the data retrieved from each call to the webservice for a page of data.</p> <p>There are several things that can expire my cache. Filtering and sorting are the main reason. However, a user may edit a row of data in the grid by opening an editor. The data they edit could cause the data displayed in the row to be stale. I could easily go to the webservice and get the whole page of data, but since the page size is set at runtime I could be looking at a large amount of records to retrieve.</p> <p>So let me now get to the heart of the issue that I am experiencing. In order to prevent getting the whole page of data back I make a call to the webservice asking for the completely updated record (the editor handles saving its data).</p> <p>Since I'm using custom objects I need to serialize them on the server to XML (this is handled already for other portions of our software). All data is handled through XML in e4x. The cache in the Dictionary is stored as an XMLList.</p> <p><strong>Now let me show you my code...</strong></p> <pre><code>var idOfReplacee:String = this._WebService.GetSingleModelXml.lastResult.*[0].*[0].@Id; var xmlToReplace:XMLList = this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee); if(xmlToReplace.length() &gt; 0) { delete (this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0]); this._DataPages[this._Options.PageIndex].Data += this._WebService.GetSingleModelXml.lastResult.*[0].*[0]; } </code></pre> <p>Basically, I get the id of the node I want to replace. Then I find it in the cache's Data property (<code>XMLList</code>). I make sure it exists since the filter on the second line returns the <code>XMLList</code>.</p> <p>The problem I have is with the delete line. I cannot make that line delete that node from the list. The line following the delete line works. I've added the node to the list.</p> <p>How do I replace or delete that node (meaning the node that I find from the filter statement out of the .Data property of the cache)???</p> <p>Hopefully the underscores for all of my variables do not stay escaped when this is posted! otherwise <code>this.&amp;#95 == this</code>._</p>
<p>Thanks for the answers guys.</p> <p>@Theo: I tried the replace several different ways. For some reason it would never error, but never update the list.</p> <p>@Matt: I figured out a solution. The issue wasn't coming from what you suggested, but from how the delete works with Lists (at least how I have it in this instance).</p> <p>The Data property of the _DataPages dictionary object is list of the definition nodes (was arrived at by a previous filtering of another XML document).</p> <pre><code>&lt;Models&gt; &lt;Definition Id='1' /&gt; &lt;Definition Id='2' /&gt; &lt;/Models&gt; </code></pre> <p>I ended up doing this little deal:</p> <pre><code>//gets the index of the node to replace from the same filter var childIndex:int = (this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0]).childIndex(); //deletes the node from the list delete this._DataPages[this._Options.PageIndex].Data[childIndex]; //appends the new node from the webservice to the list this._DataPages[this._Options.PageIndex].Data += this._WebService.GetSingleModelXml.lastResult.*[0].*[0]; </code></pre> <p>So basically I had to get the index of the node in the XMLList that is the Data property. From there I could use the delete keyword to remove it from the list. The += adds my new node to the list.</p> <p>I'm so used to using the ActiveX or Mozilla XmlDocument stuff where you call "SelectSingleNode" and then use "replaceChild" to do this kind of stuff. Oh well, at least this is in some forum where someone else can find it. I do not know the procedure for what happens when I answer my own question. Perhaps this insight will help someone else come along and help answer the question better!</p>
<p>I don't immediately see the problem, so I can only venture a guess. The <code>delete</code> line that you've got is looking for the first item <em>at the top level</em> of the list which has an attribute "Id" with a value equal to <code>idOfReplacee</code>. Ensure that you don't need to dig deeper into the XML structure to find that matching id.</p> <p>Try this instead:</p> <pre><code>delete (this._DataPages[this._Options.PageIndex].Data..(@Id == idOfReplacee)[0]); </code></pre> <p>(Notice the extra '.' after <code>Data</code>). You could more easily debug this by setting a breakpoint on the second line of the code you posted, and ensure that the XMLList looks like you expect.</p>
3,213
<p>How do I determine whether an object is a member of a collection in VBA?</p> <p>Specifically, I need to find out whether a table definition is a member of the <code>TableDefs</code> collection.</p>
<p>Your best bet is to iterate over the members of the collection and see if any match what you are looking for. Trust me I have had to do this many times.</p> <p>The second solution (which is much worse) is to catch the "Item not in collection" error and then set a flag to say the item does not exist. </p>
<p>I did it like this, a variation on Vadims code but to me a bit more readable:</p> <pre><code>' Returns TRUE if item is already contained in collection, otherwise FALSE Public Function Contains(col As Collection, item As String) As Boolean Dim i As Integer For i = 1 To col.Count If col.item(i) = item Then Contains = True Exit Function End If Next i Contains = False End Function </code></pre>
16,673
<p>Sorry if this is basic but I was trying to pick up on .Net 3.5.</p> <p>Question: Is there anything great about Func&lt;> and it's 5 overloads? From the looks of it, I can still create a similar delgate on my own say, MyFunc&lt;> with the exact 5 overloads and even more.</p> <p>eg: <code>public delegate TResult MyFunc&lt;TResult&gt;()</code> and a combo of various overloads...</p> <p>The thought came up as I was trying to understand Func&lt;> delegates and hit upon the following scenario:</p> <pre><code>Func&lt;int,int&gt; myDelegate = (y) =&gt; IsComposite(10); </code></pre> <p>This implies a delegate with one parameter of type int and a return type of type int. There are five variations (if you look at the overloads through intellisense). So I am guessing that we can have a delegate with no return type?</p> <p>So am I justified in saying that Func&lt;> is nothing great and just an example in the .Net framework that we can use and if needed, create custom "func&lt;>" delegates to suit our own needs?</p> <p>Thanks,</p>
<p>The greatness lies in establishing <strong>shared language for better communication</strong>.</p> <p>Instead of defining your own delegate types for the same thing (delegate explosion), use the ones provided by the framework. Anyone reading your code instantly grasps what you are trying to accomplish.. minimizes the time to 'what is this piece of code actually doing?' So as soon as I see a</p> <ul> <li><strong>Action</strong> = some method that just does something and returns no output</li> <li><strong>Comparison</strong> = some method that compares two objects of the same type and returns an int to indicate order</li> <li><strong>Converter</strong> = transforms Obj A into equivalent Obj B</li> <li><strong>EventHandler</strong> = response/handler to an event raised by some object given some input in the form of an event argument</li> <li><strong>Func</strong> = some method that takes some parameters, computes something and returns a result</li> <li><strong>Predicate</strong> = evaluate input object against some criteria and return pass/fail status as bool</li> </ul> <p>I don't have to dig deeper than that unless it is my immediate area of concern. So if you feel the delegate you need fits one of these needs, use them before rolling your own. </p> <p><em>Disclaimer: Personally I like this move by the language designers.</em></p> <p><strong>Counter-argument</strong> : Sometimes defining your delegate may help communicate intent better. e.g. <code>System.Threading.ThreadStart</code> over <code>System.Action</code>. So it’s a judgment call in the end.</p>
<p>Though it is an old thread I had to add that func&lt;> and action&lt;> also help us use covariance and contra variance.</p> <p><a href="http://msdn.microsoft.com/en-us/library/dd465122.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/dd465122.aspx</a></p>
41,355
<p>I have a legacy app where it reads message from a client program from file descriptor 3. This is an external app so I cannot change this. The client is written in C#. How can we open a connection to a specific file descriptor in C#? Can we use something like AnonymousPipeClientStream()? But how do we specify the file descriptor to connect to?</p>
<p>Unfortunately, you won't be able to do that without P/Invoking to the native Windows API first.</p> <p>First, you will need to open your file descriptor with a native P/Invoke call. This is done by the OpenFileById WINAPI function. <a href="http://msdn.microsoft.com/en-us/library/aa365432(VS.85).aspx" rel="noreferrer">Here's how to use it</a> on MSDN, <a href="http://social.msdn.microsoft.com/forums/en-US/windowssearch/thread/4b71fcb3-bea9-4cfb-bdb7-2f1a91522ea6/" rel="noreferrer">here's an other link</a> explaining it in detail on the MSDN forums, and <a href="http://www.pinvoke.net/" rel="noreferrer">here's some help (pinvoke.net)</a> on how to construct your P/Invoke call.</p> <p>Once you got the file handle, you need to wrap it in a SafeFileHandle, this time in safe, managed C#:</p> <pre><code>// nativeHandle is the WINAPI handle you have acquired with the P/Invoke call SafeFileHandle safeHandle = new SafeFileHandle(nativeHandle, true); </code></pre> <p>Now you can open the file stream directly:</p> <pre><code>Stream stream = new FileStream(safeHandle, FileAccess.ReadWrite); </code></pre> <p>And from this point you can use it as any other file or stream in C#. Don't forget to dispose your objects once you're done.</p>
<p>I was able to solve the same issue by using <a href="https://msdn.microsoft.com/en-us/library/ks2530z6.aspx" rel="nofollow noreferrer"><code>_get_osfhandle</code></a>. Example:</p> <pre><code>using System; using System.IO; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; class Comm : IDisposable { [DllImport("MSVCRT.DLL", CallingConvention = CallingConvention.Cdecl)] extern static IntPtr _get_osfhandle(int fd); public readonly Stream Stream; public Comm(int fd) { var handle = _get_osfhandle(fd); if (handle == IntPtr.Zero || handle == (IntPtr)(-1) || handle == (IntPtr)(-2)) { throw new ApplicationException("invalid handle"); } var fileHandle = new SafeFileHandle(handle, true); Stream = new FileStream(fileHandle, FileAccess.ReadWrite); } public void Dispose() { Stream.Dispose(); } } </code></pre>
30,499
<p>I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate). </p> <p><a href="http://www.imperialviolet.org/pybloom.html" rel="noreferrer">Pybloom</a> is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has <a href="http://bitworking.org/news/380/bloom-filter-resources" rel="noreferrer">an implementation</a>. </p> <p>Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation.</p> <p>Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?</p>
<p>I recently went down this path as well; though it sounds like my application was slightly different. I was interested in approximating set operations on a large number of strings. </p> <p>You do make the key observation that a <strong>fast</strong> bit vector is required. Depending on what you want to put in your bloom filter, you may also need to give some thought to the speed of the hashing algorithm(s) used. You might find this <a href="http://www.partow.net/programming/hashfunctions/index.html" rel="noreferrer">library</a> useful. You may also want to tinker with the random number technique used below that only hashes your key a single time.</p> <p>In terms of non-Java bit array implementations:</p> <ul> <li>Boost has <a href="http://www.boost.org/doc/libs/1_37_0/libs/dynamic_bitset/dynamic_bitset.html" rel="noreferrer">dynamic_bitset</a></li> <li>Java has the built in <a href="http://java.sun.com/javase/6/docs/api/java/util/BitSet.html" rel="noreferrer">BitSet</a></li> </ul> <p>I built my bloom filter using <a href="http://cobweb.ecn.purdue.edu/~kak/dist/" rel="noreferrer">BitVector</a>. I spent some time profiling and optimizing the library and contributing back my patches to Avi. Go to that BitVector link and scroll down to acknowledgments in v1.5 to see details. In the end, I realized that performance was not a goal of this project and decided against using it. </p> <p>Here's some code I had lying around. I may put this up on google code at python-bloom. Suggestions welcome.</p> <pre><code>from BitVector import BitVector from random import Random # get hashes from http://www.partow.net/programming/hashfunctions/index.html from hashes import RSHash, JSHash, PJWHash, ELFHash, DJBHash # # ryan.a.cox@gmail.com / www.asciiarmor.com # # copyright (c) 2008, ryan cox # all rights reserved # BSD license: http://www.opensource.org/licenses/bsd-license.php # class BloomFilter(object): def __init__(self, n=None, m=None, k=None, p=None, bits=None ): self.m = m if k &gt; 4 or k &lt; 1: raise Exception('Must specify value of k between 1 and 4') self.k = k if bits: self.bits = bits else: self.bits = BitVector( size=m ) self.rand = Random() self.hashes = [] self.hashes.append(RSHash) self.hashes.append(JSHash) self.hashes.append(PJWHash) self.hashes.append(DJBHash) # switch between hashing techniques self._indexes = self._rand_indexes #self._indexes = self._hash_indexes def __contains__(self, key): for i in self._indexes(key): if not self.bits[i]: return False return True def add(self, key): dupe = True bits = [] for i in self._indexes(key): if dupe and not self.bits[i]: dupe = False self.bits[i] = 1 bits.append(i) return dupe def __and__(self, filter): if (self.k != filter.k) or (self.m != filter.m): raise Exception('Must use bloom filters created with equal k / m paramters for bitwise AND') return BloomFilter(m=self.m,k=self.k,bits=(self.bits &amp; filter.bits)) def __or__(self, filter): if (self.k != filter.k) or (self.m != filter.m): raise Exception('Must use bloom filters created with equal k / m paramters for bitwise OR') return BloomFilter(m=self.m,k=self.k,bits=(self.bits | filter.bits)) def _hash_indexes(self,key): ret = [] for i in range(self.k): ret.append(self.hashes[i](key) % self.m) return ret def _rand_indexes(self,key): self.rand.seed(hash(key)) ret = [] for i in range(self.k): ret.append(self.rand.randint(0,self.m-1)) return ret if __name__ == '__main__': e = BloomFilter(m=100, k=4) e.add('one') e.add('two') e.add('three') e.add('four') e.add('five') f = BloomFilter(m=100, k=4) f.add('three') f.add('four') f.add('five') f.add('six') f.add('seven') f.add('eight') f.add('nine') f.add("ten") # test check for dupe on add assert not f.add('eleven') assert f.add('eleven') # test membership operations assert 'ten' in f assert 'one' in e assert 'ten' not in e assert 'one' not in f # test set based operations union = f | e intersection = f &amp; e assert 'ten' in union assert 'one' in union assert 'three' in intersection assert 'ten' not in intersection assert 'one' not in intersection </code></pre> <p>Also, in my case I found it useful to have a faster count_bits function for BitVector. Drop this code into BitVector 1.5 and it should give you a more performant bit counting method:</p> <pre><code>def fast_count_bits( self, v ): bits = ( 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 ) return bits[v &amp; 0xff] + bits[(v &gt;&gt; 8) &amp; 0xff] + bits[(v &gt;&gt; 16) &amp; 0xff] + bits[v &gt;&gt; 24] </code></pre>
<p>I've put up a python bloom filter implementation at <a href="http://stromberg.dnsalias.org/~strombrg/drs-bloom-filter/" rel="nofollow">http://stromberg.dnsalias.org/~strombrg/drs-bloom-filter/</a></p> <p>It's in pure python, has good hash functions, good automated tests, a selection of backends (disk, array, mmap, more) and more intuitive arguments to the <code>__init__</code> method, so you can specify an ideal number of elements and desired maximum error rate, instead of somewhat ethereal, datastructure-specific tunables.</p>
40,105
<p>I have a .fla file with some text that I want to get at. Is there a free app than you can use to open .fla files, or just a tool to dump strings and pics?</p>
<p>With such question, I just experiment...</p> <p>I went to deviantART, went to the <a href="http://browse.deviantart.com/resources/applications/flash/" rel="noreferrer" title="Flash .FLA Files">Flash .FLA Files</a> gallery and downloaded one at random.<br> I got a .fla file of about 1MB.</p> <p>I went to Sysinternals's site to get the latest version of <a href="http://technet.microsoft.com/en-us/sysinternals/bb897439.aspx" rel="noreferrer" title="Strings">Strings</a>, a command line tool to extract plain text strings from binary files.<br> Ran:</p> <pre><code>strings -n 10 "D:\Archives\scrolling flash gallery with preloader.fla" &gt; str </code></pre> <p>Got at text file with lot of data you have to sort yourself...</p> <p>There are some other similar freewares utilities, some with GUI, but this command line version is handy. Works with both (or either) Unicode and Ansi strings.</p> <p>Oh, obviously it is for Windows. You forgot to specify if you target a specific platform.</p> <p>PS.: for what it is worth, I believe the Flash SDK is free at Adobe's site. You just don't have the Flash IDE, only a compiler, etc. for AS development. Perhaps it includes a tool to look at .fla files (not tried the toolkit yet).</p>
<p>you can access the .FLA file by simply changing its .FLA to .ZIP, and brows it as a directory. As far as making changes, I would install the free trial "Animator". you could try and replace a file inside the .fla (now .zip), but i do not think it will actually work. Than again, it IS flash, so.. </p> <p>Best of luck.</p>
40,097
<p>My app has many controls on its surface, and more are added dynamically at runtime.</p> <p>Although i am using tabs to limit the number of controls shown, and double-buffering too, it still flickers and stutters when it has to redraw (resize, maximize, etc).</p> <p>What are your tips and tricks to improve WinForms app performance?</p>
<p>I know of two things you can do but they don't always apply to all situations.</p> <ol> <li><p>You're going to get better performance if you're using absolute positioning for each control (myNewlyCreatedButton.Location.X/Y) as opposed to using a flow layout panel or a table layout panel. WinForms has to do a lot less math trying to figure out where controls should be placed.</p></li> <li><p>If there is a single operation in which you're adding/removing/modifying a lot of controls, call "SuspendLayout()" on the container of the affected controls (whether it is a panel or the whole form), and when you're done with your work call "ResumeLayout()" on the same panel. If you don't, the form will have to do a layout pass each and every time you add/remove/modify a control, which cost a lot more time. see: <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx</a></p></li> </ol> <p>Although, I'm not sure how these approaches could apply when resizing a window.</p>
<p>Are you making good use of <code>SuspendLayout()</code> and <code>ResumeLayout()</code>?</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx</a></p>
6,669
<p>Currently I run an classic (old) ASP webpage with recordset object used directly in bad old spagethi code fasion.</p> <p>I'm thinking of implementing a data layer in asp.net as web serivce to improve manageability. This is also a first step towards upgrading the website to asp.net. The site itself remains ASP for the moment...</p> <p>Can anybody recommend a good way of replacing the recordset object type with a web service compatible type (like an array or something)? What do I replace below with?:</p> <pre><code>set objRS = oConn.execute(SQL) while not objRS.eof ... name = Cstr(objRS(1)) ... wend </code></pre> <p>and also mutliple recordsets can be replaced with? I'm talking :</p> <pre><code> set objRS = objRs.nextRecordset </code></pre> <p>Anybody went through this and can recommend?</p> <p><strong><em>@AdditionalInfo - you asked for it :-)</em></strong></p> <p>Let me start at the beginning. <strong>Existing Situation is</strong>: I have an old ASP website with classical hierachical content (header, section, subsection, content) pulled out of database via stored procedures and content pages are in database also (a link to html file).</p> <p>Now bad thing is, ASP code everywhere spread over many .asp files all doing their own database connections, reading, writing (u have to register for content). Recently we had problems with SQL injection attacks so I was called to fix it.</p> <p>I <em>could</em> go change all the .asp pages to prevent sql injection but that would be madness. So I thought build a data layer - all pages using this layer to access database. Once place to fix and update db access code.</p> <p>Coming to that decision I thought asp.net upgrade isn'f far away, why not start using asp.net for the data layer? This way it can be re-used when upgrading the site.</p> <p>That brings me to the questions above!</p>
<p>First my favorite advice of this week: do not treat your Web Service like it if was a local object or you are going to pay a very hefty performance price. Essentially, don't do things like this in your web application:</p> <pre><code>MyDataWebService ws = new MyDataWebService(); foreach(DataItem item in myData) { ws.Insert(item); } </code></pre> <p>You should always prefer to minimize calls to your Web Service (and SQL):</p> <pre><code>MyDataWebService ws = new MyDataWebService(); ws.Insert(myData); // Let the web service process the whole set at once. </code></pre> <p>Now, as far as the data type to use for your web service calls, you basically have two choices:</p> <ul> <li>DataSet</li> <li>Everything else (Array)</li> </ul> <p>Most collections returned from a web service (like a List&lt;MyData&gt;) actually convert to an Array during the Web Service invocation. Remember that Web Services don't return objects (data + behavior) but just data structures (or a sequence of). Therefore, there is little distinction between a List and an Array.</p> <p>DataSets are more complex classes; they use their own custom serializer and pretty much get fully recreated in the calling application. There is a cost in performance to be paid for using DataSets like that, so I don't usually recommend it for most scenarios. Using arrays to pass data back and forth tends to be more efficient, and quite frankly it's easier to do.</p> <p>Your case is a bit different; because you are converting an existing site that already uses ADO, an ADO.NET DataSet might be your best updgrade path. ADO.NET and ADO are similar enough that a straight update might be easier that way. It kind of depends how your web site is built.</p> <p>For the last part of your question, DataSets do support multiple recordsets similar to ADO's Recordset. They are called DataTables. Every DataSet has at least one DataTable and you can read them in any order.</p> <p>Good luck.</p>
<p>I'd suggest using the XmlHttp class in your ASP code.</p> <p>Assuming you have an ASMX web service similar to this, in MyService.asmx:</p> <pre><code>[WebMethod] public string HelloWorld() { return "Hello World"; } </code></pre> <p>You could call it in ASP something like this:</p> <pre><code>Dim xhr Set xhr = server.CreateObject("MSXML2.XMLHTTP") xhr.Open "POST", "/MyService.asmx/HelloWorld", false xhr.SetRequestHeader "content-type", "application/x-www-form-urlencoded" xhr.Send Response.Write(xhr.ResponseText) </code></pre> <p>ResponseText would be an XML response of:</p> <pre><code>&lt;string&gt;Hello World&lt;/string&gt; </code></pre> <p>Assuming your service returned a collection of data, you could iterate over it using XPath or any other XML processing technique/library.</p> <p>Googling around about MSXML2 will probably answer any specific questions you have, since it's specific to ASP classic.</p>
7,901
<p>I'm looking for an open-source library for editing AAC metadata in M4A files (as appearing in iTunes). Specifically, I need to be able to add an album art tag. It should be something similar to id3lib, which works with ID3 tags on MP3 files.</p>
<p>Try looking at <a href="//github.com/svnpenn/mp4v2" rel="nofollow noreferrer">mp4v2</a>. Although the code base is rather large and may be difficult to integrate into your build system, the library provides some command-line executables that you can use to modify AAC tags, including artwork.</p> <p>Thanks.</p>
<p>Since I hadn't find any open-source library maybe open-source program, that can read and set iTunes-style metadata tags in MPEG-4 files, will help you. <a href="http://atomicparsley.sourceforge.net/" rel="nofollow noreferrer">atomicparsley.sourceforge.net</a></p> <p>There is also Known iTunes Metadata structure provided: <a href="http://atomicparsley.sourceforge.net/mpeg-4files.html" rel="nofollow noreferrer"><a href="http://atomicparsley.sourceforge.net/mpeg-4files.html" rel="nofollow noreferrer">http://atomicparsley.sourceforge.net/mpeg-4files.html</a></a></p> <p>This discussion may also turn out helpful for you: <a href="http://www.hydrogenaudio.org/forums/lofiversion/index.php/t31022.html" rel="nofollow noreferrer">www.hydrogenaudio.org/forums/lofiversion/index.php/t31022.html</a></p> <p>Good Luck</p>
22,026
<p>I've noticed that just in the last year or so, many major websites have made the same change to the way their pages are structured. Each has moved their Javascript files from being hosted on the same domain as the page itself (or a subdomain of that), to being hosted on a differently named domain.</p> <h2>It's not simply parallelization</h2> <p>Now, there is a well known technique of spreading the components of your page across multiple domains to parallelize downloading. <a href="http://developer.yahoo.com/performance/rules.html#split" rel="nofollow noreferrer">Yahoo recommends it</a> as do many others. For instance, <strong>www.example.com</strong> is where your HTML is hosted, then you put images on <strong>images.example.com</strong> and javascripts on <strong>scripts.example.com</strong>. This gets around the fact that most browsers limit the number of simultaneous connections per server in order to be good net citizens.</p> <p>The above is <em>not</em> what I am talking about.</p> <h2>It's not simply redirection to a content delivery network (or maybe it is--see bottom of question)</h2> <p>What I am talking about is hosting Javascripts specifically on an entirely different domain. Let me be specific. Just in the last year or so I've noticed that:</p> <p><strong>youtube.com</strong> has moved its .JS files to <strong>ytimg.com</strong></p> <p><strong>cnn.com</strong> has moved its .JS files to <strong>cdn.turner.com</strong></p> <p><strong>weather.com</strong> has moved its .JS files to <strong>j.imwx.com</strong></p> <p>Now, I know about content delivery networks like <a href="http://www.akamai.com" rel="nofollow noreferrer">Akamai</a> who specialize in outsourcing this for large websites. (The name "cdn" in Turner's special domain clues us in to the importance of this concept here).</p> <p>But note with these examples, each site has its own specifically registered domain for this purpose, and its not the domain of a content delivery network or other infrastructure provider. In fact, if you try to load the home page off most of these script domains, they usually redirect back to the main domain of the company. And if you reverse lookup the IPs involved, they <em>sometimes</em> appear point to a CDN company's servers, sometimes not.</p> <h2>Why do I care?</h2> <p>Having formerly worked at two different security companies, I have been made paranoid of malicious Javascripts.</p> <p>As a result, I follow the practice of whitelisting sites that I will allow Javascript (and other active content such as Java) to run on. As a result, to make a site like <strong>cnn.com</strong> work properly, I have to manually put <strong>cnn.com</strong> into a list. It's a pain in the behind, but I prefer it over the alternative.</p> <p>When folks used things like <strong>scripts.cnn.com</strong> to parallelize, that worked fine with appropriate wildcarding. And when folks used subdomains off the CDN company domains, I could just permit the CDN company's main domain with a wildcard in front as well and kill many birds with one stone (such as *.edgesuite.net and *.akamai.com).</p> <p>Now I have discovered that (as of 2008) this is not enough. Now I have to poke around in the source code of a page I want to whitelist, and figure out what "secret" domain (or domains) that site is using to store their Javascripts on. In some cases I've found I have to permit three different domains to make a site work.</p> <h2>Why did all these major sites start doing this?</h2> <p>EDIT: OK <a href="https://stackoverflow.com/questions/160376/why-move-your-javascript-files-to-a-different-main-domain-that-you-also-own#160451">as "onebyone" pointed out</a>, it does appear to be related to CDN delivery of content. So let me modify the question slightly based on his research...</p> <p>Why is <strong>weather.com</strong> using <strong>j.imwx.com</strong> instead of <strong>twc.vo.llnwd.net</strong>?</p> <p>Why is <strong>youtube.com</strong> using <strong>s.ytimg.com</strong> instead of <strong>static.cache.l.google.com</strong>?</p> <p>There has to a reasoning behind this.</p>
<p>Your follow-up question is essentially: Assuming a popular website is using a CDN, why would they use their own TLD like imwx.com instead of a subdomain (static.weather.com) or the CDN's domain?</p> <p>Well, the reason for using a domain they control versus the CDN's domain is that they retain control -- they could potentially even change CDNs entirely and only have to change a DNS record, versus having to update links in 1000s of pages/applications.</p> <p>So, why use nonsense domain names? Well, a big thing with helper files like .js and .css is that you want them to be cached downstream by proxies and people's browsers as much as possible. If a person hits gmail.com and all the .js is loaded out of their browser cache, the site appears much snappier to them, and it also saves bandwidth on the server end (everybody wins). The problem is that once you send HTTP headers for really aggressive caching (i.e. cache me for a week or a year or forever), these files aren't ever reliably loaded from the server any more and you can't make changes/fixes to them because things will break in people's browsers.</p> <p>So, what companies have to do is stage these changes and actually change the URLs of all of these files to force people's browsers to reload them. Cycling through domains like "a.imwx.com", "b.imwx.com" etc. is how this gets done.</p> <p>By using a nonsense domain name, the Javascript developers and their Javascript sysadmin/CDN liaison counterparts can have their own domain name/DNS that they're pushing these changes through, that they're accountable/autonomous for.</p> <p>Then, if any sort of cookie-blocking or script-blocking starts happening on the TLD, they just change from one nonsense TLD to kyxmlek.com or whatever. They don't have to worry about accidentally doing something evil that has countermeasure side effects on all of *.google.com.</p>
<p>It's not just javascript that you can move to different domains but as many assets as possible will yield performance improvements.</p> <p>Most browsers have a limit to the number of simultanious connections you can make to a single domain (I think it's around 4) so when you have a lot of images, js, css, etc theres often hold up in downloading each file.</p> <p>You can use something like YSlow and FireBug to view when each file is downloaded from the server.</p> <p>By having assets on separate domains you lessen the load on your primary and can have more simultanious connections and download more files at any given time.</p> <p>We recently launched a realestate website which has a lot of images (of the houses, duh :P) which uses this principle for the images, so it's a lot faster to list the data.</p> <p>We've also used this on many other websites which have high asset volumne.</p>
19,393
<p>I'm mocking about with plt-scheme's ffi and I have a C-function that returns a char ** (array of strings). If I declare my function as <code>(_fun _pointer -&gt; _pointer)</code>, how do I convert the result to a list of strings in scheme?</p> <p>Here are the relevant C-declarations:</p> <pre><code>typedef char **MYSQL_ROW; /* return data as array of strings */ // ... MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result); </code></pre>
<p>I <em>think</em> that what you want is the cvector:</p> <p><a href="http://docs.plt-scheme.org/foreign/Derived_Utilities.html#(part._foreign~3acvector)" rel="nofollow noreferrer">http://docs.plt-scheme.org/foreign/Derived_Utilities.html#(part._foreign~3acvector)</a></p> <p>A cvector of _string/utf-8 or whichever encoding you need seems reasanable.</p> <p>But that's from a quick survey of the docs - I haven't tried this myself. Please let me know if it works!</p>
<p>I know it's not exactly what you are looking for, but it might help a little bit. I've done some work on a basic Gambit Scheme FFI for MySQL. I don't know how PLT Scheme and Gambit differ in terms of their FFI implementation (I'd venture with "quite a bit") but maybe you can get something out of it:</p> <p><a href="http://bunny.jonnay.net/zengarden/trunk/lib/mysql/mysql-ffi.scm" rel="nofollow noreferrer">http://bunny.jonnay.net/zengarden/trunk/lib/mysql/mysql-ffi.scm</a></p>
13,135
<p>I am looking for a tool that can take a unit test, like </p> <pre><code>IPerson p = new Person(); p.Name = "Sklivvz"; Assert.AreEqual("Sklivvz", p.Name); </code></pre> <p>and generate, automatically, the corresponding stub class and interface</p> <pre><code>interface IPerson // inferred from IPerson p = new Person(); { string Name { get; // inferred from Assert.AreEqual("Sklivvz", p.Name); set; // inferred from p.Name = "Sklivvz"; } } class Person: IPerson // inferred from IPerson p = new Person(); { private string name; // inferred from p.Name = "Sklivvz"; public string Name // inferred from p.Name = "Sklivvz"; { get { return name; // inferred from Assert.AreEqual("Sklivvz", p.Name); } set { name = value; // inferred from p.Name = "Sklivvz"; } } public Person() // inferred from IPerson p = new Person(); { } } </code></pre> <p>I know ReSharper and Visual Studio do some of these, but I need a complete tool -- command line or whatnot -- that automatically infers what needs to be done. If there is no such tool, how would you write it (e.g. extending ReSharper, from scratch, using which libraries)?</p>
<p>What you appear to need is a parser for your language (Java), and a name and type resolver. ("Symbol table builder"). </p> <p>After parsing the source text, a compiler usually has a name resolver, that tries to record the definition of names and their corresponding types, and a type checker, that verifies that each expression has a valid type.</p> <p>Normally the name/type resolver complains when it can't find a definition. What you want it to do is to find the "undefined" thing that is causing the problem, and infer a type for it.</p> <p>For</p> <pre><code> IPerson p = new Person(); </code></pre> <p>the name resolver knows that "Person" and "IPerson" aren't defined. If it were</p> <pre><code> Foo p = new Bar(); </code></pre> <p>there would be no clue that you wanted an interface, just that Foo is some kind of abstract parent of Bar (e.g., a class or an interface). So the decision as which is it must be known to the tool ("whenever you find such a construct, assume Foo is an interface ..."). You could use a heuristic: IFoo and Foo means IFoo should be an interface, and somewhere somebody has to define Foo as a class realizing that interface. Once the tool has made this decision, it would need to update its symbol tables so that it can move on to other statements:</p> <p>For</p> <pre><code> p.Name = "Sklivvz"; </code></pre> <p>given that p must be an Interface (by the previous inference), then Name must be a field member, and it appears its type is String from the assignment.</p> <p>With that, the statement:</p> <pre><code> Assert.AreEqual("Sklivvz", p.Name); </code></pre> <p>names and types resolve without further issue. </p> <p>The content of the IFoo and Foo entities is sort of up to you; you didn't have to use get and set but that's personal taste.</p> <p>This won't work so well when you have multiple entities in the same statement:</p> <pre><code> x = p.a + p.b ; </code></pre> <p>We know a and b are likely fields, but you can't guess what numeric type if indeed they are numeric, or if they are strings (this is legal for strings in Java, dunno about C#). For C++ you don't even know what "+" means; it might be an operator on the Bar class. So what you have to do is collect <em>constraints</em>, e.g., "a is some indefinite number or string", etc. and as the tool collects evidence, it narrows the set of possible constraints. (This works like those word problems: "Joe has seven sons. Jeff is taller than Sam. Harry can't hide behind Sam. ... who is Jeff's twin?" where you have to collect the evidence and remove the impossibilities). You also have to worry about the case where you end up with a contradiction.</p> <p>You could rule out p.a+p.b case, but then you can't write your unit tests with impunity. There are standard constraint solvers out there if you want impunity. (What a concept).</p> <p>OK, we have the ideas, now, can this be done in a practical way?</p> <p>The first part of this requires a parser and a bendable name and type resolver. You need a constraint solver or at least a "defined value flows to undefined value" operation (trivial constraint solver). </p> <p>Our <a href="http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html" rel="nofollow">DMS Software Reengineering Toolkit</a> with its <a href="http://www.semanticdesigns.com/Products/FrontEnds/JavaFrontEnd.html" rel="nofollow">Java Front End</a> could probably do this. DMS is a tool builder's tool, for people that want to build tools that process computer langauges in arbitrary ways. (Think of "computing with program fragments rather than numbers").</p> <p>DMS provides general purpose parsing machinery, and can build an tree for whatever front end it is given (e.g., Java, and there's a C# front end). The reason I chose Java is that our Java front end has all that name and type resolution machinery, and it is provided in source form so it can be bent. If you stuck to the trivial constraint solver, you could probably bend the Java name resolver to figure out the types. DMS will let you assemble trees that correspond to code fragments, and coalesce them into larger ones; as your tool collected facts for the symbol table, it could build the primitive trees. </p> <p>Somewhere, you have to decide you are done. How many unit tests the tool have to see before it knows the entire interface? (I guess it eats all the ones you provide?). Once complete, it assembles the fragments for the various members and build an AST for an interface; DMS can use its prettyprinter to convert that AST back into source code like you've shown.</p> <p>I suggest Java here because our Java front end has name and type resolution. Our C# front end does not. This is a "mere" matter of ambition; somebody has to write one, but that's quite a lot of work (at least it was for Java and I can't imagine C# is really different).</p> <p>But the idea works fine in principle using DMS. </p> <p>You could do this with some other infrastructure that gave you access to a parser and an a bendable name and type resolver. That might not be so easy to get for C#; I suspect MS may give you a parser, and access to name and type resolution, but not any way to change that. Maybe Mono is the answer? </p> <p>You still need a was to generate code fragments and assemble them. You might try to do this by string hacking; my (long) experience with gluing program bits together is that if you do it with strings you eventually make a mess of it. You really want pieces that represent code fragments of known type, that can only be combined in ways the grammar allows; DMS does that thus no mess.</p>
<p>I find that whenever I need a code generation tool like this, I am probably writing code that could be made a little bit more generic so I only need to write it once. In your example, those getters and setters don't seem to be adding any value to the code - in fact, it is really just asserting that the getter/setter mechanism in C# works.</p> <p>I would refrain from writing (or even using) such a tool before understanding what the motivations for writing these kinds of tests are.</p> <p>BTW, you might want to have a look at <a href="http://code.google.com/p/nbehave/" rel="nofollow noreferrer">NBehave</a>?</p>
11,701
<p>Is there any way to find out what exceptions might be thrown by any method in .NET code? Ideally I want to see what might be thrown and choose which ones I want to handle. I guess I want the information you'd get from the throws clause in java. </p> <p>The situation is I'm doing a linq query on an xml document from the network and want to know what could go wrong. I could open up the assembly in reflector and have a look but I thought there might be an easier way. </p>
<p>.NET does not have enforced (&quot;checked&quot;) exceptions like java. The intellisense <em>might</em> show this information, if the developer has added a <code>/// &lt;exception.../&gt;</code> block - but ultimately more exceptions can happen than you expect (<code>OutOfMemoryException</code>, <code>ThreadAbortException</code>, <code>TypeLoadException</code>, etc can all happen fairly unpredictably).</p> <p>In general, you should have an idea of what things are likely to go wrong, and which ones you can actually do something useful about. In most cases, the correct behaviour is to let the exception bubble up (just running any &quot;finally&quot; code to release resources).</p> <p>Eric Lippert has a good blog on this subject <a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/vexing-exceptions" rel="nofollow noreferrer">here</a>.</p>
<p>As long as you're using BCL classes, they are all completely documented and Intellisense therefore displays any exception a method can throw. Other than that (and reading the docs), there is no way, I think.</p>
33,173
<p>Some things look strange to me:</p> <ul> <li>What is the distinction between 0.0.0.0, 127.0.0.1, and [::]?</li> <li>How should each part of the foreign address be read (part1:part2)?</li> <li>What does a state Time_Wait, Close_Wait mean?</li> <li>etc.</li> </ul> <p>Could someone give a quick overview of how to interpret these results?</p>
<p>0.0.0.0 usually refers to stuff listening on all interfaces. 127.0.0.1 = localhost (only your local interface) I'm not sure about [::]</p> <p>TIME_WAIT means both sides have agreed to close and TCP must now wait a prescribed time before taking the connection down.</p> <p>CLOSE_WAIT means the remote system has finished sending and your system has yet to say it's finished. </p>
<p>For those seeing [::] in their netstat output, I'm betting your machine is running IPv6; that would be equivalent to 0.0.0.0, i.e. listen on any IPv6 address. </p>
4,126
<p>I have a text file of URLs, about 14000. Below is a couple of examples:</p> <p><a href="http://www.domainname.com/pagename?CONTENT_ITEM_ID=100&amp;param2=123" rel="nofollow noreferrer">http://www.domainname.com/pagename?CONTENT_ITEM_ID=100&amp;param2=123</a><br /> <a href="http://www.domainname.com/images?IMAGE_ID=10" rel="nofollow noreferrer">http://www.domainname.com/images?IMAGE_ID=10</a><br /> <a href="http://www.domainname.com/pagename?CONTENT_ITEM_ID=101&amp;param2=123" rel="nofollow noreferrer">http://www.domainname.com/pagename?CONTENT_ITEM_ID=101&amp;param2=123</a><br /> <a href="http://www.domainname.com/images?IMAGE_ID=11" rel="nofollow noreferrer">http://www.domainname.com/images?IMAGE_ID=11</a><br /> <a href="http://www.domainname.com/pagename?CONTENT_ITEM_ID=102&amp;param2=123" rel="nofollow noreferrer">http://www.domainname.com/pagename?CONTENT_ITEM_ID=102&amp;param2=123</a><br /></p> <p>I have loaded the text file into a Python list and I am trying to get all the URLs with CONTENT_ITEM_ID separated off into a list of their own. What would be the best way to do this in Python?</p> <p>Cheers</p>
<p>Here's another alternative to Graeme's, using the newer list comprehension syntax:</p> <pre><code>list2= [line for line in file if 'CONTENT_ITEM_ID' in line] </code></pre> <p>Which you prefer is a matter of taste!</p>
<pre><code>list2 = filter( lambda x: x.find( 'CONTENT_ITEM_ID ') != -1, list1 ) </code></pre> <p>The filter calls the function (first parameter) on each element of list1 (second parameter). If the function returns true (non-zero), the element is copied to the output list.</p> <p>The lambda basically creates a temporary unnamed function. This is just to avoid having to create a function and then pass it, like this:</p> <pre><code>function look_for_content_item_id( elem ): if elem.find( 'CONTENT_ITEM_ID') == -1: return 0 return 1 list2 = filter( look_for_content_item_id, list1 ) </code></pre>
32,257
<p>I'm working on a .net solution that is run completely inside a single network. When users make a change to the system, I want to launch an announcement and have everyone else hear it and act accordingly. Is there a way that we can broadcast out messages like this (like UDP will let you do) while keeping guaranteed delivery (like TCP)?</p> <p>This is on a small network (30ish clients), if that would make a difference.</p>
<p>Almost all games have a need for the fast-reacting properties (and to a lesser extent, the connectionless properties) of UDP and the reliability of TCP. What they do is they build their own reliable protocol on top of UDP. This gives them the ability to just burst packets to whereever and optionally make them reliable, as well.</p> <p>The reliable packet system is usually a simple retry-until-acknowledged system simpler than TCP but there are protocols which go way beyond what TCP can offer.</p> <p>Your situation sounds very simple. You'll probably be able to make the cleanest solution yourself - just make every client send back an "I heard you" response and have the server keep trying until it gets it (or gives up).</p> <p>If you want something more, most custom protocol libraries are in C++, so I am not sure how much use they'll be to you. However, my knowledge here is a few years old - perhaps some protocols have been ported over by now. Hmm... RakNet and enet are two C/C++ libraries that come to mind.</p>
<p>do a RDP multicast. </p>
5,153
<p>I need help on this following aspx code</p> <p>aspx Code:</p> <pre><code>&lt;asp:Label ID ="lblName" runat ="server" Text ="Name"&gt;&lt;/asp:Label&gt; &lt;asp:TextBox ID ="txtName" runat ="server"&gt;&lt;/asp:TextBox&gt; </code></pre> <p>Consider this is my aspx page content. I am going to populate the values for the TextBox only after the postback from server. But the label is also posting to the server (<code>runat="server"</code>) even though it's not necessary. Should I write my code like this to save time from server with less load.</p> <p>Corrected Code:</p> <pre><code>&lt;label id ="lblNames"&gt;Name&lt;/label&gt; &lt;asp:TextBox ID ="txtName" runat ="server"&gt;&lt;/asp:TextBox&gt; </code></pre> <p>Only my server control will send to the server for postback and not my HTML control which has a static value.</p> <p>Please suggest whether this is the correct way of coding.</p>
<p>If you take the <strong><code>runat='server'</code></strong> out of the <code>&lt;label&gt;</code> element then it won't be parsed as a server control. If you're not going to do anything with <em><code>lblNames</code></em> from the server then it is perfectly okay to leave it out.</p>
<p>If you're not doing <em>anything</em> with the label server-side, then just use a <code>&lt;span></code>. It'll end up as the same html at the browser.</p>
19,981
<p>When I localize an asp.net page that is using bound controls (DetailsView, etc) that has TemplateFields bound using the &lt;%# Bind() #> syntax, after the localization all of the bindings are removed and I have to go back in &amp; rebind everything. I'm creating the localized resource file by switching to design view, then Tools / Generate Local Resource from the menu.</p> <p>Has anyone else seen this problem, and if so, do you have any suggestions for a workaround?</p> <p>Before:</p> <pre><code>&lt;asp:TemplateField HeaderText="First Name:"&gt; &lt;InsertItemTemplate&gt; &lt;uc:FirstNameTextBox runat="server" ID="FirstName" ValidationGroup="Main" Text='&lt;%# Bind("FirstName") %&gt;' /&gt; &lt;/InsertItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre> <p>After:</p> <pre><code>&lt;asp:TemplateField HeaderText="First Name:" meta:resourcekey="TemplateFieldResource1"&gt; &lt;InsertItemTemplate&gt; &lt;uc:FirstNameTextBox runat="server" ID="FirstName" ValidationGroup="Main" /&gt; &lt;/InsertItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre> <hr> <p>Edit: Looks like its just my own UserControls that lose the binding. I tried adding the Bindable and Localizable(false) attributes to the properties, but that didn't seem to help.</p>
<p>Just found this... <a href="http://blog.smart-ms.ordina.nl/Generate+Local+Resource+Files.aspx" rel="nofollow noreferrer">http://blog.smart-ms.ordina.nl/Generate+Local+Resource+Files.aspx</a></p> <p>Seems to do the trick without mangling your ASPX file at all... I've not run it over a master page / user control yet.</p>
<p>Yes! I had this happen to me, but just on user controls as well. Is this a normal problem then? I don't know how to resolve it though.</p> <p>Out of interest, is there any alternative to using Tools -> Generate Local Resource from the menu for building resource files??? I generally already attach my meta:resourcekey tags onto my localizable content controls and don't want it to change it for anything else.</p>
49,168
<p>Is there a difference between <code>Cursor.Current</code> and <code>this.Cursor</code> (where <code>this</code> is a WinForm) in .Net? I've always used <code>this.Cursor</code> and have had very good luck with it but I've recently started using CodeRush and just embedded some code in a "Wait Cursor" block and CodeRush used the <code>Cursor.Current</code> property. I've seen on the Internet and at work where other programmers have had some problems with the <code>Cursor.Current</code> property. It just got me to wondering if there is a difference in the two. Thanks in advance.</p> <p>I did a little test. I have two winforms. I click a button on form1, set the <code>Cursor.Current</code> property to <code>Cursors.WaitCursor</code> and then show form2. The cursor doesn't change on either form. It remains <code>Cursors.Default</code> (pointer) cursor.</p> <p>If I set <code>this.Cursor</code> to <code>Cursors.WaitCursor</code> in the button click event on form1 and show form2, the wait cursor only shows on form1 and the default cursor is on form2 which is expected. So, I still don't know what <code>Cursor.Current</code> does.</p>
<p>Windows sends the window that contains the mouse cursor the WM_SETCURSOR message, giving it an opportunity to change the cursor shape. A control like TextBox takes advantage of that, changing the cursor into a I-bar. The Control.Cursor property determines what shape will be used.</p> <p>The Cursor.Current property changes the shape directly, without waiting for a WM_SETCURSOR response. In most cases, that shape is unlikely to survive for long. As soon as the user moves the mouse, WM_SETCURSOR changes it back to Control.Cursor.</p> <p>The UseWaitCursor property was added in .NET 2.0 to make it easier to display an hourglass. Unfortunately, it doesn't work very well. It requires a WM_SETCURSOR message to change the shape and that won't happen when you set the property to true and then do something that takes a while. Try this code for example:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { this.UseWaitCursor = true; System.Threading.Thread.Sleep(3000); this.UseWaitCursor = false; } </code></pre> <p>The cursor never changes. To whack that into shape, you'll need to use Cursor.Current as well. Here is a little helper class to make it easy:</p> <pre><code>using System; using System.Windows.Forms; public class HourGlass : IDisposable { public HourGlass() { Enabled = true; } public void Dispose() { Enabled = false; } public static bool Enabled { get { return Application.UseWaitCursor; } set { if (value == Application.UseWaitCursor) return; Application.UseWaitCursor = value; Form f = Form.ActiveForm; if (f != null &amp;&amp; f.Handle != IntPtr.Zero) // Send WM_SETCURSOR SendMessage(f.Handle, 0x20, f.Handle, (IntPtr)1); } } [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); } </code></pre> <p>And use it like this:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { using (new HourGlass()) { System.Threading.Thread.Sleep(3000); } } </code></pre>
<p>This works great for me when the LongRunningOperation() is processing messages.</p> <pre><code>private void btnDoLongRunningOperation_Click(object sender, System.EventArgs e) { this.Cursor = Cursors.WaitCursor; LongRunningOperation(); this.Cursor = Cursors.Arrow; } </code></pre>
38,874
<p>I have configured a simple LAMP stack on Debian and I am experiencing some problems with the Apache web server. </p> <p>Each 3-4 hours the web server is entering a deadlock and all the requests that hit the database block. The server is creating a new child for each request. The number of processes increases very quickly. After a few seconds Monit notices something is wrong and restarts the Apache server.</p> <p>I suspect this problem is generated by the way PHP handles database connection pooling because the server is still able to answer static content requests. Have you experienced this kind of behavior? What should I try to do?</p> <p><strong>Update:</strong> Problem solved. It seems it's a bad idea to use APC for opcode caching and user data. I am now using Memcache for storing user data and APC only for code. I still get some segmentation faults from time to time but the server is most of the time stable.</p>
<p>I would suspect that the problems are:</p> <ul> <li>A difficult long-running database query which blocks further requests. This is fairly easy if you're using the MySQL MyISAM engine which has only table-level locking and readers can easily block writers and vice versa, so a single tricky query on, say a user table, can pretty much block the entire server while the database waits for I/O. You can usually diagnose this by using "SHOW PROCESSLIST" or a tool which does this for you.</li> <li>Having set MaxClients much too high for the RAM available on a prefork server - almost everyone does this. If you are using a "fat" prefork Apache (e.g. with in-process PHP), then don't set MaxClients higher than you have enough ram for. This is probably a lot less than typical values of 100 or 150.</li> </ul> <p>These two things conspire to cause the issue you're seeing. They both need to be fixed as they can cause problems alone.</p> <p>This is based entirely on guesswork and experience.</p>
<p>The mysql-slow log is also useful for finding slow problem-causing queries.</p>
40,340
<p>I'm hooked on bitwise for a new security paradigm I'm creating called VMAC. Variable Matrix Access Control. I want to do logical implication on to bit strings. Just trying to avoid echoeureka (reinventing the wheel). </p> <ol> <li><p>Before I reinvent the wheel, is there an established shortcut to emulate &rArr; (logical implication) using AND and OR and NOT or other basic SQL binary operators?</p></li> <li><p>XNOR would allow me to cut &rArr; emulation down to four operations: NOT, XOR, OR, AND. But it is not widely available. Any known shortcuts to XNOR? I was thinking of something like AND operation on operands plus NOTted operands off the top of my head.</p></li> <li><p>Any comments on efficiency achieved by implementation of bitwise data structures on a 64-bit platform, or on the speed of multi-threaded apps using concurrent threads operating on word-size segments of larger data object?</p></li> </ol> <p>(Sorry, I'm not a computer scientist)</p>
<p><strong><em>if A then B</em></strong> is logically equivalent to <strong><em>(not A) or B</em></strong></p>
<p>The definition of <code>XNOR</code> is A*B + !A*!B</p> <p>Therefore in SQL this could be implemented like this:</p> <pre><code>DECLARE @A AS BIT; DECLARE @B AS BIT; (@A &amp; @B) | (~@A &amp; ~@B) </code></pre> <p>An alternate notation can be found here: <a href="http://michaelmairegger.wordpress.com/2011/10/14/sql-nand-xnor/" rel="nofollow">http://michaelmairegger.wordpress.com/2011/10/14/sql-nand-xnor/</a></p>
49,135
<p>We have been developing an Outlook Add-in using Visual Studio 2008. However I am facing a strange behavior while adding a command button to a custom command bar. This behavior is reflected when we add the button in the reply, reply all and forward windows. The issue is that the caption of the command button is not visible though when we debug using VS it shows the caption correctly. But the button is captionless when viewed in Outlook(2003).</p> <p>I have the code snippet as below. Any help would be appreciated.</p> <pre><code>private void AddButtonInNewInspector(Microsoft.Office.Interop.Outlook.Inspector inspector) { try { if (inspector.CurrentItem is Microsoft.Office.Interop.Outlook.MailItem) { try { foreach (CommandBar c in inspector.CommandBars) { if (c.Name == "custom") { c.Delete(); } } } catch { } finally { //Add Custom Command bar and command button. CommandBar myCommandBar = inspector.CommandBars.Add("custom", MsoBarPosition.msoBarTop, false, true); myCommandBar.Visible = true; CommandBarControl myCommandbarButton = myCommandBar.Controls.Add(MsoControlType.msoControlButton, 1, "Add", System.Reflection.Missing.Value, true); myCommandbarButton.Caption = "Add Email"; myCommandbarButton.Width = 900; myCommandbarButton.Visible = true; myCommandbarButton.DescriptionText = "This is Add Email Button"; CommandBarButton btnclickhandler = (CommandBarButton)myCommandbarButton; btnclickhandler.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.OnAddEmailButtonClick); } } } catch (System.Exception ex) { MessageBox.Show(ex.Message.ToString(), "AddButtInNewInspector"); } } </code></pre>
<p>I don't know the answer to your question, but I would highly recommend Add-In Express for doing the addin. See <a href="http://www.add-in-express.com/add-in-net/" rel="nofollow noreferrer">http://www.add-in-express.com/add-in-net/</a>. I've used this in many projects, including some commercial software and it is completely awesome. </p> <p>It does all the Outlook (and office) integration for you so you just work with it like any toolbar and just focus on the specifics of what you need it to do. You won't ever have to worry about the Outlook extensibility at all. Highly recommended. </p> <p>Anyway, just wanted to mention it as something to look in to. It will definitely save some headaches if you're comfortable with using a 3rd party component in the project.</p>
<p>I don't know, but your code raises two questions:</p> <ol> <li><p>Why are you declaring "CommandBarControl myCommandbarButton" instead of "CommandBarButton myCommandbarButton"?</p></li> <li><p>Why are you setting the width to 900 pixels? That's huge. I never bother with this setting in Excel since it autosizes, and I'm guessing the Outlook would behave the same.</p></li> </ol>
4,387
<p>Can this be done? How?</p> <hr> <p>I want to write my own extension. Can Get the current page sorcecode in my own extension?</p>
<p>As Rich says, adding <code>view-source</code> in front of the URL will give you the current page's source code. A keyboard shortcut for this is <code>Ctrl+U</code>.</p> <blockquote> <p>I want to write my own extension.</p> </blockquote> <p>There are a number of existing Firefox extensions that fetch a page's source code and apply some action to it (colour-coding, syntax-checking, etc). Downloading them and looking at how they handle it may be a good place to start!</p> <ul> <li><p><a href="http://www.searchenginejournal.com/7-firefox-extensions-to-explore-page-source-code/7375/" rel="nofollow noreferrer">7 Firefox extensions to explore source code</a></p></li> <li><p><a href="https://addons.mozilla.org/en-US/firefox/addon/697" rel="nofollow noreferrer">View Formatted Source extension</a></p></li> </ul> <p>If you're new to Firefox extension development, <a href="http://lifehacker.com/software/programming/how-to-build-a-firefox-extension-264490.php" rel="nofollow noreferrer">this article at Lifehacker</a> is an excellent primer in how to start, and will give you an idea of where to look in the above linked extensions for tasks that may be similar to your own.</p>
<p>Sure, just add view-source: in front of the URL.</p> <pre><code>view-source:http://stackoverflow.com/posts/edit/145419 </code></pre> <p>Will show the source of this page for instance - try it in the address bar.</p>
17,478
<p>Is there a way to access file system info via some type of Windows API? If not what other methods are available to a user mode developer?</p>
<p>Not very clean, but you can use <code>DeviceIoControl()</code> Open volume as a file, pass resulting handle to <code>DeviceIoControl()</code> together with control code. Check MSDN for control codes, there is something like "read journal record".</p>
<p>In another post, someone recommended this : <a href="http://www.microsoft.com/msj/0999/journal/journal.aspx" rel="nofollow noreferrer">Keeping an Eye on Your NTFS Drives: the Windows 2000 Change Journal Explained</a>.</p> <p>It explains how to use the NTFS Filesystem with C++ through Windows 2000. The implementation might have changed.</p>
8,082
<p>I want to write a function that accepts two objects as parameters and compare only the fields contained within the objects. I do not know what type the objects will be at design time, but the objects passed will be classes used within our application.</p> <p>Is it possible to compare object's fields without knowing their types at runtime?</p>
<p>Yes, it is possible to find the fields, properties, and methods of objects at runtime. You will need to use System.Reflection and find the matching fields, make sure the datatypes are compatible, and then compare the values.</p>
<p>This function would compare two simple objects (_Objeto1 and _Objeto2). First, they must not be NOTHING. Second, they must be same type (_AnyObject.GetType.ToString). Third, we have to iterate through each of their properties and compare their values. If at least one property has a different value, the functions returns FALSE. Otherwise, it returns TRUE.</p> <p>This function doesn't consider complex objects (one of their properties is another object). Simple objects are strings, integers, boolean, etc.</p> <p>Imports System Imports Microsoft.VisualBasic Imports System.Reflection</p> <p>Public Function CompararObjetos(ByVal _Objeto1 As Object, ByVal _Objeto2 As Object) As Boolean</p> <pre><code> Dim _TipoObjeto1 As String = "" Dim _TipoObjeto2 As String = "" If Not _Objeto1 Is Nothing Then _TipoObjeto1 = _Objeto1.GetType.ToString End If If Not _Objeto2 Is Nothing Then _TipoObjeto2 = _Objeto2.GetType.ToString End If Dim _Resultado As Boolean = True If _TipoObjeto1 = _TipoObjeto2 Then Dim Propiedades() As PropertyInfo = _Objeto1.GetType.GetProperties Dim Propiedad As PropertyInfo Dim _Valor1 As Object Dim _Valor2 As Object For Each Propiedad In Propiedades _Valor1 = Propiedad.GetValue(_Objeto1, Nothing) _Valor2 = Propiedad.GetValue(_Objeto2, Nothing) If _Valor1 &lt;&gt; _Valor2 Then _Resultado = False Exit For End If Next Else _Resultado = False End If Return _Resultado End Function </code></pre>
39,816
<p>I'm looking at an existing site and they are using separate databases. The databases seem to be setup in the following manner:</p> <ul> <li>general types (user_type, language, age, etc)</li> <li>member data (registration information &amp; login)</li> <li>site configuration</li> </ul> <p>Personally, I would put everything into 1 database. To me this would make it easier than almost always having to put the database name in front of every table.</p> <p>I can see from a security perspective ensuring that people cannot access the wrong data by accident, but on this site there are going to be admins (about 10% of the users on the site) that will need to access all the databases, doing cross database searches.</p> <p>What could be the reasons for doing separate databases? (The site is in PHP &amp; MySQL.)</p> <p><strong>Edit:</strong> The names of the db are:</p> <ul> <li><code>sitename</code> (the actual site name) (general types)</li> <li><code>member</code> (member data)</li> <li><code>siteconfig</code> (site configuration)</li> </ul>
<p>Purely speculation on what was in the minds of the creators:</p> <p>Maybe a difference in the volitilaty of the data, so that there could be a different backup/replication strategy for the different physical dbs?</p> <p>Maybe an idea that say, "general types" could be shared across multiple applications but the "site configuration", for example, would be specific to just one application?</p> <p>Maybe an idea that the different databases could be put on different pieces of hardware that have different performance characteristics, like their RAID configuration. Data that is read a lot but not updated versus data that is updated a lot.</p> <p>Again, pure speculation...</p> <p>@Darryl - my answer is more archeology than technology. I'm not saying I buy any of it. I'm just trying to step into the mindset of the ancestors...</p>
<p>If there were a good reason for breaking up a database into a bunch of smaller ones like this, the databases would probably have names like "hadronsupercolliderrawdata" and "googlebackup_2008". Names like "generaltypes" and "memberdata" suggest they were just overwhelmed by stupidity.</p>
35,828