input
stringlengths
51
42.3k
output
stringlengths
18
55k
How to find the next record after a specified one in SQL? <p>I'd like to use a single SQL query (in MySQL) to find the record which comes after one that I specify.</p> <p>I.e., if the table has:</p> <pre><code>id, fruit -- ----- 1 apples 2 pears 3 oranges </code></pre> <p>I'd like to be able to do a query like:</p> <pre><code>SELECT * FROM table where previous_record has id=1 order by id; </code></pre> <p>(clearly that's not real SQL syntax, I'm just using pseudo-SQL to illustrate what I'm trying to achieve)</p> <p>which would return:</p> <pre><code>2, pears </code></pre> <p>My current solution is just to fetch all the records, and look through them in PHP, but that's slower than I'd like. Is there a quicker way to do it?</p> <p>I'd be happy with something that returned two rows -- i.e. the one with the specified value and the following row.</p> <p>EDIT: Sorry, my question was badly worded. Unfortunately, my definition of "next" is not based on ID, but on alphabetical order of fruit name. Hence, my example above is wrong, and should return oranges, as it comes alphabetically next after apples. Is there a way to do the comparison on strings instead of ids?</p>
<p>After the question's edit and the simplification below, we can change it to</p> <pre><code>SELECT id FROM table WHERE fruit &gt; 'apples' ORDER BY fruit LIMIT 1 </code></pre>
How to version control, deploy and develop php and mySQL <p>I'm working in a project where we develop php on Zend using a mySQL database and the project is about to get to a point where it will be necessary to use version control not only for the actual code but also for the database. </p> <p>Also we are getting a good production server (and the actual production server will be a test server). </p> <p>So i was wondering if you guys think its a good idea to standardize the IDE the programmers use and make them have a apache/php/mySQL installed in their boxes to test the code thus having a developers environment in each computer, a test server and a production server.</p> <p>If so, what set up would you recommend to each part of this process, especially mysql version control (I've never done that) and how to make the deployment?</p> <p>I know its a very big question and most have been answered in different questions, but I would like a global answer about how is the faster, better (harder and stronger) set-up for this and how much time would we have to stop programming to actually have all this working! (and yes, hiring an expert in the subject is pretty much a no-no)</p> <p>Thanks!</p>
<p>No, I would not force standardization on IDE for all developers. You should be standardizing on coding style, not IDEs.</p> <p>Having a PHP/Apache/MySQL install on a developer's machine is a good idea. The only issue you may run into is the developer's machines will probably not have the exact same configuration/runtime environment as the test and production server. Using a virtual image can fix this.</p> <p>As far as MySQL version control, put your schema in your source code management system (CVS, SVN, Perforce, whatever). To deal with changes, you might want to look into Rails migrations for inspiration.</p> <p>Deployment is a huge question. All I can say is there are tons of tools out there that you can use. <a href="http://www.capify.org/">Capistrano</a>, <a href="http://phing.info/trac/">Phing</a>, etc. </p>
Visual Source Safe - Removing files from web projects <p>I'll try to make this as straight forward as possible.</p> <ol> <li>Currently our team has a VSS database where our projects are stored.</li> <li>Developers grab the code and place on their localhost machine and develop locally.</li> <li>Designated developer grabs latest version and pushes to development server.</li> </ol> <p>The problem is, when a file is removed from the project (by deleting it in VS2008) then the next time another developer (not the one who deleted it) checks in, it prompts them to check in those deleted files because they still have a copy on their local machine.</p> <p>Is there a way around this? To have VSS instruct the client machine to remove these files and not prompt them to check back in? What is the preferred approach for this?</p> <p><hr /></p> <p>Edit Note(s):</p> <ol> <li>I agree SVN is better than VSS</li> <li>I agree Web Application project is better than Web Site project</li> <li><strong>Problem</strong>: This same thing happens with files which are removed from class libraries.</li> </ol>
<p>You number one way around this is to stop using web site projects. Web Site Projects cause visual studio to automatically add anything it finds in the project path to the project.</p> <p>Instead, move to Web Application Projects which don't have this behavior problem.</p> <p>Web Site projects are good for single person developments. </p> <p><strong>UPDATE:</strong></p> <p>VB shops from the days gone past had similiar issues in that whatever they had installed affected the build process. You might take a page from their playbook and have a "clean" build machine. Prior to doing a deployment you would delete all of the project folders, then do a get latest. This way you would be sure that the only thing deployed is what you have in source control.</p> <p>Incidentally, this is also how the TFS Build server works. It deletes the workspace, then creates a new one and downloads the necessary project files.</p> <p>Further, you might consider using something like <a href="http://cruisecontrol.sourceforge.net/" rel="nofollow">Cruise Control</a> to handle builds.</p>
Can Microsoft Windows Workflow route to specific workstations? <p>I want to write a workflow application that routes a link to a document. The routing is based upon machines not users because I don't know who will ever be at a given post. For example, I have a form. It is initially filled out in location A. I now want it to go to location B and have them fill out the rest. Finally, it goes to location C where a supervisor will approve it. </p> <p>None of these locations has a known user. That is I don't know who it will be. I only know that whomever it is is authorized (they are assigned to the workstation and are approved to be there.)</p> <p>Will Microsoft Windows Workflow do this or do I need to build my own workflow based on SQL Server, IP Addresses, and so forth?</p> <p>Also, How would the user at a workstation be notified a document had been sent to their machine?</p> <p>Thanks for any help.</p>
<p>You might also want to look at human workflow engines, as they are designed to do things such as this (and more), I'm most familiar with <a href="http://www.pnmsoft.com" rel="nofollow">PNMsoft</a>'s Sequence</p>
PHP - Javascript Controls <p>I'm currently developing (another) Open Source CMS in PHP and I'd like to use javascript controls especially for the admin panel. The question is, are there any open-source, freely distributable controls (for creating javascript Editable Grids, Trees, tabs etc ) that have an interface for PHP ?</p> <p>I've experimented with <a href="http://extjs.com/" rel="nofollow">ExtJs</a> in the past but although its usability and beauty when it comes to implementing it with php, it's a frustration. I've also tried PHP-EXT and ExtPHP libraries but I was disappointed by their generated code, their limited implementation of ExtJs and lack of proper documentation.</p> <p><a href="http://www.coolite.com/" rel="nofollow">Coolite</a> is a nice implementation for .NET but I haven't found anything similar for php. That surprised me, taking into account the years of php development on the market. </p> <p>Off course there's always the option of implementing different libraries for each component but this would become an overwhelming task, besides the incompatibilities and the difference in look&amp;feel that are going to come up.</p> <p>Any suggestions?</p> <p>Thank you in advance.</p>
<p>I really like <a href="http://jquery.com/" rel="nofollow">jQuery</a> with their new <a href="http://ui.jquery.com/" rel="nofollow">jQuery UI</a>. Also, browse through their <a href="http://plugins.jquery.com/" rel="nofollow">plugins list</a> for more tools.</p> <p>But you might like <a href="http://mootools.net/" rel="nofollow">mootools</a> too.</p>
Javascript/Ajax - Manually remove event handler from a Sys.EventHandlerList() <p>I have two scriptcontrols, one holds the other, and I have successfully been able to handle events from the child on the parent using:</p> <pre><code>initialize: function() { this._autoComplete = $get(this._autoCompleteID); this._onAutoCompleteSelected = Function .createDelegate(this, this.handleAutoCompleteSelected); var autoControl = this._autoComplete.control; autoControl.addItemSelected(this._onAutoCompleteSelected); ... } </code></pre> <p>Where addItemSelected(on the child) is:</p> <pre><code>addItemSelected: function(handler) { list = this.getEvents(); list.addHandler('userItemSelected', handler); }, </code></pre> <p>and getEvents is:</p> <pre><code>getEvents: function() { if (this._events == null) { this._events = new Sys.EventHandlerList(); } return this._events; }, </code></pre> <p>Problem is that on dispose of the parent, I want to do the same thing:</p> <pre><code>dispose: function() { var autoControl = this._autoComplete.control; autoControl.removeItemSelected(this._onAutoCompleteSelected); ... } </code></pre> <p>but .control no longer exists. I am guessing this is because the child control has already been disposed and thus the .control property no longer works. </p> <p>In light of this, I decided to run though the event list on the child and remove all the event handlers in it. </p> <pre><code>dispose: function() { list = this.getEvents(); for(var item in list._list) { var handler; handler = list.getHandler(item); list.removeHandler(item, handler); } .... } </code></pre> <p>Is there a better way to do this?</p>
<p>I'm not sure that the "control" expando property on the DOM element is the right way to reference the control object. It is managed by the framework and as you're seeing, I think it's already munged by the time your dispose is called.</p> <p>Have you tried using <code>$find</code> instead of <code>$get</code> and reworking your references this way?:</p> <pre><code>initialize: function() { this._autoControl = $find(this._autoCompleteID); this._onAutoCompleteSelected = Function .createDelegate(this, this.handleAutoCompleteSelected); this._autoControl.addItemSelected(this._onAutoCompleteSelected); } dispose: function() { this._autoControl.removeItemSelected(this._onAutoCompleteSelected); this._autoControl = null; } </code></pre> <p>Oh yeah and where you reference the DOM element stored in <code>this._autoComplete</code> you instead go through the control object itself:</p> <pre><code>this._autoControl.get_element(); </code></pre> <p>So basically invert the logic of "get element => get control object" to "get control object => get element".</p>
Convert XSD into SQL relational tables <p>Is there something available that could help me convert a XSD into SQL relational tables? The XSD is rather big (in my world anyway) and I could save time and boring typing if something pushed me ahead rather than starting from scratch.</p> <p>The XSD is <a href="http://www.grip.no/kjemikalier/XMLstandardformat/hmsdatablad.xsd">here</a> if you want to have a look. It's a standardized/localized format to exchange MSDS.</p>
<p>Altova's <a href="http://www.altova.com/features_database.html">XML Spy</a> has a feature that will generate SQL DDL Script from an XSD file. XML Spy will cost you some money though.</p> <p>Interestingly enough, a developer used a really clever trick of using an XSLT translation to create the DDL script from an XSD file. They have outlined it in two parts <a href="http://annlewkowicz.blogspot.com/2007/03/create-ddl-from-dataset-xsd-file.html">here</a> and <a href="http://annlewkowicz.blogspot.com/2008/01/create-ddl-from-xsd-file-part-ii.html">here</a>.</p> <p>I might have to try this out myself for future use...</p> <p>EDIT: Just found this question asked previously <a href="http://stackoverflow.com/questions/138575/how-can-i-create-database-tables-from-xsd-files">here</a>...</p>
Using a custom URL rewriter, IIS6, and urls with .htm, .html, etc <p>I have a custom site I'm building with automatic url rewriting using a custom engine. The rewriting works fine as long as the page url doesn't end in somehting like .htm or .html. For these pages it goes directly to the iis 404 page instead of hitting my rewriting engine first.</p> <p>I have the * wildcard handler in the "Home Directory" section of the IIS6 configuration of that website but these urls seem to be ignored by it (altho things like css, jpg, js, etc to get sent to the url handler in my web project). How do i set up IIS6 to force these urls to get sent to the handler, while still serving the page if it exists normally?</p> <p>The handler basically does this</p> <pre><code>if (!File.Exists(Request.Path)) { doMyRewriting(); } </code></pre> <p>I have to assume that using a block like this (just and example, the real one does some other stuff to format the Request.Path to be proper with everything) should run the "doMyRewriting()" if the requested file does not exist otherwise it will serve the page normally. Am I mistaken?</p> <p>If I tell IIS specifically to send .htm and .html pages thru to the .NET handler the rewriting works but if the page is actually there it will not serve it.</p> <p>Any help would be greatly appreciated.</p> <p>Thanks in advance!</p>
<p>Don't know if you can or would want to do this, but there is the Ionics Isapi url rewriter you can use.</p> <p><a href="http://www.codeplex.com/IIRF" rel="nofollow">http://www.codeplex.com/IIRF</a></p> <p>Basically install that then set a rule to remove the .html that way it hits your rewrite engine. I use it on IIS 6 with several of my blogs.</p>
How do regular expressions work in selenium? <p>I want to store part of an id, and throw out the rest. For example, I have an html element with an id of 'element-12345'. I want to throw out 'element-' and keep '12345'. How can I accomplish this?</p> <p>I can capture and echo the value, like this:</p> <pre>| storeAttribute | //pathToMyElement@id | myId | | echo | ${!-myId-!} | |</pre> <p>When I run the test, I get something like this:</p> <pre>| storeAttribute | //pathToMyElement@id | myId | | echo | ${myId} | element-12345 |</pre> <p>I'm recording with the Selenium IDE, and copying the test over into Fitnesse, using the Selenium Bridge fixture. The problem is I'm using a clean database each time I run the test, with random ids that I need to capture and use throughout my test.</p>
<p>The solution is to use the JavaScript <code>replace()</code> function with <code>storeEval</code>:</p> <pre><code>| storeAttribute | //pathToMyElement@id | elementID | | storeEval | '${elementID}'.replace("element-", "") | myID | </code></pre> <p>Now if I echo <code>myID</code> I get just the ID:</p> <pre><code>| echo | ${myID} | 12345 | </code></pre>
What are the current best practices for load testing and profiling ASP.NET web applications? <p>I am tasked with improving the performance of a particular page of the website that has an extremely high response time as reported by google analytics.</p> <p>Doing a few google searches reveals a product that came with VS2003 called ACT (Application Center Test) that did load testing. This doesn't seem to be distributed any longer</p> <p>I'd like to be able to get a baseline test of this page before I try to optimize it, so I can see what my changes are doing.</p> <p>Profiling applications such as dotTrace from Jetbrains may play into it and I have already isolated some operations that are taking a while within the page using trace. </p> <p>What are the best practices and tools surrounding performance and load testing? I'm mainly looking to be able to see results not how to accomplish them.</p>
<p>Here is an article showing how to profile using VSTS profiler.</p> <p><a href="http://blogs.msdn.com/tess/archive/2008/10/07/using-vsts-test-and-profilers-to-troubleshoot-a-high-cpu-in-gc-issue.aspx" rel="nofollow">If broken it is, fix it you should</a></p> <p>Also apart from all the tools why not try enabling the "Health Monitoring" feature of asp.net.</p> <p>It provides some good information for analysis. It emits out essential information related to process, memory, diskusage, counters etc. HM with VSTS loadtesting gives you a good platform for analysis.</p> <p>Check out the below link..</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms998306.aspx" rel="nofollow">How to configure HealthMonitoring?</a></p> <p>Also, for reference to some checklist have a look at the following rules/tips from yahoo....</p> <p><a href="http://developer.yahoo.com/performance/rules.html" rel="nofollow">High performance website rules/tips</a></p> <p>HttpWatch is also a good tool to for identifying specific performance issues.</p> <p><a href="http://developer.yahoo.com/performance/rules.html" rel="nofollow">HttpWatch - Link</a></p> <p>Also have a look at some of the tips here.. <a href="http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx" rel="nofollow">10 ASP.NET Performance and Scalability secret</a></p>
Using Full-Text Search in SQL Server 2008 across multiple tables, columns <p>I need to search across multiple columns from two tables in my database using Full-Text Search. The two tables in question have the relevant columns full-text indexed.</p> <p>The reason I'm opting for Full-text search: 1. To be able to search accented words easily (cafè) 2. To be able to rank according to word proximity, etc. 3. "Did you mean XXX?" functionality</p> <p>Here is a <strong>dummy</strong> table structure, to illustrate the challenge:</p> <pre> <strong>Table Book</strong> BookID Name (Full-text indexed) Notes (Full-text indexed) <strong>Table Shelf</strong> ShelfID BookID <strong>Table ShelfAuthor</strong> AuthorID ShelfID <strong>Table Author</strong> AuthorID Name (Full-text indexed) </pre> <p><strong>I need to search across Book Name, Book Notes and Author Name.</strong> </p> <p>I know of two ways to accomplish this:</p> <ol> <li><p><strong>Using a Full-text Indexed View:</strong> This would have been my preferred method, but I can't do this because for a view to be full-text indexed, it needs to be schemabound, not have any outer joins, have a unique index. The view I will need to get my data does not satisfy these constraints (it contains many other joined tables I need to get data from).</p></li> <li><p><strong>Using joins in a stored procedure</strong>: The problem with this approach is that I need to have the results sorted by rank. If I am making multiple joins across the tables, SQL Server won't search across multiple fields by default. I can combine two individual CONTAINS queries on the two linked tables, but I don't know of a way to extract the <strong>combined</strong> rank from the two search queries. For example, if I search for 'Arthur', the results of both the Book query and the Author query should be taken into account and weighted accordingly. </p></li> </ol>
<p>Using FREETEXTTABLE, you just need to design some algorithm to calculate the merged rank on each joined table result. The example below skews the result towards hits from the book table.</p> <pre><code>SELECT b.Name, a.Name, bkt.[Rank] + akt.[Rank]/2 AS [Rank] FROM Book b INNER JOIN Author a ON b.AuthorID = a.AuthorID INNER JOIN FREETEXTTABLE(Book, Name, @criteria) bkt ON b.ContentID = bkt.[Key] LEFT JOIN FREETEXTTABLE(Author, Name, @criteria) akt ON a.AuthorID = akt.[Key] ORDER BY [Rank] DESC </code></pre> <p>Note that I simplified your schema for this example.</p>
Determining the path to Outlook.exe from java? <p>I want to invoke outlook from the command line (for various reasons) and wanted to know how I go about discovering the Path to the Outlook.exe file.</p> <p>I'm pretty sure it's stored in the registry, but was wondering how to go about reading that from Java.</p> <p>thanks</p>
<p>I found <a href="http://javabyexample.wisdomplug.com/java-concepts/34-core-java/62-java-registry-wrapper.html" rel="nofollow">this site</a> that might be able to help you. It's a Java Registry wrapper, seems to have a lot of features but no idea how robust the implementation is.</p>
How to customize the background color of the standard label within a UITableViewCell? <p>I'm trying for the past several hours to figure out how to do this, but with no luck. There are several potential solutions for this when searching Google, but nothing seems to work.</p> <p>I'm trying to customize the background color of the standard UILabel that goes in a UITableViewCell (since I already customized the background color of the cell itself), but nothing I do seems to work.</p> <p>I'm creating my own UILabel to customize the colors in -tableView:cellForRowAtIndexPath:</p> <pre><code>UILabel* label = [[[UILabel alloc] init] autorelease]; label.textColor = [UIColor blueColor]; label.backgroundColor = [UIColor redColor]; label.opaque = YES; [cell.contentView addSubview:label]; cell.text = @"Sample text here"; </code></pre> <p>But that doesn't work, and the resulting table view still has a bunch of cells with labels with black text and white background in it.</p> <p>Any clues on what I am doing wrong here?</p> <p>UPDATE: If I try to do the following instead:</p> <pre><code>UILabel* label = [[[UILabel alloc] init] autorelease]; label.textColor = [UIColor blueColor]; label.backgroundColor = [UIColor redColor]; label.opaque = YES; [cell.contentView addSubview:label]; label.text = @"Sample text here"; </code></pre> <p>I get a bunch of UITableViewCells with no text at all.</p>
<p>It appears that you're assigning the text to the cell instead of the label. You probably want:</p> <pre><code>label.text = @"Sample text here"; </code></pre> <p>Also, you'll need to set the label's frame to what you require:</p> <pre><code>label.frame = CGRectMake(10,10, 80, 40); </code></pre> <p>or directly in the constructor:</p> <pre><code>label = [[UILabel alloc] initWithFrame:myFrame]; </code></pre>
Handling dynamically generated controls in asp.net <p>What's the best way to handle data entered through dynamically generated controls in ASP.NET?</p> <p>Currently, I have a group of controls that are generated in the Page_Load stage, and I need to access the data from them. It seems like it might be possible to just use a hidden field that's read and parsed on postback, but I'd like to know if there's a better way to do it that makes better use of the framework.</p>
<p>The key is recreating the controls on postback.</p> <p><a href="http://aspnet.4guysfromrolla.com/articles/092904-1.aspx" rel="nofollow">Old but good article</a> to explain how and why.</p> <p>You can also use the request.form collection to grab the posted values.</p>
I am confused about SOAP namespaces <p>I am learning about SOAP implementation and have become somewhat confused regarding the appropriate namespace URI for a SOAP 1.2 Envelope. </p> <p>The <a href="http://www.w3.org/TR/soap12-part1">w3c specification for SOAP</a> refers to the <code>"http://www.w3.org/2003/05/soap-envelope"</code> namespace. However, I have seen other examples that refer to the <code>"http://schemas.xmlsoap.org/soap/envelope/"</code> namespace. </p> <p>It seems to me that one or the other namespace should be used. Which of these two is the correct namespace URI to use?</p>
<p>It is related to the SOAP version. SOAP 1.2 uses <code>http://www.w3.org/2003/05/soap-envelope</code> for the namespace and SOAP 1.1 uses <code>http://schemas.xmlsoap.org/soap/envelope/</code>.</p> <p>For reference, see <a href="http://www.w3.org/TR/soap/">http://www.w3.org/TR/soap/</a> and look at the envelope section in the different version specs. </p> <p>Also, you can browse to each of those envelope URLs and check the version number to see exactly which version of the spec you are using.</p>
Use of Print Preview in .Net Winforms <p>I am writing c# code in .Net 2008 Winforms.</p> <p>I created a print preview window to create a report. It works fine I can preview the report and then print it. The only problem is it is not as flexible as the Office Print preview. The users cannot chose a printer other that the default printer and they cannot limit the print to certain pages. Perhaps I am missing some prperties I need.</p> <p>Here is a portion of the code I use: </p> <pre><code>PrintDocument pd = new PrintDocument(); pd.PrintPage += new PrintPageEventHandler(this.PrintTheGraph); pd.DefaultPageSettings.Landscape = true; // Allocate a print preview dialog object. PrintPreviewDialog dlg = new PrintPreviewDialog(); dlg.Width = 100; dlg.MinimumSize = new Size(375, 250); dlg.SetBounds(100, -550, 800, 800); dlg.Document = pd; DialogResult result = dlg.ShowDialog(); </code></pre> <p>Thanks, </p> <p>Bob</p>
<p>Print Preview and Print are different functions and should be different menu options. Choosing Print Preview should not print your document, it is entirely likely that a user would want to see what their document looks like laid out on a page without actually printing it.</p> <p>To print a page and allow selecting printer devices, use :</p> <pre><code>PrintDialog pDialog = new PrintDialog( ); pDialog.Document = printDocument; if (pDialog.ShowDialog( ) == DialogResult.OK) { printDocument.DocumentName = fileName; printDocument.Print( ); }</code></pre> <p>The <code>PrintDialog</code> class has a <code>UseEXDialog</code> property you can use to show an expanded Page Setup dialog with print selections, ranges, n-up printing, et. al. Handling all these options is a lot of work, get <code>PrintDialog </code> working first.</p>
retaining list selectedIndex between data binding reloads in Flex <p>In my Flex interface, I've got a few List components that are data bound to ArrayCollections. I'm finding that when the ArrayCollections are updated (by Web services) and the data bindings for the Lists update, each List is reset and its selectedIndex is dropped. This is a problem if a user is in the middle of a task and has already selected an item in the List, but hasn't yet submitted the form.</p> <p>I know how I can kludge together some ActionScript to deal with these cases, but do you know of any way to handle this more naturally using Flex's data binding or general-purpose event utilities?</p> <p>As always, thanks!</p>
<p>I like using the observe class found <a href="http://weblogs.macromedia.com/paulw/archives/2006/05/the_worlds_smal.html" rel="nofollow">here</a> to call a function when data changes. It takes two parameters: data to watch, and a function to call. (Saves you time of repeating setters and getters all the time)</p> <p>I would stored the selectedItem when it is selected and when the data is updated reselect this item by looping through the list and selecting the item again.</p>
How do you like your primary keys? <p>In a fairly animated discussion in my team I was made to think what most people like as primary keys. We had the following groups-</p> <ol> <li>Int/ BigInt which autoincrement are good enough primary keys.</li> <li>There should be at least 3 columns that make up the primary key.</li> <li>Id, GUID and human readable row identifiers all should be treated differently.</li> </ol> <p>Whats the best approach for PKs? It would be awesome if you could justify your opinion. Is there a better approach that the above? </p> <p>EDIT: Anyone has a simple sample/algorithm to generate human readable identifiers for rows that scales well?</p>
<p>If you're going to be doing any syncing between databases with occasionally connected apps, then you should be using GUIDs for your primary keys. It is kind of a pain for debugging, so apart from that case I tend to stick to ints that autoincrement.</p> <p>Autoincrement ints should be your default, and <strong>not</strong> using them should be justified.</p>
Adding multiple function calls to a case of in delphi? <pre><code> case i of 0..99 : Function-call('bobo') ; 100..209 : function-smell('Hobo'); 210..300 : function-yikes('argh'); end; </code></pre> <p>But what if I wanted 210..300 to call both function yikes and function smell? Can't figure out how thanks.</p>
<p>Just add a begin end block:</p> <pre><code>case i of 0..99 : function-call('bobo') ; 100..209 : function-smell('Hobo'); 210..300 : begin function-yikes('argh'); function-smell('Hobo'); end; end; </code></pre>
Design Patterns - Architecture Astronaut <p>Perhaps my question is similar in nature to this one: <a href="http://stackoverflow.com/questions/11586/do-you-use-design-patterns">Do you use design patterns?</a></p> <p>The programs that I write are small 50-75 K line programs mostly using <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow">Windows Forms</a> and <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow">ASP.NET</a>. These programs are GUI intensive allowing the design and layout of various graphics and graphics processing.</p> <p>I consider myself good at OOP and practiced at balancing OOP and traditional procedural methods to create maintainable code.</p> <p>The problem comes in when I consider design patterns. The linked to thread has an interesting comment that design patterns may be used but not intentionally. When I want to intentionally use a design pattern (in the design of my program), it feels like I'm going above and beyond what is needed, that I'm in the realm of "<a href="http://www.joelonsoftware.com/articles/fog0000000018.html" rel="nofollow">architecture astronaut</a>" so I fall back to my traditional methods and everything goes along smoothly (i.e. normally).</p> <p>Take the MVC pattern as an example. If I want to implement this pattern using Windows Forms or ASP.NET (Visual Studio 2005) then I have to write a "Framework" and writing frameworks seems to be more trouble than it's worth for the size of the application.</p> <p>Perhaps my applications are too small to justify the use of some of these patterns. Perhaps I just don't know the patterns well enough or need to study them more.</p> <p>Does anyone else experience this "architecture astronaut" feeling?</p> <p>How do you go about intentionally using design patterns without going "overboard?"</p>
<p>When it comes to smaller applications of this nature, I generally worry more about <a href="http://c2.com/cgi/wiki?AntiPattern">anti-patterns</a> than I do about design patterns. That said, it's really two sides to the same coin: the power of a design pattern for me is being familiar with them so as to recognize the less-than-obvious pros and cons of whatever solution I'm thinking of. I rarely if ever go out of my way to actually fully implement a complete design pattern (unless I actually need all the functionality); however, I have often saved myself a lot of future re-work by recognizing the path I'm on and looking at the common pitfalls or drawbacks to that solution, which I can then check against my future uses to see if it's going to be a relevant concern for me or not. Thus, the power of a design pattern is that you can easily predict the future consequences of your current solution against your potential needs, without worrying that you might be missing some less-than-obvious caveat or special case that you haven't considered.</p>
Uninstalling a Windows app installed by a nonexistent user <p>We have a .Net Winforms app running on XP machines that are not connected to the internet. We install and update this app by distributing a CD with a .MSI installer file. Users uninstall the old app from the Add or Remove Programs control panel and install the new app from CD.</p> <p>A while ago we required users to log in under individual accounts and not a shared account. All these individual accounts are "Standard User" accounts in the Power Users group from the XP User Accounts control panel. Such users are able to install the app for all users, we have tested this and it works.</p> <p>Until recently. A user updating a remote machine says the application does not appear in Add or Remove programs, though the application and data files are installed. Trying to run the new installer shows a dialog reading "The system administrator has set policies to prevent this installation". This is not true, we have set no policies on this machine, and there are no Windows Installer policies in the Group Policy panel of Windows Management Console.</p> <p>We tried logging on to this machine with an administrator account, and see the same thing.</p> <p>My current theory is that the application was installed under an account that was later deleted, and only that user can uninstall the app. But why can an administrator not uninstall the app? Is there some way to have the installer remove the old app, regardless of who installed it?</p> <p>Additional information:</p> <p>I am not asking how a user can uninstall the app; we create the installer and I want to know how our deployment project can detect and handle this situation.</p> <p>A technician logged on to the affected machine as an administrator and says the app does appear in the Add/Remove control panel but there's no Remove button, selecting it shows app info but no buttons.</p> <p>I do not know for sure if the app was originally installed by a deleted user, this is a guess based on the fact user accounts were recently changed on this machine.</p>
<p>All right, this is not an answer but just to help diagnose; can you look in the below registry key and see if there is an entry for your application? This is how Add/Remove Programs is populated:</p> <p>HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall</p>
splash screen w/ load assembly status <p>I'm trying to create a splash screen that shows assemblies (all referenced library) loading status. I use AppDomain.AssemblyLoad AssemblyLoadEventHandler delegate to catch what assembly is being loaded but the problem is the event is not triggered when the program initializes. I tried register the event handler in application startup "MyApplication_Startup" but it didn't work. Here's my test code:</p> <pre><code> Partial Friend Class MyApplication Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup AddHandler AppDomain.CurrentDomain.AssemblyLoad, AddressOf MyAssemblyLoadEventHandler End Sub Sub MyAssemblyLoadEventHandler(ByVal sender As Object, ByVal args As AssemblyLoadEventArgs) Console.WriteLine("&gt;&gt;&gt; ASSEMBLY LOADED: " + args.LoadedAssembly.FullName) Console.WriteLine() End Sub End Class </code></pre>
<p>One issue you are going to run into is that assemblies in .Net are not loaded until they are needed.</p> <p>For instance, create a new assembly with a "Hello World" class in it, reference it with any executable, then delete the new assembly from the working directory, at no time will you notice that it is loaded.</p> <p>Next, on a button click event, initialize the "Hello World" class, keep the assembly deleted from the working directory, and you will receive the error that the assembly can not be found when the button is clicked.</p> <p>This is the key reason that first database access is generally slow in .Net, and has a "speed up" feel to it (more you use it, the faster it gets), that is because the objects you use in your data layer are not loaded into the runtime until they are accessed.</p>
What have you used Regular Expressions for? <p>I have heard of regular expressions and only seen use cases for a few things so I don't think of using them very often. In the past I have done a couple of things and it has taken me hours to do. Later I talk to someone and they say "here is how to do it using a regular expression".</p> <p>So what are things for which you have used Regular Expressions? If I get more examples then maybe I can begin to know when to look for and use them.</p>
<p>Many things. Including:</p> <ul> <li>Examining command lines</li> <li>Parsing user input</li> <li>Parsing various text files</li> <li>Examining web server logs</li> <li>Examining test results</li> <li>Finding text in emails</li> <li>Reading configuration files</li> </ul> <p>When learning regular expressions, it may be helpful to also learn restraint. You might be tempted, like me, to see regular expressions as a solution to far too many problems.</p>
LINQ to SQL <p>I am finishing off a C# ASP.NET program that allows the user to build their own computer by selecting hardware components such as memory, cpu, etc from a drop down lists. The SQL datatable has 3 columns; ComputerID, Attribute and Value. The computerID is an ID that corresponds to a certain computer in my main datatable of products, the Attribtute is the name of the hardware component; memory,cpu, hard drive etc.. and the value is the value assigned to that attribute, such as 1GB or 2.8GHz 320GB. This means that a computer will have multiple attributes. </p> <p>What I am trying to do it narrow down the results by first selecting all computers that meet the first attribute requirements and then getting from that list, all computers that meet the next requirement.. and so on for about 10+ attributes.</p> <p>I thought it might be a good idea to show you an example of my LINQ to SQL query so that you have a btter idea of what I am trying to do. This basically selects the ComputerID where the the computers memory is larger than 1GB.</p> <pre><code>var resultsList = from results in db.ComputerAttributes where computer.Value == "MEMORY" &amp;&amp; computer.Value &gt;= "1" select results.ComputerID; </code></pre> <p>Next I want to select from the resultsList where the CPU is say, faster than 2.8Ghz and so on. </p> <p>I hope I have given you enough information. If anyone could please give me some advice as to how I might go about finishing this project that would be great.</p> <p>Thanks</p>
<p>You need to use Concat as a "Union All".</p> <pre><code>IQueryable&lt;ComputerAttribute&gt; results = null; foreach(ComputerRequirement z in requirements) { //must assign to a locally scoped variable to avoid using // the same reference in all of the where methods. ComputerRequirement cr = z; if (results == null) { results = db.ComputerAttributes .Where(c =&gt; c.Attribute == cr.Attribute &amp;&amp; c.Value &gt;= cr.Value); } else { results = results .Concat(db.ComputerAttributes .Where(c =&gt; c.Attribute == cr.Attribute &amp;&amp; c.Value &gt;= cr.Value) ); } } int requirementCount = requirements.Count(); //Get the id's of computers that matched all requirements. IQueryable&lt;int&gt; ids = results .GroupBy(x =&gt; x.ComputerId) .Where(g =&gt; g.Count == requirementsCount) .Select(g =&gt; g.Key); //Get all attributes for those id's List&lt;ComputerAttributes&gt; data = db .ComputerAttributes.Where(c =&gt; ids.Contains(c.ComputerId)) .ToList(); </code></pre>
What MIME type if JSON is being returned by a REST API? <p>My REST API returns JSON. </p> <p>I'm currently returning text/plain as the MIME type, but it feels funny. Should I be returning <code>application/x-javascript</code> or some other type?</p> <p>The second question is with regard to the HTTP status code for error conditions. If my REST API is returning an error state, I am returning as JSON</p> <pre><code>{ result: "fail", errorcode: 1024, errormesg: "That sucked. Try again!" } </code></pre> <p>Should the HTTP status code remain at <code>200 OK</code>?</p>
<p>The <a href="http://www.ietf.org/rfc/rfc4627.txt">JSON</a> spec suggests <code>application/json</code>, and that seems to be supported by the <a href="http://www.ietf.org/rfc/rfc4627.txt">IETF</a> and <a href="http://www.iana.org/assignments/media-types/application/">IANA</a> registry.</p> <p><strike>On the second question, I think if the message handling fails in some way you should return a structured and standard error response as a JSON message; only if there is a failure to deliver the message to the backend handler for some reason should you consider an HTTP error code.</strike></p> <p><strong>Update 2014-06-27</strong>: The days where clients (browsers) only worked with a 200 response are long past and the prevailing advice for RESTful APIs is to use HTTP response codes appropriate for the response, 2xx for successful responses (e.g. 201 Created for PUT; 204 No Content for DELETE) and 4xx and 5xx for all error conditions, including those from the API itself.</p>
SQL Server Enterprise Manager 2005 - stored procedures not showing up <p>When using SQL Server Management Studio from SQL Server 2005, I can connect to an instance of SQL Server 2000... but none of the stored procedures show up. Is there some trick to allow SQL Server Enterprise Manager 2005 to properly talk to SQL Server 2000 databases?</p>
<p>I'm guessing that the account that you're logging in as does not have access to execute the stored procs. If it doesn't have access to use a stored proc, SQL Server Management Studio 2005 won't show it (regardless of it you're connecting to a SQL 2000 or 2005 server)</p>
Cocoa Won't Capture Shift Modifier? <p>Hey All, I have an application in which I'm trying to capture the shift key modifier to perform an action, however when I run the program and press and normal key without the shift key modifier I get a beep and the modifier and key are not sent to my keyDown event. The relevant code is:</p> <pre><code>NSString* eventChars = [theEvent charactersIgnoringModifiers]; if ([eventChars isEqualTo:@"w"]) { newPlayerRow++; direction = eUp; } else if ([eventChars isEqualTo:@"x"]) { newPlayerRow--; direction = eDown; } else if ([eventChars isEqualTo:@"a"]) { newPlayerCol--; direction = eLeft; } else if ([eventChars isEqualTo:@"d"]) { newPlayerCol++; direction = eRight; } else { [super keyDown:theEvent]; return; } // handle the player firing a bullet if (([theEvent modifierFlags] &amp; (NSShiftKeyMask | NSAlphaShiftKeyMask)) != 0) { NSLog(@"Shift key"); [self fireBulletAtColumn:newPlayerCol row:newPlayerRow inDirection:direction]; [self setNeedsDisplay:YES]; } else { ... } </code></pre> <p>I'm not sure what is causing this, but I'd like to be able to capture shift key presses. Thanks in advance for any help with this problem.</p> <p>EDIT: Also I'm using a MacBook keyboard if that makes any difference.</p> <p>EDIT: This is definitely a shift-centric problem as changing (NSShiftKeyMask | NSAlphaShiftKeyMask) to NSControlKeyMask does have the desired effect.</p>
<p>First, -charactersIgnoringModifiers doesn't ignore the shift key, so you will still get shifted characters (i.e UPPERCASE and !%#$%^&amp;*) returned from it. What's probably happening in your function is: You press shift-w, your -isEqualTo: returns false because you're comparing a lowercase 'w' and an uppercase 'W', and so you return before getting to the shift-detection code at the bottom. The simplest solution is to just check for both.</p> <p>However, if you want, for example, Arabic keyboardists to be able to easily use your app, you really shouldn't hardcode characters that may not even appear on the user's keyboard. The value returned by -keyCode refers to a key's position on the keyboard, not the represented character. For starters, the constants beginning in 'kVK_ANSI_' and 'kVK_' in Events.h (you may have to link to Carbon.framework and #include &lt;Carbon/Carbon.h&gt; to use those constants) can be compared to what -keyCode returns, and they refer to the key positions a QWERTY-using USian expects. So you can be (pretty) sure that, regardless of keyboard layout, the keycodes for 'wasd' (kVK_ANSI_W, kVK_ANSI_A, etc.) will refer to that triangle in the top left of your user's keyboard.</p>
Is this a Windows XP firewall bug? <p>I have a webserver running on my Windows XP computer. I have set the firewall to allow incoming HTTP connections: Firewall settings window->'Advanced' tab->select my network connection->Settings->Services->check 'Webserver(HTTP)' checkbox. </p> <p>Normally, this works. However, sometimes upon restarting the server machine, the firewall again begins blocking HTTP connections, notwithstanding the fact that the 'Webserver(HTTP)' exception is still checked in the Firewall settings window. </p> <p>The only way, then, to get things working again is to uncheck the said option, save the settings, reopen the firewall dialog and check the option and save again. </p> <p>My question is, is this some peculiarity of my machine or is this a Windows XP firewall bug? </p>
<p>No, that's not a bug, you're just misunderstanding what the Services tab is for.</p> <p>The list on that tab are for the scenario where the firewalled system also serves as a NAT gateway ("Internet Connection Sharing" or whichever name Microsoft came up with) for another computer. It's basically a form of DNAT. It controls whether or not to allow the initiation of connections to that port through to hosts running on a private network <em>behind</em> the firewalled system.</p> <p>What you need is to add an exception for port 80 / TCP on the Exceptions tab (don't forget to click on Change scope and select the appropiate scope!) That will work without a hitch. I also recommend you uncheck what you checked ASAP since Windows client operating systems aren't particularly suited for packet forwarding and settings on that tab sometimes mysteriously interfere with normal network traffic (like in your case.)</p>
http-on-examine-response observer - possible to block response from further processing? <p>I am attempting to implement a firefox extension which filters incoming HTTP responses and handles them accordingly.</p> <p>I wish to block HTTP responses containing a specific header. Having read through some of the MDC articles, it appears the most common way of observing HTTP responses is by registering an http-on-examine-response observer.</p> <p>My question is: Using this observer, is it possible to block the HTTP request from further processing (as a by-product, the page will continue to wait for a response)? Or do I need to use some other facet of XPCOM (if so, care to point me in the right direction)?</p> <p>Thanks in advance,<br/>Mike</p>
<p>Should be possible: the "subject" of that notification is a HTTP channel, on which you can call nsIRequest::cancel().</p> <p>the page will <strong>not</strong> continue to wait for a response, though, since you blocked the response. Perhaps you've been actually looking for a way to <a href="http://stackoverflow.com/questions/1695440/altering-http-responses-in-firefox-extension">alter an HTTP response</a>?</p>
Can I use a Regex in an XPath expression? <p>Something like <code>.//div[@id='foo\d+]</code> to capture div tags with <code>id='foo123'</code>.</p> <p>I'm using .NET, if that matters.</p>
<p>As other answers have noted, <strong><a href="http://www.w3.org/TR/xpath" rel="nofollow">XPath 1.0</a> does not support regular expressions</strong>.</p> <p><strong>Nonetheless, you have the following options</strong>:</p> <ul> <li><strong>Use an XPath 1.0 expression</strong> (note the <a href="http://www.w3.org/TR/xpath#function-starts-with" rel="nofollow"><strong><code>starts-with()</code></strong></a> and <a href="http://www.w3.org/TR/xpath#function-translate" rel="nofollow"><strong><code>translate()</code></strong></a> functions) like this:</li> </ul> <pre> .//div [starts-with(@id, 'foo') and 'foo' = translate(@id, '0123456789', '') and string-length(@id) > 3 ] </pre> <ul> <li><p><strong>Use <a href="http://www.codeplex.com/MVPXML/Wiki/View.aspx?title=EXSLT.NET&amp;referringTitle=Home" rel="nofollow">EXSLT.NET</a></strong> -- there is a way to <a href="http://msdn.microsoft.com/en-us/library/ms950808.aspx" rel="nofollow"><strong>use its functions directly in XPath expressions without having to use XSLT</strong></a>. The EXSLT extension functions that allow RegEx-es to be used are: <a href="http://exslt.org/regexp/functions/match/index.html" rel="nofollow"><strong><code>regexp:match()</code></strong></a>, <a href="http://exslt.org/regexp/functions/replace/index.html" rel="nofollow"><strong><code>regexp:replace()</code></strong></a> and <a href="http://exslt.org/regexp/functions/test/index.html" rel="nofollow"><strong><code>regexp:test()</code></strong></a></p></li> <li><p><strong>Use</strong> <a href="http://www.w3.org/TR/xpath20/" rel="nofollow"><strong>XPath 2.0</strong></a>/<a href="http://www.w3.org/TR/xslt20/" rel="nofollow">XSLT 2.0</a> and its <a href="http://www.w3.org/TR/xpath-functions/#regex-syntax" rel="nofollow"><strong>inbuilt support for regular expressions</strong></a> (the functions <a href="http://www.w3.org/TR/xpath-functions/#func-matches" rel="nofollow"><strong>matches()</strong></a>, <a href="http://www.w3.org/TR/xpath-functions/#func-replace" rel="nofollow"><strong>replace()</strong></a> and <a href="http://www.w3.org/TR/xpath-functions/#func-tokenize" rel="nofollow"><strong>tokenize()</strong></a>)</p></li> </ul>
CSS issue: link is wrongly displayed <pre><code>a { color: #000; } a:hover { text-decoration: none; color: #fff; } </code></pre> <p>That is the code I use. But, none of the links I have in my pages listen to this. They abide by this instead: </p> <pre><code>#menu li, a{ text-align: center; display: block; float: left; margin: 0; font-family: Arial, Helvetica, sans-serif; font-size:1.2em; color: #575757; text-decoration: none; list-style: none; } </code></pre> <p>Therefore a lot of the links are skewed, as they all float left and things.<br /> The code for the links itself isn't wrapped in any way. At least not in a way that explains my errors.</p> <pre><code>&lt;div id="footer"&gt; &lt;p&gt;&lt;center&gt;Copyright 2008 - &lt;a href="index.php"&gt;G.S.B.V. Pugilice&lt;/a&gt;&lt;/center&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>That bit of code gives me two lines instead of one, the link floats left on the second line.</p>
<p>I think you may be mis-understanding how selectors work.</p> <pre><code>#menu li, a { ... } </code></pre> <p>Means apply styles to any li descendant of a element with the id #menu <strong>and</strong> to any a found any where.</p> <p>Did you actually intend:-</p> <pre><code>#menu li, #menu a {...} </code></pre> <p>?</p>
How to format a Date without using code - Format String Question <p>How can I achieve the following with a format string: Do 01.01.2009 ? It has to work in all languages (the example would be for Germany). So there should only be the short weekday and then the short date.</p> <p>I tried 'ddd d' (without the '). However, this leads to 'Do 01'. Is there maybe a character I can put before the 'd' so that it is tread on its own or something like that?</p>
<pre><code>DateTime.Now.ToString("ddd dd/MM/yyyy") </code></pre>
Policy to allow user to enumerate accounts only within his own OU in Active Directory <p>Is it possible to define a policy which restricts a user to enumerate only accounts in his own OU?</p> <p>For example lets consider a domain Contosos and OUs Sales and HR.The Sales OU has two users A and B and the HR OU has users C and D.</p> <p>Is it possible to define a policy so that A can only enumerate accounts A and B and C can only enumerate C and D and not the accounts not in their OU?</p>
<p>Don't do That!</p> <p>But, you can create a group for each OU and put the ou users inside the group. Than you can change the permission on every other OU to deny this group the "list content" permission. I don't think that there is a way to configure this without scripting. But as the rule is simple it can be scripted.</p> <p>That said. I would advise you not to dare and change the active directory default permission without having a dedicated group of experts on this specific subject. You can quite easily render your network useless with just a few clicks. And even if you don't, there is a chance that programs that have expectation from active directory security ( without even realizing this ) will suffer from subtle errors.</p> <p>So the rule is. If you have to ask, don't do it. if you need to become an expert, then:</p> <p><a href="http://www.google.com/search?hl=en&amp;q=active+directory+permission+site:microsoft.com&amp;btnG=Search" rel="nofollow">http://www.google.com/search?hl=en&amp;q=active+directory+permission+site:microsoft.com&amp;btnG=Search</a></p> <p><strong>Update:</strong> The "If you need to ask" rule refers to asking on a public site like this. Where non-experts, like me, can give you potentially misleading information, as mine can be( I hope not, but...). I am not sure that your requirement don't have a simple solution. But as far as I know, this is a path that burned more than few brave souls.</p>
How do I make jQuery modify only one div, instead of all divs of the same class? <p>Each page of my site has 10 (almost) identical divs, varying only in the text within. When a certain part of a div is clicked, I want a different part of that div to be modified.</p> <p>I'm using this code:</p> <pre><code>$(document).ready(function(){ $(".notLogged img").mouseover(function(){ $(this).parent()&gt;$("span").html("You must be logged in to vote."); }) }) </code></pre> <p>I thought this would work as follows: For all <code>img</code> elements within a "notLogged" classed div, a mouseover would cause a different part of that div to change.</p> <p>However, that's not what happens. Whenever that mouseover event is triggered, <em>all</em> divs with the "notLogged" class are modified.</p> <p><strong>How can I modify this code so only the div in which the mouseover originated is modified?</strong></p>
<p>Try it like this:</p> <pre><code>$(document).ready(function(){ $(".notLogged img").mouseover(function(){ $(this).parent().find("span").html("You must be logged in to vote."); }); }); </code></pre>
What is your convention for specifying complex SQL queries in Rails? <p>I am fairly new to Rails and I was curious as to some of the conventions experts are using when they need to construct a very complex SQL query that contains many conditions. Specifically, keeping the code readable and maintainable. </p> <p>There are a couple of ways I can think of:</p> <p>Single line, in the call to find():</p> <pre><code>@pitchers = Pitcher.find(:all, "&lt;conditions&gt;") </code></pre> <p>Use a predefined string and pass it in:</p> <pre><code>@pitchers = Pitcher.find(:all, @conditions) </code></pre> <p>Use a private member function to return a query</p> <pre><code>@pitchers = Pitcher.find(:all, conditionfunction) </code></pre> <p>I sort of lean towards the private member function convention, additionally because you could pass in parameters to customize the query. </p> <p>Any thoughts on this?</p>
<p>I almost never pass conditions to <code>find</code>. Usually those conditions would be valuable to add to your object model in the form of a <code>named_scope</code> or even just a class method on the model. Named scopes are nice because you can chain them, which takes a little bit of the bite out of the complexity. They also allow you to pass parameters as well.</p> <p>Also, you should almost never just pass a raw SQL condition string. You should either use the hash style (<code>:conditions =&gt; { :name =&gt; 'Pat' }</code>) or the array style (<code>['name = ?', 'Pat']</code>). This way, the SQL is escaped for you, offering some protection against SQL injection attacks.</p> <p>Finally, I think that the approach you're considering, where you're trying to create conditions in whatever context you're calling <code>find</code> is a flawed approach. It is the job of the model to provide an interface through which the pertinent response is returned. Trying to determine conditions to pass into a <code>find</code> call is too close to the underlying implementation if you ask me. Plus it's harder to test.</p>
Can my .NET Web Services be considered as a RESTful interface? <p>Happy New Year.</p> <p>I have a bunch of SOAP Web Services. They all have an HTTP POST and GET interfaces along with the SOAP interface. I believe POST and GET are offered by default when building SOAP Web Services in .NET/Visual Studio.</p> <p>These methods either: (1) get information, e.g., provide your username, password and a transaction ID -> get an XML with your transaction's status; (2) create a transaction by providing your username, password and some data -> get an XML with your transaction ID.</p> <p>My question is: would it be accurate to say I have a RESTful web service for those Ruby guys out there?</p>
<p>Well, it might be POX - but for true REST, the URIs themselves would be representative of the data being requested, such as /Orders/12345; is this the case?</p> <p>Also - the data coming back would be data-centric, rather than operation-centric (which tends to be the norm for SOAP-based services). i.e. results would generally be directly related to data.</p> <p>Note that you can create REST services in .NET with ADO.NET Data Services (aka Astoria). This is part of 3.5 SP1, and uses WCF under the bonnet. By default, full REST is available for Entity Framework, or query-only on any <code>IQueryable</code> API. But you can also enable full REST on LINQ-to-SQL (or anything else for that matter) by implementing <code>IUpdatable</code>. I cover this in a series starting <a href="http://marcgravell.blogspot.com/2008/12/astoria-and-linq-to-sql-getting-started.html" rel="nofollow">here</a>.</p>
Best practices when applying conditional formatting in data bound controls? <p>I have a Repeater contol bound to a custom object (an EntitySpaces query) and have noticed there are a couple of ways to conditionally format the values being displayed. </p> <p>1) From my aspx I can call a method in my code-behind and pass through the bound value and use that to drive any conditional logic:</p> <pre><code> &lt;a class="star" href="&lt;%#MakePackageSelectionUrl((int)DataBinder.Eval(Container.DataItem, "PackageId"))%&gt;"&gt; and then in the code-dehind: protected string MakePackageSelectionUrl(int packageId) { return string.Format("/Packages/NoAjax/ToggleStar.aspx?p={0}&amp;amp;s={1}&amp;amp;st={2}", packageId, _streamId, (int)_phase); } </code></pre> <p>2) I can hook into the ItemDataBound event, retrieve e.Item.DataItem as a DataRowView and then go crazy:</p> <pre><code> protected void PackageList_ItemDataBound(Object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType != ListItemType.Item &amp;&amp; e.Item.ItemType != ListItemType.AlternatingItem) { return; } DataRowView details = (DataRowView)e.Item.DataItem; EncodePackageName(e, details); EncodeStatusName(e); DisplayStarImage(e, details); } private static void EncodePackageName(RepeaterItemEventArgs e, DataRowView dr) { HtmlAnchor p = (HtmlAnchor)e.Item.FindControl("packageLink"); if (p != null) { p.HRef = string.Format("/Packages/View.aspx?p={0}", dr["packageId"]); p.InnerHtml = HttpUtility.HtmlEncode((string)dr["packageName"]); } } </code></pre> <p>I've also noticed that using e.Item.FindControl() in the code-behind requires runat="server" on the control in the aspx which has a nasty habit of encoding ids and generally messing up the HTML.</p> <p>I'm keen to hear from anyone that has come up with a nice approach for dealing with these sorts of issues.</p>
<p>Keep It Simple.</p> <p>The more code you write (even if it is repetitive), the more errors may sneak in.</p> <p>I prefer the first method, since you don't need the event handler, and keep all your formatting in a separate class if used more than once.</p>
What third-party ASP.NET controls or libraries can you not live without? <p>I am working on a project right now, and I have a few must-have controls that I include in most sites I build. Often times it strikes me that the best controls are not always that well publicized so I thought I would ask the Stack Overflow community about their favorite third-party ASP.NET controls - the ones you just have to have on a project because they are so valuable.</p> <p>EDIT:</p> <p>Some people have asked for clarification and the controls that I include.</p> <p>First, I am not talking about just user interface controls but libraries as well, a few people have mentioned <a href="http://en.wikipedia.org/wiki/Log4j#Ports" rel="nofollow">log4net</a> which falls into this category.</p> <p>For me, there is one third-party control package which I find to be masterfully done and an incredible value for the money - it is Peter Blum's Data Entry Suite. As Scott Hanselman says, it is a "complete re-imagining of the ASP.NET Validation framework" and it is loaded with controls for rich interaction with data entry forms.</p> <p>Outside of that, I am really digging <a href="http://en.wikipedia.org/wiki/JQuery" rel="nofollow">jQuery</a> lately but like most of the answers so far also use the ASP.NET Ajax Control Toolkit in many places.</p>
<p>Generally, I prefer to avoid dependencies whenever possible. However, there are a couple of 3rd party libraries which usually end up being used on nearly all projects:</p> <ul> <li>ASP.NET AJAX Toolkit</li> <li>Log4net</li> </ul> <p>On many projects, I'm also using some internal libraries (compiled separately and referenced by the project). These are for data access, configuration management, and utility functionality.</p> <p>The Telerik controls are really good as well for use on ASP.NET projects, though again, only added into the project if they are actually going to be used.</p>
What is a cyclic data structure good for? <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&amp;lpg=PP1&amp;dq=learning%20python&amp;pg=PA254#v=onepage&amp;q=cyclic&amp;f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p> <pre><code> >>> L = ['grail'] >>> L.append(L) >>> L ['grail', [...]] </code></pre> <p>It was identified as a cyclic data structure.</p> <p>So I was wondering, and here is my question:</p> <h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2> <p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p> <pre><code> >>> L[0] 'grail' >>> L[1][0] 'grail' >>> L[1][1][0] 'grail' </code></pre>
<p>Lots of things. Circular buffer, for example: you have some collection of data with a front and a back, but an arbitrary number of nodes, and the "next" item from the last should take you back to the first.</p> <p>Graph structures are often cyclic; acyclicity is a special case. Consider, for example, a graph containing all the cities and roads in a traveling salesman problem.</p> <p><hr></p> <p>Okay, here's a particular example for you. I set up a collection of towns here in Colorado:</p> <pre><code>V=["Boulder", "Denver", "Colorado Springs", "Pueblo", "Limon"] </code></pre> <p>I then set up pairs of cities where there is a road connecting them.</p> <pre><code>E=[["Boulder", "Denver"], ["Denver", "Colorado Springs"], ["Colorado Springs", "Pueblo"], ["Denver", "Limon"], ["Colorado Springs", "Limon"]] </code></pre> <p>This has a bunch of cycles. For example, you can drive from Colorado Springs, to Limon, to Denver, and back to Colorado Springs.</p> <p>If you create a data structure that contains all the cities in V and all the roads in E, that's a <em>graph</em> data structure. This graph would have cycles.</p>
How to get t4 files to build in visual studio? <p>When I build my c# solution the .tt files will not create the .cs file outputs. But if I right click the .tt files one at a time in solution explorer and select "Run Custom Tool" the .cs is generated, so the build tool setting is correct. What do I do to get the overall solution build to force the custom tool to run on the .tt files?</p>
<p>Paul, you can also generate code at build time with <a href="http://msdn.microsoft.com/en-us/library/bb126245.aspx">TextTransform.exe</a> or <a href="http://geekswithblogs.net/EltonStoneman/archive/2008/07/25/an-msbuild-task-to-execute-t4-templates.aspx">Elton Stoneman's MSBuild task</a>. Just keep in mind that behavior of the built-in directives, like <a href="http://www.olegsych.com/2008/02/t4-assembly-directive/">assembly</a> and <a href="http://www.olegsych.com/2008/02/t4-include-directive/">include</a> is different when T4 runs in Visual Studio vs. the command-line host.</p>
Detecting that a ThreadPool WorkItem has completed/waiting for completion <p>For whatever reason, <code>ThreadPool</code>'s <code>QueueWorkItem</code> doesn't return an <code>IAsyncResult</code> or some other handle to the work item, which would allow to wait until it's completed. There are <code>RegisterWait...</code> methods, but you have to pass a <code>WaitHandle</code> and creating them is expensive (see <code>IAsyncResult</code> documentation, which advises you to delay creating a <code>WaitHandle</code> until requested). The Task Parallel Library will fix this lack, but there is a long wait before that's available. So, are there any problems with this design:</p> <pre><code>public class Concurrent&lt;T&gt; { private ManualResetEvent _resetEvent; private T _result; public Concurrent(Func&lt;T&gt; f) { ThreadPool.QueueUserWorkItem(_ =&gt; { _result = f(); if (_resetEvent != null) _resetEvent.Set(); }); } public WaitHandle WaitHandle { get { if (_resetEvent == null) _resetEvent = new ManualResetEvent(_result != null); return _resetEvent; } ... </code></pre> <p>EDIT: I asked a <a href="http://stackoverflow.com/questions/406915/using-begininvoke-endinvoke-in-a-multithreaded-fashion-how-do-asynccallback-asy">follow-up question about the concerns which arise when using async delegates instead of the ThreadPool</a>.</p>
<p>Well, you've got a race condition between fetching the WaitHandle and setting it. Do you really want the caller to be waiting forever if they happen to be a tiny bit late?</p> <p>You should probably do some appropriate locking and keep an "I've finished" flag so that if you <em>do</em> create the WaitHandle after it's finished, you set it before returning it.</p> <p>I'd also personally write a static factory method rather than just using a public constructor - or make it a "create and <em>then</em> explicitly start" pattern. Queuing the work item in the constructor feels weird to me.</p>
Methods for interacting with a Pervasive SQL database <p>I'm in the process of developing a web interface to a service business management application that uses a Pervasive SQL database to store information (not my choice, by the way). At the moment, I'm using the official Pervasive SqlClient implementation with a custom set of query generation classes so I can write code like:</p> <pre><code>new SelectQuery().From("CUSTOMER").Fields("CUSTOMERNBR", "NAME"); </code></pre> <p>It's working fine so far, but I'm running into little problems here and there. Rather than keep going in this direction, I'd rather use a proven DAL. However, I'm not having very much luck in finding a DAL system that can interact with a Pervasive database.</p> <p>Opf3 has a Pervasive storage provider, but I've never heard of that framework before and the website only displays the Pervasive v8 logo, while I need something that will work with v9.5 and, in the future, v10.</p> <p>I tried writing an NHibernate provider, but that ended up being even more of a headache than my current query generation system.</p> <p>What do you suggest? I'm on a very rushed timeline, so I'd like something that will integrate as easily as possible.</p>
<p>Pervasive.SQL has a pretty solid ADO Adapter, and rocks over ODBC in most cases; I have used if successufully for years, but not without the headaches of Pervasive's syntax. In Pervasive's defense their relational engine does comply with SQL-92 and most of SQL-99. </p> <p>What I am curious about is what parts of the syntax are you having a problem with, what is causing your grief?</p> <p>What version of Pervasive's engine are you using?</p>
In Subversion can I be a user other than my login name? <p>I'd like to know how to get <code>Subversion</code> to change the name that my changes appear under.</p> <p>I'm just starting to use <code>Subversion</code>. I'm currently using it to version control code on an XP laptop where I'm always logged in under my wife's name. I'd like the subversion DB to show the changes under my name.</p> <p>Later on I'll replicate the DB so it is accessible to the whole house. My wife uses the office computer where she is always logged in under my name. I'll probably set it up so that it automatically checks in modified documents... preferably under her name.</p> <p>Eventually I'll probably be using it from a linux machine under another username.</p> <p>Is there some way to modify the user environment to change the user name that Subversion calls you? I'd expect something like setting <code>SVN_USERNAME='Mark'</code> which would override however it usually gets the name.</p> <p><strong>Update:</strong> It looks like the <code>--username</code> flag that Michael referred to does work to change the name reported by <code>"svn stat"</code>, even for local file: repositories. In addition, it is sticky so you don't need to specify it for the next command. I even rebooted and it still used the <code>"--username"</code> value from my previous boot.</p>
<p>Most Subversion commands take the <code>--username</code> option to specify the username you want to use to the repository. Subversion remembers the last repository username and password used in each working copy, which means, among other things, that if you use <code>svn checkout --username myuser</code> you never need to specify the username again.</p> <p><strong>EDIT</strong>: <a href="http://stackoverflow.com/questions/405690/in-subversion-can-i-be-a-user-other-than-my-login-name#405699">As Kamil Kisiel says</a>, when Subversion is accessing the repository directly off the file system (that is, the repository URL is of form <code>file:///path/to/repo</code> or <code>file://file-server/path/to/repo</code>), it uses your file system permissions to access the repository. And when you <a href="http://svnbook.red-bean.com/nightly/en/svn.serverconfig.svnserve.html#svn.serverconfig.svnserve.sshauth">connect via SSH tunneling</a> (<code>svn+ssh://server/path/to/repo</code>), SVN uses your FS permissions on the <em>server</em>, as determined by your SSH login. In those cases, <code>svn checkout --username</code> may not work for your repository.</p>
Project source or published DLL's? <p>When reusing code (for example, a Util library you created), do you add its project to your solution or use a compiled/published DLL from the Util library?</p>
<p>If an assembly is mature, not likely to change or I'm fairly certain I won't need to step into it I would reference the DLL. If it's likely that changes will be made in the assembly's project or it's likely I'll want to step into it, I reference the project.</p>
Why are compilers so stupid? <p>I always wonder why compilers can't figure out simple things that are obvious to the human eye. They do lots of simple optimizations, but never something even a little bit complex. For example, this code takes about 6 seconds on my computer to print the value zero (using java 1.6):</p> <pre><code>int x = 0; for (int i = 0; i &lt; 100 * 1000 * 1000 * 1000; ++i) { x += x + x + x + x + x; } System.out.println(x); </code></pre> <p>It is totally obvious that x is never changed so no matter how often you add 0 to itself it stays zero. So the compiler could in theory replace this with System.out.println(0).</p> <p>Or even better, this takes 23 seconds:</p> <pre><code>public int slow() { String s = "x"; for (int i = 0; i &lt; 100000; ++i) { s += "x"; } return 10; } </code></pre> <p>First the compiler could notice that I am actually creating a string s of 100000 "x" so it could automatically use s StringBuilder instead, or even better directly replace it with the resulting string as it is always the same. Second, It does not recognize that I do not actually use the string at all, so the whole loop could be discarded!</p> <p>Why, after so much manpower is going into fast compilers, are they still so relatively dumb?</p> <p><strong>EDIT</strong>: Of course these are stupid examples that should never be used anywhere. But whenever I have to rewrite a beautiful and very readable code into something unreadable so that the compiler is happy and produces fast code, I wonder why compilers or some other automated tool can't do this work for me.</p>
<p>In my opinion, I don't believe it's the job of the compiler to fix what is, honestly, bad coding. You have, quite explicitly, told the compiler you want that first loop executed. It's the same as:</p> <pre><code>x = 0 sleep 6 // Let's assume this is defined somewhere. print x </code></pre> <p>I wouldn't want the compiler removing my <code>sleep</code> statement just because it did nothing. You may argue that the sleep statement is an explicit request for a delay whereas your example is not. But then you will be allowing the compiler to make very high-level decisions about what your code should do, and I believe that to be a bad thing.</p> <p>Code, and the compiler that processes it, are tools and you need to be a tool-smith if you want to use them effectively. How many 12" chainsaws will refuse to try cut down a 30" tree? How many drills will automatically switch to hammer mode if they detect a concrete wall?</p> <p>None, I suspect, and this is because the cost of designing this into the product would be horrendous for a start. But, more importantly, you shouldn't be using drills or chainsaws if you don't know what you're doing. For example: if you don't know what kickback is (a very easy way for a newbie to take off their arm), stay away from chainsaws until you do.</p> <p>I'm all for allowing compilers to <em>suggest</em> improvements but I'd rather maintain the control myself. It should not be up to the compiler to decide unilaterally that a loop is unnecessary.</p> <p>For example, I've done timing loops in embedded systems where the clock speed of the CPU is known exactly but no reliable timing device is available. In that case, you can calculate precisely how long a given loop will take and use that to control how often things happen. That wouldn't work if the compiler (or assembler in that case) decided my loop was useless and optimized it out of existence.</p> <p>Having said that, let me leave you with an old story of a VAX FORTRAN compiler that was undergoing a benchmark for performance and it was found that it was <em>many</em> orders of magnitude faster than its nearest competitor.</p> <p>It turns out the compiler noticed that the result of the benchmark loops weren't being used anywhere else and optimized the loops into oblivion.</p>
Large amount of data - what is the best way to send them? <p>we have this scenario:</p> <p>A server which contains needed data and client component which these data wants.</p> <p>On the server are stored 2 types of data: - some information - just a couple of strings basically - binary data</p> <p>We have a problem with getting binary data. Both sides are written in Java 5 so we have couple of ways....</p> <p>Web Service is not the best solution because of speed, memory etc...</p> <p>So, What would you prefer?</p> <p>I would like to miss low level socket connection if possible...</p> <p>thanks in advance</p> <p>Vitek</p>
<p>Take a look at the W3C standard MTOM to transfer binary data as part of a SOAP service. It is efficient in that it sends as a binary and can also send as buffered chunks. It will also interop with other clients or providers:</p> <p><a href="http://blogs.msdn.com/smguest/archive/2005/06/30/434218.aspx" rel="nofollow">How to do MTOM Interop</a></p> <p><a href="http://www.theserverside.com/tt/articles/article.tss?l=SendingAttachmentsWithSOAP" rel="nofollow">Server Side - Sending Attachments with SOAP</a></p>
.NET Rectangular Arrays: how to access in a loop? <p>Basically you have two ways for doing this:</p> <pre><code>for (int x = 0; x &lt; UPPER_X; x++) for (int y = 0; y &lt; UPPER_Y; y++) { arr1[x, y] = get_value(); arr2[y, x] = get_value(); } </code></pre> <p>The only difference is what variable to change in the inner loop: first or second. I heard that the results differ from language to language. </p> <p>What is right order for .NET?</p>
<p>You should benchmark your particular circumstances to be sure.</p> <p>You would think that there would be no difference for rectangular arrays (i.e. contiguously allocated memory), BUT according to this <a href="http://msdn.microsoft.com/en-us/magazine/cc163995.aspx" rel="nofollow">MSDN article</a> there is a difference:</p> <blockquote> <p>You can get even better results by converting a multidimensional array into a single-dimensional array. If you don't mind the syntax, this can be trivial; just use one index as an offset. For example, the following declares a single-dimensional array to be used as a two-dimensional array: </p> </blockquote> <pre><code>double[] myArray = new double[ROW_DIM * COLUMN_DIM]; </code></pre> <blockquote> <p>For indexing the elements of this array, use the following offset: </p> </blockquote> <pre><code>myArray[row * COLUMN_DIM + column]; </code></pre> <blockquote> <p>This will undoubtedly be faster than an equivalent jagged or rectangular array.</p> </blockquote>
Using svn with Textmate <p>Coming from IDEs with full-blown svn support such as Eclipse and Netbeans, I'm wondering what is the recommended way to use svn with Textmate? Is it all manual, ie using the command line, or are there features that allow you to diff/checkin/merge/etc in Textmate itself?</p>
<p>There is a plugin for textmate wich can be found here: <a href="http://www.reinventar.com/2008/07/svn-plugin-for-textmate/">http://www.reinventar.com/2008/07/svn-plugin-for-textmate/</a></p> <p>The plugin mentioned in that post is SVNMate</p>
Get the id of inserted row using C# <p>I have a query to insert a row into a table, which has a field called ID, which is populated using an AUTO_INCREMENT on the column. I need to get this value for the next bit of functionality, but when I run the following, it always returns 0 even though the actual value is not 0:</p> <pre><code>MySqlCommand comm = connect.CreateCommand(); comm.CommandText = insertInvoice; comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', " + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ")"; int id = Convert.ToInt32(comm.ExecuteScalar()); </code></pre> <p>According to my understanding, this should return the ID column, but it just returns 0 every time. Any ideas?</p> <p><strong>EDIT:</strong></p> <p>When I run:</p> <pre><code>"INSERT INTO INVOICE (INVOICE_DATE, BOOK_FEE, ADMIN_FEE, TOTAL_FEE, CUSTOMER_ID) VALUES ('2009:01:01 10:21:12', 50, 7, 57, 2134);last_insert_id();" </code></pre> <p>I get:</p> <pre><code>{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'last_insert_id()' at line 1"} </code></pre>
<pre><code>MySqlCommand comm = connect.CreateCommand(); comm.CommandText = insertStatement; // Set the insert statement comm.ExecuteNonQuery(); // Execute the command long id = comm.LastInsertedId; // Get the ID of the inserted item </code></pre>
What is a RESTful way of monitoring a REST resource for changes? <p>If there is a REST resource that I want to monitor for changes or modifications from other clients, what is the best (and most RESTful) way of doing so?</p> <p>One idea I've had for doing so is by providing specific resources that will keep the connection open rather than returning immediately if the resource does not (yet) exist. For example, given the resource:</p> <pre><code>/game/17/playerToMove </code></pre> <p>a "GET" on this resource might tell me that it's my opponent's turn to move. Rather than continually polling this resource to find out when it's my turn to move, I might note the move number (say 5) and attempt to retrieve the next move:</p> <pre><code>/game/17/move/5 </code></pre> <p>In a "normal" REST model, it seems a GET request for this URL would return a 404 (not found) error. However, if instead, the server kept the connection open until my opponent played his move, i.e.:</p> <pre><code>PUT /game/17/move/5 </code></pre> <p>then the server could return the contents that my opponent PUT into that resource. This would both provide me with the data I need, as well as a sort of notification for when my opponent has moved without requiring polling.</p> <p>Is this sort of scheme RESTful? Or does it violate some sort of REST principle?</p>
<p>Your proposed solution sounds like <a href="http://stackoverflow.com/questions/333664/simple-long-polling-example-code">long polling</a>, which could work really well.</p> <p>You would request <code>/game/17/move/5</code> and the server will not send any data, until move 5 has been completed. If the connection drops, or you get a time-out, you simply reconnect until you get a valid response.</p> <p>The benefit of this is it's very quick - as soon as the server has new data, the client will get it. It's also resilient to dropped connections, and works if the client is disconnected for a while (you could request <code>/game/17/move/5</code> an hour after it's been moved and get the data instantly, then move onto <code>move/6/</code> and so on)</p> <p>The issue with long polling is each "poll" ties up a server thread, which quickly breaks servers like Apache (as it runs out of worker-threads, so can't accept other requests). You need a specialised web-server to serve the long-polling requests.. The Python module <a href="http://twistedmatrix.com/trac/"><code>twisted</code></a> (an "an event-driven networking engine") is great for this, but it's more work than regular polling..</p> <p>In answer to your comment about Jetty/Tomcat, I don't have any experience with Java, but it seems they both use a similar pool-of-worker-threads system to Apache, so it will have that same problem. I did find <a href="http://www.ibm.com/developerworks/web/library/wa-aj-hiperform/index.html">this post</a> which seems to address exactly this problem (for Tomcat)</p>
Passing Pointer To An Array Of Arrays Through Function <p>There is a pointer-to-an-Array of Arrays i.e. NameList in the code. I want the contents of each of the Arrays in the Pointer(NameList) to get printed one by one. The below code is not able do the task. Pls. help.</p> <pre><code>int Data1[] = {10,10}; int Data2[] = {20,20}; int Data3[] = {30,30}; int *NameList[] = {Data1, Data2, Data3}; main() { Function(NameList); } Function(int *ArrayPointer) { int i, j, index=0; for (i=0; i &lt; 3; i++) { for (j=0; j &lt; 2; j++) { //It does not print the data printf("\nName: %s", ArrayPointer[index++]); } index=0; //Counter reset to 0 ArrayPointer++; //Pointer is incremented by one to pick next array in the pointer } } print("code sample"); </code></pre> <p>Another note from the original poster of the question:</p> <p>I have completed a pacman game in Turbo C. I was polishing some graphics routines so that it can be reused again easily. This is only a small sample created for the purpose of help and understanding the concept. All data in the code actually are char arrays for sprites. Now i simply want to call a function passing the pointer so that each arrays in the pointer are drawn to the screen. How can this code be modified to handle this? Im actually stuck up here.</p>
<p>Darn it <em>litb</em>, once again you beat me to the punch by mere minutes. (If only I didn't have kids who keep waking up...)</p> <p>Ahh, what the hell. Perhaps this will still be useful to somebody.</p> <p><hr /></p> <p>Oh, and just to nail this thing down:</p> <ul> <li>Arrays, such as <em>int a[4]</em> allocate memory space for their data.</li> <li>Pointers, such as <em>int * p</em> allocate just enouch memory space for a pointer to another spot in memory.</li> <li>That's why we can use <em>sizeof</em> on arrays and get the full memory footprint, but not on pointers.</li> </ul> <p>Other than that little distinction, there really isn't a big difference between int[] and int*. (Consider how many folks declare *main(int argc, char **argv) vs <em>main(int argc, char * argv[])</em>.)</p> <p><hr /></p> <p><strong>ATTENTION: All memory addresses here are fictional. I'm just making them up to illustrate a point.</strong></p> <p>Given:</p> <pre><code>int Data1[] = {10,11}; int Data2[] = {20,22}; int Data3[] = {30,33}; </code></pre> <p>We now have 3 blocks of memory. Say:</p> <pre><code>0xffff0000-0xffff0003 with a value of (int)(10) 0xffff0004-0xffff0007 with a value of (int)(11) 0xffff0008-0xffff000b with a value of (int)(20) 0xffff000c-0xffff000f with a value of (int)(22) 0xffff0010-0xffff0013 with a value of (int)(30) 0xffff0014-0xffff0017 with a value of (int)(33) </code></pre> <p>Where:</p> <pre><code>Data1 == &amp; Data1 [0] == 0xffff0000 Data2 == &amp; Data2 [0] == 0xffff0008 Data3 == &amp; Data3 [0] == 0xffff0010 </code></pre> <p><strong>NO</strong>, I'm <strong>not</strong> going to get into big-endian vs little-endian byte ordering here!</p> <p>Yes, in this case, Data1[2] == Data2[0]. But you can't rely on your compiler laying things out in memory the same way I've laid them out here.</p> <p>Next:</p> <pre><code>int *NameList[] = {Data1, Data2, Data3}; </code></pre> <p>So we now have another block of memory. Say:</p> <pre><code>0xffff0018-0xffff001b with a value of (int*)(0xffff0000) 0xffff001c-0xffff001f with a value of (int*)(0xffff0008) 0xffff0020-0xffff0023 with a value of (int*)(0xffff0010) </code></pre> <p>Where:</p> <pre><code>NameList == &amp; NameList [0] == 0xffff0018 </code></pre> <p>Note that NameList is of <strong>int **</strong> type, and <strong>NOT int*</strong> type!</p> <p>We can then write:</p> <pre><code>void Function(int **ArrayPointer) { for ( int i=0; i &lt; 3; i++ ) for ( int j=0; j &lt; 2; j++) printf("Name: %d\n", ArrayPointer[i][j] ); } int main() { Function(NameList); } </code></pre> <p>ArrayPointer resolves to (int**)0xffff0018.</p> <p>ArrayPointer[0] == *( (int**) 0xffff0018 ) == (int*)(0xffff0000) == Data1.</p> <p>ArrayPointer[0][1] == *( ( * (int**) 0xffff0018 ) + 1 ) == (int) * ( (int*)0xffff0000 + 1 ) == (int) * (int*) 0xffff0004 == Data1[1].</p> <p><hr /></p> <p>You may want to review pointer arithmetic: array[N] == *( array + N )</p>
Best way to have event occur n times? <p>I use the following code to create countdowns in Javascript. n is the number of times to repeat, freq is the number of milliseconds to wait before executing, funN is a function to call on each iteration (typically a function that updates part of the DOM) and funDone is the function to call when the countdown is complete. </p> <pre><code>function timer(n, freq, funN, funDone) { if(n == 0){ funDone(); }else{ setTimeout(function(){funN(n-1); timer(n-1, freq, funN, funDone);}, freq); } } </code></pre> <p>It can be called like so:</p> <pre><code> timer(10, 1000, /* 1 second */ function(n){console.log("(A) Counting: "+n);}, function() {console.log("(A) Done!");} ); timer(10, 500, function(n){console.log("(B) Counting: "+n);}, function() {console.log("(B) Done!");} ); </code></pre> <p>The advantage of this is that I can call timer() as many times as I want without worrying about global variables etc. Is there a better way to do this? Is there a clean way to make setInterval stop after a certain number of calls (without using global variables)? This code also creates a new lambda function with each call to setTimeout which seems like it could be problematic for large countdowns (I'm not sure how javascript's garbage collector handles this). </p> <p>Is there a better way to do this? Thanks.</p>
<p>This is basically the same idea as @balabaster, but it is tested, uses prototype, and has a little more flexible interface.</p> <pre><code>var CountDownTimer = function(callback,n,interval) { this.initialize(callback,n,interval); } CountDownTimer.prototype = { _times : 0, _interval: 1000, _callback: null, constructor: CountDownTimer, initialize: function(callback,n,interval) { this._callback = callback; this.setTimes(n); this.setInterval(interval); }, setTimes: function(n) { if (n) this._times = n else this._times = 0; }, setInterval: function(interval) { if (interval) this._interval = interval else this._interval = 1000; }, start: function() { this._handleExpiration(this,this._times); }, _handleExpiration: function(timer,counter) { if (counter &gt; 0) { if (timer._callback) timer._callback(counter); setTimeout( function() { timer._handleExpiration(timer,counter-1); }, timer._interval ); } } }; var timer = new CountDownTimer(function(i) { alert(i); },10); ... &lt;input type='button' value='Start Timer' onclick='timer.start();' /&gt; </code></pre>
Web data grid of infragistic controls <p>I am working on a web project where i need to use web data grid of infragistic controls. I have problem to customise the header layout. I did not find event like InisalizeLayOut in ultrawebgrid. My problem is that i want to row in header. Please give me your valuable suggations. Thanks</p>
<p>You need to use <code>WebHierarchicalDataGrid</code> control for representing hierarchical data structures instead <code>WebDataGrid</code>, check out the samples here <a href="http://samples.infragistics.com/aspnet/ComponentOverview.aspx?cn=hierarchical-data-grid" rel="nofollow">http://samples.infragistics.com/aspnet/ComponentOverview.aspx?cn=hierarchical-data-grid</a></p>
How do I add a file to Subversion that has the same name as a directory that was deleted? <p>A long time ago I had the following directory structure in my SVN repository</p> <pre><code>trunk/ data/ levels/ 1.level 2.level ... ... ... </code></pre> <p>But I deleted the 'levels' directory long ago. Now I want to add a single text file called 'levels' to the 'data' directory, so it will look like this:</p> <pre><code>trunk/ data/ levels ... ... </code></pre> <p>Now when I try to add the file 'levels', I get this message:</p> <pre><code>$ svn add data/levels svn: Can't replace 'data/levels' with a node of a differing type; the deletion m ust be committed and the parent updated before adding 'data/levels' </code></pre> <p>How can I solve this?</p>
<p>Try running <code>svn update</code>. That will update the current folder's revision number and all associated metadata. You should also make sure <code>svn status</code> doesn't display anything related to this.</p>
Does Team Explorer integrate with VS2005 <p>I have both VS2005 and VS2008 installed on my machine. I was able to install Team Explorer 2008, but could not install Team Explorer 2005 (it kept throwing some error number 2337 which I could not resolve).</p> <p>Currently, I am having to launch the VS2008 IDE for using source control, and VS2005 for working on the source code (as the projects and solution files are still in the older VS2005 format). </p> <p>Can I TE2008 to work with VS2005 in order to have an integrated experience?</p>
<p>You must have the the 2005 version of Team Explorer installed for the TFS integration to be present in VS 2005. Visual Studio 2005 + Team Explorer 2005 can happily co-exist on a machine with Visual Studio 2008 + Team Explorer 2008 and run side by side.</p> <p>So, to get this to work you need to work past your 2337 error. The only times when I have seen that error myself have been where the Team Explorer installer was corrupted. You could try <a href="http://download.microsoft.com/download/2/a/d/2ad44873-8ccb-4a1b-9c0d-23224b3ba34c/VSTFClient.img" rel="nofollow">re-downloading it</a> or accessing it from a Team Foundation Server 2005 installation CD.</p> <p>Hope that helps,</p> <p>Martin.</p>
Regular expression to match line that doesn't contain a word? <p>I know it's possible to match a word and then reverse the matches using other tools (e.g. <code>grep -v</code>). However, I'd like to know if it's possible to match lines that <em>don't</em> contain a specific word (e.g. hede) using a regular expression? </p> <p>Input:</p> <pre><code>hoho hihi haha hede </code></pre> <p>Code: </p> <pre><code># grep "Regex for doesn't contain hede" Input </code></pre> <p>Desired output: </p> <pre><code>hoho hihi haha </code></pre>
<p>The notion that regex doesn't support inverse matching is not entirely true. You can mimic this behavior by using negative look-arounds:</p> <pre><code>^((?!hede).)*$ </code></pre> <p>The regex above will match any string, or line without a line break, <strong>not</strong> containing the (sub) string 'hede'. As mentioned, this is not something regex is "good" at (or should do), but still, it <em>is</em> possible. </p> <p>And if you need to match line break chars as well, use the <a href="http://perldoc.perl.org/perlre.html#Modifiers">DOT-ALL modifier</a> (the trailing <code>s</code> in the following pattern):</p> <pre><code>/^((?!hede).)*$/s </code></pre> <p>or use it inline:</p> <pre><code>/(?s)^((?!hede).)*$/ </code></pre> <p><em>(where the <code>/.../</code> are the regex delimiters, ie, not part of the pattern)</em></p> <p>If the DOT-ALL modifier is not available, you can mimic the same behavior with the character class <code>[\s\S]</code>:</p> <pre><code>/^((?!hede)[\s\S])*$/ </code></pre> <h2>Explanation</h2> <p>A string is just a list of <code>n</code> characters. Before, and after each character, there's an empty string. So a list of <code>n</code> characters will have <code>n+1</code> empty strings. Consider the string <code>"ABhedeCD"</code>:</p> <pre><code> +--+---+--+---+--+---+--+---+--+---+--+---+--+---+--+---+--+ S = |e1| A |e2| B |e3| h |e4| e |e5| d |e6| e |e7| C |e8| D |e9| +--+---+--+---+--+---+--+---+--+---+--+---+--+---+--+---+--+ index 0 1 2 3 4 5 6 7 </code></pre> <p>where the <code>e</code>'s are the empty strings. The regex <code>(?!hede).</code> looks ahead to see if there's no substring <code>"hede"</code> to be seen, and if that is the case (so something else is seen), then the <code>.</code> (dot) will match any character except a line break. Look-arounds are also called <em>zero-width-assertions</em> because they don't <em>consume</em> any characters. They only assert/validate something. </p> <p>So, in my example, every empty string is first validated to see if there's no <code>"hede"</code> up ahead, before a character is consumed by the <code>.</code> (dot). The regex <code>(?!hede).</code> will do that only once, so it is wrapped in a group, and repeated zero or more times: <code>((?!hede).)*</code>. Finally, the start- and end-of-input are anchored to make sure the entire input is consumed: <code>^((?!hede).)*$</code></p> <p>As you can see, the input <code>"ABhedeCD"</code> will fail because on <code>e3</code>, the regex <code>(?!hede)</code> fails (there <em>is</em> <code>"hede"</code> up ahead!).</p>
Add New Column in Infragistics Wingrid <p>I am using Infragistics wingrid in my application. I have assigned a datasource to my wingrid. Now i want to add a new column at a specific location.</p> <p>Can any one please tell me how can this be performed?</p> <p>Regards, Savan.</p>
<p>Greetings, </p> <p>I would add the new column to your datasource. Since the datasource is bound to the grid the column should appear. </p>
How to add bottom padding to a div that contains floating divs? <p>I have a div that contains other floating divs:</p> <p>&lt;div id="parent"&gt;<br /> &nbsp;&nbsp;&lt;div style="float:left;"&gt;text&lt;/div&gt;<br /> &nbsp;&nbsp;&lt;div style="float:left;"&gt;text&lt;/div&gt;<br /> &nbsp;&nbsp;&lt;div style="float:right;"&gt;text&lt;/div&gt;<br /> &lt;/div&gt;</p> <p>How can I add bottom padding to the parent div and make it work in IE6 (or in other words avoid the bugs in IE6)?</p> <p>Thanks</p>
<p>In my CSS reset file i have a "clearfix" code:</p> <pre><code>.clearfix:after { content:"."; display:block; height:0; clear:both; visibility:hidden; } .clearfix {display:inline-block;} /* Hide from IE Mac \*/ .clearfix {display:block;} /* End hide from IE Mac */ * html .clearfix {height:1px;} </code></pre> <p>Looks weird but works great on ALL common browsers : IE6/7, FF2/3, Opera, Safari.</p> <p><strong>How to use?</strong></p> <p>Something like this: </p> <pre><code>&lt;div class="clearfix"&gt; &lt;div class="floatLeft"&gt; left div &lt;/div&gt;&lt;!-- /.floatLeft--&gt; &lt;div class="floatRight"&gt; right div &lt;/div&gt;&lt;!-- /.floatRight--&gt; &lt;/div&gt;&lt;!-- /.clearfix--&gt; </code></pre> <p><strong>ATTENTION!</strong> Do <em>NOT</em> use clearfix class on footers (or at last element in page), otherwise you will have an ugly space under all content.</p>
Divide by zero error in stored procedure <p>Hi i executed the following stored procedure in .net web application. Then run the application. I got this error</p> <p>" Divide By zero error "</p> <p>Stored procedure:</p> <pre><code>CREATE procedure Details(@Stringtext varchar(8000),@SearchStringtext varchar(100)) as begin SELECT ({fn LENGTH(@Stringtext)}- {fn LENGTH({fn REPLACE(@Stringtext, @SearchStringtext, '')})})/ { fn LENGTH(@SearchStringtext)}AS String_Count end </code></pre>
<p>Evidently:</p> <pre><code>{ fn LENGTH(@SearchStringtext)} </code></pre> <p>... is evaluating to zero.</p>
What is the best practices in db design when I want to store a value that is either selected from a dropdown list or user-entered? <p>I am trying to find the best way to design the database in order to allow the following scenario:</p> <ol> <li>The user is presented with a dropdown list of Universities (for example)</li> <li>The user selects his/her university from the list if it exists</li> <li>If the university does not exist, he should enter his own university in a text box (sort of like Other: [___________])</li> </ol> <p>how should I design the database to handle such situation given that I might want to sort using the university ID for example (probably only for the built in universities and not the ones entered by users)</p> <p>thanks!</p> <p>I just want to make it similar to how Facebook handles this situation. If the user selects his Education (by actually typing in the combobox which is not my concern) and choosing one of the returned values, what would Facebook do?</p> <p>In my guess, it would insert the UserID and the EducationID in a many-to-many table. Now what if the user is entering is not in the database at all? It is still stored in his profile, but where? <img src="http://i43.tinypic.com/hufztt.jpg" alt="typing &quot;St&quot;...suggesting Stanford"></p> <p><img src="http://i41.tinypic.com/14j56s8.jpg" alt="typing non-existing university"></p>
<pre><code>CREATE TABLE university ( id smallint NOT NULL, name text, public smallint, CONSTRAINT university_pk PRIMARY KEY (id) ); CREATE TABLE person ( id smallint NOT NULL, university smallint, -- more columns here... CONSTRAINT person_pk PRIMARY KEY (id), CONSTRAINT person_university_fk FOREIGN KEY (university) REFERENCES university (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION ); </code></pre> <p>public is set to 1 for the Unis in the system, and 0 for user-entered-unis.</p>
How do you set up your virtual machines? <p>Recently the buzz of virtualization has reached my workplace where developers trying out virtual machines on their computers. Earlier I've been hearing from several different developers about setting up virtual machine in their desktop computers for sake of keeping their development environments clean.</p> <p>There are plenty of Virtual Machine software products in the market:</p> <ul> <li>Microsoft <a href="http://sv.wikipedia.org/wiki/Microsoft_Virtual_PC">Virtual PC</a></li> <li>Sun <a href="http://www.virtualbox.org/">VirtualBox</a></li> <li><a href="http://www.vmware.com/">VMWare</a> <a href="http://en.wikipedia.org/wiki/VMware_Workstation">Workstation</a> or <a href="http://en.wikipedia.org/wiki/VMware_Player">Player</a></li> <li>Parallell Inc's <a href="http://www.parallels.com/en/products/desktop/">Parallells Desktop</a></li> </ul> <p>I'm interested to know how you use virtualization effectively in your work. My question is <strong>how do you use Virtual Machines for day-to-day development</strong> and for what reason?</p>
<p>I just built a real beefy machine at home so that I could run multiple VMs at once. My case is probably extreme though, but here is my logic for doing so.</p> <p><strong>Testing</strong></p> <p>When I test, particularly a desktop app, I typically create multiple VMs, one for each platform that my software should run on (Windows 2000/XP/Vista etc). If 32 and 64 bit flavors are available, I also build one of each. I also play with the VM hardware settings (e.g. lots of RAM, little RAM, 1 core, 2 core, etc). I found plenty of little bugs this way, that definitely would have made it into the wild had I not used this approach.</p> <p>This approach also makes it easy to play with different software scenarios (what happens if the user installing the program doesn't have .NET 3.5 sp1? What happens if he doesn't have XXX component? etc?</p> <p><strong>Development</strong></p> <p>When I develop, I have one VM running my database servers (SQL2000/2005/2008). This is for two reasons. First, it is more realistic. In a production environment your app is probably not running on the same box as the db. Why not replicate it when you develop? Also, when I'm not developing (remember this is also my home machine), do I really need to have all of those database services running? Yes, I could turn them on and off manually, but its so much easier to switch a VM on.</p> <p><strong>Clients</strong></p> <p>If I want to show a client some web work I've done, I can put just a single VM into the DMZ and he can log into the VM and play with the web project, while the rest of my network/computer is safe.</p> <p><strong>Compatibility</strong></p> <p>Vista64 is now my main machine. Any older hardware/software I own will not play nicely with that OS. My solutions is to have Windows XP 32 as a VM for all of those items.</p>
Vertical center an anchor tag within a fieldset <p>I am trying to vertically center an anchor within a fieldset using CSS but it always appears to align to bottom. Is there any tricks to this?</p>
<p>You are not giving too much detail here. Besides the line-height you might also want to tweak top and bottom padding. It all depends on how much stuff you have inside the fieldset.</p>
Performance comparisons betweeen enum evaluations and ints <p>Would there be difference in speed between<br/></p> <pre><code>if (myInt == CONST_STATE1) </code></pre> <p>and</p> <pre><code>if (myEnum == myENUM.State1) </code></pre> <p>in c#?</p>
<p>In C# Enums are in-lined to be constants by the compilier anyway, so the benefit is code legibility</p>
What's your most controversial programming opinion? <p>This is definitely subjective, but I'd like to try to avoid it becoming argumentative. I think it could be an interesting question if people treat it appropriately.</p> <p>The idea for this question came from the comment thread from <a href="http://stackoverflow.com/questions/282329/what-are-five-things-you-hate-about-your-favorite-language#282342">my answer</a> to the <a href="http://stackoverflow.com/questions/282329">"What are five things you hate about your favorite language?" question</a>. I contended that classes in C# should be sealed by default - I won't put my reasoning in the question, but I might write a fuller explanation as an answer to this question. I was surprised at the heat of the discussion in the comments (25 comments currently).</p> <p>So, what contentious opinions do <em>you</em> hold? I'd rather avoid the kind of thing which ends up being pretty religious with relatively little basis (e.g. brace placing) but examples might include things like "unit testing isn't actually terribly helpful" or "public fields are okay really". The important thing (to me, anyway) is that you've got reasons behind your opinions.</p> <p>Please present your opinion and reasoning - I would encourage people to vote for opinions which are well-argued and interesting, whether or not you happen to agree with them.</p>
<p><strong>Programmers who don't code in their spare time for fun will never become as good as those that do.</strong></p> <p>I think even the smartest and most talented people will never become truly good programmers unless they treat it as more than a job. Meaning that they do little projects on the side, or just mess with lots of different languages and ideas in their spare time.</p> <p>(Note: I'm not saying good programmers do nothing else than programming, but they do more than program from 9 to 5)</p>
Forcing reload of a html page after a small wait <p>I have a html page A and a link in the page which opens up page B in a new window. How to reload the page A on clicking and opening this link ? </p> <p><strong>EDIT:</strong></p> <p>I should have been more clear. Page B opens in a new window and not as a popup. The hyperlink in question has its target attribute set to _blank. Taking a clue from the answers that I got (Thanks guys !), I tried setting onclick = "window.location.reload()" and it works perfectly fine.</p> <p>However I have a problem. In fact another question altogether. How to make sure that the reload of page A waits until the page opened in the new window (page B) loads ?</p>
<p>Something like this:</p> <pre><code>&lt;a href="javascript:window.open('pageB.htm');window.location.reload();"&gt;open page b&lt;/a&gt; </code></pre>
Can Java Enumerations be merged (like Bitwise in C#)? <p>Is there a way in Java to declare an enumeration whose values can be used together? For example:</p> <pre><code>enum FileAccess { Read, Write, ReadWrite } </code></pre> <p>Is it possible to define ReadWrite as <code>Read | Write</code> (or anything that would yield the same result)?</p>
<p>You use <a href="http://java.sun.com/javase/6/docs/api/java/util/EnumSet.html">EnumSet</a>:</p> <pre><code>EnumSet&lt;FileAccess&gt; readWrite = EnumSet.of(FileAccess.Read, FileAccess.Write); </code></pre> <p>This is actually somewhat more elegant than the C#/.NET way, IMO - aside from anything else, you can easily distinguish between a set and a single value.</p>
It's possible to develop for .net 2.x in Visual Studio 2008? <p>It's possible to develop only for .net 2.0 running Visual Studio 2008?</p> <p>Thanks!</p>
<p>Check out this article - <a href="http://weblogs.asp.net/scottgu/archive/2007/06/20/vs-2008-multi-targeting-support.aspx" rel="nofollow">http://weblogs.asp.net/scottgu/archive/2007/06/20/vs-2008-multi-targeting-support.aspx</a></p> <p>You might be able to ditch 2005 now...</p> <p>I still use 2.0 projects in VS 2008 on a weekly basis and it works perfectly.</p>
How to show all ASP.NET web application's loaded/referenced assemblies with version numbers? <p>I'd like to show a list of all used assemblies on a dedicated web page inside a ASP.NET web application for debugging and maintainance purposes (there are many instances of this web application on many different servers). The assemblies could be called from the <em>bin folder</em> or from the <em>GAC</em>. There are some written by myself, but also third-party assemblies.</p> <p>Is there a simple, automated way to get a <strong>list of all loaded or referenced assemblies</strong> of the web application including the <strong>version number</strong> (calling <code>System.Reflection.Assembly</code> - <code>GetName().Version</code> ...)? Do I have to explicitly pass all assembly names for version check or could I retrieve them automatically? Do I have to use Reflection for a comprehensive list of dependencies/references?</p>
<p>I think you can use AppDomain.CurrentDomain.GetAssemblies() for this, e.g something like this:</p> <pre><code>foreach (System.Reflection.Assembly a in AppDomain.CurrentDomain.GetAssemblies()) { Response.Write(a.FullName + "&lt;br/&gt;"); } </code></pre>
Debugging issues <p>I have a certain application in MSVC6.0 all C code. I have it as two workspaces :</p> <p>1.) First workspace creates a static library file, *.lib after compiling the source.</p> <p>2.)Second workspace has a test application(main()) and links the previously generated *.lib library and creates and exe. </p> <p>When i try to single step the test application, i am not able to do so. It keeps asking for a file crt0.c and even after pointing it to that file, i am not able to step in my main function at all, it exits without even entering my main.</p> <p>[The same setup works if i just exectute Ctrl-F5. It works fine with correct output, so no issues in execution]</p> <p>But i need to debug/single-step.</p> <p>So i did one thing to verify.</p> <p>Created one new workspace in MSVC6.0 (Win32 console application without generating this library et al. A single workspace generating an exe. In this new setup, i am able to debug through the main().</p> <p>1.) Any pointers what is happening? Why am i not able to debug in my library-executable setup?</p> <p>2.) How can i do the debugging in that setup? Any project settings i am missing on?</p> <p>-AD</p>
<p>Under <strong>Project Settings / C++ / General</strong>, ensure you have debug information enabled, e.g. set to <strong>Program Database</strong>. Under <strong>Project Settings / Link / Debug</strong>, make sure <strong>Debug info</strong> is ticked and <strong>Microsoft format</strong> is selected.</p>
.htaccess URL is being cut at a space (I'm using Codeigniter) <p>I've used the following code to map https://live.example.com on to <a href="http://example.com/api" rel="nofollow">http://example.com/api</a></p> <pre><code>Options +FollowSymLinks RewriteEngine On RewriteCond %{HTTPS} =on RewriteCond %{HTTP_HOST} ^live\.example\.com [NC] RewriteRule (.+)$ "http://example.com/api/$1" [L,P] </code></pre> <p>The following url:</p> <pre><code>https://live.example.com/userlinks/xml/John%20James/MvPjeUTo15/ </code></pre> <p>Is suppose to map onto:</p> <pre><code>http://example.com/api/userlinks/xml/John%20James/MvPjeUTo15/ </code></pre> <p>Instead it maps it to:</p> <pre><code>http://example.com/api/userlinks/xml/John </code></pre> <p>So it seems to cut it at the space. I am using the Codeigniter framework but I am not sure if the problem lies there.</p> <p>Also using <code>%20</code> or just a space in the url bar produces no different results.</p> <p>Anyone any idea and/or solution why this happens?</p> <p>Thank you very much,</p> <p>Ice</p>
<p>I got it fixed:</p> <p>Added to apache2.conf (httpd.conf):</p> <pre><code>RewriteMap escapemap int:escape </code></pre> <p>.htaccess:</p> <pre><code>Options +FollowSymLinks RewriteEngine On RewriteCond %{HTTPS} =on RewriteCond "%{HTTP_HOST}" "^live\.domain\.com" [NC] RewriteRule "(.*)$" "http://domain.com/api/${escapemap:$1}" [L,P] </code></pre> <p><em>source: <a href="http://www.nabble.com/Re%3A-Re-users%40httpd--writeRule%2C--P--and-space-on-URL-p15632475.html" rel="nofollow">http://www.nabble.com/Re%3A-Re-users%40httpd--writeRule%2C--P--and-space-on-URL-p15632475.html</a></em></p>
VS2005 - Automatically requesting checkout of form on open, with "View Designer" <p>I'm trying to integrate our Source Control(SourceAnywhere) with VS and are getting a lot of push back because of this one issue. </p> <p>Almost every time we open some of our Windows forms using 'View Designer' it edits the file (* appears beside file name). Nothing has yet been changed, I've tried comparing the before and after files and they are exactly the same. If we have the solution bound it will check the file out, but even if its not bound it still 'edits' the file. When you try to check the file back in, it doesn't get a new version or anything. </p> <p>I've done some searching and haven't been able to find any way to change this behavior. </p> <p>This is a huge pain point for me as if someone already has the form checked out and someone else tries to open it, they just get told that it can't be checked out, and the form won't open. Or, someone who has no intention to edit the form, will now have the form checked out but hasn't made any changes. </p> <p>Thoughts?</p>
<p>This usually happens when there are controls within the form that have "Dock" set. If the IDE feels it needs to resize the form, then those controls will also be resized, and all of that information needs to get re-written to the source file. In the case where you're editing a form named "Form1" this source file is not Form1.cs, but rather Form1.Designer.cs - try comparing that file with the version from source control.</p> <p>Alternatively, move to a source control system that doesn't use locking by default (for example, Subversion) or disable that feature in SourceAnywhere. This will require users to manage merge conflicts, but allows multiple users to work on a single file at the same time.</p>
Sending Keyboard Macro Commands to Game Windows <p>I wanna do a macro program for a game. But there is a problem with sending keys to only game application (game window). I am using <code>keybd_event</code> API for sending keys to game window. But I only want to send keys to the game window, not to explorer or any opened window while my macro program is running. When I changed windows its still sending keys. I tried to use <code>Interaction.App</code> with <code>Visual Basic.dll</code> reference. But <code>Interaction.App</code> only Focus the game window.</p> <p>I couldn't find anything about my problem. Can anyone help me? Thanx</p>
<p>Are you retrieving the handle of the window all the time, or are you remembering it?</p> <p>If you use the FindWindow() API, you can simply store the Handle and use the SendMessage API to send key/mouse events manually.</p>
Zend_Rest_Client - error on localhost <p>I am using Zend_Rest_Client to connect Zend_Rest_Server, everything seems to be allright, but when I try to get() from the server I recieve this error:</p> <blockquote> <p>Zend_Http_Client_Adapter_Exception: Unable to Connect to tcp://localhost:80. Error #10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. in C:\www\zf_1_72\library\Zend\Http\Client\Adapter\Socket.php on line 148</p> </blockquote> <p>here is code, which I use</p> <pre><code>$client = new Zend_Rest_Client('http://localhost/my_application/api/index/'); $client-&gt;auth($key); $result = $client-&gt;get(); </code></pre> <p>thank's for any advice</p>
<p><a href="http://www.zfforums.com/zend-framework-components-13/web-web-services-22/http_client-raising-error-10060-a-1302.html" rel="nofollow">This thread</a> suggetss the issue may be with the 'localhost' name - try using <code>127.0.0.1</code> instead.</p>
Best Update Method for MySQL DB <p>I have read through the solutions to similar problems, but they all seem to involve scripts and extra tools. I'm hoping my problem simple enough to avoid that.</p> <p>So the user uploads a csv of next week's data. It gets inserted into the DB, no problem.</p> <p>BUT</p> <p>an hour later he gets feedback from everyone, and must make updates accordingly. He updates the csv and goes to upload it to the DB.</p> <p>Right now, the system I'm using checks to see if the data for that week is already there, and if it is, pulls all of that data from the DB, a script finds the differences and sends them out, and after all of this, the data the old data is deleted and replaced with the new data.</p> <p>Obviously, it is a lot easier to just wipe it clean and reenter the data, but not the best method, especially if there are lots of changes or tons of data. But I have to know WHAT changes have been made to send out alerts. But I don't want a transaction log, as the alerts only need to be sent out the one time and after that, the old data is useless.</p> <p>So! </p> <p>Is there a smart way to compare the new data to the already existing data, get only the rows that are changed/deleted/added, and make those changes? Right now it seems like I could do an update, but then I won't get any response on what has changed...</p> <p>Thanks!</p> <p>Quick Edit:</p> <p>No foreign keys are currently in use. This will soon change, but it shouldn't make a difference, because the foreign keys will only point to who the data effects and thus won't need to be changed. As far as primary keys go, that does present a bit of a dilemma:</p> <p>The data in question is everyone's work schedule. So it would be nice (for specific applications of this schedule beyond simple output) for each shift to have a key. But the problem is, let's say that user1 was late on Monday. The tardiness is recorded in a separate table and is tied to the shift using the shift key. But if on Tuesday there is some need to make some changes to the week already in progress, my fear is that it will become too difficult to insure that all entries in the DB that have already happened (and thus may have associations that shouldn't be broken) will get re-keyed in the process. Unfortunately, it is not as simple as only updating all events occurring AFTER the current time, as this would add work (and thus make it less marketable) to the people who do the uploading. Basically, they make the schedule on one program, export it to a CSV, and then upload it on a web page for all of the webapps that need that data. So it is simply much easier for them (and less stressful for everyone involved) to do the same routine every time of exporting the entire week and uploading it.</p> <p>So my biggest concern is to make the upload script as smart as possible on both ends. It doesn't get bloated trying to find the changes, it can find the changes no matter the input AND none of the data that is unchanged risks getting re-keyed.</p> <p>Here's a related question:</p> <pre><code>Suppose Joe User was schedule to wash dishes from 7:00 PM to 8:00 PM, but the new data has him working 6:45 PM to 8:30 PM. Has the shift been changed? Or has the old one been deleted and a new one added? </code></pre> <p>And another one:</p> <pre><code>Say Jane was schedule to work 1:00 PM to 3:00 PM, but now everyone has a mandatory staff meeting at 2:00 to 3:00. Has she lost one shift and gained two? Or has one shift changed and she gained one? </code></pre> <p>I'm really interested in knowing how this kind of data is typically handled/approached, more than specific answers to the above.</p> <p>Again, thank you.</p>
<p>If you have a unique key on one of the fields, you can use:</p> <pre><code>LOAD DATA LOCAL INFILE '/path/to/data.csv' REPLACE INTO TABLE table_name </code></pre>
Calling a const function from a non-const object <p>I need to call a const function from a non-const object. See example</p> <pre><code>struct IProcess { virtual bool doSomeWork() const = 0L; }; class Foo : public IProcess { virtual bool doSomeWork() const { ... } }; class Bar { public: const IProcess&amp; getProcess() const {return ...;} IProcess&amp; getProcess() {return ...;} void doOtherWork { getProcess().doSomeWork(); } }; </code></pre> <p>Calling </p> <pre><code>getProcess().doSomeWork(); </code></pre> <p>will always results in a call to</p> <pre><code>IProcess&amp; getProcess() </code></pre> <p>Is there another way to call</p> <pre><code>const IProcess&amp; getProcess() const </code></pre> <p>from a non constant member function? I have so far used</p> <pre><code>const_cast&lt;const Bar*&gt;(this)-&gt;getProcess().doSomeWork(); </code></pre> <p>which does the trick but seems overly complicated.</p> <p><hr></p> <p>Edit: I should mention that code is being refactored and eventually only one function will remain.</p> <pre><code>const IProcess&amp; getProcess() const </code></pre> <p>However, currently there is a side effect and the const call may return a different instance of IProcess some of the time.</p> <p>Please keep on topic.</p>
<p><code>const_cast</code> is for casting <strong>away</strong> constness! </p> <p>You're casting from non-const to const which is safe, so use <code>static_cast</code>:</p> <pre><code> static_cast&lt;const Bar*&gt;(this)-&gt;getProcess().doSomeWork(); </code></pre> <p><em>I mean techincally speaking you can cast in constness with <code>const_cast</code>, but it's not a pragmatic use of the operator. The purpose of new style casts (versus the old c-style cast), is to communicate the intent of the cast. <code>const_cast</code> is a code smell, and it's use should be reviewed at least. <code>static_cast</code> on the other hand is safe. But it's a matter of C++ style.</em> </p> <p>Or you can create a new (private) const method, and call that from <code>doOtherWork</code>:</p> <pre><code> void doSomeWorkOnProcess() const { getProcess().doSomeWork(); } </code></pre> <p>Using a const temporary is also an option (answer by "MSN"):</p> <pre><code> const Bar* _this = this; _this-&gt;getProcess().doSomeWork(); </code></pre>
Pros and cons of using DB id in the URL? <p>For example: <code>http://stackoverflow.com/questions/396164/exposing-database-ids-security-risk</code> and <code>http://stackoverflow.com/questions/396164/blah-blah</code> loads the same question.</p> <p>(I guess this is DB id of Questions table? Is this standard in ASP.NET?)</p> <p>What are the pros and cons of using this type of scheme in your web app?</p>
<p>Well, for one, simple id's are usually sequential, so it's quite easy to guess at and retrieve other data from your application.</p> <p><a href="http://stackoverflow.com/questions/395857/doesnt-matter-what-I-type-here">http://stackoverflow.com/questions/395857/doesnt-matter-what-I-type-here</a> <a href="http://stackoverflow.com/questions/395858/doesnt-matter-what-I-type-here">http://stackoverflow.com/questions/395858/doesnt-matter-what-I-type-here</a></p> <p>Now, having said that, that might also be seen as a bonus, because nobody in their right mind would make their whole security hinge on the fact that you have to clink on a link to get to your <em>secure data</em>, and thus easy discoverability of the data might be good.</p> <p>However, one point is that you're at some point going to reindex your database, having something that makes the old url's invalid would be bad, if for no other reason that search engines would still have old links.</p> <p>Also, here on SO it's quite normal to use links like this to other questions, so if they at some point want to reindex and thus renumber things (or move to guid's), they will still have to keep the old structure and id's.</p> <p>Now, is this likely to ever happen or be needed? Probably no.</p> <p>I wouldn't worry too much about it, just build your security as though every entrypoint to your application is known and there should be no problems.</p>
Calling a C# method, and make it take 10 seconds to return <p>From a web service (WCF), I want an endpoint to take 10 seconds to finish.</p> <p>Is there a way I can do a <code>thread.sleep(10);</code> on the method?</p>
<p>You could create a wrapper method which does the appropriate sleep.</p> <pre><code>Thread.Sleep(TimeSpan.FromSeconds(10)) </code></pre>
Binding a object with a sub objects as properties to a datagrid <p>I am working with an object which has sub objects within (see example below). I am attempting to bind a <code>List&lt;rootClass&gt;</code> to the datagrid. When I bind the <code>List&lt;&gt;</code>, in the cell that contains the <code>subObject</code>, I see the following value <code>... "namespace.subObject" ...</code> the string values display correctly.</p> <p>Ideally I would like to see the “Description” property of the <code>subObject</code> in the datacell. How can I map the <code>subObject.Description</code> to show in the datacell?</p> <pre><code>public class subObject { int id; string description; public string Description { get { return description; } } } public class rootClass { string value1; subObject value2; string value3; public string Value1 { get { return value1; } } public subObject Value2 { get { return value2; } } public string Value3 { get { return value3; } } } </code></pre>
<p>If I'm not mistaken, it shows the result of calling .ToString() on your subObject, so you can override that to return the contents of Description.</p> <p>Have you tried just binding to Value1.Description? (I'm guessing it doesn't work).</p> <p>I have a class that can be used instead of List when binding, that will handle this, it implements ITypedList, which allows a collection to provide more "properties" for its objects, including calculated properties.</p> <p>If no easy solution crops up, I'll post a link to my repository later when I'm at my home computer.</p> <p><strong>Edit</strong>: Ok, the current version of the files I have are here:</p> <p><a href="http://code.google.com/p/lvknet/source/browse/#svn/trunk/LVK/Collections">http://code.google.com/p/lvknet/source/browse/#svn/trunk/LVK/Collections</a></p> <p>Depending on your browser you will get either a warning or an error message saying something about the certificate. The reason is that the certificate doesn't match the url and I'm too lazy to try to figure out if there is something I can do about it. It's a subversion repository so nothing malicious should be there but the usual guidelines are in effect.</p> <p>You'll need a username and password, both are <strong>guest</strong> in lower-case.</p> <p>The files you want are the ones near the bottom of that list, TypedList*.</p> <p>Unfortunately (for you), I tend to write classes and code in that class library by reusing other bits I have already written, so you'll need to download the first few files and if those doesn't compile, either try taking something out or grab a few more files. There are namespaces and such further up the hierarchy if you need them.</p> <p>To use:</p> <pre><code>List&lt;rootClass&gt; yourList = ... TypedListWrapper&lt;rootClass&gt; bindableList = new TypedListWrapper&lt;rootClass&gt;(yourList); bindableList.BindableProperties = "Value1;Value2.Description;Value3.Description"; gridView1.DataSource = bindableList; </code></pre> <p>Basically you bind to an instance of <code>TypedList&lt;T&gt;</code> instead of <code>List&lt;T&gt;</code>, and adjust the BindableProperties property. I have some changes in the work, including one that just builds up BindableProperties automatically as it goes, but it isn't in the trunk yet.</p> <p>You can also add calculated properties, like this:</p> <pre><code>yourList.AddCalculatedProperty&lt;Int32&gt;("DescriptionLength", delegate(rootClass rc) { return rc.Value2.Description.Length; }); </code></pre> <p>or with .NET 3.5:</p> <pre><code>yourList.AddCalculatedProperty&lt;Int32&gt;("DescriptionLength", rc =&gt; rc.Value2.Description.Length); </code></pre>
Problem with encoding after in/out of a database <p>I'm doing a bookmarking-system. But when I insert the fetched title "Chapter 4. Examples for advanced use of VLC's stream output (transcoding, multiple streaming, etc...)", it looks perfectly good in the database, but when I print it out again on the display-page, it looks like this: </p> <p><code>Chapter�4.� Examples for advanced use of VLC's stream output (transcoding, multiple streaming, etc...)</code></p> <p>Why is this happening and how do I fix it?</p> <p>The whole system is running on utf-8.</p> <p>Thanks in advance! =)</p>
<p>There is most likely a layer of your application not using utf-8. Try to isolate the problem by inserting known extended characters (e.g.‘’—) into the database and into your application code and see how they are displayed.</p>
Custom properties in XAML of System.Windows.Window <p>I've got a very simple WPF UserControl that looks like this:</p> <pre><code>namespace WpfControlLibrary1 { public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); Composite = new Composite(); Composite.Color = Colors.Red; } protected override void OnRender(DrawingContext drawingContext) { Draw(drawingContext, new Rect(RenderSize)); } public void Draw(DrawingContext g, Rect rect) { Composite.Draw(g, rect); } public Composite Composite { get; set; } } public class Composite { public void Draw(DrawingContext g, Rect rect) { g.DrawRectangle(new SolidColorBrush(Color), new Pen(Brushes.Black, 1.0), rect); } public Color Color { get; set; } } } </code></pre> <p>However, when I try to do this in the XAML of the Window in which the UserControl is sitting:</p> <pre><code>&lt;Window x:Class="WpfApplication1.Window2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:test="clr-namespace:WpfControlLibrary1;assembly=WpfControlLibrary1" Title="Window2" Height="500" Width="700"&gt; &lt;test:UserControl1 Name="uControl1" Composite.Color="Blue"&gt; &lt;/test:UserControl1&gt; &lt;/Window&gt; </code></pre> <p>I get the following errors:</p> <pre><code>Error 1 The attachable property 'Color' was not found in type 'Composite'. Error 2 The property 'Composite.Color' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'. </code></pre> <p>There must be simple way to get the above to work, but I'm afraid I haven't been able to find any relevant info on the subject. Can anybody please give me a pointer or two?</p> <p>Many thanks!</p>
<p>The syntax <code>Type.Property</code> is used to set <a href="http://msdn.microsoft.com/en-us/library/ms749011.aspx" rel="nofollow">attached properties</a>. Try this instead:</p> <pre><code>&lt;test:UserControl1 Name="whatever"&gt; &lt;test:UserControl1.Composite&gt; &lt;test:Composite Color="Blue"/&gt; &lt;/test:UserControl1.Composite&gt; &lt;/test:UserControl1&gt; </code></pre>
Strange SQL2005 problem. "SqlConnection does not support parallel transactions" <p>I have a problem that seems like its a result of a deadlock-situation. Whe are now searching for the root of the problem but meantime we wanted to restart the server and get the customer going.</p> <p>And now everytime we start the program it just says "SqlConnection does not support parallel transactions". We have not changed anything in the program, its compiled and on the customers server, but after the "possible deadlock"-situation it want go online again.</p> <p>We have 7 clients (computers) running the program, each client is talking to a webservice on a local server, and the webservice is talking to the sql-server (same machine as webserver). </p> <p>We have restarted both the sql-server and the iis-server, but not rebooted the server because of other important services running on the server so its the last thing we do. We can se no locks or anything in the management tab. </p> <p>So my question is, why does the "SqlConnection does not support parallel transactions" error comming from one time to another without changing anything in the program and it still lives between sql-restart.</p> <p>It seems like it happens at the first db-request the program does when it start.</p> <p>If you need more information just ask. Im puzzled...</p> <p><strong>More information:</strong> I dont think I have "long" running transactions. The scenario is often that I have a dataset with 20-100 rows (ContractRows) in that Ill do a .Update on the tableAdapter. I also loop throug those 20-100 rows and for some of them Ill create ad-hook-sql-querys (for example if a rented product is marked as returned I create a sql-query to mark the product as returned in the database)</p> <p>So I do this very simplified:</p> <pre><code>Create objTransactionObject Create objtableadapter (objTransactionObject) for each row in contractDS.contractrows if row.isreturned then strSQL &amp;= "update product set instock=1 where prodid=" &amp; row.productid &amp; vbcrlf End if next objtableadapter.update(contractDS) objData.ExecuteQuery(strSQL, objTransactionObject) if succsesfull objtransactionobject.commit else objtransactionobject.rollback end if objTran.Dispose() </code></pre> <p>And then Im doing commit or rollback depending on if It went well or not.</p> <p>Edit: None of the answers have solved the problem, but I'll thank you for the good trouble shooting pointers.</p> <p>The "SqlConnection does not support parallel transactions" dissapeared suddenly and now the sql-server just "goes down" 4-5 times a day, I guess its a deadlock that does that but I have not the right knowledge to find out and are short on sql-experts who can monitor this for me at the moment. I just restart the sql-server and everything works again. 1 of 10 times I also have to restart the computer. Its really bugging me (and my customers of course).</p> <p>Anyone knowing a person with <strong>good</strong> knowledge in analyzing troubles with deadlocks or other sql problems in sweden (or everywhere in the world,english speaking) are free to contact me. I know this is'nt a contact site but I take my chanse to ask the question because I have run out of options, I have spent 3 days and nights optimizing the clients to be sure we close connections and dont do too much stupid things there. Without luck.</p>
<p>It seems to be that you are sharing connections and creating new transactions on the same open connection (this is the parallel part of the exception you are seeing).</p> <p>Your example seems to support this as you have no mention of how you acquire the connection in it.</p> <p>You should do a review of your code and make sure that you are only opening a connection and then disposing of it when you are done (and by all means, use the using statement to make sure that you close the connection), as it seems like you are leaving one open somewhere.</p>
How best to use XPath with very large XML files in .NET? <p>I need to do some processing on fairly large XML files ( large here being potentially upwards of a gigabyte ) in C# including performing some complex xpath queries. The problem I have is that the standard way I would normally do this through the System.XML libraries likes to load the whole file into memory before it does anything with it, which can cause memory problems with files of this size.</p> <p>I don't need to be updating the files at all just reading them and querying the data contained in them. Some of the XPath queries are quite involved and go across several levels of parent-child type relationship - I'm not sure whether this will affect the ability to use a stream reader rather than loading the data into memory as a block.</p> <p>One way I can see of making it work is to perform the simple analysis using a stream-based approach and perhaps wrapping the XPath statements into XSLT transformations that I could run across the files afterward, although it seems a little convoluted.</p> <p>Alternately I know that there are some elements that the XPath queries will not run across, so I guess I could break the document up into a series of smaller fragments based on it's original tree structure, which could perhaps be small enough to process in memory without causing too much havoc.</p> <p>I've tried to explain my objective here so if I'm barking up totally the wrong tree in terms of general approach I'm sure you folks can set me right...</p>
<p>XPathReader is the answer. It isn't part of the C# runtime, but it is available for download from Microsoft. Here is an <a href="http://msdn.microsoft.com/en-us/library/ms950778.aspx" rel="nofollow">MSDN article</a>. </p> <p>If you construct an XPathReader with an XmlTextReader you get the efficiency of a streaming read with the convenience of XPath expressions.</p> <p>I haven't used it on gigabyte sized files, but I have used it on files that are tens of megabytes, which is usually enough to slow down DOM based solutions.</p> <p>Quoting from the below: "The XPathReader provides the ability to perform XPath over XML documents in a streaming manner". </p> <p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=DB0C5FAE-111D-4B24-B10C-E4CDB13705DA&amp;displaylang=en" rel="nofollow">Download from Microsoft</a></p>
ASP.NET: Function key shortcuts? <p>I recently participated a project that replaced a mainframe system with a web (asp.net 2.0, VS2005) system.<br/> The 3270-terminals are still much used and I respect the IMS/CICS/Cobol application designers for their work.<br/></p> <p>Users like the web application, but one thing they keep ask for is:<br/> Functionkeys and shortcuts that navigates directly to different web forms.</p> <p>Do you know a way to implement function key shortcuts in asp.net that will be like 3270 function key actions?</p> <p>We are using asp:menu as a content in master-page, but asp:item does not support the accesskey attribute:</p> <pre><code>&lt;asp:SiteMapDataSource ID="_siteMapDataSource" runat="server" ShowStartingNode="False" /&gt; &lt;asp:Menu ID="Menu1" runat="server" DataSourceID="_siteMapDataSource" Orientation="Horizontal"&gt; &lt;/asp:Menu&gt; </code></pre> <p>Update: 24.jan 09: I liked @John Sheehan answer. Will implement it with the jQuery support in ASP.Net 3.5 SP1</p>
<p>There is nothing specific to ASP.NET for this since you would need to handle it with JavaScript. The easiest way would be to use a jQuery plugin like <a href="http://jshotkeys.googlepages.com/" rel="nofollow">js-hotkeys</a></p>
What is the benefit of tableless design if you need clearing blocks everywhere? <p>I understand that the goal of moving towards <code>&lt;div&gt;</code> tags from <code>&lt;table&gt;</code> makes sense since it is more semantic. However, I don't understand the benefit gained if you still need a clearing block to make column-based layouts work. For example:</p> <pre><code>&lt;!-- Note: location-info &amp; personal-info both float left. --&gt; &lt;div class="contact"&gt; &lt;div class="personal-info"&gt; &lt;p&gt; Shawn, etc, etc &lt;/p&gt; &lt;/div&gt; &lt;div class="location-info"&gt; &lt;p&gt;&lt;address&gt;etc&lt;/address&gt;&lt;/p&gt; &lt;/div&gt; &lt;br style="clear:both" /&gt; &lt;!-- clearing block --&gt; &lt;/div&gt; </code></pre> <p>The extraneous <code>&lt;br&gt;</code> tag is used strictly to describe style, and is required to make the layout work. Doesn't this ruin all benefits gained from removing tables?</p>
<p>What if I told you <a href="http://www.sitepoint.com/simple-clearing-of-floats/" rel="nofollow">you</a> <a href="http://www.innovatingtomorrow.net/2008/03/24/how-clear-floats-css" rel="nofollow">didn't</a> <a href="http://www.positioniseverything.net/easyclearing.html" rel="nofollow">need</a> a clearing block?</p> <pre><code>.clear-block:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .clear-block { display: inline-block; } &lt;div id="wrapper" class="clear-block"&gt; &lt;div style="float:right"&gt; Your content here &lt;/div&gt; &lt;div style="float:left"&gt; More content here &lt;/div&gt; &lt;/div&gt; </code></pre> <p><a href="https://jsfiddle.net/v3vnbz4p/" rel="nofollow">JSFiddle</a></p>
Adding Date Picker to view programatically? <p>Can someone illustrate (or point me to a good tutorial) on how to add a Date Picker to a view programatically (i.e., without using the interface editor)? </p>
<p>It's very easy man.You can do it in seconds.</p> <p>Just use the these methods in your.m file...all is ready</p> <pre><code>- (void)viewDidLoad { CGRect pickerFrame = CGRectMake(0,250,0,0); UIDatePicker *myPicker = [[UIDatePicker alloc] initWithFrame:pickerFrame]; [myPicker addTarget:self action:@selector(pickerChanged:) forControlEvents:UIControlEventValueChanged]; [self.view addSubview:myPicker]; [myPicker release]; } - (void)pickerChanged:(id)sender { NSLog(@"value: %@",[sender date]); } </code></pre>
Javascript and Translations <p>I have a PHP application that makes extensive use of Javascript on the client side. I have a simple system on the PHP side for providing translators an easy way to provide new languages. But there are cases where javascript needs to display language elements to the user (maybe an OK or cancel button or "loading" or something). </p> <p>With PHP, I just have a text file that is cached on the server side which contains phrase codes on one side and their translation on the other. A translator just needs to replace the english with their own language and send me the translated version which I integrate into the application.</p> <p>I want something similar on the client side. It occurred to me to have a javascript include that is just a set of translated constants but then every page load is downloading a potentially large file most of which is unnecessary.</p> <p>Has anyone had to deal with this? If so, what was your solution?</p> <p><strong>EDIT</strong>: To be clear, I'm not referring to "on-the-fly" translations here. The translations have already been prepared and are ready to go, I just need them to be made available to the client in an efficient way.</p>
<p>How about feeding the javascript from php? So instead of heaving:</p> <pre><code> &lt;script type='text/javascript' src='jsscript.js'&gt;&lt;/script&gt; </code></pre> <p>do</p> <pre><code> &lt;script type='text/javascript' src='jsscript.php'&gt;&lt;/script&gt; </code></pre> <p>And then in the php file replace all outputted text with their associated constants.</p> <p>Be sure to output the correct caching headers from within PHP code.</p> <p><b>EDIT</b></p> <p>These are the headers that I use:</p> <pre><code>header('Content-type: text/javascript'); header('Cache-Control: public'); header('expires: '. date("r", time() + ( 7 * 24 * 60 * 60 ) ) ); // 1 week header("Pragma: public"); </code></pre>
How to convert between Progress Database Character[] datatype and C# strings? <p>Progress databases allow for a Character[x] datatype. How can I write to a particular x using C# and ODBC?</p> <p>Please do not answer unless you understand the what Character[x] means... it is not a string (array of chars), it is an array of strings (which are arrays of chars).</p>
<p>I figured it out. The documentation I have refers to a datatype of character[20], format x(24). character[x] (where x is a number), is like an array of strings. Format x(24) means each string in the array can be 24 characters long. </p> <p>Essentially characters[20], format x(24) is a string that is 20 * 24 characters long with each "array element" separated with a semi-colon (;). </p> <p>If column "options" is defined as character[20], x(24) then to populate it with strings from 1 to 20, one would merely write:</p> <p>row.options = "1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20";</p> <p>To populate it with all empty strings write:</p> <p>row.options = ";;;;;;;;;;;;;;;;;;;";</p>
Stop LINQ to SQL from executing select statements after insert <p>I'm using LINQ to SQL to update my database. I'm inserting a lot of records, and when I call SubmitChanges(), LINQ to SQL executes an insert and a select statement for each object. I don't really care to update my objects after they are inserted into the database.</p> <p>Do you know I can prevent LINQ to SQL from issuing the select statements after the insert statements? This should make my app much faster.</p>
<p>You're looking for <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.autosync.aspx" rel="nofollow">ColumnAttribute.AutoSync</a>. If you're using the designer, check each column for an Auto-Sync property and set it to Never.</p> <p><strong>Edit:</strong> Ok, that didn't work for you. Brace yourself for some mapping hackery!</p> <p>When I Insert with some autogenerated primary key column, I get this SQL:</p> <pre><code>INSERT INTO [dbo].[TableName]( fieldlist ) VALUES (@p0, @p1, @p2, @p3, @p4) SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value] </code></pre> <p>As I understand your request, you don't want that SELECT</p> <p>Attempt 1: I went to the primary key field and set auto-generated to false. This caused a Sql Exception "Cannot insert explicit value for identity column in table 'TableName' when IDENTITY_INSERT is set to OFF." In other words, linq specified a value for that column.</p> <p>Attempt 2: I deleted the autogenerated columns from the designer. This caused Linq to give me an Invalid Operation Exception: "Can't perform Create, Update or Delete operations on 'Table(TableName)' because it has no primary key."</p> <p>Attempt 3: I deleted the autogenerated columns from the designer, then I marked another column as primary key. Even though this column is not a primary key in the database, LINQ's DataContext will use it to track row identity. It must be unique for observed records of a given DataContext.</p> <p>This third attempt generated the following SQL (which is what you ask for)</p> <pre><code>INSERT INTO [dbo].[TableName]( fieldlist ) VALUES (@p0, @p1, @p2, @p3, @p4) </code></pre>
Mapping individual buttons on ASP.NET MVC View to controller actions <p>I have an application where I need the user to be able to update or delete rows of data from the database. The rows are displayed to the user using a foreach loop in the .aspx file of my view. Each row will have two text fields (txtName, txtDesc), an update button, and a delete button. What I'm not sure of, is how do I have the update button send the message to the controller for which row to update? I can see a couple way of doing this:</p> <ol> <li>Put each row within it's own form tag, then when the update button is clicked, it will submit the values for that row only (there will also be a hidden field with the rowId) and the controller class would take all the post values as parameters to the Update method on the controller.</li> <li>Somehow, have the button be scripted in a way to send back only the values for that row with a POST to the controller.</li> </ol> <p>Is there a way of doing this? One thing I am concerned about is if each row has different names for it's controls assigned by ASP.NET (txtName1, txtDesc1, txtName2, txtDesc2), then how will their values get mapped to the correct parameters of the Controller method?</p>
<p>You can use multiple forms, and set the action on the form to be like this:</p> <pre><code>&lt;form method="post" action="/YourController/YourAction/&lt;%=rowId%&gt;"&gt; </code></pre> <p>So you will have <code>YourController/YourAction/1</code>, <code>YourController/YourAction/2</code> and so on. </p> <p>There is no need to give different names to the different textboxes, just call them txtName, txtDesc etc (or even better, get rid of those txt prefixes). Since they are in different forms, they won't mix up.</p> <p>Then on the action you do something like</p> <pre><code>public ActionResult YourAction(int id, string username, string description) </code></pre> <p>Where username, description are the same names that you used on the form controls (so they are mapped automatically). The id parameter will be automatically mapped to the number you put on the form action.</p>
Is there an XSLT buddy available somewhere? <p>I think a lot of people know about tools like RegexBuddy. Is there something similar for XSLT?</p>
<p><em>XSLT IDEs</em> (Interactive Development Environments):</p> <ul> <li><strong><a href="http://sourceforge.net/projects/xselerator">XSelerator</a></strong> (the one I've been using for 6-7 years). Free, has a Debugger for MSXML, has intellisense for both XSLT 1.0 and XSLT 2.0. In addition has some dynamic intellisense. The debugger has breakpoints, data breakpoints,visualizes temporary trees, variables, test conditions, current output, ..., etc.</li> <li><strong><a href="http://www.microsoft.com/visualstudio/default.mspx">VS2008</a></strong> -- a good XML Editor + XSLT Debugger. Good static intellisence. Match patterns are statically checked. Breakpoints, data breakpoints, visualization of variables and the current output.</li> <li><strong><a href="http://www.oxygenxml.com/">oXygen</a></strong></li> <li><strong><a href="http://www.altova.com/products/xmlspy/xml_editor.html">XML-SPY</a> (Altova)</strong></li> <li><strong><a href="http://www.stylusstudio.com/">Stylus Studio</a></strong></li> </ul> <p><em>XPath tools</em>:</p> <ul> <li><strong>The <a href="http://www.huttar.net/dimitre/XPV-Zip-2008.zip">XPath Visualizer</a></strong> -- A <a href="http://www.huttar.net/dimitre/XPV/TopXML-XPV.html"><strong>popular tool for learning XPath</strong></a> by playing with XPath expressions. Free and open source. Allows any XPath expression to be evaluated against a given XML document and displayes the results hi-lighted in the xml document (if they are node(s)) or in a separate box (if the results are atomic values). Allows xsl:variable-s to be defined and then used in XPath expressions. Allows xsl:key-s to be defined and then referenced by key() functions within XPath expressions.</li> </ul> <p><strong>EDIT</strong>: The XPath Visualizer now has a <strong><a href="http://www.huttar.net/dimitre/XPV/TopXML-XPV.html">new, safer home</a></strong>, due to the kindness of Lars Huttar.</p>
ASP.NET/C# - Custom PerformanceCounters only show up in 32-bit perfmon on 64-bit system <p>I'm trying to create a set of custom performance counters to be used by my ASP.NET application. I use the following code to increment the counters:</p> <pre><code>internal static void Increment(String instanceName, DistributedCacheCounterInstanceType counterInstanceType) { var permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Write, Environment.MachineName, "CounterName"); permission.Assert(); var counter = new PerformanceCounter("CategoryName", "CounterName", instanceName, false); counter.RawValue++; // Use RawValue++ instead of Increment() to avoid locking counter.Close(); } </code></pre> <p>This works perfectly in unit tests and also in Cassini on my dev box (Vista Business x64)., and I can watch the counters working in Performance Monitor. However, the counters don't seem to register any incrementation in my production environment (Win Server 2003 x64). The counter instances themselves are available, but they all just show "--" for the last/average/minimum/maximum display.</p> <p>Any ideas as to what I could be doing wrong?</p> <p><strong>EDIT:</strong> Here's <a href="http://msdn.microsoft.com/en-us/library/ms979204.aspx#scalenethowto12_topic5" rel="nofollow">a [perhaps somewhat outdated] MSDN article that I used for reference</a></p> <p><strong>EDIT 2:</strong> I'm using VS 2008/.NET Framework v3.5 SP1, if that makes any difference.</p> <p><strong>EDIT 3:</strong> Just found <a href="http://www.improve.dk/blog/2008/04/01/missing-asp-net-performance-counter-values" rel="nofollow">this article about 32 bit/64 bit app and monitor mismatching</a>, but I'm not sure how it applies to my situation, if at all. Cassini is indeed a 32-bit app, but I had no problem viewing the values on my 64-bit system. On my production server, both the app and the system are 64-bit, but I can't see the values.</p> <p><strong>EDIT 4:</strong> The values <em>are</em> showing up when I run the 32-bit perfmon on the production server. So I suppose now the question is why can't I read the values in the 64-bit perfmon?</p> <p><strong>EDIT 5:</strong> It actually does appear to be working, it was just that I had to restart my instance of perfmon because it was open before the counters were created.</p>
<p>I read that instantiating a PerformanceCounter is quite resource intensive. Have you thought of caching these in a Session / Application variable?</p> <p>Also, is it wise to update the counter without locking in a multithreaded ASP.net application?</p> <p>Patrick</p>
When to use a Float <p>Years ago I learned the hard way about precision problems with floats so I quit using them. However, I still run into code using floats and it make me cringe because I know some of the calculations will be inaccurate.</p> <p>So, when is it appropriate to use a float?</p> <p><strong>EDIT:</strong> As info, I don't think that I've come across a program where the accuracy of a number isn't important. But I would be interested in hearing examples.</p>
<p>Short answer: You only have to use a <strong>float</strong> when you know exactly what you're doing and why.</p> <p>Long answer: <strong>floats</strong> (as opposed to <strong>doubles</strong>) aren't really used anymore outside 3D APIs as far as I know. Floats and doubles have the same performance characteristics on modern CPUs, doubles are somewhat bigger and that's all. If in doubt, just use double.</p> <p>Oh yes, and use <strong>decimal</strong> for financial calculations, of course.</p>
Reference counting in PHP <p>I'd like to implement database caching functionality in PHP based on reference counts. For example, code to access the record in table <strong>foo</strong> with an ID of 1 might look like:</p> <pre><code>$fooRecord = $fooTable-&gt;getRecord(1); </code></pre> <p>The first time this is called, $fooTable fetches the appropriate record from the database, stores it in an internal cache, and returns it. Any subsequent calls to getRecord(1) will return another reference to the same object in memory. $fooRecord signals $fooTable when it destructs, and if there are no remaining references, it stores any changes back to the database and removes it from the cache.</p> <p>The problem is that PHP's memory management abstracts away the details about reference counts. I've searched PECL and Google for an extension to do so, but found no results. So question #1 is: does such an extension exist?</p> <p>In an alternative approach, $fooTable returns a super-sneaky fake object. It pretends to be the record by forwarding __call(), __set(), and __get(), and its constructor and destructor provide the appropriate hooks for reference counting purposes. Tests, works great, except that it breaks type-hinting. All my methods that were expecting a FooRecord object now get a Sneaky object, or maybe a FooSneaky if I feel like creating an empty subclass of Sneaky for <em>every one of my tables</em>, which I do not. Also, I'm afraid it will confuse maintenance programmers (such as myself).</p> <p>Question #2: Is there another approach I've missed?</p>
<p>For php5, just make use of the destructor in the record class.</p> <pre><code>class Table { /* [...] */ protected $record_cache = array(); public function getRecord($id) { if(isset($this-&gt;record_cache[$id]) return $this-&gt;record_cache[$id]; $r = $db-&gt;getRecord($id); if($r instanceof Record) { $this-&gt;record_cache[$id] = $r; } return $r; } public function _unregister($id) { unset($this-&gt;record_cache[$id]); } } class Record { /* [...] */ function __destruct() { this-&gt;table-&gt;_unregister($this-&gt;id); } } </code></pre> <p>If you don't want to have a public method for this in Table, you could probably use some callback trick or some other clever hack :)</p>
Check the signature on large data sets efficiently using JCA <p>I have to verify the signature on a file that may be as large as 2Gb, and I want to do so in a way that is as memory-efficient as possible. For various reasons, the file will already be loaded completely into memory, and is accessed using an <code>InputStream</code> by the application. I would like to verify the signature using the stream interface, but the JCA <code>Signature</code> class' <code>update</code> method only accepts <code>byte[]</code> and related classes.</p> <p>How can I do this efficiently? I don't want to load the beast into a second byte array, otherwise we'll be seeing some seriously high memory use, but the interface doesn't seem to support it otherwise.</p> <p><strong>Update</strong></p> <p>If it matters, the signing algorithm is SHA-1</p>
<p>Why not just read the input stream a block (4096bytes or whatever convenient size) at a time, call update() for each block.</p>
Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes? <p>Is there a foreach structure in MATLAB? If so, what happens if the underlying data changes (i.e. if objects are added to the set)?</p>
<p>MATLAB's <strong>FOR</strong> loop is static in nature; you cannot modify the loop variable between iterations, unlike the <strong>for(initialization;condition;increment)</strong> loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.</p> <pre><code>A = 1:5; for i = A A = B; disp(i); end </code></pre> <p>If you want to be able to respond to changes in the data structure during iterations, a <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/brqy1c1-1.html#brqy1c1-9"><strong>WHILE</strong> loop</a> may be more appropriate --- you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish.</p> <p>Btw, the <strong>for-each</strong> loop <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html">in Java</a> (and possibly other languages) produces unspecified behavior when the data structure is modified during iteration. If you need to modify the data structure, you should use an appropriate <strong><a href="http://java.sun.com/javase/6/docs/api/java/util/Iterator.html">Iterator</a></strong> instance which allows the addition and removal of elements in the collection you are iterating. The good news is that MATLAB supports Java objects, so you can do something like this:</p> <pre><code>A = java.util.ArrayList(); A.add(1); A.add(2); A.add(3); A.add(4); A.add(5); itr = A.listIterator(); while itr.hasNext() k = itr.next(); disp(k); % modify data structure while iterating itr.remove(); itr.add(k); end </code></pre>
How do I check out an SVN project into Eclipse as a Java project? <p>I was trying to check out a project from SVN using Eclipse. I tried using "Checkout As" to make it into a "Java project from existing Ant script", but the project wizard requires the file to have already been downloaded. Is there a way to checkout the project into Eclipse as a Java project, without having to download it elsewhere first?</p> <p>(I am using Eclipse Ganymade 3.4.1 with Subversive.)</p>
<p>Here are the steps:</p> <ul> <li>Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: <a href="http://subclipse.tigris.org/install.html">http://subclipse.tigris.org/install.html</a></li> <li>Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.</li> <li>Select your project's root folder and select checkout as a project in the workspace.</li> </ul> <p>It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),</p>
SQL 2005 Query Help <p>I have table with 50 entries (users with such details like Name Surname Location etc)</p> <p>I want to create a query that give me users from row 1 to row 10. Then another query that give me users from 11 to 20 and so on.</p> <p>Is there any way how to do that?</p> <p>Thanks</p>
<p><a href="http://www.singingeels.com/Articles/Pagination_In_SQL_Server_2005.aspx" rel="nofollow">http://www.singingeels.com/Articles/Pagination_In_SQL_Server_2005.aspx</a></p>
Returning from inside the scope of a 'using' statement? <p>I've got some code that looks like this:</p> <pre><code>using (DBDataContext dc = new DBDataContext(ConnectionString)) { Main main = new Main { ClientTime = clientTime }; dc.Mains.InsertOnSubmit(main); dc.SubmitChanges(); return main.ID; } </code></pre> <p>If I return from inside a "using", will the using still clean up?</p>
<p>Yes, and that's one of the big advantages of <code>using</code> it.</p>
How Can I Get the Index of An Item in a ListBox? <p>I am adding items to a <code>ListBox</code> like so:</p> <pre><code>myListBox.Items.addRange(myObjectArray); </code></pre> <p>and I also want to select some of the items I add by the following:</p> <pre><code>foreach(MyObject m in otherListOfMyObjects) { int index = myListBox.Items.IndexOf(m); myListBox.SelectedIndices.Add(index); } </code></pre> <p>however <code>index</code> is always <code>-1</code>.</p> <p>Is there a different way to get the index of an object in a <code>ListBox</code>?</p>
<p>You should make sure that <code>MyObject</code> overrides <code>Equals()</code>, <code>GetHashCode()</code> and <code>ToString()</code> so that the <code>IndexOf()</code> method can find the object properly.</p> <p>Technically, <code>ToString()</code> doesn't need to be overridden for equality testing, but it is useful for debugging.</p>
Microsoft Exception Handling Block - Isn't it a perfect example for overengineering? <p>Ever since Microsoft has introduced the application blocks, I've been bumping into people who use the <a href="http://msdn.microsoft.com/en-us/library/dd203116.aspx">Exception Handling Application Block</a>. I've recently had a closer look myself and would summarize the basic functionality as follows (skip the following block if you already know what it does):</p> <blockquote> <p>The exception handling application block aims to centralize and make fully configurable with config files the following <a href="http://msdn.microsoft.com/en-us/library/dd203198.aspx">key exception handling tasks</a>:</p> <ul> <li>Logging an Exception</li> <li>Replacing an Exception</li> <li>Wrapping an Exception</li> <li>Propagating an Exception</li> <li>etc.</li> </ul> <p>The library does that by having you modify your try catch blocks as follows:</p> <pre><code>try { // Run code. } catch(DataAccessException ex) { bool rethrow = ExceptionPolicy.HandleException(ex, "Data Access Policy"); if (rethrow) { throw; } } </code></pre> <p>Based on what is specified in the app.config for the policy name (<a href="http://msdn.microsoft.com/en-us/library/dd139868.aspx">see here for docs</a>), HandleException will either ...</p> <ul> <li>throw a completely new exception (replace the original exception)</li> <li>wrap the original exception in a new one and throw that</li> <li>swallow the exception (i.e. do nothing)</li> <li>have you rethrow the original exception</li> </ul> <p>Additionally you can also configure it to do more stuff beforehand (e.g. log the exception).</p> </blockquote> <p>Now here's my problem: I completely fail to see how it can be beneficial to make it configurable whether an exception is replaced, wrapped, swallowed or rethrown. In my experience, this decision must be made at the time you write the code because you'll typically have to change the surrounding or calling code when you change the exception handling behavior.</p> <p>For example, your code will likely start to behave incorrectly when you reconfigure such that a particular exception thrown at a particular point is now swallowed instead of rethrown (there might be code after the catch block that must not be executed when the exception occurs). The same goes for all other possible changes in exception handling (e.g. replace -> rethrow, swallow -> wrap).</p> <p>So, to me the bottom line is that the exception handling block solves problems that really don't exist in practice. The exception logging and notifying bit is fine, but isn't all the other stuff just a perfect example for overengineering?</p>
<p>If you use exceptions for control flow, then you would want to stay away from policy-based exception handling.</p> <p>But in the case of exceptions which you want to treat as non-recoverable (a background task failed, the socket was disconnected, the file was deleted, etc.), you may want to have configurable, policy-based exception handling.</p> <p>For example, if you are developing an API, you may want to have every function in your API throw only the standard exceptions (<code>ArgumentException</code>, etc.), as well as your own library-specific exception in the case of an inner non-standard exception (e.g. a <code>MyLibraryException</code>). In this type of case, all that matters is that something did not work correctly. You are not picking apart the exception and figuring out what went wrong. You are simply acknowledging the fact that <em>some</em>thing went wrong, and that you are supposed to do <em>some</em>thing now.</p> <p>That <em>some</em>thing should be configurable, because it doesn't really matter what you do. Display a Message Box to the user? Modal or non-modal? Log the exception? How do you want to log the exception? Call a logging web service? Append to a log file? Write to the Windows Event Log? Insert an entry into the database? Insert an entry into two databases? It doesn't really matter to the rest of your application. The choice of how to handle an exception is completely orthogonal to the rest of the application.</p> <p>(As an aside, this is not how I would approach configurable policy-based exception-handling. I would tends more towards an AOP style, such as registering an exception-logger interceptor in the container.)</p>