Nematolah's shared items

Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

Tuesday, July 20, 2010

Google Font Preview lets you play with Web Fonts

Google Font Preview lets you play with Web Fonts:


googlefontpreview

Google Font Preview is a new way to play with Google's Web Fonts API. The API is already dead-easy to use: you just include a single line of text in your Web page source code, and you can use fonts in your CSS.


But that's 'ease of use' defined in web developer terms... What about the designer types who don't always feel like messing around with code just to see what stuff looks like on the screen? While they can always go for something fancy like Type Folly (which I really do like), sometimes that can be a bit of overkill. Type Folly pulls fonts from paid services as well as Google's free one, and gives you a ton of options.


For the times when you just want to play around with a couple of sliders and be sure you're working with freely available fonts only, Google Font Preview is just what the doctor ordered. As you can see, you can set whatever text you want to play with since your playing field is just a Firefox text area (spell check works, and apparently 'Hmm' is not a real word). You get sliders for playing with letter, word and line spacing, you can transform the text (capitalize, uppercase, lowercase), see what it looks like with a shadow, and apply most other CSS3 options. The tool is decidedly newbie-friendly, so you won't see terms like 'kerning' or 'leading' but only 'letter spacing' or 'line spacing'.



The code you've generated is always at the bottom of the window, so once you're happy with the results you can just copy and paste it into your own page.

Cassandra: Predicting the Future of NoSQL


Cassandra: Predicting the Future of NoSQL:

cassandra_ajax_bummer.jpgWhen Twitter announced a few weeks ago that it would not be using Cassandra for tweet storage, there was a flurry of 'I told you so's' from NoSQL skeptics. The folklorist in me found that rather amusing, as Cassandra in Greek mythology was cursed with the ability to see the future. But poor Cassandra could convince no one to believe her predictions, including a rather grim one about a Trojan Horse. The tech blogger in me figured, however, she should probably have a better grasp of Cassandra and NoSQL than just my knowledge of Homer.

SQL RDBMS BBQ

SQL and relational databases have long been the solution standard for data storage and retrieval. But new web applications that are being built today don't necessarily fit into this older schema. There are new demands on databases, not simply in terms of scalability, but also in terms of availability and unpredictability. In response, a number of new databases have been developed, loosely categorized as NoSQL.

Although the name sounds like a repudiation of SQL, it doesn't mean 'no SQL never ever.' It means 'not only SQL,' and offers a far more flexible and targeted response to database management.

NoSQL OMG


