instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I am trying to monitor my outlook inbox so whenever new emails come in with attachments I save the attachment to some other location. Can anyone help me out?</p>
<p>This is not a complete solution, but it describes some of the fundamental tools you'll be using in the Outlook API.</p> <p>From <a href="http://hspinfo.wordpress.com/tag/outlook-email-using-c/" rel="nofollow noreferrer">Access Outlook Emails with ASP.NET, C#</a>:</p> <pre><code>using Outlook; Outlook.Application oOutlook; Outlook.NameSpace oNs; Outlook.MAPIFolder oFldr; long iAttachCnt; try { oOutlook = new Outlook.Application(); oNs = oOutlook.GetNamespace(”MAPI”); //getting mail folder from inbox oFldr = oNs.GetDefaultFolder(OlDefaultFolders.olFolderInbox); Response.Write(”Total Mail(s) in Inbox :” + oFldr.Items.Count + “&lt;br&gt;”); Response.Write(”Total Unread items = ” + oFldr.UnReadItemCount); foreach (Outlook.MailItem oMessage in oFldr.Items) { StringBuilder str = new StringBuilder(); str.Append(”&lt;table style=’border:1px solid gray;font-family:Arial;font-size:x-small;width:80%;’ align=’center’&gt;&lt;tr&gt;&lt;td style=’width:20%;’&gt;&lt;b&gt;Sender :&lt;/b&gt;&lt;/td&gt;&lt;td&gt;”); str.Append(oMessage.SenderEmailAddress.ToString() + “&lt;/td&gt;&lt;/tr&gt;”); //basic info about message str.Append(”&lt;tr&gt;&lt;td&gt;&lt;b&gt;Date :&lt;/b&gt;&lt;/td&gt;&lt;td&gt;” + oMessage.SentOn.ToShortDateString() + “&lt;/td&gt;&lt;/tr&gt;”); if (oMessage.Subject != null) { str.Append(”&lt;tr&gt;&lt;td&gt;&lt;b&gt;Subject :&lt;/b&gt;&lt;/td&gt;&lt;td&gt;” + oMessage.Subject.ToString() + “&lt;/td&gt;&lt;/tr&gt;”); } //reference and save all attachments iAttachCnt = oMessage.Attachments.Count; if (iAttachCnt &gt; 0) { for (int i = 1; i &lt;= iAttachCnt; i++) { str.Append(”&lt;tr&gt;&lt;td&gt;&lt;b&gt;Attachment(” + i.ToString() + “) :&lt;/b&gt;&lt;/td&gt;&lt;td&gt;” + oMessage.Attachments[i].FileName + “&lt;/td&gt;&lt;/tr&gt;”); } } str.Append(”&lt;/table&gt;&lt;br&gt;”); Response.Write(str.ToString()); } } catch (System.Exception ex) { Response.Write(”Execption generated:” + ex.Message); } finally { GC.Collect(); oFldr = null; oNs = null; oOutlook = null; } </code></pre>
<p><a href="http://www.dimastr.com/redemption/" rel="nofollow noreferrer">Outlook Redemption</a> is the best thing currently to use that I have found. It will allow you to get into the messages and extract the attachments and the message bodies. I am using it now to do just that. It also keeps the security dialogs from appearing when you access the messages.</p> <p>Here is some code I use in a class. I included the constructor and the processing function I use to save off the attachments. I cut out the code that is specific to my needs but you can get an idea of what to use here.</p> <pre><code> private RDOSession _MailSession = new RDOSession(); private RDOFolder _IncommingInbox; private RDOFolder _ArchiveFolder; private string _SaveAttachmentPath; public MailBox(string Logon_Profile, string IncommingMailPath, string ArchiveMailPath, string SaveAttPath) { _MailSession.Logon(Logon_Profile, null, null, true, null, null); _IncommingInbox = _MailSession.GetFolderFromPath(IncommingMailPath); _ArchiveFolder = _MailSession.GetFolderFromPath(ArchiveMailPath); _SaveAttachmentPath = SaveAttPath; } public void ProcessMail() { foreach (RDOMail msg in _IncommingInbox.Items) { foreach (RDOAttachment attachment in msg.Attachments) { attachment.SaveAsFile(_SaveAttachmentPath + attachment.FileName); } } if (msg.Body != null) { ProcessBody(msg.Body); } } } </code></pre> <p>This is how I call it and what is passed</p> <pre><code>MailBox pwaMail = new MailBox("Self Email User", @"\\Mailbox - Someone\Inbox", @"\\EMail - Incomming\Backup", @"\\SomePath"); </code></pre>
38,322
<p>For e.g. if i am storing some files on a network server which is under many hierarchical folders.</p> <p>Then i want to do backup. But i always encounter issue because the file path is more than 255?</p> <p>How can i resolve this issue or work around it?</p>
<p>Preface: I'm assuming the OS of the machine you want to copy the files to is some flavor of Windows.</p> <p>The first part of Mark Bessey's is somewhat correct, however even on modern versions of windows with modern filesystems (NTFS for example) you can still run into problems.</p> <p>I suspect the limitation you're running into is due to MAX_PATH, which is a predefined limit on the length of a path that many APIs on Windows will accept.</p> <p>You may try using <a href="http://en.wikipedia.org/wiki/Robocopy" rel="nofollow noreferrer" title="Robocopy">Robocopy</a> to do the backup as it is able to create paths longer than the MAX_PATH limitation. However, most applications will not be able to access these files.</p> <p>Taring or Zipping the files may be a good plan but it seems unlikely that you'd be able to unzip or untar them to a Windows machine.</p>
<p>Maybe upgrade to an Operating System that's been updated in the last decade or so? Seriously, though - what OS and file system are you using? Even FAT32 supports long path and file names, though any single component of the path is limited to 255 characters.</p> <p>If you've got directories with more than 255 characters in their name, then that's problematic (and a little weird). To work around that issue, you could consider using an archiving utility (tar or zip) run on the server, then ship the archive over to yuor desktop machine.</p>
28,782
<p>Here is my query:</p> <pre><code> Select Top 10 CS.CaseStudyID, CS.Title, CSI.ImageFileName From CaseStudy CS Left Join CaseStudyImage CSI On CS.CaseStudyID = CSI.CaseStudyID And CSI.CSImageID in( Select Min(CSImageID) -- &gt;not really satisfactory From CaseStudyImage Group By CaseStudyID ) Order By CS.CaseStudyID ASC </code></pre> <p>Instead of min(CSImageID) I'd like a random record from my CaseStudyImage table that corresponds to the particular case study</p> <p>Can anyone point me in the right direction pleas?</p>
<p>You can use ranking function and newid() to create randomize order with grouping.</p> <pre><code>WITH CSI AS ( SELECT CSI.CaseStudyID, CSI.ImageFileName, ROW_NUMBER() OVER(PARTITION BY CSI.CaseStudyID ORDER BY newid()) AS RowNumber FROM CaseStudyImage CSI ) SELECT TOP (10) CS.CaseStudyID, CS.Title, CSI.ImageFileName FROM CaseStudy CS LEFT JOIN CSI On CS.CaseStudyID = CSI.CaseStudyID WHERE CSI.RowNumber = 1 ORDER BY CS.CaseStudyID ASC </code></pre>
<p><code>ORDER BY RAND() LIMIT 1</code>?</p>
48,491
<p>Consider an SQL Server table containing:</p> <pre><code>ID ParentID Text === ========= ============= 1 (null) Product 2 (null) Applications 3 1 Background 4 1 Details 5 2 Mobile </code></pre> <p>i fill a SqlDataSet with the table, and now i want to add the Parent-Child relation to the DataSet:</p> <pre><code>public DataRelation( string relationName, DataColumn parentColumn, DataColumn childColumn, bool createConstraints ) </code></pre> <p>Now <a href="http://aspalliance.com/822" rel="nofollow noreferrer">this guy</a> uses:</p> <pre><code>DataRelation relation = newDataRelation("ParentChild", ds.Tables[0].Columns["ID"], //parentColumn ds.Tables[0].Columns["ParentID"] //childColumn, true //createConstraints ); </code></pre> <p>But when i do that i get the exception:</p> <pre><code>This constraint cannot be enabled as not all values have corresponding parent values. </code></pre> <p>People have suggested passing false for <code>createConstraints</code>; but then why does it work for him? </p> <p>And what is a child and what is a parent anyway? i would have thought the <strong>child column</strong> is the column that needs pointing to a parent, and <strong>parent column</strong> is the thing that does the pointing, which would reverse the relation:</p> <pre><code>DataRelation relation = newDataRelation("ParentChild", ds.Tables[0].Columns["ParentID"], //parentColumn ds.Tables[0].Columns["ID"], //childColumn true //createConstraints ); </code></pre> <p>So which is it? Why does his work? What's with the exception? Why can he create the constraint when he has nulls?</p> <p><em>God it's hot in here.</em></p>
<p>Wow no one had the right answer ....</p> <p>The problem is that the example you were reading is under the label "Step 3 - Retrieve Data and Create <strong>Nested Relationships</strong>".</p> <p>If you would like to add a relation between two columns of the SAME TABLE (nested), then you must set the 'Nested" variable to true(before adding it) as is shown on his website.</p> <blockquote> <pre><code>relation.Nested = true; ds.Relations.Add(relation); </code></pre> </blockquote>
<p>One reason why his works might be because all the rows in he result set might have a parentID. Child column is the one that refers and parent column is the one that is being refered by the child column. In other words child refers the parent. So in your case Id is the parent column and parentId is the child column.</p>
36,568
<p>I think that business logic should exist in a model when using an MVC or MVP design pattern, but should be hidden behind a service in a service-oriented architecture.</p> <p>Can a software system use the MVC or MVP design pattern within a service-oriented architecture? If so, where does the model sit?</p>
<p>Well they are totally different animals. MVC is all about presentation of data, controlling the navigation of the user dialog and some business logic in building the data model.</p> <p>SOA is about retrieving data from a service provider.</p> <p>On the client side, you can use SOA within the Model part of the MVC pattern to build up your model with data from a SOA service.</p> <p>On the service side, as there is no presentation and no user dialog, most of the MVC pattern becomes redundant. Furthermore, good SOA design should concentrate on providing a useful service regardless of the underlying data store, so the "model" part becomes largely incidental.</p> <p>It is true that many services are "stateful" (e.g. orders are validated, paid for, dispatched then received), but these states are an integral part of the business logic and don't lend themselves to the session management typical of the MVC pattern. </p>
<p>Good Question. I think MVC and SOA will and must co-exist. MVC is the most sucessful architecture for User to system communication. SOA is an architecture for effective system-system communication. In most organisation, there is a place for both. Therefore I believe they will co-exist. </p> <p>In terms of how they interact with each other, my personal opinion is - MVC will remain (once the SOA hype is gone) as the core architectural pattern with both model and controller exposing service interfaces where appropriate. </p>
44,619
<p>I work in an Oracle shop. There's a toolset that consists of roughly 1000 Oracle Forms (using the Forms builder from 6i, early 90's software) with Oracle 10g on the back end. It's serving roughly 500 unique people a month, with 200 concurrent connections at any given time during the work day.</p> <p>Obviously this is something that needs to be addressed to get rid of the Forms runtime and move to a web based solution. The tools need to be accessed from Windows, Linux, various UNIX's, VMS and Solaris.</p> <p>What options out there exist that would be feasible to migrate to? Not only does it need to be feasible for migration but the development will need to be done by 8 or so engineers who support the tool set (and many of which who would prefer to stay put and not modernize this tool set).</p> <p>Oracle offers a few solutions that convert Oracle Forms into a crappy Java Applet (it's a very terrible temporary solution).</p> <p>My solution of choice has been migrating to Ruby on Rails (which I'm a big proponent of Rails) but this will involve a learning curve (which we'll hit with any solution) for other developers. Also, the other difficulty in this is converting some very complex forms to HTML forms.</p> <p>Has anyone tackled such a solution? Are there any packages offered by anyone outside of Oracle?</p> <p>Any specific Java Web frameworks?</p> <p>Would GWT, jQuery UI, ExtJS or any other JavaScript UI frameworks offer the rich user experience needed?</p> <p>.NET is a consideration but a last resort (mostly because of license costs, there's no room in the budget in addition to what we're paying for Oracle licenses).</p>
<p>That's exactly what I am currently doing using...</p> <p><a href="http://apex.oracle.com/i/index.html" rel="noreferrer">Oracle Application Express</a></p> <p>The learning curve is much smaller than most web-based alternatives for Forms developers, as all the code is in PL/SQL (unless you start getting fancy with Javascript, which you can). Also, in the latest release of Application Express (3.2), there is a <a href="http://www.oracle.com/technology/obe/apex32/apex32frmmigr.htm" rel="noreferrer">tool to convert Forms applications to Apex</a>.</p> <p>It comes free with Oracle versions since 9.2.</p>
<p>Hi i have done a similar work using GWT/springs/ORMS combination, the results are fantastic ,how ever it also depends on the complexity of business process mine was a very very complex business process, what i did was segragate all the layers and treat each layer as a service , in the process i made an application which every one goes wow and at the same time is eligible for many certifications , but if you want to do it more faster and not change the front end u can use exodus cheers </p> <p>vasem </p> <p>vasem_want@yahoo.co.uk </p>
21,702
<p>i've been asked to generate some demographic reports (crime rates, birth/deaths, etc) based on state and cities for the USA. I have all the demographic data (provided by our client) but can't seem to find any places which have the boundaries (read: LAT/LONG's) of the USA States and their cities.</p> <p>Our data are Lat/Long points of data (eg. a crime, a birth, etc) and we want to get some mapped reports and also datamine using Sql server (we're using MS Sql 2008, but that shouldn't impact this question).</p> <p>So .. can anyone direct me to where there are some <em>state and city boundary sources</em>? I know our government has all this information available for free at the <a href="http://www.census.gov/" rel="nofollow noreferrer">US Census Bureau</a>, but i can't seem to understand where it's found and how to digest this info.</p> <p>I'm assuming that this info will be in the form of lat/long polygons (eg. a shapefile, etc) which i can then import into the DB and mine away.</p> <p>Can anyone help, please?</p>
<p>A bit late, but in case anyone stumbles across this like I did:</p> <p>To get the city boundary layers you navigate to "Download Shapefiles" for the year you're interested in and drop down to the city boundary layer, which is called "Places". (which is not an intuitive enough name for me...)</p> <p><a href="http://www.census.gov/cgi-bin/geo/shapefiles2011/main">http://www.census.gov/cgi-bin/geo/shapefiles2011/main</a></p> <p>That's the link for 2011's shapefiles.</p>
<p>I think you are looking for <a href="http://en.wikipedia.org/wiki/Geographic_information_system" rel="nofollow noreferrer" title="Geographic information system - Wikipedia, the free encyclopedia">GIS data</a>. For example, I found <a href="http://data.geocomm.com/catalog/US/61088/group214.html" rel="nofollow noreferrer" title="US Census Bureau TIGER/Line 2007FE Shapefiles Mississippi, United States">US Census Bureau TIGER/Line 2007FE Shapefiles Mississippi, United States</a> although I am not sure what you get with the download nor how to exploit the information...</p> <p>HTH.</p>
45,892
<p>I have this string</p> <pre><code>'john smith~123 Street~Apt 4~New York~NY~12345' </code></pre> <p>Using JavaScript, what is the fastest way to parse this into</p> <pre><code>var name = "john smith"; var street= "123 Street"; //etc... </code></pre>
<p>With JavaScript’s <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split" rel="noreferrer"><code>String.prototype.split</code></a> function:</p> <pre><code>var input = 'john smith~123 Street~Apt 4~New York~NY~12345'; var fields = input.split('~'); var name = fields[0]; var street = fields[1]; // etc. </code></pre>
<p>Use this code --</p> <pre><code>function myFunction() { var str = "How are you doing today?"; var res = str.split("/"); } </code></pre>
12,203
<p>I'm trying to print the following model:</p> <p><a href="https://i.stack.imgur.com/b8cSN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b8cSN.jpg" alt="View 1" /></a></p> <p><a href="https://i.stack.imgur.com/HGgi3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HGgi3.jpg" alt="View 2" /></a></p> <p>I'm using <a href="https://www.simplify3d.com/" rel="nofollow noreferrer">Simplify3d</a> to print the model with the following settings on my <a href="https://www.qd3dprinter.com/" rel="nofollow noreferrer">Qidi X-pro</a>:</p> <ul> <li>Filament is ABS</li> <li>Bed temp is 100 °C</li> <li>Extruder temp is 230 °C</li> <li>1 top layer</li> <li>1 bottom layer</li> <li>4 perimeter shells</li> <li>The outside direction is 'outside in'.</li> <li>Internal infill is triangular at 60 %.</li> </ul> <p>I've tried numerous tweaks to the settings, but, I can't seem to get a perfect perpendicular exterior wall as seen in the photos. The print more resembles a trapezoid. It appears like the walls are bowing inward. This also seems to throw off the dimensions. They aren't consistent. For example, the height of the part is 6 mm, but, in measuring with a caliper it shows 5.8 mm to 6.2 mm.</p> <p>Can anyone tell me how I can get my external walls perpendicular?</p>
<p>You may be getting shrinking due to cooling on the non-top and non-bottom layers. Sixty percent infill is rather substantial. I'm printing 20 hour pieces in ABS at 100 °C / 250 °C using ten percent infill and getting nothing like what your image shows.</p> <p>Can you do with a lower infill? More isn't always stronger. Four perimeter shells may be a factor but you'll probably see a difference with a smaller percentage infill.</p>
<p>If your object doesn't need to be flexible and can tolerate a more brittle material, PLA has better dimensional accuracy. Thus, it would be easier to get your desired shape.</p> <p>Try two perimeter shells, but slow down the print speed of the perimeter.</p>
1,928
<p>We have a custom project management tool built in ASP,net 3.5 and we use VisualSVN for our version management. However, we are looking a way to report the version changes through the project management tool by integrating VisualSVN with our project management tool, i.e. pretty much similar to what Trac [python based SCM tool] provides. </p> <p>Basically looking for a simple VisualSVN Client API to be able to detect &amp; report the file changes based on the revision set provided.</p>
<p>There is also <a href="http://sharpsvn.open.collab.net/" rel="nofollow noreferrer">SharpSvn</a> wich encapsulates the whole Subversion 1.5 client api. It's is licensed under the Apache 2.0 license and it's from CollabNet.</p>
<p>Check <a href="http://www.pumacode.org/projects/svndotnet/" rel="nofollow noreferrer">Svn.NET</a> I think is the best solution for right now .NET bindings of the Subversion client system libraries.</p>
36,861
<p>I have a table like the following:</p> <pre><code>transaction_id user_id other_user_id trans_type amount </code></pre> <p>This table is used to maintain the account transactions for a finance type app.</p> <p>Its double entry accounting so a transfer from User A to B would insert two rows into the table looking like.</p> <pre><code>1, A, B, Sent, -100 1, B, A, Received, 100 </code></pre> <p>The balance on any account is calculated by summing up the transactions for that account.</p> <p>For example:</p> <pre><code>select sum(amount) from transactions where user_id=A </code></pre> <p>What is the best way to lock down transferring of funds? My current code looks like:</p> <pre><code>Start Transaction Debit the sender's account check the balance of the sender's account if new balance is negative then the sender didn't have enough money and rollback if the balance is positive then credit the receiver and commit </code></pre> <p>This seems not to be working exactly as expected. I see a lot of examples online about transactions that say basically: start, debit sender, credit receiver, commit. But what is the best way to check the sender's balance in between?</p> <p>I have transactions getting through that shouldn't. Say a user has a balance of 3K and two transactions come in at exactly the same time for 3K, both of these are getting through when only one should.</p> <p>Thank you</p>
<p>Are you using InnoDB tables or MyISAM tables? MySQL doesn't support transactions on MyISAM tables (but it won't give you an error if you try to use them). Also, make sure your transaction isolation level is set appropriately, it should be SERIALIZABLE which is not the default for MySQL. </p> <p>This <a href="http://www.informit.com/articles/article.aspx?p=26890&amp;seqNum=3" rel="noreferrer">article</a> has a good example that explains the impact of the different isolation levels using an example very similar to yours.</p>
<p>The problem is that the concept of the "user account" is "scattered" through many rows in your table. With the current representation, I think you can't "lock the user account" (so to speak), so you are open to race conditions when modifying them.</p> <p>A possible solution would be to have another table with user accounts, and lock a row in that table , so anybody needing to modify the account can try to obtain the lock, do the operation, and release the lock.</p> <p>For instance:</p> <pre><code>begin transaction; update db.accounts set lock=1 where account_id='Bob' and lock=0; if (update is NOT successful) # lock wasn't on zero { rollback; return; } if (Bob hasn't enough funds) { rollback; return; } insert into db.transactions value (?, 'Bob', 'Alice', 'Sent', -3000); insert into db.transactions value (?, 'Alice', 'Bob', 'Received', 3000); update db.accounts set lock=0 where account_id='Bob' and lock=1; commit; </code></pre> <p>... or something like that.</p>
37,345
<p>I have inherited a client site which crashes every 3 or 4 days. It is built using the zend-framework with which I have no knowledge.</p> <p>The following code:</p> <pre><code>&lt;?php // Make sure classes are in the include path. ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes'); // Use autoload so include or require statements are not needed. require_once 'Zend/Loader.php'; Zend_Loader::registerAutoload(); // Run the application. App_Main::run('production'); </code></pre> <p>Is causing the following error:</p> <pre> [Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Warning: require_once(Zend/Loader.php) [function.require-once]: failed to open stream: No such file or directory in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6 [Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Fatal error: require_once() [function.require]: Failed opening required 'Zend/Loader.php' (include_path='.:.:/usr/share/php5:/usr/share/php5/PEAR') in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6 </pre> <p>I don't even know where to begin trying to fix this. My level of knowledge of PHP is intermediate but like I said, I have no experience with Zend. Also, contacting the original developer is not an option.</p> <p>The interesting thing is that even though the code is run every time a page of the site is hit the error is only happening every now and then.</p> <p>I believe it must be something to do with the include_path but I am not sure.</p>
<p>for a start I think your include path should maybe have a trailing slash. Here is an example of mine :</p> <pre><code> set_include_path('../library/ZendFramework-1.5.2/library/:../application/classes/:../application/classes/excpetions/:../application/forms/'); </code></pre> <p>You bootstrap file will be included by another file (probably an index.php file). This means that if your include path is relative (as mine is) instead of absolute, then the path at which Loader.php is looked for changes if the file including bootstrap.php changes.</p> <p>For example, I have two index.php files in my Zend app, one for the front end, and one for the admin area. These index files each need there own bootstrap.php with different relative paths in because they are included by different index files, which means they <strong>have to be relative to the original requested index file, not the bootstrap file they are defined within</strong>.</p> <p>This could explain why your problem is intermittent, there could be another file including the bootstrap somewhere that is only used occasionally. I'd search through all the sites files for 'bootstrap.php' and see all the places which are including / requiring this file.</p>
<p>It works sometimes so there isn't anything inherently wrong on the PHP end of things (if the path was wrong it would never work... but it does, yes?). So what is causing Loader.php to be periodically inaccessible? I would suspect a permissions problem. Something that is making Loader.php or the directory that it is in inaccessible. Maybe a cron job is setting/reseting permissions? Check that first. See what permissions are when it is working and what they are when it is not. </p>
6,037
<p>I have an object I am using to store document meta data into a table. The body text of the document can be very large, sometimes > 2GB so I will be storing it into a nvarchar(max) field in SQL 2008. I'll use SQL 2008 later to index that field. I won't be using filestreams because they are very restrictive to the database and prevents certain types of concurrency locking schemes.</p> <p>This object is exposed to the developer via LinqToSQL. My concern is that the field will be to large and I have seen .Net bomb out with an OutOfMemory exception if the text is > 1.5 GB. </p> <p>So I am wondering, can I treat this blob as a stream with Linq? Or do I have to bypass Linq altogether if I want to use a blob?</p>
<p>Given the answer to <a href="https://stackoverflow.com/questions/53873/can-a-linq-query-retrieve-blobs-from-a-sql-database">"Can a LINQ query retrieve BLOBs [...]"</a> I <em>suspect</em> you're out of luck. The <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.binary.aspx" rel="nofollow noreferrer">System.Data.Linq.Binary</a> type doesn't have any mechanism for streaming - basically it's just an immutable byte array representation.</p> <p>There may be some deep LINQ mojo you could invoke, but I suspect it would really have to be pretty deep.</p> <p>It's possible that the Entity Framework would handle it - I haven't investigated that.</p>
<p>I ended up writing my own method around linqtoSql utlising the write method avaiable to varchar(max) objects in SQL. This allows developers to chunk inserts into the DB for large data types.</p>
36,869
<p>I have potentially large files that need to be sorted by 1-n keys. Some of these keys might be numeric and some of them might not be. This is a fixed-width columnar file so there are no delimiters.</p> <p>Is there a good way to do this with Unix sort? With one key it is as simple as using '-n'. I have read the man page and searched Google briefly, but didn't find a good example. How would I go about accomplishing this?</p> <p>Note: I have ruled out Perl because of the file size potential. It would be a last resort.</p>
<p>Take care though:</p> <p>If you want to sort the file primarily by field 3, and secondarily by field 2 you want this:</p> <pre><code>sort -k 3,3 -k 2,2 &lt; inputfile </code></pre> <p><strong>Not this:</strong> <code>sort -k 3 -k 2 &lt; inputfile</code> which sorts the file by the string from the beginning of field 3 to the end of line (which is potentially unique).</p> <pre><code>-k, --key=POS1[,POS2] start a key at POS1 (origin 1), end it at POS2 (default end of line) </code></pre>
<p>I just want to add some tips, when you using sort , be careful about your locale that effects the order of the key comparison. I usually explicitly use LC_ALL=C to make locale what I want.</p>
46,622
<p>I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing. I have found several method in web framework such as django or turbogears.</p> <p>I just want a kind of username-password association stored into a local file. I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).</p>
<p>dbr said:</p> <blockquote> <pre><code>def hash_password(password): """Returns the hashed version of a string """ return hasher.new( str(password) ).hexdigest() </code></pre> </blockquote> <p>This is a really insecure way to hash passwords. You <em>don't</em> want to do this. If you want to know why read the <a href="http://www.openbsd.org/papers/bcrypt-paper.pdf" rel="noreferrer" title="&quot;B-Crypt Paper">Bycrypt Paper</a> by the guys who did the password hashing system for OpenBSD. Additionally if want a good discussion on how passwords are broken check out <a href="http://www.securityfocus.com/columnists/388" rel="noreferrer">this interview</a> with the author of Jack the Ripper (the popular unix password cracker).</p> <p>Now B-Crypt is great but I have to admit I don't use this system because I didn't have the EKS-Blowfish algorithm available and did not want to implement it my self. I use a slightly updated version of the FreeBSD system which I will post below. The gist is this. Don't just hash the password. Salt the password then hash the password and repeat 10,000 or so times.</p> <p>If that didn't make sense here is the code: </p> <pre><code>#note I am using the Python Cryptography Toolkit from Crypto.Hash import SHA256 HASH_REPS = 50000 def __saltedhash(string, salt): sha256 = SHA256.new() sha256.update(string) sha256.update(salt) for x in xrange(HASH_REPS): sha256.update(sha256.digest()) if x % 10: sha256.update(salt) return sha256 def saltedhash_bin(string, salt): """returns the hash in binary format""" return __saltedhash(string, salt).digest() def saltedhash_hex(string, salt): """returns the hash in hex format""" return __saltedhash(string, salt).hexdigest() </code></pre> <p>For deploying a system like this the key thing to consider is the HASH_REPS constant. This is the scalable cost factor in this system. You will need to do testing to determine what is the exceptable amount of time you want to wait for each hash to be computed versus the risk of an offline dictionary based attack on your password file. </p> <p>Security is hard, and the method I present is not the best way to do this, but it is significantly better than a simple hash. Additionally it is dead simple to implement. So even you don't choose a more complex solution this isn't the worst out there.</p> <p>hope this helps, Tim</p>
<p>Use " md5 " it's much better than base64</p> <pre><code>&gt;&gt;&gt; import md5 &gt;&gt;&gt; hh = md5.new() &gt;&gt;&gt; hh.update('anoop') &gt;&gt;&gt; hh.digest &lt;built-in method digest of _hashlib.HASH object at 0x01FE1E40&gt; </code></pre>
9,607
<p>I would like to refer HTML templates designed/developed especially for form based Web Applications.</p> <p>I have been searching them but am not able to find out which I find better.</p> <p>Regards, Jatan</p>
<p>Much of the choice in this sort of thing is going to be defined by your choice of server tech / platform, e.g. .NET has in built widgets you can use, as do many web application frameworks.</p> <p>The django admin layouts are extremely well designed, you could download <a href="http://www.djangoproject.com/" rel="nofollow noreferrer">Django</a> and check it out.</p> <p>Similar forms are also implemented for Rails by the <a href="http://streamlinedframework.org/" rel="nofollow noreferrer">Streamlined framwork</a>, not to mention the inbuilt scaffolding generators.</p> <p>Tthe YUI framework has a bunch of different widgets with a consistent style, as does the ExtJS framework, and are server technology agnostic. These can be dynamically created using json as the data source, rather than html/xml </p> <p>You could also use a CSS framework such as BlueprintCSS, and combine it with the suggested HTML, and add effects + interactions with jQuery, and build that on top of your html.</p> <p>Modifying an existing layout is not too hard, for a simple CRUD application you probably just need a large area for forms and lists/tables and a menu.</p> <p>If you need anything more particular than that, its probably time to invest in a design, or learn to do it yourself.</p> <p>The simplest possible layout is going to be a header with a menu inside (&amp; maybe a heading), and a content area for your forms. </p> <hr> <pre><code>&lt;style type="text/css" media="screen"&gt; div#page { width:900px; margin:0; auto; } &lt;/style&gt; &lt;body&gt; &lt;div id="page"&gt; &lt;div id="header"&gt; &lt;!-- Menu Goes Here! --&gt; &lt;/div&gt; &lt;div id="content"&gt; &lt;!-- Put some Forms n stuff here --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre>
<p>I personally like <a href="http://themeforest.net/" rel="nofollow noreferrer">ThemeForest</a>. They have a large selection and includes the raw markup and css scripts so you can make your forms app look like the template in no time.</p>
17,788
<p>I have a Windows form application written in C#. I update the title of the form frequently, but there's a substantial lag between the title changing and the title dislayed in the taskbar being updated. </p> <p>What's a clean way to force an update / redraw of the task bar's entry for my program? Failing that, how can I force a redraw of the entire task bar?</p> <p>Elaboration: It turns out that the delay in updating the taskbar is fixed at about 100ms, however this seems to be a delay based on when the Form.Text was last modified. If you modify the text faster then that - say, every 10ms, the taskbar is not updated until the Form.Text has been left unchanged for at least ~100ms.</p> <p>OS: Vista 32.</p>
<p>Did you try to call Form.Refresh() after updating the title?</p> <p>Edit:</p> <p>If you are doing the title updates in a loop you might have to do something along the line of:</p> <pre><code> this.Invalidate(); this.Update(); Application.DoEvents(); </code></pre>
<p>I just did a simple test. The changes are quite instantaneous. From the look of it, it's definitely less than 500ms. If you need to update the title at a higher rate, I won't really recommend it. Generally I've seen the fastest update rate of twice per second.</p> <p>EDIT: I tested using keypress event. When I hold down the key for a fast repeat, it won't update until I've release my key. Thus, same scenario as your setup. </p> <p>Btw, why do you need to update every 10ms? Just keep in mind that <code>Thread.Sleep(timeout)</code> with timeout of less than 50ms is not accurate. Also, 10ms timeout will equal to 100Hz, unless you're using high end display, you'll have miss a few frame. Most general LCD have a refresh rate of 60Hz. And our eye can't differentiate anything faster than 25Hz. Thus 40ms delay is more than enough, if you want to animate. Generally I would recommend 15Hz (67ms) for simple animation. If just want to scroll some text, 2Hz is more than enough. Anything faster will make the user dizzy.</p>
49,845
<p>the new keyboard from Microsoft, <a href="http://www.microsoft.com/hardware/gaming/productdetails.aspx?pid=102" rel="nofollow noreferrer">Sidewinder x6</a> can record in game macro. I was woundering if it could be used in Visual Studio (record key in application too)?</p> <p>(This could be very useful to press 1 key instead of Ctrl+M,M to Toggle Outline.)</p>
<p>YES IT CAN! Sure, why not? Okay, some reasoning behind my answer.</p> <p>Just create a "gaming profile" for devenv.exe instead of a game. BAM! There you go.</p>
<p>Yes its perfect for vs2008. A+++++++++ </p>
18,222
<p>I have a dictionary that I normally access with a key, so I need fast random access reads. However for one function I need to process every item in the dictionary where the order is important. It seems to be working OK in tests. Is it OK to depend on the order of items in a dictionary?</p>
<p>No. If you need to keep an order, you should have a list of items as well. You could encapsulate all the operations you need in your own collection class, which would update both the dictionary and the list at the same time.</p> <p>It's unfortunate that .NET doesn't have a dictionary which supports this itself - it's a reasonably common request - Java does, as <a href="http://java.sun.com/javase/6/docs/api/java/util/LinkedHashMap.html" rel="noreferrer">LinkedHashMap</a>.</p>
<p>No. You're better off using a <a href="http://msdn.microsoft.com/en-us/library/f7fta44c.aspx" rel="nofollow noreferrer">SortedDictionary</a> if you want to keep your keys in an order.</p> <p>Edit: Either that, or add your keys to a linked list if you want to keep track of the order you added the items.</p>
32,224
<p>Is it possible to run an external process from Perl, capture its stderr, stdout AND the process exit code?</p> <p>I seem to be able to do combinations of these, e.g. use backticks to get stdout, IPC::Open3 to capture outputs, and system() to get exit codes.</p> <p>How do you capture stderr, stdout, and the exit code all at once?</p>
<p>If you reread the documentation for IPC::Open3, you'll see a note that you should call <a href="http://perldoc.perl.org/functions/waitpid.html" rel="noreferrer">waitpid</a> to reap the child process. Once you do this, the status should be available in <code>$?</code>. The exit value is <code>$? &gt;&gt; 8</code>. See <a href="http://perldoc.perl.org/perlvar.html#&#36;CHILD_ERROR" rel="noreferrer"><code>$?</code> in perldoc perlvar</a>.</p>
<p>If you're getting really complicated, you might want to try Expect.pm. But that's probably overkill if you don't need to also manage sending input to the process as well.</p>
13,439
<p><a href="http://pear.php.net/manual/en/package.database.db-dataobject.php" rel="nofollow noreferrer">DB_DataObject</a> does not appear to be ActiveRecord because you do not necessarily store business logic in the "table" classes. It seems more like Table Data Gateway or Row Data Gateway, but I really cannot tell. What I need is good ORM layer that we can use with DataMapper and a DomainModel. Any ideas?</p>
<p>Follow <a href="http://pear.php.net/manual/en/package.database.db-dataobject.intro-purpose.php" rel="nofollow noreferrer">this link</a> to read what DB_DO is. In a nutshell, it doesn't implement a specific pattern, it just aims to provide a common interface. The idea is to not rebuild the same basic code in each project.</p> <p>As for an ORM, I'd recommend <a href="http://phpdoctrine.org/" rel="nofollow noreferrer">Doctrine</a>. It implements ActiveRecord.</p>
<p>It sounds like what you're looking for is something like <a href="http://ibatis.apache.org/" rel="nofollow noreferrer">IBatis</a> for PHP. Sadly, this doesn't yet exist. I've actually written some custom DataMapper stuff based on PDO for the current application I'm working on to achieve a persistence ignorant domain layer. It's definitely more work to develop and maintain though, so I would suggest if at all possible, go with an existing data layer implementation like Doctrine for most of your needs.</p>
5,971
<p>I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this:</p> <pre><code> def Review(models.Model) ...fields... overall_score = models.FloatField(blank=True) def Score(models.Model) review = models.ForeignKey(Review) question = models.TextField() grade = models.IntegerField() </code></pre> <p>A Review is has several "scores", the overall_score is the average of the scores. When a review or a score is saved, I need to recalculate the overall_score average. Right now I'm using a overridden save method. Would there be any benefits to using Django's signal dispatcher?</p>
<p>Save/delete signals are generally favourable in situations where you need to make changes which aren't completely specific to the model in question, or could be applied to models which have something in common, or could be configured for use across models.</p> <p>One common task in overridden <code>save</code> methods is automated generation of slugs from some text field in a model. That's an example of something which, if you needed to implement it for a number of models, would benefit from using a <code>pre_save</code> signal, where the signal handler could take the name of the slug field and the name of the field to generate the slug from. Once you have something like that in place, any enhanced functionality you put in place will also apply to all models - e.g. looking up the slug you're about to add for the type of model in question, to ensure uniqueness.</p> <p>Reusable applications often benefit from the use of signals - if the functionality they provide can be applied to any model, they generally (unless it's unavoidable) won't want users to have to directly modify their models in order to benefit from it.</p> <p>With <a href="https://github.com/django-mptt/django-mptt/" rel="noreferrer">django-mptt</a>, for example, I used the <code>pre_save</code> signal to manage a set of fields which describe a tree structure for the model which is about to be created or updated and the <code>pre_delete</code> signal to remove tree structure details for the object being deleted and its entire sub-tree of objects before it and they are deleted. Due to the use of signals, users don't have to add or modify <code>save</code> or <code>delete</code> methods on their models to have this management done for them, they just have to let django-mptt know which models they want it to manage.</p>
<p>If you'll use signals you'd be able to update Review score each time related score model gets saved. But if don't need such functionality i don't see any reason to put this into signal, that's pretty model-related stuff.</p>
20,552
<p>I hope I can explain this clearly enough, but if not let me know and I'll try to clarify.</p> <p>I'm currently developing a site using ColdFusion and have a mod_rewrite rule in place to make it look like the site is using PHP. Any requests for index.php get processed by index.cfm (the rule maps *.php to *.cfm).</p> <p>This works great - so far, so good. The problem is that I want to return a 404 status code if index.cfm (or any ColdFusion page) is requested directly.</p> <p>If I try to block access to *.cfm files using mod_rewrite it also returns a 404 for requests to *.php.</p> <p>I figure I might have to change my Apache config rather than use .htaccess</p>
<p>You can use the <code>S</code> flag to skip the <code>404</code> rule, like this:</p> <pre><code>RewriteEngine on # Do not separate these two rules so long as the first has S=1 RewriteRule (.*)\.php$ $1.cfm [S=1] RewriteRule \.cfm$ - [R=404] </code></pre> <p>If you are also using the <code>Alias</code> option then you should also add the <code>PT</code> flag. See the <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html" rel="nofollow noreferrer">mod_rewrite documentation</a> for details.</p>
<p>Post the rules you already have as a starting point so people don't have to recreate it to help you.</p> <p>I would suggest testing [L] on the rule that maps .php to .cfm files as the first thing to try.</p>
3,032
<p>I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?</p> <p>(I'm not asking about <code>$('p.foo')</code> syntax that you see in jQuery and others, but normal variables like <code>$name</code> and <code>$order</code>)</p>
<p>Very common use in <strong>jQuery</strong> is to distinguish <strong>jQuery</strong> objects stored in variables from other variables. </p> <p>For example, I would define:</p> <pre><code>var $email = $("#email"); // refers to the jQuery object representation of the dom object var email_field = $("#email").get(0); // refers to the dom object itself </code></pre> <p>I find this to be very helpful in writing <strong>jQuery</strong> code and makes it easy to see <strong>jQuery</strong> objects which have a different set of properties.</p>
<p>The reason I sometimes use php name-conventions with javascript variables: When doing input validation, I want to run the exact same algorithms both client-side, and server-side. I really want the two side of code to look as similar as possible, to simplify maintenance. Using dollar signs in variable names makes this easier.</p> <p>(Also, some judicious helper functions help make the code look similar, e.g. wrapping input-value-lookups, non-OO versions of strlen,substr, etc. It still requires some manual tweaking though.)</p>
25,221
<p>I've somehow managed to get an SVN repository into a bad state. I've moved a directory and now I can't commit it in its new location.</p> <p>As far as <code>svn status</code> is concerned, the directory is unknown (the name of the directory is <code>type</code>).</p> <pre> $ svn status ? type </pre> <p>When I try to add the directory, the server says it already exists.</p> <pre> $ svn add type svn: warning: 'type' is already under version control </pre> <p>If I try to update the directory, it's gone again.</p> <pre> $ svn update type svn: '.' is not under version control </pre> <p>If I try to commit it, the server complains that it's old parent directory no longer exists.</p> <pre> $ svn commit type -m "Moving type" svn: Commit failed (details follow): svn: '/prior/trunk/src/nyu/prior/cvc3/theorem_prover/expression' path not found </pre> <p>To add to the mystery, the contents of the directory are marked as modified.</p> <pre> $ svn status type A + type M + type/IntegerType.java M + type/BooleanType.java M + type/Type.java M + type/RationalRangeType.java M + type/RationalType.java M + type/IntegerRangeType.java </pre> <p>If I try to update from within the directory, I get this.</p> <pre> $ cd type $ svn update svn: Two top-level reports with no target </pre> <p>Committing from within the directory gives the same <code>path not found</code> error as above.</p> <p>What's going on and how do I fix it?</p> <p>EDIT: @Rob Oxspring caught me out: I got too aggressive moving things around in Eclipse.</p> <p>UPDATE: I'm accepting @Rob Oxspring's answer of "don't do that/just start over" and taking his advice. I'd still be interested if anybody could tell me: (a) what the above error messages <em>mean</em> precisely and (b) how to actually <em>fix</em> the problem.</p>
<p>It looks to me like <code>type</code> was created by some Subversion-aware copy command, then moved into the current directory using a Subversion-unaware copy. In my experience, this sort of thing typically occurs when package refactoring operations have been chained together in Eclipse without commits in between. Typically, Subversion doesn't handle it well when you copy/move a locally copied/moved file or folder, although I think version 1.5 may handle it better.</p> <p>To avoid this in the future, commit between such steps. If you'd like to hide the intervening commits then I'd recommend doing the multi-step refactoring on a branch and then merging the changes back into the mainline in that single commit you were after.</p> <p>If it's not too much work, then I'd recommend getting back to a clean working copy and redoing your changes, committing after each step. If you're happy to lose the history, i.e. allowing the new <code>IntegerType.java</code> to not be linked at all to the old <code>IntegerType.java</code>, then you could take the approach suggested by BCS:</p> <ul> <li>Move your changed files into some temporary location, stripping out any <code>.svn</code> directories</li> <li>Update your working copy into a clean working state</li> <li>Copy your changes back to where you want them to be</li> <li>Commit the resulting working copy</li> </ul>
<p>My experience is that sometimes the local copy gets out of sync with the repository. I usually solve this by going up the local directory tree, starting from the directory with the problem and try to do do cleanup and update with each step.</p>
6,922
<p>I'm attempting to put together some basic report screens. I've got some fairly complicated SQL queries that I'm feeding into ActiveRecord's find_by_sql method. The problem I am having here is that I am losing the order of the columns as given in the original query. I'm assuming that this is because the Hash class does not preserve entry order of its keys. </p> <p>Is there a way around this problem? Should I be using a different method then find_by_sql for my queries?</p>
<p>You're correct in that the Ruby Hash does not preserve order. That's part of the point, really - you access it using the key.</p> <p>I assume your query is written to deliver the columns in the order that you want to output them and you were hoping to output the values via a loop? Seems like a decent enough idea, but I can't think of a way to achieve it without at least some extra work.</p> <p>What I'd recommend is to explicitly access the columns by key in your template, since you're probably going to end up applying styles, formatting using helper functions like number_with_delimiter, that kind of thing.</p> <p>To get something like the shortcut mentioned above, I suppose you could create an array of symbols in the order required and pull the values out of the hash in a loop. Something like this? (please excuse the potentially dodgy erb: I'm a <a href="http://haml.hamptoncatlin.com/" rel="nofollow noreferrer">haml</a> user!)</p> <pre><code>&lt;% for row in @report.rows %&gt; &lt;tr&gt; &lt;% for col in [:a, :b, :c] %&gt; &lt;td&gt;&lt;%= row[col] %&gt;&lt;/td&gt; &lt;% end %&gt; &lt;/tr&gt; &lt;% end %&gt; </code></pre>
<p>How are you creating these "report screens"? Are they erb templates? Are you just calling .each on columns to print them all out?</p> <p>If that's the case you could override the columns() method in your models to return an ordered array.</p>
25,721
<p>I have an HttpHandler on my webserver that takes a URL in the form of "<a href="https://servername/myhandler?op=get&amp;k=Internal&amp;m=jdahug1" rel="nofollow noreferrer">https://servername/myhandler?op=get&amp;k=Internal&amp;m=jdahug1</a>". I need to call this URL from my .NET app and capture whatever the output is. Does anyone know how I can do that? I want it to be simple so that I just get back a string with the output, and that I can specify my own timeout.</p> <ul> <li>Thanks!</li> </ul>
<p>Try the System.Net.WebClient class.</p> <p>You can use the .DownloadStringAsync() method to enforce a timeout.</p>
<p>we have used the following in the backend of our product (this is just the core code, not with timeout errorhandling etc.)</p> <pre><code>using System.Net; using System.IO; HttpWebRequest req = (HttpWebRequest) WebRequest.Create(WebPageUrl); WebResponse resp = req.GetResponse(); Stream stream = resp.GetResponseStream(); StreamReader reader = new StreamReader(stream); output.Write(reader.ReadToEnd()); </code></pre>
24,642
<p>I'm researching a bug that looks like some kind of timing issue and so I'm a bit curious about how events work in Delphi 7. What happens is we get some data sent to our application through a COM interface and it gets handled in an event raised from the COM thread. It seems like the event, which has quite a bit of code in it, takes longer and longer to execute and after a while the entire application crashes. There are calls to graphics and stuffing into large arrays inside the event that might affect time. I have been unable to spot any significant increase in memory usage and have not had opportunity to run any profilers to check for leaks yet. Also, the obvious thing to test would be to strip the event of all the code in it just to see if we can run for a longer period of time.</p> <p>Are events serial or parallell in Delphi, that is, if I get a new event while one is executing -what happens? Is it run in parallell on some kind of automatic thread, is it ignored or is it queued up?</p> <p>If it is queued up, how many can I have in the queue before the application crashes?</p> <p>Does indexing into a large array take longer the further into it you are? Even if it's of a fixed size? I don't think it should so I'm looking for leaks and allocations that take time. If I get sent an object through the event, should I dispose of it within the event or in the "calling" code?</p> <p>What things usually do not scale well in Delphi? What can I look for that would increase in execution time?</p> <p>Finally, since this is COM related, any pointers to common pitfalls in COM are appreciated although I realize this is tricky. I do have a grip on co-initialize though.</p>
<p>Delphi is mostly serial in handling events. Unfortunately, it is possible to tell Delphi to handle other events while you're running in some event already. As a result, new events will run while your current event is waiting for the new event to finish. In the worst case, your application might appear to behave normally while it's really stacking events within events within events. Rule one: avoid using Application.ProcessMessages unless you really need this. </p> <p>When using COM objects, things become a bit more complex since the COM object might have it's own events, start it's own threads and do all other kinds of things that you don't have any control over. COM appears to be easy to use in Delphi but it does have many hidden pitfalls for the inexperienced developers. (I still have the scars after surviving a few of them!)</p> <p>In general, when working with COM objects, I try to separate the COM calls in their own threads, creating special components that will keep the COM object within it's own thread and adding a lot of synchronization code, just so I can keep the GUI responsive while some long COM task is doing some processing. But doing this requires a lot of experience with COM and multi-threading. But basically, designing your custom wrapper component around any COM component is good practice, just to protect the resources that your COM class needs.</p> <p>Delphi's strongest weakness tends to be string handling and the handling of huge arrays. (Especially arrays that contain objects; use records instead.) Strings themselves are fast in Delphi, but the string functions in Delphi are not very optimized. For example, I once had a string containing some XML data. It had a lot of boolean fields that were spelled like "True" and "False" and needed to convert them to "true" and "false". A simple string-replace took about 15 seconds to replace all these values. The I rewrote it by using MSXML to load the XML in a DOM Document, using XPath to select all boolean nodes, loop through those nodes to replace all the values with the proper texts and then put the XML back into a single string. Suddenly it was able to do the same within two seconds! A huge performance gail for something that appeared to be slower. The reason? When Delphi is handling strings, it tends to copy the string a few times during processing. Or it needs to allocate more and more memory for the string to increase in size. This takes time, which doesn't get wasted in some other languages like C++.</p>
<p>Did some research and got a few pointers, particularly to my first question:</p> <p><em>Are events serial or parallell in Delphi, that is, if I get a new event while one is executing -what happens? Is it run in parallell on some kind of automatic thread, is it ignored or is it queued up? If it is queued up, how many can I have in the queue before the application crashes?</em></p> <p>Well, obviously events are as synchronous as in everything else, or should I say serial. You can not get more events as you process one since that event essentially is a function call.</p> <p>In the event handler, some graphic components are handled. Since the event is raised on another thread this is bad. I either need to make some updating mechanism on the graphics that lies on the thread that created the graphics or make a thread switch in the event.</p> <p>Also, tests indicate that it in fact is the update of the graphics that is taking increasingly longer time, thus a refactoring of the graphics handling sounds like a good path to try at first.</p>
48,430
<p>In MySql's interpreter, it's very easy to dump a table to the screen along with its field names. </p> <p>There seems to be no simple way to export a table to a tab-delimted or CSV outfile <em>including</em> its column headers.</p> <p>I'm trying to do this using only SQL or the Linux command line, without writing a program in another language.</p> <p>Thank you</p>
<p>Piping the query to the commandline client outputs a tab separated list with the column names as the first line</p> <pre><code>$ echo "select * from surveys limit 5" | mysql -uroot -pGandalf surveys phone param1 param2 param3 param4 p0 p1 p2 p3 audio4 code time XXXXXXXXX 2008-07-02 11:17:23 XXXXXXXX SAT - - - - - ERROR 2008-07-02 12:18:32 XXXXXXXXX 2008-07-02 11:22:52 XXXXXXXX SAT - - - - - COLGADO 2008-07-02 12:04:29 XXXXXXXXX 2008-07-02 11:41:29 XXXXXXXX SAT - - - - - COLGADO 2008-07-02 12:07:22 XXXXXXXXX 2008-07-02 12:16:19 XXXXXXXX SAT 1 1 1 9 XXXXXXXXX_4.wav OK 2008-07-02 16:14:27 XXXXXXXXX 2008-07-02 08:21:25 XXXXXXXX SAT 1 1 1 1 XXXXXXXXX_4.wav OK 2008-07-02 12:29:40 </code></pre>
<p>I have created a procedure to automate the exporting of the contents of a larger number of tables to .csv file by using <code>SELECT ... INTO OUTFILE</code>. Please refer to the following if you have need for something like this</p> <p><a href="http://lifeboysays.wordpress.com/2012/06/23/mysql-how-to-export-data-to-csv-with-column-headers/" rel="nofollow">http://lifeboysays.wordpress.com/2012/06/23/mysql-how-to-export-data-to-csv-with-column-headers/</a>.</p> <p>It uses the method described by cafe876, but will work for one or a whole series of tables, plus you can set the delimiter and quote character to be used.</p>
32,912
<p>What is smart navigation in .NET? </p>
<p>SmartNavigation is a property of the Page class in System.Web.UI. When a request comes in to Internet Explorer 5.5 or higher and SmartNavigation is turned on (set to true), the following actions are performed:</p> <ul> <li>The flash caused by navigation is eliminated</li> <li>The scroll position is persisted when moving from page to page</li> <li>Element focus is persisted between navigations</li> <li>Only the last page state in the browser's history is retained</li> </ul> <p>Here is a <a href="http://msdn.microsoft.com/en-us/magazine/cc163735.aspx" rel="nofollow noreferrer">good article</a> about it.</p> <p><em>Warning</em> It doesn't work on other browser than IE. Should not be used for public website.</p>
<p>A feature of ASP.NET that allows a web page to do a postback and display new content without flickering or skipping back to the top of the page. I don't see that it has much place now that AJAX exists.</p>
47,730
<p>I have a loop that reads each line in a file using <code>getline()</code>:</p> <pre><code>istream is; string line; while (!getline(is, line).eof()) { // ... } </code></pre> <p>I noticed that calling <code>getline()</code> like this also seems to work:</p> <pre><code>while (getline(is, line)) </code></pre> <p>What's going on here? <code>getline()</code> returns a stream reference. Is it being converted to a pointer somehow? Is this actually a good practice or should I stick to the first form?</p>
<p>The <code>istream</code> returned by <code>getline()</code> is having its operator <code>void*()</code> method implicitly called, which returns whether the stream has run into an error. As such it's making more checks than a call to <code>eof()</code>.</p>
<p>I would stick with the first form. While the second form may work, it is hardly explicit. Your original code clearly describes what is being done and how it is expected to behave.</p>
32,385
<p>I'm using managed c++ to implement a method that returns a string. I declare the method in my header file using the following signature:</p> <pre><code>String^ GetWindowText() </code></pre> <p>However, when I'm using this method from C#, the signature is:</p> <pre><code>string GetWindowTextW(); </code></pre> <p>How do I get rid of the extra "W" at the end of the method's name?</p>
<p>To get around the preprocessor hackery of the Windows header files, declare it like this:</p> <pre><code>#undef GetWindowText String^ GetWindowText() </code></pre> <p>Note that, if you actually use the Win32 or MFC <code>GetWindowText()</code> routines in your code, you'll need to either redefine the macro or call them as <code>GetWindowTextW()</code>.</p>
<p>GetWindowText is a win32 api call that is aliased via a macro to GetWindowTextW in your C++ project.</p> <p>Try adding #undef GetWindowText to you C++ project.</p>
12,892
<pre><code>&lt;Grid.Triggers&gt; &lt;EventTrigger RoutedEvent="Border.Loaded"&gt; &lt;EventTrigger.Actions &gt; &lt;BeginStoryboard&gt; &lt;Storyboard x:Name="MyStoryboard" AutoReverse="True" RepeatBehavior="Forever"&gt; &lt;ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="border" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"&gt; &lt;SplineColorKeyFrame KeyTime="00:00:01" Value="#FFFAFAFA"/&gt; &lt;/ColorAnimationUsingKeyFrames&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/EventTrigger.Actions&gt; &lt;/EventTrigger&gt; &lt;/Grid.Triggers&gt; </code></pre> <p>How do I enable\disable this event trigger\animation dynamically. I was thinking I could bind to a IValueConverter and disable the storyboard, but there does not seem to be any suitable property to bind to?</p>
<p>The only trigger currently available in Silverlight is "Loaded", for all other events you'll have to write a bit of code. To use this technique, Storyboards should go in the Resources section instead of Triggers, and you'll call Begin() on the Storyboard from the code.</p> <p>If you're doing templating of a control, then there are what are called Transitions which let you kick off storyboards based on control events, like MouseOver. This is handled by the Visual State Manager:</p> <p><a href="http://timheuer.com/blog/archive/2008/06/04/silverlight-introduces-visual-state-manager-vsm.aspx" rel="nofollow noreferrer">http://timheuer.com/blog/archive/2008/06/04/silverlight-introduces-visual-state-manager-vsm.aspx</a></p>
<p>I wasn't really looking for the animation to be turned off based on an event. I wanted to do it based on a property of my business object that Im binding too? I was hoping there was something like Storyboard.Enabled = False!?!?!</p>
20,080
<p>MySQL's explain output is pretty straightforward. PostgreSQL's is a little more complicated. I haven't been able to find a good resource that explains it either.</p> <p>Can you describe what exactly explain is saying or at least point me in the direction of a good resource?</p>
<p><a href="http://wiki.postgresql.org/wiki/Image:Explaining_EXPLAIN.pdf" rel="noreferrer">Explaining_EXPLAIN.pdf</a> could help too.</p>
<p>If you install pgadmin, there's an Explain button that as well as giving the text output draws diagrams of what's happening, showing the filters, sorts and sub-set merges that I find really useful to see what's happening.</p>
14,281
<p>I have a method in .NET (C#) which returns <code>string[][]</code>. When using RegAsm or TlbExp (from the .NET 2.0 SDK) to create a COM type library for the containing assembly, I get the following warning:</p> <blockquote> <p>WARNING: There is no marshaling support for nested arrays.</p> </blockquote> <p>This warning results in the method in question not being exported into the generated type library. I've been told there's ways around this using Variant as the COM return type, and then casting/etc on the COM client side. For this particular assembly, the target client audience is VB6. <b>But how do you actually do this on the .NET side?</b></p> <p><i>Note</i>: I have an existing legacy DLL (with its exported type library) where the return type is Variant, but this DLL (and the .tlb) is generated using pre-.NET legacy tools, so I can't use them. </p> <p>Would it help at all if the assembly was written in VB.NET instead?</p>
<p>Even if you were to return an Object (which maps to a Variant in COM Interop), that doesn't solve your problem. VB will be able to "hold" onto it and "pass it around", but it won't be able to do anything with it.</p> <p>Technically, there is no exact equivalent in VB for a string[][]. However, if your array is not "jagged" (that is, all the sub-arrays are the same length), you should be able to use a two-dimensional array as your return type. COM Interop should be able to translate that.</p> <pre><code>string [,] myReturnValue = new string[rowCount,colCount]; </code></pre> <p>Whether your method formally returns an Object (which will look like a Variant to VB), or a string[,] (which will look like an Array of Strings in VB), is somewhat immaterial. The String array is a nicer return, but not a requirement.</p> <p>If you array <em>is</em> jagged, then you are going to have to come up with a different method. For example, you could choose to make your return 2D array as big as the biggest of the sub-arrays, and then pass the length information in a separate [out] int[] parameter, so that VB can know which elements are used.</p>
<p>The equivalent of variant in C# is System.Object. So you might want to try to return the result cast to object and pick it back up on the other side as a variant.</p> <p>VB doesn't have any facilities that C# lacks, so I doubt it would be better or easier if the .NET side was written in VB.</p>
9,590
<p>Any recommended crypto libraries for Java. What I need is the ability to parse X.509 Certificates to extract the information contained in them.</p> <p>Thanks</p>
<p>In Java, java.security.cert.CertificateFactory.</p> <p>"A certificate factory for X.509 must return certificates that are an instance of java.security.cert.X509Certificate"</p>
<p>Java doesn't need crypto libraries, it ships with that functionality already. In particular, java.security.cert.X509Certificate.</p>
17,326
<p>How can I center a model at the middle of the printing area of the printer when creating a g-code with CuraEngine. </p> <p>Are there any parameters I can add to <code>ultimaker2.def.json</code> to achieve this? Thanks.</p>
<p>Found a solution. This need to be applied under <code>"settings"</code></p> <pre><code>"command_line_settings": { "label": "Command Line Settings", "description": "Settings which are only used if CuraEngine isn't called from the Cura frontend.", "type": "category", "enabled": true, "children": { "center_object": { "description": "Whether to center the object on the middle of the build platform (0,0), instead of using the coordinate system in which the object was saved.", "type": "bool", "label": "Center object", "default_value": true, "enabled": true } } } </code></pre>
<p>If this is over the commandline tool "CuraEngine", then you will have to read the sourcecode. According to the <a href="https://ultimaker.com/en/community/4337-doc-of-curaengine" rel="nofollow noreferrer">Author</a>, 'Nope. Only documentation there is in the code, readme and my head.' (cringe!).</p> <p>If you're talking of the GUI program, then right click and click "Center". But this requires GUI usage. Not so nice if you want to automate using curaengine as your slicer.</p>
708
<p>I need to do some emulation of some old DOS or mainframe terminals in Flex. Something like the image below for example.</p> <p><img src="https://i.stack.imgur.com/qFtvP.png" alt="alt text"></p> <p>The different coloured text is easy enough, but the ability to do different background colours, such as the yellow background is beyond the capabilities of the standard Flash text.</p> <p>I may also need to be able to enter text at certain places and scroll text up the "terminal". Any idea how I'd attack this? Or better still, any existing code/components for this sort of thing?</p>
<p>Use <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextField.html" rel="nofollow noreferrer"><code>TextField.getCharBoundaries</code></a> to get a rectangle of the first and last characters in the areas where you want a background. From these rectangles you can construct a rectangle that spans the whole area. Use this to draw the background in a <code>Shape</code> placed behind the text field, or in the parent of the text field.</p> <p><em>Update</em> you asked for an example, here is how to get a rectangle from a range of characters:</p> <pre><code>var firstCharBounds : Rectangle = textField.getCharBoundaries(firstCharIndex); var lastCharBounds : Rectangle = textField.getCharBoundaries(lastCharIndex); var rangeBounds : Rectangle = new Rectangle(); rangeBounds.topLeft = firstCharBounds.topLeft; rangeBounds.bottomRight = lastCharBounds.bottomRight; </code></pre> <p>If you want to find a rectangle for a whole line you can do this instead:</p> <pre><code>var charBounds : Rectangle = textField.getCharBoundaries(textField.getLineOffset(lineNumber)); var lineBounds : Rectangle = new Rectangle(0, charBounds.y, textField.width, firstCharBounds.height); </code></pre> <p>When you have the bounds of the text range you want to paint a background for, you can do this in the <code>updateDisplayList</code> method of the parent of the text field (assuming the text field is positioned at [0, 0] and has white text, and that <code>textRangesWithYellowBackground</code> is an array of rectangles that represent the text ranges that should have yellow backgrounds):</p> <pre><code>graphics.clear(); // this draws the black background graphics.beginFill(0x000000); graphics.drawRect(0, 0, textField.width, textField.height); graphics.endFill(); // this draws yellow text backgrounds for each ( var r : Rectangle in textRangesWithYellowBackground ) graphics.beginFill(0xFFFF00); graphics.drawRect(r.x, r.y, r.width, r.height); graphics.endFill(); } </code></pre>
<p>The font is fixed width and height, so making a background bitmap dynamically isn't difficult, and is probably the quickest and easiest solution. In fact, if you size it correctly there will only be one stretched pixel per character.</p> <p>Color the pixel (or pixels) according to the background of the character.</p> <p>-Adam</p>
8,545
<p>I would like to be able to know, in run-time in my code, how much memory a certain object is taking (a Dataset in this case, but i'm looking for a "general" solution).</p> <p>Is this possible through reflection?</p> <p>This is for .Net 2.0.</p> <p>Thanks!</p>
<p>I believe this is a duplicate. Check out: </p> <ul> <li><a href="https://stackoverflow.com/questions/155022/what-is-the-easiest-way-to-find-out-how-much-memory-an-object-uses-in-net">What is the easiest way to find out how much memory an object uses in .NET?</a></li> <li><a href="https://stackoverflow.com/questions/51540/determine-how-much-memory-a-class-uses#51895">Determine how much memory a class uses?</a></li> </ul>
<pre><code>int size = Marshal.SizeOf(typeof(int)); </code></pre> <p>That should work too.</p>
28,136
<p>Ok so I've ordered <a href="http://www.amazon.co.uk/Applying-Domain-Driven-Design-Patterns-Using/dp/0321268202/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1226403396&amp;sr=1-1" rel="noreferrer">Applying Domain-Driven Design and Patterns: Using .Net</a>, but while I wait for it to arrive I'm looking at starting to apply the techniques in my current project. I really grasp the concepts quite well now, but when I try to apply them I get caught up with the execution and end up leaking my respsonsibilities across the various projects. As such I'm looking for resources out there that can guide me in the right direction, <strong>especially sample projects with actual code</strong> that I can work against. I remember a sample site out there in the Alt.Net world that had a real working project that people could browse but can't seem to find it? Does anyone out there have that link, or any other links they could share??</p> <p>Edit: I have since found this <a href="http://dddsample.sourceforge.net/" rel="noreferrer">sample application</a> from the DomainDrivenDesign.org site (although it is Java based) as well as the example outlined below.</p> <p>I am still looking for the Alt.Net sample application if anyone knows where to find it?</p>
<p>The following CodePlex projects seem to be right up your ally:</p> <ul> <li><a href="http://www.codeplex.com/dddpds" rel="noreferrer">.NET Domain-Driven Design with C#: Problem-Design-Solution</a></li> <li><a href="http://www.codeplex.com/domaindrivendesign" rel="noreferrer">Domain Driven Design (.NET) Example Application</a></li> <li><a href="http://www.codeplex.com/StoreDDD" rel="noreferrer">StoreDDD</a></li> </ul>
<p>As part of a talk I have done at a Dutch .NET community event, I have started implementing a full-blown Silverlight 4 example using CQRS and Event Sourcing. It relies heavily on one of the most serious open-source CQRS initiatives, <a href="http://ncqrs.org/" rel="nofollow noreferrer">NCQRS</a>. You can find its corresponding CodePlex site <a href="http://thecqrskitchen.codeplex.com/" rel="nofollow noreferrer">here</a>.</p>
35,497
<p>When I do an update and zillions of files are updated, I often miss the one that aren't merged because of conflicts. The only way I have is to go through all my changelists and look at file icons.</p> <p>Isn't there a nicer way ? even a console based command would do...</p>
<p>You could immediately do an update again, which this time would just print out the conflicts. If you are using p4v, make sure you have the log showing, as the results should scroll through there.</p>
<p>You could immediately do an update again, which this time would just print out the conflicts. If you are using p4v, make sure you have the log showing, as the results should scroll through there.</p>
47,385
<p>What would be the quickest way to construct a Python binding to a C or C++ library?</p> <p>(I am using Windows if this matters.)</p>
<p><a href="https://docs.python.org/3/library/ctypes.html" rel="noreferrer">ctypes</a> module is part of the standard library, and therefore is more stable and widely available than <a href="http://www.swig.org/" rel="noreferrer">swig</a>, which always tended to give me <a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/d94badd9847fe43a?pli=1" rel="noreferrer">problems</a>.</p> <p>With ctypes, you need to satisfy any compile time dependency on python, and your binding will work on any python that has ctypes, not just the one it was compiled against.</p> <p>Suppose you have a simple C++ example class you want to talk to in a file called foo.cpp:</p> <pre><code>#include &lt;iostream&gt; class Foo{ public: void bar(){ std::cout &lt;&lt; "Hello" &lt;&lt; std::endl; } }; </code></pre> <p>Since ctypes can only talk to C functions, you need to provide those declaring them as extern "C"</p> <pre><code>extern "C" { Foo* Foo_new(){ return new Foo(); } void Foo_bar(Foo* foo){ foo-&gt;bar(); } } </code></pre> <p>Next you have to compile this to a shared library</p> <pre><code>g++ -c -fPIC foo.cpp -o foo.o g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o </code></pre> <p>And finally you have to write your python wrapper (e.g. in fooWrapper.py)</p> <pre><code>from ctypes import cdll lib = cdll.LoadLibrary('./libfoo.so') class Foo(object): def __init__(self): self.obj = lib.Foo_new() def bar(self): lib.Foo_bar(self.obj) </code></pre> <p>Once you have that you can call it like</p> <pre><code>f = Foo() f.bar() #and you will see "Hello" on the screen </code></pre>
<p>First you should decide what is your particular purpose. The official Python documentation on <a href="https://docs.python.org/2/extending/" rel="nofollow noreferrer">extending and embedding the Python interpreter</a> was mentioned above, I can add a good <a href="http://web.archive.org/web/20160530183233/http://python-packaging-user-guide.readthedocs.io/en/latest/extensions/" rel="nofollow noreferrer">overview of binary extensions</a>. The use cases can be divided into 3 categories:</p> <ul> <li><strong>accelerator modules</strong>: to run faster than the equivalent pure Python code runs in CPython.</li> <li><strong>wrapper modules</strong>: to expose existing C interfaces to Python code.</li> <li><strong>low level system access</strong>: to access lower level features of the CPython runtime, the operating system, or the underlying hardware.</li> </ul> <p>In order to give some broader perspective for other interested and since your initial question is a bit vague ("to a C or C++ library") I think this information might be interesting to you. On the link above you can read on disadvantages of using binary extensions and its alternatives. </p> <p>Apart from the other answers suggested, if you want an accelerator module, you can try <a href="http://numba.pydata.org/" rel="nofollow noreferrer">Numba</a>. It works "by generating optimized machine code using the LLVM compiler infrastructure at import time, runtime, or statically (using the included pycc tool)". </p>
17,516
<p>currently i have jdbc code with the following basic stucture:</p> <p>get Connection</p> <p>(do the next 4 lines several times, never closing statement)<br> get statement<br> get result set<br> process result set<br> close result set </p> <p>close connection </p> <p>It occurred to me after writing this code that i need to close the statement.<br> 1 what are the effects of not closing the statement.<br> 2 will the following work, this si will closing the statement prevent me from processing the result set as normal?</p> <p>get Connection</p> <p>(do the next 5 lines several times)<br> get statement<br> get result set<br> close statement<br> process result set<br> close result set </p> <p>close connection</p>
<p>The answer depends on your JDBC driver unfortunately. What you wrote there might work.</p> <p>However, the general rule is that you close your statement only when you are done with the corresponding resultset. </p> <p>EDIT: I realize that you had a second question where you asked about the effects of not closing the statements/Resultsets and so on. The effects also depend on your JDBC driver but, it could lead to significant resource leaks.</p>
<p>If you're using Oracle and forget to close the statements you'll get </p> <pre><code>ORA-01000: maximum open cursors exceeded </code></pre> <p>after a while.</p>
31,765
<p>Some background info;</p> <ul> <li>LanguageResource is the base class</li> <li>LanguageTranslatorResource and LanguageEditorResource inherit from LanguageResource</li> <li>LanguageEditorResource defines an IsDirty property</li> <li>LanguageResourceCollection is a collection of LanguageResource</li> <li>LanguageResourceCollection internally holds LanguageResources in <code>Dictionary&lt;string, LanguageResource&gt; _dict</code></li> <li>LanguageResourceCollection.GetEnumerator() returns <code>_dict.Values.GetEnumerator()</code></li> </ul> <p>I have a LanguageResourceCollection _resources that contains only LanguageEditorResource objects and want to use LINQ to enumerate those that are dirty so I have tried the following. My specific questions are in bold.</p> <ol> <li><p><code>_resources.Where(r =&gt; (r as LanguageEditorResource).IsDirty)</code><br/><br/> neither Where not other LINQ methods are displayed by Intellisense but I code it anyway and am told "LanguageResourceCollection does not contain a definition for 'Where' and no extension method...".<br/><br/> <strong>Why does the way that LanguageResourceCollection implements IEnumerable preclude it from supporting LINQ?</strong></p></li> <li><p>If I change the query to<br/><br/> <code>(_resources as IEnumerable&lt;LanguageEditorResource&gt;).Where(r =&gt; r.IsDirty)</code><br/><br/> Intellisense displays the LINQ methods and the solution compiles. But at runtime I get an ArgumentNullException "Value cannot be null. Parameter name: source".<br/><br/> <strong>Is this a problem in my LINQ code?<br> Is it a problem with the general design of the classes?<br> How can I dig into what LINQ generates to try and see what the problem is?</strong></p></li> </ol> <p>My aim with this question is not to get a solution for the specific problem, as I will have to solve it now using other (non LINQ) means, but rather to try and improve my understanding of LINQ and learn how I can improve the design of my classes to work better with LINQ.</p>
<p>It sounds like your collection implements <code>IEnumerable</code>, not <code>IEnumerable&lt;T&gt;</code>, hence you need:</p> <pre><code>_resources.Cast&lt;LanguageEditorResource&gt;().Where(r =&gt; r.IsDirty) </code></pre> <p>Note that <code>Enumerable.Where</code> is defined on <code>IEnumerable&lt;T&gt;</code>, not <code>IEnumerable</code> - if you have the non-generic type, you need to use <code>Cast&lt;T&gt;</code> (or <code>OfType&lt;T&gt;</code>) to get the right type. The difference being that <code>Cast&lt;T&gt;</code> will throw an exception if it finds something that isn't a <code>T</code>, where-as <code>OfType&lt;T&gt;</code> simply ignores anything that isn't a <code>T</code>. Since you've stated that your collection <em>only</em> contains <code>LanguageEditorResource</code>, it is reasonable to check that assumption using <code>Cast&lt;T&gt;</code>, rather than silently drop data.</p> <p>Check also that you have "using System.Linq" (and are referencing System.Core (.NET 3.5; else LINQBridge with .NET 2.0) to get the <code>Where</code> extension method(s).</p> <p>Actually, it would be worth having your collection implement <code>IEnumerable&lt;LanguageResource&gt;</code> - which you could do quite simply using either the <code>Cast&lt;T&gt;</code> method, or an iterator block (<code>yield return</code>).</p> <p>[edit] To build on Richard Poole's note - you could write your <em>own</em> generic container here, presumably with <code>T : LanguageResource</code> (and using that <code>T</code> in the <code>Dictionary&lt;string,T&gt;</code>, and implementing <code>IEnumerable&lt;T&gt;</code> or <code>ICollection&lt;T&gt;</code>). Just a thought.</p>
<p>In addition to Marc G's answer, and if you're able to do so, you might want to consider dropping your custom <code>LanguageResourceCollection</code> class in favour of a generic <code>List&lt;LanguageResource&gt;</code>. This will solve your current problem and get rid of that nasty .NET 1.1ish custom collection.</p>
33,614
<p>Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist?</p> <p>Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView?</p>
<p>Here's what I did:</p> <pre><code>&lt;link rel="Stylesheet" type="text/css" href="Stylesheet.css" id="style" runat="server" visible="false" /&gt; </code></pre> <p>It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered.</p> <hr> <p>Here's an even more concise way to do this with multiple references;</p> <pre><code>&lt;% if (false) { %&gt; &lt;link rel="Stylesheet" type="text/css" href="Stylesheet.css" /&gt; &lt;script type="text/javascript" src="js/jquery-1.2.6.js" /&gt; &lt;% } %&gt; </code></pre> <p>As seen in <a href="http://haacked.com/archive/2008/11/21/combining-jquery-form-validation-and-ajax-submission-with-asp.net.aspx" rel="noreferrer">this blog post</a> from Phil Haack.</p>
<p>You Can use <code>CSS</code> direct in <code>userControl</code>.</p> <p>Use this in <code>UserControl</code>:</p> <pre><code> &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;style type="text/css"&gt; .wrapper { margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */ } &lt;/style&gt; &lt;/head&gt; </code></pre> <p>This will work.</p>
5,459
<p>I was reading about the <code>debuggerstepperboundary</code> attribute and a site says it is is useful in a context switch.</p> <p>What exactly is a context switch? I'm assuming it is a switch from one thread to another, or in execution or security context? However, these are not particularly educated guesses so I'm asking here.</p>
<p>A context switch (also sometimes referred to as a process switch or a task switch) is the switching of the CPU (central processing unit) from one process or thread to another.</p> <p>Context switching can be described in slightly more detail as the kernel (i.e., the core of the operating system) performing the following activities with regard to processes (including threads) on the CPU: (1) suspending the progression of one process and storing the CPU's state (i.e., the context) for that process somewhere in memory, (2) retrieving the context of the next process from memory and restoring it in the CPU's registers and (3) returning to the location indicated by the program counter (i.e., returning to the line of code at which the process was interrupted) in order to resume the process.</p> <p>A context switch is sometimes described as the kernel suspending execution of one process on the CPU and resuming execution of some other process that had previously been suspended. Although this wording can help clarify the concept, it can be confusing in itself because a process is, by definition, an executing instance of a program. Thus the wording suspending progression of a process might be preferable.</p>
<blockquote> <p>Switching the CPU core to another process requires performing a state save of the current process and a state restore of a different process. This task is known as a <strong><em>context switch</em></strong></p> </blockquote> <p>Excerpted from: Operating System Concepts, Abraham (Dinosaurs coverpage) </p> <hr> <p>But it doesn't necessarily help me to understand the concept. I like to see animations or images as studying. So, <a href="http://web.archive.org/web/20171119164253/http://www.freertos.org/implementation/a00006.html" rel="nofollow noreferrer">the RTOS's link</a> is genuinely helpful.</p>
38,467
<p>I often get a problem with Windows Installer trying to uninstall a package, but it complains that:</p> <blockquote> <p>The feature you are trying to use is on a network resource that is unavailable.</p> </blockquote> <p>Is there a known means of uninstalling such packages when the original MSI is simply not available?</p>
<p>Please note that Microsoft has now released an official tool to resolve these issues, without the problems that previously existed with MSIZAP.</p> <ul> <li>Microsoft Fixit: <a href="http://support.microsoft.com/mats/Program_Install_and_Uninstall" rel="noreferrer">Fix problems with programs that can't be installed or uninstalled</a></li> </ul>
<p>Control Panel --> Add/Remove programs?</p> <p><strong>EDIT:</strong> Your post mentions nothing about using add remove programs to uninstall the app, you said the "Windows Installer" (MSIEXEC - see the link below), which is not the same thing.</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa367988(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa367988(VS.85).aspx</a></p>
43,373
<p>Say I have a hierarchy of classes, let's use the classic <code>Shape</code> examples: </p> <p><code>abstract class Shape</code><br> <code>Circle : Shape</code><br> <code>Square : Shape</code> </p> <p>I have a second hierarchy of renderer classes that handle the rendering of shapes in different ways:</p> <p><code>abstract class ShapeRenderer</code><br> <code>HtmlShapeRenderer : ShapeRenderer</code><br> <code>WindowsFormsShapeRenderer : ShapeRenderer</code> </p> <p>Allowing these to vary independently would traditionally involve using the Bridge pattern. Allowing the rendering actions to be extended without modifying the <code>Shape</code> classes would traditionally involve the Visitor pattern.</p> <p>However, both of these focus exclusively on extending the implementation side and not the abstraction side. Say I wanted to add a new <code>Shape</code>, say <code>Triangle</code> - I want to be able to support rendering the <code>Triangle</code> as well. Since both the Visitor and the Bridge pattern rely on "flattening" the abstraction hierarchy into a set of methods, e.g.:</p> <pre><code>public abstract class ShapeRenderer { public abstract void RenderCircle(Circle c); public abstract void RenderSquare(Square s); } </code></pre> <p>The only way to extend the <code>Shape</code> hierarchy is to modify the code of the base <code>ShapeRenderer</code> class, which is a breaking change.</p> <p>Jon, to clarify: Using the Bridge or Visitor allows clients to provide alternative rendering implementations, but requires them to know about all potential Shapes. What I'd like to be able to do is allow clients to <em>also</em> be able to extend the <code>Shape</code> class and <em>require</em> them to provide a rendering implementation for their new class. This way, existing code can work with any type of <code>Shape</code>, without worrying about the particulars of rendering them.</p> <p>Is there a common solution to this sort of problem usable in C#?</p>
<p>I think it <em>should</em> be a breaking change. If you add a shape, the existing renderers clearly aren't going to be able to cope - they'll need to be changed.</p> <p>You could change ShapeRenderer to add RenderTriangle() as a virtual (non-abstract) method which just logs the fact that it can't render appropriately, and then fix up the renderers one at a time, but fundamentally you're not going to be able to render the new type without more code.</p> <p>What kind of non-breaking change are you really hoping to achieve?</p>
<p>Design to an interface not an implementation.</p> <p>Hey - I get to use the same answer twice today (i guess it's arguable that Renderer is an implementation)...</p> <p>I'm not sure I'd go with the ShapeRenderer class. What about an IRenderHTML, IRenderWindows that are implemented by the shape classes? </p> <p>You get extensibility with the Shapes as well as with the Renderings.</p> <p>I think it may be better OO to say hey circle go render yourself, than to pass the circle to a utility class for rendering. You could readily add new shapes and new renderings by letting the shapes do the rendering themselves.</p>
46,039
<p>I found some informations about controlling IIS 5.1 from command line via adsutil.vbs (<a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d3df4bc9-0954-459a-b5e6-7a8bc462960c.mspx?mfr=true" rel="nofollow noreferrer">http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d3df4bc9-0954-459a-b5e6-7a8bc462960c.mspx?mfr=true</a>). The utility is available at c:\InetPub\AdminScripts.</p> <p>The utility throw only errors like the following: ErrNumber: -2147463164 (0x80005004) Error Trying To GET the Schema of the property: IIS://localhost/Schema/ROOT</p> <p>Can you tell me, how to check if there exists a virtual directory and create it, if it does not exist?</p>
<p>The microsoft official way is just to copy them into the relevant folders (as seen by downloading their template packs). However, you could also create your own site definition and add the items to the correct libraries and lists in the same way that the master pages are added.</p> <p>If you are going to deploy CSS and Master Pages through features remember you will have to activate your the publishing infrastructure on the site collection and the publishing feature on the site.</p> <p>To deploy a master page/page layout as a feature you should follow the steps at the site below, you can use the "fileurl" element to specify your CSS and place it into the correct folder (style library, for example): <a href="http://www.sharepointnutsandbolts.com/2007/04/deploying-master-pages-and-page-layouts.html" rel="nofollow noreferrer">http://www.sharepointnutsandbolts.com/2007/04/deploying-master-pages-and-page-layouts.html</a></p>
<p>Consider uploading them to "Style Library" in the root of the site collection. <p>If you don't have a "Style Library" at the root, consider making one -- it's just a document library. <p>Make sure the permissions are set correctly so everyone who needs to read it can. <p>You can reference them using "/Style%20Library/my.css" but this won't work on site collections that don't live at the root of the domain.</p>
7,713
<p>I am using the program below to sort and eventually print out email messages. Some messages may contain attachments or HTML code, which would not be good for printing. Is there an easy way to strip attachments and strip HTML but not the text formatted by HTML from the messages?</p> <pre><code>#!/usr/bin/perl use warnings; use strict; use Mail::Box::Manager; open (MYFILE, '&gt;&gt;data.txt'); binmode(MYFILE, ':encoding(UTF-8)'); my $file = shift || $ENV{MAIL}; my $mgr = Mail::Box::Manager-&gt;new( access =&gt; 'r', ); my $folder = $mgr-&gt;open( folder =&gt; $file ) or die "$file: Unable to open: $!\n"; for my $msg ( sort { $a-&gt;timestamp &lt;=&gt; $b-&gt;timestamp } $folder-&gt;messages) { my $to = join( ', ', map { $_-&gt;format } $msg-&gt;to ); my $from = join( ', ', map { $_-&gt;format } $msg-&gt;from ); my $date = localtime( $msg-&gt;timestamp ); my $subject = $msg-&gt;subject; my $body = $msg-&gt;decoded-&gt;string; # Strip all quoted text $body =~ s/^&gt;.*$//msg; print MYFILE &lt;&lt;""; From: $from To: $to Date: $date Subject: $subject \n $body } </code></pre>
<p><code>Mail::Message::isMultipart</code> will tell you whether a given message has any attachments. <code>Mail::Message::parts</code> will give you a list of the mail parts.</p> <p>Thus:</p> <pre><code>if ( $msg-&gt;isMultipart ) { foreach my $part ( $msg-&gt;parts ) { if ( $part-&gt;contentType eq 'text/html' ) { # deal with html here. } elsif ( $part-&gt;contentType eq 'text/plain' ) { # deal with text here. } else { # well? } } } </code></pre>
<p>It looks like someone has already <a href="http://www.linuxquestions.org/questions/programming-9/perl-mimehtml-mail-48546/" rel="nofollow noreferrer">solved this on the linuxquestions forum</a>.</p> <p>From the forum:</p> <pre><code> # This is part of Mail::POP3Client to get the headers and body of the POP3 mail in question $body = $connection-&gt;HeadAndBody($i); # Parse the message with MIME::Parser, declare the body as an entitty $msg = $parser-&gt;parse_data($body); # Find out if this is a multipart MIME message or just a plaintext $num_parts=$msg-&gt;parts; # So its its got 0 parts i.e. is a plaintext if ($num_parts eq 0) { # Get the message by POP3Client $message = $connection-&gt;Body($i); # Use this series of regular expressions to verify that its ok for MySQL $message =~ s/&lt;/&amp;lt;/g; $message =~ s/&gt;/&amp;gt;/g; $message =~ s/'//g; } else { # If it is MIME the parse the first part (the plaintext) into a string $message = $msg-&gt;parts(0)-&gt;bodyhandle-&gt;as_string; } </code></pre>
48,504
<p>I'm looking into using MemCached for a web application I am developing and after researching MemCached over the past few days, I have come across a question I could not find the answer to.</p> <p><strong>How do you link Memcached server together or how do you replicate data between MemCached server?</strong></p> <p><strong>Additionally:</strong> Is this functionality controlled by the servers or the clients and how?</p>
<p>I've used <a href="http://code.google.com/p/beitmemcached/wiki/Embed" rel="noreferrer">BeITMemcached</a> and in that you create an instance of MemcacheClient and set the servers you want to use, just as strings.</p> <p>At that point the client itself determines which of the servers it has available to put different items into. You never know which an item will be in.</p> <p>Check <a href="http://code.google.com/p/memcached/wiki/FAQ" rel="noreferrer">here to see how the servers handle failover</a>.</p> <p>The easiest thing is to have a repopulate mechanism. In my case, I store several hundred objects in memcache which come out of a database. I can just call repopulate and put them all back in there. Whenever I add, update or delete them to the database, I make those same calls to memcache.</p>
<p>Memcached does not provide replication property. To do that, you need to add the server to memcached client server list and then hit the DB for the data to be stored in that particular server.</p>
45,906
<p>I have a game in which you can score from -40 to +40 on each match. Users are allowed to play any number of matches. I want to calculate a total score that implicitly takes into account the number of matches played.</p> <p>Calculating only the average is not fair. For example, if Peter plays four games and gets 40 points on each match, he will have the same total score as Janne who played only one match with 40 points.</p> <p>Adding up the match scores isn't fair either. Peter plays 2 games (40 points on each match), total score 80. Janne plays 8 games (10 points on each match), total score 80.</p> <p>Is there a (simple) and fair way to calculate the total score? I have read about the Elo &amp; Glicko system for chess ratings, but both are based upon a players rating history and the opponents rating. </p>
<p>It depends what you want to accentuate, but I think this is both simple and effective:</p> <p>average score + games played</p> <p>You could weight the variables a bit (e.g. 2* games played, if you want to have more of an impact) - but the basic relationship seems reasonable.</p> <p>In your first example Peter would have 44 and Jane would have 40 - but if Peter starting losing points Jane could catch up.</p>
<p>It depends how much you want to weight games played compared to the scores. You could define a function that returned a games played weight: some smallish fraction for only one game and 1 for a lot of games (e.g. 1 - 1/(2 * #Games)) and multiple that by the cumulative score.</p>
35,466
<p>I have an app where I would like to support device rotation in certain views but other don't particularly make sense in Landscape mode, so as I swapping the views out I would like to force the rotation to be set to portrait.</p> <p>There is an undocumented property setter on UIDevice that does the trick but obviously generates a compiler warning and could disappear with a future revision of the SDK.</p> <pre><code>[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait]; </code></pre> <p>Are there any documented ways to force the orientation?</p> <p><strong>Update:</strong> I thought I would provide an example as I am not looking for shouldAutorotateToInterfaceOrientation as I have already implemented that.</p> <p>I want my app to support landscape and portrait in View 1 but only portrait in View 2. I have already implemented shouldAutorotateToInterfaceOrientation for all views but if the user is in landscape mode in View 1 and then switches to View 2, I want to force the phone to rotate back to Portrait.</p>
<p>This is long after the fact, but just in case anybody comes along who isn't using a navigation controller and/or doesn't wish to use undocumented methods:</p> <pre><code>UIViewController *c = [[UIViewController alloc]init]; [self presentModalViewController:c animated:NO]; [self dismissModalViewControllerAnimated:NO]; [c release]; </code></pre> <p>It is sufficient to present and dismiss a vanilla view controller.</p> <p>Obviously you'll still need to confirm or deny the orientation in your override of shouldAutorotateToInterfaceOrientation. But this will cause shouldAutorotate... to be called again by the system.</p>
<p>If you are using UIViewControllers, there is this method:</p> <pre><code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation </code></pre> <p>Return <code>NO</code> for the view controllers containing the views you don't want to rotate.</p> <p><a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instm/UIViewController/shouldAutorotateToInterfaceOrientation:" rel="nofollow noreferrer">More info here</a></p>
21,947
<p>What do I need to do to avoid the "Manual Install" in Firefox for a Plugin and where do I have to go or what do I have to do to avoid the (Author not verified) message when downloading a Plugin. Ideally I would like to initiate the installation of the Plugin automatically and if I need to sign the Plugin somehow to show that it is not doing any kind of malicious things I would like to do that as well.</p> <p>Thanks!</p>
<p>Here is the <a href="http://www.mozdevgroup.com/docs/pete/Signing-an-XPI.html" rel="nofollow noreferrer">official tutorial</a>, which only deals with signing the XPI. I don't believe it's possible to install the plug in automatically for rather obvious security reasons.</p>
<p>Here is the <a href="https://www.mozdevgroup.com/docs/pete/Signing-an-XPI.html" rel="nofollow noreferrer">official tutorial </a> which deals with signing the XPI. Automatic installation isn't possible because of the security considerations.</p>
34,973
<p>I am trying to unit test my WPF databindings using the test suit provided by Microsoft Team System. I would like to be able to test the bindings without showing the window because most of my tests will be for user controls and not actually on a window. Is this possible or is there a better way to do it? The code below works if I show the window, but if I don't, the bindings don't update. </p> <pre><code> Window1_Accessor target = new Window1_Accessor(); UnitTestingWPF.Window1_Accessor.Person p = new UnitTestingWPF.Window1_Accessor.Person() { FirstName = "Shane" }; Window1 window = (target.Target as Window1); window.DataContext = p; //window.Show(); //Only Works when I actually show the window //Is it possible to manually update the binding here, maybe? Is there a better way? Assert.AreEqual("Shane", target.textBoxFirstName.Text); //Fails if I don't Show() the window because the bindings aren't updated </code></pre>
<p>Shane, if what you're really worried about is a binding breaking silently, you should look at redirecting the binding traces to somewhere you can examine. I'd start here:</p> <p><a href="http://blogs.msdn.com/mikehillberg/archive/2006/09/14/WpfTraceSources.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/mikehillberg/archive/2006/09/14/WpfTraceSources.aspx</a></p> <p>Other than that, I agree with Gishu that bindings aren't good candidates for unit testing, mainly due to the automagic going on that Gishu mentioned in the "Epilogue". Instead focus on making sure the underlying class behaves correctly.</p> <p>Note, too, that you can get even more robust traces using the PresentationTraceSources class:</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.presentationtracesources.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.diagnostics.presentationtracesources.aspx</a></p> <p>Hope that helps!</p>
<p>you can try <a href="http://guia.codeplex.com" rel="nofollow">Guia</a>. With it you can unit-test your UserControl and check if the data binding is correct. You have to show the window though.</p> <p>Here is an example. It starts a new instance of your UserControl and sets its DataContext and then checks if the textbox is set to the right value.</p> <pre><code> [TestMethod] public void SimpleTest() { var viewModel = new SimpleControlViewModel() {TextBoxText = "Some Text"}; customControl = CustomControl.Start&lt;SimpleUserControl&gt;((control) =&gt; control.DataContext = viewModel); Assert.AreEqual("Some Text", customControl.Get&lt;TextBox&gt;("textbox1").Value); customControl.Stop(); } </code></pre>
42,900
<p>I've recently created these two (unrelated) methods to replace lots of boiler-plate code in my winforms application. As far as I can tell, they work ok, but I need some reassurance/advice on whether there are some problems I might be missing.</p> <p>(from memory)</p> <pre><code>static class SafeInvoker { //Utility to avoid boiler-plate InvokeRequired code //Usage: SafeInvoker.Invoke(myCtrl, () =&gt; myCtrl.Enabled = false); public static void Invoke(Control ctrl, Action cmd) { if (ctrl.InvokeRequired) ctrl.BeginInvoke(new MethodInvoker(cmd)); else cmd(); } //Replaces OnMyEventRaised boiler-plate code //Usage: SafeInvoker.RaiseEvent(this, MyEventRaised) public static void RaiseEvent(object sender, EventHandler evnt) { var handler = evnt; if (handler != null) handler(sender, EventArgs.Empty); } } </code></pre> <p>EDIT: See related question <a href="https://stackoverflow.com/questions/258409/how-to-get-information-about-an-exception-raised-by-the-target-of-controlinvoke">here</a></p> <p><strong>UPDATE</strong></p> <p>Following on from deadlock problems (related in <a href="https://stackoverflow.com/questions/2055960/control-invoke-getting-stuck-in-hidden-showdialog">this question</a>), I have switched from Invoke to BeginInvoke (see an explanation <a href="https://stackoverflow.com/questions/229554/whats-the-difference-between-invoke-and-begininvoke/229558#229558">here</a>).</p> <p><strong>Another Update</strong></p> <p>Regarding the second snippet, I am increasingly inclined to use the 'empty delegate' pattern, which fixes this problem 'at source' by declaring the event directly with an empty handler, like so:</p> <pre><code>event EventHandler MyEventRaised = delegate {}; </code></pre>
<p>This is good stuff. Make them extension methods though to clean up your code a little more. For example:</p> <pre><code>//Replaces OnMyEventRaised boiler-plate code //Usage: SafeInvoker.RaiseEvent(this, MyEventRaised) public static void Raise(this EventHandler eventToRaise, object sender) { EventHandler eventHandler = eventToRaise; if (eventHandler != null) eventHandler(sender, EventArgs.Empty); } </code></pre> <p>Now on your events you can call: myEvent.Raise(this);</p>
<p>Similar patterns have worked for me with no problems. I am not sure why you are wrapping Action in MethodInvoker though.</p>
23,455
<p>Assume I have a function like this:</p> <pre><code>MyClass &amp;MyFunction(void) { static MyClass *ptr = 0; if (ptr == 0) ptr = new MyClass; return MyClass; } </code></pre> <p>The question is at program exit time, will the ptr variable ever become invalid (i.e. the contents of that ptr are cleaned up by the exiting process)? I realize that this function leaks, but it is only an example for simplicity.</p> <p>The same question also applies to other primitives besides pointers as well. How about if I have a static integer, does the value of that integer always persist throughout exit or is variable due to static destruction order issues?</p> <p>EDIT:</p> <p>Just to clarify, I want to know what actually happens to the contents of the static pointer (or any other primitive type like an int or a float) and not to the memory it is pointing to. For instance, imagine that the ptr points to some memory address which I want to check in the destructor of some other static class. Can I rely on the fact that the contents of the ptr won't be changed (i.e. that the pointer value won't be cleaned up during the static destruction process)?</p> <p>Thanks, Joe</p>
<p>When you process exits the all memory pages allocated to it will be freed by the OS (modulo shared memory pages that someone else may be using).</p> <p>However, as others point out the destructor for MyClass is never called. Nor is the value pointed to by ptr ever changed. If you have a static int with the value 123 then its value will stay 123 through to the very end of the process' lifetime.</p>
<p>The short answer is "no": your pointer will not "become invalid" at program exit time. I.e. the pointer value will not automatically be reset to null, and destructor of the MyClass object to which it points will not automatically be called.</p> <p>This is because a pointer is a "primitive type", i.e. not an object.</p> <p>If you have a non-local (i.e. global or static) variable which is an object, then the rules are different: the destructor of the object will be called when the program terminates by calling exit() or by returning from the main function. It will not be called if the program terminates by calling abort().</p>
39,306
<p>As a complete beginner with no programming experience, I am trying to find beautiful Python code to study and play with. Please answer by pointing to a website, a book or some software project.</p> <p>I have the following criterias:</p> <ul> <li>complete code listings (working, hackable code)</li> <li>beautiful code (highly readable, simple but effective)</li> <li>instructional for the beginner (yes, hand-holding is needed)</li> </ul> <p>I've tried learning how to program for too long now, never gotten to the point where the rubber hits the road. My main agenda is best spelled out by <a href="http://nat.org/blog/?p=773" rel="noreferrer">Nat Friedman's "How to become a hacker</a>". </p> <p>I'm aware of O'Reilly's "Beautiful Code", but think of it as too advanced and confusing for a beginner.</p>
<p>Buy <a href="https://rads.stackoverflow.com/amzn/click/com/0596529325" rel="noreferrer" rel="nofollow noreferrer">Programming Collective Intelligence</a>. Great book of interesting AI algorithms based on mining data and all of the examples are in very easy to read Python.</p> <p>The other great book is <a href="https://rads.stackoverflow.com/amzn/click/com/0321112547" rel="noreferrer" rel="nofollow noreferrer">Text Processing in Python</a></p>
<p>I'd recommend you review Exaile music player for linux. It includes a lot of practically useful things like plugins, lambda, decorators, settings manager, gui (using GTK+) and much more.</p> <p>Exaile source code is not an ideal but will give you enough helpful information and basic Python coding concepts.</p>
15,197
<p>Is there a way (a program, a library) to approximately know which language a document is written in?</p> <p>I have a bunch of text documents (~500K) in mixed languages to import in a i18n enabled CMS (Drupal)..</p> <p>I don't need perfect matches, only some guess.</p>
<p>There is a pretty easy way to do this, given that you have corpus data in all the different languages you'll need to identify. It's called n-gram modeling. I think <a href="http://search.cpan.org/~ambs/Lingua-Identify-0.51/lib/Lingua/Identify.pm" rel="nofollow noreferrer">Lingua::Identify</a> does this already, though, so that is your best bet rather than implementing your own.</p>
<p>There seems to be a Perl module for this: <a href="https://metacpan.org/pod/Lingua::Identify" rel="nofollow noreferrer">Lingua::Identify</a></p> <p>Paul.</p>
32,086
<p>I'm evaluating Microsoft Team Foundation Server for my customer, who currently uses Visual SourceSafe and nothing else. They have explicitly expressed a desire to implement a more rigid and process-driven environment as their application is in production and they have future releases to consider.</p> <p>The particular areas I'm trying to cover are:</p> <ul> <li>Configuration management (e.g., source control)</li> <li>Change management (workflow and doco for change requests, tasks)</li> <li>Release management (builds and deployments)</li> <li>Incident and problem management (issues and bugs)</li> <li>Document management (similar to source control, but available via web)</li> <li>Code analysis constraints on check-ins</li> <li>A testing framework</li> <li>Reporting</li> <li>Visual Studio 2008 integration</li> </ul> <p>TFS does all of these things quite well, but it's expensive and complex to maintain, and the inexpensive Workgroup edition doesn't scale. We don't get TFS as part of our MSDN subscription.</p> <p>Those problems can be overcome, but before I tell my customer to go the TFS route, which in itself isn't a terrible thing, I wanted to evaluate the alternatives. I know Subversion is often suggested for its configuration management/source control, but what about the other areas? Would a combination of Subversion/NUnit/Wiki/CruiseControl/NAnt/something else satisfy all of these requirements? What tools do I need to include in my evaluation?</p> <p>Or should I just bite the bullet and go with TFS since we're already invested in the Microsoft stack?</p>
<p>Good question(s). I've never used TFS but all this certainly is possible with a number of tools. The biggest hurdle is the culture and mindset of the company and developers. </p> <p>I am pro SVN. (But TFS would work I am sure)</p> <p>I'd suggest very light intrusion on daily tasks. </p> <p>Having sandboxes or promotion rules from one branch to another in SVN is one way to do code analysis without holding up the commit process.</p> <p>So, to address each of your points: SVN handles source control and is ancillary/included in change management and Release management</p> <p>Change management/Workflow is basically defined by the project team and can be helped with simple tools or just enforced by policy.</p> <p>Release management is also policy based and uses the existing framework/tools (SVN)</p> <p>Most any of the popular defect/issue tracking systems will handle the Incident and Document management - think wiki with trac or fogbugz (along with SVN for doc mgmt)</p> <p>FXCop and all the other tools can be part of a build for code analysis</p> <p>Testing framework is more policy based than tool driven - you have to make it a priority if that is what you want.</p> <p>Your reporting notion is vague, but I think you have more than enough tools in any scenario to satisfy this</p> <p>I am not sure what you really need as far as integration with 2008. In any case this not much can be as as tightly coupled as TFS, but I don't see that as a problem. </p> <p>(I think you answered your own question.) This may end up being a religious war between MS and anti-MS sides. </p> <p>In the three places I was at where I was in charge of recommending and implementing a solution, we voted with our wallets - against MS. I am sure TFS is capable, but the competition is quite up to the task and I think those tools translate well for other jobs. </p> <p>As for tools to consider - I think searching Stack overflow for nant, msbuild, cruisecontrol, etc will give you more content than you can shake a stick at... </p>
<p>As much as people hate consultants, you might consider talking to a firm that does commercial svn support. If TFS is as expensive as you say, this may save you some money with the benefit of starting you off with a good setup. There are risks involved with this of course.</p>
37,129
<p>The following loop takes about 700 seconds to run in octave and 22 seconds to run in matlab when the DJI matrix has 21000 rows. How can I increase the efficiency of this?</p> <pre> for i=1:length(DJI) DJI2(i,1)=datenum(char(DJI(i,2)),'yyyy-mm-dd'); end </pre>
<p><a href="https://stackoverflow.com/questions/346842/mysql-query-takes-15-seconds-to-run-what-can-i-do-to-cacheimprove-it-php#346851">MarkR</a> mentioned the index. Make sure you:</p> <pre><code>create index videotags_tag_id on videotags(tag_id); </code></pre>
<p>I think your best bet is to create some kind of summary table which you maintain when things change.</p> <p>The query above needs to scan all the rows in the table in order to find the aggregates in the group by - there is NO WHERE CLAUSE. A query with no where clause has no hope of optimisation, as it necessarily has to check every row.</p> <p>The fix is to create a summary table with the same data as the result of that query (or similar), which you will have to maintain from time to time when the data change or change significantly.</p> <p>Only you can decide, based on the nature of your application and your data, whether it's appropriate to update the summary table on a scheduled basis, on each update, or some combination.</p> <p>As you're doing a join, the right indexes are still beneficial, but you knew that, right, and had already done it?</p>
45,131
<p>I need customers to be able to download PDFs of letters that have been sent to them.</p> <p>I have read the threads about database versus filesystem storage of documents or images, and it does sound like the consensus is that, for anything more than just a few images, filesystem is the way to go.</p> <p>What I want to know: </p> <ul> <li>would a reasonable alternative be to just store the letter details in the database, and recreate the PDF 'on the fly' when it is requested?</li> <li>Is that approach superior or inferior to fetching the PDF from the filesystem?</li> </ul>
<p>If it is for archival purposes, I would definitely store the PDF because in future, your PDF generation script may change and then the letter will not be exactly the same as what was originally sent. The customer will be expecting it to be exactly the same.</p> <p>It doesn't matter what approach is superior, sometimes it is better to go for what approach is safer.</p>
<p>I'm inclined to say "it depends".</p> <p>When one document is requested many times, it may be a saving if you compose it on the first request, and retrieve it subsequentially.</p> <p>OTOH if most requests for a document are of the just-once type, and the creation process doesn't eat up most of your server capacity, on-the-fly will have clear advantage.</p>
28,188
<p>Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute?</p> <p>I know that marking it as disabled works but then it gets displayed differently (greyed out).</p> <p>To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link.</p> <p>I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link.</p>
<p>This sounds like a job for JQuery. Just give a specific class name to all of the HyperLink controls that you want the URLs removed and then apply the following JQuery snippet to the bottom of your page:</p> <pre><code>$(document).ready(function() { $('a.NoLink').removeAttr('href') }); </code></pre> <p>All of the HyperLink controls with the class name "NoLink" will automatically have all of their URLs removed and the link will appear to be nothing more than text.</p> <p>A single line of JQuery can solve your problem.</p>
<p>If you are using databind in asp.net handle the databinding event and just don't set the NavigateUrl if that users is disabled.</p>
7,186
<p>I have 16,000 jpg's from a webcan screeb grabber that I let run for a year pointing into the back year. I want to find a way to grab every 4th image so that I can then put them into another directory so I can later turn them into a movie. Is there a simple bash script or other way under linux that I can do this.</p> <p>They are named like so......</p> <p>frame-44558.jpg</p> <p>frame-44559.jpg</p> <p>frame-44560.jpg</p> <p>frame-44561.jpg</p> <p>Thanks from a newb needing help.</p> <hr> <p>Seems to have worked. Couple of errors in my origonal post. There were actually 280,000 images and the naming was. /home/baldy/Desktop/webcamimages/webcam_2007-05-29_163405.jpg /home/baldy/Desktop/webcamimages/webcam_2007-05-29_163505.jpg /home/baldy/Desktop/webcamimages/webcam_2007-05-29_163605.jpg</p> <p>I ran. cp $(ls | awk '{nr++; if (nr % 10 == 0) print $0}') ../newdirectory/</p> <p>Which appears to have copied the images. 70-900 per day from the looks of it.</p> <p>Now I'm running mencoder mf://*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi</p> <p>I'll let you know how the movie works out.</p> <p>UPDATE: Movie did not work. Only has images from 2007 in it even though the directory has 2008 as well. webcam_2008-02-17_101403.jpg webcam_2008-03-27_192205.jpg webcam_2008-02-17_102403.jpg webcam_2008-03-27_193205.jpg webcam_2008-02-17_103403.jpg webcam_2008-03-27_194205.jpg webcam_2008-02-17_104403.jpg webcam_2008-03-27_195205.jpg</p> <p>How can I modify my mencoder line so that it uses all the images?</p>
<p>One simple way is: </p> <pre> $ touch a b c d e f g h i j k l m n o p q r s t u v w x y z $ mv $(ls | awk '{nr++; if (nr % 4 == 0) print $0}') destdir </pre>
<p>Just iterate over a list of files:</p> <pre><code>files=( frame-*.jpg ) i=0 while [[ $i -lt ${#files} ]] ; do cur_file=${files[$i]} mungle_frame $cur_file i=$( expr $i + 4 ) done </code></pre>
9,732
<p>Compiling this lines</p> <pre><code> long int sz; char tmpret[128]; //take substring of c, translate in c string, convert to int, //and multiply with 1024 sz=atoi(c.substr(0,pos).c_str())*1024; snprintf(tmpret,128,"%l",sz); </code></pre> <p>I read two warning on snprintf line:</p> <pre><code> warning: conversion lacks type at end of format warning: too many arguments for format </code></pre> <p>Why? The type is specified (long int sz, and %l in snprintf) and the argument in snprintf is only one. Can anybody help me? Thanks.</p>
<p>Your format lacks type, because l is a "sizeof" modifier. Should be %ld </p>
<p>int sprintf ( char * str, const char * format, ... );</p> <p>It does not require the length of "str", as the second argument. The name of the string pointer/ array name is enough.</p>
43,923
<p>How do you fix a names mismatch problem, if the client-side names are keywords or reserved words in the server-side language you are using?</p> <p>The DOJO JavaScript toolkit has a QueryReadStore class that you can subclass to submit REST patterned queries to the server. I'm using this in conjunction w/ the FilteringSelect Dijit.</p> <p>I can subclass the QueryReadStore and specify the parameters and arguments getting passed to the server. But somewhere along the way, a "start" and "count" parameter are being passed from the client to the server. I went into the API and discovered that the QueryReadStore.js is sending those parameter names.</p> <p>I'm using Fiddler to confirm what's actually being sent and brought back. The server response is telling me I have a parameter names mismatch, because of the "start" and "count" parameters. The problem is, I can't use "start" and "count" in PL/SQL.</p> <p>Workaround or correct implementation advice would be appreciated...thx.</p> <p>//I tried putting the code snippet in here, but since it's largely HTML, that didn't work so well.</p>
<p>While it feels like the wrong thing to do, because I'm hacking at a well tested, nicely written JavaScript toolkit, this is how I fixed the problem:</p> <p>I went into the DOJOX QueryReadStore.js and <b>replaced</b> the "start" and "count" references with acceptable (to the server-side language) parameter names.</p> <p>I would have like to handled the issue via my PL/SQL <i>(but I don't know how to get around reserved words)</i> or client-side code <i>(subclassing did not do the trick)</i>...without getting into the internals of the library. But it works, and I can move on.</p>
<p>As opposed to removing it from the API, as you mentioned, you can actually create a subclass with your own fetch, and remove start/count parameters (theoretically). Have a look at this URL for guidance:</p> <p><a href="http://www.sitepen.com/blog/2008/06/25/web-service-data-store/" rel="nofollow noreferrer">http://www.sitepen.com/blog/2008/06/25/web-service-data-store/</a></p> <p>Start and count are actually very useful because they allow you to pass params for the query that you can use to filter massive data sets, and it helps to manage client-side paging. I would try to subclass instead, intercept, and remove.</p>
23,414
<p>Can you suggest an asp.net 3.5 hosting provider with continuous integration (cctray – nant builds) and source control facilities (svn)? </p> <p>My requirement would be something like this: </p> <ul> <li>I checkin to a svn branch (say trunk) on the hosting provider space.</li> <li>CruiseControl.NET on the server fires off a build.</li> <li>I see success/failure on my cctray.</li> <li>On success my peers go to the website (say <a href="http://trunk.mywebsite.com" rel="nofollow noreferrer">http://trunk.mywebsite.com</a>) and see changes</li> </ul>
<p>I would also have to suggest a VPS as I have yet to see a Shared Hosting provider with compilers installed.</p> <p>On the code repository side <a href="http://www.assembla.com/" rel="nofollow noreferrer">Assembla.com</a> has free svn hosting and they also provide a way to kick off a build process by allowing you to specify a URL to post to when a check-in occurs. This URL can kick off a script that pulls the latest code and builds it. You can find more details on how to set this up <a href="http://blog.assembla.com/assemblablog/tabid/12618/bid/2916/Running-builds-from-Assembla-repositories.aspx" rel="nofollow noreferrer">here</a>.</p>
<p>I agree with everyone here. For every custom demands, it would be cheaper to look on a VPS / dedicated server to perform what you ask. You may find what you need, but at a high cost.</p>
16,024
<p>In c#, we have interfaces. Where did these come from? They didn't exist in c++.</p>
<p>Interfaces are pretty old, and have been around for quite a while.</p> <p>Early (mid to late late 1970's) non-object oriented languages such as Modula and Euclid used constructs called "modules" to specify the interfaces between components. Components would then communicate with each other via explicit importing and exporting modules. Interfaces in C# are object oriented evolutions of that same concept. </p> <p>Interfaces in C# directly extend from the concept of interfaces in C++ (and Java), where they were used as part of COM for describing object-oriented component interfaces.</p> <p><strong>EDIT:</strong> In doing a small amount of research, the earliest language I could find with an explicit "interface" keyword was Modula-3, a derivitive of Modula created around 1986. </p>
<p>Java, perhaps?</p> <p><a href="http://java.sun.com/docs/books/tutorial/java/concepts/interface.html" rel="nofollow noreferrer">http://java.sun.com/docs/books/tutorial/java/concepts/interface.html</a></p>
12,417
<p>I'm currently printing 11 copies of the same model. I noticed as it's printing that it seems to work on one model at a time but doesn't travel to the nearest model next. I suspect it's traveling around the bed in the order that I put the models in the slicer. This is resulting in extra unnecessary travel and therefore, increasing print time. I slice in Cura 4.9.</p> <p>Is there a slicer that handles this better? Or is there a way to optimize movements in Cura?</p>
<p>It's well known in mathematical circles that the &quot;salesman problem&quot; is what mathematicians call &quot;hard&quot; -- in their usage, that means a lot of extremely smart people have worked on the problem for many years (more than a century?) and still not found a robust, works-every-time solution.</p> <p>What's probably happening with Cura and other slicers is that, for their version of this issue (the most efficient way to visit multiple locations) the decision was made that reducing computing time in slicing was more practical than optimizing travel time of the machine. This is a reasonable decision, from a programming standpoint, because you're likely to be sitting in front of a screen, getting more and more impatient (and thinking less and less of the software you're using) every second the slicing takes, but when the actual printing is going on, you can be doing something else (sleeping, working at your day job, etc.)</p> <p>Therefor, it's likely that what you see in Cura <em>is</em> optimized -- to minimize <em>your</em> time on the way to a solution, rather than to minimize the time for a machine that simply doesn't care if a print takes five hours or nine.</p>
<p><strong>Long story short:</strong> I only know the setting &quot;Combing Mode OFF&quot; that improves the travel paths. In my case it did not help. In your case I suggest you should give PrusaSlicer a try. I assume that the overall print duration will be improved because of a better calculation of the travel paths. But this is only my personal opinion between these two Slicers.</p> <p><strong>Further explanation:</strong> I downloaded the Cura 4.9 and made an install from scratch. I tried to reproduce your issue by placing lots of copies of the same part. As printer I selected the Ultimaker S5 and used the standard configuration for slicing. I let Cura arrange the parts on the print plate. I checked the travel paths between the parts and in most cases Cura has chosen the nearest distance to move the printhead to the next part. In my opinion, there could be a more efficient choice for the next part to print. After this first test I experimented with the settings (e.g. &quot;Combing Mode&quot; OFF) but without an improvement in travel movements.</p> <p>In the past I used Cura in combination with an Ultimaker S5 at work to print parts for production usecases. Over the past two years I recognized lots of parts where the travel movements have been chosen very unefficiently at the cost of high print duration.</p> <p>For comparison I used my standard slicer &quot;PrusaSlicer&quot; and did the test under the same conditions: standard settings, auto-arrangement of the parts. Overall the travel paths are calculated more efficiently, but there is also some room for improvement.</p>
1,991
<p>I need to extend MS Project's functionality for my company, so I would like to embed some .NET GUI controls into Project. The plan is that my controls save the user input into my custom DB tables, but I do have to bind them to tasks, current user, resources etc. Could you give me some advise how to start? I am interested in:</p> <ul> <li>Sample apps/walk-throughs, how to embed a control into MS Project. </li> <li>How to bind user input of my control to current context (e.g., currently selected task)</li> <li>Since the control runs on the client side, how can I roll it out enterprise wide.</li> </ul>
<p><a href="http://www.add-in-express.com/add-in-net/" rel="nofollow noreferrer" title="Add-In Express">Add-In Express</a> is a great library for writing .Net plugins for MS Office, including Project.</p> <p>Can't say I've used it with Project myself (only Visio really), but I know there is support for it, so might be worth a look!</p> <p>It greatly simplifies the writing on plug-ins / add-ins so it might be easier to see if it can do what you're after.</p>
<p>AFAIK you can not embed a control in Project, all you can do is make a plugin.</p>
24,464
<p>The CSRF prevention built in to Rails is causing some problems for some automated load testing we are doing, and I want to turn it off for the duration of the process. How do I do this?</p>
<p>I love simple questions with clear answers.</p> <pre><code>#I go in application.rb self.allow_forgery_protection = false </code></pre> <p>If you want to do this for testing only you can move that into one of the environment files (obviously, you'll be touching <code>Application</code> then rather than <code>self</code>). You could also write something like:</p> <pre><code>#I still go in application.rb self.allow_forgery_protection = false unless ENV["RAILS_ENV"] == "production" </code></pre> <p>See <a href="http://ryandaigle.com/articles/2007/9/24/what-s-new-in-edge-rails-better-cross-site-request-forging-prevention" rel="noreferrer">here</a> for details. (Continuing Rails' wonderful tradition of having documentation of core features in 2 year old blog posts, which were distilled from commit logs.)</p>
<p>In Rails 3, remove the <code>protect_from_forgery</code> command in <code>app/controllers/application_controller.rb</code></p>
16,741
<p>I print ABS on a LulzBot Taz 5 and frequently have issues with the corners of objects lifting off the bed.</p> <p>My extruder is at 230&nbsp;°C and the bed is at 90&nbsp;°C for the first layer and 100&nbsp;°C for the rest of the layers.</p> <p>I have experimented with using ABS slurry (ABS + acetone) on the bed for increased adhesion, building a foam enclosure for the printer, and varying the fan speed. I have noticed the problem is more common the taller the parts are and the sharper the corner is.</p> <p>Adding ABS slurry helped for smaller parts (less than an inch tall) but with my more recent larger parts the adhesion to the bed was so good that the corners of the part lifting actually peeled the PEI tape off of the bed.</p> <p>I have tried using both a skirt and a brim with no change. The skirt stays on the bed, the brim gets pulled up with the corner.</p>
<p>There are many different approaches to solving this issue and most of the answers already are spot-on. However, the fundamental reason for the "warping" is incorrect and inconsistent temperature across the material.</p> <p>If there is too much fluctuation in the temperature across the object in this heated state can result in warping. The reason you see this mostly on the build plate is because the temperature of the first few layers of molten plastic vary much more against the build plate than against higher layers. Note that you can see additional warping mid-print using ABS and this can be a result of a draft or sudden drop in ambient temperature.</p> <p>So, to help solve your problem, here are some suggestions (sorry if there are duplicates):</p> <ul> <li>Completely <a href="https://3dprinting.stackexchange.com/questions/1292/should-i-enclose-my-3d-printer">enclose/seal your machine's build area</a> to reduce (or eliminate if possible) draft and prevent the natural heat of the machine from escaping.</li> <li>Increase the temperature on your build plate. I almost exclusively use ABS on my printer and I keep my HBP at about 112C. However, I live in the NW of the US, so my climate is naturally cooler than say Florida.</li> <li>Alternatively, <a href="https://3dprinting.stackexchange.com/questions/1251/how-to-choose-an-extrusion-temperature">try decreasing the nozzle temperature</a> to a lower point within the ABS melting range. This will just shorten the gap between the inconsistencies in temperature across layers. It is typically better to print at lower temperatures if you can help it. Obviously there are differences in the filament, so you'll have to find that "sweet spot".</li> <li><a href="https://3dprinting.stackexchange.com/questions/470/bed-leveling-method/479#479">Ensure your build plate is flat</a> and your tape doesn't have bubbles. Your BP being flat should be a no brainer, but if your kapton tape (or whatever you use) has bubbles, your freshly printed plastic may not be getting the same temperature from the BP as the rest of your part. This is a bad thing as mentioned earlier.</li> <li>Use extra adhesion techniques such as "ABS Glue" (ABS w/ acetone) or even hairspray. This works about 80% of the time for me, but can make it a bit difficult when removing the parts off the BP.</li> </ul>
<p>I think you answered your question in your statement. Lulzbot and ABS. Lulz does not have an enclosure. </p> <p>Try using PLA for an open air system. Or build an enclosure. Following you can add glue or hairspray.</p> <p>But I promise you, with any open air printer, you will face this problem. I only use ABS on my FFCPs. Even with their passive heat chambers I plan to move to PLA for all my printers.</p>
102
<p>I have a Visual Studio solution with four C# projects in it. I want to step into the code of a supporting project in the solution from my main project, but when I use the "Step into" key, it just skips over the call into that other project. I've set breakpoints in the supporting project, and they're ignored, and I can't for the life of me get it to step into any references to that project.</p> <p>Everything is set to compile as "Debug", and I've seen Visual Studio warn me that my breakpoints won't be hit before - it doesn't do that in this case. It's as though it looks as though my code will debug, but then at run-time, there's a setting somewhere that tells Visual Studio not to step through the code in that project. All the other projects in my solutions debug without problems.</p> <p>What box have I checked to cause this behavior?</p> <p><strong>UPDATE FOR CLARITY</strong>: The "Just my code" option is currently disabled. Also, since the code belongs to a project in my same solution, I don't think the "Just my code" option applies here. I thought it only applied to pre-compiled code that I didn't have the source for, but since I have the source in my project, I don't think this option has any effect.</p>
<p>Not sure if this is it, but "Tools>Options>Debugging>General:Enable Just My Code" is a possibility. (I prefer to always leave this unchecked.)</p>
<p>A couple of possibilities:</p> <ul> <li><p>There is a check box to step into "just my code". Its intent is to make it so you can't step into Microsoft's Framework code (unless you choose to by unchecking the box). </p></li> <li><p>You might try recompiling the supporting code to make sure the code you're debugging exactly matches the code file you're looking at. VS does care about this and will disable a breakpoint if you put it in the code file whose version doesn't match. Also, make sure the PDB file is in the same directory as the DLL.</p></li> </ul>
27,445
<p>Note: I know very little about the GCC toolchain, so this question may not make much sense.</p> <p>Since GCC includes an Ada front end, and it can emit ARM, and devKitPro is based on GCC, is it possible to use Ada instead of C/C++ for writing code on the DS?</p> <p>Edit: It seems that the target that devKitARM uses is arm-eabi.</p>
<p>devkitPro is not a toolchain, compiler or indeed any software package. The toolchain used to target the DS is devkitARM, one of the toolchains provided by devkitPro.</p> <p>It may be possible to build the ada compiler but I doubt very much if you'll ever manage to get anything useful running on the DS itself. devkitPro will certainly never provide an ada compiler as part of the packages we produce.</p>
<p>On a practical plane, it is not possible.</p> <p>On a theoretical plane, you could use one custom Ada parser (I found <a href="http://www.antlr.org/grammar/ada" rel="nofollow noreferrer">this one</a> on the <a href="http://www.antlr.org" rel="nofollow noreferrer">ANTLR</a> site, but it is quite old) in order to translate Ada to C/C++, and then feed that to devkitpro.</p> <p>However, the effort of building such translator is probably going to be equal (if not higher) to creating the game itself.</p>
17,501
<p>I'm about to push out a website soon and so I've gotten in the last stages. Time to optimize the baby! The website performs pretty good overall, with an average framerate of 32fps. But at some heavy animation parts it likes to drop a couple of frames to about 22fps. Which is not that horrible. But I'm tweaking it as much as possible to keep it running at the highest speed possible.</p> <p>I might overlooked some tips and tricks to make this baby run even smoother. </p> <p>So hereby I open this thread to share whatever ninja tricks ever helped you in the past. A couple of mine which I can think of right now:</p> <p><strong>Sequencing the animation:</strong></p> <p>Let as less as possible transitions happen at the same time, try to make it act more as a transformer, one thing at a time. Next to gaining speed in animation, you probably end up gaining more flow.</p> <p><strong>Keep the animating objects as small as possible:</strong></p> <p>So flash has to calculate less pixels at the same time.</p> <p><strong>cacheAsBitmap = true:</strong></p> <p>Those big movieclips, vector shapes being moved around, are probably quicker moved when they are cached as a bitmap. Might take up some space in your memory, but anything for higher framerates ;)</p> <p><strong>Destroy everything you do not use:</strong></p> <p>Set those unused movieclips to null and then remove it as a child. So your garbage collector takes care of it.</p>
<p>Alpha transparency can be intensive to render...</p> <p>From what I've heard, the glow filter will wreak havoc if you are animating it.</p> <p>Use visible = false instead of alpha = 0 where possible.</p>
<p>Flash (8 - Actionscript 2 or below) will render a clip even if it's visibility is set to false - to stop it being rendered you need to move it off the 'visible' screen (i.e. x = -2000, provided the clips width is less than 2000). </p>
18,750
<p>I have recently purchased an Anet A8 but have been wondering why the prints look squished and have tiny balls on them. </p> <p>I am using 1.75&nbsp;mm cheap PLA bought from eBay and have also had problems of filament oozing out of the print block. </p> <p><img src="https://i.stack.imgur.com/9bEPO.jpg" alt="Photos of squished prints" title="Photos of squished prints">]<a href="https://i.stack.imgur.com/9bEPO.jpg" rel="nofollow noreferrer" title="Photos of squished prints">1</a></p>
<p>It could be that cheap filament has inconsistent diameter, or your calibration is over extruding, or you have something loose that needs to be tight. It's hard for me to tell precisely from just these images. In your shoes, I would print 20mm x 20mm x 10mm, 100% infill boxes until I got it dialed in so that it is square, fully filled in, but nice and flat.</p> <p>If they're coming out square and staying stuck to the build plate properly, but are bumpy and overfilled, then you're over extruding and you'll want to either recalibrate e-steps or if they're correct, adjust your flow rate in the slicer (down).</p> <p>If they aren't square then you need to square up your frame and tighten it and the belts.</p> <p>Etc.</p> <p>But my first guess is that you're extruding too much plastic since I'll bet they were flatter when they were still on the build plate, yes?</p> <p>On the question of ooze: you'll always get some ooze. Molten plastic and gravity means some will ooze out pretty much no matter what. What you need to worry about is when this results in stringing or unwanted lines on the surface of the print. These things you address with retraction (which reduces the pressure on the nozzle during travel moves, but can't stop gravity) and for the surface problem various travel, z-hop and combing strategies depending on your slicer.</p>
<p>You may be having an over-extrusion issue, you should check the flow rate in whatever slicer you use. </p> <p>You should also check to make sure that the filament diameter you are using matches that of the diameter setting in your slicer.</p>
587
<p>getEmployeeNameByBatchId(int batchID)<BR> getEmployeeNameBySSN(Object SSN)<BR> getEmployeeNameByEmailId(String emailID)<BR> getEmployeeNameBySalaryAccount(SalaryAccount salaryAccount)<BR></p> <p>or</p> <p>getEmployeeName(int typeOfIdentifier, byte[] identifier) -> In this methods the typeOfIdentifier tells if identifier is batchID/SSN/emailID/salaryAccount</p> <p>Which one of the above is better way implement a get method? </p> <p>These methods would be in a Servlet and calls would be made from an API which would be provided to the customers.</p>
<p>Why not overload the getEmployeeName(??) method? <br> <br> getEmployeeName(int BatchID)<br> <strike>getEmployeeName(object SSN)</strike>(bad idea)<br> getEmployeeName(String Email)<br> etc.</p> <p>Seems a good 'many' approach to me.</p>
<p>You are thinking C/C++.</p> <p>Use objects instead of an identifier byte (or int).</p> <p><strong>My Bad, the overload approach is better and using the SSN as a primary key is not so good</strong></p> <pre><code>public ??? getEmployeeName(Object obj){ if (obj instanceof Integer){ ... } else if (obj instanceof String){ ... } else if .... // and so on } else throw SomeMeaningFullRuntimeException() return employeeName } </code></pre> <p>I think it is better to use Unchecked Exceptions to signaling incorrect input.</p> <p>Document it so the customer knows what objects to expect. Or create your own wrappers. I prefer the first option.</p>
10,648
<p>Debugging some finance-related SQL code found a strange issue with numeric(24,8) mathematics precision.</p> <p>Running the following query on your MSSQL you would get A + B * C expression result to be 0.123457</p> <p>SELECT A, B, C, A + B * C FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A, CAST(0 AS NUMERIC(24,8)) AS B, CAST(500 AS NUMERIC(24,8)) AS C ) T</p> <p>So we have lost 2 significant symbols. Trying to get this fixed in different ways i got that conversion of the intermediate multiplication result (which is Zero!) to numeric (24,8) would work fine.</p> <p>And finally a have a solution. But still I hace a question - why MSSQL behaves in this way and which type conversions actually occured in my sample?</p>
<p>Just as addition of the float type is inaccurate, multiplication of the decimal types can be inaccurate (or cause inaccuracy) if you exceed the precision. See <a href="http://msdn.microsoft.com/en-us/library/ms191530%28SQL.90%29.aspx#_decimal" rel="noreferrer">Data Type Conversion</a> and <a href="http://msdn.microsoft.com/en-us/library/ms187746%28SQL.90%29.aspx" rel="noreferrer">decimal and numeric</a>.</p> <p>Since you multiplied <code>NUMERIC(24,8)</code> and <code>NUMERIC(24,8)</code>, and SQL Server will only check the type not the content, it probably will try to save the potential 16 non-decimal digits (24 - 8) when it can't save all 48 digits of precision (max is 38). Combine two of them, you get 32 non-decimal digits, which leaves you with only 6 decimal digits (38 - 32).</p> <p>Thus the original query </p> <pre><code>SELECT A, B, C, A + B * C FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A, CAST(0 AS NUMERIC(24,8)) AS B, CAST(500 AS NUMERIC(24,8)) AS C ) T </code></pre> <p>reduces to</p> <pre><code>SELECT A, B, C, A + D FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A, CAST(0 AS NUMERIC(24,8)) AS B, CAST(500 AS NUMERIC(24,8)) AS C, CAST(0 AS NUMERIC(38,6)) AS D ) T </code></pre> <p>Again, between <code>NUMERIC(24,8)</code> and <code>NUMERIC(38,6)</code>, SQL Server will try to save the potential 32 digits of non-decimals, so <code>A + D</code> reduces to </p> <pre><code>SELECT CAST(0.12345678 AS NUMERIC(38,6)) </code></pre> <p>which gives you <code>0.123457</code> after rounding.</p>
<p>Following the logic pointed out by <a href="https://stackoverflow.com/questions/126401/sql-server-2005-numeric-precision-loss#126473">eed3si9n</a> and what you said in your question it seems that the best approach when doing mathematics operations is to extract them into a function and additionally to specify precision after each operation,</p> <p>It this case the function could look something like:</p> <pre><code>create function dbo.myMath(@a as numeric(24,8), @b as numeric(24,8), @c as numeric(24,8)) returns numeric(24,8) as begin declare @d as numeric(24,8) set @d = @b* @c return @a + @d end </code></pre>
15,376
<p>I suspect that one of my applications eats more CPU cycles than I want it to. The problem is - it happens in bursts, and just looking at the task manager doesn't help me as it shows immediate usage only.</p> <p>Is there a way (on Windows) to track the history of CPU &amp; Memory usage for some process. E.g. I will start tracking "firefox", and after an hour or so will see a graph of its CPU &amp; memory usage during that hour.</p> <p>I'm looking for either a ready-made tool or a programmatic way to achieve this.</p>
<p>Press <kbd>Win</kbd>+<kbd>R</kbd>, type <code>perfmon</code> and press <kbd>Enter</kbd>. When the Performance window is open, click on the <strong>+</strong> sign to add new counters to the graph. The counters are different aspects of how your PC works and are grouped by similarity into groups called &quot;Performance Object&quot;.</p> <p>For your questions, you can choose the &quot;Process&quot;, &quot;Memory&quot; and &quot;Processor&quot; performance objects. You then can see these counters in real time</p> <p>You can also specify the utility to save the performance data for your inspection later. To do this, select &quot;Performance Logs and Alerts&quot; in the left-hand panel. (It's right under the System Monitor console which provides us with the above mentioned counters. If it is not there, click &quot;File&quot; &gt; &quot;Add/remove snap-in&quot;, click Add and select &quot;Performance Logs and Alerts&quot; in the list&quot;.) From the &quot;Performance Logs and Alerts&quot;, create a new monitoring configuration under &quot;Counter Logs&quot;. Then you can add the counters, specify the sampling rate, the log format (binary or plain text) and log location.</p>
<p>I use taskinfo for history graph of CPU/RAM/IO speed. <a href="http://www.iarsn.com/taskinfo.html" rel="nofollow noreferrer">http://www.iarsn.com/taskinfo.html</a></p> <p>But bursts of unresponsiveness, sounds more like interrupt time due to a falty HD/SS drive. </p>
9,474
<p><b>Summary:</b> C#/.NET is supposed to be garbage collected. C# has a destructor, used to clean resources. What happen when an object A is garbage collected the same line I try to clone one of its variable members? Apparently, on multiprocessors, sometimes, the garbage collector wins...</p> <p><b>The problem</b></p> <p>Today, on a training session on C#, the teacher showed us some code which contained a bug only when run on multiprocessors.</p> <p>I'll summarize to say that sometimes, the compiler or the JIT screws up by calling the finalizer of a C# class object before returning from its called method.</p> <p>The full code, given in Visual C++ 2005 documentation, will be posted as an &quot;answer&quot; to avoid making a very very large questions, but the essential are below:</p> <p>The following class has a &quot;Hash&quot; property which will return a cloned copy of an internal array. At is construction, the first item of the array has a value of 2. In the destructor, its value is set to zero.</p> <p>The point is: If you try to get the &quot;Hash&quot; property of &quot;Example&quot;, you'll get a clean copy of the array, whose first item is still 2, as the object is being used (and as such, not being garbage collected/finalized):</p> <pre><code>public class Example { private int nValue; public int N { get { return nValue; } } // The Hash property is slower because it clones an array. When // KeepAlive is not used, the finalizer sometimes runs before // the Hash property value is read. private byte[] hashValue; public byte[] Hash { get { return (byte[])hashValue.Clone(); } } public Example() { nValue = 2; hashValue = new byte[20]; hashValue[0] = 2; } ~Example() { nValue = 0; if (hashValue != null) { Array.Clear(hashValue, 0, hashValue.Length); } } } </code></pre> <p>But nothing is so simple... The code using this class is wokring inside a thread, and of course, for the test, the app is heavily multithreaded:</p> <pre><code>public static void Main(string[] args) { Thread t = new Thread(new ThreadStart(ThreadProc)); t.Start(); t.Join(); } private static void ThreadProc() { // running is a boolean which is always true until // the user press ENTER while (running) DoWork(); } </code></pre> <p>The DoWork static method is the code where the problem happens:</p> <pre><code>private static void DoWork() { Example ex = new Example(); byte[] res = ex.Hash; // [1] // If the finalizer runs before the call to the Hash // property completes, the hashValue array might be // cleared before the property value is read. The // following test detects that. if (res[0] != 2) { // Oops... The finalizer of ex was launched before // the Hash method/property completed } } </code></pre> <p>Once every 1,000,000 excutions of DoWork, apparently, the Garbage Collector does its magic, and tries to reclaim &quot;ex&quot;, as it is not anymore referenced in the remaning code of the function, and this time, it is faster than the &quot;Hash&quot; get method. So what we have in the end is a clone of a zero-ed byte array, instead of having the right one (with the 1st item at 2).</p> <p>My guess is that there is inlining of the code, which essentially replaces the line marked [1] in the DoWork function by something like:</p> <pre><code> // Supposed inlined processing byte[] res2 = ex.Hash2; // note that after this line, &quot;ex&quot; could be garbage collected, // but not res2 byte[] res = (byte[])res2.Clone(); </code></pre> <p>If we supposed Hash2 is a simple accessor coded like:</p> <pre><code>// Hash2 code: public byte[] Hash2 { get { return (byte[])hashValue; } } </code></pre> <p>So, the question is: <b>Is this supposed to work that way in C#/.NET, or could this be considered as a bug of either the compiler of the JIT?</b></p> <h1>edit</h1> <p>See Chris Brumme's and Chris Lyons' blogs for an explanation.</p> <p><a href="http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx</a><br> <a href="http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx</a></p> <p>Everyone's answer was interesting, but I couldn't choose one better than the other. So I gave you all a +1...</p> <p>Sorry</p> <p>:-)</p> <h1>Edit 2</h1> <p>I was unable to reproduce the problem on Linux/Ubuntu/Mono, despite using the same code on the same conditions (multiple same executable running simultaneously, release mode, etc.)</p>
<p>It's simply a bug in your code: finalizers should not be accessing managed objects.</p> <p>The only reason to implement a finalizer is to release unmanaged resources. And in this case, you should carefully implement <a href="http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx" rel="noreferrer">the standard IDisposable pattern</a>.</p> <p>With this pattern, you implement a protected method "protected Dispose(bool disposing)". When this method is called from the finalizer, it cleans up unmanaged resources, but does not attempt to clean up managed resources.</p> <p>In your example, you don't have any unmanaged resources, so should not be implementing a finalizer.</p>
<h2>The Full Code</h2> <p>You'll find below the full code, copy/pasted from a Visual C++ 2008 .cs file. As I'm now on Linux, and without any Mono compiler or knowledge about its use, there's no way I can do tests now. Still, a couple of hours ago, I saw this code work and its bug:</p> <pre><code>using System; using System.Threading; public class Example { private int nValue; public int N { get { return nValue; } } // The Hash property is slower because it clones an array. When // KeepAlive is not used, the finalizer sometimes runs before // the Hash property value is read. private byte[] hashValue; public byte[] Hash { get { return (byte[])hashValue.Clone(); } } public byte[] Hash2 { get { return (byte[])hashValue; } } public int returnNothing() { return 25; } public Example() { nValue = 2; hashValue = new byte[20]; hashValue[0] = 2; } ~Example() { nValue = 0; if (hashValue != null) { Array.Clear(hashValue, 0, hashValue.Length); } } } public class Test { private static int totalCount = 0; private static int finalizerFirstCount = 0; // This variable controls the thread that runs the demo. private static bool running = true; // In order to demonstrate the finalizer running first, the // DoWork method must create an Example object and invoke its // Hash property. If there are no other calls to members of // the Example object in DoWork, garbage collection reclaims // the Example object aggressively. Sometimes this means that // the finalizer runs before the call to the Hash property // completes. private static void DoWork() { totalCount++; // Create an Example object and save the value of the // Hash property. There are no more calls to members of // the object in the DoWork method, so it is available // for aggressive garbage collection. Example ex = new Example(); // Normal processing byte[] res = ex.Hash; // Supposed inlined processing //byte[] res2 = ex.Hash2; //byte[] res = (byte[])res2.Clone(); // successful try to keep reference alive //ex.returnNothing(); // Failed try to keep reference alive //ex = null; // If the finalizer runs before the call to the Hash // property completes, the hashValue array might be // cleared before the property value is read. The // following test detects that. if (res[0] != 2) { finalizerFirstCount++; Console.WriteLine(&quot;The finalizer ran first at {0} iterations.&quot;, totalCount); } //GC.KeepAlive(ex); } public static void Main(string[] args) { Console.WriteLine(&quot;Test:&quot;); // Create a thread to run the test. Thread t = new Thread(new ThreadStart(ThreadProc)); t.Start(); // The thread runs until Enter is pressed. Console.WriteLine(&quot;Press Enter to stop the program.&quot;); Console.ReadLine(); running = false; // Wait for the thread to end. t.Join(); Console.WriteLine(&quot;{0} iterations total; the finalizer ran first {1} times.&quot;, totalCount, finalizerFirstCount); } private static void ThreadProc() { while (running) DoWork(); } } </code></pre> <p>For those interested, I can send the zipped project through email.</p>
16,301
<p>Could anybody explain in plain words how Cloud computing works? I have read the <a href="http://en.wikipedia.org/wiki/Cloud_computing" rel="noreferrer">Wikipedia article</a>, but still not sure that I understand how cloud actually works.</p>
<p>Aside from the latest marketing term?</p> <p>Basically all the resources your program needs are held "somewhere" on the internet. You interact with them via a defined service contract; SOAP, REST, POX or whatever and what happens after that is up to the service provider. You don't care about how your information is stored or how the service is provided, just that it is.</p> <p>If, for example, you wanted to store files, you may choose to use Amazon's S3 cloud system. You connect to the service and upload your files; you don't know or care where the files are stored, only the location of the entry point to that service.</p> <p>If you have an application then it may also be ran in the cloud, assuming it's suitable. Live Mesh for example is a virtual machine which you can code against and run your software both locally and within the cloud, so your user simply goes to a URI and finds your program, you don't care where it is beyond it being available somewhere on the cloud.</p>
<p>None of those things makes your application a cloud application. It's a cloud application if it runs in a cloud. What is a cloud?</p> <p><a href="https://stackoverflow.com/questions/1349894/difference-between-cloud-computing-and-distributed-computing">Difference between cloud computing and distributed computing?</a></p> <p>The web site development model does tend to be amenable to running in a cloud because many parts of the system are inherently parallel. However, there are various design decisions (er, mistakes?) you could make that would limit the amount of parallelism that could be achieved, though. You can still run such a program in a cloud but it won't get nearly the kind of benefit that a highly parallel application would.</p> <p>The technologies that you are talking about can be used to create highly parallel applications, but this isn't automatic, you still have to understand what you're doing.</p>
13,342
<p>If everything that can be accomplished in <a href="http://en.wikipedia.org/wiki/MXML" rel="nofollow noreferrer">MXML</a> can also be accomplished in ActionScript and many things are easier to accomplish in ActionScript (loops, conditionals, etc) why take the time to learn MXML?</p> <p>The best reasons I have at this point are that the structure of the MXML nicely matches the visual hierarchy of the UI components and that the lines of code to initialize the UI are reduced. On the other hand real-world UIs are often dynamic, implemented as a simple static structure and then filled in dynamically based on runtime conditions (in which case UI updates are in ActionScript anyway). It would also be possible to reduce the <a href="http://en.wikipedia.org/wiki/Source_lines_of_code" rel="nofollow noreferrer">SLOC</a> needed for ActionScript with the creation of a few helper methods.</p>
<p>It depends on your application's needs, but I generally break my design into visual chunks and use custom MXML components to lay out the main areas and components of my application (data panels, dialog boxes, etc) using mxml based custom components. Then I'll augment that with custom actionscript components where I need more visual flexibilty than the built in layout components provide. MXML is handy because it makes it extremely easy to get components on the stage and set their various properties and style settings.</p> <p>Take this example of two identical login panels:</p> <p>In MXML:</p> <pre><code>&lt;mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="290" height="148" title="Login"&gt; &lt;mx:Label text="User name:" width="80" textAlign="right" y="8" x="8"/&gt; &lt;mx:Label text="Password:" width="80" textAlign="right" y="38" x="8"/&gt; &lt;mx:TextInput id="txtUsername" maxChars="20" y="8" x="90"/&gt; &lt;mx:TextInput id="txtPassword" displayAsPassword="true" y="38" x="90" maxChars="20"/&gt; &lt;mx:Button x="185" y="68" label="Login" id="btnLogin" click="doLogin()"/&gt; &lt;/mx:Panel&gt; </code></pre> <p>And in actionscript:</p> <pre><code>package { import flash.events.MouseEvent; import mx.containers.Panel; import mx.controls.Button; import mx.controls.Label; import mx.controls.TextInput; public class MyLoginPanel extends Panel { private var _unLabel:Label; private var _passLabel:Label; private var _txtUsername:TextInput; private var _txtPassword:TextInput; private var _btnLogin:Button; public function MyLoginPanel() { } override protected function createChildren():void { super.createChildren(); this.width = 290; this.height = 148; this.title = "Login"; this.layout = "absolute"; _unLabel = new Label(); _unLabel.text = "User Name:"; _unLabel.width = 80; _unLabel.setStyle("textAlign", "right"); _unLabel.move(8, 8); this.addChild(_unLabel); _passLabel = new Label(); _passLabel.text = "Password:"; _passLabel.width = 80; _passLabel.setStyle("textAlign", "right"); _passLabel.move(8, 38); this.addChild(_passLabel); _txtUsername = new TextInput(); _txtUsername.move(90, 8); this.addChild(_txtUsername); _txtPassword = new TextInput(); _txtPassword.move(90, 38); _txtPassword.displayAsPassword = true; this.addChild(_txtPassword); _btnLogin = new Button(); _btnLogin.label = "Login"; _btnLogin.move(185, 68); _btnLogin.addEventListener(MouseEvent.CLICK, doLogin); this.addChild(_btnLogin); } } } </code></pre> <p>Seven lines of code vs 62. That's a pretty simple example, but hopefully you can see how you might benefit by laying out many portions of your application in MXML, whether you're using the design mode in Flex Builder or not.</p> <p>One thing I do recommend however is keep actionscript out of your mxml files as much as possible. Treat MXML as your view and separate any heavy functionality into other classes. You can then provide public properties in those classes that the controls in your MXML components can bind to. MXML is a layout language and in my experience it pays in the end to use it where it makes sense and drop into actionscript whenever heavier lifting is required.</p>
<p>Designing UI elements with mxml and the visual designer is much easier than in code, and less error-prone in my opinion.</p> <p>Even if the UI changes dynamically, often this means swapping pre-defined UI elements in and out.</p>
32,764
<p>I have a couple databases on a shared SQL Server 2005 cluster instance, that I would like performance metrics on. I have some processes that run for a very long time and suspect that code inefficiencies, rather than insufficient hardware are to blame.</p> <p>I would like some way to get these performance metrics so that I can rule out the database hardware as the culprit.</p>
<p>The trick is to subscribe to the databinding event of the itemplaceholder in the ItemTemplate. </p> <p>The complete solution:</p> <pre><code>public class FibonacciControl : CompositeControl { public FibonacciControl() { // .... } protected override void CreateChildControls() { base.CreateChildControls(); ListView view = new ListView(); view.LayoutTemplate = new LayoutTemplate(); view.ItemTemplate = new ItemTemplate(); view.DataSource = FibonacciSequence(); view.DataBind(); this.Controls.Add(view); } private IEnumerable&lt;int&gt; FibonacciSequence() { int i1 = 0; int i2 = 1; for (int i = 0; i &lt; Iterations; i++) { yield return i1 + i2; int temp = i1 + i2; i1 = i2; i2 = temp; } yield break; } public int Iterations { get; set; } private class LayoutTemplate : ITemplate { public void InstantiateIn(Control container) { var ol = new HtmlGenericControl("ol"); var li = new HtmlGenericControl("li") { ID = "itemPlaceholder" }; ol.Controls.Add(li); container.Controls.Add(ol); } } private class ItemTemplate : ITemplate { public void InstantiateIn(Control container) { var li = new HtmlGenericControl("li"); li.DataBinding += DataBinding; container.Controls.Add(li); } public void DataBinding(object sender, EventArgs e) { var container = (HtmlGenericControl)sender; var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem; container.Controls.Add( new Literal(){Text = dataItem.ToString() }); } } } </code></pre>
<p>Setup a class like:</p> <pre><code>public delegate void InstantiateTemplateDelegate(Control container); public class GenericTemplateImplementation : ITemplate { private InstantiateTemplateDelegate instantiateTemplate; public void InstantiateIn(Control container) { this.instantiateTemplate(container); } public GenericTemplateImplementation(InstantiateTemplateDelegate instantiateTemplate) { this.instantiateTemplate = instantiateTemplate; } } </code></pre> <p>And then do the following:</p> <pre><code> view.LayoutTemplate = new GenericTemplateImplementation(p =&gt; { p.Controls.Add(new Label { Text = "Foo" }); }); </code></pre>
11,815
<p><strong>PHONE HOME</strong></p> <p>Everybody wants to now and then. ...What about software when it grows up and becomes a mature product? Shouldn't it be an adult and live in its new home quietly? Or, should it show some affection from whence it came?...</p> <p>I've heard some say they'd rip out from the platters any bits that try and communicate without their say so. I've also noticed a large number of products that now routinely ask for permission to send statistical use information. And there are many levels in between.</p> <p>I'm sitting on the fence. </p> <p>There’s a long paragraphs explanation of how this question came to me, but for all our sakes, I wrote then deleted it. Suffice to say, I’m Chief Scientist, an officer of the company <em>and</em> head of our development efforts; this is a really big deal and I’m looking for insight from the programming community as I'm not getting any useful feedback here...</p> <p>The biggest argument for <strong>PHONE HOME</strong> is that some involved fear there is likely to be serious attempts to cheat the contract(s) and if the software occasionally phoned home it would help detect cheating (for which there are penalties).</p> <p>Other pro arguments are that it can provide usage statistics and perhaps detect when updates are appropriate.</p> <p>The biggest argument against is that it’s offensive.</p> <p>I also haven’t a clue how I would architect this. Clearly, everything calling home all the time is not going to fly. There are a half dozen major products and some will run 24 X 7 X 365.24 and some will be up and down like a frigen yo-yo, yet some data on all of them would be nice - Local repository?</p> <p>Then there’s connection strategy – a mail message, while convenient, may be a bad call because it can be more obtrusive (perhaps). Then, a simple TCP ssh call may not be so great, either.</p> <p>So, how about it? If you’re pro, please tell me why. If you’re against, why also. Examples of "doing it right?" Contractual text you like somewhere - or hate?</p> <p>Next, IF we decide to do it, how should we do it – how would YOU do it? Why?</p> <p>Frankly, I’m <em>profoundly</em> torn. I hate such things in general, but as an officer of the company, I have to acknowledge above my own feelings, there’s potentially a lot of money on the table here, and being offended may not be a good argument.</p> <p>Thanks for your thoughts.</p>
<p>Informed consent, where informed means that the type, frequency and content of the information you'll be sending is told to the client is truly the only reasonable option, else you start closely resembling a malware author. People will find out and will dislike you a lot if you tried to pull it off sneakily. You probably can and should present it as a means to improve the service though, everybody likes software that reports bugs by itself.</p> <p>This means you cannot rely on this to be your cheat detection mechanism, but, given that there's a lot of money on the table, you may be able to contractually put some random inspections. For instance you could register locally the data you'd otherwise send and go look at it in the inspections. I don't think you are forced to declare you'll be locally registering usage information (IANAL, YMMV, WTF, BBQ)</p>
<p>Applications "phon[ing] home" is a very generic term, mostly used in a rather hysterical way ("iPhone phones home!!", "Microsoft Vista phones home!!")</p> <p>Any software that checks for updates is "phoning home". I simply do not care if it does this.</p> <p>Conversely, crapware (adware/spyware/viruses) that submits as much info as possible <em>is</em> a problem.</p> <p>I suppose it depends on..</p> <ul> <li>..what data is sent</li> <li>..if the user is aware of what data is sent</li> </ul> <p>Sparkle (the OS X application update framework) has the ability to send some basic system information while checking for updates.</p> <p>Almost every application I've seen use Sparkle has an option titled "Send anonymous system information" next to "Check for updates". More importantly, it has a "Show what information is sent" button. The data is sends back is stuff like CPU type (Intel or PPC), mac model (Mabook, Macbook Pro etc), number of CPUs, CPU speed.</p> <p>That is a great system - most people simply don't care, and it gives the developers are overview of what sort of systems people are using their application on. If you are paranoid about it, you can either disable update-checking, or if you want automatic-updates, tell it to send no information (aside from your IP address, obviously)</p>
29,192
<p>I have a table of events with a recorded start and end time as a MySQL DATETIME object (in the format <code>YYYY-MM-DD HH:MM:SS</code>. I want to find all events that occur in a specific date range. However, events can span multiple days (and go outside of my date range, but I want to return them if they even overlap by 1 second or more with my date range).</p> <p>Suggestions?</p>
<p>This will find every event that is completely contained inside the range:</p> <pre><code>SELECT * FROM table WHERE start_date BETWEEN start_of_range AND end_of_range AND stop_date BETWEEN start_of_range AND end_of_range </code></pre> <p>This will find any events where any part of the event overlaps any part of the range:</p> <pre><code>SELECT * FROM table WHERE start_date &lt;= end_of_range AND stop_date &gt;= start_of_range </code></pre>
<p>Llya, Roberts answer with,</p> <p>SELECT * FROM table WHERE start_date &lt;= end_of_range AND stop_date >= start_of_range</p> <p>works fine with,</p> <p>D) events with both starting and ending dates outside the range, but overlapping it</p> <p>??</p>
35,088
<p>Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?</p>
<pre class="lang-py prettyprint-override"><code>def isbound(method): return method.im_self is not None def instance(bounded_method): return bounded_method.im_self </code></pre> <p><a href="https://docs.python.org/2.7/reference/datamodel.html#index-40" rel="nofollow noreferrer">User-defined methods:</a></p> <blockquote> <p>When a user-defined method object is created by retrieving a user-defined function object from a class, its <code>im_self</code> attribute is <code>None</code> and the method object is said to be unbound. When one is created by retrieving a user-defined function object from a class via one of its instances, its <code>im_self</code> attribute is the instance, and the method object is said to be bound. In either case, the new method's <code>im_class</code> attribute is the class from which the retrieval takes place, and its <code>im_func</code> attribute is the original function object.</p> </blockquote> <p>In Python <a href="https://docs.python.org/2.7/whatsnew/2.6.html" rel="nofollow noreferrer">2.6 and 3.0</a>:</p> <blockquote> <p>Instance method objects have new attributes for the object and function comprising the method; the new synonym for <code>im_self</code> is <code>__self__</code>, and <code>im_func</code> is also available as <code>__func__</code>. The old names are still supported in Python 2.6, but are gone in 3.0.</p> </blockquote>
<p>A solution that works for both Python 2 and 3 is tricky.</p> <p>Using the package <a href="https://six.readthedocs.io/" rel="nofollow noreferrer"><code>six</code></a>, one solution could be:</p> <pre class="lang-py prettyprint-override"><code>def is_bound_method(f): &quot;&quot;&quot;Whether f is a bound method&quot;&quot;&quot; try: return six.get_method_self(f) is not None except AttributeError: return False </code></pre> <p>In Python 2:</p> <ul> <li>A regular function won't have the <code>im_self</code> attribute so <code>six.get_method_self()</code> will raise an <code>AttributeError</code> and this will return <code>False</code></li> <li>An unbound method will have the <code>im_self</code> attribute set to <code>None</code> so this will return <code>False</code></li> <li>An bound method will have the <code>im_self</code> attribute set to non-<code>None</code> so this will return <code>True</code></li> </ul> <p>In Python 3:</p> <ul> <li>A regular function won't have the <code>__self__</code> attribute so <code>six.get_method_self()</code> will raise an <code>AttributeError</code> and this will return <code>False</code></li> <li>An unbound method is the same as a regular function so this will return <code>False</code></li> <li>An bound method will have the <code>__self__</code> attribute set (to non-<code>None</code>) so this will return <code>True</code></li> </ul>
7,666
<p>While I grew up using MSWindows, I transitioned to my much-loved Mac years ago. I don't want to start a flame war here on operating systems. I do, however, want a terminal a litle closer to what I'm used to.</p> <p>I'm not asking for full POSIX support - I don't have the patience to install Cygwin - but I miss tabbed terminals, being able to easily cut and paste, and my good friends <code>ls</code>, <code>mkdir</code>, <code>rm</code>, et al. (For these last ones, I could always put .bat files on my path, but that's going to get old fast.)</p> <p>Anybody have a terminal application for MSWindows XP ?</p>
<p>Some more options:</p> <p><a href="http://www.mingw.org" rel="nofollow noreferrer">MSYS</a>: a Minimal SYStem providing a POSIX compatible Bourne shell environment, with a small collection of UNIX command line tools. Primarily developed as a means to execute the configure scripts and Makefiles used to build Open Source software, but also useful as a general purpose command line interface to replace Windows cmd.exe.</p> <p><a href="http://unxutils.sourceforge.net" rel="nofollow noreferrer">GNU utilities for Win32</a>: ports of common GNU utilities to native Win32. In this context, native means the executables do only depend on the Microsoft C-runtime (msvcrt.dll) and not an emulation layer like that provided by Cygwin tools.</p>
<p><a href="http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx" rel="nofollow noreferrer">PowerShell</a> is worth looking into. </p>
3,136
<p>Which technology stack is best for the creation of a two dimensional MMORPG and why?</p> <p>This question is loaded, so which are the major factors would you consider for development in such a domain?</p>
<p>I develop Flash for a living, so my answer should be taken with a grain of salt. I reccomend Flash for the following reasons:</p> <ol> <li>Size of install base. I don't have numbers for Silverlight but Flash 9 (the latest non-alpha revision) is <a href="http://www.adobe.com/products/player_census/flashplayer/version_penetration.html" rel="nofollow noreferrer">over 90%</a>.</li> <li><a href="http://www.adobe.com/products/air/" rel="nofollow noreferrer">Air</a> alows you to deploy to a desktop on multiple platforms with minor changes to your online code. This again increases your potential market.</li> <li>Size of community. Flash has been around much longer and there is a <em>huge</em> community developing libraries for most anything you want from animation to 3d to physics. Think of the hundreds (or thousands) of Flash games you have encountered. You will have the leverage of greater experience if you go with Flash. I searched for <a href="http://www.google.com/search?q=flash%20mmorpg%20tutorial" rel="nofollow noreferrer">Flash MMORPG tutorial</a> on google and there are a bunch of results to get you started right now.</li> <li>Performance of the Flash player is equal to or greater than Silverlight on tests. (see <a href="http://bubblemark.com/" rel="nofollow noreferrer">Bubblemark</a> and <a href="http://www.craftymind.com/guimark/" rel="nofollow noreferrer">GuiMark</a>).</li> </ol> <p>A little while ago I did a simple comparison that I suggest you do as well. Find the <em>best</em> silverlight examples that you can. Then find the <em>best</em> Flash examples that you can. When you compare those to one another I think the best platform becomes obvious.</p>
<p>Being a .Net person, I'd say Silverlight.</p> <ul> <li>Being a game, speed is important, so .Net's JIT compiling is a bonus. I'm not sure if ActionScript is compiled or not.</li> <li>Lots of libraries available for .Net, geared towards game development. For example, you can implement a custom GraphicsDevice for the XNA framework, and use that.</li> </ul>
24,455
<p>i am planning a simple, dual-language website and i'd like to use a .net based cms but i can't find anything suitable. i have experience with dotnetnuke and sharepoint but neither fit the bill - dotnetnuke does not do dynamic site elements multi-lingually &amp; sharepoint is a monster PITA no matter what angle you look at it :).</p> <p>i am on the verge of choosing Joomla! &amp; Joom!Fish. they fit the bill nicely, with one exception: i would like to create some cms plug-ins and i would much prefer to write them in .net. any suggestions?</p>
<p>Have you looked at <a href="http://www.umbraco.org/" rel="nofollow noreferrer">Umbraco</a>? I have worked with it to try out for clients and it looks really good.</p> <p>I would look to them as a possible solution.</p>
<p>For .NET, assuming you're comfortable with XSLT, Umbraco - <a href="http://www.umbraco.org" rel="nofollow noreferrer">www.umbraco.org</a></p> <p>The XSLT qualification is important because that's the basis of the template (for content) system so whilst the end users have no requirement to use XSLT those defining the templates will.</p> <hr> <p>Edit:</p> <p>As we roll towards the end of 2011 there is now an alternative to XSLT, support for the Razor engine is being added to Umbraco and its fair to say that Razor is probably a bit less challenging than XSLT (much as I continute to be impressed by what one can do with XSLT, it does need a different mindset).</p>
5,398
<p>I have the following code for a UDF but it errors with the message:</p> <blockquote> <p>Msg 156, Level 15, State 1, Procedure CalendarTable, Line 39 Incorrect syntax near the keyword 'OPTION'.</p> </blockquote> <p>is it because of my WITH statement as I can run the same code fine in a stored procedure?</p> <pre><code>SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Anthony Main -- Create date: 18/11/08 -- Description: Produce Table of Dates for Month -- ============================================= CREATE FUNCTION CalendarTable ( @StartDate DATETIME, @EndDate DATETIME ) RETURNS TABLE AS RETURN ( with MyCalendar as ( select cast(@StartDate as datetime) DateValue union all select DateValue + 1 from MyCalendar where DateValue + 1 &lt;= @EndDate ) select DateValue , datepart(dy, DateValue) [day of year] , datename(dw, DateValue) [day] , datepart(dw, DateValue-1) [day of week] , datepart(dd, DateValue) [day of month] , datepart(ww, DateValue) [week] , datepart(mm, DateValue) [month] , datename(mm, DateValue) [month] , datepart(qq, DateValue) [quarter] , datepart(yy, DateValue) [year] , datepart(HH, DateValue) [HOUR] , datepart(MI, DateValue) [MIN] , datepart(SS, DateValue) [SEC] , datepart(MS, DateValue) [MILLISECOND] from MyCalendar OPTION (MAXRECURSION 0) ) GO </code></pre>
<p>No, you can't use the OPTION keyword.</p> <p>From the documentation: "MAXRECURSION can be used to prevent a poorly formed recursive CTE from entering into an infinite loop. The following example intentionally creates an infinite loop and uses the MAXRECURSION hint to limit the number of recursion levels to two."</p> <p>If you explain what you want to query (what do you want the end results to look like), we could write a better SQL statement that doesn't need recursion.</p>
<p>Are you missing a closing bracket here? (the closing bracket for "AS RETURN ("</p>
39,523
<p>I've always preferred using XSD.exe/VS.Net to generate schema, generate classes off the schema, deserialize xml file into object tree to parse an XML file. [Well, most of my requirements thus far have made this a perfect choice].</p> <p>I've a crib though: The class names generated by XSD.exe are weird - meaning XSD.exe strives to keep them unique by concatnating all the preceding ancester tag names.</p> <p>Is there a way I could customize this? Or perhaps a tool to run on top of this?</p> <p>My motive is to keep <em>auto generated</em> code inviolate.</p> <p>Thoughts?</p>
<p>It sounds like its the schema being autogenerated that is causing the problem. I've used the class generation part of XSD.exe and the class have usually been fine.</p> <p>If the schema is being automatically generated then its probably going to need a bit of tweaking manually to correct the crazy node names.</p>
<p>I'm really starting to wish for a simple way to alter the output of xsd.exe without resorting to hacking codedom... seems like a project that just "needs to happen"... </p>
36,326
<p>I've found a answer how to remove diacritic characters on stackoverflow, but could you please tell me if it is possible to change diacritic characters to non-diacritic ones?</p> <p>Oh.. and I think about .NET (or other if not possible)</p>
<p>Copying from <a href="https://stackoverflow.com/questions/285228/how-to-convert-utf-8-to-us-ascii-in-java#285791">my own answer to another question</a>:</p> <blockquote> <p>Instead of creating your own table, you could instead convert the text to normalization form D, where the characters are represented as a base character plus the diacritics (for instance, "á" will be replaced by "a" followed by a combining acute accent). You can then strip everything which is not an ASCII letter.</p> <p>The tables still exist, but are now the ones from the Unicode standard.</p> <p>You could also try NFKD instead of NFD, to catch even more cases.</p> <p>References:</p> <ul> <li><a href="http://unicode.org/reports/tr15/" rel="nofollow noreferrer">http://unicode.org/reports/tr15/</a></li> <li><a href="http://www.siao2.com/2005/02/19/376617.aspx" rel="nofollow noreferrer">http://www.siao2.com/2005/02/19/376617.aspx</a></li> <li><a href="http://www.siao2.com/2007/05/14/2629747.aspx" rel="nofollow noreferrer">http://www.siao2.com/2007/05/14/2629747.aspx</a></li> </ul> </blockquote>
<p>My site inputs data from external sources which have many strange characters. I wrote the following C# function to replace accented characters and strip out non-US keyboard characters using Regex:</p> <pre><code> using System.Text; using System.Text.RegularExpressions; internal static string SanitizeString(string source) { return Regex.Replace(source.Normalize(NormalizationForm.FormD), @"[^A-Za-z 0-9 \.,\?'""!@#\$%\^&amp;\*\(\)-_=\+;:&lt;&gt;\/\\\|\}\{\[\]`~]*", string.Empty).Trim(); } </code></pre> <p>Hope it helps.</p>
42,915
<p>I've found myself increasingly unsatisfied with the DataSet/DataTable/DataRow paradigm in .Net, mostly because it's often a couple of steps more complicated than what I really want to do. In cases where I'm binding to controls, DataSets are fine. But in other cases, there seems to be a fair amount of mental overhead.</p> <p>I've played a bit with SqlDataReader, and that seems to be good for simple jaunts through a select, but I feel like there may be some other models lurking in .Net that are useful to learn more about. I feel like all of the help I find on this just uses DataSet by default. Maybe that and DataReader really are the best options.</p> <p>I'm not looking for a best/worst breakdown, just curious what my options are and what experiences you've had with them. Thanks!</p> <p>-Eric Sipple</p>
<p>Since .NET 3.5 came out, I've exclusively used LINQ. It's really that good; I don't see any reason to use any of those old crutches any more. </p> <p>As great as LINQ is, though, I think any ORM system would allow you to do away with that dreck.</p>
<p>I NEVER use datasets. They are big heavyweight objects only usable (as someone pointed out here) for "demoware". There are lot's of great alternatives shown here.</p>
3,909
<p>I have a bulletin board (punBB based) that I was running out of the root directory for a couple of years. I foolishly decided to do a little gardening and in the process moved the punbb code into it's own subdirectory. The code works great; as long as you point the browser at the new subdirectory. The issue is that the users expect to see it at the root...</p> <p>I tried an index file in the root that had the following:</p> <pre><code>&lt;?php chdir('punbb'); include('index.php'); </code></pre> <p>But that didn't seem to do the trick. So, I tried using the "damn cool voodoo" of mod_rewrite in .htaccess but I can't seem to figure out the right combination of rules to make it work.</p> <p>Here is what I would like to make happen:</p> <p>User enters: </p> <pre><code> http://guardthe.net </code></pre> <p>Browser displays: </p> <pre><code> http://guardthe.net/punbb/ </code></pre> <p>or</p> <pre><code> http://punbb.guardthe.net/ </code></pre> <p>Is this possible, or should I just move the code base back into the root?</p>
<p>Something like this in .htacces should do it:</p> <pre><code> RewriteEngine On RewriteRule ^/?$ /punbb/ [R=301,L] </code></pre> <p>The 301 return code is to mark the move as permanentm making it posible for the browser to update bookmarks.</p>
<p>Your example code is missing but here's one way to do it using mod_rewrite:</p> <pre><code>RewriteEngine on RewriteRule ^$ http://guardthe.net/punbb/ [L,R=301] </code></pre>
10,071
<p>I have a library I created,</p> <h3>File <em>mylib.c:</em></h3> <pre><code>#include &lt;mylib.h&gt; int testlib() { printf(&quot;Hello, World!\n&quot;); return (0); } </code></pre> <h3>File <em>mylib.h:</em></h3> <pre><code>#include &lt;stdio.h&gt; extern int testlib(); </code></pre> <p>In my program, I've attempted to call this library function:</p> <h3>File <em>myprogram.c</em>:</h3> <pre><code>#include &lt;mylib.h&gt; int main (int argc, char *argv[]) { testlib(); return (0); } </code></pre> <p>When I attempt to compile this program I get the following error:</p> <pre>In file included from myprogram.c:1 mylib.h:2 warning: function declaration isn't a prototype</pre> <p>I'm using: <code>gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2)</code></p> <p>What is the proper way to declare a function prototype?</p>
<p>In C <code>int foo()</code> and <code>int foo(void)</code> are different functions. <code>int foo()</code> accepts an arbitrary number of arguments, while <code>int foo(void)</code> accepts 0 arguments. In C++ they mean the same thing. I suggest that you use <code>void</code> consistently when you mean no arguments.</p> <p>If you have a variable <code>a</code>, <code>extern int a;</code> is a way to tell the compiler that <code>a</code> is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (<code>extern</code>, <code>static</code>) only affects its visibility and <code>extern</code> is the default, so <code>extern</code> is actually unnecessary.</p> <p>I suggest removing the <code>extern</code>, it is extraneous and is usually omitted. </p>
<p>Try:</p> <pre><code>extern int testlib(void); </code></pre>
6,351
<p>I have played with the idea of using a wiki (MediaWiki) to centralize all project information for a development project. This was done using extensions that pull information from SVN (using <a href="http://svnkit.com/" rel="nofollow noreferrer">SVNKit</a>) and by linking to Bugzilla to extract work assigned to a developer or work remaining for a release.</p> <p>Examples:</p> <pre><code>&lt;bugzilla type="summary" user="richard.tasker@gmail.com" /&gt; </code></pre> <p>would return a summary</p> <p><img src="https://i.stack.imgur.com/rfJjy.png" alt="Bugzilla Summary"></p> <pre><code>&lt;bugzilla type="status" status="ASSIGNED" product="SCM BEPPI" /&gt; </code></pre> <p>would return</p> <p><img src="https://i.stack.imgur.com/YSV0t.png" alt="Bugzilla Status"></p> <p>Do you think that this would be useful? If so then what other integrations would you think would be valuable?</p>
<p>I think this would be extremly useful. Depending on the size of a project team members come and go. And a wiki is a good tool to keep the history and the "spirit" of a project available to new team members. I did that in many projects, and though the projects were already finished, all the informations are available.</p> <p>One more idea: also try to integrate meeting schedules, minutes etc. If your team communicates via IM, try to integrate a log of the conversations.</p>
<p>The other classic integration would be your source code repository, e.g. svn, or cvs. <a href="http://trac.edgewall.org/" rel="nofollow noreferrer">trac</a> is an existing product that does exactly this - it combines a wiki, custom bug tracker, and integrates nicely with svn.</p>
7,213
<p>C#: What is the proper way to change the font style (underline) from a Label at runtime?</p> <p>So far I understand that if you want to change font related properties at runtime from a label, mainly all font properties, you would have to use,</p> <pre><code> lblName.Font = new Font(... etc. etc. </code></pre> <p>Is there a shortcut to the above but only assign nothing but a new Font style such FontStyle.Underline? </p> <p>or </p> <p>Would I have to proceed with using the "new Font()" method and assign all fields along with it too just to underline my label?</p>
<p>The way you did it:</p> <pre><code>this.Font = new Font(this.Font, FontStyle.Underline); </code></pre> <p>is correct. The reason is that Font is a sealed and immutable type (by design). When introduced in .NET 1 this seemed a bit strange but with today's emphasis on functional programming, concurrency and immutability this style is seen a lot more. Perhaps it was done this way since controls inherit the font of their container and tracking individual font property changes would be more work than tracking a wholesale font change. </p>
<p>How about (I'm using .Net Framework 2.0) Okay so this works for a Web Application. In a forms application it is read-only.</p> <p>lblName.Font.Underline = true;</p> <p>Here's the definition:</p> <pre><code> // // Summary: // Gets or sets a value that indicates whether the font is underlined. // // Returns: // true if the font is underlined; otherwise, false. The default value is false. [DefaultValue(false)] [NotifyParentProperty(true)] public bool Underline { get; set; } </code></pre>
34,894
<p>I've come across this term POD-type a few times.<br> What does it mean? </p>
<p><em>POD</em> stands for <em>Plain Old Data</em> - that is, a class (whether defined with the keyword <code>struct</code> or the keyword <code>class</code>) without constructors, destructors and virtual members functions. <a href="http://en.wikipedia.org/wiki/Plain_Old_Data_Structures" rel="noreferrer">Wikipedia's article on POD</a> goes into a bit more detail and defines it as:</p> <blockquote> <p>A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.</p> </blockquote> <p>Greater detail can be found in <a href="https://stackoverflow.com/a/4178176/734069">this answer for C++98/03</a>. C++11 changed the rules surrounding POD, relaxing them greatly, thus <a href="https://stackoverflow.com/a/7189821/734069">necessitating a follow-up answer here</a>.</p>
<p>With C++, Plain Old Data doesn't just mean that things like int, char, etc are the only types used. Plain Old Data really means in practice that you can take a struct memcpy it from one location in memory to another and things will work exactly like you would expect (i.e. not blow up). This breaks if your class, or any class your class contains, has as a member that is a pointer or a reference or a class that has a virtual function. Essentially, if pointers have to be involved somewhere, its not Plain Old Data. </p>
17,637
<p>I've been developing business apps, basically CRUD, in ASP.Net for years now, and am interested in learning another language and platform.</p> <p>After a few trips to Borders and poking around a bit on the web, I have not found much dealing with generating reports in Ruby / Ruby on Rails apps. These reports would include things like commercial invoices, inventory reports etc. </p> <p>Can anyone provide some information of how reports are generated in a Ruby / Ruby on Rails web app? Third party controls, books with good chapters, web articles etc would all be welcomed.</p> <p>Many thanks Mike Thomas</p>
<p>Perhaps <a href="http://rubyreports.org/" rel="nofollow noreferrer">Ruport</a>?</p> <blockquote> <p>A simple, extensible reporting system built for Rubyists</p> </blockquote>
<p>It looks like there are a few options out there to get you started. Granted, these are not going to be on the same level as something else you might be used to like SQL Server Reporting Services or Business Objects, but it's a start:</p> <p><a href="http://www.google.com/search?hl=en&amp;q=ruby+reports&amp;btnG=Google+Search&amp;aq=f&amp;oq=" rel="nofollow noreferrer">http://www.google.com/search?hl=en&amp;q=ruby+reports&amp;btnG=Google+Search&amp;aq=f&amp;oq=</a></p>
42,659
<p>I've seen that a Processor Pack is available for Visual Studio 6, however it appears to only be available for users with SP5 and I am already using SP6:</p> <p><em>In addition, the Visual C++ Processor Pack (VCPP) was removed from Service Pack 6. If you have the VCPP installed, installing SP6 will remove it from your machine. If you wish to continue using the VCPP, you will need to stay with SP5 or migrate to Visual Studio 2002 or 2003 (recommended).</em></p> <p>Firstly, is this processor pack compatible with Visual Studio 6 SP6?</p> <p>Secondly, would it actually help me? I'm concerned about getting the most from my application, but it needs to run on all flavours of Intel and AMD chips so I can't just target one platform.</p>
<p>It looks like the clue was in the question:</p> <p>In addition, the Visual C++ Processor Pack (VCPP) was removed from Service Pack 6. If you have the VCPP installed, installing SP6 will remove it from your machine. If you wish to continue using the VCPP, you will need to stay with SP5 or migrate to Visual Studio 2002 or 2003 (recommended).</p> <p>I'm going to upgrade to a newer Visual Studio.</p>
<p>I think the processor pack is already integrated with SP6, like the <a href="http://msdn.microsoft.com/en-us/vs2005/aa718349.aspx" rel="nofollow noreferrer">following document</a> says.</p>
22,529