input
stringlengths
51
42.3k
output
stringlengths
18
55k
How to walk the methods and their properties contained in a DLL? <p>Using preferably JScript, but VBscript will also do, how does one walk a DLL obtaining the properties and their attributes contained therein? Why? Because it would be good to ascertain the attributes of certain objects such as their datatypes at runtime rather than having to hard-code them before hand. An example of their use would be to initialise fields to their default values, e.g., spaces for strings, zeros for binaries and current date for dates.</p> <p>Cheers, John</p>
<p><a href="http://www.vbsedit.com" rel="nofollow">VBSEdit</a> will at least show you methods and properties of DLLs for VBScript when you create an object of that type in a script.</p>
How to show real-time suggestions (e.g. existing entries with same initial characters) while user is typing in a text field in Cocoa Touch? <p>I'm wondering if there is an existing class or library code in Cocoa Touch that shows the user a list of real-time suggestions while they are entering text input, with the suggestions based on similarities between what they have already entered and previous entries.</p> <p>For instance, see how Safari on the iPod Touch shows realtime suggestions when you start to type in a URL, based on previously visited sites.</p> <p>If there is a standard way of doing this, I'd love to know! If not, suggestions for a reasonable way to implement this -- subclass UITextField and go from there? -- would be welcome. </p>
<p>You need to check out the UITextFieldTextDidChangeNotification to see when the UITextField is changed. Look at NSNotificationCenter to see how to register an observer.</p>
Convert a Silverlight text to a path <p>Is there any way to render a Silverlight text to a path or graphics object <strong>at runtime</strong>? I know this can be done using the design tools, but I want to be able to do this on the fly.</p> <p>I've seen an example that <a href="http://blogs.msdn.com/webnext/archive/2007/05/22/silverlight-convert-text-to-path.aspx" rel="nofollow">calls a webservice which uses WPF constructs to convert a WPF FormattedText object to a PathGeometry</a>, but those objects aren't available in Silverlight.</p> <p>I'm pretty sure this just isn't supported in Silverlight, but thought it was worth asking.</p>
<p>As you suspected, you'd have to do it server-side to convert the text to a PathGeometry which <b>is</b> supported in Silverlight. What are you trying to achieve?</p>
Delphi object persistence, what is the best way <p>I have developed application for drawing some shapes (lines mostly) , now i need to be able to store sketch to a file, i know that delphi has build in routines for object persistance, but i have never used it. </p> <p>Can someone tell me can object persistence be used if i have to persist object that have also references to other objects (that will be stored to), i have TLine object wich can be connected to other TLine object etc. </p> <p>Is it better to use this feature or write custom procedure to store/read object to/from file.</p> <p>thx</p>
<p>The built in object persistance is primarily designed for use in streaming components to a dfm, the work that you would need to do to persist your sketch would not benefit very much from that mechanism. </p> <p>I think that you would be better off coming up with a custom scheme.</p>
Google Friend Connect - Logged in user profile info <p>I am trying to implement Google Friend Connect. Is it possible to obtain the email address of the logged in user? If so how?</p>
<p>Nope. Google doesn't let you have this information for the obvious reason that they don't want you to spam their users. If you need it, you'll have to ask for it explicitly.</p> <p>Stuff that should be available via GFC:</p> <ul> <li>opensocial.Person.Field.ID</li> <li>opensocial.Person.Field.NAME</li> <li>opensocial.Person.Field.NICKNAME</li> <li>opensocial.Person.Field.THUMBNAIL_URL</li> <li>opensocial.Person.Field.PROFILE_URL</li> </ul>
How to make Firefox extension auto install in nav bar? <p>I'm working on a Firefox extension. I'd like to make it auto-install in the far right position on the nav bar when a user installs it. As it stands, a user has to go to View > Toolbars > Customize... and drag the extension to the nav bar once it's installed. I'd like to eliminate this step.</p> <p>The extension is here: <a href="http://madan.org/tickertool" rel="nofollow">http://madan.org/tickertool</a></p> <p>The XUL for my extension looks basically like this and it overlays browser.xul:</p> <pre><code>&lt;overlay id="my-ext-overlay" ... &gt; &lt;toolbarpalette id="BrowserToolbarPalette"&gt; &lt;toolbaritem id="my-ext-container" ... &gt; &lt;toolbarbutton id="my-ext-customize-image" ... /&gt; &lt;textbox id="my-ext-textbox" ... /&gt; &lt;hbox id="my-ext-buttons"&gt; &lt;image id="my-ext-button1" ... /&gt; &lt;image id="my-ext-button2" ... /&gt; &lt;image id="my-ext-button3" ... /&gt; &lt;/hbox&gt; &lt;/toolbaritem&gt; &lt;/toolbarpalette&gt; &lt;/overlay&gt; </code></pre> <p>I've seen code here ( <a href="https://developer.mozilla.org/en/Code_snippets/Toolbar" rel="nofollow">https://developer.mozilla.org/en/Code_snippets/Toolbar</a> ) that supposedly does what I'm looking for, but this code is if your extension is just a single button and I can't get it to work for me. The answer to my question is likely some modification of this code, but I haven't figured it out.</p>
<p>I think I got it. It's basically spelled out in the link I mentioned in the original post. I'm not sure why I thought there was more to it than that.</p>
Getting a PHP DateTime object into a string representation of a MYSQL date <p>I have a DateTime which I want to store in a Date MySQL column. I am using MySQLi and prepared statements. </p> <p>When binding parameters, I cannot specify date as a type, only strings and integers.</p> <p>How do I convert the DateTime to a MySQL date string representation? There is very little documentation on the DateTime class.</p>
<p>I almost closed this as a duplicate of <a href="http://stackoverflow.com/questions/136782/format-mysql-datetime-with-php">http://stackoverflow.com/questions/136782/format-mysql-datetime-with-php</a> but I think it's actually the reverse problem. That question asked how to format a date fetched from MySQL, and you're asking how to format a date for input to a query.</p> <p><strong>Option 1:</strong></p> <pre><code>SELECT * FROM MyTable WHERE DateTimeCol = ? </code></pre> <p>You can format the value to the <code>YYYY-MM-DD HH:MM</code> format MySQL wants:</p> <pre><code>&lt;?php $mysql_date = date('Y-m-d H:i:s', $timestamp); ?&gt; </code></pre> <p>Then submit it as a string parameter to the query.</p> <p><strong>Option 2:</strong></p> <pre><code>SELECT * FROM MyTable WHERE DateTimeCol = FROM_UNIXTIME(?) </code></pre> <p>Then you can submit the timestamp value as a numeric parameter to the query.</p> <p><strong>Option 3:</strong> </p> <pre><code>SELECT * FROM MyTable WHERE DateTimeCol = STR_TO_DATE(?, '%m/%d/%y') </code></pre> <p>You can submit a wide variety of string representations of date/time, if you specify the formatting to MySQL's <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_str-to-date" rel="nofollow"><code>STR_TO_DATE()</code></a> function. For the formatting codes, see the <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format" rel="nofollow"><code>DATE_FORMAT()</code></a> function.</p>
PHP to ASP.NET - call_user_func() equivalent? <p>I'm wondering if there is an equivalent function to PHP's <code>call_user_func()</code> in ASP.NET application. I'm looking to do a conversion from a PHP application to ASP.NET as a means of teaching myself the language, by taking a CMS I built professionally and trying to recreate it in this other language.</p> <p>The reason I need a function similar to this, is because the current structure of my PHP CMS involves a plugin architecture, and specific parts of the CMS expose themselves for the plugins, and it then handles the returned information as an array. It's pretty much the same system Drupal uses.</p> <p>Am I perhaps on the wrong track with this?</p> <p>I think for clarification I should provide an example of how this works in my current system:</p> <pre><code>&lt;?php class Test { function TestMessage() { // set up array $arrTest = array("Hello", "World"); // get extra values from all available plugins $arrExtras = CMS::InvokeHook("HelloTest"); // now contains Hello, World, Foo, Bar $arrTests = array_merge($arrTest, $arrExtras); } } class CMS { InvokeHook($function) { // now contains a couple plugins $plugins = CMS::GetPlugins(); // empty array of values $values = array(); foreach($plugins as $plugin) { // if this plugin has the called method... if(method_exists($plugin, $function)) { // call the function and merge in the results $values[] = call_user_func(array($plugin, $function)); } } // return results as an array return $values; } } class FooTest { function HelloTest() { return "Foo"; } } class BarTest { function HelloTest() { return "Bar"; } } ?&gt; </code></pre> <p>NOTE: The InvokeHook() call is simplified as I'm writing this from memory, but that is the gist of it.</p>
<p>In .NET I would probably create some events and handle them. Here's one way of doing it:</p> <pre><code>public class CMS public Event DoSomethingHook(byval sender as Object, byval e as DoSomethingEventArgs) public function DoSomething() dim data() as Integer = {} Dim e as new DoSomethingEventArgs(); e.data = data RaiseEvent DoSomethingHook(Me, e) data = e.data end function end class ' Let's say Plugin base class contains a reference to CMS public class CMSPlugin Inherits Plugin public sub New() ' Register for a hook AddHandler CMS.DoSomethingHook, AddressOf DoSomething end sub public function DoSomething(byval sender as Object, byval e as DoSomethingEventArgs) ' Do something with e.data end function end class public class DoSomethingEventArgs : Inherits EventArgs public data() as Integer end class </code></pre>
Why is my mounted MacFUSE NTFS vol read-only? <p>I got the impression from the <a href="http://code.google.com/p/macfuse/" rel="nofollow">MacFUSE</a> site that when you install it and connect an NTFS volume it will be writable. However, the volume I mounted is read only. Here is some of the output of <code>mount</code>...</p> <p>The NTFS external USB drive I'm talking about:</p> <pre><code>/dev/disk1s1 on /Volumes/SATA160 (local, nodev, nosuid, read-only) </code></pre> <p>An OS X format external USB drive (for comparison):</p> <pre><code>/dev/disk3s3 on /Volumes/USB_ext_drive_40_GB (local, nodev, nosuid, journaled) </code></pre> <p>Do I need to set something somewhere? Edit a config file?</p> <p>I'm on OS 10.4 (Tiger).</p>
<p>Did you also install the <a href="http://macntfs-3g.blogspot.com/" rel="nofollow">NTFS-3G</a> driver?</p>
Converting a development team from FTP to a Versioning System <p>I work at a small LAMP Development Studio where the idea has been to just get the code done and go on to the next item on the list.</p> <p>The team works in Zend Studio 5.5 connected to the Live server via FTP or SFTP. What they love about this is the speed of their deployment of code (since its just modifying live code).</p> <p>But of course this is not good due to many obvious reasons.</p> <p>I would like to move them to a Versioning System (CVS, SVN or any other tool) but the catch is, I am not their senior so I need a carrot for them to start using this.</p> <p>What kind of setup would I need to build on their machine so they can code along as usual?</p> <p>What I would do is create this setup on my machine and then show them. </p> <p>I know this is kinda unusual but it's turned into a passion of mine to change their way of thinking from the usual hacking of code to structure and elegance. Thanks.</p> <p>UPDATE (for Jonathan Leffler's answer):</p> <ol> <li>Yes</li> <li>No</li> <li>Yes, they really do</li> </ol> <p>Question also, the studio makes a centralized CMS system that is hosted on hundreds of sites, they need to modify individual sites, should the sites be in the main compository or within their own one?</p>
<p>Questions:</p> <ol> <li><p>Have you (they) never had a disaster where you (they) needed to revert to a previous version of the web site but couldn't because they'd broken it?</p></li> <li><p>Do they use a staging web server to test changes?</p></li> <li><p>Surely they don't modify the code in the production server without some testing somewhere?</p></li> </ol> <p>I suspect the answer to the first is "yes (they have had disasters)" and the second "no", and I hesitate to guess the answer for the third (but. from the sounds of it, the answer might be "yes, they really do"). If that's correct, I admire their bravado and am amazed that they never make a mistake. I'd never risk making changes direct on a live web site.</p> <p>I would recommend using a version control system or VCS (any VCS) yourself. Work out the wrinkles for the code you look after, and develop the slick distribution that makes it easy (probably still using SFTP) to distribute the VCS code to the web site. But also show that preserving the previous versions has its merits - because you can recover who did what when. To start with, you might find that you need to download the current version of whatever page (file) you need to work on and put that latest version into the VCS before you start modifying the page, because someone else may have modified it since it was last updated in your master repository. You might also want to do a daily 'scrape' of the files to get the current versions - and track changes. You wouldn't have the 'who', nor exactly 'when' (better than to the nearest day), nor the 'why', but you would have the (cumulative) 'what' of the changes.</p> <p><hr></p> <p>In answer to comments in the question, Ólafur Waage clarified that they've had disasters because of the lack of a VCS.</p> <p>That usually makes life much easier. They goofed; they couldn't undo the goof - they probably had annoyed customers, and they should have been incredibly annoyed with themselves. A VCS makes it much easier to recover from such mistakes. Obviously, for any given customized site, you need the (central) backup of the 'correct' or 'official' version of that site available in the VCS. I'd probably go for a single repository for all customers, using a VCS that has good support for branching and merging. That may be harder to deal with at first (while people are getting used to using a VCS), but probably leads to better results in the long term. I'd seriously consider using on of the modern distributed VCS (for example, <a href="http://git.kernel.org/" rel="nofollow">git</a>), though lots of people use SVN too (even though it is not a distributed VCS).</p>
The future direction of Help File formats <p>It would appear that CHM help files are no longer the help file format of choice.</p> <p>WinHelp<br /> - obsolete</p> <p>HtmlHelp (CHM)<br /> - not supported on Vista by default<br /> - does not work well on a network share</p> <p>Help 2 (HXS)<br /> - I understand this is used in VS2005+ for displaying help</p> <p>Web Based<br /> - Could be hard to manage for multiple versions</p> <p>What help file format would you use in a new (C#) application that provides multiple versions from the same codebase?</p> <p>We would like to use CHM help however it doesn't appear to be the direction that Microsoft wants us to move in. </p> <p>Does anyone employ HXS for their help files?</p> <p>Feeback appreciated</p> <p><hr /></p> <p>Update based upon lassevk comments;</p> <p>Looks as though HXS help is not intended to be used for normal help projects. </p> <p><hr /></p>
<p>What exactly makes you think there's no default .chm viewer on windows Vista ? (There certainly is one on my computer, as well as on my Win7 box)</p> <p>You might confuse .chm with .hlp (Microsoft indeed dropped .hlp support in vista, then eventually resumed it in a windows update)</p> <p>Bottom line : .chm files seem to be still supported on all windows version, and the only real alternative to .chm files i know of is .html</p>
CommandBars.FindControl throwing an exception <p>I am trying to use the FindControl Method of the CommandBars object in a VSTO Word addin to get <em>what else</em> a command bar object Code is as follows</p> <pre><code> private void WireContextMenu(string MenuID,string Tag, string ID, ref Office.CommandBarButton Control) { try { object missing = System.Type.Missing; Control = (Office.CommandBarButton)this.Application.CommandBars[MenuID].FindControl((object)Office.MsoControlType.msoControlButton, ID, Tag, missing, missing); if (Control == null) { Control = (Office.CommandBarButton)this.Application.CommandBars[MenuID].Controls.Add(Office.MsoControlType.msoControlButton, ID, missing, missing, missing); Control.Caption = "Biolit Markup Selection"; Control.Tag = Tag; } Control.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.cb_Click); } catch (Exception Ex) { } } </code></pre> <p>The FindControl method is throwing a Type Mismatch Exception (-2147352571) Any ideas is this the right way anyhow to add a item to the right click menu of word and then make sure you dont add it if it already exists Thanks </p>
<p>you are using Missing where Missing is not allowed as parameter ref: <a href="http://msdn.microsoft.com/en-us/library/system.type.missing.aspx" rel="nofollow">link text</a> <a href="http://msdn.microsoft.com/en-us/library/system.type.missing.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.type.missing.aspx</a></p> <p>use code like this:</p> <pre><code> object type = MsoControlType.msoControlPopup; object id = 1; object tag = null; object visible = 1; object recusive = false; //object missing = System.Type.Missing; CommandBarControl barControl = popParent.FindControl(type, id, tag, visible, recusive); </code></pre>
Unicode Regex; Invalid XML characters <p>The list of valid XML characters is well known, as defined by the spec it's:</p> <pre><code>#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] </code></pre> <p>My question is whether or not it's possible to make a PCRE regular expression for this (or its inverse) without actually hard-coding the codepoints, by using Unicode general categories. An inverse might be something like [\p{Cc}\p{Cs}\p{Cn}], except that improperly covers linefeeds and tabs and misses some other invalid characters.</p>
<p>I know this isn't exactly an answer to your question, but it's helpful to have it here:</p> <p>Regular Expression to match <strong>valid</strong> XML Characters:</p> <pre><code>[\u0009\u000a\u000d\u0020-\uD7FF\uE000-\uFFFD] </code></pre> <p>So to remove <strong>invalid</strong> chars from XML, you'd do something like</p> <pre><code>// filters control characters but allows only properly-formed surrogate sequences private static Regex _invalidXMLChars = new Regex( @"(?&lt;![\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\uFEFF\uFFFE\uFFFF]", RegexOptions.Compiled); /// &lt;summary&gt; /// removes any unusual unicode characters that can't be encoded into XML /// &lt;/summary&gt; public static string RemoveInvalidXMLChars(string text) { if (string.IsNullOrEmpty(text)) return ""; return _invalidXMLChars.Replace(text, ""); } </code></pre> <p>I had our resident regex / XML genius, <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">he of the 4,400+ upvoted post</a>, check this, and he signed off on it.</p>
Frame position in JavaScript <p>I am having a frame-based webpage with 3 frames. A topliner, a navigation on the left side and a content frame on the bottom right side.</p> <p>Now, I want to show up a popup-menu when the user right-clicks on the content-frame. Because a div-container can not go out of the frame, my idea was, placing the whole frame-page into a new iframe. In that page I could have a second iframe which is my popup-menu.</p> <p>So now, I am having this layout:</p> <pre><code>&lt;html&gt; (start-page) &lt;iframe (real content) &lt;frameset top-frame navigation-frame content-frame &gt; &gt; &lt;iframe&gt; (my popup-menu, positioned absolutelly and hidden by default) &lt;/html&gt; </code></pre> <p>In my content-frame I am having a "onmouseover"-event assigned to the body-tag. This event should open the popup-iframe at the current mouse-position. And exactly here is my problem: How to get the mouse-coordinates relativelly to the top-website (start-page in my draft)?</p> <p>Currently I am having this mouseDown-function (works in IE only, right now - but getting it working in FF &amp; Co shouldn't be the problem...)</p> <pre><code>function mouseDown(e) { if (window.event.button === 2 || window.event.which === 3) { top.popupFrame.style.left = event.screenX + "px"; top.popupFrame.style.top = event.screenY + "px"; top.popupFrame.style.display = ""; return false; } } </code></pre> <p>As you can see, the "event.screenX" and "screenY" - variables are not that variables I can use, because they are not relative to the mainpage.</p> <p>Any ideas?</p>
<p>You say it's an enterprise application - do you have to support all major browser, or is IE enough?</p> <p>I'm asking this because IE has a function that works exactly like you need:</p> <pre><code>window.createPopup(...) </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms536392" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms536392</a>(VS.85).aspx</p> <p>The pop-up will be visible even outside the browser window! :-)</p> <p>To show it, use the .show(...) method which accepts position and size arguments (refer to MSDN for details). The nice thing is, you can also pass a reference to a page element relative to which the position is relative to, so you can easily position the popup relative to a certain page element, certain frame, certain browser window or even relatively to the desktop.</p>
How do firefox extensions make use of the whole screen in 3D (eg. CoolIris)? <p>I understand that <a href="http://www.mozilla.com/en-US/" rel="nofollow">Firefox</a> addins can be created in Javascript and Chrome.</p> <p>How do they run advanced graphics applications such as <a href="http://www.cooliris.com/" rel="nofollow">CoolIris</a> ?</p> <p><img src="http://www.cooliris.com/static/images/product/slider1.png" alt="alt text" /></p>
<p>Cooliris uses native compiled code utilizing graphics acceleration on the platforms it supports.</p> <p>You can get a full screen GUI if you use Flash, but the user is informed about it (try watching a YouTube vid in fullscreen) and also the user can't do everything they can otherwise, like type using the keyboard.</p>
Database design question <p>I accumulated a quite a lot of data in a raw form (csv and binary) - 4GB per day for a few months to be precise.</p> <p>I decided to join the civilized world and use database to access the data and I wondered what would be the correct layout; the format is quite simple: a few rows for every time tick (bid, ask, timestamp, etc.) x up to 0.5Million/day x hundreds of financial instruments x monthes of data.</p> <p>There is a MySQL server with MYISAM (which I understood would be the correct engine for this type of usage) running on commodity harware (2 x 1GB RAID 0 SATA, core 2 @ 2.7GHz)</p> <p><strong>What would be correct layout of the database? How should the tables/indices look like? What are the general recommendations with this scenario? What would you predict set me pitfalls along the way?</strong></p> <p>Edit: my common usage will be simple queries to extract time series information for a specific date and instruments, e.g.</p> <pre><code>SELECT (ask + bid) / 2 WHERE instrument='GOOG' AND date = '01-06-2008' ORDER BY timeStamp; </code></pre> <p>Edit: I tried to stuff all my data in one table indexed by the timeStamp but it was way too slow - therefore I reckoned it would take a more elaborate scheme.</p>
<p>You don't really say what your background is and how much you know about programming and <a href="http://en.wikipedia.org/wiki/Database_design" rel="nofollow">database design</a>. It sounds like you should do some reading. Conceptually though your design is fairly simple. Your description identifies a mere two entities:</p> <ul> <li>Financial instrument; and</li> <li>Quote.</li> </ul> <p>So you need to then identify the attributes.</p> <p>Financial instrument:</p> <ul> <li>Security code;</li> <li>Market;</li> <li>etc.</li> </ul> <p>Quote:</p> <ul> <li>Timestamp;</li> <li>Financial instrument;</li> <li>Bid price; and</li> <li>Ask price.</li> </ul> <p>The reference to the financial instrument is what's called a <a href="http://en.wikipedia.org/wiki/Foreign_key" rel="nofollow">foreign key</a>. Each table also needs a <a href="http://databases.about.com/cs/administration/g/primarykey.htm" rel="nofollow">primary key</a>, probably just an auto-increment field.</p> <p>Conceptually fairly simple.</p> <pre><code>CREATE TABLE instrument ( id BIGINT NOT NULL AUTO_INCREMENT, code CHAR(4), company_name VARCHAR(100), PRIMARY KEY (id) ); CREATE TABLE quote ( id BIGINT NOT NULL AUTO_INCREMENT, intrument_id BIGINT NOT NULL, dt DATETIME NOT NULL, bid NUMERIC(8,3), ask NUMERIC(8,3), PRIMARY KEY (id) ) CREATE INDEX instrument_idx1 ON instrument (code); CREATE INDEX quote_idx1 ON quote (instrument_id, dt); SELECT (bid + ask) / 2 FROM instrument i JOIN quote q ON i.id = q.instrument_id WHERE i.code = 'GOOG' AND q.dt &gt;= '01-06-2008' AND q.dt &lt; '02-06-2008' </code></pre> <p>If your dataset is sufficiently large you might want to include (bid + ask) / 2 in the table so you don't have to calculate on the fly.</p> <p>Ok, so that's the normalized view. After this you may need to start making performance optimizations. Consider this question about <a href="http://stackoverflow.com/questions/365380/large-primary-key-1-billion-rows-mysql-innodb">storing billions of rows in MySQL</a>. Partitioning is a feature of MySQL 5.1+ (fairly new).</p> <p>But another question to ask yourself is this: do you need to store all this data? The reason I ask this is that I used to be working in online broking and we only stored all the trades for a very limited window and trades would be a smaller set of data than quotes, which you seem to want.</p> <p>Storing billions of rows of data is a serious problem and one you really need serious help to solve.</p>
Can any one provide me a sample of using CreateHatchBrush <p>I want to draw a shadow around a thumbnail in my software. It seems CreateHatchBrush can help but I do not know how to use it, can anyone provide me a sample in C++? Many thanks!</p>
<p>I don't have a sample, but some hints on general usage of brushes in Windows.</p> <p><code>CreateHatchBrush()</code> returns a handle. You need to use that handle to make that brush the current brush in the Device Context you are using to render. Call the Device Context's <code>SetObject</code> function (plain Windows GDI calls version):</p> <pre><code>HDC myDC = GetDC (hWnd); //pass your window handle here or NULL for the entire screen HBRUSH hatchBrush = CreateHatchBrush (HS_DIAGCROSS, RGB (255,128,0)); HBRUSH oldBrush = SelectObject (myDC, hatchBrush); //draw something here SelectObject (myDC, oldBrush); //restore previous brush ReleaseDC (myDC); </code></pre>
Using FTP with NSURL <p>I want to write a cocoa application which downloads a file using ftp. I read about the NSURL class which has "NSURLHandle FTP Property Keys". I want to know how do I make use of these constants to provide username and password to the ftp site.</p>
<p>NSURLHandle is deprecated and has been for a while. Please use NSURLConnection or NSURLDownload instead. Either create one of these objects with a URL like this:</p> <p>ftp://user:password@ftp.example.com/foo/bar.zip</p> <p>Or, implement the authentication delegate method and pass in a standard URL:</p> <p>ftp://ftp.example.com/foo/bar.zip</p> <p>If you need to do anything more complicated than downloading a file, I suggest you look at <a href="http://opensource.utr-software.com/connection/download.html">ConnectionKit</a> which provides full FTP connection support.</p>
How can one add an XML file in classpath at runtime in java? <p>I am not sure if a URLClassLoader can be used. Also, only the relative path of the XML is known.</p> <p>Thank You.</p>
<p>If you just mean read in an XML file that is already on the classpath, so that you can parse it using whatever library you prefer, the most compact way is using a <code>ClassLoader</code>:</p> <pre><code>InputStream is = ClassLoader.getResourceAsStream(); // use the input stream however you want is.close() </code></pre> <p>See <a href="http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html" rel="nofollow">http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html</a></p>
How to design interface for a game in Java <p>We're a team of a designer and a programmer. Me, the programmer, is hopeless on design of all sorts, so the user interface of the game must be created by the designer. We were thinking of a main screen, where the character walks around, a small minimap in the top, an inventory section, etc.</p> <p>All these things would have to be designed in a way that looks pretty, i.e nice graphics/buttons/colors etc. I'm assuming that the designer will create an outline of this interface in photoshop/illustrator, then send me the file in .png or .jpeg format and I'll implement it into the program, making sure the buttons all work, etc.</p> <p>My question is, is this the correct method for doing this? Should he send me the interface's layout in a .png/.jpeg format, or send me only the buttons and I have to code the rest of the interface manually in java, putting the buttons/icons where they need to be, etc. If so, how can I do this? Any classes/frameworks that do this?</p> <p>Any guidelines at all will be helpful. Thanks!</p>
<p>take a look at this:</p> <p><a href="http://www.cs.qub.ac.uk/~P.Hanna/CSC207/lectures/lectures.htm" rel="nofollow">http://www.cs.qub.ac.uk/~P.Hanna/CSC207/lectures/lectures.htm</a></p>
C#: What does the [string] indexer of Dictionary return? <p>What does the <code>[string]</code> indexer of <code>Dictionary</code> return when the key doesn't exist in the Dictionary? I am new to C# and I can't seem to find a reference as good as the Javadocs.</p> <p>Do I get <code>null</code>, or do I get an exception?</p>
<p>If you mean the indexer of a <code>Dictionary&lt;string,SomeType&gt;</code>, then you should see an exception (<code>KeyNotFoundException</code>). If you don't want it to error:</p> <pre><code>SomeType value; if(dict.TryGetValue(key, out value)) { // key existed; value is set } else { // key not found; value is default(SomeType) } </code></pre>
What is the best method to find the newest last modified time of a folder of files? <p>I have a folder with subfolders of files. I would like to get the newest filename by modified time. Is there a more efficient way of finding this short of looping through each folder and file to find it? </p>
<p>depends on how you want to do it. do you want you software to start and then look for it or continuously run and keep track of it?</p> <p>in the last case its good to make use of the FileSystemWatcher class.</p>
incrementing array value with each button press? <p>I am building a calculator in C#. I am not sure what the best way is to have it increment a number in an array every time the button is pressed. Here is one of my current button event handler methods:</p> <pre><code> //Assign button '2' to 2 with array address of 1 private void num2_Click(object sender, EventArgs e) { numbers[1] = 2; lblUpdate(1); } </code></pre> <p>I would like it so every time this button is pressed, numbers[1] gets increased by 2. Right now, it just gets set to 2 no matter how many times the button is pressed.</p> <p>Thanks so much!</p>
<p>numbers[1] += 2;</p> <p>That should do the trick.</p>
Linking a Bundle Target to a Command-Line Target in Xcode <p>I have a project in Xcode that contains multiple targets. One of these builds a sync schema bundle, and another one builds a Foundation command-line tool that initiates a sync session using the schema defined in the bundle.</p> <p>The schema bundle template creates <code>Schema-strings.h</code> and <code>Schema-strings.m</code> files, which contain constants for data class names, entity names, and attribute names, and I'd like to use these constants in my command-line tool's code.</p> <p>How do I configure the targets to make this possible?</p>
<p>After stepping away from the computer for a while, I realized that one solution to this problem was to add <code>Schema-strings.m</code> to the "Compile Sources" phase of the command-line tool's target. But I'd still be interested in hearing about any other ways to get a similar result.</p>
SQL Selecting "Window" Around Particular Row <p>It's quite possible a question like this has been asked before, but I can't think of the terms to search for.</p> <p>I'm working on a photo gallery application, and want to display 9 thumbnails showing the context of the current photo being shown (in a 3x3 grid with the current photo in the centre, unless the current photo is in the first 4 photos being shown, in which case if e.g. if the current photo is the 2nd I want to select photos 1 through 9). For example, given an album containing the list of photos with ids:</p> <p>1, 5, 9, 12, 13, 18, 19, 20, 21, 22, 23, 25, 26</p> <p>If the current photo is 19, I want to also view:</p> <p>9, 12, 13, 18, 19, 20, 21, 22, 23</p> <p>If the current photo is 5, I want to also view:</p> <p>1, 5, 9, 12, 13, 18, 19, 20, 21</p> <p>I've been thinking of something along the lines of:</p> <pre><code>SELECT * FROM photos WHERE ABS(id - currentphoto) &lt; 5 ORDER BY id ASC LIMIT 25 </code></pre> <p>but this doesn't work in the case where the ids are non-sequential (as in the example above), or for the case where there are insufficient photos before the currentphoto.</p> <p>Any thoughts?</p> <p>Thanks,</p> <p>Dom</p> <p>p.s. Please leave a comment if anything is unclear, and I'll clarify the question. If anyone can think of a more useful title to help other people find this question in future, then please comment too.</p>
<p>Probably could just use a UNION, and then trim off the extra results in the procedural code that displays the results (as this will return 20 rows in the non-edge cases):</p> <pre><code>(SELECT * FROM photos WHERE ID &lt; #current_id# ORDER BY ID DESC LIMIT 10) UNION (SELECT * FROM photos WHERE ID &gt;= #current_id# ORDER BY ID ASC LIMIT 10) ORDER BY ID ASC </code></pre> <p>EDIT: Increased limit to 10 on both sides of the UNION, as suggested by <strong>le dorfier</strong>.</p> <p>EDIT 2: Modified to better reflect final implementation, as suggested by Dominic.</p>
How to modify page URL in Google Analytics <p>How can you modify the URL for the current page that gets passed to Google Analytics? </p> <p>(I need to strip the extensions from certain pages because for different cases a page can be requested with or without it and GA sees this as two different pages.) </p> <p>For example, if the page URL is <code>http://mysite/cake/ilikecake.html</code>, how can I pass to google analytics <code>http://mysite/cake/ilikecake</code> instead?</p> <p>I can strip the extension fine, I just can't figure out how to pass the URL I want to Google Analytics. I've tried this, but the stats in the Google Analytics console don't show any page views:</p> <blockquote> <p>pageTracker._trackPageview('cake/ilikecake');</p> </blockquote> <p>Thanks, Mike</p>
<p>You could edit the GA profile and add custom filters ...</p> <p>Create a 'Search and Replace' custom filter, setting the filter field to 'Request URI' and using something like:</p> <p>Search String: <code>(.*ilikecake\.)html$</code></p> <p>Replace String: <code>$1</code><br /> (was <code>\1</code>) </p>
Change Assembly Version in a compiled .NET assembly <p>Simple question... is there a way to change the Assembly Version of a compiled .NET assembly?</p> <p>I'd actually be fine with a way to change the Assembly File Version.</p>
<p>You can use <a href="http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx">ILMerge</a>:</p> <pre>ILMerge.exe Foo.dll /ver:1.2.3.4 /out:Foo2.dll</pre> <p>A valid reason to do this is to increment the assembly version in a build in you find breaking changes (using NDepend for example). That way if there are no breaking changes the assembly version stays the same, and you can patch released builds easily.</p> <p>We always increment the file version, and that reflects the build number. </p>
MSSQL 2005 Fulltext search setup <p>I'm beginning my foray into fulltext search for MSSQL2005. This is a new, in-dev database, so I can monkey around with it.</p> <p>Let's say I have a "Form" table that has a one-to-many relationship to two other tables, "Answer" and "Comment." I want the user to be able to enter one search term and have it peg all three of those tables via fulltext search. What's the best way? It appears as though I can create an <a href="http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx" rel="nofollow">indexed view</a> to speed things along.</p> <p>If I do use an indexed view (is this the best route anyway?), how do I handle the one-to-many relationships? Let's assume all I really want to figure out is the ID of the "Form" table that would contain any search results found in the child Answer/Comment tables, so I can show the entire form that contains the located entries. An inner join on the view would result in multiple "master" form rows being returned - doesn't sound great for performance. How about concatenating all child answer/comment rows into one "column" for the view? So instead of....</p> <pre><code>Form 1, Answer A, Comment A Form 1, Answer B, Comment A Form 1, Answer A, Comment B Form 1, Answer B, Comment B </code></pre> <p>...it'd be...</p> <pre><code>Form 1, Answer A Answer B, Comment A Comment B </code></pre> <p>Remember all I care about is the ID of that master "form" row.</p> <p>This seems logical to me, but I'm not sure the best practices around fulltext search yet, so just curious if I'm approaching it correctly.</p> <p><strong>UPDATE:</strong> Looks like indexed views are pretty strict; no left joins, no subqueries, so I might go down the path of a summary table populated by triggers if it isn't going to be too unwieldy.</p>
<p>In SQL you should use this rule of thumb: - start with the element you want to retrieve - add filters to limit the set of elements to retrieve</p> <p>that sounds like a no-brainer, but it's really all you have to do. Here, you want Form elements (rows), so you write:</p> <pre><code>SELECT ID FROM Form </code></pre> <p>and then you add the filters to limit the total set to the set of forms you're interested in. You do this by using IN predicates. As you say Answer and Comment have a 1:n relationship with Form, this means that Answer and Comment have an FK to Form.ID. So we can add the where:</p> <pre><code>WHERE ID IN (SELECT FormID FROM Answer WHERE CONTAINS(FullTextColumnInAnswer, @stringToSearch)) OR ID IN (SELECT FormID FROM Comment WHERE CONTAINS(FullTextColumnInComment, @stringToSearch)) </code></pre> <p>this will lead to a set of Form.ID values which are distinct and which are the IDs of forms which have at least 1 answer OR comment which contains the string to search in the field which is full-text-search enabled. </p> <p>On SqlServer 2000 this can be slower than on 2005, as you use multiple CONTAINS statements. </p> <p>You can also use CONTAINSTABLE() in join scenario's instead, see the BOL for examples, though I'd go for the IN clause setup first to get things working. </p>
What are the implications of using GPL django apps in a non-GPL django project? <p>If I was to integrate a third-party GPLv3,v2 or LGPL django app in my django project, would the licence apply to the complete project or just the third-party application I'm using?</p>
<p>GPLv2 isn't so viral on web apps, since you're not distributing. GPLv3 might be, there's some extra wording for this case.</p> <p>usually it's best to contact the developer. it's not uncommon that he changes licenses, or clarifies his intentions. most Django-related code is under MIT licenses, so it's not unreasonable to ask.</p> <p>and, if he specifically doesn't want to accomodate your case; then you shouldn't use that code, no matter what you think the legalese says.</p> <p>(AINAL)</p>
Crystal reports 11: How to handle or trim special characters <p>In my crystal report, I noticed one of the fields being pulled from a table has special characters. More specifically carriage returns and tabs. Is there a way to strip this out, so it doesn't show up blank in my reports?</p> <p>Thanks in advance.</p>
<p>This should do it:</p> <pre><code>stringvar output := {TABLE_NAME.FIELD_NAME}; output := Trim(output); //get rid of leading &amp; trailing spaces output := Replace(output,Chr(13),''); //get rid of line feed character output := Replace(output,Chr(10),''); //get rid of carriage return character //add any other special characters you want to strip out. </code></pre> <p>If you have a lot of characters to strip out, you can use this slightly fancier approach. Just add whatever characters you want to strip out to the in[]:</p> <pre><code>stringvar input := {DROPME.TEST_FIELD}; stringvar output := ''; numbervar i; input := Trim(input); for i := 1 to Length(input) Step 1 do if not(input[i] in [Chr(13),Chr(10)]) then output := output + input[i]; output </code></pre>
Application of [L]GPL to Java/C# code <p>How the [L]GPL license should be applied to Java and C# code ? I know that when Sun JDK become GPL, they did special exceptions for standard libraries. </p> <p>So, if I cannot open my application source and still want to distribute it ...</p> <ul> <li>... could I use GPL'ed library (by <strong>import</strong>'ing its classes)?</li> <li>... could I use LGPL'ed one</li> <li>... could my application run on top of GPL'ed Application Server (using its services and APIs) </li> </ul> <p>In all above questions GPL = GPL v.2.</p> <p>Thanks</p>
<p>Firstly, if you're building commercial software on top of someone else's work, you should hire a lawyer to help you ensure that you remain in compliance with the copyright holder's license and your specific usage.</p> <p>That said, here's my advice:</p> <ol> <li>You should not link to a GPL app or library unless you want to distribute your code as GPL.</li> <li>As far as LGPL goes, you may want to check with the copyright holder, but the Free Software Foundation has clarified its interpretation of the LGPL with respect to Java: <a href="http://www.fsf.org/licensing/licenses/lgpl-java.html" rel="nofollow">LGPL and Java by David Turner</a>.</li> <li>If you're extending a GPL framework (such as an app server), you'll need to follow the framework's license.</li> <li>If you're using something like SOAP to access a service, you should be OK under GPLv2. If you use RMI, then maybe the situation is different because the stubs that you would link to would probably be under GPL.</li> </ol> <p>Now, if you're concerned about the Java runtime, I don't think you'll need to worry. I'd be surprised if Sun made Java GPL-only. They have too many customers that depend on the fact that Java can be extended and used for building proprietary applications. Often software is released under multiple licenses which allows the user to choose the terms (Firefox, for example uses this approach and is triple-licensed: GPL, LGPL, and MPL).</p>
Task Schedule Refusal <p>Although some might not think of it as programming related, it certainly is. The task Scheduler is a program. It's launching a process that I have written. Stating that it's a common problem is not very helpful.</p> <p>I've set up my own backup procedures, both on a Windows xP machine at home, and on several at the office, where I use the task scheduler to start a backup file which does an xcopy of all files with a newer date than what's on the backup drive TO the backup drive.</p> <p>Trying to set this up for a friend, I can't get the task scheduler to run, even with his log-in password set up.</p> <p>He recently got rid of all his Norton anti-virus. . . Is there perhaps a connection?</p> <p>I also have my own Windows 2000 machine, from which I long ago removed Norton, and the task scheduler doesn't work there either. . . It's not that important there, since there's not much data volatility on that machine anymore.</p>
<p>Maybe a dumb question - but is his login an administrator on the box? I would set up a "service account" and give it administrator privileges and run the task under that account. There may be residual problems with anti-virus or firewall - depending on what he is using now he may have to explicitly authorize that program to run.</p> <p>Make sure that whatever account is used doesn't have to be logged on to run - though of course machine has to be on.</p>
Windows Disk Cloning vs Automatic installation of servers <p>During development , testing, and deployment, I have a need to fully automate a windows 2003 server setup.</p> <p>I'm trying to find the best way to automatically delpoy a server, which installs the OS, software dependencies that I have (for example SQL server, .net framework + my own application code).</p> <p>From what I've found , there are two approaches to this issue:</p> <ol> <li>Disk Cloning (also known as disk imaging). Using tools like Ghost, Acronis.</li> <li>Unattended installation of OS + SW. Using RIS (now called WDS), or <a href="http://unattended.sourceforge.net/" rel="nofollow">Unattended</a>, basically running an unattended installation of the OS and then an unattended installation of all software needed at first boot (using the various command line flags of windows installation managers like MSI,InstallSheld.</li> </ol> <p><strong>Unattended installation pros:</strong></p> <ul> <li>The advantage of having the entire installation &amp; configuration self documented in the scripts/configuration that create the unattended installation </li> <li>These scripts/configuration can sit in a revision control system.</li> <li>Using <a href="http://driverpacks.net/" rel="nofollow">DriverPacks</a> can give the flexibility to install on just about any hardware.</li> </ul> <p><strong>Unattended installation cons:</strong></p> <ul> <li>Take much longer to fully deploy.</li> <li>More work to accomplish than disk cloning where you just have to install , configue a server manually, and then clone it.</li> </ul> <p><strong>Disk Cloning pros:</strong></p> <ul> <li>Less work to create clones.</li> <li>Fast deployment.</li> </ul> <p><strong>Disk Cloning cons:</strong></p> <ul> <li>Very hard to keep track of configuration/installation changes that took place before cloning as none of it is scripted.</li> <li>The resulting deployment is not as "clean" as a scratch installation, requiring he use of SysPrep or the likes.</li> <li>Hardware / Driver issues might come up when restoring a disk clone to a new hardware.</li> </ul> <p>I know this is not strictly a programming question (although writing an unattended windows + S/W installation does require some coding), but it is something we all have to do from time to time and we might as well come up with the best possible way to do this.</p> <p>Edit : More info on the situation: Virtualization is a nice option for development, but for testing and especially stress testing, real hardware ,with fast disks will have to be used.</p> <p>The need is to develop a Windows Server 2003 &amp; SQL Server 2005 server appliance &amp; an in house application. So this will be deployed in house for development &amp; testing and eventually be sold to customers.</p> <p>So basically what I'm asking is: What is the recommended way to install development,testing and production servers? Disk Cloning ? Automatic installation? A combination of both?</p>
<p>I don't know if it is an option in your case, but another thing to seriously consider is Virtualization.</p> <p>Virtualization basically has all the benefits of disk cloning, but you don't have the hardware / driver issues.</p> <p>If you take snapshots at the right points in time on your base VM you will be able to revert to any point in time along the installation of your base image.</p> <p>The cost of course, is that the Virtualization costs you a little performance.</p>
Split by \b when your regex engine doesn't support it <p>How can I split by word boundary in a regex engine that doesn't support it?</p> <p>python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation.</p> <p>example input:</p> <pre><code>"hello, foo" </code></pre> <p>expected output:</p> <pre><code>['hello', ', ', 'foo'] </code></pre> <p>actual python output:</p> <pre><code>&gt;&gt;&gt; re.compile(r'\b').split('hello, foo') ['hello, foo'] </code></pre>
<p>(\W+) can give you the expected output:</p> <pre><code>&gt;&gt;&gt; re.compile(r'(\W+)').split('hello, foo') ['hello', ', ', 'foo'] </code></pre>
Why would you use a ".pfx" file in .NET <p>What is the ".pfx" extension used for in .NET?</p> <p><br /></p> <p>Why does it ask for a password when the solution is being built?</p>
<p>A file containing an encrypted private key. It's probably being used for code signing the application (so the user knows who created the program and hence if they can trust it).</p> <p>You can probably see it being used by right-clicking on the project, getting Properties, then looking at the Signing tab.</p>
Data Access Library Return DataSet or Object <p>Is there a general consensus out there for when working with library's that call stored procedures? Return datasets or use sqldatareader to populate custom objects?</p> <p>Is the cost of serialization your Data Transport Object less then a DataSet?</p>
<p>Personally, I use a SqlDataAdapter with DataTables. DataTables have <em>WAY</em> less overhead than DataSets. My entity objects only contain business rules, they aren't used to transport data across tiers.</p>
What's the difference between using jQuery's onclick and the onclick attribute? <p>What's the difference between the following two pieces of HTML (apologies if there are any typos as I'm typing this freehand)?</p> <p>Using jQuery:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { $("#clickme").click(function() { alert("clicked!"); }); }); &lt;/script&gt; &lt;a id="clickme" href="javascript:void(0);"&gt;click me&lt;/a&gt; </code></pre> <p>Not using jQuery:</p> <pre><code>&lt;a id="clickme" href="javascript:void(0);" onclick="alert('clicked!');"&gt;click me&lt;/a&gt; </code></pre>
<p>One big difference is that jQuery's events are handled in a registry which is parsed on the click event. Crucially, this means that you are permitted to assign multiple callbacks, and have them triggered in the order in which they were registered:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { $("#clickme").click(function() { alert("clicked!"); }); $("#clickme").click(function() { alert("I concur, clicked!"); }); }); &lt;/script&gt; </code></pre> <p>They will both be invoked on the <code>click</code> event, in that order. The "real" <code>onClick</code> event is overridden by jQuery's registry-driven system. In the vanilla document structure, without a system like jQuery in place, there can only be one <code>onClick</code> event.</p>
Keyboard hook w/ C# and WPF for minimized system tray application <p>I have a WPF application that I minimize to the system tray through this.Hide() and System.Windows.Forms.NotifyIcon. When it's minimized, I want to have a keyboard hook maximize the application. How do I register a keyboard hook like Windows-Button &amp; T, for example.</p> <p>Thanks.</p>
<p>If you don't mind Win32 API calls, I'd say your best bet is to call <a href="http://msdn.microsoft.com/en-us/library/ms646309%28VS.85%29.aspx" rel="nofollow">RegisterHotKey</a>. You pass it the modifier and key to catch, then a <code>WM_HOTKEY</code> is sent to the HWND that you passed in originally.</p>
productivity superstar frameworks/tools for side gigs <p>If you were going to start building web sites as a consulting business on the side -- keeping your day job -- and you also had a toddler and a wife, what frameworks/tools would you pick to save you typing? </p> <p>Any language. </p> <p>I'm looking for a productivity superstar stack that won't tie my hands too much when I have to update the site 6 months later, or "evolve" the data model once in production.</p> <p>It needs to allow me to say "yes" to the client: community features, CMS, security, moderation, AJAX, ...</p>
<p>I would suggest Django. Super simple to get something up and running really quick. You are using Python which has a large library to go with it. For me Ruby on Rails would be a close second.</p>
How to install JScience library in Eclipse? <p>Or just any library, in general? I downloaded the bin.zip file, but I can't seem to do much with it? This is driving me up the wall...</p> <p>EDIT: In other words, there is no "standard" way to do it? I know how to add the Jar files, is it ok to just put them (and the docs) anywhere?</p>
<p>Shouldn't be much harder than putting the JARs into your project build path.</p> <p>Unzip the archive and put the JARs where Eclipse can find them.</p>
How to flush all caches in process for EntLib Caching <p>I'd like to know if there is a way to tell the Enterprise Library Caching objects to flush all configured caches for that process to flush.</p> <p>Even enumerating through all of the configured caches for that process, and manually flushing each one, is ok, but is there an API method from EntLib.Caching that will give me those values?</p> <p>Or do I need to enum through the config file myself?</p>
<p>How about this:</p> <pre><code>CacheManagerSettings conf = (CacheManagerSettings)ConfigurationSourceFactory.Create() .GetSection(CacheManagerSettings.SectionName); conf.CacheManagers.ForEach(delegate(CacheManagerDataBase cache) { CacheFactory.GetCacheManager(cache.Name).Flush(); }); </code></pre>
How can I obtain the dimensions of a Flash video file from PHP code? <p>I have an application where users can upload video files of any size, and I'd like to be able to determine the the height/width of a Flash video file (flv or f4v) from a PHP script so that I can size the player appropriately. I'd love a pure PHP solution, but I'd be open to shelling out to a command line tool and parsing the output (if such a tool exists).</p> <p>Thanks in advance!</p>
<p><a href="http://www.ffmpeg.org/">ffmpeg</a> is probably your best bet, there is even a <a href="http://ffmpeg-php.sourceforge.net/">php module</a> of it.</p> <p>ffmpeg -i "FileName"</p> <p>Alternativly you could read the information from the flv file directly by opening the file and reading the meta information.</p>
HTMl Helpers in MVC: How do I render html tags with helper such as ActionLink? <p>When using ActionLink to render data from database which has HTML tags </p> <pre><code>(ie &lt;p&gt;) </code></pre> <p>incorporated in it, ActionLink escapes the tags. What is the best way to handle this? </p>
<p>I don't know that you can turn off the XSS protection in the helper methods, but you can always build your own helper methods. Just make an extension method that hangs off the Html class. </p> <p>If you just want to render some HTML from the database, you can use &lt;%= ViewData["MyContent"] %> if you're controller loads the data into the MyContent view data. Just know that you have to clean this HTML yourself.</p>
Calculating the semantic distance between words <p>Does anyone know of a good way to calculate the "semantic distance" between two words?</p> <p>Immediately an algorithm that counts the steps between words in a thesaurus springs to mind.</p> <hr> <p>OK, looks like a similar question has already been answered: <a href="http://stackoverflow.com/questions/62328/">Is there an algorithm that tells the semantic similarity of two phrases</a>.</p>
<p>The thesaurus idea has some merit. One idea would be to create a graph based on a thesaurus with the nodes being the words and an edge indicating that there they are listed as synonyms in the thesaurus. You could then use a shortest path algorithm to give you the distance between the nodes as a measure of their similarity.</p> <p>One difficulty here is that some words have different meanings in different contexts. Your algorithm may need to take this into account and use directed links with the weight of the outgoing link dependent on the incoming link being followed (or ignore some outgoing links based on the incoming link).</p>
Going where PHP parse_url() doesn't - Parsing only the domain <p>PHP's parse_url() has a host field, which includes the full host. I'm looking for the most reliable (and least costly) way to only return the domain and TLD.</p> <p>Given the examples:</p> <ul> <li><a href="http://www.google.com/foo">http://www.google.com/foo</a>, parse_url() returns www.google.com for host</li> <li><a href="http://www.google.co.uk/foo">http://www.google.co.uk/foo</a>, parse_url() returns www.google.co.uk for host</li> </ul> <p>I am looking for only <strong>google.com</strong> or <strong>google.co.uk</strong>. I have contemplated a table of valid TLD's/suffixes and only allowing those and one word. Would you do it any other way? Does anyone know of a pre-canned valid REGEX for this sort of thing?</p>
<p>How about something like that?</p> <pre><code>function getDomain($url) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if (preg_match('/(?P&lt;domain&gt;[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } return false; } </code></pre> <p>Will extract the domain name using the classic <code>parse_url</code> and then look for a valid domain without any subdomain (www being a subdomain). Won't work on things like 'localhost'. Will return false if it didn't match anything.</p> <p><strong>// Edit:</strong></p> <p>Try it out with:</p> <pre><code>echo getDomain('http://www.google.com/test.html') . '&lt;br/&gt;'; echo getDomain('https://news.google.co.uk/?id=12345') . '&lt;br/&gt;'; echo getDomain('http://my.subdomain.google.com/directory1/page.php?id=abc') . '&lt;br/&gt;'; echo getDomain('https://testing.multiple.subdomain.google.co.uk/') . '&lt;br/&gt;'; echo getDomain('http://nothingelsethan.com') . '&lt;br/&gt;'; </code></pre> <p>And it should return:</p> <pre><code>google.com google.co.uk google.com google.co.uk nothingelsethan.com </code></pre> <p>Of course, it won't return anything if it doesn't get through <a href="http://php.net/parse_url"><code>parse_url</code></a>, so make sure it's a well-formed URL.</p> <p><strong>// Addendum:</strong></p> <p>Alnitak is right. The solution presented above will work in <strong>most</strong> cases but not necessarily all and needs to be maintained to make sure, for example, that their aren't new TLD with .morethan6characters and so on. The only reliable way of extracting the domain is to use a maintained list such as <a href="http://publicsuffix.org/">http://publicsuffix.org/</a>. It's more painful at first but easier and more robust on the long-term. You need to make sure you understand the pros and cons of each method and how it fits with your project.</p>
Why doesn't a Dictionary access nonexistent keys like a Hashtable does? <p>If I'm using a <code>Hashtable</code>, I can write code like this:</p> <pre><code>object item = hashtable[key] ?? default_value; </code></pre> <p>That works whether or not <code>key</code> appears in the <code>Hashtable</code>.</p> <p>I can't do that with a <code>Dictionary&lt;TKey. TValue&gt;</code>. If the key's not present in the dictionary, that will throw a <code>KeyNotFoundException</code>. So I have to write code like this:</p> <pre><code>MyClass item; if (!(dict.TryGetValue(key, out item)) { item = default_value; } </code></pre> <p>I'm wondering why this is. <code>Dictionary&lt;TKey, TValue&gt;</code> is just a wrapper around <code>Hashtable</code>. Why has this restriction been added to it?</p> <p><strong>Edit:</strong></p> <p>For another perspective on PopCatalin's answer (see below), the code I'd written above won't work if the dictionary's values are of a value type. If I'm using a <code>Dictionary&lt;int, int&gt;</code>, then the code I would <em>like</em> to use looks like this:</p> <pre><code>int i = dict[key] ?? default_value; </code></pre> <p>And that won't compile, because <code>dict[key]</code> isn't a nullable or reference type.</p>
<p>The difference between a <code>Dictionary&lt;T&gt;</code> and a <code>Hashtable</code> is that a <code>Dictionary&lt;T&gt;</code> is a generic type that can specialize to store value types along reference types.</p> <p>The hashtable can only store reference types (a <code>Object</code> passed by reference) and only value types that are boxed (also passed by reference).</p> <p>When a dictionary is specialized with value types, it must return those values 'by value' not by reference.So, therefore, a <code>Dictionary&lt;T&gt;</code> can't return null, as null is <strong>not a valid value</strong> for value types.</p>
Is it possible to get the raw param string in rails? <p>Given the following url: </p> <pre><code>http://foo.com?bar=1&amp;wee=2 </code></pre> <p>What is the quickest way to get the raw param part of the url from an action? </p> <p>i.e.</p> <pre><code>?bar=1&amp;wee=2 </code></pre>
<p>Sure, just use request.query_string from within your controller</p>
WPF Default Credential <p>I am trying to access .net 2.0 Web Service from WPF. I generated the proxy using Visual Studio and also Credential of the proxy to Default Credentials. </p> <p>I am getting 401 Unauthorized while accessing the web service. When I output the user name from the default credential it is empty, Am I missing anything?</p>
<p>found solution to my problem, </p> <p>{proxy}.UseDefaultCredentials = true; It works after setting this flag to true</p>
<label> on checkboxes: is there a reason why more websites don't use it? <p>I always try to do the following:</p> <pre><code>&lt;label&gt;&lt;input type="checkbox" /&gt; Some text&lt;/label&gt; </code></pre> <p>or</p> <pre><code>&lt;label for="idOfField"&gt;&lt;input type="checkbox" id="idOfField" /&gt; Some text&lt;/label&gt; </code></pre> <p>My question is related to the label tag, specifically on a checkbox.</p> <p>Most websites (I would say >40%) don't use the <code>&lt;label&gt;</code> tag.</p> <p>Is there a reason for this? Is there a problem in a browser or some other issue?</p> <p><strong>Note:</strong> Incase people don't know about the <code>&lt;label&gt;</code> tag, it has a number of advantages:</p> <ul> <li>checkboxes &amp; radios: you can click on the text as well as the checkbox to check the checkbox (as well as focus I believe): Blah blah blah</li> <li>other inputs: if you click the text, it will focus the input (textarea, text, file) (this functionality isn't as useful as checkboxes &amp; radios)</li> </ul> <p><strong>Note 2:</strong> Some people have mentioned that example #2 is more correct than #1 (above), but according to the documentation <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.9.1">here</a>, either is correct</p>
<p>I think it's probably more a factor that people don't know about the &lt;label&gt; tag. I didn't, until this post.</p>
How to make an embedded video not autoplay <p>I'm embedding a Flash video into an HTML and would like the user to have to click it to begin playing. According to the <a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701">Adobe <code>&lt;object&gt;</code> / <code>&lt;embed&gt;</code> element documentation</a>, there are variety of methods to do this:</p> <p>1) Add a Flash parameter inside the <code>&lt;object&gt;</code> tag:</p> <pre><code>&lt;param name="play" value="false"&gt; </code></pre> <p>2) Add the attribute <code>play</code> inside the <code>&lt;embed&gt;</code> tag:</p> <pre><code>&lt;embed ... play="false"&gt; </code></pre> <p>3) Add the attribute <code>flashvars</code> inside the <code>&lt;embed&gt;</code> tag:</p> <pre><code>&lt;embed ... flashvars="play=false"&gt; </code></pre> <p>Which is awesome. Only ... none of them work for me:</p> <p><a href="http://johnboxall.github.com/test/flash/flash.htm">http://johnboxall.github.com/test/flash/flash.htm</a></p> <p>My code looks like this now:</p> <pre><code>&lt;object width="590" height="475"&gt; &lt;param name="movie" value="untitled_skin.swf"&gt; &lt;param name="play" value="false"&gt; &lt;embed src="untitled_skin.swf" width="590" height="475" type="application/x-shockwave-flash" play="false" flashvars="autoplay=false&amp;play=false" menu="false"&gt;&lt;/embed&gt; &lt;/object&gt; </code></pre> <p>Anyone have any ideas? What am I doing wrong?</p>
<p>A couple of wires are crossed here. The various <code>autoplay</code> settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.</p> <p>However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.</p> <p>Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)</p>
Development tactics : phoenix development cycles <p>I was wondering how you guys actually develop large applications when you are your own boss. For myself I have been learning the hard way the necessity for patience and hope. I have been working on implementing an application (in the form of a series of scripts linked to a database) that clusters wikipedia articles using a combination of knowledge of wikilinks and article text/content. I have been at it for two years now; no results yet.</p> <p>I cant seem to get any results for I am continuously reengineering my scipts and db due to changes in either the essence (pseudo-pseudo code, the theoretical algorithm) or form (script, threads, db tables, the practical algorithm) of the algorithm. Basically, I find myself continuously learning from the mistakes I discover while implementing; the devil being in the details, so are the answers it seems. </p> <p>Anyway, every time I reengineer a script or a table or something, I need to scrap all my documentation and script. I am now able to do this without fear, but it has made me hate programming (I hate the details). </p> <p>I feel that reengineering is the way to go since I am thinking long-term and I wish to learn fast, but I am wondering if you guys have a similar programming experience or if you never really need or choose to have a better script come out of the death of the last one (like a phoenix). </p> <p>The hardest part for me is scraping my documentation for I spend more time documenting than coding; I use documentation as a means to discuss issues and consider solutions; I use it to formulate implementable solutions. While if it would be but for me, I would not mind scraping it, yet I always write it as if it were to be published the next week for while developing a script, I also seek to develop myself; I also try, like those of you who participate to this website, to share my knowledge or wisdom with others.</p> <p>Anyways, I have been developing at full speed these last 2 months, reengineering countless essays, scripts, tables, etc; my patience is running low for I seek results. </p> <p>Any tactics, any help, any experiences or anecdotes you wish to share?</p> <p>Thanks for your consideration!</p>
<p>keep a development log; this is the place to discuss details with yourself, work things out on paper, sketch documentation, make notes about current and future issues, remind yourself what you've tried and what you have left to try, and so on. It's also a good idea to always note what the 'next thing to do' is, so you don't waste time remembering/reviewing when you have time to work on it. Date each entry.</p> <p>i have used this approach on a number of long-running, sometimes frustrating, one-man projects of durations varying from a few months to several years, and it helps keep me focused and it helps keep me from trying something more than once.</p> <p>It also eliminated the internal pressure to document everything, which might be of great benefit to you.</p> <p>think of it this way: notes to yourself about what you've done are useful to you, but detailed documentation intended for third parties for code that gets scrapped is a <em>waste of your time</em>.</p> <p>Maybe this will help your OCD documentation neurons to shut up so you can solve the problem completely, <em>then</em> document the working solution - instead of continually re-documenting the latest <em>prototype</em>.</p>
Google Map Overlay Icon disappears at certain zoom level <p>I notice that Firefox 3 demonstrates this problem. I put down an overlay icon and play around with the map zoom. At certain zoom level, I found that the icon disappears for some unknown reason. </p> <p>Zooming out brings back the icon. Or during the disappearance, I click on the Google Map and it will somehow trigger to bring back the icon.</p> <p>I suspect it has something to do with the event triggering. Internet Explorer doesn't demonstrate the same problem though.</p> <p>Any advice? Like how to trigger update event on Firefox?</p>
<p>Try using <code>optimized: false</code> when creating the marker.</p>
rails model attributes without corresponding column in db <p>I have some rails models which don't need any persistence, however I'd like rails to think the model actually has attributes x, y, z so when calling methods like to_json in the controller I get them included for free.</p> <p>For example,</p> <pre><code>class ModelWithoutTableColumns &lt;&lt; ActiveRecord::Base def x return "Custom stuff here" end </code></pre> <p>There is no column x in the database for Table "ModelWithoutTable" (sorry for the slightly confusing name!)</p> <p>Anyone have an idea how to tackle this one?</p>
<p>Just don't inherit from ActiveRecord::Base</p> <p>Edit: Have you tried passing options to to_json, like :methods perhaps? See <a href="http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001637" rel="nofollow">here</a></p>
Making JavaFX compile to Java 1.6 level source code <p>How do I make JavaFX with netbeans compile my code to 1.6 level compliance.</p> <p>At the moment it seems to be hard coded to 1.5 levels - stopping me from using useful tools in java.awt.Desktop (and the like)</p>
<p>Remember - because JavaFX must run on the Apple Java run-time which currently is Java 1.5 - JavaFX can't compile to Java 1.6.</p> <p>Thus it likely will change in the future so that it can compile to Java 1.6.</p>
iPhone Development - Complex application using multiple views/xib/nib <p>I'm new to iPhone development, and multiple views (xib or nib) are really confusing me. This is what i'm trying to achieve...</p> <ol> <li>View with Tab Bar (Tab 1, Tab 2, Tab 3)</li> <li>Tab 2 View (Navigation Controller) 2.1 Selecting Table Row will show a View with cell details 2.2 Add button on the navigation bar will show a series of view interfaces to get different type of information (e.g. Location Information, Personal Information, etc) - Need this to be sequential, can't use control segment for this. Once information is successfully gathered, create a new cell in Tab 2 View Table, Save related information to a custom structure, and show a completion page with 2 options (Add another, View added item - readonly view)</li> </ol> <p>I'm confused about how to handle these multiple views (both linking them together, and communicating information back and forth). Will all these be handled by my application delegate class or i can/should use multiple delegate classes? Either way can you point me in the right direction - possibly some sample application or tutorial explaining how to handle situation like this or more complex.</p> <p>Any help in this regard will be highly appreciated.</p> <hr> <p>I have seen both TheElements and SeismicXML examples. </p> <p>TheElements sample code gives a basic idea of how to use <code>UITabBarController</code>, and <code>UINavigationController</code>, but the example does not discuss passing information from Child Controller to Parent. </p> <p>In my case, I have a <code>UITabBarController</code>, one of the Tab shows a <code>UINavigationController</code> with (+) on the top right corner or Navigation Bar. Now (+) will open an interface for user input and that input will be used to store the data (say in sql), and create a new Table Cell in <code>UITableView</code> embedded in <code>UINavigationController</code>. Now, the interface that will open using (+) will take user input following a sequence of steps (like Main > Step 1 > Step 2> Complete). Each step will show a separate view. I'm getting hard time trying to design this model. Or, maybe I'm not used to programming in Cocoa/iPhone and I'm not looking straight. What other options do I have - when it comes to taking user input involving 20-30 fields (Text, List, Date, Image e.t.c.). Can you provide some input regarding this.</p> <p>Thanks for your help.</p>
<p>For the iPhone, you'll want to handle most views and switching between with the the respective view controllers. For your case, these would be the UITabBarController and UINavigationController. For the purposes of controlling them outside the user's own actions and for storing data, as you want, you'll probably need to look into creating your own subclasses of these controllers. Some good starting points would be the TheElements (which covers tab bars and table views) and SeismicXML (table views and navigation controllers). </p> <p>Most of the actual linking can be handled in Interface Builder, where you can create and layout all the various tabs' contents, but you'll need to use your subclasses to provide data (especially in the case of the table view, where you'll need to setup the data for each cell).</p> <p>Hope this helped,<br/>Geoff</p>
Design question for abstract base class? <p>Have a interface </p> <pre><code>class abc { public: virtual int foo() = 0; ... } class concrete1: public abc { public: int foo() { .. } class concrete2 : public abc { public: int foo() { .. } } </code></pre> <p>Now in my main program I need to construct classes based upon a value of a variable </p> <pre><code>abc *a; if (var == 1) a = new concrete1(); else a = new concrete2(); </code></pre> <p>Obviously I don't want these two lines everywhere in the program (please note I have simplified here so that things are clear). What design pattern should I be using if there are any? </p>
<p>You are looking for <a href="http://en.wikipedia.org/wiki/Factory_method_pattern" rel="nofollow">http://en.wikipedia.org/wiki/Factory_method_pattern</a></p>
How do I enforce a package-level build order in eclipse <p>Explanation: Say package A is always built first and then package B. I need to configure my eclipse workspace such that it mimics the build environment and shows compilation errors when sources in package A refer package B. Is this possible? If yes, how?</p>
<p>You'd need to build them as separate projects, with project B referring to project A but not the other way round.</p>
Should developers fear updates to their workstation software / development stack? <p>As I have discovered, many developers avoid any updating (automatic or manual), because they fear it might do changes to their machine they don't understand, and the software they are developing might fail at some point for reasons they don't know.</p> <p>strategy A.) LEAVE THE SYSTEM AS IT IS, FOR AS LONG AS POSSIBLE.</p> <p>I personally like to have my system as "up to date" as possible (OS and app's), because generally I feel to have less trouble working this way.</p> <p>strategy B.) ALWAYS UP TO DATE</p> <p>What type of developer are you ? And why ?</p>
<p>B. Definitely. </p> <p>If you're developing for a platform with uncertain update pedigrees (e.g. The Real World) then virtual machines are an important weapon, but it pays to be as up to date as possible when you release. </p> <p>It's so much easier to tell your users "just run the update" than to try and guess what patch history they might have that's causing the problem (or at least to be able to rule it out). </p> <p>If you're developing for a purely internal audience then you've really only got one question: </p> <ul> <li>is there an update schedule for the company? <ul> <li>yes: then you need to ensure your software runs both on Production and on anything that's coming up </li> <li>no: probably best to fix that. </li> </ul></li> </ul>
Best compiler warning level for C/C++ compilers? <p>What compiler warning level do you recommend for different C/C++ compilers?</p> <p>gcc and g++ will let you get away with a lot on the default level. I find the best warning level for me is '-Wall'. And I always try to remove fix the code for the warnings it generates. (Even the silly ones about using parenthesis for logical precedence rules or to say I really mean 'if (x = y)')</p> <p>What are your favorite levels for the different compilers, such as Sun CC, aCC (HPUX ?), Visual Studio, intel?</p> <p>Edit:</p> <p>I just wanted to point out that I don't use "-Werror" (but I do understand it's utility) on gcc/g++ because, I use:</p> <pre> #warning "this is a note to myself" </pre> <p>in a few places in my code. Do all the compilers understand the #warning macro?</p>
<p>This is a set of extra-paranoid flags I'm using for C++ code:</p> <pre><code> -g -O -Wall -Weffc++ -pedantic \ -pedantic-errors -Wextra -Waggregate-return -Wcast-align \ -Wcast-qual -Wchar-subscripts -Wcomment -Wconversion \ -Wdisabled-optimization \ -Werror -Wfloat-equal -Wformat -Wformat=2 \ -Wformat-nonliteral -Wformat-security \ -Wformat-y2k \ -Wimplicit -Wimport -Winit-self -Winline \ -Winvalid-pch \ -Wunsafe-loop-optimizations -Wlong-long -Wmissing-braces \ -Wmissing-field-initializers -Wmissing-format-attribute \ -Wmissing-include-dirs -Wmissing-noreturn \ -Wpacked -Wpadded -Wparentheses -Wpointer-arith \ -Wredundant-decls -Wreturn-type \ -Wsequence-point -Wshadow -Wsign-compare -Wstack-protector \ -Wstrict-aliasing -Wstrict-aliasing=2 -Wswitch -Wswitch-default \ -Wswitch-enum -Wtrigraphs -Wuninitialized \ -Wunknown-pragmas -Wunreachable-code -Wunused \ -Wunused-function -Wunused-label -Wunused-parameter \ -Wunused-value -Wunused-variable -Wvariadic-macros \ -Wvolatile-register-var -Wwrite-strings </code></pre> <p>That should give you something to get started. Depending on a project, you might need to tone it down in order to not see warning coming from third-party libraries (which are usually pretty careless about being warning free.) For example, Boost vector/matrix code will make g++ emit a lot of noise.</p> <p>A better way to handle such cases is to write a wrapper around g++ that still uses warnings tuned up to max but allows one to suppress them from being seen for specific files/line numbers. I wrote such a tool long time ago and will release it once I have time to clean it up.</p>
Populating Rails Form Fields after an auto_complete field is populate <p>I am trying to create a form in Rails 2.2.2 that populates a field based on a choice a user has made in an 'auto_complete' field. It looks as though the observe_field functionality is what I need to use but I'm stuck on how to update the value of an existing text field.</p> <p>The sequence of events I am trying to model is follows:</p> <p>1) Use types some characters into a auto_complete field, is given a list of options and selected the relevant option.</p> <p>2) The option corresponds to an ActiveRecord model and I would like to populate another field in the same form (i.e. set a default) using information from the selected ActiveRecord.</p> <p>Thanks for any guidance</p> <p>David</p>
<p>There's a Railscasts episode for this: <a href="http://railscasts.com/episodes/88" rel="nofollow">http://railscasts.com/episodes/88</a></p> <p>hope this helps :)</p>
Should I use the same controller and view for editing and creating models in ASP.NET MVC? <p>Should I use the same controller and view for editing and creating models in ASP.NET MVC, or should I create a view and controller action for creating and a view and controller action for editing?</p> <p>The editing view is certainly likely to be different - it doesn't always make sense for the user interface for editing an object be the same as the view for creation,</p> <p>By separating the views I will avoid lots of "if statements" to determine if I'm editing or creating...</p> <p>Thoughts?</p>
<p>The recommendations I've seen are suggesting that the views are separate with common elements contained within a control to stay DRY.</p> <p>It seems logical to take the same approach with the controller - reuse common parts where appropriate.</p> <p>This view is mirrored here <a href="http://stackoverflow.com/questions/304451/how-to-cleanly-reuse-edit-new-views-in-aspnet-mvc">http://stackoverflow.com/questions/304451/how-to-cleanly-reuse-edit-new-views-in-aspnet-mvc</a> as the question is very similar.</p>
Ignoring XML errors in Python <p>I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser. Is it possible to ignore them, like a browser for example? I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible.</p>
<p>There is a library called <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a>, I think it's what you're looking for. As you're trying to parse a invalid XML, the normal XML parser won't work. BeautifulSoup is more fail-tolerant, it can still extract information from invalid XML.</p> <blockquote> <p>Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful:</p> <ol> <li>Beautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document. This is usually good enough to collect the data you need and run away.</li> <li>Beautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. You don't have to create a custom parser for each application.</li> <li>Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. You don't have to think about encodings, unless the document doesn't specify an encoding and Beautiful Soup can't autodetect one. Then you just have to specify the original encoding. </li> </ol> <p>Beautiful Soup parses anything you give it, and does the tree traversal stuff for you. You can tell it "Find all the links", or "Find all the links of class externalLink", or "Find all the links whose urls match "foo.com", or "Find the table heading that's got bold text, then give me that text."</p> </blockquote>
Reading and running a mathematical expression in Python <p>Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it? </p> <p>Aside from grabbing a string, file or url I have no idea of where to start with this.</p>
<p>Because python supports some algebraic forms, you could do:</p> <pre><code>eval("1 + 1") </code></pre> <p>But this allows the input to execute about anything defined in your env:</p> <pre><code>eval("__import__('sys').exit(1)") </code></pre> <p>Also, if you want to support something python doesn't support, the approach fails:</p> <pre><code>x³ + y² + c ----------- = 0 z </code></pre> <p>Instead of doing this, you can implement a tokenizer and a parser with <a href="http://www.dabeaz.com/ply/">ply</a>. Evaluating a thing like '1 + 1' ought not take more than ten lines or so.</p> <p>You could also implement the tokenizer and the parser by hand. Read about LL and LR parsers. Before attempting this it's also better to learn using parser generators first.</p>
Linq returns list or single object <p>I have a Linq to Entities query like this one:</p> <pre><code>var results = from r in entities.MachineRevision where r.Machine.IdMachine == pIdMachine &amp;&amp; r.Category == (int)pCategory select r; </code></pre> <p>Usually, I use the code below to check if some results are returned:</p> <pre><code>if (results.Count() &gt; 0) { return new oMachineRevision(results.First().IdMachineRevision); } </code></pre> <p>However, I'm getting <strong>NotSupportedException</strong> in the <strong>if</strong> condition.</p> <p>The error message is: <em>Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.</em></p> <p>Note that <strong>pCategory</strong> is an Enum type.</p>
<p><strong>EDIT</strong>: Based on your update, the error may be related to an enum in your entity class. See this <a href="http://gmontrone.com/problem-with-casting-enums-in-linq-to-entities/">blog entry</a> for more information and a work-around. I'm leaving my original answer as an improvement on your query syntax.</p> <p>Try doing the selection of the first entity in the query itself using FirstOrDefault and then check if the result is null.</p> <pre><code>int compareCategory = (int)pCategory; // just a guess var result = (from r in entities.MachineRevision where r.Machine.IdMachine == pIdMachine &amp;&amp; r.Category == compareCategory select r).FirstOrDefault(); if (result != null) { return new oMachineRevision(result.IdMachineRevision); } </code></pre>
How to dispose asynchronously? <p>Let's say I have a class that implements the <strong>IDisposable</strong> interface. Something like this:</p> <p><img src="http://farm4.static.flickr.com/3199/3149605015_f090f20185_o.png" alt="http://www.flickr.com/photos/garthof/3149605015/" /></p> <p><strong>MyClass</strong> uses some unmanaged resources, hence the <em>Dispose()</em> method from <strong>IDisposable</strong> releases those resources. <strong>MyClass</strong> should be used like this:</p> <pre><code>using ( MyClass myClass = new MyClass() ) { myClass.DoSomething(); } </code></pre> <p><hr /></p> <p>Now, I want to implement a method that calls <em>DoSomething()</em> asynchronously. I add a new method to <strong>MyClass</strong>:</p> <p><img src="http://farm4.static.flickr.com/3103/3149605005_bde86e4e0b_o.png" alt="http://www.flickr.com/photos/garthof/3149605005/" /></p> <p>Now, from the client side, <strong>MyClass</strong> should be used like this:</p> <pre><code>using ( MyClass myClass = new MyClass() ) { myClass.AsyncDoSomething(); } </code></pre> <p>However, if I don't do anything else, this could fail as the object <em>myClass</em> might be disposed before <em>DoSomething()</em> is called (and throw an unexpected <strong>ObjectDisposedException</strong>). So, the call to the <em>Dispose()</em> method (either implicit or explicit) should be delayed until the asynchronous call to <em>DoSomething()</em> is done. </p> <p>I think the code in the <em>Dispose()</em> method should be executed <strong>in a asynchronous way, and only once all asynchronous calls are resolved</strong>. I'd like to know which could be the best way to accomplish this.</p> <p>Thanks.</p> <p><em>NOTE: For the sake of simplicity, I haven't entered in the details of how Dispose() method is implemented. In real life I usually follow the <a href="http://msdn.microsoft.com/en-us/library/fs2xkftw(VS.80).aspx">Dispose pattern</a>.</em></p> <p><hr /></p> <p><strong>UPDATE:</strong> Thank you so much for your responses. I appreciate your effort. As <a href="http://stackoverflow.com/users/3055/chakrit">chakrit</a> <a href="http://stackoverflow.com/questions/400130/how-to-dispose-asynchronously#400165">has commented</a>, I need that <strong>multiple calls to the async DoSomething can be made</strong>. Ideally, something like this should work fine:</p> <pre><code>using ( MyClass myClass = new MyClass() ) { myClass.AsyncDoSomething(); myClass.AsyncDoSomething(); } </code></pre> <p>I'll study the counting semaphore, it seems what I'm looking for. It could also be a design problem. If I find it convenient, I will share with you some bits of the real case and what <strong>MyClass</strong> really does.</p>
<p>It looks like you're using the event-based async pattern (<a href="http://msdn.microsoft.com/en-us/library/ms228969.aspx">see here for more info about .NET async patterns</a>) so what you'd typically have is an event on the class that fires when the async operation is completed named <code>DoSomethingCompleted</code> (note that <code>AsyncDoSomething</code> should really be called <code>DoSomethingAsync</code> to follow the pattern correctly). With this event exposed you could write:</p> <pre><code>var myClass = new MyClass(); myClass.DoSomethingCompleted += (sender, e) =&gt; myClass.Dispose(); myClass.DoSomethingAsync(); </code></pre> <p>The other alternative is to use the <code>IAsyncResult</code> pattern, where you can pass a delegate that calls the dispose method to the <code>AsyncCallback</code> parameter (more info on this pattern is in the page above too). In this case you'd have <code>BeginDoSomething</code> and <code>EndDoSomething</code> methods instead of <code>DoSomethingAsync</code>, and would call it something like...</p> <pre><code>var myClass = new MyClass(); myClass.BeginDoSomething( asyncResult =&gt; { using (myClass) { myClass.EndDoSomething(asyncResult); } }, null); </code></pre> <p>But whichever way you do it, you need a way for the caller to be notified that the async operation has completed so it can dispose of the object at the correct time.</p>
How do I automatically delete tempfiles in c#? <p><br> What are a good way to ensure that a tempfile is deleted if my application closes or crashes? Ideally I would like to obtain a tempfile, use it and then forget about it.</p> <p>Right now I keep a list of my tempfiles and delete them with an eventhandler that triggers on Application.ApplicationExit.</p> <p>Is there a better way?</p>
<p>Nothing is guaranteed if the process is killed prematurely, however, I use "<code>using</code>" to do this..</p> <pre><code>using System; using System.IO; sealed class TempFile : IDisposable { string path; public TempFile() : this(System.IO.Path.GetTempFileName()) { } public TempFile(string path) { if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path"); this.path = path; } public string Path { get { if (path == null) throw new ObjectDisposedException(GetType().Name); return path; } } ~TempFile() { Dispose(false); } public void Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (disposing) { GC.SuppressFinalize(this); } if (path != null) { try { File.Delete(path); } catch { } // best effort path = null; } } } static class Program { static void Main() { string path; using (var tmp = new TempFile()) { path = tmp.Path; Console.WriteLine(File.Exists(path)); } Console.WriteLine(File.Exists(path)); } } </code></pre> <p>Now when the <code>TempFile</code> is disposed or garbage-collected the file is deleted (if possible). You could obviously use this as tightly-scoped as you like, or in a collection somewhere.</p>
Office XP Shared Addin VS 2008 <p>I'm trying to create a Shared Addin using VS 2008 for Office XP (Excel to be precise). However, after creating the project in Visual studio and changing the references to Office XP (apart from Extensibility which I don't seem to be able to find a copy for office xp) and adding excel.exe to the references as well. I now don't seem to be able to get the addin to install on any computers.</p> <p>Does anyone have any guides on writing Office XP addins using VS 2008 (Com Addins I might add)?</p> <p>Does anyone know the reference that I'm meant to have or things prior that I'm meant to have installed on the pc?</p> <p>I have three test pcs, this one has office xp, 2003 and 2007 on it and I can write an addin using 2003 references that runs on this but no other box. One with just office xp on it but also office xp PIAs installed and .NET and another one just with office xp on.</p> <p>Any help would be very much appriciated.</p>
<p>I found the problem with this in the end.</p> <p>The problem came from a KB entry <a href="http://support.microsoft.com/kb/908002" rel="nofollow">908002</a>. Unfortunatley, to run the fix you need Visual Studio 2005 and Office 2003 installed otherwise it won't deploy the fix and so I had glossed over this quite a few times. In the end I found an old copy of VS2005 and Office 2003 on a spare machine, installed the fix, created an installer and tried it on a machine with Office XP and everything worked fine.</p> <p>There are two fixes that are needed for this to work on any machine with Office XP:</p> <pre><code>extensibilityMSM.msi - installs the extensibility.dll lockbagRegKey.msi - adds a fix to a registry key </code></pre> <p>I couldn't find these to be downloaded seperately from the KB908002 fix but I have copies locally.</p> <p>After applying these fixes it was easy to use COM Addins like using VSTO and it took me less than an hour to write the actual code. I'm not looking for a way to include these in my MSI installer as prerequesites.</p> <p>Any questions chuck them in a comment and I'll try and update asap.</p>
How can I get a list of available wireless networks on Linux? <p>I would like to get a list of the wireless networks available. Ideally this would be via some C call, but I don't mind if I have to kludge it with a system call. Even better if the required C call or program doesn't require some exotic 3rd party package.</p> <p>The internet seems to suggest I use <code>sudo iwlist &lt;interface&gt; scan</code> which does seem to do the trick from the command line, but I'd rather not require root permissions. I only want to see the basics, not change anything.</p>
<p>It's pretty easy to do a scan in the command line. The man pages are your friend here (check out <strong>iwconfig</strong> and <strong>iwlist</strong>). But using the C interface is a little more difficult so I'll focus on that.</p> <p>First of all, as other people have mentioned, definitely download out the <a href="http://www.hpl.hp.com/personal/Jean_Tourrilhes/Linux/Tools.html#latest">wireless tools source code</a>. All the documentation for the programming interface is in the <strong>.c</strong> files. As far as I can tell, there is no web documentation for the api. However, the source code is pretty easy to read through. You pretty much only need <strong>iwlib.h</strong> and <strong>iwlib.c</strong> for this question.</p> <p>While you can use <code>iw_set_ext</code> and <code>iw_get_ext</code>, the <strong>libiw</strong> implements a basic scanning function <code>iw_scan</code>, from which you can extract most of the information that you need.</p> <p>Here is a simple program to get the ESSID for all available wireless networks. Compile with <code>-liw</code> and run with <code>sudo</code>.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;iwlib.h&gt; int main(void) { wireless_scan_head head; wireless_scan *result; iwrange range; int sock; /* Open socket to kernel */ sock = iw_sockets_open(); /* Get some metadata to use for scanning */ if (iw_get_range_info(sock, "wlan0", &amp;range) &lt; 0) { printf("Error during iw_get_range_info. Aborting.\n"); exit(2); } /* Perform the scan */ if (iw_scan(sock, "wlan0", range.we_version_compiled, &amp;head) &lt; 0) { printf("Error during iw_scan. Aborting.\n"); exit(2); } /* Traverse the results */ result = head.result; while (NULL != result) { printf("%s\n", result-&gt;b.essid); result = result-&gt;next; } exit(0); } </code></pre> <p>DISCLAIMER: This is just a demonstration program. It's possible for some results to not have an essid. In addition, this assumes your wireless interface is "wlan0". You get the idea.</p> <p>Read the <strong>iwlib</strong> source code!</p>
Tool for testing using parameter permutations <p>I remember there existed a testing program/library that will run your code and/or unit tests, creating all kinds of permutations of the parameters (null values, random integers, strings and so on). I just can't remember what it was called and searching google doesn't seem to come up with anything.</p> <p>I know it was created for Java code and I think it was quite expensive as well. That's really all I can remember, anyone have a clue what program/library I am thinking about?</p>
<p>The <a href="http://www.agitar.com/solutions/products/automated_junit_generation.html" rel="nofollow">AgitarOne JUnit Generator</a> comes to mind. I'm not sure it's what you're thinking of, though.</p>
Getting an error while attempting to checkout with SharpSVN <p>While attempting to use the following code, I am receiving the following error : Already working for different url, error code 155000.</p> <pre><code>string targetPath = @"C:\Documents and Settings\Admin\My Documents\CPM Creator\"; //" for prettify client.Authenticatio​n.DefaultCredentials​ = new NetworkCredential("guestUser", "hjk$#&amp;123"); // Checkout the code to the specified directory client.CheckOut(new Uri("http://svn.peerlis.com:8080/CPM Creator"), targetPath); </code></pre>
<p>Well, is it correct? Is this already the working path for a SVN folder? Are there any hidden svn folders in that location?</p> <p>I use SharpSVN in a "get to scratch area, work locally, throw away" cycle, so I always start with a clean (empty) folder (with no SVN folders in the ancestors). This has always worked fairly well.</p>
What's all this business about Flash, Flex, Adobe Air, Java FX and Silverlight? <p>What's all this business about Flash, Flex, Adobe Air, Java FX and Silverlight? Why would I choose one over the other? and what happened to Java Applets and ActiveX controls?</p> <p>Oh, and where does AJAX fit in to all this? and is Laszlo relevant?</p> <p>Afteredit (in response to some "d'uh" type answers): the question is a bit tongue-in-cheek. I know about the various RIA technologies. I am, however, interested in the StackOverflow community's opinion about each - particularly why you would use one over the other</p>
<p>Big topic and it would take pages to provide a full answer so here is the "short" version...</p> <ol> <li><p>Adobe Flex/AIR is by far the most mature RIA platform out there and it runs in FlashPlayer. You write apps using ActionScript (similar to Javascript) and MXML (markup used primarily for layout/view code). You can also deploy Flex applications easily to the desktop if the user has the AIR runtime installed.</p></li> <li><p>Silverlight is Microsoft's offering which is still quite a bit behind Flex but is rapidly gaining ground. The SL runtime is new and slowly gaining a larger install base. You can use C#, VB.NET or other languages supported by the .NET runtime. It runs on Windows and Mac but doesn't run on the desktop.</p></li> <li><p>JavaFX is a platform, API and scripting language for building RIA on the Java platform. It's the newest entry and just recently had its 1.0 release. It can run in the browser or the desktop and can leverage any and all Java code. Given how much open source Java code exists this can be pretty compelling.</p></li> </ol> <p>AJAX / DHTML is primarily an alternative to these technologies, although since FP, SL and Java all have two-way Javascript APIs, you can write applications that use both and allow them to interoperate.</p>
Sample Hibernate program? <p>How would I write a simple program using Hibernate in Java, with MySQL as a backend?</p>
<p>The <a href="http://www.hibernate.org/hib_docs/v3/reference/en-US/html/" rel="nofollow">Hibernate reference docs</a> are a good place to start.</p> <p>Maybe a <a href="http://www.javaworld.com/javaworld/jw-10-2004/jw-1018-hibernate.html" rel="nofollow">"Hello, Hibernate"</a> can help.</p>
What are the major differences between Rails 1.X and 2.X <p>Most dead-tree books and web tutorials address Rails 1.X. I'm wondering if they are worth using to learn Rails 2.X. If so, what sections and concepts should I avoid and what have pretty much stayed the same?</p>
<p>One of my favorite books is the "skateboard" book from The Pragmatic Programmers, "Agile Web Development with Rails". Many of the things that have changed were moved from core into plugins, so if they are features that you want or need, then you can still use them. Most of the new features were adding, rather than removing things.</p> <p>As mentioned in other comments, to find out more you can visit these links:</p> <ul> <li><a href="http://weblog.rubyonrails.org/2007/9/30/rails-2-0-0-preview-release" rel="nofollow">http://weblog.rubyonrails.org/2007/9/30/rails-2-0-0-preview-release</a></li> <li><a href="http://www.infoq.com/news/2007/12/rails-20-docs" rel="nofollow">http://www.infoq.com/news/2007/12/rails-20-docs</a></li> </ul> <p>That said, I also have "The Rails Way" by Obie Fernandez which covers Rails 2.0. However, I still find myself reaching for the Agile book more often. You can get it, and the soon-to-come 3rd Edition here: <a href="http://pragprog.com/titles/rails3/agile-web-development-with-rails-third-edition" rel="nofollow">http://pragprog.com/titles/rails3/agile-web-development-with-rails-third-edition</a>.</p> <p>Because development on Rails is so fast paced, it is very difficult for books to actually keep up with the framework. I find that reading blogs is the best way to stay abreast of new features that have been added or to find out about not-new features that I didn't know about.</p> <p>Some of the blogs that I subscribe to (there are many, many more available than these):</p> <ul> <li><a href="http://weblog.rubyonrails.com/" rel="nofollow">http://weblog.rubyonrails.com/</a></li> <li><a href="http://delicious.com/jnunemaker/railstips" rel="nofollow">http://delicious.com/jnunemaker/railstips</a></li> <li><a href="http://railstips.org/" rel="nofollow">http://railstips.org/</a></li> <li><a href="http://blog.hasmanythrough.com/" rel="nofollow">http://blog.hasmanythrough.com/</a></li> <li><a href="http://ryandaigle.com/" rel="nofollow">http://ryandaigle.com/</a></li> <li><a href="http://railspikes.com/" rel="nofollow">http://railspikes.com/</a></li> <li><a href="http://www.railsontherun.com/" rel="nofollow">http://www.railsontherun.com/</a></li> <li><a href="http://agilewebdevelopment.com/plugins" rel="nofollow">http://agilewebdevelopment.com/plugins</a></li> </ul>
Best practice for managing data-model changes in a released system <p>I am about to embark on the development of a web application project.</p> <p>I'd like to get something up early and often for early adopters to play with and feedback.</p> <p>But I envisage the data model changing as the project progresses and my understanding of the system improves. </p> <p>How should I manage the dilemma of updating the data model appropriately and preventing data loss for early adopters? Should I simply put up a big warning saying "user beware", or should I put in the effort to create migration scripts?</p>
<p>What platform are you using? Ruby on Rails gives you migration scripts as part of the package. If you're in Java-land, you might want to check out <a href="http://migrate4j.sourceforge.net/" rel="nofollow" title="migrate4j">migrate4j</a>.</p> <p>In the end, I'd suggest doing both things: Warn your users that they're using alpha software, and employ migration scripts with the intent of preserving their data whenever you can (lest they become peeved and lose interest).</p>
Testing C code using the web <p>I have a number of C functions which implement mathematical formulae. To-date these have been tested for mathematical "soundness" by passing parameters through command line applications or compiling DLL's for applications like Excel. Is there an easy way of doing this testing over the web?</p> <p>Ideally something along the lines of:</p> <ul> <li>compile a library</li> <li>spend five minutes defining a web form which calls this code</li> <li>testers can view the webpage, input parameters and review the output</li> </ul> <p>A simple example of a calculation could be to calculate the "accrued interest" of a bond:</p> <p><strong>Inputs</strong>: current date, maturity date, coupon payment frequency (integer), coupon amount (double)</p> <p><strong>Outputs</strong>: the accrued interest (double)</p>
<p>You should have a look into automated testing. Manual tests will all have to be repeated every time you change something in your code. Automated tests are the solution for your kind of tests. Let testers write test cases with the accompanying results, then make them into unit tests. </p> <p>See also: <a href="http://en.wikipedia.org/wiki/Unit_testing" rel="nofollow">unit testing</a></p>
How can I create an instance of an arbitrary Array type at runtime? <p>I'm trying to deserialize an array of an type unknown at compile time. At runtime I've discovered the type, but I don't know how to create an instance.</p> <p>Something like:</p> <pre><code>Object o = Activator.CreateInstance(type); </code></pre> <p>which doesn't work because there is no parameterless constructor, Array doesn't seem to have any constructor.</p>
<p>Use <a href="http://msdn.microsoft.com/en-us/library/system.array.createinstance.aspx">Array.CreateInstance</a>.</p>
layer hit test only returning layer when bottom half of layer is touched <p>I have a sublayer on a layer-backed view. The sublayer's contents are set to an Image Ref and is a 25x25 rect.<br /> I perform a hit test on the super layer when the touchesBegan and touchesMoved methods are invoked. The hit test method does, in fact, return the sublayer if it is touched, BUT only if the bottom half of the image is touched. If the top half of the image is touched, it returns the superlayer instead.</p> <p>I do know the iPhone OS compensates for the tendancy of user touches to be lower than intended. Even if I resize the sublayer to a larger size, 50x50, it exhibits the same behavior.</p> <p>Any thoughts? </p>
<p>The documentation for hitTest says:</p> <pre><code>/* Returns the farthest descendant of the layer containing point 'p'. * Siblings are searched in top-to-bottom order. 'p' is in the * coordinate system of the receiver's superlayer. */ </code></pre> <p>So you need to do (something like this):</p> <pre><code>CGPoint thePoint = [touch locationInView:self]; thePoint = [self.layer convertPoint:thePoint toLayer:self.layer.superlayer]; CALayer *theLayer = [self.layer hitTest:thePoint]; </code></pre> <p>(Repeating answer from other post for completeness' sake)</p>
What ASP.NET Web Controls implement IPostBackDataHandler? <p>Could someone point me to a list of controls that implement <code>IPostBackDataHandler</code>?</p> <p>I want to know what controls implement this interface and what properties the controls will set during the <code>Postback</code>.</p> <p>For example:</p> <blockquote> <p>Textbox : Text</p> <p>DropDownList : SelectedIndex</p> </blockquote> <p>I'm basically looking for a list of properties that will not be saved in <code>ViewState</code>.</p> <p>Thanks!</p>
<p>In the .NET IDE open the Object Browser Window. You can find this window on the View menu, or it may be, depending on your configuration, on the top toolbar.</p> <p>In the search textbox type in the class, or interface in this case, you are looking for: <code>IPostBackDataHandler</code> and submit.</p> <p>In the results, expand the type and then expand the derived types folder, you will find what you seek!</p>
Preventive vs Reactive C# programming <p>I've always been one to err on the side of preventing exception conditions by never taking an action unless I am certain that there will be no errors. I learned to program in C and this was the only way to really do things.</p> <p>Working with C# I frequently see more reactive programing - try to do something and handle exceptions. To me this seems like using exceptions as control statements. The first few times I saw this I dismissed it as bad practice. But over the past few months I've seen it all over the place and just have to wonder - is this accepted/efficient or just an epidemic?</p> <p>Update: For a bit of clarification most of the exception handling I am seeing is things like</p> <pre><code>try { //open file } catch { //message box for file not found } </code></pre> <p>or even worse</p> <pre><code>try { //open xml //modify xml (100+ lines of code) } catch { //message for 'unspecified error' } </code></pre> <p>I understand there are times when exception handling is very good to use (such as database connections) but I'm referring to the use of exceptions in place of more 'traditional' control. I asked this because I felt like this programming style was using exceptions as a crutch instead of as a recovery method and wanted to know if this was just something I'd have to learn to expect in the C# world.</p>
<p>As usual, the answer is "it depends", but I subscribe to the "fail fast" philosophy in general.</p> <p>I prefer to use try/finally (sans catch) unless I can actually do something useful to recover from an exception in a particular block of code. Catching every possible exception isn't worth it. In general, failing fast is preferable to failing silently.</p> <p>If, on the other hand, you know how to recover from a particular exception, then yes, go do that.</p> <p>Say you have a file transfer library. It will probably throw an exception if the transfer is interrupted due to a timeout or network failure. That's reasonable. You'll be annoyed if the library just fails silently; checking for a return code is far more error-prone, and not necessarily more readable. But perhaps you have a business rule for sending a bunch of files to a server that you should make at least 3 attempts to transfer the file before giving up and asking for user intervention. In that case, the business logic should handle the exception, try to recover, then do whatever it's supposed to do when the automatic solution fails (alert the user, schedule a later attempt, or whatever).</p> <p>If you find code that does this:</p> <pre><code>try { // do something that could throw // ... } catch {} //swallow the exception </code></pre> <p>or:</p> <pre><code>catch { return null; } </code></pre> <p>That's <strong>probably</strong> broken. Sure, sometimes code that you call can throw an exception that you really don't care about. But I often see people do this just so they don't have to "handle" the exception upstream; the practice makes things harder to debug. </p> <p>Some people consider allowing exceptions to cascade up the chain of responsibility to be bad because you're just "hoping" someone upstream will "miraculously" know what to do. Those people are wrong. Upstream code is often the only place that <strong>can</strong> know what to do.</p> <p>Occasionally, I'll try/catch and throw a different, more appropriate exception. However, when possible, a guard clause is better. e,g. <code>if (argument==null) throw new ArgumentNullException();</code> is better than allowing a NullReferenceException to propagate up the call stack, because it's clearer what went wrong.</p> <p>Some conditions "should never happen" or "I didn't know that could happen" should probably be logged (see, for example, jboss logging), but can be swallowed before they bring down your application, at least in some cases.</p> <p>ETA: It is probably broken to take a specific exception and then display a general, ambiguous error message. For your second example above, that sounds bad to me. For your first, "File not found", that may be more reasonable (if you actually catch that specific exception, and not just "everything"), unless you have a better way to deal with that condition somewhere else. Modal Messageboxes are usually a bad "interaction design smell" to me, but that's mostly beside the point.</p>
Display os x window full screen on secondary monitor using Cocoa <p>I'm working on a Cocoa Mac app where I need to display a window/view on a secondary monitor, full-screen. I know how to create a window that could be dragged onto the secondary monitor, but I was wanting to programatically create the window and make it full screen on the external monitor. Thanks for the help.</p>
<p>First, determine which screen you want to use by iterating over [NSScreen screens].</p> <p>Create a full screen window with:</p> <pre><code>NSScreen *screen = /* from [NSScreen screens] */ NSRect screenRect = [screen frame]; NSWindow *window = [[NSWindow alloc] initWithContentRect:screenRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO screen:screen]; [window setLevel: CGShieldingWindowLevel()]; </code></pre> <p>You might want to google CGDisplayCapture() as well.</p>
high cpu in IIS <p>I'm developing a POS application that has a local database on each POS computer, and communicates with the server using WCF hosted in IIS. The application has been deployed in several customers for over a year now.</p> <p>About a week ago, we've started getting reports from one of our customers that the server that the IIS is hosted on is very slow. When I've checked the issue, I saw the application pool with my process rocket to almost 100% cpu on an 8 cpu server.</p> <p>I've checked the SQL Activity Monitor and network volume, and they showed no significant overload beyond what we usually see.</p> <p>When checking the threads in Process Explorer, I saw lots of threads repeatedly calling CreateApplicationContext. I've tried installing .Net 2.0 SP1, according to some posts I found on the net, but it didn't solve the problem and replaced the function calls with CLRCreateManagedInstance.</p> <p>I'm about to capture a dump using adplus and windbg of the IIS processes and try to figure out what's wrong.</p> <p>Has anyone encountered something like this or has an idea which directory I should check ?</p> <p>p.s. The same version of the application is deployed in another customer, and there it works just fine. I also tried rolling back versions (even very old versions) and it still behaves exactly the same.</p> <p>Edit: well, problem solved, turns out I've had an SQL query in there that didn't limit the result set, and when the customer went over a certain number of rows, it started bogging down the server. Took me two days to find it, because of all the surrounding noise in the logs, but I waited for the night and took a dump then, which immediately showed me the query.</p>
<p>Usually this has nothing to do with hardware and everything to do with how IIS is configured coupled with some slightly long running queries (100+ milliseconds).</p> <p>Under your application pool configuration set your web garden setting to something like 20 or more. </p> <p>The web garden setting is pretty much the number of threads available to process requests for your application. If it's set to 1 then a single query could block handling other requests until it completes. </p> <p>I have an app that's handling close to 3.5 million requests a day. When the web garden was set to 1, the web server CPU stayed at 100% and had a LOT of requests dropped. When I upped it to 50, the web server CPU dropped to just under 2% and no requests were dropped. </p>
Expression Web: Shortcut doesn't point to an exe file, but I want to use it to edit <p><strong>Problem:</strong> I have to support users who need to edit web pages. Some of these web pages exist only as textarea controls. Fortunately, there is a firefox plugin that allows the user to open the textarea in a default text editor. Unfortunately, this plugin requires you to point to the EXE file of the text editor you want to invoke.</p> <p>This is a reasonable requirement, but @#$%^ Microsoft Expression Web is one of those applications whose shortcut .lnk file does not appear to point to a real EXE file. If there is an EXE file somewhere, it's hidden.</p> <p><strong>Question:</strong> How can I locate the actual EXE file so people can configure Microsoft Expression web to be their editor of choice?</p> <p><strong>Update:</strong> I should have emphasized that I was looking for a way to automate this via script or batch file (hence the SO posting, in case anyone's "not-programming-related" spidey sense was tingling).</p>
<p>I found my executable in the following location:</p> <pre><code>C:\Program Files\Microsoft Expression\Web Designer\EXPRWD.EXE </code></pre> <p>I'm not sure if that gives you what you need, but you can always have your users (or programmatically) search for EXPRWD.EXE and go from there.</p>
Converting GUID to Integer and Back <p>so I have a 3rd party application that I have to interface with, this application needs the userID from my users table. the problem is that I store my userIDs as GUIDs and the 3rd party app only accepts an integer. so I figure, if there is a way to convert a GUID to an integer then be able to convert it back (as i get communications from their server regarding the userID) then I don't have to recode a too much. any ideas?</p>
<p>You'll need a store a mapping from your Guid to the 3rd party's integer: either a new "int thirdPartyId" field in your existing user table, or a new table.</p>
How do I Change the FontFamily on a ContentPresenter? <p>I have a custom template for an expander that is close to the code below. I had to change some of the code to take out custom classes, brushes, etc..</p> <pre><code>&lt;Style TargetType="{x:Type Expander}"&gt; &lt;Setter Property="HorizontalContentAlignment" Value="Stretch" /&gt; &lt;Setter Property="VerticalContentAlignment" Value="Top" /&gt; &lt;Setter Property="BorderBrush" Value="Transparent" /&gt; &lt;Setter Property="FontFamily" Value="Tahoma" /&gt; &lt;Setter Property="FontSize" Value="12" /&gt; &lt;Setter Property="Foreground" Value="Black" /&gt; &lt;Setter Property="BorderThickness" Value="1" /&gt; &lt;Setter Property="Margin" Value="2,0,0,0" /&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type Expander}"&gt; &lt;Border x:Name="Border" SnapsToDevicePixels="true" Background="White" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Margin="0,0,0,10" Padding="0" CornerRadius="8"&gt; &lt;DockPanel&gt; &lt;Border x:Name="HeaderSite" Background="Blue" CornerRadius="8" Height="32" DockPanel.Dock="Top"&gt; &lt;DockPanel&gt; &lt;ToggleButton Foreground="White" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" Margin="0" MinHeight="0" MinWidth="0" Padding="6,2,6,2" IsChecked="{Binding Path=IsExpanded, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" DockPanel.Dock="Left"&gt; &lt;/ToggleButton&gt; &lt;ContentPresenter SnapsToDevicePixels="True" HorizontalAlignment="Left" Margin="4,0,0,0" ContentSource="Header" VerticalAlignment="Center" RecognizesAccessKey="True" /&gt; &lt;/DockPanel&gt; &lt;/Border&gt; &lt;Border x:Name="InnerBorder" Margin="0" &gt; &lt;ContentPresenter Focusable="false" Visibility="Collapsed" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" x:Name="ExpandSite" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" DockPanel.Dock="Bottom" /&gt; &lt;/Border&gt; &lt;/DockPanel&gt; &lt;/Border&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsExpanded" Value="true"&gt; &lt;Setter Property="Margin" TargetName="InnerBorder" Value="5" /&gt; &lt;Setter Property="Visibility" TargetName="ExpandSite" Value="Visible" /&gt; &lt;/Trigger&gt; &lt;Trigger Property="IsEnabled" Value="false"&gt; &lt;Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" /&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>As you can see there are two ContentPresenters. I would like the first one to use Tahoma Bold as the font instead of the default Tahoma. How can I do this?</p>
<p>You need to use the FontWeight property to specify a bold font. However, you've probably noticed that ContentPresenter doesn't have that property. So you'll need to use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock.fontweight.aspx">TextBlock.FontWeight</a> attached property to tell the ContentPresenter that any text inside it should be bold.</p> <p>Try this:</p> <pre><code>&lt;ContentPresenter TextBlock.FontFamily="Tahoma" TextBlock.FontWeight="Bold" SnapsToDevicePixels="True" HorizontalAlignment="Left" Margin="4,0,0,0" ContentSource="Header" VerticalAlignment="Center" RecognizesAccessKey="True" /&gt; </code></pre>
"Brokered definition set" design pattern -- well-known under another name? <p>In a project that I've been involved with for many years, I've gradually evolved a design pattern that's proven to be extremely useful for me. I sometimes feel I should get a bit evangelical with it, but I'd be a bit embarrassed if I tried and found out that it was just my version of somebody's old hat. I've dug through <i>Design Patterns</i> looking for it in vain, and I haven't run across anyone else talking about it, but my search hasn't been exhaustive.</p> <p>The core idea is having a broker object that manages a set of definition objects, each definition object constituting a possible value of some complex property. As an example, you might have Car, Plane, and Generator classes that all have an EngineType. Car doesn't store its own EngineType object, it stores a reference key of some kind that states the kind of Engine it has (such as an integer or string ID). When we want to look at properties or behavior of an EngineType, say WankelEngine, we ask the EngineTypeBroker singleton object for WankelEngine's definition object, passing it the reference key. This object encapsulates whatever's interesting to know about EngineTypes, possibly simply being a property list but potentially having behavior loaded onto it as well.</p> <p>So what it's facilitating is a kind of shared, loosely-coupled aggregation, where many Cars may have a WankelEngine but there is only one WankelEngine definition object (and the EngineTypeBroker can replace that object, leveraging the loose coupling into enhanced runtime morphism).</p> <p>Some elements of this pattern as I use it (continuing to use EngineType as an example):</p> <ol> <li>There are always IsEngineType(x) and EngineType(x) functions, for determining whether a given value is a valid reference key for an EngineType and for retrieving the EngineType definition object corresponding to a reference key, respectively.</li> <li>I always allow multiple forms of reference key for a given EngineType, always at least a string name and the definition object itself, more often than not an integer ID, and sometimes object types that aggregate an EngineType. This helps with debugging, makes the code more flexible, and, in my particular situation, eases a lot of backward compatibility issues relative to older practices. (The usual way people used to do all this, in this project's context, was to define hashes for each property an EngineType might have and look up the properties by reference key.)</li> <li>Usually, each definition instance is a subclass of a general class for that definition type (i.e. WankelEngine inherits EngineType). Class files for definition objects are kept in a directory like /Def/EngineType (i.e. WankelEngine's class would be /Def/EngineType/WankelEngine). So related definitions are grouped together, and the class files resemble configuration files for the EngineType, but with the ability to define code (not typically found in configuration files).</li> </ol> <p>Some trivially illustrative sample pseudocode:</p> <pre><code>class Car { attribute Name; attribute EngineTypeCode; object GetEngineTypeDef() { return EngineTypeBroker-&gt;EngineType(this-&gt;GetEngineTypeCode()); } string GetDescription() { object def = this-&gt;GetEngineTypeDef(); return "I am a car called " . this-&gt;GetName() . ", whose " . def-&gt;GetEngineTypeName() . " engine can run at " . def-&gt;GetEngineTypeMaxRPM() . " RPM!"; } } </code></pre> <p>So, is there a name out there for this?</p>
<p>I've used a pattern similar to this before, most often in games. I'd have a WeaponDefinition and WeaponInstance classes (not quite with those names). The WeaponDefinition class (and various subclasses, if I have different types of weapons, e.g. melee vs projectile) would be responsible for keeping track of the global data for that type of weapon (rate of fire, max ammo, name, etc) and has all the logic. The WeaponInstance class (and subclasses) contain the current state in the firing sequence (for use with comparing the rate of fire), the current ammo count, and a pointer (it could be some key into a manager class as in your example, but that doesn't seem to be a requirement of the pattern) to the WeaponDefinition. The WeaponInstance has a bunch of functions for firing, reloading, etc, that just call the appropriate method on the WeaponDefinition instance, passing itself as an argument. This means the WeaponDefinition stuff isn't dupicated for every tank/soldier/airplane in the game world, but they all have their own ammo counts, etc.</p> <p>I have no idea what it's called, and I'm not sure it's quite the same as what you're talking about, but I think it's close. It's definitely useful.</p>
Is there anyway to speed up SQL Server Management Objects traversal of a existing database? <p>I'm currently using SMO and C# to traverse databases to create a tree of settings representing various aspects of the two databases, then comparing these trees to see where and how they are different.</p> <p>The problem is, for 2 reasonably sized database, it takes almost 10mins to crawl them locally and collect table/column/stored procedure information I wish to compare.</p> <p>Is there a better interface then SMO to access databases in such a fashion? I would like to not include any additional dependencies, but I'll take that pain for a 50% speed improvement. Below is a sample of how I'm enumerating tables and columns.</p> <pre><code> Microsoft.SqlServer.Management.Smo.Database db = db_in; foreach (Table t in db.Tables) { if (t.IsSystemObject == false) { foreach (Column c in t.Columns) { } } } </code></pre>
<p>Try to force SMO to read all the required fields at once, instead of querying on access. See <a href="http://davidhayden.com/blog/dave/archive/2006/03/29/2894.aspx" rel="nofollow">this blog</a> for more information</p> <hr> <p>EDIT: Link is dead but I found <a href="http://web.archive.org/web/20100102060107/http://davidhayden.com/blog/dave/archive/2006/03/29/2894.aspx" rel="nofollow">the page</a> on archive.org. Here's the relevant code:</p> <pre><code>Server server = new Server(); // Force IsSystemObject to be returned by default. server.SetDefaultInitFields(typeof(StoredProcedure), "IsSystemObject"); StoredProcedureCollection storedProcedures = server.Databases["AdventureWorks"].StoredProcedures; foreach (StoredProcedure sp in storedProcedures) { if (!sp.IsSystemObject) { // We only want user stored procedures } } </code></pre>
More than a window in Processing <p>Is it even possible? Can you load more than one image and have them displayed in more than one window?</p>
<p>Yes.</p> <p>It would be useful if you could clarify your question a bit more (Web or Desktop application? Server or Client Side (Flash, Java, JavaScript)? Any existing Framework (.net? Ruby on Rails?) or technology (GDI+? ImageMagick?), but the answer to your question is in most circumstances "Yes", and "Yes, but..." in other cases)</p>
Jquery video tutorial resources <p>Is there any place where I can find JQuery video tutorials from novice level to master level? The books I saw mostly assume you are very familiar with CSS syntax. If there is any video tutorial resource for CSS, that would be awesome too.</p>
<p>I found the following links: </p> <ul> <li><a href="http://www.google.ca/search?hl=en&amp;q=jquery+video+tutorials&amp;btnG=Google+Search&amp;meta=" rel="nofollow">JQuery Video Tutorial</a> (via <a href="http://google.com" rel="nofollow">Google</a>) </li> <li><a href="http://15daysofjquery.com/jquery-online-movie-tutorial-by-john-resig/29/" rel="nofollow">15 Days of JQuery - Query Movie Tutorial</a> </li> <li><a href="http://query7.com/basics-slides-in-jquery-video-tutorial/" rel="nofollow">Basics of JQuery - Video Tutorial</a>. </li> </ul>
ASP.net Ajax: Use Code behind function instead web service <p>Is it possible not to use web service for ASP.net ajax instead call code-behind function to fetch data?</p> <p>any example or link is much appericate.</p>
<p>According to the <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx" rel="nofollow">ASP.NET AJAX documentation</a> (at least for the AutoComplete TextBox control), if you do not provide the ServicePath property for the control to access, then the method that is to be called (specified in the ServiceMethod property) must be a page method.</p> <p>I read this to say that you can simply create a method in your code behind file that matches the proper signature that the AutoComplete is expecting and you should be all set.</p>
Trace and Debug statements <p>Im a little confused over how to use the .NET Trace and Debug classes.</p> <p>Why would you bother using Trace instead of Debug?</p> <pre><code>Trace.TraceError() Trace.TraceInformation() Trace.Assert() Debug.WriteLine() Debug.Assert() </code></pre> <p>Also, I understand that Debug statements are ignored when your in Release config mode, but If trace statements apply all the time, how does this affect performance?</p>
<p>At the simplest level, they have different compilation switches - i.e. <code>Debug.WriteLine</code> etc is only toggled if you have the <code>DEBUG</code> compilation symbol (not common for release builds), where-as <code>Trace.WriteLine</code> will usually be included even in release builds.</p> <p>The <code>Trace</code> route has customizable trace-listeners, that can be plumbed in via configuration; <code>Debug</code> generally goes to a debugger as the listener. Of course, there are 3rd-party trace systems that offer much more flexibility.</p>
Working with large wsdl, can we trim it? <p>My webservice provider give me a large WSDL file, but we are going to use only a few function inside.</p> <p>I believe that the large WSDL have negative impact to the application performance.</p> <p>We use the webservice in client appliction, <strong>startup time</strong> and <strong>memory usage</strong> are issues. Large WSDL means that jax-ws will takes longer to do binding and will takes more memory for the stub class.</p> <p>Is is possible that we trim WSDL file to a lightweight version? Are there any tool for this purpose?</p> <p>I do not think my webservice provider will generate another WSDL for us. We may have to <strong>do it auto in the build script</strong>.</p>
<p>In short, your answers are "No tool, but you can DIY".</p> <p>I wish there are simple tool can do it because my WSDL contains too many unused function and schema of data structure.</p> <p>If I can automate it, WSDL -> trimmed WSDL -> generate client stubs classes. Nothing unused will be generated, no misuse, no maintenances required, we will not touch on the generated code, and I can really focus on the code which in use. Smaller JAR, shorter XML parse time. If the WSDL get updated, I will had only to rebuild client stubs classes and run unit test.</p> <p>I tried to keep off from human invoked. It takes time, easily to get mistake, and have to redo every time every little change on the original WSDL.</p> <p>I am not conversant on the WSDL schema. I am thinking can it be done by XSLT?</p>
Layering images in CSS - possible to put 2 images in same element? <p>Supposing I'm setting a background image for a web page in CSS like this:</p> <pre><code>body { font-size: 62.5%; /* Resets 1em to 10px */ font-family: Verdana, Arial, Sans-Serif; background-color: #9D5922; color: #000; margin-left: auto; margin-right: auto; margin: 0; padding: 0; background: url(images/desk.gif) repeat bottom left; } </code></pre> <p>Is there any way to layer a second image on top of the desk.gif within the body element itself, or is the only way to create a separate class and use the z axis?</p> <p>Sorry, it's a simpleminded question, but I've been trying to figure this out and though I haven't been able to make it work, I also haven't found a clear slapdown of the idea anywhere online... so, is there a way, or is this just a no can do?</p> <p>Thanks!</p>
<p>Layered backgrounds are part of the <a href="http://www.w3.org/TR/css3-background/#layering" rel="nofollow">CSS3 Working Draft</a> but, as far as I know, support for them is limited to WebKit/KHTML-based browsers such as Safari, Chrome, Konqueror and OmniWeb.</p> <p>Using your example code, this would look like:</p> <pre><code>body { font-size: 62.5%; /* Resets 1em to 10px */ font-family: Verdana, Arial, Sans-Serif; background-color: #9D5922; color: #000; margin-left: auto; margin-right: auto; margin: 0; padding: 0; background: url("images/top.gif") left bottom repeat, url("images/desk.gif") left bottom repeat; } </code></pre>
Back Button with iFrames <p>I'm using an iframe to display content that has links. When the user clicks around in the iFrame and hits "back," it goes back in the iFrame. This behavior is OK. However, once they're back to the first page of the iFrame and they hit "back" again, the entire window is taken back to the previous page. This is unwanted.</p> <p>To prevent this behavior, I've put a fake "back" button within the iFrame. (In most cases this is bad UI, in this case, it works well). I'd like this fake back button to only go back if the previous page is the iFrame's page -- not the entire page. <strong>When they hit the fake back button in the iFrame, it should only move that iFrame back, nothing else.</strong> Is there a way to do this? Does an iFrame get its own history object?</p> <p>Something that might be of benefit: the domain of the iFrame and the main window can be assumed to be distinct. So, if it's possible to read the "global" history object, I can check to see if the previous page was mine by checking to see if the domain is mine. If the domain is not mine, the fake back button will be hidden or not do anything.</p> <p>Help greatly appreciated, and happy holidays!</p>
<pre><code>document.location.href = document.referrer; </code></pre>
Is it possible to "add" to classpath dynamically in java? <pre><code>java -classpath ../classes;../jar;. parserTester </code></pre> <p>How can i get the functionality in the above command programmatically? Like, is it possible to run as:</p> <pre><code>java parserTester </code></pre> <p>and get the same result? I tried using URLClassLoader but it modifies the classpath and does not add to it.</p> <p>Thanx!</p> <hr> <p>Thanks for the response Milhous. But that is what i am trying to do.. How is it possible to get the jar into the classpath first? I tried using a custom classloader too :(</p> <p>That works.. But sorry that i need to run it only as: java parserTester I would like to know if such a thing is possible???</p> <p>It needs to be so bcoz i have parserTester.java and .class in a separate folder. I need to retain the file structure. The parserTester makes use of a jar in a separate jar folder.</p>
<p>You can use a java.net.URLClassLoader to load classes with any program defined list of URL's you wish:</p> <blockquote> <p>public class URLClassLoader extends SecureClassLoader</p> <p>This class loader is used to load classes and resources from a search path of URLs referring to both JAR files and directories. Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be opened as needed.</p> <p>The AccessControlContext of the thread that created the instance of URLClassLoader will be used when subsequently loading classes and resources.</p> <p>The classes that are loaded are by default granted permission only to access the URLs specified when the URLClassLoader was created.</p> <p>Since: 1.2</p> </blockquote> <p>And a little fancy footwork can extend it to support using wildcarded pathnames to pick up entire directories of JARs (this code has some references to utility methods, but their implementation should be obvious in the context):</p> <pre><code>/** * Add classPath to this loader's classpath. * &lt;p&gt; * The classpath may contain elements that include a generic file base name. A generic basename * is a filename without the extension that may begin and/or end with an asterisk. Use of the * asterisk denotes a partial match. Any files with an extension of ".jar" whose base name match * the specified basename will be added to this class loaders classpath. The case of the filename is ignored. * For example "/somedir/*abc" means all files in somedir that end with "abc.jar", "/somedir/abc*" * means all files that start with "abc" and end with ".jar", and "/somedir/*abc*" means all files * that contain "abc" and end with ".jar". * */ public void addClassPath(String cp) { String seps=File.pathSeparator; // separators if(!File.pathSeparator.equals(";")) { seps+=";"; } // want to accept both system separator and ';' for(StringTokenizer st=new StringTokenizer(cp,seps,false); st.hasMoreTokens(); ) { String pe=st.nextToken(); File fe; String bn=null; if(pe.length()==0) { continue; } fe=new File(pe); if(fe.getName().indexOf('*')!=-1) { bn=fe.getName(); fe=fe.getParentFile(); } if(!fe.isAbsolute() &amp;&amp; pe.charAt(0)!='/' &amp;&amp; pe.charAt(0)!='\\') { fe=new File(rootPath,fe.getPath()); } try { fe=fe.getCanonicalFile(); } catch(IOException thr) { log.diagln("Skipping non-existent classpath element '"+fe+"' ("+thr+")."); continue; } if(!GenUtil.isBlank(bn)) { fe=new File(fe,bn); } if(classPathElements.contains(fe.getPath())) { log.diagln("Skipping duplicate classpath element '"+fe+"'."); continue; } else { classPathElements.add(fe.getPath()); } if(!GenUtil.isBlank(bn)) { addJars(fe.getParentFile(),bn); } else if(!fe.exists()) { // s/never be due getCanonicalFile() above log.diagln("Could not find classpath element '"+fe+"'"); } else if(fe.isDirectory()) { addURL(createUrl(fe)); } else if(fe.getName().toLowerCase().endsWith(".zip") || fe.getName().toLowerCase().endsWith(".jar")) { addURL(createUrl(fe)); } else { log.diagln("ClassPath element '"+fe+"' is not an existing directory and is not a file ending with '.zip' or '.jar'"); } } log.diagln("Class loader is using classpath: \""+classPath+"\"."); } /** * Adds a set of JAR files using a generic base name to this loader's classpath. See @link:addClassPath(String) for * details of the generic base name. */ public void addJars(File dir, String nam) { String[] jars; // matching jar files if(nam.endsWith(".jar")) { nam=nam.substring(0,(nam.length()-4)); } if(!dir.exists()) { log.diagln("Could not find directory for Class Path element '"+dir+File.separator+nam+".jar'"); return; } if(!dir.canRead()) { log.error("Could not read directory for Class Path element '"+dir+File.separator+nam+".jar'"); return; } FileSelector fs=new FileSelector(true).add("BaseName","EG",nam,true).add("Name","EW",".jar",true); if((jars=dir.list(fs))==null) { log.error("Error accessing directory for Class Path element '"+dir+File.separator+nam+".jar'"); } else if(jars.length==0) { log.diagln("No JAR files match specification '"+new File(dir,nam)+".jar'"); } else { log.diagln("Adding files matching specification '"+dir+File.separator+nam+".jar'"); Arrays.sort(jars,String.CASE_INSENSITIVE_ORDER); for(int xa=0; xa&lt;jars.length; xa++) { addURL(createUrl(new File(dir,jars[xa]))); } } } private URL createUrl(File fe) { try { URL url=fe.toURI().toURL(); log.diagln("Added URL: '"+url.toString()+"'"); if(classPath.length()&gt;0) { classPath+=File.pathSeparator; } this.classPath+=fe.getPath(); return url; } catch(MalformedURLException thr) { log.diagln("Classpath element '"+fe+"' could not be used to create a valid file system URL"); return null; } } </code></pre>
About "AUTOMATIC TEXT SUMMARIZER (lingustic based)" <p>I am having "AUTOMATIC TEXT SUMMARIZER (linguistic approach)" as my final year project. I have collected enough research papers and gone through them. Still I am not very clear about the 'how-to-go-for-it' thing. Basically I found "AUTOMATIC TEXT SUMMARIZER (statistical based)" and found that it is much easier compared to my project. My project guide told me not to opt this (statistical based) and to go for linguistic based.</p> <p>Anyone who has ever worked upon or even heard of this sort of project would be knowing that summarizing any document means nothing but SCORING each sentence (by some approach involving some specific algos) and then selecting sentences having score more than threshold score. Now the most difficult part of this project is choosing the appropriate algorithm for scoring and later implementing it.</p> <p>I have moderate programming skills and would like to code in JAVA (because there I'll get lots of APIs resulting in lesser overheads). Now I want to know that for my project, what should be my approach and algos used. Also how to implement them.</p>
<p><a href="http://research.microsoft.com/en-us/um/people/cyl/download/papers/lexical-chains.pdf">Using Lexical Chains for Text Summarization (Microsoft Research)</a></p> <p>An analysis of different algorithms: <a href="http://www.ark.cs.cmu.edu/LS2/images/9/90/DasMartins.2007.pdf">DasMartins.2007</a></p> <p>Most important part in the doc:</p> <blockquote> <p>• Nenkova (2005) analyzes that no system could beat the baseline with statistical significance<br> • Striking result!</p> </blockquote> <p>Note there are 2 different nuances to the <strong>liguistic</strong> approach: </p> <ul> <li>Linguistic rating system (all clear here)</li> <li>Linguistic generation (rewrites sentences to build the summary)</li> </ul>
Possible to generate an iPhone application automatically from another iPhone application? <p>As title; is there any function that can achieve this?</p>
<p>Officially, no. Official apps must be compiled and signed on an OS X machine.</p> <p>In practice, sort of - if you don't mind jailbreaking. For jailbroken phones, gcc and signing tools are available that run on the iPhone. So on jailbroken phones you could have an application that generated new applications. Apple wouldn't let you sell such an app in the App Store, though.</p>
Batching in ADO.NET without DataAdapters <p>Is it possible to implement batching of multiple stored procedure calls (doing updates/deletes) in ADO.NET without resorting to DataAdapters?</p>
<p>You could try using System.Data.SqlClient.SqlCommandSet. It's actually internal, but <a href="http://ayende.com/Blog/archive/2006/09/13/OpeningUpQueryBatching.aspx" rel="nofollow">Ayende made a wrapper to make it public</a>.</p> <p>Code is currently hosted in <a href="http://rhino-tools.svn.sourceforge.net/viewvc/rhino-tools/trunk/rhino-commons/Rhino.Commons/ToPublic/SqlCommandSet.cs?view=markup" rel="nofollow">sourceforge</a>.</p>
Using Git in a Company? <p>At my workplace we have one large Subversion repository which holds about 100 projects. Some projects use each other through svn:externals. Usually all people have read+write access to everything, but sometimes external people and interns have only restricted read/write access to some custom folders so they don't get our crown jewels.</p> <p>How would you structure this in git? Each Project its own repository? how can you reuse code? Can you somehow implement access rights?</p>
<p><strong>Structure:</strong> Yes, 1 project per repository. Git is designed for it to work this way and it does it quite nicely.</p> <p><strong>Reusing Code:</strong> Use <a href="http://git-scm.com/docs/git-submodule">git submodules</a> (very similar to svn:externals, only better)</p> <p><strong>Access rights:</strong> Yes, access control is often built around ssh and public keys. If you want to host it yourself, try <a href="http://scie.nti.st/2007/11/14/hosting-git-repositories-the-easy-and-secure-way">gitosis</a>, but I actually highly recommend a hosted solution, like <a href="http://github.com">GitHub</a>.</p>
Easiest way to move Outlook 2007 emails to GMail? <p>I've decided to move completely away from my old POP3 email accounts and into GMail.</p> <p>I have a lot of archived mail in a Outlook 2007 .pst file.</p> <p>I know I could just forward them from Outlook, but then I would receive them as only one email with a lot of attachments in GMail?</p> <p>How can I move these into my GMail?</p>
<p>The most foolproof way I think is add your Gmail account to Outlook and move the messages within Outlook. Don't have any experience, but Google gives a lot of useful results.</p>
Camellia Ruby Computer Vision Library on OS X <p>Has anyone had any luck getting the <a href="http://camellia.sourceforge.net/" rel="nofollow">Camellia</a> computer vision library to install on OS X? I've been banging my head against a wall trying to get it to install. There is <a href="http://po-ru.com/diary/camellia-and-ruby-on-mac-os-x/" rel="nofollow">only one reference I can find</a> online and it is a bit dated. I've followed the instructions to the T with no luck.</p> <p>I'm hoping one of your brilliant folks on SO can help a dude out.</p>
<p>What exactly is your problem? Is there any error message? Are you trying to compile the library or are you trying to build the gem?</p> <p>The sourcecode of the Camellia library is written in C. If you want to compile the library on your OS X machine you'll need a C <a href="http://en.wikipedia.org/wiki/Compiler" rel="nofollow">compiler</a> (like <a href="http://en.wikipedia.org/wiki/GNU%5FCompiler%5FCollection" rel="nofollow">GCC</a>). The easiest way to get one on OS X is by installing <a href="http://developer.apple.com/TOOLS/xcode/" rel="nofollow">Apple's XCode</a> because GCC is part of this package. You can check if you've GCC installed by entering the command <strong><code>which gcc</code></strong> in a <a href="http://www.osxterminal.com/" rel="nofollow">Terminal</a> window. If this command returns the path to the gcc application (like <strong><code>/usr/bin/gcc</code></strong>) you already have installed GCC. If the command returns nothing, you should install GCC (or XCode, as mentioned before).</p> <p>After that, just follow the steps on the website you mentioned.</p> <p>If that doesn't answer your question, please edit your request and be more specific about the problems and what you want to do.</p>