Monday, April 11, 2011

redirect to another page

< type="button" value="PRINT" onClick="window.open('print.php?id=&sec=&subj=&type=viewrec2&Year=&faci= ','mywindow','width=800,height=800,left=0,top=100,screenX=0,screenY=100')">

when i click this button im being redirected into a new window. the problem is that on the main page where this button is located i want it also to redirect it to the previous page on that the same window how can i do that im using php and javascript?

From stackoverflow
  • <input type="button" value="PRINT" onClick="window.open('print.php?id=&sec=&subj=&type=viewrec2&Year=&faci= ','mywindow','width=800,height=800,left=0,top=100,screenX=0,screenY=100');history.back()">
    
  • Just add

    history.go(-1);
    

    changing the code to:

    <input type="button" value="PRINT" onClick="window.open('print.php?id=&sec=&subj=&type=viewrec2&Year=&faci= ','mywindow','width=800,height=800,left=0,top=100,screenX=0,screenY=100');history.go(-1)">
    

Using Tidy in JRuby

After spending some hours with the Ruby Debugger I finally learned that I need to clean up some malformed HTML pages before I can feed those to Hpricot. The best solution I found so far is the Tidy Ruby interface.

Tidy works great from the command line and also the Ruby interface works. However, it requires dl/import, which fails to load in JRuby:

$ jirb
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'tidy'
LoadError: no such file to load -- dl/import

Is this library available for JRuby? A web search revealed that it wasn't available last year.

Alternatively, can someone suggest other ways to clean up malformed HTML in JRuby?

Update

Following Markus' suggestion I now use Tidy via popen instead of libtidy. I posted the code which pipes the document data through tidy for future reference. Hopefully, this is robust and portable.

def clean(data)
    cleaned = nil
    tidy = IO.popen('tidy -f "log/tidy.log" --force-output yes -wrap 0 -utf8', 'w+')
    begin
        tidy.write(data)
        tidy.close_write
        cleaned = tidy.read
        tidy.close_read
    rescue Errno::EPIPE
        $stderr.print "Running 'tidy' failed: " + $!
        tidy.close
    end        
    return cleaned if cleaned and cleaned != ""
    return data
end
From stackoverflow
  • You could use it from the command line from within JRuby with %x{...} or backticks. You may also want to consider popen (and pipe things through it).

    Not elegant perhaps, but more likely to get you going with minimal hassle than trying to mess with unsupported libraries.

Hibernate HQL: two levels of joins

I am new to HQL and have the following table relationships:

  • Term has many Definitions
  • Definition has many DefinitionProducts
  • DefinitionProducts has one Product

I want to get the list of Terms that have at least one Definition that has at least one DefinitionProduct that has a specific Product

This is my best attempt (in Grails):

Term.findAll("from Term t, Definition d inner join t.definitions def,  
def.definitionProducts dp where ? = some elements (dp.product)",
Product.get(1))

With the above, I get a "def.definitionProducts is not mapped" exception.

From stackoverflow
  • select t from Term t join t.definitions def join def.definitionProducts dp where dp.product=?

    Mike Sickler : That seems to return a list of definitionProducts
    Maurice Perry : select t from Term t join t.definitions def join def.definitionProducts dp where dp.product=?
    Mike Sickler : Yes! Thanks a lot. In grails, I just had to switch the call from Term.findAll to Term.executeQuery and it worked!

add "Now Loading" before UITabBarController tab select?

Hello everyone -

One of the tabs of my UITabBarController takes some time to work before it can be displayed.

What is the best way to display a "Now Loading" before the viewcontroler completes its work?

I tried setting up a "now loading" view in the tab's viewController's viewDidLoad method, then I do the work in viewDidAppear, setting a flag to not do the work again on next time through viewDidAppear.

However, I never see the "now loading" view... some optimizing must be getting done -- the viewcontroller's viewDidAppear is called before the TabBarControllerDelegate didSelectViewController.

Is there a UITabBarController mechanism that would allow for a placeholder view to be displayed before the viewcontroller is displayed?

Any ideas?

Thank you- Matt

