<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>json &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/json/</link>
	<description>Feed of posts on WordPress.com tagged "json"</description>
	<pubDate>Fri, 05 Sep 2008 04:38:16 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Day Three - geek time]]></title>
<link>http://creativefragments.wordpress.com/?p=26</link>
<pubDate>Wed, 03 Sep 2008 23:13:12 +0000</pubDate>
<dc:creator>creativesnippets</dc:creator>
<guid>http://creativefragments.wordpress.com/?p=26</guid>
<description><![CDATA[If man is 5 then code is 6.  That&#8217;s what the bones had in store for me today.  Luckily, I]]></description>
<content:encoded><![CDATA[<p>If man is 5 then code is 6.  That's what the bones had in store for me today.  Luckily, I've been working on a AJAJ/flash mp3 player website. I say AJAJ instead of AJAX as I pull data from the (A)synchronous request that is JSON formated.  It's light weight (as opposed to XML) and easy to wrap up and push out. BTW, this is all web lingo but it's what sites like Facebook, Gmail and even Wordpress heavily rely on to make their interfaces smooth and oh so 21 century. For me it has put the 'Wah' back in website as it adds a hold bag of tricks for making bubbly quick transforming websites.</p>
<p>Back to my little pet project. I already have playlists being generated according to folder structure, but a random playlist link had been on my mind as some days I just don't want to pick an album to listen to.  To do that a list of the entire directory structure has to be made to pick from randomly.  From my days of running web servers and web servers that had octopus like directories full of mp3s I knew I needed a <a href="http://en.wikipedia.org/wiki/Recursion_(computer_science)" target="_blank">recursive algorithm</a> to sweep through all of those folders.  The concept of a recursive algorithm is the same in all programming languages, the function calls itself again once the same set of steps are needed for a level down.  It should also not run forever, which is an easy feat when doing this type of logic.  I did some research and found some examples, but these errored out as they needed far to large amounts of memory to be allocation temporaryily.  With some tweaking I came up with:</p>
<pre>function directoryToArray($directory,$recursive=true,$include_directories_in_list=true){
 $array_items=array();
  if($handle=opendir($directory)){
   while (false!==($file=readdir($handle))){
    if($file!="."&#38;&#38;$file!=".."){
     if(is_dir($directory."/".$file)){
      if($recursive &#38;&#38;){
       $narr=directoryToArray($directory."/".$file,$recursive);
       foreach($narr as $nr){
        array_push($array_items,$nr);
       }
      }
      if($include_directories_in_list){
       array_push($array_items,preg_replace("/'/","\\'",($directory."/".$file)));
      }
     }else{
      if(preg_match("/mp3$/i",$file)){
       array_push($array_items,preg_replace("/'/","\\'",($directory."/".$file)));
      }
     }
    }
   }
   closedir($handle);
  }
 return $array_items;
}</pre>
<p>Sort, simple and it got the done in a reasonable amount of time.  I added the javascript to tie it together and a random playlist was doable.  Now I have to deal with the whole UTF-8 charater set.  That's for next time.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[JSON Framework 2.1]]></title>
<link>http://skuggdev.wordpress.com/?p=58</link>
<pubDate>Sat, 30 Aug 2008 17:23:12 +0000</pubDate>
<dc:creator>Stig Brautaset</dc:creator>
<guid>http://skuggdev.wordpress.com/?p=58</guid>
<description><![CDATA[I just uploaded JSON framework version 2.1 to Google Code. Changes since the 2.0 series, big and sma]]></description>
<content:encoded><![CDATA[<p><img src="http://skuggdev.files.wordpress.com/2008/08/json211.png" alt="JSON2.1.png" border="0" width="371" height="144" align="right" />I just uploaded <a href="http://json-framework.googlecode.com/files/JSON_2.1.dmg">JSON framework version 2.1</a> to Google Code. Changes since the 2.0 series, big and small, include:</p>
<p><strong>iPhone-ready SDK</strong><br><br />
The disk image now contains a Custom SDK. This makes the framework a lot easier to use on the iPhone. See the INSTALL file in the dmg for details.</p>
<p><strong>New sortKeys option</strong><br><br />
This makes the generator produce objects with the keys in sorted order. This is very handy when you need to compare JSON documents.</p>
<p><strong>Leopard only</strong><br><br />
From version 2.1 onwards this framework is Leopard-only. Stick with version 2.0 if you need Tiger support. Some of the Objective-C 2.0 features are just <em>too shiny</em> to pass up for long. Some of the changes related to this:</p>
<ul>
<li><strong>64 bit support</strong><br><br />
The JSON framework now supports 64 bit. Moved to use the 10.5 64-bit compatibility typedefs for basic types.</p>
</li>
<li><strong>Garbage collection support</strong><br><br />
The framework is now built with garbage collection support by default.</p>
</li>
<li><strong>Syntesized properties</strong><br><br />
Killed some redundant code by moving to use synthesised properties.</p>
</li>
<li><strong>Fast iteration loops</strong><br><br />
Update the code to use Objective-C 2.0 fast iteration loops in a couple of places.
</li>
</ul>
<p><strong>Removed deprecated methods</strong><br><br />
Removed the option-taking category methods, as promised in v2.0. Rewrote some tests to use the underlying object instead.</p>
<p><strong>New error code</strong><br><br />
Introduced a new error code for clarity: EEOF - premature end of input.</p>
<p><strong>Documentation target</strong><br><br />
Added a documentation target to integrate the documentation into Xcode automatically.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Pesterfish]]></title>
<link>http://abaff.wordpress.com/?p=54</link>
<pubDate>Thu, 28 Aug 2008 22:27:16 +0000</pubDate>
<dc:creator>pos.thum.us</dc:creator>
<guid>http://abaff.wordpress.com/?p=54</guid>
<description><![CDATA[In my research for what data serialisation models to use to represent our repository data, I was hun]]></description>
<content:encoded><![CDATA[<p>In my research for what data serialisation models to use to represent our repository data, I was hunting down some XML to JSON conversions. For the past few months I have been hell-bent on using JSON as the representations, because it is far more useful to me than chunks of XML, and closer to the nature of the data being represented. As <a href="http://steve-yegge.blogspot.com/2008/06/rhinos-and-tigers.html">Steve Yegge says</a>:<br />
"XML is better if you have more text and fewer tags. And JSON is better if you have more tags and less text".</p>
<p>The problem is however that almost all the tools out there in Fedora-Commons land are biased towards XML, and have (almost) never heard of JSON. So if I only have some basic Dublic Core and a gob of JSON in my objects, that is not going to help very much. The other extreme, and undoubtedly "The Right Way To Do It" is to have a lovely shiny Content Model and define everything in an ontology and RDF and then my brain melts. And we want to migrate our repository sooner rather than later and don't have the time to remain in la-la land designing around our navels forever.</p>
<p>So now I am swinging back the other way and have decided to <a href="http://people.w3.org/~liam/blog/?p=8">store the data in the objects as simple stupid XML with a smattering of tags</a>, and at least have some XSLT disseminators to provide more buzzword compliant FOAF, Bibliontology, OAI-ORE etc. And JSON. Via XSLT. Which brings me to http://code.google.com/p/xml2json-xslt/ which pointed at http://badgerfish.ning.com/ and finally to <a href="http://www.smullyan.org/files/pesterfish.py">pesterfish</a>:</p>
<p>Jacob Smullyan wrote a related Python model, pesterfish, which he describes as: "a quick Python module which is uses the same xml object model as the dominant xml module in the Python world, elementtree; Some elementtree implementation (there are several) and simplejson are required. BTW, elementtree stores namespaces in Clark notation: {http://www.w3.org/1999/xhtml}br and so does this.". pesterfish also lets you round trip XML through it without any data loss.</p>
<p>I like the ElementTree API. Lots. It is very elegant and a joy to work with, especially if you have ever had to use any other XML APIs like DOM or SAX that makes you want to gnaw your own arm to the bone out of frustration. So the chance of having an ElementTree-like way of consuming XML in Javascript expecially appeals to me. (well until http://en.wikipedia.org/wiki/E4X E4X is widely supported)</p>
<p>And so, with this long-winded preamble I would like to present pesterfish on AppEngine:</p>
<p>http://epoz.appspot.com/pesterfish/</p>
<p>You can POST an XML file to it, and it will return the pesterfish application/json.</p>
<p>Or you can <a href="http://epoz.appspot.com/pesterfish/?in=http://www.w3schools.com/XML/note.xml">call it with a URL</a> for the XML file specified in the 'in=' parameter, like this.</p>
<pre>http://epoz.appspot.com/pesterfish/?in=http://www.w3schools.com/XML/note.xml</pre>
<p>It turns this XML:</p>
<pre>&#60;note&#62;

<span>	</span>&#60;to&#62;Tove&#60;/to&#62;

<span>	</span>&#60;from&#62;Jani&#60;/from&#62;

<span>	</span>&#60;heading&#62;Reminder&#60;/heading&#62;

<span>	</span>&#60;body&#62;Don't forget me this weekend!&#60;/body&#62;

&#60;/note&#62;</pre>
<p>Into this JSON:</p>
<pre>{"text": "\n\t", "tag": "note", "children":
 [{"text": "Tove", "tail": "\n\t", "tag": "to"},
 {"text": "Jani", "tail": "\n\t", "tag": "from"},
 {"text": "Reminder", "tail": "\n\t", "tag": "heading"},
 {"text": "Don't forget me this weekend!
", "tail": "\n", "tag": "body"}]}</pre>
<p>And it supports JSONP:</p>
<pre>http://epoz.appspot.com/pesterfish/?in=http://www.w3schools.com/XML/note.xml&#38;callback=some_callback</pre>
<p>Thanks Jacob!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[c# loves JSon, or at least likes it]]></title>
<link>http://bradrover.wordpress.com/?p=14</link>
<pubDate>Mon, 25 Aug 2008 15:27:51 +0000</pubDate>
<dc:creator>bradrover</dc:creator>
<guid>http://bradrover.wordpress.com/?p=14</guid>
<description><![CDATA[Dare recently posted about the state of REST, JSon, and .Net:
The only problem is how to deal with s]]></description>
<content:encoded><![CDATA[<p>Dare <a href="http://www.25hoursaday.com/weblog/2008/08/24/RESTfulJSONBringingRESTAndRPCCloserTogether.aspx">recently posted</a> about the state of REST, JSon, and .Net:</p>
<blockquote><p>The only problem is how to deal with statically typed languages like C# and Java. These languages need the types of the objects that application will consume from a Web service defined up front. So if we could just figure out how to come up with service documents for JSON services that included the notion of a class definition, we could pretty much have our cake and eat it to with regards to getting the ease of use of an RPC system while building a RESTful service.</p></blockquote>
<p>This isn't that hard:</p>
<p>- get Damien Katz latest <a href="http://incubator.apache.org/couchdb/">CouchDB</a> from svn.</p>
<p>- get <a href="http://james.newtonking.com/pages/json-net.aspx">JSon.Net</a></p>
<p>- learn LINQ</p>
<p>With JSon.net you can easily convert objects from c# to JSon, and vice versa, then POST those directly to CouchDB with their REST API. In practice, its mildly more difficult than that. Consider you have a c# object called Product. This can be easily converted to JSon using JSon.net and POSTed to couchdb. Voila, object database using REST api.</p>
<p>To de-serialize this to CouchDB you need to be able to accept some standard fields for ID and Revision  that CouchDB is going to add to any document you POST. In JSon:</p>
<pre>{"_id":"00018aefcce4a579c8dc263ebae00638","_rev":"550271284", ...</pre>
<p>To handle this you need to extend your c# Product type. This can be done easily with generics:</p>
<pre>   // documents have at a minimum the _id and _rev properties
    public abstract class Document : IDocument
    {
        public string _id { get; set; }
        public string _rev { get; set; }
        public virtual string ToJSon()
        {
            return JavaScriptConvert.SerializeObject(this);
        }

    }

   public class Entity&#60;T&#62; : Document
    {
        public T entityobject;

        public static Entity FromJSon(string json)
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.MissingMemberHandling = MissingMemberHandling.Ignore;

            StringReader sr = new StringReader(json);
            Entity&#60;T&#62; docObject = (Entity&#60;T&#62;)serializer.Deserialize(sr, typeof(Entity&#60;T&#62;));
            return docObject;
        }
    }</pre>
<p>So now we have something that can read and write an object from couchdb using REST and return a strongly typed object. Some helper methods are embedded to get/set JSon. In the serialized result, the c# object itself is always contained in the JSon field called "entityobject", which sits beside the ID and Revision root level elements.</p>
<pre>{
   "_id":"00018aefcce4a579c8dc263ebae00638",
   "_rev":"550271284",
   "entityobject":{
      "SKU":"my SKU",
      "ISBN":"",
      "Cost":2.1e+01,
      "Price":8.99899999999999948841e+01,
...</pre>
<p>This all sounds great but what I find even more enticing is to leave the results in a generic JSon object (similar in spirit to XmlNode), and run LINQ queries to extract the fields I needed from that. JSon.Net provides JObject for this purpose, which can be bound to an asp.net MVC view:</p>
<pre>var query = from row in ViewData.Model["rows"].Children()
               orderby row.Value&#60;int&#62;("value") descending
       select new
           {
               Manufacturer = row.Value&#60;string&#62;("key"),
               Count = row.Value&#60;int&#62;("value")
           };</pre>
<p>Its not as pretty as Rails, or as elegant as Python, but it seems to make sense. And making sense is what its all about.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Dillon Chase - The Pursuit]]></title>
<link>http://crayzeejoe.wordpress.com/?p=93</link>
<pubDate>Sat, 23 Aug 2008 21:04:47 +0000</pubDate>
<dc:creator>crayzeejoe</dc:creator>
<guid>http://crayzeejoe.wordpress.com/?p=93</guid>
<description><![CDATA[
&#8220;What do YOU Pursue?&#8221;  That&#8217;s the question Dillon asks on his latest CD that dro]]></description>
<content:encoded><![CDATA[<p style="text-align:center;"><a href="http://www.thebus-shop.com/shop.cfm?prod=462"><img class="alignnone size-full wp-image-94" src="http://crayzeejoe.wordpress.com/files/2008/08/dc.jpg" alt="" width="200" height="200" /></a></p>
<p><strong>"What do YOU Pursue?"</strong>  That's the question Dillon asks on his latest CD that dropped today called <em>"The Pursuit." </em> The first song I ever heard from Dillon was on the <em>13 Letters</em> CD from the 116 Clique, called "<em>Take 'em Back."</em>  The song was about the book of Philemon.  That's the thing about guys like Dillon Chase - the music is hot and the lyrics are all straight up exegetical!</p>
<p>Check out tha songs and download tha CD now at the following link or by clicking on the album cover above.  <a href="http://www.thebus-shop.com/shop.cfm?prod=462">http://www.thebus-shop.com/shop.cfm?prod=462</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[JSON in 5 seconds]]></title>
<link>http://stikiflem.wordpress.com/?p=3</link>
<pubDate>Fri, 22 Aug 2008 10:23:01 +0000</pubDate>
<dc:creator>stikiflem</dc:creator>
<guid>http://stikiflem.wordpress.com/?p=3</guid>
<description><![CDATA[&lt;script type=&#8221;text/javascript&#8221;&gt;
/*sample code by stikiflem
Copy and Paste all of t]]></description>
<content:encoded><![CDATA[<p>&#60;script type="text/javascript"&#62;</p>
<p>/*sample code by stikiflem</p>
<p>Copy and Paste all of these. Save as sample.html. Run in browser.<br />
*/<br />
<code>function getData(){</code></p>
<p>var sampleJSON = {<br />
// string<br />
a : 'accessing a string in json',<br />
// array<br />
b : ['obj1','im a string in an array!','three',4,'obj5'],<br />
// function<br />
c : function() {<br />
alert('im a function!');<br />
}<br />
}</p>
<p>alert(sampleJSON.a);<br />
alert(sampleJSON.b[1]);<br />
alert(sampleJSON.c());</p>
<p>}<br />
/*<br />
JSON is just pure javascript. no BS.<br />
Just remember:<br />
1. Entry inside {} are properties.<br />
2. Entry with [] is an array which can contain another array or a property.<br />
3. JSON can also carry a function (e.g. in alert #3)<br />
*/<br />
&#60;/script&#62;<br />
&#60;input type="button" value="Get JSON Sample" onClick="getData();" /&#62;</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[CouchDB Presentation at Railscamp UK]]></title>
<link>http://ijonas.wordpress.com/?p=108</link>
<pubDate>Wed, 20 Aug 2008 21:29:27 +0000</pubDate>
<dc:creator>ijonas</dc:creator>
<guid>http://ijonas.wordpress.com/?p=108</guid>
<description><![CDATA[I&#8217;ve been playing around with and kicking the tyres of CouchDB for a couple of weeks and I]]></description>
<content:encoded><![CDATA[<p>I've been playing around with and kicking the tyres of CouchDB for a couple of weeks and I'm truly excited about the project. If I was to use tags to describe CouchDB I'd use the following:</p>
<p><code>apache, opensource, documents, metadata, database, json, javascript, REST, addressability, horizontal scaling, erlang.</code></p>
<p>So I found myself at Railscamp UK on the weekend without a ruby+rails topic to really talk about during the presentations part of the camp. I'm still a noob wrt. Rails, you see. Realising that CouchDB is relevant to most web developers because most developers deal with document-based content at some point and that Ruby, Rails, and Erlang are kindda like the current bratpack (<a href="http://en.wikipedia.org/wiki/John_Hughes_(film_director)">in a John Hughes-sense</a>) of computer languages, I thought it would be a great little topic for a 15-minute presentation.</p>
<p>So I thought I share the slides and some of the code I hacked up on the weekend. First of all the slides...</p>
<p style="text-align:center;"><a href="http://www.scribd.com/doc/4916889/CouchDB-Railscamp-UK"><img class="aligncenter size-medium wp-image-113" src="http://ijonas.wordpress.com/files/2008/08/couchdb_slides.png?w=300" alt="" width="300" height="225" /></a></p>
<p style="text-align:center;"><a href="http://www.scribd.com/doc/4916889/CouchDB-Railscamp-UK" target="_blank">(click me)</a></p>
<p>You can play about with some sample code that was expanded upon after the presentation. Here's a little helper class to interface into CouchDB using JSON and HTTP:</p>
<p>[sourcecode language='ruby']<br />
require 'rubygems'<br />
require 'httparty'<br />
require 'json/pure'<br />
require 'find'</p>
<p>class CouchHack<br />
  include HTTParty<br />
  base_uri 'http://127.0.0.1:5984'<br />
  format :json</p>
<p>  def update( path, document )<br />
    options = { :body => JSON.generate(document) }<br />
    puts self.class.put(path, options )<br />
  end</p>
<p>  def get(path)<br />
    self.class.get(path)<br />
  end</p>
<p>  def create(db_path, document )<br />
    options = { :body => JSON.generate(document) }<br />
    self.class.post(db_path, options )<br />
  end</p>
<p>  def define_view(db_path, design_doc_name, views )<br />
    document = { "views" => views }<br />
    options = { :body => JSON.generate(document) }<br />
    self.class.put("#{db_path}/_design/#{design_doc_name}", options)<br />
  end<br />
end<br />
[/sourcecode]</p>
<p>Once that's in place you can use the CouchHack class by defining a view like so:</p>
<p>[sourcecode language='ruby']<br />
ch = CouchHack.new<br />
gem_views = {<br />
  "small_gems" =><br />
    {<br />
      "map" => "function(doc) { if (doc.length < 3000) emit(doc.path, doc) }",<br />
    },<br />
  "large_gems" =><br />
    {<br />
      "map" => "function(doc) { if (doc.length > 3000) emit(doc.path, doc) }",<br />
    }<br />
}<br />
ch.define_view("/railscamp", "gems", gem_views)<br />
[/sourcecode]</p>
<p>This design document, as is its known in CouchDB parleance, defines two views (think 'baked queries'), to return a list of small gems - those less than 3000 bytes - and a list of large gems - those larger than 3000 bytes.</p>
<p>So where do these gems come from and how do they end up in CouchDB ? That's what the next and last little fragment of Ruby code does.</p>
<p>[sourcecode language='ruby']<br />
Find.find('/Library/Ruby/Gems/1.8/gems/' ) do &#124;f&#124;<br />
  if File.file?(f) and f.ends_with?('.rb' )<br />
    begin<br />
      gem_contents = IO.read(f)<br />
      gem_document = { "path" => f, "length" => gem_contents.length, "content" => gem_contents }<br />
      ch.create( "/railscamp", gem_document )<br />
    rescue Exception => bang<br />
      puts "Skipping #{f}"<br />
    end<br />
  end<br />
end<br />
[/sourcecode]</p>
<p>So what happens is that the last little fragment traverses the filesystem starting at /Library/Ruby/Gems/1.8/gems/ and looks for *.rb files. When it finds one it POSTs that whole document including the file length to CouchDB, where it becomes part of the resultset of one of the pre-defined views. These views can be accessed through the following two URLs (assuming the 'railscamp' DB was used).</p>
<ul>
<li><a href="http://localhost:5984/railscamp/_view/gems/large_gems">http://localhost:5984/railscamp/_view/gems/large_gems</a></li>
<li><a href="http://localhost:5984/railscamp/_view/gems/small_gems">http://localhost:5984/railscamp/_view/gems/small_gems</a></li>
</ul>
<p>Feel free to post comments and ask questions.</p>
<p>Enjoy.</p>
<p>P.S. and if you get a chance to go to a *camp conference, GO! They're an amazing format and you'll learn soooo much!.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[[Programação]: Parse em strings JSON com Javascript]]></title>
<link>http://juliovedovatto.wordpress.com/?p=284</link>
<pubDate>Mon, 18 Aug 2008 05:24:10 +0000</pubDate>
<dc:creator>juliovedovatto</dc:creator>
<guid>http://juliovedovatto.wordpress.com/?p=284</guid>
<description><![CDATA[Estava fazendo um upload de arquivos via flash, utilizando o SWFUpload, intercambiando com o jQuery,]]></description>
<content:encoded><![CDATA[<p>Estava fazendo um upload de arquivos via flash, utilizando o <a href="http://swfupload.org/" target="_blank"><strong>SWFUpload</strong></a>, intercambiando com o <strong><a href="http://www.jquery.com" target="_blank">jQuery</a></strong>, até ai tudo bem, o problema vinha com o retorno do upload. ;S</p>
<p style="text-align:center;"><a title="JSON" href="http://www.json.org/" target="_blank"><img class="size-full wp-image-292 aligncenter" src="http://juliovedovatto.wordpress.com/files/2008/08/json_logo.gif" alt="" width="160" height="160" /></a></p>
<p>Quando terminava o upload, a aplicação retorna um código <a href="http://www.json.org/" target="_blank"><strong>JSON</strong></a>, só que o jQuery infelizmente não tem nenhuma utilidade de conveter uma String representada para <a href="http://www.json.org/" target="_blank"><strong>JSON</strong></a>. Só que ai veio uma idéia: vou utilizar um antigo e quase esquecido amigo do Javascript, o <strong><a href="http://www.w3schools.com/jsref/jsref_eval.asp" target="_blank"><strong>eval()</strong></a>.</strong> Então simplsmente fiz assim:</p>
<p>Código retornado pelo <strong>PHP</strong> (string representada):<br />
<code>{"filename":"file.ext","size":"2516582","location":"\/path\/to\/file\/file.ext"}</code></p>
<p>Solução em <strong>Javascript</strong>:<br />
<code>var response = eval( '(' + jsonString + ')' );</code></p>
<p>Só tomem cuidado com o tamanho da string em <a href="http://www.json.org/" target="_blank"><strong>JSON</strong></a> que irão retornar, o <a href="http://www.w3schools.com/jsref/jsref_eval.asp" target="_blank"><strong>eval()</strong></a><strong> </strong>é bom, mas tem que saber utilizar ele. Esta função é uma das mais básicas, porém essenciais numa linguagem de programação. ;D</p>
<p>Apreciem com moderação. ;)</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Go here:]]></title>
<link>http://grahana.wordpress.com/?p=93</link>
<pubDate>Sun, 17 Aug 2008 07:04:41 +0000</pubDate>
<dc:creator>p6</dc:creator>
<guid>http://grahana.wordpress.com/?p=93</guid>
<description><![CDATA[www.grahana.net
]]></description>
<content:encoded><![CDATA[<p><a href="http://www.grahana.net">www.grahana.net</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Facebook style ajax auto suggest/auto complete from database using ASP.NET, C#, JSON and SQL Server]]></title>
<link>http://azizulislam.wordpress.com/?p=24</link>
<pubDate>Mon, 11 Aug 2008 07:08:02 +0000</pubDate>
<dc:creator>azizulislam</dc:creator>
<guid>http://azizulislam.wordpress.com/?p=24</guid>
<description><![CDATA[Would you like to include an input that resembles the famous Apple Mail to: textfield? It would be s]]></description>
<content:encoded><![CDATA[<p>Would you like to include an input that resembles the famous Apple Mail to: textfield? It would be something similar to Facebook List Input. Basically, it’s a group of pieces or bits that can be either a box or an input. The user is able to move around between the bits by using his keyboard or his mouse. You can remove the bits by click the “x” symbol.</p>
<p><a href="http://azizulislam.files.wordpress.com/2008/08/untitled1.jpg"><img class="aligncenter size-full wp-image-26" src="http://azizulislam.wordpress.com/files/2008/08/untitled1.jpg" alt="" width="469" height="109" /></a></p>
<p>It has a auto complete feature as well. It works by caching all the results from a JSON Request and feeding them to the autocompleter object. When a item is added as a box, it’ removed from the feed array, and when the box is disposed it’s added back, so that it becomes available in the list when the user types. You’ll also be able to let it add boxes from the HTML directly. If you are interested in this amazing textboxlist, you can mail me</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[On My Mind - by J'Son and Crayzee Joe]]></title>
<link>http://crayzeejoe.wordpress.com/?p=65</link>
<pubDate>Mon, 11 Aug 2008 00:21:20 +0000</pubDate>
<dc:creator>crayzeejoe</dc:creator>
<guid>http://crayzeejoe.wordpress.com/?p=65</guid>
<description><![CDATA[On a recent album release by J&#8217;Son from the 116 Clique, he had a track (17) called &#8220;In t]]></description>
<content:encoded><![CDATA[<p>On a recent album release by J'Son from the 116 Clique, he had a track (17) called "In the Studio."  On this track, he recorded the first verse but did not have a hook or second verse and said that the listener could go ahead and write the hook and second verse.  So I did.  Here is the song, now called "On My Mind."  May God get all the glory! (click the link below or go to <a href="http://www.soundclick.com/crayzeejoe">www.soundclick.com/crayzeejoe</a> and find it there)</p>
<p><a href="http://crayzeejoe.files.wordpress.com/2008/08/on-my-mind.mp3">on-my-mind</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[When's the sailing on? Introducing genre schedules...]]></title>
<link>http://derivadow.wordpress.com/?p=503</link>
<pubDate>Sat, 09 Aug 2008 11:25:09 +0000</pubDate>
<dc:creator>Tom Scott</dc:creator>
<guid>http://derivadow.wordpress.com/?p=503</guid>
<description><![CDATA[You might find this helpful - you&#8217;ve been able to browse schedules by radio station or TV chan]]></description>
<content:encoded><![CDATA[<p>You might find this helpful - you've been able to <a href="http://www.bbc.co.uk/programmes">browse schedules</a> by <a href="http://www.bbc.co.uk/radio/programmes">radio</a> station or <a href="http://www.bbc.co.uk/tv/programmes">TV</a> channel for a while now which is great, but what if you don't care where the BBC broadcasts your favourite <a href="http://www.bbc.co.uk/programmes/genres/sport/olympics">Olympic sport</a>, <a href="http://www.bbc.co.uk/programmes/genres/music">music genre</a> or <a href="http://www.bbc.co.uk/programmes/genres/drama/scifiandfantasy">SciFi programme</a>?</p>
<p><a href="http://news.bbc.co.uk/sport1/hi/olympics/monkey/7521287.stm"><img class="alignnone size-full wp-image-504" src="http://derivadow.wordpress.com/files/2008/08/bbc-monkey.jpg" alt="" width="510" height="286" /></a></p>
<p>To help you find programmes, no matter which station or channel they are broadcast on, <a href="http://www.bbc.co.uk/programmes/developers/are">we've</a> started publishing schedules for all our genres (sport, music etc.). These views are being used as part of the <a href="http://news.bbc.co.uk/sport1/hi/olympics/default.stm">BBC's Olympics coverage</a> - specifically to drive the <a href="http://news.bbc.co.uk/sol/shared/bsp/hi/olympics2008/epg/html/epg.stm">TV schedule</a> and <a href="http://www.bbc.co.uk/programmes/b00cpqd1/episodes/2008">individual sport pages</a>. But as you might be able to guess a little bit of URL hacking gives you more. All you need to do is add <code>/schedules</code> to the end of any genre aggregation, so for example:</p>
<p>A schedule for your favourite music genre :<br />
<a href="http://www.bbc.co.uk/programmes/genres/music/classicpopandrock/schedules/">www.bbc.co.uk/programmes/genres/music/classicpopandrock/schedules</a></p>
<p>What's happening on the Olympics:<br />
<a href="http://www.bbc.co.uk/programmes/genres/sport/olympics/schedules/">www.bbc.co.uk/programmes/genres/sport/olympics/schedules</a></p>
<p>Drama on radio:<br />
<a href="http://www.bbc.co.uk/radio/programmes/genres/drama/schedules/">www.bbc.co.uk/radio/programmes/genres/drama/schedules</a></p>
<p>Or science and the environment on Radio 4:<br />
<a href="http://www.bbc.co.uk/radio4/programmes/genres/factual/sciencenatureandenvironment/schedules">www.bbc.co.uk/radio4/programmes/genres/factual/sciencenatureandenvironment/schedules</a></p>
<p>And obviously you can get this data both as HTML and as XML, JSON, YAML just by adding .xml .json or .xml to the end of the URL. So the TV coverage for sailing as XML is:</p>
<p><a href="http://www.bbc.co.uk/programmes/genres/sport/sailing/schedules.xml">www.bbc.co.uk/programmes/genres/sport/sailing/schedules.xml</a></p>
<p>Hope that helps you find your favorite programme.</p>
<h3>UPDATE</h3>
<p>As <a href="http://whomwah.com/">Duncan</a> has previously <a href="http://www.bbc.co.uk/blogs/radiolabs/2008/07/some_ical_views_onto_programme.shtml">discussed</a> on the BBC's Radio Lab blog you can also get this data in your Calendar via iCal - just add <code>.../upcoming.ics</code> to the above URL. For example:</p>
<p><a href="http://www.bbc.co.uk/programmes/genres/sport/sailing/schedules/upcoming.ics">www.bbc.co.uk/programmes/genres/sport/sailing/schedules/upcoming.ics</a></p>
<p><a href="http://www.bbc.co.uk/radio4/programmes/genres/factual/sciencenatureandenvironment/schedules/upcoming.ics">www.bbc.co.uk/radio4/programmes/genres/factual/sciencenatureandenvironment/schedules/upcoming.ics</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Ejemplo AJAX con JQuery + Struts + JSON]]></title>
<link>http://hermosodia.wordpress.com/?p=44</link>
<pubDate>Fri, 08 Aug 2008 21:41:57 +0000</pubDate>
<dc:creator>LeChuckNorris</dc:creator>
<guid>http://hermosodia.wordpress.com/?p=44</guid>
<description><![CDATA[El siguiente snippet realiza una llamada asíncrona a una url que devuelve texto en formato JSON al ]]></description>
<content:encoded><![CDATA[<p>El siguiente snippet realiza una llamada asíncrona a una url que devuelve texto en formato JSON al hacer click sobre un botón cuyo id es "idBoton" para posteriormente rellenar el select cuyo id es "idSelect".</p>
<p>[sourcecode language='jscript']<br />
$("#idBoton").click(function () {<br />
	      $.getJSON("./devuelveJSON.do,<br />
	        function(data){<br />
	          $("select[name='idSelect']").removeOption(/./);<br />
	          $.each(data.listaObjetos, function(i,objeto){<br />
	          	$("select[name='idSelect']").addOption(objeto.id, "[" + objeto.nombre + "] " );<br />
	          });<br />
	        });<br />
	});<br />
[/sourcecode]</p>
<p>Para la manipulación de Selects (del modo que se hace aquí) hay que importar un plugin de JQuery que se encuentra en la siguiente URL <a href="http://www.texotela.co.uk/code/jquery/select/">http://www.texotela.co.uk/code/jquery/select/</a>.</p>
<p>A continuación se muestra como devolver una cadena JSON desde un action de Struts. En el ejemplo  el JSON se genera a partir de un ArrayList de objetos "Objeto" (valga la redundancia). Cada objeto tiene como atributos un <em>"id"</em> y un <em>"nombre"</em>. Para la conversión de listas a cadenas JSON se usa  <a href="http://json-lib.sourceforge.net/">Json-lib</a>, una librería  java muy útil para la transformacion de beans, mapas, colecciones, arrays y XML a JSON y viceversa.</p>
<p>[sourcecode language='java']<br />
public ActionForward execute(ActionMapping mapping, ActionForm form,<br />
HttpServletRequest request, HttpServletResponse response)<br />
throws Exception {</p>
<p>response.setContentType("text/json");</p>
<p>ArrayList lista = new ArrayList();<br />
Objeto objeto =new Objeto();<br />
objeto.setId("1");<br />
objeto.setNombre("Objeto 1");</p>
<p>lista.add(objeto);</p>
<p>objeto.setId("2");<br />
objeto.setNombre("Objeto 2");</p>
<p>lista.add(objeto);</p>
<p>JSONArray jsonArray = JSONArray.fromObject(lista);</p>
<p>PrintWriter pw = response.getWriter();<br />
pw.write("({\"objetos\":" + jsonArray.toString() + "})");<br />
pw.flush();<br />
pw.close();<br />
return null;</p>
<p>}<br />
[/sourcecode]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Spring sends JSON to a guy named Ext...]]></title>
<link>http://wannabecoder.wordpress.com/?p=36</link>
<pubDate>Thu, 07 Aug 2008 07:54:34 +0000</pubDate>
<dc:creator>jollyca</dc:creator>
<guid>http://wannabecoder.wordpress.com/?p=36</guid>
<description><![CDATA[So as I said in my previous post&#8230; no more *faces. I put on my goggles and dive deeply into the]]></description>
<content:encoded><![CDATA[<p>So as I said in my previous post... no more *faces. I put on my goggles and dive deeply into the depths of Spring and ExtJS.</p>
<p>The first step is... integration (please note my avoidant personality which tend to ignore stuff like "how the f' should I code *anything* in Ext and jumps right into "ok, how should I display a grid ?"). This integration comes in two flavors - XML and JSON. From what I figure, an XML representation is larger (in terms of bytes) than a JSON representation so I tried to go the JSON way. <!--more--></p>
<p>On the Spring side some there is a small lib called <a href="http://spring-json.sourceforge.net/" target="_blank">Spring JSON View</a> which is basically a Spring view implementation. Long story short - it serializes JavaBeans to a JSON representation which is sent to the facade. Yes, of course it has more features, like form validation and stuff, but all in due time...</p>
<p>On the ExtJS side we have a JsonStore which is basically a DataStore encapsulating a proxy and a JsonReader. Here's where my stupidity kicked-in: the JSON generated by Spring looks something like<br />
<code>{"model":<br />
{"products":<br />
[{"productName":"Pretzels","skuNo":"1","productPrice":2.0},<br />
{"productName":"Arrows","skuNo":"3","productPrice":4.0},<br />
{"productName":"Nuclear warheads","skuNo":"2","productPrice":2.3}]<br />
}<br />
}</code><br />
As an absolute n00b I wondered "Ok, which is the root of the store ? Is it "products" ? Is it "model" ? Is it "model.products" ? The latter was my logical choice but it didn't work. I wandered around forums and various blogs, I even wrote an override for the JSON reader, figuring that the problem is the root.</p>
<p>After spending a few hours on this I decided to ask the forums... Turns out that this specific line in the JsonStore was a bit... wrong:<br />
<code>fields:[{name:'productName',type:'string'},{name:'skuNo',type:'string'},name:'productPrice',type:'double'}]</code><br />
Double is not an accepted type. I replaced it with "float" and everything worked like a charm</p>
<p>Never underestimate the power of your own stupidity...</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[PowerShellASP Applied: JSON Factory]]></title>
<link>http://solutionizing.wordpress.com/?p=83</link>
<pubDate>Wed, 06 Aug 2008 23:04:06 +0000</pubDate>
<dc:creator>Keith Dahlby</dc:creator>
<guid>http://solutionizing.wordpress.com/?p=83</guid>
<description><![CDATA[Now that we can use PowerShellASP with SharePoint, what can we do with it? Well without master page ]]></description>
<content:encoded><![CDATA[<p>Now that we can use <a href="http://www.powershelltoys.com/">PowerShellASP</a> <a href="http://solutionizing.net/2008/07/24/powershellasp-with-sharepoint/">with SharePoint</a>, what can we do with it? Well without master page or web part support, we can't easily integrate PoShASP content directly into the SharePoint experience. Fortunately, we can leverage PowerShell in other ways. An easy example is generating <a title="JavaScript Object Notation" href="http://json.org/">JSON</a>, perhaps from the PowerShell standby <code>Get-Process</code>:</p>
<pre>&#60;% $Response.ContentType = "application/json; charset=utf-8" %&#62;
&#60;% $Response.Cache.SetCacheability([System.Web.HttpCacheability]'NoCache') %&#62;
&#60;% $Response.Cache.SetExpires([DateTime]::MinValue) %&#62;
&#60;% if( !($n = $Request.QueryString["n"] -as [int]) ) { $n = 10 } %&#62;
{"processes":[
  &#60;% [string]::Join(",`n  ",
  (get-process &#124; sort ws -desc &#124; select -first $n &#124; foreach {
  "{'ID':$($_.ID),'Name':'$($_.Name)','WS':$($_.ws)}" })) %&#62;
]}</pre>
<p>After we set the JSON ContentType and cache policy, we try to fetch an "n" query parameter. If n is missing or not a number, we default to 10. Now we can start building our JSON object. To build our array, we use <code>System.String</code>'s static <code>Join</code> method (the backtick is PowerShell's escape character, so <code>`n</code> is a newline). <code>Join</code>'s <code>string[]</code> parameter is provided by a PowerShell pipeline that fetches our system processes, sorts by working set size, selects the top <code>$n</code> and then iterates through those process objects, returning a string of JSON with our desired properties. Note also that PoShASP seems to require an empty line at the end of the file, otherwise "]}" is ignored. Our output will look something like this:</p>
<pre>{"processes":[
  {'ID':1672,'Name':'sqlservr','WS':506028032},
  {'ID':3296,'Name':'devenv','WS':230555648},
  {'ID':4720,'Name':'w3wp','WS':181100544},
  {'ID':376,'Name':'services','WS':121995264},
  {'ID':3372,'Name':'w3wp','WS':102522880}
]}</pre>
<p>Let's save our JSON endpoint as %12%\TEMPLATE\LAYOUTS\Get-Process.json.ps1x, which we can test by visiting http://server/_layouts/Get-Process.json.ps1x?n=5. Now it's AJAX time! Since not everyone can use the ASP.NET AJAX Extensions, we'll just do it the old-fashioned way. Starting with a Content Editor Web Part on a page of your choice, set the source to the following:</p>
<pre>&#60;div id="d_procs"&#62;
&#60;img src="/_layouts/images/GEARS_AN.GIF"
  alt="Loading..." align="center" /&#62;
&#60;/div&#62;
&#60;script&#62;
function getXmlHttpRequestObject() {
 if (window.XMLHttpRequest) {
  return new XMLHttpRequest();
 } else if(window.ActiveXObject) {
  return new ActiveXObject("Microsoft.XMLHTTP");
 } else {
  document.getElementById('d_procs').innerHTML =
  'Cound not create XmlHttpRequest Object.';
 }
}

var r = getXmlHttpRequestObject();
var c = 0;
var mTimer;

function getProcs() {
 if (r.readyState == 4 &#124;&#124; r.readyState == 0) {
  r.open("GET", '/_layouts/Get-Process.json.ps1x?n=5', true);
  r.onreadystatechange = handleReceiveProcs;
  r.send(null);
 }
}

function handleReceiveProcs() {
 if (r.readyState == 4) {
  var d = document.getElementById('d_procs');
  var response = eval("(" + r.responseText + ")");
  var p = response.processes;
  var t = "&#60;table width=\"100%\"&#62;";
  t += "&#60;tr&#62;&#60;th&#62;ID&#60;/th&#62;&#60;th&#62;Name&#60;/th&#62;&#60;th&#62;WS(MB)&#60;/th&#62;&#60;/tr&#62;";
  for(i=0;i &#60; p.length; i++) {
   t += '&#60;tr&#62;&#60;td&#62;'+p[i]['ID']+'&#60;/td&#62;';
   t += '&#60;td&#62;'+p[i]['Name']+'&#60;/td/&#62;';
   t += '&#60;td align=\"right\"&#62;';
   t += (p[i]['WS']/(1024*1024.0)).toFixed(2);
   t += '&#60;/td/&#62;&#60;/tr&#62;';
  }
  t += "&#60;/table&#62;&#60;p&#62;Refresh count: "+(++c)+"&#60;/p&#62;";
  d.innerHTML = t;
  mTimer = setTimeout('getProcs();', 3000); // 3-sec refresh
 }
}

_spBodyOnLoadFunctionNames.push('getProcs');
&#60;/script&#62;</pre>
<p>I haven't put much effort into cleaning up the code, but it does the job (in FF2 and IE7, at least):<br />
<a href="http://solutionizing.files.wordpress.com/2008/08/poshasp-json-webpart.png"><img class="alignnone size-full wp-image-86" src="http://solutionizing.wordpress.com/files/2008/08/poshasp-json-webpart.png" alt="" width="280" height="210" /></a></p>
<p>With PowerShell's ease of development and specialized adapters, this is just the tip of the iceberg. What other real-time data would you find useful?</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Создание сайтов для мобильных устройств с помощью Google App Engine]]></title>
<link>http://techworkru.wordpress.com/?p=119</link>
<pubDate>Tue, 05 Aug 2008 18:32:09 +0000</pubDate>
<dc:creator>techworkru</dc:creator>
<guid>http://techworkru.wordpress.com/?p=119</guid>
<description><![CDATA[Оценивается, что на сегодняшний момент в мире насчитыв]]></description>
<content:encoded><![CDATA[<p>Оценивается, что на сегодняшний момент в мире насчитывается около 1,3 миллиардов мобильных устройств. Можно ли использовать платформу App Engine для работы с ними? Коротким ответом на этот вопрос будет - да, конечно мы можем задействовать GAE для работы с мобильным контентом. Но для того, чтобы создавать мобильные приложения, которые действительно имеют хороший пользовательский интерфейс, необходимо будет использовать алгоритм по определению возможностей мобильных устройств.</p>
<p>Определение возможностей осуществляется для двух целей:</p>
<ul>
<li>Различение мобильных и десктопных браузеров. Скорее всего вы захотите иметь различные представления сайтов для пользователей, работающих с обычных компьютеров и с мобильных устройств.</li>
<li>Отладить работу поведения сайта в каждом конкретном случае в зависимости от возможностей устройства.</li>
</ul>
<p>На персональных компьютерах различия довольно минимальны: необходимо поддерживать 3 или 4 популярных браузера, все компьютеры имеют клавиатуру и мышь, и мы можем с большой степенью вероятности утверждать, что пользователи работают с разрешением 1024x768 и выше. При сравнении характеристик мобильных устройств существуют колоссальные различия: бесконечное количество различных браузеров, разрешений экрана и устройств ввода.</p>
<p>Чтобы уверенно поддерживать работу сайта на всем этом многообразии, необходимо иметь универсальный инструмент для определения возможностей мобильных устройств. Эта статья описывает интеграцию Google App Engine и базы данных устройств <strong>DeviceAtlas</strong> от dotMobi. Почему именно DeviceAtlas?</p>
<ul>
<li>Он содержит точную и всеобъемлющую информацию. База данных DeviceAtlas включает в себя информацию из различных источников: WURFL, Volantis, ArgoGroup и прочих</li>
<li>Он достаточно быстрый - несколько тысяч запросов на умеренном аппаратном обеспечении</li>
<li>Он бесплатен для разработчиков</li>
</ul>
<p>Наша статья описывает процесс создания простейшего приложения для определения типа мобильного устройства и соответствующего ему вывода информации. Приложение будет выводить месторасположение офиса компании dotMobi в Дублине с помощью Google Maps, учитывая возможности целевого устройства:</p>
<p><img class="aligncenter" src="http://dev.mobi/files/Screenshot%20-%2029_05_2008%20,%2018_49_04.png" alt="" width="323" height="395" /></p>
<h3>Начинаем</h3>
<p>Первое, что необходимо сделать - создать как обычно каталог нового приложения Google App Engine и его конфигурационный файл app.yaml. Мы назовем наше приложение - "contact-dotmobi".</p>
<p>Далее, необходимо добавить к приложению код определения мобильных устройств. Эта статья описывает использование интерфейса API DeviceAtlas для языка Python. Достаточно положить в каталог с приложением модули библиотеки и JSON-файл с базой данных устройств:</p>
<ul>
<li> api.py - основной модуль DeviceAtlas</li>
<li>daExceptions.py -определения исключений</li>
<li>DeviceAtlas.json - данные устройств</li>
</ul>
<p>Обратите внимание, что библиотека зависит от модуля SimpleJson, который производит обработку файла данных. Так как он не включен в стандартную поставку платформы, то его необходимо добавить вручную. Наиболее простой способ это сделать - скачать его с сайта <a href="http://www.undefined.org/python/" target="_blank">http://www.undefined.org/python/</a> и поместить каталог с модулем SimpleJson в каталог нашего приложения. После этого он будет выглядеть так:<br />
<code> </code></p>
<pre>api.py
app.yaml
daExceptions.py
DeviceAtlas.json
index.yaml
simplejson</pre>
<p>Теперь необходимо задать схему URL в конфигурации приложения и иконку нашего приложения favicon.ico. Содержимое файла app.yaml:</p>
<pre><code>application: contact-dotmobi
version: 1
runtime: python
api_version: 1

handlers:
- url: /
  script: contact-dotmobi.py
- url: /favicon.ico
  static_files: favicon.ico
  upload: favicon.ico
</code></pre>
<h3>Пишем первый код</h3>
<p>Конфигурация завершена, теперь необходимо создать файл с кодом <strong>contact-dotmobi.py.</strong> Начнем со стандартных импортов:</p>
<pre><span style="font-weight:bold;color:#ff7700;">import</span> wsgiref.<span style="color:black;">handlers</span>
<span style="font-weight:bold;color:#ff7700;">from</span> google.<span style="color:black;">appengine</span>.<span style="color:black;">ext</span> <span style="font-weight:bold;color:#ff7700;">import</span> webapp
<span style="font-weight:bold;color:#ff7700;">from</span> google.<span style="color:black;">appengine</span>.<span style="color:black;">ext</span>.<span style="color:black;">webapp</span> <span style="font-weight:bold;color:#ff7700;">import</span> template</pre>
<p>Далее мы импортируем модуль DeviceAtlas:<br />
<code> </code></p>
<div class="geshifilter">
<div class="geshifilter-python" style="font-family:monospace;"><span style="font-weight:bold;color:#ff7700;">import</span> api</div>
</div>
<p>И читаем данные устройств из файла данных:<br />
<code> </code></p>
<div class="geshifilter">
<div class="geshifilter-python" style="font-family:monospace;"><span style="font-style:italic;color:#808080;"># подключаем API и читаем формат JSON</span><br />
TREEFILE = <span style="color:#483d8b;">'DeviceAtlas.json'</span><br />
da = api.<span style="color:black;">DaApi</span><span style="color:black;">(</span><span style="color:black;">)</span><br />
tree = da.<span style="color:black;">getTreeFromFile</span><span style="color:black;">(</span>TREEFILE<span style="color:black;">)</span></div>
</div>
<p>Этот код создает экземпляр интерфейса библиотеки и загружает базу данных с конфигурациями мобильных устройств. Он выполняется лишь один раз и создает доступные для всех остальных запросов объекты.</p>
<p>Теперь когда данные готовы для работы, мы можем перейти к созданию обработчика запроса:<br />
<code> </code></p>
<pre><span style="font-weight:bold;color:#ff7700;">class</span> MainPage<span style="color:black;">(</span>webapp.<span style="color:black;">RequestHandler</span><span style="color:black;">)</span>:
    <span style="font-weight:bold;color:#ff7700;">def</span> get<span style="color:black;">(</span><span style="color:#008000;">self</span><span style="color:black;">)</span>:
        <span style="color:#008000;">self</span>.<span style="color:black;">response</span>.<span style="color:black;">headers</span><span style="color:black;">[</span><span style="color:#483d8b;">'Content-Type'</span><span style="color:black;">]</span> = <span style="color:#483d8b;">'text/html'</span>
        ua = <span style="color:#008000;">self</span>.<span style="color:black;">request</span>.<span style="color:black;">user_agent</span></pre>
<p>Здесь мы просто создаем потомок класса RequestHandler, устанавливаем HTTP заголовок ответа и определяем тип браузера пользователя по переменной, полученной из запроса. Самое интересное здесь как раз и является переменная ua, значение которой мы будем передавать интерфейсу DeviceAtlas:</p>
<pre>        props = da.<span style="color:black;">getPropertiesAsTyped</span><span style="color:black;">(</span>tree, ua<span style="color:black;">)</span></pre>
<p>Это обращение приведет к поиску в данных объекта tree нашей строки с определением браузера пользователя. Метод getPropertiesAsTyped возвращает словарь значений, которые сообщают наиболее подробную информацию об устройстве пользователя. Теперь мы можем принять решение о формате вывода данных, прежде всего, является ли удаленное устройство мобильным:</p>
<pre>        mobileDevice = <span style="color:#008000;">False</span>
             <span style="font-weight:bold;color:#ff7700;">if</span> props.<span style="color:black;">has_key</span><span style="color:black;">(</span><span style="color:#483d8b;">'mobileDevice'</span><span style="color:black;">)</span>:
                         <span style="font-weight:bold;color:#ff7700;">if</span> props<span style="color:black;">[</span><span style="color:#483d8b;">'mobileDevice'</span><span style="color:black;">]</span>:
                             mobileDevice = <span style="color:#008000;">True</span></pre>
<p>Далее мы определяем, какого размера изображение мы можем вывести на экран пользователя:</p>
<pre>        mapWidth = <span style="color:#ff4500;">512</span> <span style="font-style:italic;color:#808080;"># по умолчанию максимум для Google maps </span>
        mapHeight = <span style="color:#ff4500;">512</span>

        <span style="font-weight:bold;color:#ff7700;">if</span> mobileDevice:
            mapWidth = <span style="color:#ff4500;">128</span> <span style="font-style:italic;color:#808080;"># используем, если нет информации о размерах экрана</span>
            mapHeight = <span style="color:#ff4500;">128</span>
            <span style="font-weight:bold;color:#ff7700;">if</span> props.<span style="color:black;">has_key</span><span style="color:black;">(</span><span style="color:#483d8b;">'displayWidth'</span><span style="color:black;">)</span>: <span style="font-style:italic;color:#808080;"># иначе определяем по ширине</span>
                mapWidth = mapHeight = props<span style="color:black;">[</span><span style="color:#483d8b;">'displayWidth'</span><span style="color:black;">]</span> - <span style="color:#ff4500;">25</span></pre>
<p>Так как большинство мобильных устройств имеют портретную ориентацию, мы используем ширину экрана как наименьшую величину, устанавливая его высоту такой же. Уменьшая определенное значение на 25 пикселей, с учетом различных скроллеров, мы гарантируем что изображение не будет вылазить за пределы экрана.</p>
<p>Теперь мы знаем всю необходимую для отображения информацию и готовы сформировать словарь этих параметров и передать в шаблон:</p>
<pre>        template_values = <span style="color:black;">{</span>
            <span style="color:#483d8b;">'props'</span>: props,
            <span style="color:#483d8b;">'mapWidth'</span>: mapWidth,
            <span style="color:#483d8b;">'mapHeight'</span>: mapHeight,
            <span style="color:#483d8b;">'zoom'</span>: zoom,
            <span style="color:#483d8b;">'ua'</span>: ua,
            <span style="color:black;">}</span></pre>
<h3>Шаблоны</h3>
<p>В большинстве случаев предпочтительнее генерировать разметку в формате XHTML для мобильных устройств и обычный HTML для "настоящих" компьютеров. Обычно их стандартные браузеры меньше следуют стандартам и позволяют использовать больше вольностей в разметке страниц, что позволяет создавать богатый интерфейс. В нашем случае мы хотим использовать раздельные шаблоны для мобильных и стационарных устройств:</p>
<pre>        <span style="font-weight:bold;color:#ff7700;">if</span> mobileDevice:
            <span style="color:#008000;">self</span>.<span style="color:black;">response</span>.<span style="color:black;">out</span>.<span style="color:black;">write</span><span style="color:black;">(</span>template.<span style="color:black;">render</span><span style="color:black;">(</span><span style="color:#483d8b;">'index.xhtml'</span>, template_values<span style="color:black;">)</span><span style="color:black;">)</span>
        <span style="font-weight:bold;color:#ff7700;">else</span>:
            <span style="color:#008000;">self</span>.<span style="color:black;">response</span>.<span style="color:black;">out</span>.<span style="color:black;">write</span><span style="color:black;">(</span>template.<span style="color:black;">render</span><span style="color:black;">(</span><span style="color:#483d8b;">'index.html'</span>, template_values<span style="color:black;">)</span><span style="color:black;">)</span></pre>
<p>Этот код передает параметры в шаблон, который создает ответ для устройства. Ниже приведен пример шаблона для мобильных устройств:</p>
<p><span style="color:#009900;"><span style="font-weight:bold;color:black;">&#60;?xml</span> <span style="color:#000066;">version</span>=<span style="color:#ff0000;">"1.0"</span> <span style="color:#000066;">encoding</span>=<span style="color:#ff0000;">"ISO-8859-1"</span><span style="font-weight:bold;color:black;">?&#62;</span></span><br />
<span style="color:#00bbdd;">&#60;!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"&#62;</span><br />
<span style="color:#009900;"><span style="font-weight:bold;color:black;">&#60;html</span> <span style="color:#000066;">xmlns</span>=<span style="color:#ff0000;">"http://www.w3.org/1999/xhtml"</span><span style="font-weight:bold;color:black;">&#62;</span></span><br />
<span style="color:#009900;"><span style="font-weight:bold;color:black;">&#60;head<span style="font-weight:bold;color:black;">&#62;</span></span></span><br />
<span style="color:#009900;"><span style="font-weight:bold;color:black;">&#60;title<span style="font-weight:bold;color:black;">&#62;</span></span></span>Contact dotMobi<span style="color:#009900;"><span style="font-weight:bold;color:black;">&#60;/title<span style="font-weight:bold;color:black;">&#62;</span></span></span><br />
<span style="color:#009900;"><span style="font-weight:bold;color:black;">&#60;/head<span style="font-weight:bold;color:black;">&#62;</span></span></span><br />
<span style="color:#009900;"><span style="font-weight:bold;color:black;">&#60;strong<span style="font-weight:bold;color:black;">&#62;</span></span></span>Phone: <span style="color:#009900;"><span style="font-weight:bold;color:black;">&#60;/strong<span style="font-weight:bold;color:black;">&#62;</span></span></span><br />
{% if props.uriSchemeTel %} <span style="color:#009900;"><span style="font-weight:bold;color:black;">&#60;a</span> <span style="color:#000066;">href</span>=<span style="color:#ff0000;">"tel:+35318541100"</span><span style="font-weight:bold;color:black;">&#62;</span></span>+353 (1) 854 110<span style="color:#009900;"><span style="font-weight:bold;color:black;">&#60;/a<span style="font-weight:bold;color:black;">&#62;</span></span></span> {% else %} +353 (1) 854 1100 {% endif %}<br />
<span style="color:#009900;"><span style="font-weight:bold;color:black;">&#60;img</span> <span style="color:#000066;">src</span>=<span style="color:#ff0000;">"http://maps.google.com/staticmap?center=53.348592,-6.247315&#38;amp;zoom={{zoom}}&#38;amp;maptype=mobile&#38;amp;size={{mapWidth}}x{{mapHeight}}&#38;amp;markers=53.348592,-6.247315,blued&#38;amp;key=xxx"</span> <span style="color:#000066;">width</span>=<span style="color:#ff0000;">"{{mapWidth}}"</span> <span style="color:#000066;">height</span>=<span style="color:#ff0000;">"{{mapHeight}}"</span> <span style="color:#000066;">alt</span>=<span style="color:#ff0000;">"map"</span> <span style="font-weight:bold;color:black;">/&#62;</span></span><br />
Detected UA string: {{ua}}<br />
DeviceAtlas version: {{apiRevision}}<br />
Vendor: {{props.vendor}} Model: {{props.model}&#62;</p>
<p>В этом шаблоне есть три интересные вещи:</p>
<ul>
<li>мы используем атрибут <em>uriSchemeTel</em> из свойств, полученных от интерфейса DeviceAtlas, чтобы определить поддерживает ли устройство ссылку на номер телефона. Если да - отображаем ее</li>
<li>размер изображения с картой Google определяется по шаблонной переменной <em>mapWidth</em></li>
<li>внизу таблицы мы выводим некоторую отладочную информацию: строка UA, версия библиотеки DeviceAtlas, производитель и модель мобильного устройства.</li>
</ul>
<p>Версия шаблона для стационарных компьютеров (index.html) в отличии от мобильной очень простая и мы не будем ее здесь рассматривать. Что у нас получилось:</p>
<p><img class="aligncenter" src="http://dev.mobi/files/Screenshot%20-%2029_05_2008%20,%2018_50_11.png" alt="" width="323" height="470" /></p>
<h3>Запуск приложения</h3>
<p>Теперь все что осталось, добавить основной код приложения:</p>
<div class="geshifilter">
<div class="geshifilter-python" style="font-family:monospace;"><span style="font-weight:bold;color:#ff7700;">def</span> main<span style="color:black;">(</span><span style="color:black;">)</span>:<br />
application = webapp.<span style="color:black;">WSGIApplication</span><span style="color:black;">(</span> <span style="color:black;">[</span><span style="color:black;">(</span><span style="color:#483d8b;">'/'</span>, MainPage<span style="color:black;">)</span><span style="color:black;">]</span>, debug=<span style="color:#008000;">True</span><span style="color:black;">)</span><br />
wsgiref.<span style="color:black;">handlers</span>.<span style="color:black;">CGIHandler</span><span style="color:black;">(</span><span style="color:black;">)</span>.<span style="color:black;">run</span><span style="color:black;">(</span>application<span style="color:black;">)</span></p>
<p><span style="font-weight:bold;color:#ff7700;">if</span> __name__ == <span style="color:#483d8b;">"__main__"</span>:<br />
main<span style="color:black;">(</span><span style="color:black;">)</span></div>
</div>
<p>Теперь каталог с приложением выглядит так:</p>
<p><em>api.py<br />
app.yaml<br />
daExceptions.py<br />
DeviceAtlas.json<br />
favicon.ico<br />
contact-dotmobi.py<br />
index.html<br />
index.xhtml<br />
index.yaml<br />
simplejson</em></p>
<p>Это все. Работу этого приложения "наживую" можно посмотреть на сайте <a href="http://contact-dotmobi.appspot.com/" target="_blank">http://contact-dotmobi.appspot.com/</a>.</p>
<h3>Другой пример</h3>
<p>Разработчики, которые экспериментировали с DeviceAtlas предложили другой пример приложения, отображающего все доступные возможности текущего устройства:</p>
<p><img class="aligncenter" src="http://dev.mobi/files/Screenshot%20-%2029_05_2008%20,%2018_55_00.png" alt="" width="533" height="506" /></p>
<p>Код этого приложения очень простой:</p>
<p><span style="font-weight:bold;color:#ff7700;">def</span> get<span style="color:black;">(</span><span style="color:#008000;">self</span><span style="color:black;">)</span>:<br />
<span style="color:#008000;">self</span>.<span style="color:black;">response</span>.<span style="color:black;">headers</span><span style="color:black;">[</span><span style="color:#483d8b;">'Content-Type'</span><span style="color:black;">]</span> = <span style="color:#483d8b;">'text/html'</span><br />
ua = <span style="color:#008000;">self</span>.<span style="color:black;">request</span>.<span style="color:black;">user_agent</span><br />
apiRevision = da.<span style="color:black;">getApiRevision</span><span style="color:black;">(</span><span style="color:black;">)</span></p>
<p>props = da.<span style="color:black;">getPropertiesAsTyped</span><span style="color:black;">(</span>tree, <span style="color:#008000;">self</span>.<span style="color:black;">request</span>.<span style="color:black;">user_agent</span><span style="color:black;">)</span></p>
<p><span style="font-weight:bold;color:#ff7700;">if</span> props.<span style="color:black;">has_key</span><span style="color:black;">(</span><span style="color:#483d8b;">'vendor'</span><span style="color:black;">)</span> <span style="font-weight:bold;color:#ff7700;">and</span> props.<span style="color:black;">has_key</span><span style="color:black;">(</span><span style="color:#483d8b;">'model'</span><span style="color:black;">)</span>:<br />
imgSrc = <span style="color:#483d8b;">'http://deviceatlas.com/sites/deviceatlas.com/themes/eris/img/device_images/%s/%s.jpg'</span> <span style="color:#66cc66;">%</span> <span style="color:black;">(</span>props<span style="color:black;">[</span><span style="color:#483d8b;">'vendor'</span><span style="color:black;">]</span>.<span style="color:black;">lower</span><span style="color:black;">(</span><span style="color:black;">)</span>, props<span style="color:black;">[</span><span style="color:#483d8b;">'model'</span><span style="color:black;">]</span>.<span style="color:black;">lower</span><span style="color:black;">(</span><span style="color:black;">)</span><span style="color:black;">)</span><br />
<span style="font-weight:bold;color:#ff7700;">else</span>:<br />
imgSrc = <span style="color:#008000;">False</span></p>
<p>template_values = <span style="color:black;">{</span><br />
<span style="color:#483d8b;">'apiRevision'</span>: apiRevision,<br />
<span style="color:#483d8b;">'props'</span>: props,<br />
<span style="color:#483d8b;">'imgSrc'</span>: imgSrc,<br />
<span style="color:#483d8b;">'ua'</span>: ua,<br />
<span style="color:#483d8b;">'t'</span>: <span style="color:#008000;">True</span>,<br />
<span style="color:#483d8b;">'f'</span>: <span style="color:#008000;">False</span>,<br />
<span style="color:black;">}</span></p>
<p>Соответствующий файл с шаблоном выглядит так:</p>
<p><span style="color:black;">{</span><span style="color:#66cc66;">%</span> <span style="font-weight:bold;color:#ff7700;">if</span> imgSrc <span style="color:#66cc66;">%</span><span style="color:black;">}</span><br />
<span style="color:#66cc66;">&#60;</span>img src=<span style="color:#483d8b;">"{{ imgSrc }}"</span> alt=<span style="color:#483d8b;">"Device Image"</span> /<span style="color:#66cc66;">&#62;</span><br />
<span style="color:black;">{</span><span style="color:#66cc66;">%</span> <span style="font-weight:bold;color:#ff7700;">else</span> <span style="color:#66cc66;">%</span><span style="color:black;">}</span><br />
<span style="color:#66cc66;">&#60;</span>p<span style="color:#66cc66;">&#62;</span>No image available<span style="color:#66cc66;">&#60;</span>/p<span style="color:#66cc66;">&#62;</span><br />
<span style="color:black;">{</span><span style="color:#66cc66;">%</span> endif <span style="color:#66cc66;">%</span><span style="color:black;">}</span></p>
<p><span style="color:#66cc66;">&#60;</span>strong<span style="color:#66cc66;">&#62;</span>Available Properties<span style="color:#66cc66;">&#60;</span>/strong<span style="color:#66cc66;">&#62;</span></p>
<p><span style="color:#66cc66;">&#60;</span>table style=<span style="color:#483d8b;">"font-size:0.9em;"</span><span style="color:#66cc66;">&#62;</span><br />
<span style="color:black;">{</span><span style="color:#66cc66;">%</span> <span style="font-weight:bold;color:#ff7700;">for</span> prop <span style="font-weight:bold;color:#ff7700;">in</span> props.<span style="color:black;">items</span> <span style="color:#66cc66;">%</span><span style="color:black;">}</span><br />
<span style="color:#66cc66;">&#60;</span>tr style=<span style="color:#483d8b;">"background-color: #{% cycle fff,f8f8f8 %};"</span><span style="color:#66cc66;">&#62;</span><br />
<span style="color:#66cc66;">&#60;</span>td<span style="color:#66cc66;">&#62;</span><br />
<span style="color:#66cc66;">&#60;</span>strong<span style="color:#66cc66;">&#62;</span><span style="color:black;">{</span><span style="color:black;">{</span> prop<span style="color:#ff4500;">.0</span> <span style="color:black;">}</span><span style="color:black;">}</span><span style="color:#66cc66;">&#60;</span>/strong<span style="color:#66cc66;">&#62;</span><br />
<span style="color:#66cc66;">&#60;</span>/td<span style="color:#66cc66;">&#62;</span><br />
<span style="color:#66cc66;">&#60;</span>td<span style="color:#66cc66;">&#62;</span><br />
<span style="color:black;">{</span><span style="color:#66cc66;">%</span> ifequal prop<span style="color:#ff4500;">.1</span> t <span style="color:#66cc66;">%</span><span style="color:black;">}</span><br />
<span style="color:#66cc66;">&#60;</span>span style=<span style="color:#483d8b;">"color: #0c0;"</span><span style="color:#66cc66;">&#62;</span> <span style="color:black;">{</span><span style="color:black;">{</span> prop<span style="color:#ff4500;">.1</span> <span style="color:black;">}</span><span style="color:black;">}</span><span style="color:#66cc66;">&#60;</span>/span<span style="color:#66cc66;">&#62;</span><br />
<span style="color:black;">{</span><span style="color:#66cc66;">%</span> <span style="font-weight:bold;color:#ff7700;">else</span> <span style="color:#66cc66;">%</span><span style="color:black;">}</span><br />
<span style="color:black;">{</span><span style="color:#66cc66;">%</span> ifequal prop<span style="color:#ff4500;">.1</span> f <span style="color:#66cc66;">%</span><span style="color:black;">}</span><br />
<span style="color:#66cc66;">&#60;</span>span style=<span style="color:#483d8b;">"color: #c00;"</span><span style="color:#66cc66;">&#62;</span> <span style="color:black;">{</span><span style="color:black;">{</span> prop<span style="color:#ff4500;">.1</span> <span style="color:black;">}</span><span style="color:black;">}</span><span style="color:#66cc66;">&#60;</span>/span<span style="color:#66cc66;">&#62;</span><br />
<span style="color:black;">{</span><span style="color:#66cc66;">%</span> <span style="font-weight:bold;color:#ff7700;">else</span> <span style="color:#66cc66;">%</span><span style="color:black;">}</span><br />
<span style="color:black;">{</span><span style="color:black;">{</span> prop<span style="color:#ff4500;">.1</span> <span style="color:black;">}</span><span style="color:black;">}</span><br />
<span style="color:black;">{</span><span style="color:#66cc66;">%</span> endifequal <span style="color:#66cc66;">%</span><span style="color:black;">}</span><br />
<span style="color:black;">{</span><span style="color:#66cc66;">%</span> endifequal <span style="color:#66cc66;">%</span><span style="color:black;">}</span><br />
<span style="color:#66cc66;">&#60;</span>/td<span style="color:#66cc66;">&#62;</span><br />
<span style="color:#66cc66;">&#60;</span>/tr<span style="color:#66cc66;">&#62;</span><br />
<span style="color:black;">{</span><span style="color:#66cc66;">%</span> endfor <span style="color:#66cc66;">%</span><span style="color:black;">}</span><br />
<span style="color:#66cc66;">&#60;</span>/table<span style="color:#66cc66;">&#62;</span></p>
<p>Аналогично, посмотреть работу приложения можно по адресу <a href="http://deviceatlas.appspot.com/" target="_blank">http://deviceatlas.appspot.com/</a>. Исходный код обоих приложений доступен <a href="http://dev.mobi/files/contact-dotmobi.zip_.txt">здесь</a> и <a href="http://dev.mobi/files/deviceatlas.zip_.txt">здесь</a> соответственно. После загрузки необходимо переименовать расширения файлов в обычные .zip.</p>
<p>Скачать библиотеку можно после регистрации на <a href="http://deviceatlas.com/user/login?destination=downloads" target="_blank">сайте производителя</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Chofter.com - A Next-Gen Search Portal is launched]]></title>
<link>http://shaneosullivan.wordpress.com/?p=111</link>
<pubDate>Mon, 04 Aug 2008 09:11:20 +0000</pubDate>
<dc:creator>Shane O'Sullivan</dc:creator>
<guid>http://shaneosullivan.wordpress.com/?p=111</guid>
<description><![CDATA[For quite a while, I had been working with various REST services, e.g. Flickr, the Google search ser]]></description>
<content:encoded><![CDATA[<p>For quite a while, I had been working with various REST services, e.g. Flickr, the Google search services and more, as part of my contributions to the <a href="http://www.dojotoolkit.org" target="_blank">Dojo Ajax Toolkit</a>, when it occurred to me that no one had done a good job of bringing all these various sources of information together in a usable way.</p>
<p>Cut to four months later, and I have <a href="http://chofter.com/blog/?p=5" target="_blank">launched </a>my new search portal, <a href="http://www.chofter.com" target="_blank">Chofter.com</a>.</p>
<p>To add it to the search bar in your browser, click <a href="http://http://www.chofter.com/searcher/resources/addSearch.html">here</a>.</p>
<p>Immodest as it may sound, Chofter.com provides a better search experience than Google, Yahoo or Microsoft Live, because it incorporates search results from all of them, and much more.</p>
<p>The entire application is written using the Dojo toolkit, utilising</p>
<ul>
<li><a href="http://dojocampus.org/explorer/#Dijit_Layout" target="_blank">Layouts</a>, Dialogs, Menus and ContentPanes for the user interface.</li>
<li><a href="http://dojocampus.org/explorer/#Dojo_Data" target="_blank">dojo.data</a> and dojo.rpc for data transfer.</li>
<li><a href="http://dojocampus.org/explorer/#Dojox_DTL" target="_blank">dojox.dtl</a> (Django Templating Library) for transforming search data into visuals.</li>
<li><a href="http://dojocampus.org/explorer/#Dojo_FX" target="_blank">dojo.fx</a> and <a href="http://dojocampus.org/explorer/#Dojox_Widgets_FishEyeLite" target="_blank">FisheyeLite</a> for eye candy</li>
<li>.... and a chunk of custom code.</li>
</ul>
<p>As of writing, the following search sources are available, arranged into a number of categories:</p>
<ul>
<li>Google - web, news, image, blog, video and book search.</li>
<li>Yahoo - web, news and image search.</li>
<li>Microsoft Live - web and news search.</li>
<li>YouTube - video search.</li>
<li>Flickr - image search.</li>
<li>BBC News - news and sports search.</li>
<li>Digg - web, news and video search.</li>
<li>Amazon.com - book search.</li>
<li>Wikipedia - web search.</li>
<li>IMDB - video search.</li>
<li>Technorati - blog search.</li>
<li>DZone - technical search.</li>
</ul>
<p>I will be adding more as time goes on.  A forum is being set up, and I welcome all feedback on the site.  I've also set up a blog for the site at <a href="http://www.chofter.com/blog" target="_blank">http://www.chofter.com/blog</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Iphone test wntru ]]></title>
<link>http://hugogamboa.wordpress.com/2008/07/31/iphone-test-wntru/</link>
<pubDate>Thu, 31 Jul 2008 01:42:42 +0000</pubDate>
<dc:creator>hgamboa</dc:creator>
<guid>http://hugogamboa.wordpress.com/2008/07/31/iphone-test-wntru/</guid>
<description><![CDATA[Test
]]></description>
<content:encoded><![CDATA[<p>Test</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[ColdBox error: Invalid JSON &amp; The document you are trying to decode is not in valid JSON format]]></title>
<link>http://ipggi.wordpress.com/?p=83</link>
<pubDate>Wed, 30 Jul 2008 02:40:22 +0000</pubDate>
<dc:creator>Ben</dc:creator>
<guid>http://ipggi.wordpress.com/?p=83</guid>
<description><![CDATA[ 
Upon migrating from ColdBox 2.52 over to ColdBox 2.6 I was caught out by a subtle but show stoppin]]></description>
<content:encoded><![CDATA[<p><!--[if gte mso 9]&#62;  12.00  &#60;![endif]--><!--[if gte mso 9]&#62;  Normal 0     false false false  EN-AU X-NONE X-NONE              MicrosoftInternetExplorer4              &#60;![endif]--><!--[if gte mso 9]&#62;                                                                                                                                            &#60;![endif]--><!--  /* Font Definitions */  @font-face 	{font-family:"Cambria Math"; 	panose-1:2 4 5 3 5 4 6 3 2 4; 	mso-font-charset:0; 	mso-generic-font-family:roman; 	mso-font-pitch:variable; 	mso-font-signature:-1610611985 1107304683 0 0 159 0;} @font-face 	{font-family:Calibri; 	panose-1:2 15 5 2 2 2 4 3 2 4; 	mso-font-charset:0; 	mso-generic-font-family:swiss; 	mso-font-pitch:variable; 	mso-font-signature:-1610611985 1073750139 0 0 159 0;}  /* Style Definitions */  p.MsoNormal, li.MsoNormal, div.MsoNormal 	{mso-style-unhide:no; 	mso-style-qformat:yes; 	mso-style-parent:""; 	margin-top:0cm; 	margin-right:0cm; 	margin-bottom:10.0pt; 	margin-left:0cm; 	line-height:115%; 	mso-pagination:widow-orphan; 	font-size:11.0pt; 	font-family:"Calibri","sans-serif"; 	mso-ascii-font-family:Calibri; 	mso-ascii-theme-font:minor-latin; 	mso-fareast-font-family:Calibri; 	mso-fareast-theme-font:minor-latin; 	mso-hansi-font-family:Calibri; 	mso-hansi-theme-font:minor-latin; 	mso-bidi-font-family:"Times New Roman"; 	mso-bidi-theme-font:minor-bidi; 	mso-fareast-language:EN-US;} .MsoChpDefault 	{mso-style-type:export-only; 	mso-default-props:yes; 	mso-ascii-font-family:Calibri; 	mso-ascii-theme-font:minor-latin; 	mso-fareast-font-family:Calibri; 	mso-fareast-theme-font:minor-latin; 	mso-hansi-font-family:Calibri; 	mso-hansi-theme-font:minor-latin; 	mso-bidi-font-family:"Times New Roman"; 	mso-bidi-theme-font:minor-bidi; 	mso-fareast-language:EN-US;} .MsoPapDefault 	{mso-style-type:export-only; 	margin-bottom:10.0pt; 	line-height:115%;} @page Section1 	{size:595.3pt 841.9pt; 	margin:72.0pt 72.0pt 72.0pt 72.0pt; 	mso-header-margin:35.4pt; 	mso-footer-margin:35.4pt; 	mso-paper-source:0;} div.Section1 	{page:Section1;} --><!--[if gte mso 10]&#62; &#60;!   /* Style Definitions */  table.MsoNormalTable 	{mso-style-name:"Table Normal"; 	mso-tstyle-rowband-size:0; 	mso-tstyle-colband-size:0; 	mso-style-noshow:yes; 	mso-style-priority:99; 	mso-style-qformat:yes; 	mso-style-parent:""; 	mso-padding-alt:0cm 5.4pt 0cm 5.4pt; 	mso-para-margin-top:0cm; 	mso-para-margin-right:0cm; 	mso-para-margin-bottom:10.0pt; 	mso-para-margin-left:0cm; 	line-height:115%; 	mso-pagination:widow-orphan; 	font-size:11.0pt; 	font-family:"Calibri","sans-serif"; 	mso-ascii-font-family:Calibri; 	mso-ascii-theme-font:minor-latin; 	mso-fareast-font-family:"Times New Roman"; 	mso-fareast-theme-font:minor-fareast; 	mso-hansi-font-family:Calibri; 	mso-hansi-theme-font:minor-latin;} --> <!--[endif]--></p>
<p class="MsoNormal">Upon migrating from ColdBox 2.52 over to ColdBox 2.6 I was caught out by a subtle but show stopping issue. Unfortunately the error thrown is not very precise as to the details of the error is or what exactly has triggered it.</p>
[caption id="attachment_89" align="alignnone" width="300" caption="Invalid JSON"]<a href="http://ipggi.files.wordpress.com/2008/07/28-07-2008-2-03-48-pm1.png"><img class="size-medium wp-image-89" src="http://ipggi.wordpress.com/files/2008/07/28-07-2008-2-03-48-pm1.png?w=300" alt="Invalid JSON" width="300" height="280" /></a>[/caption]
<p class="MsoNormal">Looking into the pages being called prior to the error you can see the line ..</p>
<pre class="MsoNormal">Called from \coldbox\system\plugins\XMLParser.cfc: line 1013</pre>
<p class="MsoNormal">So one can assume it is probably an issue with one of the XML file, yet which file is not mentioned. However the XML file itself is not the problem, rather it is the data contained within. As JSON or JavaScript Object Notion like XML is another form of human readable data interchange. Unlike XML though JSON is light weight and less complex.</p>
<p class="MsoNormal">Now if you read the official <a href="http://ortus.svnrepository.com/coldbox/trac.cgi/wiki/cbWhatsNew2.60">What’s New Guide</a> for ColdBox 2.6 you can find the following heading ‘JSON notation for dynamic complex settings’.</p>
<p><span style="color:#993300;">The configuration file allowed for simple notation to create structures: <em>{name:'luis',active:'true'}</em> and arrays: <em>[1,2,3]</em>. However, with the inclusion of the new <em>json</em> plugin, you can now declare full JSON syntax notations on ALL complex variables in the configuration file. So you can inflate queries, nested arrays, structures and so much more.</span></p>
<p class="MsoNormal">My slipup was that I was transferring an old ColdBox 2.52 coldbox.xml file for use in ColdBox 2.6. I had missed one of my Settings elements under YourSettings that used complex but invalid JSON style data structures. But it was easily fixed with a few single quotes here and there...</p>
<p class="MsoNormal"><strong>2.52 statement</strong></p>
<pre>&#60;Setting name="TransferSettings"
value="{datasourceFile:config/datasource.xml.cfm,
transferFile:config/transfer.xml.cfm,
definitions:config/definitions}"/&#62;</pre>
<p class="MsoNormal"><strong>2.6 updated statement</strong></p>
<pre>&#60;Setting name="TransferSettings"
value="{datasourceFile:<span style="color:#0000ff;">'config/datasource.xml.cfm'</span>,
transferFile:<span style="color:#0000ff;">'config/transfer.xml.cfm'</span>,
definitions:<span style="color:#0000ff;">'config/definitions'</span>}"/&#62;</pre>
]]></content:encoded>
</item>
<item>
<title><![CDATA[The all new BBC music site where programmes meet music and the semantic web]]></title>
<link>http://derivadow.wordpress.com/?p=450</link>
<pubDate>Mon, 28 Jul 2008 19:17:12 +0000</pubDate>
<dc:creator>Tom Scott</dc:creator>
<guid>http://derivadow.wordpress.com/?p=450</guid>
<description><![CDATA[We (well Nick, Patrick, Tony, Deanna, Sacha and Guy) have recently been working on a major rewrite o]]></description>
<content:encoded><![CDATA[<p><a href="http://www.bbc.co.uk/music/developers/are">We</a> (well <a href="http://www.aelius.com/njh/" rel="friend co-worker">Nick</a>, <a href="http://metade.org/" rel="friend co-worker">Patrick</a>, Tony, Deanna, Sacha and Guy) have recently been working on a major rewrite of the <a href="http://www.bbc.co.uk/music/beta">BBC's music site</a> [beta] - and since its just gone live as a public beta I thought it would be a good time to explain a bit about what we've done and what we hope to do with the site. I would also love to hear what you think about what we've done so far - especially as we move from public beta towards a replacement for the <a href="http://www.bbc.co.uk/music">current site</a>.</p>
[caption id="attachment_488" align="alignnone" width="500" caption="Madonna&#39;s artist page on the BBC&#39;s new beta music site"]<img class="size-full wp-image-488" src="http://derivadow.wordpress.com/files/2008/07/music-site1.jpg" alt="Madonna's artist page on the BBC's new beta music site" width="500" height="589" />[/caption]
<p>Our work so far has focused on providing core information for every artist the BBC plays on our daytime radio network shows. That's shows like <a href="http://www.bbc.co.uk/programmes/b006wkh9">Annie Mac</a> and <a href="http://www.bbc.co.uk/programmes/b006wkqb">Chris Moyles</a> on Radio 1, or <a href="http://www.bbc.co.uk/programmes/b0072lb2">Steve Lamacq</a><a href="http://www.bbc.co.uk/programmes/b0072l8y"></a> on <a href="http://www.bbc.co.uk/6music/">6Music</a>. We've focused on these shows because we've integrated the site with the radio playout system <a href="http://www.vcs.de/media-broadcasting-solutions/our-solutions/dira-radio.html?L=1">VCS dira!</a> which are basically giant iPods in the basement of <a href="http://en.wikipedia.org/wiki/Broadcasting_House">Broadcasting House</a>. Unfortunately the specialist shows as well as national and local radio shows don't use these so we haven't got track listing data in the right format for these programmes. But we have a plan and will be adding more shows in due course.</p>
<h2>So what have done so far?</h2>
<p>For starters we decided that we wanted to have a single canonical page for every artist. We decided to do this because we want to aggregate everything we know about an artist at a single URL. But this means that we need unique, persistent, unambiguous URLs. Thankfully, as Michael has <a href="http://www.bbc.co.uk/blogs/radiolabs/2008/06/the_simple_joys_of_webscale_id.shtml">already discussed</a>, <a href="http://blog.musicbrainz.org/?p=274">Musicbrainz</a> gives us unique identifiers that allow us to provide just such a set of URLs.</p>
<p>The core of the new site then is built around Musicbrainz. In addition to giving us web scale identifiers Musicbrainz is also being used to give core music metadata e.g. discographies, related artists and related links. Some of those related links are Wikipedia links and we are using those to go and fetch the introductory text for each artist's biography from Wikipedia.</p>
<p>The approach we're using to keep the Wikipedia data up to date is, I think, quite neat. <a href="http://metade.org/">Patrick</a> has written a <a href="http://en.wikipedia.org/wiki/IRC_bot">bot</a> to monitor the <a href="http://en.wikipedia.org/wiki/Wikipedia:IRC_channels">Wikipedia IRC channel</a> for updates - when it spots an update we fetch the new Wikipedia content. Oh and obviously all this data is rendered dynamically using the <a href="http://www.bbc.co.uk/blogs/radiolabs/2007/11/perl_on_rails.shtml">same MVC framework</a> we are using for <a href="http://www.bbc.co.uk/programmes/">/programmes</a> which means that updates happen almost instantaneously.</p>
<p>This brings me to the next major feature - integration with <a href="http://www.bbc.co.uk/programmes/">/programmes</a>. As I've said we have integrated with VCS to give us track listing information for our daytime radio shows - we are matching this data with both our internal database of programme metadata and Musicbrainz. This lets us know which radio stations and shows have played which artists.</p>
<p>We also want to make this data available for <a href="http://www.bbc.co.uk/blogs/radiolabs/2008/05/helping_machines_play_with_pro.shtml">others to use</a> and so have designed the site to provide a RESTful API, following the principles of <a href="http://en.wikipedia.org/wiki/Linked_Data">Linked Data</a>:</p>
<blockquote><p>...namely thinking of URIs as more than just locations for documents. Instead using them to identify anything, from a particular person to a particular programme. These resources in-turn have representations, which can be machine-processable (through the use of RDF, Microformats, RDFa, etc.), and these representations can hold links towards further web resources, allowing agents to jump from one data-set to another.</p></blockquote>
<p>If you would like to have a play with these we have RDF, XML, JSON and YAML representations of the resources - just add <a href="http://www.bbc.co.uk/music/artists/d4d17620-fd97-4574-92a8-a2cb7e72ce42.xml">.xml</a> <a href="http://www.bbc.co.uk/music/artists/d4d17620-fd97-4574-92a8-a2cb7e72ce42.rdf">.rdf</a> <a href="http://www.bbc.co.uk/music/artists/d4d17620-fd97-4574-92a8-a2cb7e72ce42.json">.json</a> or <a href="http://www.bbc.co.uk/music/artists/d4d17620-fd97-4574-92a8-a2cb7e72ce42.yaml">.yaml</a> to the end of the <a href="http://www.bbc.co.uk/music/artists/d4d17620-fd97-4574-92a8-a2cb7e72ce42">artist url</a>.</p>
<h2>Where next?</h2>
<p><a href="http://www.aelius.com/njh/">Nick</a>, <a href="http://www.bbc.co.uk/blogs/radiolabs/2008/03/whats_that_star_on_the_wall.shtml">Michael</a> and I have previous <a href="http://www.bbc.co.uk/blogs/radiolabs/2008/05/helping_machines_play_with_pro.shtml">spoken</a> about our plans for linking <a href="http://www.bbc.co.uk/programmes/">programmes</a>, music, events, topics and users. Well this is our first foray into this world. Information about programmes and music is interesting, it's useful; but it's not as interesting nor as useful as when the two are intelligently linked. Joining the two worlds means that you can aggregate information about the programmes that have played an artist [as we've done], you can put track listings on episode pages, you can have charts of which artists are played most on all BBC Radio programmes, on Radio 1, by Zane Lowe. You can also aggregate all episodes that you can currently listen to that feature a given artist. Or show which programme first played a given artist and how often the BBC has played them since. Basically the interesting stuff happens at the joins between the nodes because that's where the context lives.</p>
<p><img class="alignnone size-full wp-image-453" src="http://derivadow.wordpress.com/files/2008/07/bbc-graph-of-data.jpg" alt="" width="500" height="457" /></p>
<p>By exposing the information that is created by joining programmes and music we can provide context and serendipity. We can help you find out about the music you've just listened to and introduce you to new shows that also features the music you like. So that's what we're working on.</p>
<p>We also need to provide more data about each artist - from both inside and outside the BBC. That means bringing the <a href="http://www.bbc.co.uk/music/release/">album reviews</a> into the fold, hooking up external news feeds and the like. But whatever we do it's worth bearing in mind that this is on a much larger scale than the current music site. This new site has in the order of 388,398 artist pages, 157,677 external links and 93,912 artist to artist relationships.</p>
<p>It would be great to hear what you think about what we've done and our plans for the future. You are welcome to leave a comment here, or via the <a href="http://backstage.bbc.co.uk/">Backstage</a> mailing list.</p>
]]></content:encoded>
</item>

</channel>
</rss>
