Friday, May 6, 2011

How can I estimate a Web site build (refresh) when I don't know all of the site's features?

I know there are several estimating questions here, and I have read through most of them, but this one is slightly different. If you're doing a refresh on a Web site, it might include usability enhancements that increase the hours for page production and development. We'll never look at a Web site and say to ourselves the way it is now is the way it will be in the future. If that were the case, then our clients wouldn't be looking for our expertise. Should it always be a requirement to do a team brainstorm before responding to an RFP or creating a formal statement of work? What if those doing the brainstorming are not doing the final work? We can only inventory the current site to a certain extent, and I'm starting to think we should make estimates only for what we know, letting the potential client tell us where we're missing certain elements.

From stackoverflow
  • When you don't know what your estimating, expect the estimation to be inaccurate (and, at best, approximate).

    State your assumptions ("X if we do Foo or Y if we don't").

    State what you would need to reduce uncertainty ("we need to spend an hour with the client to gather requirements before we can provide any estimate").

  • In your proposal, be fairly specific about what you saw on the current web site (how many pages/resources? are they low/med/high complex? What are the high level features you see already existing (i.e. search, security, AJAX, profiles, etc.) and what would you consider adding? Give ranges, rather than specific estimates.

    The more detail you give about what you saw without knowing the requirements will help the client believe you didn't just shoot the proposal through an RFP chute, and that you're serious about the work, without tying you to a commitment to deliver more/faster than you can. Clients do understand that you can't really make a reliable estimate, but the more they believe you have made a serious attempt, the more they're likely to commit their time to helping you understand the requirements towards making a final proposal and SOW.

What is the easiest way to create a overview 'outline' of the most important sections of an app in VS 2005 (VB.net) ?

I want to code in our VB.net to be a little easier to follow both to improve readability and also make it a lot easier to know the best place to put a new bit of code/feature.

Essentially, I'd like to have a 10,000 foot "outline" of the code" with hyperlinks from the outline to the code.

It needs to be portable, so BookMarks won't do the trick (I think). I'm thinking maybe TODO comments. I'd like to create our own Todo style comment like "Outline" or something but that keyword would need to be in the config file for VS as well (but then it's just one thing to keep sync'd).

So something like:

TODO: 1 : App Starts

TODO: 2 : Read INI settings

TODO: 3: Show Splash screen

TODO: 4: Start Lesson (this is educational software)

TOOO: 5: Start Exercise

TODO: 6: Next Exercise

TODO: 7: End Lesson

TODO: 8: AppExit

Any other ideas?

From stackoverflow
  • Have you checked out the Rock Scroll plugin for Visual Studio. It has several of the features that you are looking for.

    Clay Nichols : The logical, operational "flow" or sequence of the program is going to be different than the linear list of code, so this doesn't give me what I need. But thanks, it looks like a cool tool!
  • It seems like you could get quite far with a Whitehorse diagram (VS 2005 class diagram tool) with good annotations on it. I might even go so far as to suggest a sort-order-influencing name. If it's the only class diagram, a good VS dev will feel the pull to see what it has to tell them about the code model.

    If the code doesn't lend itself to the object model with simple, good annotations describing flow... perhaps it needs to be refactored so that it DOES lend itself to that simple view?

    Clay Nichols : That won't work with our code because: 1. a lot of it isn't in classes 2. The flow order doesn't correspond to any order of the classes (alphabetical, etc.). E.g., you might have Registration.Validate, followed by SplashScreen.Start followed by Lesson.Begin, etc. 3. There's no way to "highlight" the sections of the classes that are most important. I.e. if you only want to see the 10 most relevent sections of the code, there's no way to do that.
    Tetsujin no Oni : Definitely sounds like a target for refactoring. Creating classes that make the interaction clearer is definitely where I would attack this problem. Absent a look at the codebase you're trying to outline, I think that the description of the problems with using a class diagram as documentation of the interactions (perhaps of interfaces declared to provide only the interaction parts you want to outline...) highlight opportunities to improve the design.
  • This may be obvious, sorry if I missed the essesence of what you are asking for, but would something like:

    region "application start"

    . .

    regoin end

    help at all?

    Clay Nichols : If we created a bunch of regions like that ("Start", "Next Exercise", "End Lesson", etc.) is there one window where we'd see a list of only the regions that had been identified?
    MostlyLucid : Sorry, been under a serious crunch on a project (need in production monday AM) -- I did not find a way to do that from within VS - however, this tool seems to show some promise: http://www.syntaxia.com/Syntaxia/HomePage.php --I will look around over the weekend - it is a interesting problem -
    Nick Whaley : Maybe if you made the text bigger.
    MostlyLucid : In case you missed this one: http://www.devexpress.com/Products/Visual_Studio_Add-in/index.xml
  • I was working in some old VB6 Code and thought of this method:

    Create a Sub CodeOutline ( Order as Double, Description as string)

    Then call it at various places in the code:

    CodeOutline 1, "App Starts" CodeOutline 2, "Load Settings" CodeOutline 3, "Start Lession" (this is educational software to it has "lessons and exercises" CodeOutline 4, "Next Exercise" CodeOutline 5, "Lesson Finished"

    Now you can do a couple of things:

    1. In the above Sub you can put a debug statement. (We have a "debug mode" we can put the app in where any debug message will be reported as a msgbox).

    CodeOutline (Order as double, descr as string) SysMsg cstr(Order) & " -" & Descr, Msg_Debug end

    1. You can also put a breakpoint in the CodeOutline

    2. You can search on CodeOutline and get a list (often sorted by the Order paramater if you're using the MzTools's vb6 addin search function (far superior to the built in vb6). And the search results are hyperlinked.

    EXAMPLE OF THE SEARCH RESULTS

    Tutor
       Modules
          COMMON (COMMON.BAS)
             Sub Main()
                CodeOutline 1, "Startup"
                CodeOutline 6, "Checking Registration status"
                CodeOutline 4, "Loading Splash Screen"
             Public Sub CodeOutline(Order As Double, sDescription As String)
                Public Sub CodeOutline(Order As Double, sDescription As String)
                '   do a Search on CodeOutline  to see all the code outlines
                On Error GoTo CodeOutline_Error
                CodeOutline_Error:
                sysMsg "Error " & Err.Number & " (" & Err.Description & ") in procedure CodeOutline of Module COMMON" & ",," & Err.Description, MSG_LOG
          IO (IO.BAS)
             Sub APP_INITIALIZE()
                CodeOutline 2, "Initializine App"
                CodeOutline 3, "Exiting from App_initialize"
       Forms
          frmSplash (SPLASH.FRM)
             Private Sub Command2_Click(index As Integer)
                CodeOutline 4.1, "User Clicked button # " & index & " on Splash screen"
             Private Sub Form_Load()
                CodeOutline 5, "Exiting from frmSplash.Load"
             Private Sub tmrUnload_Timer()
                CodeOutline 6, "Preparing to unload the Splash Form, tmrUnload"
    

SIFR Font tweaking a nightmare!

Hi All,

I've been trying to tweak my SIFR navigation. I'm replacing with Gill (although I've had the same issue with other fonts).

The problem is that no matter what I do with the letter spacing, short words are ok with one setting but not long words and vice versa.

In order to stop any words wrapping I have to set letter spacing to 1px (for example) but this then causes the larger words to have a much bigger movie than they need and as the nav is horizontal this pushes the next item too far over to the right.

Has anyone had the same issue? And if so, did you solve it?

See image here: http://www.glg-group.com/gill.jpg

It's driving me crazy!

Many thanks

Tom Gosling

From stackoverflow
  • Sorry for not directly answering your question, but you may want to try Cufon

    Cufón aims to become a worthy alternative to sIFR, which despite its merits still remains painfully tricky to set up and use.

    Hope it deals with the issue.

    Rex M : Cufón has legal questions which have not yet been resolved.
    ohnoes : Could you provide more information please?
  • If you use sIFR 3 you can add the fitExactly: true parameter for the replacements, this will make the Flash movies exactly wide enough to fit the text.

    (With the caveat that Flash might use incorrect values, but you can use the offsetLeft/offsetTop and tuneWidth/tuneHeight parameters to tune the text position and movie dimensions.)

Does Delphi sometimes revert text form files (DFM) to binary format?

Our Delphi 7 development team stores form files (dfm) in text mode, and uses a source control system (Subversion) to track changes.

Sometimes, we noticed that a form file returned to binary format between revisions, causing diff tools like TortoiseMerge to complain.

Using the Subversion change log, I can see that the DFM file was stored in text form before. The software developers never change the storage file format back to binary manually.

Have you encountered the same? Is it a known problem?

From stackoverflow
  • If someone has opened the project with different version of Delphi (or changed the default settings), he may save the forms in different format.

    mjustin : Good hint, I will check this. We have also Delphi 2007 and 2009 installed. The default settings are only for new forms, so I am not sure how they can affect existing forms.
  • No, I've never seen (or heard of) this happening on it's own before. We have hundreds of .DFMs in a couple of dozen apps, and this has only happened when some idiot accidentally right-clicks on a form and unchecks 'Text DFM' on the context menu.

    mjustin : Maybe it was the infamous 'right click and uncheck text dfm' virus? ;)
    Ken White : Nah... Our AV software would have caught that. It was an idiot.
    mjustin : Is it Delphi 7?
    Ken White : We have a mix of Delphi 7 and 2007 (I'm the only one who's moved fully to 2009).
  • I have seen it happen in Delphi 7 when a form inheriting from another form from a different project was opened in Delphi on its own without the project it belongs to being open.

  • We've certainly encountered this. We use D7 exclusively.

    Never got to the bottom of it as it happens only half a dozen times a year or so, and although it's a nuisance it's fairly easily remedied.

    I was interested to see Lars's answer, and will certainly look to see if that's a possible cause next time it happens.

  • You may be interested in investigating the use of Beyond Compare instead of TortoiseSVN's built-in merge tool. Beyond Compare is written in Delphi, and natively knows how to read binary DFMs. This means that it then becomes less of an issue (or even no issue) whether your DFMs are stored in Subversion in binary or text. Beyond Compare V3 also does 3-way merging which makes it really easy to merge multiple commits etc. Even ignoring the ability to diff binary DFMs, it's still a much better diff viewer than TortoiseSVN's built-in tools. I can highly recommend it, and it's very inexpensive (I have no connection with Scooter Software, other than being a very happy customer).

    Scooter Software

  • This sometimes happens when the IDE gets confused.

    It usually starts after you got an access violation inside the Delphi 7 IDE.

    Sometimes also one or mor of your Delphi editor buffers inside the IDE become readonly (while the files on disk are still read/write).

    The behaviour occurs much less than in Delphi 5 or 6, but sometimes it does occur in Delphi 7.

    The best thing you can do is restart the Delphi 7 IDE as soon as you get an access violation.

  • We also have this issue from time to time, and it seems to be related to looking at the DFM's source (Alt-F12) and then doing a Visual Source Safe operation (e.g. check-in).

  • This does happen in Delphi 7 but is fixed in later versions. Usually you access forms in the IDE by opening the .pas file and then switching to the Form View. Right click your form and it will show that it is "Text DFM" ticked if you have done this before.

    You will experience the problem you have described of a text DFM switching to a binary DFM when in the Delphi 7 IDE you open the .dfm file directly. eg. File->Open->Somefile.dfm .. Right click the dfm and choose "View as Form". Now right click the form, you will see that the "Text DFM" is unticked.

    We were getting the problem when we opened up a DFM which was a grep search result. It had us perplexed also, and would cause corruption of the dfm in cvs as it was checked in as text.

First Column of a Grid is the headers?

Is there a way (using jquery, yui or some other js library) to display a grid that has the headers in the first column?

That is, I would have something like:

Name       Geoffrey
EMail      GMan67@..
Username   GJFM

Instead of:

Name      EMail      Username
Geoffrey  GMan67@..  GJFM

G-Man

From stackoverflow
  • What you are wanting to create is called a pivot table. I'm not aware of any out of the box solutions for this though.

  • Yes there is a way to do it, it took me an hour to write but It was a nice exercise :)

    This will switch headers and columns inplace. And it works both ways. i.e. you can use it to switch the two styles back and forth.

    // number of columns
    columns = $('table.flipme th').size();
    // number of rows minus one to exclude the header
    rows = $('table.flipme tr').size() - 1;  
    $table = $('table.flipme');
    
    // Add rows to the table to equal the number of columns
    while (rows < columns){
        $table.append('<tr></tr>');
        rows++
    }
    
    // flip in place and mark the old rows and
    // columns as a duplicate to be removed
    for (i=1; i<=rows; i++){
        $('tr')
        .children(':nth-child(' + i + ')').addClass('delete')
        .clone(true).removeClass('delete')
        .appendTo('tr:eq(' + i + ')');
    }
    // remove dublicate
    $('.delete').remove();
    

$html-link() using onmouseover

Trying to use an onmouseover event

echo $html->link("Dashboard", 
     "/dashboard/index", 
     array("onmouseover" => "Tip('Test');") );

becomes

<a href="/dashboard/index" onmouseover="Tip(&#039;Test&#039;);">Dashboard</a>

How do I prevent the link function from removing the single quotes?

From stackoverflow
  • This should work:

    echo $html->link("Dashboard", 
         "/dashboard/index", 
         array("onmouseover" => "Tip('Test');"),
         array('escape' => false));
    
    Jack B Nimble : added onclick="return confirm('Array');" after the onmouseover. It went into the confirm return true/false parameter of link.
  • Using Cake 1.2, this should definitely work:

    echo $html->link('Dashboard', '/dashboard/index',
    array("onmouseover" => "Tip('Test');"), null, false);
    

    The last parameter is the escape option. It defaults to true.

exporting tables to excel / word using POI

i want the code to export tables/ reports to excel and word uisng POI i saw the examples that came with POI but cuoldnot understand.Can anyone provide me a small/easy code to do the same.

From stackoverflow
  • Seeing as you wanted actual code for using POI. Here is some to do some exporting:

    import java.util.Date;
    import java.util.List;
    import java.util.ListIterator;
    import java.util.StringTokenizer;
    import java.io.*;
    import org.apache.poi.hssf.usermodel.*;
    
    
    public class XLSExporter implements Exporter {
    
        /**
         * Constructor for XLSExporter
         */
        public XLSExporter(){
        }
    
    
        public void exportFile( File f, List o ) throws IOException{
    
            HSSFWorkbook wb = new HSSFWorkbook();
            FileOutputStream fileOut = new FileOutputStream(f);
    
            HSSFSheet sheet = wb.createSheet();
    
    
         ListIterator it = o.listIterator();
    
            //Construct the headings
            HSSFRow headingsRow  = sheet.createRow((short)0); 
    
    
            //Heading format
            HSSFFont headingFont = wb.createFont();
            headingFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            HSSFCellStyle headingStyle = wb.createCellStyle();
            headingStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            headingStyle.setFont(headingFont);
    
    
            HSSFCell headingA = headingsRow.createCell((short)0);
            headingA.setCellValue("Heading");
            headingA.setCellStyle(headingStyle);
    
    
    
    
            int i = 1;
            // Iterate over the rows
         while(it.hasNext()){
    
    
          //Create the row
          HSSFRow row  = sheet.createRow((short)i); 
    
          //Write data
          HSSFCell cellRunway = row.createCell((short)0);
          cellRunway.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
          cellRunway.setCellValue("Whateva");    
          cellRunway.setCellStyle(standardStyle);
    
    
    
          i++;
         }
    
         //Set the column widths where needed
         sheet.setColumnWidth((short)1, (short)4000); 
    
    
            wb.write(fileOut); // Write the workbook
            fileOut.close();
        }
    
    }
    

wc gzipped files?

I have a directory with both uncompressed and gzipped files and want to run wc -l on this directory. wc will provide a line count value for the compressed files which is not accurate (since it seems to count newlines in the gzipped version of the file). Is there a way to create a zwc script similar to zgrep that will detected the gzipped files and count the uncompressed lines?

From stackoverflow
  • Try this zwc script:

    #! /bin/bash --
    for F in "$@"; do
      echo "$(zcat -f <"$F" | wc) $F"
    done
    
    Reef : It should be "echo "$(zcat -f <"$F" | wc -l) $F"
    pseinstein : Thanks, this works great.
    Chas. Owens : or $(zgrep -c "" $F)

Why "cannot use an object as a parameter to a method"?

I have the following ViewController class

#import <UIKit/UIKit.h>

@interface SampleViewController : UIViewController {
    IBOutlet UITextField *field1;
}

@property (nonatomic, retain) UITextField *field1;

- (IBAction) method1:(id)sender; 
@end

When I change the method1:(id)sender to method1:(UITextField)sender, I get the error "Cannot use an object as a parameter to a method".

I searched and found this post which says "it [using an object as a method parameter] is not a good idea in Objective-C because Objective-C does not allow statically allocated object".

Can anyone point out where I can find a more detailed explanation for this?

Thank you.

From stackoverflow
  • You're not passing a pointer of UITextField.

    method1:(UITextField)sender
    

    should be

    method1:(UITextField *)sender
    

    Objective-C doesn't like it when you pass non-pointers for object types.

    Casebash : Interestingly, you can pass it if it is a struct rather than object
  • Simple and correct answer. Thanks, been searching for hours.

    Casebash : Peter, please don't post comments until you gain enough rep to post them as comments instead of answers

Is it possible to do a git-rebase after doing a git-commit

I started to rewrite some of the Perl programs from the NASM source files. I have already done a few commits to my own working copy, and I was wondering if I should have instead of doing git pull, if I should have been doing git rebase.

I have pretty much decided that I should have been doing a git rebase, but I don't know how to rework my repository to achieve that effect, or even if it is possible.

Screenshot-gitk: nasm.crop

From stackoverflow
  • I've had success with the following method in the past:

    For this method, I have added the following alias:

    up = pull --rebase origin
    
    1. Branch your master branch to something like 'dev' or whatever
    2. Work in dev
    3. when you've finished adding and committing changes
    4. git up master
    5. switch to master
    6. git merge dev
    7. git push

    When pulling in changes from the remote repo:

    1. switch to master
    2. git up
    3. switch to dev
    4. git up master

    YMMV

    Dustin : Your alias seems to be a less standard way to do `git config --global branch.master.rebase` along with `git config --global branch.autosetuprebase always` (you can always fetch and merge if you want to do so for a particular branch)
  • It is possible, and the Git Magic tutorial will explain how to do it. But if anyone else has seen your branch, it is unsafe. Even if nobody else has seen your branch, let me urge you to reconsider.

    Why have rebasing? Why not just pull/merge?

    The purpose of rebasing is to rewrite history so that your repository reflects the way you believe your software should have evolved instead of the way it actually did. When is this important? When you are a junior member of a distributed development team, and you don't have commit privileges—instead, all you can do is submit patches to a gatekeeper and hope that they are accepted. To maximize the chances of acceptance, you want to rewrite history to make your patches as clean and clear as possible. Is the development model sounding familiar?

    Manoj Srivastava has written a fairly thoughtful analysis of rebase-vs-merge.

  • You should be able to undo your last merge by changing the branches like this:

    git branch your-changes <reflog of "Reworked test files...">
    git branch -f master remotes/origin/master
    

    After that you can try rebasing.

    1. Ensure that the current commit is the merge commit: git log
    2. First we re-set the master to the previous commit (the one right before the merge): git reset HEAD^
      • HEAD^ means: 'the commit before the commit referenced by HEAD'
    3. Now you can do a normal rebase: git rebase origin/master

    Next time I recommend to do a git fetch and then the rebase as step 3.

    I would recommend to create a small tarball of your current git repo, just in case the rebase goes wrong. You'll do that less often when you feel more confident (and usually you can fix almost everything with git, but sometimes the tarball is faster).

  • As a followup to Dustin's reply, it should be "git config --global branch.master.rebase true".

Rails escaping quotation mark in link_to_function partial

I have a little piece of rails code which lets users enter a review. If one already is written it displays the current review with a link to edit it.

      <div id="text_area">
        <% if @user_rating.review.blank? %>
          <%= render :partial => "reviews/text_area" %>
        <% else %>
          <%= simple_format @user_rating.review %>
          <%= link_to_function "Edit Review" do |page|
            page.replace_html :text_area, :partial => "reviews/text_area"
          end %>
        <% end %>
      </div>

This works correctly EXCEPT if the review contains a double quote character. Here is the HTML output it generates after a user has already written a review (the else block from above).

      <div id="text_area">
          <p>some text with "quotation marks"</p>
          <a href="#" onclick="try {
Element.update(&quot;text_area&quot;, &quot;&lt;form action=\&quot;/pages/iphone-reviews/reviews/new/write\&quot; class=\&quot;edit_rating\&quot; id=\&quot;edit_rating_16\&quot; method=\&quot;post\&quot;&gt;&lt;div style=\&quot;margin:0;padding:0\&quot;&gt;&lt;input name=\&quot;_method\&quot; type=\&quot;hidden\&quot; value=\&quot;put\&quot; /&gt;&lt;input name=\&quot;authenticity_token\&quot; type=\&quot;hidden\&quot; value=\&quot;fSZK30kpWEUtCxOvr4xDF1O+puDiPm87mhaxaLirIT8=\&quot; /&gt;&lt;/div&gt;\n        &lt;textarea cols=\&quot;40\&quot; id=\&quot;rating_review\&quot; name=\&quot;rating[review]\&quot; rows=\&quot;20\&quot; style=\&quot;width:100%;height:150px;\&quot;&gt;some text with &quot;quotation marks&quot;&lt;/textarea&gt;\n&lt;/form&gt;&quot;);
} catch (e) { alert('RJS error:\n\n' + e.toString()); alert('Element.update(\&quot;text_area\&quot;, \&quot;&lt;form action=\\\&quot;/pages/iphone-reviews/reviews/new/write\\\&quot; class=\\\&quot;edit_rating\\\&quot; id=\\\&quot;edit_rating_16\\\&quot; method=\\\&quot;post\\\&quot;&gt;&lt;div style=\\\&quot;margin:0;padding:0\\\&quot;&gt;&lt;input name=\\\&quot;_method\\\&quot; type=\\\&quot;hidden\\\&quot; value=\\\&quot;put\\\&quot; /&gt;&lt;input name=\\\&quot;authenticity_token\\\&quot; type=\\\&quot;hidden\\\&quot; value=\\\&quot;fSZK30kpWEUtCxOvr4xDF1O+puDiPm87mhaxaLirIT8=\\\&quot; /&gt;&lt;/div&gt;\\n        &lt;textarea cols=\\\&quot;40\\\&quot; id=\\\&quot;rating_review\\\&quot; name=\\\&quot;rating[review]\\\&quot; rows=\\\&quot;20\\\&quot; style=\\\&quot;width:100%;height:150px;\\\&quot;&gt;some text with &quot;quotation marks&quot;&lt;/textarea&gt;\\n&lt;/form&gt;\&quot;);'); throw e }; return false;">Edit Review</a>

      </div>

This example breaks because the text of the review contains a double quote. It works with single quotes and any other text I can think of. I think rails is not escaping the double quote correctly in the javascript.

The error which comes up in Firebug is this:

missing ) after argument list [Break on this error] \" id=\"rating_review\" name=\"rating[re...n:right;\">\n