From stackoverflow
  • I could be wrong, but perhaps your problem is that by doing the time-consuming work in viewDidAppear, you're blocking the main event thread so that the view doesn't update until the work is complete. I.e. you set up the "now loading" in viewWillAppear, but you never see it since, by the time viewDidAppear completes, it's done with the heavy work.

  • The technique to use here is this:

    1. put up a "Loading view" in your controller's viewWillAppear: or viewDidLoad: method
    2. then, spawn a new thread to do the actual loading (or whatever time consuming process you're doing)
    3. when complete, send a message to the controller (using the delegate pattern, for example) that the "loading" is done
    4. finally, remove the Loading view and let the user proceed

    Doing it this way leaves your application interface still usable, even though the particular view controller is busy.

    There are no build in methods to do this, you'll have to code it all yourself.

  • NSObject's performSelector:withObject:afterDelay: method can be useful here. Display your "Please wait" alert or view, or whatever, then use performSelector:withObject:afterDelay: to start the actual work. Your loading will be delayed until after the next execution of the event loop, by which time the user interface will have been redrawn.

flex preloader not working with # in the url (deep linking)

I can't get flash preloaders to work when there is a a # in the url of my page (even without any deep linking libraries or logic). I am using flex 3.3. Flash plugins 9 and 10, all browsers.

There is this bug regarding # in the url preventing preloaders from working: http://bugs.adobe.com/jira/browse/SDK-14162

However, somehow, someone, somewhere has ways around this. Here are somewhat working examples (remember to clear your cache to ensure you see the preloader awesomeness):

However, these do not work (no preloader at all or momentarily stuck on 100%):

So, what is going on here? I suspect the flex framework.

Anyone know where to look in the flex code? Or is this bug deeper than anyone but adobe can fix?

From stackoverflow
  • Few things going on here.

    (1) Looks like the quickest pre-loader from my #wtf examples is from Adobe. They load a very small container.swf, which then loads their 3mb main swf (amongst other biggies).

    (2) Some of the others "preloaders" aren't really preloaders. Their opening animations play when the whole thing is loaded.

  • I believe the problem you are having is that you have your assets loading into the same frame as your preloader assets and code. Flash doesn't display a frame until it has been loaded to its entirety, cause your preloader not to be seen during load, and then covered up by the new asset after.

    As a flex developer you do not have a timeline, so this is why it is important to use a small "container" as you call it or as loader movie. This movie is to have a tiny foot print so that it is available asap. Upon completion of load, the container can then call the main movie into itself, tracking the incoming data with the ProgressEvent.

    It is hard to know exactly what the issue is from what you have said, but this is a common problem. Fonts, and any other embedded items either need to be embedded on frame 2 or laterm which I believe you can only do with the flash IDE, or you require the extra loader swf, lightweight and quick to load!

    I have successfully deeplinked the following with preloaders
    http://www.madagascargame.com
    http://www.kungfupandagame.com

    Brian Hodge hodgedev.com blog.hodgedev.com

dynamic rows and columns inside a foreach loop

I'm trying, but I'm stucked with the logic... so, I have this:

$max_items=10;

echo '<table>';
echo '<tr>';

foreach ($feed->get_items(0, $max_items) as $item): 

echo '<td>';
echo $some_value; 
echo '</td>';

endforeach; 

echo '</tr>';
echo '</table>';

I want to show the results like this:

[1][2]
[3][4]
[5][6]
[7][8]
[9][10]

I have to use a while statement? A for loop? Inside or outside the foreach code?

I really don't get it...

Thanks for any kind of help

From stackoverflow
  • Take a look at this link to Displaying Recent Posts On a Non-WordPress Page. I think what you may be looking for is a way to loop over the objects get methods. For that you will need a nested loop and some sort of reflection.

  • I was just recently working with SimplePie on the February release of Cogenuity so this is still fresh in my mind.

    • Your $some_value variable never gets initialized.
    • The $item object will have such methods as get_permalink(), get_title(), get_description(), and get_date()
  • Here's a very simple example of how to do this sort of HTML building.

    <?php
    
    $data = range( 'a', 'z' );
    $numCols = 2;
    
    echo "<table>\n";
    echo "\t<tr>\n";
    
    foreach( $data as $i => $item )
    {
        if ( $i != 0 && $i++ % $numCols == 0 )
        {
         echo "\t</tr>\n\t<tr>\n";
        }
        echo "\t\t<td>$item</td>\n";
    }
    
    echo "\t</tr>\n";
    echo '</table>';
    

    This way, you can change $numCols to be 3 or 4 (or any number) and always see that number of columns in the output, and it does so without using an nested loop.

Is the 'name' attribute considered outdated for <a> anchor tags?

Visual Studio doesn't like on-page anchor tags:

Validation (XHTML 1.0 Transitional): Attribute 'name' is considered outdated. A newer construct is recommended.

I'm using name attributes in this way…

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd" xml:lang="en">
    ...
    <body>
        ...
        <p>On this page&hellip;</p>
        <ul>
            <li><a href="#one">Section One</a></li>
            ...
        </ul>
        ...
        <h2><a name="one">Section One</a></h2>
        ...
    </body>
</html>

Is there really a more-modern way of doing this? Or is Visual Studio full of crap?

From stackoverflow
  • I believe the proper way to do it is <a id="one">

  • name attributes are deprecated in XHTML 1.0 - you can use an id attribute in the same way though, see Fragment Identifiers in the HTML Compatibility Guidelines of the XHTML spec.

    So you can simply use

    <h2><a id="one">Section One</a></h2>
    

    But note that the 1.0 spec recommends playing it safe with something like this:

    <h2><a name="one" id="one">Section One</a></h2>
    

    However, your fragment uses XHTML 1.1, where the name attribute has been entirely removed from a and map elements - so you can only use an id.

    Jörg W Mittag : Actually, the fragment in the question is XHTML 1.1, which means that `name` is not just deprecated, it's plain illegal.
    Paul Dixon : Well spotted, I missed that he was using 1.1 - will amend answer
    R. Bemrose : I'm assuming 1.1 still has the name attribute for the input tag, though... I don't have time to check it at the moment.
    R. Bemrose : I should explain why I assume it still have the name attribute for input: radio buttons all have the same name, and checkboxes are also allowed to have the same name to have their values grouped together.
    Paul Dixon : sorry, yes I overstated - it's removed from a and map tags
  • I believe the modern approach is to use the id attribute, which would be evaluated as an anchor. For example, if you changed

    <h2><a name="one">Section One</a></h2>
    

    to

    <h2><a id="one">Section One</a></h2>
    

    You would still address it as page.html#one.

  • You should use the id attribute instead. Works the same way, and you don't need an artifical <a name=...>, but simply

    <h2 id="one">Section One</h2>
    
  • Yes it is outdated. You should replace with the "id" attribute.

    Quoting w3schools page:

    "The id Attribute Replaces The name Attribute HTML 4.01 defines a name attribute for the elements a, applet, frame, iframe, img, and map. In XHTML the name attribute is deprecated. Use id instead."

    http://www.w3schools.com/Xhtml/xhtml_syntax.asp

  • You can also link on a section header :

    Table of Contents

    <P>
        <A href="#section1">Introduction</A><BR>
        <A href="#section2">Some background</A><BR>
        <A href="#section2.1">On a more personal note</A><BR>
        ...the rest of the table of contents...
        ...the document body...
    
        <H2 id="section1">Introduction</H2>
        ...section 1...
    
        <H2 id="section2">Some background</H2>
        ...section 2...
    
        <H3 id="section2.1">On a more personal note</H3>
        ...section 2.1...
    
    [...]
    </P>
    

    Source: http://www.w3.org/TR/REC-html40/struct/links.html

  • name= attributes are for labeling elements in a form, and can only be used on <form> elements (input, textarea, select etc). For everything else, ID= is used. Exactly why the W3C folks thought two different ways of naming an element (with different sets of allowable characters) were needed is not readily known.

return underlying array from vector

Will the array be deallocated and if so, what is a workaround?

double * GetArrayFromVector( std::map<std::string, double> m, char ** names, int count )
{ 
    if(!names) return 0;

    std::vector<double> vec(m.size());
    for (int i=0; i<count; ++i)
    { 
       if(!names[i]) return 0;
       std::map<std::string, double>::iterator iter=m.find(name[i]);
       if(iter!=m.end())
          vec.push_back(iter->second);
       else
         return 0;   
    }

    return &vec[0]; 
}

Thanks a lot

From stackoverflow
  • Yes the array will be deallocated.

    Change the function to:

    double * GetArrayFromVector( std::map<std::string, double> m, vector<double> &vec, char ** names, int count )
    { 
         vec.clear();
         vec.reserve(m.size());
    
         for (int i=0; i<count; ++i)
         { 
             if(!names[i]) return 0;
    
             std::map<std::string, double>::iterator iter=m.find(name[i]);
             if(iter!=m.end())
                vec.push_back(iter->second);
             else
               return 0;   
         }
    
        return &vec[0]; 
    }
    

    Or else use boost::shared_array (also, look at boost::scoped_array)

    boost::shared_array<double> GetArrayFromVector( std::map<std::string, double> m, char ** names, int count )
    { 
         boost::shared_array<double> vec(new double[m.size()]);
    
         for (int i=0; i<count; ++i)
         { 
             if(!names[i]) return boost::shared_array<double>();
    
             std::map<std::string, double>::iterator iter=m.find(name[i]);
             if(iter!=m.end())
                vec[i] = iter->second;
             else
               return boost::shared_array<double>();   
         }
    
        return vec; 
    }
    
    Benoît : I am a firm believer in the shared_array idea. I would go even further, using scoped_array and forcing a swap.
    Eclipse : scoped_array is a little harder to use, but is probably a better fit in this situation (although that may depend on how the return value is used)
    Johannes Schaub - litb : i think scoped_array with using swap would be awkward here. it would "hack" move semantics into it while it does not have them. swap is just for swapping, not for transfering ownership i think. std::unique_ptr would be ideal though i think. or shared_ptr since boost does not have a public move ptr.
  • You can pass it by reference or new/delete it, but as posted your vector will be destructed after the function returns.

  • Yes, the vector (and the data store it holds) will be deallocated when the function ends.

    Why are you creating a vector? If you want an array, just create & fill one of those..

    double * GetArrayFromVector( std::map<std::string, double> m, char * names[], int count )
    { 
        if(!names) return 0;
    
        double* vec = new double[m.size()];
        int j = 0;
        for (int i=0; i<count; ++i)
        { 
           if(!names[i]) return 0;
           std::map<std::string, double>::iterator iter=m.find(name[i]);
           if(iter!=m.end())
              vec[j++] =iter->second;
           else
             return 0;   
        }
    
        return vec;
    }
    
    James Curran : You're right. I wasn't paying attention to the code, and thought it skipped over null names instead of aborting the function.
  • Yes -- it's deallocated as soon as your return from the function, because vec is declared on the stack. The std::vector destructor takes care of freeing the memory. Since you're returning the address of a deallocated array, you're going to start messing around with deallocated memory, which is a big no-no. At best, you'll crash immediately. At worst, you'll silently succeed with a big gaping security hole.

    There are two ways to fix this: (1) return the entire vector by-value, which makes a copy of the entire vector, or (2) return the vector via a reference parameter.

    Solution 1:

    std::vector<double> GetArrayFromVector(...)
    {
        ...
        return vec;  // make copy of entire vec, probably not a good idea
    }
    

    Solution 2:

    void GetArrayFromVector(..., std::vector<double> & vec)
    {
        // compute result, store it in vec
    }
    
    Kristo : +1. Great straightforward answer.
  • Yes the vector will be deallocated when the function exits (and the 'vec' variable goes out of scope). The pointer you return will therefore be invalid.

    An alternative is to allocate the array on the heap (using the 'new' operator) and return that pointer instead, but it will be the caller's responsibility to 'delete' the pointer, which is usually frown upon.

    A better alternative is to return a shared_ptr to your array.

    Eclipse : shared_ptr will not work with arrays, since they call delete, not delete[] upon destruction.
  • vec is a local variable. Its scope is limited to the GetArrayFromVector() function only. Never return the address of a local variable. Either return the array by value:

    std::vector<double> GetArrayFromVector( std::map<std::string, double> m,
                             char ** names, int count )
    

    or, pass a reference to the vector as an output parameter:

    void GetArrayFromVector( std::map<std::string, double> m,
                             char ** names, int count, 
                             std::vector<double>& vec)
    

    or, pass an output iterator:

    void GetArrayFromVector( std::map<std::string, double> m,
                             char ** names, int count, 
                             std::vector<double>::iterator vecIter)
    

    The last two will require some careful implementation of the function definition and calling though.

    Additionally, if you are game for a bit more adventure try this:

    // you'd need to change the value to use when an element is not
    // found in the map to something that suits your needs
    double pred(std::map<char*, double> haystick, char* const needle) {
        std::map<char*, double>::iterator i = haystick.find(needle);
        return i != haystick.end() ? i->second : 0; 
    }
    
    int main(int argc, char* argv[])
    {
    
       std::map<char *, double> m;
       std::vector<char *> names;
       std::vector<double> dv;
    
       m[ "Sasha" ] = 729.0;
       m[ "josh" ] = 8154.0;
    
       names.push_back("Sasha");
       names.push_back("JonSkeet");
       names.push_back("josh");
    
       // transform is part of STL's <algorithm> header
       // it takes a container (actually a range -- [begin(), end()) 
       //                  note it is a half-open range -----------^
       // as is customary for all STL algorithms, applies the function
       // or functor specified as the last parameter to each element of
       // the sequence and writes the result back to another container
       // specified via the output iterator -- the third argument
       //
       // since I have not reserved enough elements for the vector dv
       // i cannot blindly use it -- i need a back_inserter to coax
       // transform to push_back() instead of do an insert operation
       // of course, for vectors, this is costly since reallocations 
       // may happen, but let's leave the performance aside for a while!
       //
       // ok, so what about the last parameter, you ask? it has to be an
       // unary_operation. well, mostly so. but what is it that we want?
       // we want to take an iterator from the original char* (string) 
       // array and see if there's an entry in the map. if there is one
       // we retrieve the associated double value and put it in dv; else,
       // we set a default value of 0 -- change it to whatever pleases you
       // maybe a std::numeric_limit<double> if it works for you.
       // 
       // you can create a functor inheriting std::unary_function and pass
       // it on. that's the easy way out. but what if you already have a
       // comparator, a C-style find() function? will it work? yes, it will.
       // but we have to wrap it using the function adaptor std::ptr_fun
       // to make the compiler happy (after all it wants a unary_function, right?)
       // 
       // this simple scheme of things works very well, save for a last little
       // glitch. the comparator actually takes two parameters -- a what to search
       // and a where to search. and guess what -- the where to search is always 
       // fixed. so that gives us a good oppertunity to fix the first parameter to
       // our map<char*, double> which is exactly what std::bind1st() does. 
       // surprisingly, now that you've fixed one function, you no longer have a
       // binary function (one taking two arguments) but an unary one -- which is
       // just what you'd pass to transform. voila!
       std::transform(names.begin(), names.end(), std::back_inserter(dv), 
           std::bind1st(std::ptr_fun(pred), m));
    
       std::copy(dv.begin(), dv.end(), 
           std::ostream_iterator<double>(std::cout, "\n"));
    
        return 0;
    }
    

    Some interesting links:

    Also check out Boost. They have done some magic with bind()!

    dirkgently : added comments in code -- being plain lazy ;)
  • Since you know count up front, there's no benefit to using an stl vector. You could simply do this:

    double* GetArrayFromVector(std::map<char*, double> m, char** names, int count)
    {
        double* result = new double[count];
        for (int i = 0; i < count; ++i)
        { 
            if(!names[i])
            {
                delete[] result;
                return 0;
            }
            map<std::string, double>::iterator iter = m.find(name[i]);
            if(iter != m.end())
            {
                result[i] = iter->second;
            }
            else
            {
                delete[] result;
                return 0;
            }
        }
        return result;
    }
    

    Note that you are passing ownership of the allocated array to the caller. Personally, I'd try to write the code in a way that observes the RAII principle; either pass in a vector to be populated, or use a managed/shared pointer, etc. (both of these options have been suggested in other answers).

    Eclipse : However, you just removed any hope of having exception-safe code. Current C++ wisdom avoids raw pointers wherever possible.
    zweiterlinde : Agree with both comments. Personally, I prefer passing in a vector to populate, or returning a managed pointer of some kind.
    Johannes Schaub - litb : yeah, you should use std::vector here. there was a proposal to add std::dynarray for exactly this purpose (where you want to have a dynamic, fixed array) similar to variable length arrays in C but wrapped up a class. i dunno whether it was accepted. otherwise, i would use shared_array too.
  • Divide your function on two. Make your functions make just one action:
    1. fill vector from map.
    2. create array from vector.
    Don't forget to pass map by const reference.

    Main note: caller of the GetArrayFromVector is responsible for memory deallocation.

    void FillVector( const std::map<std::string, double>& m, 
                      std::vector< double >& v, 
                      char ** names, 
                      int count )
     {
           .......
     }
    
     double* createArray( const std::vector< double >& v )
     {
         double* result = new double [v.size()];
    
         memcpy( result, &v.front(), v.size() * sizeof( double ) );
    
         return result; 
     }  
    
     // and finally your function
    
     double* GetArrayFromVector( const std::map<std::string, double>& m,  
                                 char ** names, 
                                 int count )
     {
          std::vector< double > v;
          FillVector( m, v, names, count );
    
          return CreateArray( v );
     }
    
    Mykola Golubyev : @Sasha: done. I didn't test this though.
  • There is a concept call move constructors that would allow you to transfer the ownership of a resource held by a (stack-based) object to a new object. I have heard that STLport has a move_source template to accomplish this

    This will be coming to C++0x.

    In this case, you would be returning std::vector<double> instead of double*.

  • You could use std::auto_ptr smart pointer (but passing vector reference to your function is better solution).

    Example of std::auto_ptr:

    
        std::auto_ptr< std::vector<int> > getArray(int& count){  
           std::auto_ptr< std::vector<int> > vec(new std::vector<int>());  
              vec->push_back(10);  
              vec->push_back(12);  
              vec->push_back(14);  
              vec->push_back(16);  
    
              count = vec->size();  
              return vec;  
           }  
    
        int main(){  
           int size = 0;  
           std::auto_ptr< std::vector<int> > autoPtrVec = getArray(size);  
           int* ptr = &(*autoPtrVec)[0];  
    
           std::cout << "Size: " << size << std::endl;  
           for(int i=0; i<size; i++){  
              std::cout << "[" << i << "]=" << ptr[i] <<     std::endl;  
            }  
    
           return 0;  
        }  
    
  • Kinda surprised no one has mentioned vector::swap. Have the caller pass in a reference to a vector which will have its contents replaced by the function:

    void GetArrayFromVector( std::vector<double>& output, ... )
    { 
        std::vector<double> vec(m.size());
    
        // construct vec here...
    
        output.swap(vec); 
    }
    

    BTW: "GetArrayFromVector" and you pass in a map?