In a great summary of the NoSQL movement on Heroku's blog, Adam Wiggins gives the following examples of NoSQL usage:


  • Frequently-written, rarely read statistical data (for example, a web hit counter) should use an in-memory key/value store like Redis, or an update-in-place document store like MongoDB.
  • Big Data (like weather stats or business analytics) will work best in a freeform, distributed db system like Hadoop.
  • Binary assets (such as MP3s and PDFs) find a good home in a datastore that can serve directly to the user's browser, like Amazon S3.
  • Transient data (like web sessions, locks, or short-term stats) should be kept in a transient datastore like Memcache
  • If you need to be able to replicate your data set to multiple locations (such as syncing a music database between a web app and a mobile device), you'll want the replication features of CouchDB.
  • High availability apps, where minimizing downtime is critical, will find great utility in the automatically clustered, redundant setup of datastores like Cassandra and Riak.

  • Oh, Grow Up


    In a recent article on NoSQL in SD Times, Forrester analyst Mike Gualtieri says that NoSQL is 'not a substitute for a database; it can augment a database. For transaction types of processing, you still need a database. You need integrity for those transactions. For storing other data, we don't need that consistency. NoSQL is a great way to store all that extra data.' This cautious sort of approach - use NoSQL for 'extra data' but use SQL for the real stuff - is pretty common.


    It does allow people to take small steps towards NoSQL implementation. 'Don't migrate your existing production data,' suggests Wiggins, 'instead, use one of these new datastores as a supplementary tool.'


    This hesitation is understandable; the legacy of relational databases is substantial. In an interview with ReadWriteWeb, Nati Shalom, CTO of GigaSpaces spoke of the history of databases, with the financial sector being among the first to hit a wall, so to speak with scalability. The rise of social networking and the read/write web, alongside cloud technologies, has vastly reshaped our needs for and demands on database architecture as well as information retrieval.


    Shalom argues that the technology behind NoSQL is sound and will provide the solutions for addressing some of these issues. Nevertheless, he says, NoSQL still requires two things: better implementation and more maturity.

    What the future holds for NoSQL and for database management remains to be seen. There's a Cassandra joke to be made there, I'm sure.

    BlackBerry 6's WebKit-based browser bests the competition in a good 'ol standards showdown

    -- It would be great because we all know how bad the current browser is. But this does not show speed.

    BlackBerry 6's WebKit-based browser bests the competition in a good 'ol standards showdown: "
    BlackBerry 6's WebKit-based browser bests the competition in a good 'ol speed showdown

    It's been almost a year since RIM picked up Torch Mobile and locked its newly acquired division in a closet, telling those coders to not come out until BlackBerry had a world-class browser. Early tests from Salomondrin, the self-described '007 of the Phone World,' indicates that those tired engineers can now finally go home and get some sleep. The new WebKit-based browser, a part of BlackBerry OS 6.0, managed a score of 208 on the Acid HTML5 tests, measuring browser compliance and performance. Meanwhile the iPhone 4 scored 185 and HTC's Incredible pulled down 151. Mind you, benchmark performance doesn't always equate to real-world browser responsiveness, but regardless this is good news for CrackBerry addicts. The only question now is: when will they get their fix?



    Update: The browsers were run through a suite of tests, and the above scores were actually from The HTML5 Test!

    Entanglement is an engaging, HTML5-powered Time-Waster

    -- Have some fun with HTML5 - this is actually a very fun mind bending game... take a few minutes to get the hang of it.

    Entanglement is an engaging, HTML5-powered Time-Waster:


    entanglement

    I am really enjoying watching HTML5 come into its own and mature into a full-fledged platform for video, Web apps, and now some games, too. Entanglement is an HTML5-driven puzzle game, and it feels just like Flash.


    It's a simple brain teaser. You start with a hexagon in the middle of the board. An orange line comes out of that hexagon and touches another hexagon right next to it. That other hexagon shows several possible paths that the orange line could take, depending on how you connect it. You can rotate the second hexagon using the mouse wheel or arrow keys. Once you hit the space bar or click the mouse button, the orange line 'flows' into it, and the path becomes longer. You now get another hexagon to rotate and connect.


    The goal is to make the path as long as you can without going back to the source point, allowing the path to cross itself, or touching the side of the board. My record is 23. Post your (undoubtedly higher) records below!

    Entanglement is an engaging, HTML5-powered Time-Waster originally appeared on Download Squad on Tue, 20 Jul 2010 13:00:00 EST. Please see our terms for use of feeds.

    Monday, July 19, 2010

    How To Use CSS3 Media Queries To Create a Mobile Version of Your Website

    -- important article for any mobile web developer to learn!

    How To Use CSS3 Media Queries To Create a Mobile Version of Your Website:

    CSS3 continues to both excite and frustrate web designers and developers. We are excited about the possibilities that CSS3 brings, and the problems it will solve, but also frustrated by the lack of support in Internet Explorer 8. This article will demonstrate a technique that uses part of CSS3 that is also unsupported by Internet Explorer 8. However, it doesn’t matter as one of the most useful places for this module is somewhere that does have a lot of support — small devices such as the iPhone, and Android devices.

    In this article I’ll explain how, with a few CSS rules, you can create an iPhone version of your site using CSS3, that will work now. We’ll have a look at a very simple example and I’ll also discuss the process of adding a small screen device stylesheet to my own site to show how easily we can add stylesheets for mobile devices to existing websites.

    [Offtopic: by the way, did you already get your copy of the Smashing Book?]

    Media Queries

    If you have ever created a print stylesheet for a website then you will be familiar with the idea of creating a specific stylesheet to come into play under certain conditions – in the case of a print stylesheet when the page is printed. This functionality was enabled in CSS2 by media types. Media Types let you specify a type of media to target, so you could target print, handheld and so on. Unfortunately these media types never gained a lot of support by devices and, other than the print media type, you will rarely see them in use.

    The Media Queries in CSS3 take this idea and extend it. Rather than looking for a type of device they look at the capability of the device, and you can use them to check for all kinds of things. For example:

    • width and height (of the browser window)
    • device width and height
    • orientation – for example is a phone in landscape or portrait mode?
    • resolution

    If the user has a browser that supports media queries then we can write CSS specifically for certain situations. For example, detecting that the user has a small device like a smart phone of some description and giving them a specific layout. To see an example of this in practice, the UK web conference dConstruct has just launched their website for the 2010 conference and this uses media queries to great effect.

    Dconstruct-desktop-crop in How To Use CSS3 Media Queries To Create a Mobile Version of Your Website

    The dConstruct 2010 website in Safari on a desktop computer

    Dconstruct-iphone in How To Use CSS3 Media Queries To Create a Mobile Version of Your Website

    The dConstruct 2010 website on an iPhone

    You can see from the above example that the site hasn’t just been made smaller to fit, but that the content has actually been re-architected to be made more easy to access on the small screen of the device. In addition many people might think of this as being an iPhone layout – but it isn’t. It displays in the same way on Opera Mini on my Android based phone – so by using media queries and targeting the device capabilities the dConstruct site caters for all sorts of devices – even ones they might not have thought of!

    Using Media Queries to create a stylesheet for phones

    To get started we can take a look at a very simple example. The below layout is a very simple two column layout.

    Example-browser-crop in How To Use CSS3 Media Queries To Create a Mobile Version of Your Website

    A very simple two column layout

    To make it easier to read on a phone I have decided to linearize the entire design making it all one column, and also to make the header area much smaller so readers don’t need to scroll past the header before getting to any content.

    The first way to use media queries is to have the alternate section of CSS right inside your single stylesheet. So to target small devices we can use the following syntax:

     @media only screen and (max-device-width: 480px) {

    }

    We can then add our alternate CSS for small screen and width devices inside the curly braces. By using the cascade we can simply overwrite any styles rules we set for desktop browsers earlier in our CSS. As long as this section comes last in your CSS it will overwrite the previous rules. So, to linearize our layout and use a smaller header graphic I can add the following:

     @media only screen and (max-device-width: 480px) {
    div#wrapper {
    width: 400px;
    }

    div#header {
    background-image: url(media-queries-phone.jpg);
    height: 93px;
    position: relative;
    }

    div#header h1 {
    font-size: 140%;
    }

    #content {
    float: none;
    width: 100%;
    }

    #navigation {
    float:none;
    width: auto;
    }
    }

    In the code above I am using an alternate background image and reducing the height of the header, then setting the content and navigation to float none and overwriting the width set earlier in the stylesheet. These rules only come into play on a small screen device.

    Example-phone in How To Use CSS3 Media Queries To Create a Mobile Version of Your Website

    My simple example as displayed on an iPhone

    Linking a separate stylesheet using media queries

    Adding the specific code for devices inline might be a good way to use media queries if you only need to make a few changes, however if your stylesheet contains a lot of overwriting or you want to completely separate the styles shown to desktop browsers and those used for small screen devices, then linking in a different stylesheet will enable you to keep the CSS separate.

    To add a separate stylesheet after your main stylesheet and use the cascade to overwrite the rules, use the following.

    <link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="small-device.css" />

    Testing media queries

    If you are the owner of an iPhone, Android device or other device that has a browser which supports media queries you can test your CSS yourself. However you will need to upload the code somewhere in order to view it. What about testing devices you don’t own and testing locally?

    An excellent site that can help you during the development process is ProtoFluid. This application gives you a form to enter your URL – which can be a local URL – and view the design as if in the browser on an iPhone, iPad or a range of other devices. The screenshot below is the dConstruct site we looked at earlier as seen through the iPhone view on ProtoFluid.

    Dconstruct-protofluid-crop in How To Use CSS3 Media Queries To Create a Mobile Version of Your Website

    The dConstruct 2010 website in ProtoFluid

    You can also enter in your own window size if you have a specific device you want to test for and know the dimensions of it’s screen.

    To use ProtoFluid you need to slightly modify the media query shown earlier to include max-width as well as max-device-width. This means that the media query also comes into play if the user has a normal desktop browser but using a very tiny window.

     @media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {

    }

    After updating your code to the above, just refresh your page in the browser and then drag the window in and you should see the layout change as it hits 480 pixels. The media queries are now reacting when the viewport width hits the value you entered.

    You are now all ready to test using ProtoFluid. The real beauty of ProtoFluid is that you can still use tools such as FireBug to tweak your design, something you won’t have once on the iPhone. Obviously you should still try and get a look at your layout in as many devices as possible, but ProtoFluid makes development and testing much simpler.

    Note that if you don’t want your site to switch layout when someone drags their window narrow you can always remove the max-width part of the query before going live, so the effect only happens for people with a small device and not just a small browser window.

    Retrofitting an existing site

    I have kept the example above very simple in order to demonstrate the technique. However this technique could very easily be used to retrofit an existing site with a version for small screen devices. One of the big selling points of using CSS for layout was this ability to provide alternate versions of our design. As an experiment I decided to take my own business website and apply these techniques to the layout.

    The desktop layout

    The website for my business currently has a multi-column layout. The homepage is a little different but in general we have a fixed width 3 column layout. This design is a couple of years old so we didn’t consider media queries when building it.

    Edgeofmyseat-browser-crop in How To Use CSS3 Media Queries To Create a Mobile Version of Your Website

    My site in a desktop browser

    Adding the new stylesheet

    There will be a number of changes that I need to make to linearize this layout so I’m going to add a separate stylesheet using media queries to load this stylesheet after the current stylesheet and only if the max-width is less than 480 pixels.

     <link rel="stylesheet" type="text/css" media="only screen and (max-width: 480px), only screen and (max-device-width: 480px)" href="/assets/css/small-device.css" />

    To create my new stylesheet I take the default stylesheet for the site and save it as small-device.css. So this starts life as a copy of my main stylesheet. What I am going to do is go through and overwrite certain rules and then delete anything I don’t need.

    Shrinking the header

    The first thing I want to do is make the logo fit nicely on screen for small devices. As the logo is a background image this is easy to do as I can load a different logo in this stylesheet. I also have a different background image with a shorter top area over which the logo sits.

     body {
    background-image: url(/img/small-bg.png);
    }

    #wrapper {
    width: auto;
    margin: auto;
    text-align: left;
    background-image: url(/img/small-logo.png);
    background-position: left 5px;
    background-repeat: no-repeat;
    min-height: 400px;
    }

    Linearizing the layout

    The next main job is to linearize the layout and make it all one column. The desktop layout is created using floats so all I need to do is find the rules that float the columns, set them to float: none and width:auto. This drops all the columns one under another.

     .article #aside {
    float: none;
    width: auto;
    }

    Tidying up

    Everything after this point is really just a case of looking at the layout in ProtoFluid and tweaking it to give sensible amounts of margin and padding to areas that now are stacked rather than in columns. Being able to use Firebug in ProtoFluid makes this job much easier as my workflow mainly involves playing around using Firebug until I am happy with the effect and then copying that CSS into the stylesheet.

    Edgeofmyseat-protofluid-crop in How To Use CSS3 Media Queries To Create a Mobile Version of Your Website

    Testing the site using ProtoFluid

    Testing in an iPhone

    Having created my stylesheet and uploading it I wanted to check how it worked in a real target device. In the iPhone I discovered that the site still loaded zoomed out rather than zooming in on my nice readable single column. A quick search on the Safari developer website gave me my answer – to add a meta tag to the head of the website setting the width of the viewport to the device width.

      <meta name="viewport" content="width=device-width" />

    After adding the meta tag the site now displays zoomed in one the single column.

    Edgeofmyseat-phone in How To Use CSS3 Media Queries To Create a Mobile Version of Your Website

    The site as it now displays on an iPhone

    This was a very simple retrofit to show that it is possible to add a mobile version of your site simply. If I was building a site from scratch that I would be using media queries on, there are definitely certain choices I would make to make the process simpler. For example considering the linearized column orders, using background images where possible as these can be switched using CSS – or perhaps using fluid images.

    Our desktop layout features a case studies carousel on the homepage, this wasn’t easy to interact with on a touch screen device and so I checked using JavaScript if the browser window was very narrow and didn’t launch the carousel. The way this was already written meant that the effect of stopping the carousel loading was that one case study would appear on the screen, which seems a reasonable solution for people on a small device. With a bit more time I could rewrite that carousel with an alternate version for users of mobile devices, perhaps with interactions more suitable to a touch screen.

    More resources

    This is a relatively new technique but already there are some excellent tutorials on the subject of media queries. If you know of others then please post them in the comments.

    Providing support for Media Queries in older browsers

    This article covers the use of media queries in devices that have native support. If you are only interested in supporting iPhone and commonly used mobile browsers such as Opera Mini you have the luxury of not needing to worry about non-supporting browsers. If you want to start using media queries in desktop browsers then you might be interested to discover that there are a couple of techniques available which use JavaScript to add support to browsers such as Internet Explorer 8 (and lower versions) and Firefox prior to 3.5. Internet Explorer 9 will have support for CSS3 Media Queries.

    More inspiration

    To see more interesting use of Media Queries have a look at Hicksdesign where Jon Hicks has used Media Queries to not only provide a better experience for mobile device users, but also for regular web browser users with smaller windows. Also, have a look at Simon Collison’s website and Ed Merritt’s portfolio for other examples of this technique.

    Try it for yourself

    Using Media Queries is one place you can really start to use CSS3 in your daily work. It is worth remembering that the browsers that support media queries also support lots of other CSS3 properties so your stylesheets that target these devices can also use other CSS3 to create a slick effect when viewed on an iPhone or other mobile device. If you have implemented media queries on your site, or try this technique after reading this article, let us know in the comments.

    14 Light and Easy to Use Open-Source Content Management Systems

    -- This is a great list if you want to get started with a CMS and don't know where to look!

    14 Light and Easy to Use Open-Source Content Management Systems:

    An all singing and all dancing CMS (who uses all of there features anyway?) is not always the best option for every web design project, sometimes all you need is something with a little less punch, something with a smaller learning curve and something that is really, really light.

    All of the CMSes below can be regarded as ‘light’, that’s not to say they are lightweights, but what they are is a simpler system, for you and your clients, to manage content.

    And best of all? All of these CMSes are open-source.

    Frog CMS

    Frog CMS
    Frog CMS simplifies content management by offering an elegant user interface, flexible templating per page, simple user management and permissions, as well as the tools necessary for file management.
    Frog is unique because of its simple templating code. Because it uses PHP directly, there is no need to learn yet another scripting language.
    Frog requires PHP5, a MySQL database or SQLite 3 with PDO, and a web server (Apache with mod_rewrite is highly recommended). It is distributed under the GNU General Public License version 3.
    Frog CMS HomepageDocumentation

    Frog CMS Admin Screenshot

    Frog CMS

    GetSimple CMS

    GetSimple CMS
    GetSimple is an open source CMS that is loaded it with features that every website needs, but with nothing it doesn't. It utilizes the speed and convenience of XML, a best-in-class UI and with one of the easiest learning curve of any simple CMS out there.
    GetSimple is an open-source project licensed under the GNU GENERAL PUBLIC LICENSE.
    GetSimple CMS HomepageDocumentation

    GetSimple Admin Screenshot

    GetSimple CMS

    Stacey

    Stacey
    Stacey is a very very lightweight content management system. It needs no database setup or installation files, simply drop the application on a server and it runs. The content is managed by creating folders and editing text files, so, no login screens, nor is there an admin interface.
    Stacey stores all of its content using flat text files & folders rather than a traditional database. So installation is as simple as copying the application files onto your server. No install file, no database setup and it will run on any standard php server.
    Stacey HomepageDocumentation

    Stacey Admin Screenshot

    Stacey

    Symphony

    Symphony
    Symphony leverages open standards like XML and XSLT, and good old XHTML and CSS. Even the admin interface employs the widely-used jQuery library, so extension developers don’t have to learn a whole new framework when extending the back end.
    Symphony is open source software, adopting the ultra-permissive MIT/X11 license.
    Symphony HomepageDocumentation

    Symphony Admin Screenshot

    Symphony

    Pixie

    Pixie
    Pixie is not out to compete with any other site management tool, there main goal is to keep Pixie so simple that even your Grandma could use it!
    It uses the latest web standards so whatever site you build, it's accessible to all your visitors and is search engine friendly and you will love the fact that all you need to know is CSS to customise your site.
    Pixie has been released under the GNU General Public License v3.
    Pixie HomepageDocumentation

    Pixie Admin Screenshot

    Pixie

    Radiant CMS

    Radiant CMS
    Radiant is an open source CMS designed for small teams that has been built from the ground up to be as simple as possible, featuring an elegant administrative interface that centers around three key components: pages, snippets, and layouts.
    It has a special macro language (similar to HTML) called Radius which makes it easy to include content from other pages, iterate over page children, and display content conditionally.
    Radiant CMS HomepageDocumentation (via GitHub)”>

    Radiant Admin Screenshot

    Radiant CMS

    SkyBlueCanvas

    SkyBlueCanvas
    SkyBlueCanvas Lightweight CMS is an open source, free content management system written in php and built specifically for small web sites. It has been custom-built for those instances when more robust systems like Joomla, WordPress and Drupal are too much horsepower.
    SkyBlueCanvas includes a lot of the same basic abilities as more robust systems but in a simpler form. The software is not meant to be all things to all users but it does offer features you expect like a familiar Plugin API, Extensibility and skinnability.
    SkyBlueCanvas HomepageDocumentation

    SkyBlueCanvas Admin Screenshot

    SkyBlueCanvas

    sNews

    sNews
    sNews is a completely free, standards compliant, PHP and MySQL driven Content Management System. It is extremely lightweight, simple and customizable. It's easy to install, and easy to use via a simple web interface. sNews consists of only one core engine file, one independent template file and its accompanying CSS stylesheet file, plus an .htaccess file that makes all URLs search engine friendly.
    sNews HomepageDocumentation

    sNews Admin Screenshot

    sNews

    Zotonic

    Zotonic
    Zotonic is a fast, easy to use and open source CMS. Its extensible, flexible and has been built from the ground up with rich internet applications and web publishing in mind.
    It can also work as a framework that is easy to extend and adapt for your specific use.
    Zotonic is released under the Open Source Apache2 license, which gives you the possibility to use it and modify it in every circumstance.
    Zotonic HomepageDocumentation

    Zotonic Admin Screenshot

    Zotonic

    CushyCMS

    CushyCMS
    CushyCMS is a Content Management Systems (CMS) that is truly simple. It's free for unlimited users, unlimited changes, unlimited pages and unlimited sites.
    It's built from the ground up with ease of use in mind – for both content editors and designers. It's such a simple CMS that it takes less than 3 minutes for a web designer to implement. No PHP or ASP required for this CMS. If you can add CSS classes to HTML tags then you can implement CushyCMS. It's also a hosted CMS, so no installation or maintenance is needed either.
    CushyCMS Homepage

    CMS Made Simple

    CMS Made Simple
    CMS Made Simple is an open source ( GPL) package, built using PHP that provides website developers with a simple, easy to use utility to allow building small-ish (dozens to hundreds of pages), semi-static websites.
    CMS Made Simple HomepageDocumentation

    PageLime

    PageLime
    PageLime is a hosted Content Management System (CMS) for designers, web agencies, and web developers. It allows you to manage text, images, and documents on your site by logging into a web-app that's hosted on our servers. The best part is that it doesn't matter where your site is hosted, it doesn't matter whether you use PHP, Java, or ASP (or no scripting platform), and you don't have to make a single change to your site architecture.
    It is free to use for up to three registered sites, for anything more it costs $19 (50 sites) and $69 (unlimited sites)
    PageLime HomepageDocumentation

    PageLime Admin Screenshot

    PageLime

    CMS from Scratch

    CMS from Scratch
    CMS from Scratch is a quick, easy, and open-source solution that lets web designers give their customers a web site they can edit themselves.
    With CMS from Scratch you can turn a flat HTML page into one that your client can update in minutes – with absouletly no database or programming knowledge. It has been designed to let you chop up existing pages, or templates, saving chunks as includes, which the Editor may edit, without being able to mess up core markup. Some includes will only appear on one page, whereas others may be re-used on several pages. CMS from Scratch makes it easy to create all kinds of includes.
    CMS from Scratch HomepageDocumentation

    Zimplit CMS

    Zimplit CMS
    Zimplit is extremely lightweight, simple, customizable and open-source. It's very easy to install, and easy to use via a simple web interface and it consists of only one core engine file.
    It has no admin area, all you have to do is log in and you can live edit on-site. Simple as that!
    Zimplit CMS HomepageDocumentation

    Multithreading For Performance

    Multithreading For Performance: "

    [This post is by Gilles Debunne, an engineer in the Android group who loves to get multitasked. — Tim Bray]

    A good practice in creating responsive applications is to make sure your main UI thread does the minimum amount of work. Any potentially long task that may hang your application should be handled in a different thread. Typical examples of such tasks are network operations, which involve unpredictable delays. Users will tolerate some pauses, especially if you provide feedback that something is in progress, but a frozen application gives them no clue.

    In this article, we will create a simple image downloader that illustrates this pattern. We will populate a ListView with thumbnail images downloaded from the internet. Creating an asynchronous task that downloads in the background will keep our application fast.

    An Image downloader

    Downloading an image from the web is fairly simple, using the HTTP-related classes provided by the framework. Here is a possible implementation:

    static Bitmap downloadBitmap(String url) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance('Android');
    final HttpGet getRequest = new HttpGet(url);

    try {
    HttpResponse response = client.execute(getRequest);
    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
    Log.w('ImageDownloader', 'Error ' + statusCode + ' while retrieving bitmap from ' + url);
    return null;
    }

    final HttpEntity entity = response.getEntity();
    if (entity != null) {
    InputStream inputStream = null;
    try {
    inputStream = entity.getContent();
    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
    return bitmap;
    } finally {
    if (inputStream != null) {
    inputStream.close();
    }
    entity.consumeContent();
    }
    }
    } catch (Exception e) {
    // Could provide a more explicit error message for IOException or IllegalStateException
    getRequest.abort();
    Log.w('ImageDownloader', 'Error while retrieving bitmap from ' + url, e.toString());
    } finally {
    if (client != null) {
    client.close();
    }
    }
    return null;
    }

    A client and an HTTP request are created. If the request succeeds, the response entity stream containing the image is decoded to create the resulting Bitmap. Your applications' manifest must ask for the INTERNET to make this possible.

    Note: a bug in the previous versions of BitmapFactory.decodeStream may prevent this code from working over a slow connection. Decode a new FlushedInputStream(inputStream) instead to fix the problem. Here is the implementation of this helper class:

    static class FlushedInputStream extends FilterInputStream {
    public FlushedInputStream(InputStream inputStream) {
    super(inputStream);
    }

    @Override
    public long skip(long n) throws IOException {
    long totalBytesSkipped = 0L;
    while (totalBytesSkipped < n) {
    long bytesSkipped = in.skip(n - totalBytesSkipped);
    if (bytesSkipped == 0L) {
    int byte = read();
    if (byte < 0) {
    break; // we reached EOF
    } else {
    bytesSkipped = 1; // we read one byte
    }
    }
    totalBytesSkipped += bytesSkipped;
    }
    return totalBytesSkipped;
    }
    }

    This ensures that skip() actually skips the provided number of bytes, unless we reach the end of file.

    If you were to directly use this method in your ListAdapter's getView method, the resulting scrolling would be unpleasantly jaggy. Each display of a new view has to wait for an image download, which prevents smooth scrolling.

    Indeed, this is such a bad idea that the AndroidHttpClient does not allow itself to be started from the main thread. The above code will display 'This thread forbids HTTP requests' error messages instead. Use the DefaultHttpClient instead if you really want to shoot yourself in the foot.

    Introducing asynchronous tasks

    The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. Let's create an ImageDownloader class which will be in charge of creating these tasks. It will provide a download method which will assign an image downloaded from its URL to an ImageView:

    public class ImageDownloader {

    public void download(String url, ImageView imageView) {
    BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
    task.execute(url);
    }
    }

    /* class BitmapDownloaderTask, see below */
    }

    The BitmapDownloaderTask is the AsyncTask which will actually download the image. It is started using execute, which returns immediately hence making this method really fast which is the whole purpose since it will be called from the UI thread. Here is the implementation of this class:

    class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
    private String url;
    private final WeakReference<ImageView> imageViewReference;

    public BitmapDownloaderTask(ImageView imageView) {
    imageViewReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    // Actual download method, run in the task thread
    protected Bitmap doInBackground(String... params) {
    // params comes from the execute() call: params[0] is the url.
    return downloadBitmap(params[0]);
    }

    @Override
    // Once the image is downloaded, associates it to the imageView
    protected void onPostExecute(Bitmap bitmap) {
    if (isCancelled()) {
    bitmap = null;
    }

    if (imageViewReference != null) {
    ImageView imageView = imageViewReference.get();
    if (imageView != null) {
    imageView.setImageBitmap(bitmap);
    }
    }
    }
    }

    The doInBackground method is the one which is actually run in its own process by the task. It simply uses the downloadBitmap method we implemented at the beginning of this article.

    onPostExecute is run in the calling UI thread when the task is finished. It takes the resulting Bitmap as a parameter, which is simply associated with the imageView that was provided to download and was stored in the BitmapDownloaderTask. Note that this ImageView is stored as a WeakReference, so that a download in progress does not prevent a killed activity's ImageView from being garbage collected. This explains why we have to check that both the weak reference and the imageView are not null (i.e. were not collected) before using them in onPostExecute.

    This simplified example illustrates the use on an AsyncTask, and if you try it, you'll see that these few lines of code actually dramatically improved the performance of the ListView which now scrolls smoothly. Read Painless threading for more details on AsyncTasks.

    However, a ListView-specific behavior reveals a problem with our current implementation. Indeed, for memory efficiency reasons, ListView recycles the views that are displayed when the user scrolls. If one flings the list, a given ImageView object will be used many times. Each time it is displayed the ImageView correctly triggers an image download task, which will eventually change its image. So where is the problem? As with most parallel applications, the key issue is in the ordering. In our case, there's no guarantee that the download tasks will finish in the order in which they were started. The result is that the image finally displayed in the list may come from a previous item, which simply happened to have taken longer to download. This is not an issue if the images you download are bound once and for all to given ImageViews, but let's fix it for the common case where they are used in a list.

    Handling concurrency

    To solve this issue, we should remember the order of the downloads, so that the last started one is the one that will effectively be displayed. It is indeed sufficient for each ImageView to remember its last download. We will add this extra information in the ImageView using a dedicated Drawable subclass, which will be temporarily bind to the ImageView while the download is in progress. Here is the code of our DownloadedDrawable class:

    static class DownloadedDrawable extends ColorDrawable {
    private final WeakReference<BitmapDownloaderTask> bitmapDownloaderTaskReference;

    public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) {
    super(Color.BLACK);
    bitmapDownloaderTaskReference =
    new WeakReference<BitmapDownloaderTask>(bitmapDownloaderTask);
    }

    public BitmapDownloaderTask getBitmapDownloaderTask() {
    return bitmapDownloaderTaskReference.get();
    }
    }

    This implementation is backed by a ColorDrawable, which will result in the ImageView displaying a black background while its download is in progress. One could use a “download in progress” image instead, which would provide feedback to the user. Once again, note the use of a WeakReference to limit object dependencies.

    Let's change our code to take this new class into account. First, the download method will now create an instance of this class and associate it with the imageView:

    public void download(String url, ImageView imageView) {
    if (cancelPotentialDownload(url, imageView)) {
    BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
    DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
    imageView.setImageDrawable(downloadedDrawable);
    task.execute(url, cookie);
    }
    }

    The cancelPotentialDownload method will stop the possible download in progress on this imageView since a new one is about to start. Note that this is not sufficient to guarantee that the newest download is always displayed, since the task may be finished, waiting in its onPostExecute method, which may still may be executed after the one of this new download.

    private static boolean cancelPotentialDownload(String url, ImageView imageView) {
    BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);

    if (bitmapDownloaderTask != null) {
    String bitmapUrl = bitmapDownloaderTask.url;
    if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) {
    bitmapDownloaderTask.cancel(true);
    } else {
    // The same URL is already being downloaded.
    return false;
    }
    }
    return true;
    }

    cancelPotentialDownload uses the cancel method of the AsyncTask class to stop the download in progress. It returns true most of the time, so that the download can be started in download. The only reason we don't want this to happen is when a download is already in progress on the same URL in which case we let it continue. Note that with this implementation, if an ImageView is garbage collected, its associated download is not stopped. A RecyclerListener might be used for that.

    This method uses a helper getBitmapDownloaderTask function, which is pretty straigthforward:

    private static BitmapDownloaderTask getBitmapDownloaderTask(ImageView imageView) {
    if (imageView != null) {
    Drawable drawable = imageView.getDrawable();
    if (drawable instanceof DownloadedDrawable) {
    DownloadedDrawable downloadedDrawable = (DownloadedDrawable)drawable;
    return downloadedDrawable.getBitmapDownloaderTask();
    }
    }
    return null;
    }

    Finally, onPostExecute has to be modified so that it will bind the Bitmap only if this ImageView is still associated with this download process:

    if (imageViewReference != null) {
    ImageView imageView = imageViewReference.get();
    BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
    // Change bitmap only if this process is still associated with it
    if (this == bitmapDownloaderTask) {
    imageView.setImageBitmap(bitmap);
    }
    }

    With these modifications, our ImageDownloader class provides the basic services we expect from it. Feel free to use it or the asynchronous pattern it illustrates in your applications to ensure their responsiveness.

    Demo

    The source code of this article is available online on Google Code. You can switch between and compare the three different implementations that are described in this article (no asynchronous task, no bitmap to task association and the final correct version). Note that the cache size has been limited to 10 images to better demonstrate the issues.

    Future work

    This code was simplified to focus on its parallel aspects and many useful features are missing from our implementation. The ImageDownloader class would first clearly benefit from a cache, especially if it is used in conjuction with a ListView, which will probably display the same image many times as the user scrolls back and forth. This can easily be implemented using a Least Recently Used cache backed by a LinkedHashMap of URL to Bitmap SoftReferences. More involved cache mechanism could also rely on a local disk storage of the image. Thumbnails creation and image resizing could also be added if needed.

    Download errors and time-outs are correctly handled by our implementation, which will return a null Bitmap in these case. One may want to display an error image instead.

    Our HTTP request is pretty simple. One may want to add parameters or cookies to the request as required by certain web sites.

    The AsyncTask class used in this article is a really convenient and easy way to defer some work from the UI thread. You may want to use the Handler class to have a finer control on what you do, such as controlling the total number of download threads which are running in parallel in this case.


    Sunday, July 18, 2010

    Seven Must-See Videos and Presentations for Web App Developers

     


    via Smashing Magazine Feed by Louis Lazaris on 7/18/10

    Smashing-magazine-advertisement in Seven Must-See Videos and Presentations for Web App DevelopersSpacer in Seven Must-See Videos and Presentations for Web App Developers
     in Seven Must-See Videos and Presentations for Web App Developers  in Seven Must-See Videos and Presentations for Web App Developers  in Seven Must-See Videos and Presentations for Web App Developers
    In previous video roundups, we've collected together some interesting videos and presentations from a variety of speakers discussing topics covering usability, graphic design, CSS frameworks, web standards, and more. In this small roundup, we've included seven videos that we think would be of great interest to web app developers in particular, with less focus on design and standards.
    These presentations are a little more technically heavy than ones we've featured in the past, but we think they're worth every minute. Check them out, and be sure to comment to include links to any related videos that you feel are worth mentioning.
    [Offtopic: by the way, did you know that there is a Smashing eBook Series? Book #1 is Professional Web Design, 242 pages for just $9,90.]

    Speed Up Your JavaScript

    Speaker: Nicholas C. Zakas
    As an interpreted language, JavaScript is filled with hidden performance issues that conspire to slow down your code and ruin the user experience. Learn exactly what is fast, what is slow, and what you can do to squeeze that last bit of performance out of your JavaScript code.

    Notable Quotes:
    "The problem is that JavaScript is slow… And the secondary problem is that people notice that it's slow, because a lot of the web is about perceived performance. If your [code] is slow and people perceive it to be slow, then you're in a lot of trouble."
    "Really the issue is, browsers aren't going to help you with your code. They don't care that your code is running slow, they're not going to do anything to adapt for it. So really, if something has to be done to speed up your code, it pretty much has to be done by you."
    Series of articles by the author on the same topic:
    Further Info:

    HTML 5 and Internet Explorer 9

    Speaker: Giorgio Sardo
    Giorgio Sardo talks about HTML5, CSS3, SVG, and fast JavaScript support coming in the Internet Explorer 9 platform. His presentation includes demos showcasing the latest code, providing best practices on how to make web application standards compliant, fast and interoperable across browsers.
    This is a humorous presentation that will be of interest to front-end developers who want to create cutting-edge applications while keeping up with the latest developments in web standards.

    Notable Quotes:
    "How many of you are still on IE6? You're more than welcome to leave the room now."
    "Microsoft is committed to web standards. And I'm very serious when I say this. [audience laughter] It's not a joke!"
    "Our job as browser vendors is to make sure that we give you a professional implementation of HTML5, something you can rely on, something that, if you start building your application today, in one year from now it will not break just because the standard changes."
    Further Information:

    Introduction to HTML 5

    Speaker: Brad Neuberg
    If you want to know what's new in HTML 5 but haven't had a chance to do much reading on the topic yet, this video by Brad Neuberg provides a solid introduction to HTML 5's most powerful capabilities and features. In this presentation he discusses five aspects of the HTML5 spec: (1) Canvas and SVG; (2) HTML5 Video; (3) The Geolocation API; (4) The HTML5 database and application cache; and (5) Web Workers.
    This is a great video and a must-see for anyone that wants to start building powerful web apps using HTML5's newest features.

    Notable Quotes:
    "One of the things that's really unique about HTML5 is it [allows you to] drop SVG right into a normal HTML page, so it really makes SVG a core part of HTML."
    "Currently, video is complicated, and it's outside your control... In 2009 video really should be a part of the browser... HTML5 now gives you a video tag that really works very similar to the image tag, so you don't have to have very complicated objects or plugins — video just works."
    "Using all this JavaScript... we can end up not writing apps great, that end up freezing the browser, causing it to run slowly... HTML 5 gives you something called Web Workers, and this lets you run JavaScript in the background in such a way that it won't 'hose' or kill the browser."
    Further Information:

    eCSStender: the 'jQuery of CSS'

    Speaker: Aaron Gustafson
    In this video, Aaron Gustafson discusses an overview of his new JavaScript library along with demos and example code to demonstrate how it can be used. Along the way, Gustafson includes some interesting points on the history of the HTML and CSS specs. He also discusses the library's compatibility with IE6 and CSS3 selectors.
    Ecss in Seven Must-See Videos and Presentations for Web App Developers
    Notable Quotes:
    "You can use [eCSStender] for patching older browsers... basically standardizing implementations across browsers."
    "What the extension in the case of border-radius is doing is actually figuring out what it is that it needs to do and then building the implementation that the browser wants... It greatly simplifies the design process."
    Further Information:

    10 Things I Learned From the jQuery Source

    Speaker: Paul Irish
    This is a unique, informative, and entertaining screencast from one of the web's best JavaScript developers. Irish is funny and down-to-earth while he reveals some cool little nuggets that he's discovered from examining the jQuery source. The screencast is a remake of Irish's presentation at the recent Texas JavaScript Conference.

    Notable Quote:
    "Everyone... considers jQuery this black box, and this black box is this magical box that just works — it has this great API, we use it, we don't have to worry about how it actually works internally, we're not going to look inside the source and figure it out. But I'm here to say, if you do, I think you're going to benefit from it."
    Further Information:

    Steve Huffman on Lessons Learned at Reddit

    Speaker: Steve Huffman
    A presentation from Future of Web Apps Miami 2010 by reddit co-founder Steve Huffman. Huffman explains some of the most important lessons he and his development team learned while reddit was growing. This is a highly technical presentation that concludes with some audience Q&A.

    Notable Quotes:
    "If this talk had existed when we were starting reddit, I think it would have saved me a lot of time, so I hope something in here isn't obvious to you now and you can learn from it."
    "I dreaded my phone ringing. Nobody would call me for any other reason than to tell me Reddit was down. Even my mother would call me and say, 'Steve, your website's not working.' Thanks mom."
    "Wasting disc and memory is totally fine if you're not making your users wait. Discs and memory are far cheaper than annoying your customers."
    Further Information:

    The Paradox of Choice

    Speaker: Barry Schwartz
    This video, on the surface, is not about web development in any way, but provides an interesting viewpoint on "freedom of choice" and may well remind app and website designers to avoid bombarding users with choices and complicated options. Some very controversial insights are given here into what makes people happier, providing some food for thought for those concerned about usability.

    Notable Quotes:
    "The way to maximize freedom, is to maximize choice. The more choice people have, the more freedom they have, and the more freedom they have, the more welfare they have. This I think is so deeply embedded in the water supply, that it wouldn't occur to anyone to question it."
    "[Having too much choice] produces paralysis rather than liberation. With so many options to choose from, people find it very difficult to choose at all."
    Further Information:



    How to Scale Code Deployment Like Twitter Does

    Learning the way smart people develop is always important

     


    via ReadWriteWeb by Chris Cameron on 7/15/10

    murder_jul10.jpgThere is a fundamental problem that Internet startups face when they begin to grow: scalability. It is imperative to be able to not only handle large flows of data from usage, but also to deploy changes and upgrades to your software across multiple servers as fast as possible. Twitter faces this challenge every day as its farm of servers grows, and today the San Francisco-based company is open sourcing its solution to the deployment problem for all to use.

    Named "Murder" after the collective noun used to describe a group of crows (I guess "Gaggle," "Flock" or any other bird plural didn't sound as nice), this part-Python, part-Ruby tool allows lighting fast code deployments across large groups of servers. Twitter engineer Larry Gadea says it took what once was a 40 minute deploy and shortened it just 12 seconds - an impressive feat, no doubt.

    So how did Twitter accomplish this?
    Murder is built on top of BitTornado, a version of BitTorrent modified to include advanced functionality. Gadea says they have tweaked the app to better function in the unique environment that exists in a datacenter, including "low-latency access to servers, high bandwidth, no NAT/Firewall issues, no ISP traffic shaping, only trusted peers, etc."
    By integrating this tool with their existing deployment app, Capistrano, Twitter was able to shorten code deployments by 99.5%. Anyone can checkout Murder on GitHub right now and start thinking of ways to use it with their servers. It is important for young companies - not just those with several servers - to think about scalability before it becomes an issue. Projects like Murder are making that process much easier for first time entrepreneurs and system administrators.
    Photo by Flickr user rebeccakoconnor.