I'm at a loss on how to fix this one. Thanks!

From stackoverflow
  • You could write a javascript escape helper:

    def escape_javascript(javascript)
            javascript.gsub!("\r\n", "\\n")
            javascript.gsub!(/\n|\r/, "\\n")
            javascript.gsub(/["']/) {|m| "\\#{m}"} || javascript
    end
    

    and call it when you save your review.

    Brian Armstrong : this would save it to the database in an escaped format right? seems less than ideal, since it would require unescaping it any time it was displayed in the view, right?
    MickTaiwan : unescaping would not be necessary if you escape it in HTML like escaping " into " or \r\n into
    . See http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php
    Brian Armstrong : I think unescaping would not be necessary to display the html on a page, but if they go back to edit the text they wrote, they will want to edit the exact text they wrote. Found a solution below that worked...but thanks for the response, I appreciate it!
  • Found a solution which worked. I'm not really sure why it worked but it did.

    A couple times up above I call a partial to render the text area and form where the user can edit their review, like this

    <%= render :partial => "reviews/text_area" %>
    

    All I had to do was go in and edit this partial. One of lines in the form looked like this:

    <%= f.text_area :review %>
    

    All I did was change it to this:

    <textarea cols="40" id="rating_review" name="rating[review]" rows="20"><%=@user_rating.review%></textarea>
    

    Basically just put it in manually so it didn't use the rails function to generate the text area. For whatever reason, it works now. May be something that could be improved in the rails text_area function.

Getting string content of the complex mixed element with XQuery

For, example, there is an xml:

<article-list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="3.xsd">
    <article section="physics">
     Increasing linear dynamic range of commercial digital photocamera
     <author>M. V. Konnik</author>
     <content>
      Methods of increasing linear optical dynamic range
     </content>
    </article>

my aim is to query string content of article element. I.e.:

Increasing linear dynamic range of commercial digital photocamera

The obvious solution like this:

<!--xquery-->
{
for $article in doc("name.xml")//article-list/article
    where $article/receiving-date > xs:date("2005-01-01")
    return
     <article>
      {$article}
     </article>
}

Returns whole article tree, not only a string.

From stackoverflow
  • $article is an element, not a node. To get the text (the text you want is actually the text child node of the $article node), you just need:

     {$article/text()}
    
    skfd : Thank you it worked!
    Brabster : np glad to help, thanks for accepting.

I changed my file extensions, but google hasn't changed.

Well, I changed my file extensions to .shtml and google still has them indexed as .html. I've tried uploading a sitemap and other things to google webmaster tools but with no luck. Is there any other way I can force google to crawl my site? Im guessing thats the only way the links will update.

From stackoverflow
  • Google crawls the web periodically, just wait for a while, it will re-index your site.

  • You can try setting your change frequency to always or something more frequent to get indexed sooner. I make no guarantees though. Otherwise, you're just going to have to wait like the rest of us.

    Chris B. : FML lol. Thank you.
  • Have you set up redirection from the old .html filenames to the new .shtml filenames? You should do that - Google will pick up your changes more quickly (because it doesn't have to discover all your pages again) and it will transfer PageRank from the old URLs to the new ones. There are a million descriptions on the net about how to do that.

    But having said that, can't you just keep the .html filenames and do some trickery with .htaccess (or equivalent; you don't say which web server you're using) to make the .html files respect SSI directives? This:

    AddType text/html .html
    AddHandler server-parsed .html
    

    ought to do it for Apache.

  • If your website gets some traffic then there's a good chance that Googlebot has already visited. My website isn't big and I get crawled daily. You can be pretty sure that Google already knows your new URLs.

    The thing is that Google only updates it's indexes every 3-4 weeks or so. There are a few exceptions to that, such as regularly updated blogs and forums where new threads and posts get picked up very fast. But usually it can take a few weeks until your new URLs are in the main seach index.

    Oh and a tip: If you have rewrite rules to redirect your old .html addresses to your new .shtml addresses, make sure you use 301 redirects and not 302 redirects. With 301 redirects, Google will assign the "link juice" that the old URL has to the new URL. With 302 redirects it does not do that and you could possibly loose pagerank.

Passing a method to validates_format_of

I want to do this:

validates_format_of :email, :with => email_regex

def email_regex
  email_name_regex  = '[A-Z0-9_\.%\+\-]+'
  domain_head_regex = '(?:[A-Z0-9\-]+\.)+'
  domain_tld_regex  = '(?:[A-Z]{2,4}|museum|travel)'
  return /\A#{email_name_regex}@#{domain_head_regex}#{domain_tld_regex}\z/i
end

but I am getting an error saying that I have to pass a regex to the validates method. I was sure youo could do something like this. Am I missing a step?

Thanks

From stackoverflow
  • What about just using a contstant? This would also ensure that the regexp gets only compiled once.

    class ...
      FOO_BAR = /#{baz}.../
    
      validatess ... :with => FOO_BAR
    

    but yeah, I'm not sure why your way doesn't work.

  • Your code looks OK. And I guess you define email_regex method before it is used by the validates method.

    You have to debug what validates_format_of gets (modify RoR code to print the :with argument type). This should be quite easy and help you solve the problem.

    Now I can only guess that email_regex method is redefined somewhere and returns something else than Regexp.

Advice for Windows system scripting+programming

I just got a project where I have to do the following on a Windows OS:

  1. detect how many drives (C: D: E: ..etc) are connected to current system
  2. what the system labels are for each volume
  3. how much storage (both used and free) for each of the drives
  4. what format each drive is (NTFS/FAT32)
  5. how many files are in a given directory in any of those drives
  6. how big each file size is
  7. File processing (each file is about 2GB) where I have to do a lot of C-like fseek(), and binary data parsing, and big to little-endian conversion. Have to write some logic code as well.

I'm an experienced C\C++ programmer, but I thought this would be a perfect time for me to start learning about scripting.

Candidates that I thought of are: ( Python || Ruby ) && PowerShell.

Are those the kinds of things I can accomplish with, say, IronPython+Powershell? Or are there better tools/languages out there?

PS: Is PowerShell meant to replace VBScript? Also, what is VB.net good for anyway now that C#, WPF, and Powershell exist?

From stackoverflow
  • Except for the seventh item on your list this should be fairly trivial using Powershell and WMI, as this is perhaps the natural domain for Powershell. Since you won't need another language for the first six list items it shouldn't really matter what you use for the last one. You probably can use PS (I've never done IO with it, though) or whatever suits you.

    As for your second question: VBScript is probably not going to go away in the near future as the Windows Script Host is still a safer bet when writing small scripts for deployment, as it comes preinstalled on every Windows since 98. Powershell is only included in Windows 7 and later. That being said, Powershell is surely targeted at obsoleting WSH and CMD for automation purposes since it offers the same features of the aforementioned ones and much more (like easy .NET and WMI access).

    VB.NET on the other hand is one of the primary .NET languages marketed by Microsoft. It has little to no relation to VBScript, is no competitor to Powershell or WPF (heck, those are completely different technologies). You may see some convergence with C# going on as both languages still seem to struggle a little finding their intended market. Still, VB.NET is the easiest choice of switching to .NET when you're a VB programmer and there were/are lots of them MS didn't want to lose just because they created .NET.

  • You can do that in either IronPython|IronRuby or Powershell. I'd recommend IronPython since it's a real language (older than C# or even Java), with lots of support and full access to the .NET APIs you will need (or even COM APIs).

    I'd suggest you to read this article that answers your exact question: http://pythonconquerstheuniverse.blogspot.com/2009/04/ironpython-windows-scripting-language.html

    Rohit : Python is a language older than C# or Java, but IronPython is certainly not. Even if it's older it doesn't automatically make it better (I'm not saying it makes it worse either). Also, not sure what you mean by a "real" language.
    JasonMArcher : Yea, PowerShell is real as well. It certainly isn't fictional. :)
  • PowerShell can easily handle 1-6. Number 7 can probably be done in PowerShell, but there may be better options depending on the details.

    See What tutorial do you recommend for learning PowerShell? for some good info on learning PowerShell.

  • I'll give you the unpopular answer then since no one else has added it: Perl.

    If you're comfortable with the Win32 API as a C/C++ programmer, Perl may be the easier way to go. It has modules for accessing the Win32 API and Perl is quite easy for C/C++ programmers to get up to speed in. Perl has always done the job for me in the past.

  • As for Perl, Ruby too has access to all Win32 API and WMI functions.

  • Powershell was designed as an automation platform for Windows. So sure, Ruby, Python, Perl, VBScript etc can do the job, why not choose the tool best for the job. Here's how to get some basic drive info:

    $drives = Get-WmiObject -Class  Win32_LogicalDisk | ? {$_.DriveType -eq 3 }
    $drives | select DeviceId,VolumeName,FileSystem,FreeSpace, Size
    

    Number of files in a directory

    Get-ChildItem c:\path -Recurse | Measure-Object
    Get-ChildItem c:\path | Measure-Object
    

    With info on file size

    Get-ChildItem c:\path -Recurse |  Measure-Object -Average -Sum 
                                     -Maximum -Property Length
    

    And for file processing, you can use native cmdlets such as get-content or invoke and instantiate .Net types.

  • I think PowerShell is ideal for this task because it is optimized for this sort of system information retrieval. WMI is exceptionally easy to use from PowerShell as opposed to C# IMO (and I'm a C# dev by day). Heck, let's see how easy this is from PowerShell:

    #1,2, 3 and 4
    PS> Get-WmiObject Win32_LogicalDisk | 
    >>  Format-Table Name, VolumeName, FileSystem, Size, FreeSpace -auto
    
    Name VolumeName FileSystem         Size    FreeSpace
    ---- ---------- ----------         ----    ---------
    C:              NTFS       160038907904 100353536000
    D:
    E:
    F:   PDC2008    NTFS       160039239680  40155922432
    V:   Vista      NTFS       250056704000  33944559616
    
    #5
    PS> dir <path> -r | where {!$_.PSIsContainer} | Measure-Object
    
    #6
    PS> dir <path> -r | where {!$_.PSIsContainer} | 
    >>  Format-Table Fullname, Length -auto
    

    And PowerShell can handle #7 easily via its ability to use the .NET Framework. For an example of fseek style programming in PowerShell check out this tail-content script starting around line 139.

"Length of the data to decrypt is invalid." exception during Rijndael decryption

I get "Length of the data to decrypt is invalid." exception when i try to decrypt a memory stream. I am beginner, cant figure out whats wrong. whats wrong?

public bool EncryptStream()
    {

        string password = @"myKey123"; // Your Key Here
        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] key = UE.GetBytes(password);

        s_EncryptedStream = new MemoryStream();
        int NoOfBytes;
        byte[] b_Buffer = new byte[8192];

        s_MemoryStream.Seek(0, SeekOrigin.Begin);

        RijndaelManaged RMCrypto = new RijndaelManaged();

        s_CrytpoStream = new CryptoStream(s_EncryptedStream,
            RMCrypto.CreateEncryptor(key, key),
            CryptoStreamMode.Write);

        while (s_MemoryStream.Length < s_MemoryStream.Position)
        {
            NoOfBytes = s_MemoryStream.Read(b_Buffer, 0, 8192);
            s_CrytpoStream.Write(b_Buffer, 0, NoOfBytes);
        }

        s_MemoryStream.Seek(0, SeekOrigin.Begin);

        while (s_EncryptedStream.Position < s_EncryptedStream.Length)
        {
            NoOfBytes = s_EncryptedStream.Read(b_Buffer, 0, 8192);
            s_MemoryStream.Write(b_Buffer, 0, NoOfBytes);

        }
        s_CrytpoStream.Flush();
        s_CrytpoStream.Close();

        return true;

    }


    public bool DecryptStream()
    {


        string password = @"myKey123"; // Your Key Here

        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] key = UE.GetBytes(password);

        int NoOfBytes;
        byte[] b_Buffer = new byte[8192];

        s_DecryptedStream = new MemoryStream();


        RijndaelManaged RMCrypto = new RijndaelManaged();

        s_CrytpoStream = new CryptoStream(s_MemoryStream,
            RMCrypto.CreateDecryptor(key, key),
            CryptoStreamMode.Read);

        s_MemoryStream.Seek(0, SeekOrigin.Begin);

        while (s_MemoryStream.Length > s_MemoryStream.Position)
        {
            NoOfBytes = s_CrytpoStream.Read(b_Buffer, 0, 8192);
            s_DecryptedStream.Write(b_Buffer, 0, NoOfBytes);
        }

        s_DecryptedStream.Seek(0, SeekOrigin.Begin);
        s_MemoryStream.Seek(0, SeekOrigin.Begin);

        while (s_DecryptedStream.Position < s_DecryptedStream.Length)
        {
            NoOfBytes = s_DecryptedStream.Read(b_Buffer, 0, 8192);
            s_MemoryStream.Write(b_Buffer, 0, NoOfBytes);

        }

        s_CrytpoStream.Flush();
        s_CrytpoStream.Close();

        return true;

    }
From stackoverflow
  • For a start, this while loop condition is never right:

    while (s_MemoryStream.Length < s_MemoryStream.Position)
    

    How can the position be beyond the length?

    Rather than using the length of a stream, the usual pattern to copy a stream is to read repeatedly until the value returned isn't positive. As you're doing that twice in this code anyway, you might as well encapsulate it:

    public static void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[8192];
        int read;
        while ( (read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, read);
        }
    }
    

    It's also best to use using statements to clean up strings. Additionally, the Encoding.Unicode property means you don't have to create a new UnicodeEncoding yourself. Also, I generally find that setting the Position property is more readable than using Seek. Finally, there's no point in a method returning a value if it's always going to be true. So, your code would become:

    public void EncryptStream()
    {
        string password = @"myKey123"; // Your Key Here
        byte[] key = Encoding.Unicode.GetBytes(password);
    
        s_EncryptedStream = new MemoryStream();
        s_MemoryStream.Position = 0;
    
        RijndaelManaged RMCrypto = new RijndaelManaged();
    
        using (Stream crytpoStream = new CryptoStream(s_EncryptedStream,
            RMCrypto.CreateEncryptor(key, key),
            CryptoStreamMode.Write))
        {
            CopyStream(s_MemoryStream, cryptoStream);
        }
    
        s_MemoryStream.Position = 0;
        s_EncryptedStream.Position = 0;
        CopyStream(s_EncryptedStream, s_MemoryStream);
    }
    
    public void DecryptStream()
    {
        string password = @"myKey123"; // Your Key Here
        byte[] key = Encoding.Unicode.GetBytes(password);
    
        s_DecryptedStream = new MemoryStream();
        s_MemoryStream.Position = 0;
    
        RijndaelManaged RMCrypto = new RijndaelManaged();
    
        using (Stream crytpoStream = new CryptoStream(s_MemoryStream,
            RMCrypto.CreateDecryptor(key, key),
            CryptoStreamMode.Read))
        {
            CopyStream(cryptoStream, s_DecryptedStream);
        }
    
        s_DecryptedStream.Position = 0;
        s_MemoryStream.Position = 0;
    
        CopyStream(s_DecryptedStream, s_MemoryStream);
    }
    

    Even after amending this code, it feels like you've got way too many non-local variables here. I can't see why any of this should be in instance variables. Make the stream to be encrypted or decrypted a parameter (along with the password) and return a memory stream with the encrypted/decrypted data in, or just a byte array.

    veagles : Thanks, that was just a rough code. I have made the changes as suggested. I am still getting the same exception in CopyStream(cryptoStream, s_DecryptedStream);
    Jon Skeet : Then please post a short but complete program which demonstrates the problem. Something we can run to reproduce it.
    veagles : It worked.. It ways my mistake.. Thanks anyways.
  • You may need to call the FlushFinalBlock method on the CryptoStream after you have finished reading the input data. (ie. crytpoStream.FlushFinalBlock() after CopyStream)

    Jon Skeet : I think you *shouldn't* need to do that if you dispose of the CryptoStream - there was a bug in .NET 1.1 which meant that it didn't flush the final block then, but it was fixed in .NET 2.0.
    Sam : Ahh, ok, just me following old code examples then.
  • I have come up with a solution and I have it posted on my new Blog

    constotech.blogspot.com/2009/05/net-encryption-using-symmetricalgorithm.html

Windows Mobile: how to highlight row in datagrid and compilation delays

Hi,

I have two Windows mobile questions:

  1. how to Highlight row in datagrid (after i run any query) ?

  2. why after 20-30 compilation, it takes for 6-7 minutes to compile (the first time takes 1 minute)?

Thanks in advance!

From stackoverflow
  • For #1, take a look at Ilya Tumanov's example of custom formatting data in the DataGrid. He does custom painting of cells in it. THis is how you'd "highlight" a row.

    For #2, there's something wrong with your environment. I've not seen this or heard it reported and I've been using Studio for developing CF apps for a while now, with well over 10-30 compiles in a run. My guess is you have a network drive mapped. Unmap it and see if anything changes (though 6-7 minutes is really heinous). Also, if you're using a solution with a lot of projects, you should have a single output directory for everything instead of each project having their own, and set CopyLocal to false on all the references. This helps keep disk access duriong build to a minimum.

  • For #2: If you're using Visual Studio 2008 it may as well be a matter of PostBuild verification task. The following link pointed me in the right direction when I had the problem:

    http://blogs.msdn.com/vsdteam/archive/2006/09/15/756400.aspx

Ruby Difference Between Integer Methods

What is the difference between

10.6.to_i

and

10.6.to_int ?

From stackoverflow
  • There is no difference. They are synonymous.

    Andrew Grimm : to_i and to_int may give the same result for 10.6, but "42".to_i works, whereas "42".to_int raises a NoMethodError, for reasons given in kgiannakakis's link.
  • Read more about it here.

OOP: good class design

My question is related to this one: Python tool that builds a dependency diagram for methods of a class.

After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies between class methods. My script generated an input file for graphviz, which was used to generate a dependency graph that looks like this.

At this point I've got stuck. I've realized that I have no idea how to refactor the class to make it less complicated. I simply don't know what should I aim to. For example, in theory of relational databases there are a couple of simple rules that are used to bring a database to a normal form. What about some similar theory concerning the good class design (in terms of dependencies between its methods)? Is this topic covered somewhere so I could study it?

From stackoverflow
  • We follow the following principles when designing classes:

    Edit: Design patterns are helpful in getting your code to comply with these principles. I have found it very helpful to understand the principles first and then to look at the patterns and understand how the patterns bring your code in line with the principles.

    S.Lott : The principles, in some cases, are hard to understand; some folks find that design patterns are an easier way to get started.
    Trumpi : What you're saying is true, but I think that using patterns without understanding the principles is where "pattern abuse" stems from.
  • It's often not possible to say whats 'correct' or 'wrong' when it comes to class design. There are many guidelines, patterns, recommendation etc. about this topic, but at the end of the day, imho, it's a lot about experience with past projects. My experience is that it's best to not worry to much about it, and gradually improve your code/structure in small steps. Experiment and see how some ideas/changes feel/look like. And it's of course always a good idea to learn from others. read a lot of code and analyse it, try to understand :).

    If you wanna read about the theory I can recommend Craig Larmanns 'Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development' Amazon. He covers several parts of your question, gives some rough guidlines and shows them using an example application. I liked the book.

    Could you upload your app somewhere? Perhaps on github or so, perhaps you could ask for some concrete advices.

    duffymo : +1 Larman's book is quite good.
  • Design Patterns has become the defacto standard for good class design. Generally, each pattern has a particular use case, or scenario, which it applies to. If you can identify this in your code, you can use the pattern to create something that makes more sense, and usually has less dependencies.

    Refactoring is the tool that you would use to accomplish these sweeping changes. A good IDE will help you to refactor.

  • Try making each method easily unit-testable. I find this always drives my designs towards more readability/understandability. There are numerous OOAD rules -- SRP, DRY, etc. Try to keep those in mind as you refactor.

  • I recommend the book "Refactoring" by Martin Fowler for tons of practical examples of iteratively converting poor design to good design.

How can I "escape" quotes in javascript?

I don't know if "escaping" is the right word (please tell me what the right word/phrase is) but in Ruby you can say something like

text = "This is visit number #{numVisits} to this website"

so you can skip concatenation etc.

I'm working in JQuery and have a bit like this:

$(document).ready(function(){
    $("a.ajax").click(function(event){
    $("#content").load("data.html this.getClass");
    });
});

The behavior I want is "click on (a class="ajax" id="schedule")(/a) and the "content" div on the current page is replaced by the "schedule" div from data.html. If I manually write in

load("data.html #test");

that works, but I want the script to load the DIV with the ID value of the anchor clicked. Any help would be swell!

Example Page: http://www.mariahandalex.info/stack/

From stackoverflow
  • Try this:

    $(document).ready(function(){
        $("a.ajax").each(function(){
            var obj = $(this);
            obj.click(function(event){
               alert(obj.attr('id'));
            });
        });
    });
    
    Gumbo : @Alex Mcp: Take a look at it now.
    geowa4 : '#' + this.getClass()? you probably meant '.'
    Alex Mcp : But that will append the Class of the "#content" div. That is where the data is getting shuttled in and out of. I need to find a way to tack on the "ID" attribute of the link that was clicked, because that will identify what gets pulled out of the external page.
    Gumbo : It should work now.
    Gumbo : I forgot that it’s an jQuery object that gets returned. It works now.
    Alex Mcp : I put an example page up. This is so strange, it's only returning the id value for the first in the list of links. Maybe the list is somehow the object, and it thinks it only has one ID? I'm a bit beyond my knowledge here... Thanks so much.
  • Javascript doesn't parse string literals looking for replacement markers like Ruby or PHP does. You will have to use concatenation.

  • You cannot embed javascript code inside a string, but you can concatenate a string to an object using '+' like so

    $('#content').load('data.html #' + $(this).getClass());
    

    About embedding code in a string, I don't think it has a name. Groovy calls those strings "Gstring"s, and ruby calls those 'Expression substitution in strings'. I'm not sure it has a standard name.

    strager : I think you mean $(this).getClass() or maybe this.className.