How often and with whom do you discuss design patterns?

At my workplace we don't often discuss design patterns, best practices, common pitfalls, etc. You're just expected to know what to do and avoid mistakes without much direction. This might be because we're an overloaded group of four full time developers however I feel in a shop of any size you should be actively discussing topics to improve your architectural, design, and implementation abilities. Unfortunately, I have no one to discuss development with outside of work and so I've actively been seeking in-person and Internet forums for that reason.

So where do you get your discussion? At work or maybe a user group?

From stackoverflow
  • When I worked with a larger team, there were a bunch of us who enjoyed having these conversations. Now that I work alone, I'll either talk to myself or my two year old. At least now I never lose an argument.

    Jens Schauder : you are lucky ... I always loose when I get into a discussion with myself.
    zodeus : He probably does to, it's with his child he wins.
    Eric H : I try to foster an environment where the discussion would be welcome based on practical realities were confronted with, but I seem to get blank stares. At least your two year old actually pays attention!
  • I guess by now some colleagues turn the light down when they are late at work, because I'm known to wander office in the evening and get into discussions for an hour or two.

    Eric H : No one else in my office seems to really care other than me, it's awesome that you get someone once in a while.
  • Me and my four colleagues have discussions and debates quite frequently. We find it very useful.

    Eric H : Was this a culture that was in place when you joined the team or was it fostered? And did you have anyone who was difficult to get to join your discussions?
    zodeus : I am the team lead, and founder of the development team and I can say it has definitely been fostered in through a collective effort of the entire team. People/Developers who cannot assimilate into the team after a while are let go. Entire teams can suffer from one bad apple.
  • Interestingly, I do all of my design pattern "discussion" here on StackOverflow.

  • At my workplace we have user groups where interested developers can attend and share ideas on a variety of development topics. Usually members of the group will volunteer to present on a particular topic. This can be done informally at lunch time, etc.

    I suggest setting up a brown bag lunch for you and your colleagues. Do some research on patterns, and give a presentation to the group to get the ball rolling, even if you don't get a big turn out, you'll learn a lot just in the process of preparing your presentation. And if you get a good turn out, turn it it into a regular thing with a new topic each meeting.

    Eric H : It sounds like you work with a large group of developers? I wonder if the number of people creates a critical mass of need that provides the impetus for a group to form.
  • There's very little collaboration where I work. Everyone is assigned to a different project so it's difficult to debate the suitability of various design patterns for any particular project. My only chance to discuss design patterns, or anything programming related, is on stackoverflow.

  • There's a more than a few different routes for me in terms of picking up new knowledge, which design patterns can vary quite a bit, IMO:

    1. Microsoft directly -> There is a patterns & practices group that have articles regularly so I try to check that every 1-2 days.

    2. Blogs -> ScottGu and Brad Abrams are a couple of big Microsoft ones that I like to read and see what is up and coming within ASP.Net that I often use. Usually a few times a week I'll check these to see along with an ASP.Net debugging. CodingHorror and Joel on Software are also handy for the odd tidbit of knowledge.

    3. Local user group -> Sometimes there are code camps, open spaces, or deep dives that are where some patterns and practices can be discussed with at least one meeting a month.

    4. My team at work -> There is a scheduled practices and patterns meeting every 2 weeks where these come up in terms of how to use this or that pattern in our big project. There can also be daily discussions if there is a pairing where folks disagree on what to do and want to try to come to consensus.

    5. StackOverflow -> This site where I have a design-patterns tag marked as interesting since I like to pick up patterns as I find them interesting.

    6. CompSci ->Computer Science Canada also has some discussion boards that can have design patterns pop up from time to time.

    Eric H : Thanks for the ScottGU and Brad Abrams blogs, going to look those over. I'm an avid reader of the FogCreek guys.
  • At work we started having a developers seminar every other week. Topics vary widely, some common themes are:

    • How to use a new library or software tool
    • New results from one of our research efforts
    • Open discussion about current development issues (such as what SCM system to use)
    • Technical talk by a guest speaker

    We keep them short, under 45 minutes, and they usually generate some good discussion. A great one we had a few months ago was a "Bug Morbidity and Mortality Review", suggested by a programmer whose fiancee is a doctor. Four or five of us wrote up brief descriptions of a bug we encountered and our process of tracking it down and fixing it.

    Often these are the sort of thing that devs might just talk about over lunch, but we have a distributed team and so providing an official forum for this sort of talk helps our cohesion. A talk on design patterns would fit right in and would probably generate some useful discussion.

How To: Change Image visibility on rdlc export

Hello Everybody, I Have an Image in rdlc report. in the report i set visibility to false I want that when I Export to PDF or EXCEL To set the Image visibility to true.

  • How do I do This?
  • Is The a way to Catch the Export Event ?
  • I don`t want to create a custom 'export'.

Thanks …

From stackoverflow
  • The only way I found out how to do it was by creating a custom 'export' function...which really is quite simple.

    Step 1: Create a parameter in your report called "ShowImage". I used the data type of String, made the prompt hidden and set a default value of "False". That way, when the report first runs in your report viewer on your page, it is not hidden.

    Step 2: Change the visibility property for your image to an expression that has the following:

    =CBool(Parameters!ShowImage.Value)
    

    Step 3: Hide the Export Controls on your report viewer. Here is my example:

    <rsweb:ReportViewer ID="ReportViewer1"  runat="server" ShowExportControls="false" Font-Names="Verdana" Font-Size="8pt">
            <LocalReport ReportPath="Report1.rdlc" >
            </LocalReport>
        </rsweb:ReportViewer>
    

    Step 4: Add a button to your page and code the custom export. You will need to be sure to set the parameter you created in step 1.

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    
        'Create ReportViewer
        Dim viewer As New Microsoft.Reporting.WebForms.ReportViewer()
        Dim p(0) As Microsoft.Reporting.WebForms.ReportParameter
    
        p(0) = New Microsoft.Reporting.WebForms.ReportParameter("ShowImage", "True")
    
        viewer.LocalReport.ReportPath = Server.MapPath("Report1.rdlc")
        viewer.LocalReport.SetParameters(p)
    
        'Export to PDF
        Dim reportContent As Byte() = viewer.LocalReport.Render("PDF", Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
    
        'Return PDF
        Me.Response.Clear()
        Me.Response.ContentType = "application/pdf"
        Me.Response.AddHeader("Content-disposition", "attachment; filename=Report.pdf")
        Me.Response.BinaryWrite(reportContent)
        Me.Response.End()
    
    End Sub
    

    That's it. May I ask, why didn't you want to create a custom export event?

N2 CMS rating user control

Hi all,

I'm currently putting together a site in the N2 CMS framework. One of things I'd wanted to do was to be able to have users rate various elements of the site using a fairly standard star rating-style user control or something similar.

Has anyone seem anything similar to this implemented within N2 specifically? Just looking for some pointers as to the best way to achieve this in N2.

Also, don't think it should make a difference, but I'm currently implementing all this using ASP MVC within N2.

Thanks in advance

Paul

From stackoverflow
  • Check the source code of BlogSvc (soon to be called AtomServer)

    Source/WebCore/Plugins/Rater/RaterService.cs

    Here is a snippet:

    public RaterModel Rate(Id entryId, float rating, User user, string ip)
    {
      LogService.Info("RateEntry: {0}, {1}, {2}", entryId, rating, ip);
    
      if (!AuthorizeService.IsAuthorized(user, entryId, AuthAction.RateEntryOrMedia))
        throw new UserNotAuthorizedException(user.Name, AuthAction.RateEntryOrMedia.ToString());
    
      if (rating < 1 || rating > 5) throw new ArgumentOutOfRangeException("Rating value must be 1 thru 5.");
    
      AtomEntry entry = AtomEntryRepository.GetEntry(entryId);
      if (entry.Raters.Contains(ip)) throw new UserAlreadyRatedEntryException(ip, entry.Id.ToString());
    
      entry.RatingCount++;
      entry.RatingSum += (int)Math.Round(rating); //temporarily force int ratings
      entry.Edited = DateTimeOffset.UtcNow;
      List<string> raters = entry.Raters.ToList();
      raters.Add(ip);
      entry.Raters = raters;
      entry = AtomEntryRepository.UpdateEntry(entry);
      return new RaterModel()
      {
        PostHref = RouteService.RouteUrl("RaterRateEntry", entryId),
        Rating = entry.Rating,
        CanRate = false,
        RatingCount = entry.RatingCount
      };
    }
    
    Chops : Helpful link, but wasn't quite what I was looking for, ideally needed something integrated with N2 better. Thanks though.

Django email

I am using the Gmail SMTP server to send out emails from users of my website.

These are the default settings in my settings.py

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'example@example.com'
EMAIL_HOST_PASSWORD = 'pwd'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
SERVER_EMAIL = EMAIL_HOST_USER
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

If I want a user to send an email, I am overriding these settings and sending the email using Django's email sending methods. When an exception occurs in the system, I receive an email from the example@example.com. Sometimes I receive an email from some logged in user. Which could also possibly mean that when a user receives an email sent from my website it has a sent address different from the actual user.

What should be done to avoid this situation?

From stackoverflow
  • Django only uses settings.DEFAULT_FROM_EMAIL when any of the mail sending functions pass None or empty string as the sender address. This can be verified in django/core/mail.py.

    When there is an unhandled exception Django calls the mail_admins() function in django/core/mail.py which always uses settings.SERVER_EMAIL and is only sent to addresses listed in settings.ADMINS. This can also be verified in django/core/mail.py.

    The only other place Django itself sends e-mails is if settings.SEND_BROKEN_LINK_EMAILS is True, then CommonMiddleware will send mail to all addresses listed in settings.MANAGERS and the e-mail sender is settings.SERVER_EMAIL.

    Therefore, the only time a regular user will receive e-mail from your site is when you call send_mail(). So, always pass a real address as the from_mail argument and you will avoid users receiving email from settings.SERVER_EMAIL or settings.DEFAULT_FROM_EMAIL.

    Side note: django-registration is at least one example of a Django pluggable that will send mail from settings.DEFAULT_FROM_EMAIL so in cases like this you need to make sure it is a proper e-mail address such as support@yoursite.com or webmaster@yoursite.com.

confused -- my XMLHttpRequest has readyState of 0 and status of 200

Hello,

I've set a breakpoint in firebug and am examining my xhr object. Its readyState is 0, its status is 200. My understanding is that if the status is 200, the request should have at least started, and the readystate should be at least 1. Can anyone explain what's going on?

I'm using jquery's $.ajax to create the xhr object, but I wouldn't think that would affect the xhr's readystate and status.

thanks,

-Morgan

From stackoverflow
  • The request is complete when readyState is 4, not when the status is 200.

    Nerdling : Status 200 can happen before you get any meaningful data back: It's just a header.
    morgancodes : But does it make sense for readystate to be 0 in that case?
    Luca Matteis : morgancodes: if you set the breakpoint too early, yes.
    morgancodes : @Luca Fair enough. Thanks. My code works now, I'll consider the mystery as-solved-as-I-need-it-to-be.
  • The w3c defines that readyState is a progressive indication of the progress of the xmlhttprequest. It transitions in order from 0->4 (Uninitialized, Open, Sent, Recieving, Loaded) and only at loaded is the content ready to read. This is the point of the property and the reason you monitor the onreadystatechange event and not status which is a response header.

    By the same spec status is supposed to raise an exception when not available (at recieving or loaded) but I imagine this is flouted by implementation for ease of use.

    Luca Matteis : "at recieving or loaded" ? Status should only be available on `loaded`.
    annakata : From the spec: "It MUST be available when readyState is 3 (Receiving) or 4 (Loaded)."

Block-level elements within display: inline-block

I'm trying to put some (vertically-stacked) display:block elements within a display:inline-block element. According to the CSS specification, the inline-block element should be a containing block, so it can have display:block elements within it and those should not affect the rest of the layout.

However, the display:block elements inside the display:inline-block elements disrupt the rest of the page; so does having nothing at all within the inline-block, or even a basic element like a paragraph; only simple text avoids disruption of the rest of the page (by disruption I mean shifting other divs down, e.g. in this case the left red block moves down a line and has a blank white space above it). I'm using Firefox 3.0.6.

<html><head><style type="text/css">
#left {
  display: inline-block;
  background: red;
  width: 20%;
  height: 100%;
}
#right {
  display: inline-block;
  background: green;
  width: 80%;
  height: 100%;
}
</style></head><body>
  <div id="left">Left</div><div id="right">Right</div>
</body></html>

The above shows as two panes, left red, right green, as expected. If I change "Right" to

<p>Right</p>

or remove it entirely, or (as I want to do) replace it with a couple of divs, I get the bad formatting.

Is this a Firefox bug, or am I doing something wrong, or are my expectations incorrect? (FWIW, IE 7 mangles them all equally, as if it doesn't understand inline-block; doesn't matter, this is an internal app. and I'm only using Firefox). I may be able to get the layout I want using float/margin, but I'd prefer not to have to do that.

From stackoverflow
  • Well display: inline-block can be a bit tricky to get cross-browser. It will require at minimum, a few hacks and, for Firefox 2, potentially an extra element.

    CSS

    .inlineBlock { display: -moz-inline-stack; display: inline-block; zoom: 1; *display: inline; }
    

    display: -moz-inline-stack is for Firefox 2. All the immediate children will need to have display: block or otherwise be block level elements. Note if you need your inline-block element to shrink wrap I think you can use display: -moz-inline-box instead.

    zoom: 1 gives hasLayout to the element (for IE 7 and below). Part 1 of the hack needed for IE7 and below compatibilty.

    *display: inline is a hack second part of the hack needed for IE7 and below compatibility.

    I occasionally need to add overflow: hidden for IE compatibility as well.

    For your specific situation i think what you need is:

    <html><head><style type="text/css">
    #left {
      display: inline-block;
      background: red;
      width: 20%;
      height: 100%;
      vertical-align: top;
    }
    #right {
      display: inline-block;
      background: green;
      width: 80%;
      height: 100%;
      vertical-align: top;
    }
    </style></head><body>
      <div id="left">Left</div><div id="right"><p>Right</p><p>Right 2</p></div>
    </body></html>
    
    Josh : FF3 should have full support.
    Josh : Sorry, misunderstood, your original question.
  • I get the bad formatting.

    You are being bitten by margin collapsing, a CSS ‘cleverness’ which is a pain as often as it is a boon. The margin of the <p> collapses outwards to become a top margin on the inline-block; this then behaves as a margin would on an ‘inline’ element would, pushing the vertical-alignment of the text line out.

    You can stop it happening by removing the margins from ‘p’ elements and using padding instead. Alternatively place a non-empty element with no top margin at the top of the block and one with no bottom margin at the bottom.

    Is this a Firefox bug

    I think possibly yes, according to the spec's:

    Margins of inline-block elements do not collapse (not even with their in-flow children).

Numeric precision issue in Excel 2007 when saving as XML

I am encountering a strange issue when saving documents in XML Spreadsheet 2003 format using Excel 2007.

It seems to randomly change numeric values such as "0.58" to "0.57999999999999996".

What's really odd is that you CANNOT see this issue when you are in Excel. You can only see this when viewing the XML data directly from a text editor.

Has anyone encountered this before? If so, is there any sort of fix or workaround?

From stackoverflow
  • Excel stores numeric data as floating point. The number to the right of the decimal place (the fractional portion) is only approximate. There is no work around, 0.58 cannot be represented as a floating point number that is exactly 0.58.

    When loading the XML file at that point you should convert the number back to floating point or better yet a fixed digit decimal class (eg. Decimal in C#).

  • The number 0.58 IS the same number as 0.57999999999999996. That is to say, the difference is 0, or yet another way to say the same, the numbers are equal.

    Now, you might disagree, if you are using "regular" highschool math. Excel doesn't, and computers in general do not. They use a finite set of bits. The exact representation of 0.58 in binary uses an infinite set of bits, so you lose some of those bits.

    bitstream : The problem is that these numbers are used for financials. These fractions of a cent result in values that aren't 100% accurage UNLESS we perform operations to round up to two decimal places. What's really odd is that this problem isn't consistent.
    bitstream : ... but I understand what you are saying. Thanks for explaining this.
    MSalters : Doesn't matter for financials either, really. They should be counting in cents anyway.
  • The key is that Excel stores numbers as base 2 floating point numbers. Most decimal fractions cannot be represented as base 2 floating point numbers.

    Some answers have stated that "0.58 cannot be represented by floating point". This is not correct since 0.58 can be represented by base 10 floating point numeric types such as the .NET Decimal type - of course this does you no good since you cannot change the underlying type used for numbers in Excel.

    Excel always displays numbers in the formula bar rounded to 15 significant digits of precision. So, this number shows up as 0.58 in the formula bar even though it is not "exactly" 0.58 - and cannot be exactly 0.58 because of the limitations of Excel's underlying numeric type.

    You might try turning on Precision As Displayed (in Excel 2007 this is found under Excel Options -> Advanced -> When calculating this workbook: -> Set precision as displayed) - it may or may not cause Excel to round this particular number when saving to XML, but it would at least give you more consistent results. Just be careful since Precision As Displayed will round numbers already stored in numeric cells (it is not undoable), as well as rounding the results of calculations (this part is undoable since turning it off will recalculate without rounding). Precision as displayed will round based on the number format, so a number format of "0.00" will cause it to round to two decimal places - but most decimal fractions are not representable by Excel's base 2 number system so 0.58 might still get you the same thing when written to XML. Numbers formatted as "General" will be rounded to 15 significant digits of precision with Precision As Displayed turned on.

How can I start MS Office Word from .NET without Add-ins?

I'm using MS Office 2003 PIA to create a MS Word document from c#.

ApplicationClass officeApplication = new ApplicationClass();

Is there any way to specify that I don't want any office add-ins to be loaded using this method?

EDIT:

I know that one can do this via command line so I'm pretty sure there must be a way to do it from code:

"C:\Program Files\Microsoft Office\Office11\Winword.exe" /a
From stackoverflow
  • Try this

    System.Diagnostics.Process.Start(
      @"C:\Program Files\Microsoft Office\Office11\Winword.exe", 
      @"/a");
    
    Andrew Jackson : Thanks, but I specifically want to use the PIA as above.
  • This code unload the AddIns

    officeApplication.AddIns.Unload(false);
    

    Edited:

    When you need to mix the process start and possibility to use the office "application" interface, you need the Marshal.GetActiveObject command.
    Example :

            //startup without plugins
            System.Diagnostics.Process.Start(
                @"Winword.exe",
                @"/a");
            //give a time for startup
            Thread.Sleep(2000);
            //attach to office
            Application officeApplication = (Application)Marshal.GetActiveObject("Word.Application");
    
    Andrew Jackson : Is there a way to stop them loading in the first place? I'm trying to avoid the startup performance hit when customers have lots of add-ins. I need to start word quickly, do some processing and close it again.
    Avram : @Andrew ,see at my update.
    Andrew Jackson : Ah, Thank you. Thats what I am looking for!

Securing a PHP file manager from its users

Hello everyone, I'm developing a photo sharing web site using the CodeIgniter PHP framework. The idea is that people could upload their photos, manage them (through some sort of file browser which allows them to create subfolders, drag files around, etc) and edit them (some basic things like resizing, rotating and cropping to start with, and later on, I'll add some advanced features).

I've already implemented a third party authentication solution for CI (Redux Authentication 2 Beta) and I'm now integrating a JS/PHP file manager (AjaxExplorer), but the problem is that the PHP backend for managing files (moving, copying, etc) is trusting too much on the user input from the ajax calls. For instance, it's doing things like this (simplified for the sake of clarity):

move_uploaded_file($_FILES['upload']['tmp_name'], $root.$username.$_POST['destination_dir']);

As you can see, there are obvious security concerns as it blindly accepts whatever path the user throws in! I can already see someone sending something like "../AnotherUser/" as the $_POST['destination_dir'] value.

My question is: What's the best way to "sandbox" a user, in order to only allow him to manage his own data? Do I just validate+filter the inputs, hoping to catch every attempt of intrusion? Are there any libraries/packages dedicated to address this specific issue?

I think this problem must be somehow solved in any (mature enough) project, which gives its users the power of managing their files through a web browser, so I expected to find some clear guidelines around this (as there are a lot about SQL Injection, XSS, CSRF, etc) but I guess I'm not using the right keywords.

From stackoverflow
  • I'm not sure what your destination_dir looks like, but what I thought of was assigning directories keys, and then getting the directory based on that key. For example:

    //$_POST['destination_dir'] = '4hg43h5g453j45b3';
    *_query('SELECT dir FROM destinations WHERE key = ? LIMIT 1'); //etc.
    

    However you have to predefine keys before hand. Another alternative could be the opposite: md5/sha1 the input and use that as the destination_dir, then store that key in the database with the associated label.

  • There are no library's that I know of.
    However in your particular example, strip all (back)slashes and dots from the string and then append a slash to the end of it, that way the user can't change folders.

    $destdir = str_replace(array('.', '/', '\\'), '', $_POST['destination_dir']); 
    $destdir .= "/";
    
    bobince : String with all invalid characters gets mapped to the server root folder.
    fandelost : Thanks for the answer, however AFAIK dots, slashes and backslashes are all acceptable characters for naming a folder, at least in the *NIX world.
    fandelost : Not so true bobince, since I can prepend a path, but I won't be using this solution anyway.
  • What's the best way to "sandbox" a user, in order to only allow him to manage his own data?

    Allow any filenames/directory names the user wants, but simply don't use them on the server side filesystem. Instead, write the path names into a database with a primary key, and use the primary key as a filename like ‘34256.dat’ in a flat storage directory (or even as a BLOB in the database if you prefer). Then serve up via a download script or URL rewrite to make the desired filename appear in the URL.

    Sanitising incoming filenames is hard. Detecting ‘..’ is only the beginning. Too-long filenames; too-short filenames; combinations of leading and trailing dots; combinations of leading and trailing whitespace; the different directory separators of different platforms; characters that are invalid on some platforms; control characters; Unicode characters and the environment-specific ways of addressing them; ADSs; filenames (‘.htaccess’) or extensions (‘.php’, ‘.cgi’) that might be ‘special’ to your web server; Windows's reserved filenames...

    You can spend a lifetime tracking down funny little quirks of filepath rules on various platforms, or you can just forget it and use the database.

    fandelost : Thanks for the answer bobince! It's a good solution, but I'm concerned about portability of the data, since doing a simple backup of the files would imply running some script first to reverse the naming scheme, and if my database ever gets compromised or corrupted, I'd lose the dir's tree structure.
    Pim Jager : Good solution. @fandelost, then make sure you backup both database and files
    fandelost : I'm sorry to took so long to respond. I've finally resigned "AjaxExplorer" and built my own file managing solution, based on bobince's advice, using a database to store everything related to the files, but not touching them after they're uploaded outside the web root. I've also restricted the 'name' field for each one to a limited set of characters, and I won't be using nested folders, I instead use a single level of grouping (just to avoid the reference mess).
    Sander Versluys : hmm i had my doubts because you create a database dependency but on the other hand, it's easier to query a database than a filesystem for searching/sorting purposes and it's more secure...