<rss version="2.0">
<channel>
<title>damienlegrand.com</title>
<link>http://www.damienlegrand.com</link>
<description>Damien Legrand's Blog</description>
<language>en-us</language>
<copyright>damienlegrand.com 2014</copyright>
<ttl>10</ttl>

    
        <item>

		<title>Freebase and DBPedia</title>
		<link>http://www.damienlegrand.com/index.php/blog/article/Freebase-and-DBPedia</link>
		<guid>http://www.damienlegrand.com/index.php/blog/article/Freebase-and-DBPedia</guid>
		<image>http://www.damienlegrand.com/public/img/upload/large/Freebase-and-DBPedia.png</image>
		<description><![CDATA[
      		<p>This year I had a big project for my studies. It was a musical recommendation website. So I had to use data from different services, as Freebase and wikipedia. <br/> Here is a screenshot of this project : </p>

<div class="images">
<img src="http://www.damienlegrand.com/public/img/illustrations/smashingsound-screenshot.png" alt="Smashing Sound Website" />
</div>

<h2>Freebase</h2>

<p>Freebase is now a Google service ! And you can make queries on Freebase with MQL. It look likes a json array...</p>

<pre class="prettyprint">
{
	&quot;mid&quot; : &quot;artist's Freebase ID&quot;, 
	&quot;type&quot; : &quot;/music/artist&quot;,
	&quot;name&quot; : null,
	&quot;home_page&quot; : [{
		&quot;uri&quot; : null,
		 &quot;optional&quot; : True
	}],
	&quot;key&quot; : [{
		&quot;namespace&quot; : null,
		&quot;value&quot; : null,
		&quot;optional&quot; : True
	}],
	&quot;active_start&quot; : null,
	&quot;active_end&quot; : null,
	&quot;label&quot; : [{
		&quot;mid&quot; : null,
		&quot;name&quot; : null,
		&quot;optional&quot; : True
	}],
	&quot;genre&quot; : [{
		&quot;mid&quot; : null,
		&quot;optional&quot; : True
	}],
	&quot;album&quot; : [{
		&quot;mid&quot; : null,
		 &quot;optional&quot; : True
	}]
}
</pre>

<p>Here I'm getting data for an artist entity. Null values are what I'm asking to Freebase. If you want more information there is a nice documentation here : <a href="http://wiki.freebase.com/wiki/Main_Page" target="_blank">http://wiki.freebase.com/wiki/Main_Page</a></p>

<p>Freebase get his data from others services as MusicBrainz for musical data, and wikipedia, which is a nice thing (less work for me ;) ). But it doesn't provide the wikipedia description (more work for me ^^). Nevertheless, Freebase provide a wikipedia id (I'm getting it with the "key" attribute).</p>

<h2>WIkipedia API</h2>

<p>So with this id, I tried to get wikipedia information through the Mediawiki's API : <a href="http://www.mediawiki.org/wiki/API" target="_blank">http://www.mediawiki.org/wiki/API</a></p>

<p>But what you get is a strange things ! Wiki markup ! Because I'm a lazy developer (as the majority of developers...) and I don't want to understand how it work and how to parse it (I'm a json lover), so I found another way.</p>

<h2>DBPedia</h2>

<p>The other way is to get data from DBPedia which is a linked open data services as Freebase.<br/>
After some days of research, I found the magical SPARQL query to get data on DBPedia from a wikipedia id. And here is the query :</p>

<pre class="prettyprint">
PREFIX dbp: &lt; http://dbpedia.org/resource/ &gt;
PREFIX dbp2: &lt; http://dbpedia.org/ontology/ &gt;
SELECT ?abstract WHERE {
	dbp:WIKIPEDIA_ID dbp2:abstract ?abstract .
}
</pre>

<p>You can replace WIKIPEDIA_ID with the ... wiki... wait for it... pedia id ! Here is an example :</p>
<p><a href="http://dbpedia.org/sparql?query= PREFIX+dbp%3A+%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2F%3E%0D%0APREFIX+dbp2%3A+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2F%3E%0D%0ASELECT+%3Fabstract+WHERE+%7B%0D%0A%09dbp%3ANine_Inch_Nails+dbp2%3Aabstract+%3Fabstract+.%0D%0A%7D&format=json" target="_blank">http://dbpedia.org/sparql?query=QUERYHERE&format=json</a></p>

<p>And at this url you get all you need ! Here is the artist description in English, Spanish, Finnish, Italian, Japanese, French...</p>      		]]></description>
		<pubDate>Thu, 21 June 2012 13:38:24 UTC</pubDate>
	</item>

        
    
        <item>

		<title>An Easy Scroll To Top Plugin</title>
		<link>http://www.damienlegrand.com/index.php/blog/article/An-Easy-Scroll-To-Top-Plugin</link>
		<guid>http://www.damienlegrand.com/index.php/blog/article/An-Easy-Scroll-To-Top-Plugin</guid>
		<image>http://www.damienlegrand.com/public/img/upload/large/An-Easy-Scroll-To-Top-Plugin.jpg</image>
		<description><![CDATA[
      		<p> Now, every website need to have his scroll to top button. So I made a little jQuery plugin that fit my needs ;). You can see it in action on this page. Try to scroll down and to resize the window to see it in action.</p>

<h2>How this plugin work?</h2>

<p> You need to have a div at the end of the body. You can apply the style you want on it. But the display parameter of this div has to be set to "none". After that you just need to import jQuery and the plugin in your html page and to apply the plugin on this div.</p>
<p>Here an example:</p>

<p class="accent">HTML</p>
<pre class="prettyprint">
&lt;div id=&quot;top&quot;&gt;Top&lt;/div&gt; 
</pre>

<p class="accent">CSS</p>
<pre class="prettyprint">
#top {
	background-color: black;
	color: white;
	display: none;
	font-size: 20px;
	margin: 20px 0px;
	text-align: center;
	width: 100px;
}
</pre>

<p class="accent">JavaScript (jQuery)</p>
<pre class="prettyprint">
&lt;script type=&quot;text/javascript&quot;&gt;
	
		$(function(){

			$('#top').gotop();

		});
	
&lt;/script&gt;
</pre>

<p>So finally in a single html page :</p>
<pre class="prettyprint">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot;&gt;
        &lt;title&gt;GoTop Plugin in action&lt;/title&gt;
              
        &lt;style&gt;
         #top {
		background-color: black;
		color: white;
		display: none;
		font-size: 20px;
		margin: 20px 0px;
		text-align: center;
		width: 100px;
	}
        &lt;/style&gt;
        
&lt;/head&gt;
&lt;body&gt;

	&lt;div id=&quot;content&quot;&gt;The content of your website ...&lt;/div&gt;

	 &lt;div id=&quot;top&quot;&gt;Top&lt;/div&gt;
	
	&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
        &lt;script src=&quot;js/jquery.gotop.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
	&lt;script type=&quot;text/javascript&quot;&gt;
	
		$(function(){

			$('#top').gotop();

		});
	
	&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>

<h2>Configuration</h2>

<p>There is some parameters that can be personalize on this plugin.</p>

<pre class="prettyprint">
$('#top').gotop({
	content:	960, /*The size of the main content so the button is never display over the content*/
  	bottom:	30, /*The space in pixel between the button and the bottom of the window*/
  	margin:	&quot;none&quot;, /*The margin between the button and the left or right of the window. If this parameter is set to 'none', the plugin center the button automatically*/
  	position:	&quot;right&quot;, /*If the button is display on the left or the right of the window*/
  	scrollTop:	100, /*The button is displayed when the user scroll down; in pixel*/
  	duration:	700 /*Duration in milliseconds for the fade in and fade out*/
});
</pre>


<h2>Download</h2>

<p>You can download this plugin on <a href="https://github.com/snoozeman/GoTop-jQuery-Plugin" target="_blank">gitHub</a>.</p>      		]]></description>
		<pubDate>Sat, 11 February 2012 7:39:19 UTC</pubDate>
	</item>

        
    
        <item>

		<title>Kinect tile 3D Effect with CSS3 and jQuery</title>
		<link>http://www.damienlegrand.com/index.php/blog/article/Kinect-tile-3D-Effect-with-CSS3-and-jQuery</link>
		<guid>http://www.damienlegrand.com/index.php/blog/article/Kinect-tile-3D-Effect-with-CSS3-and-jQuery</guid>
		<image>http://www.damienlegrand.com/public/img/upload/large/Kinect-tile-3D-Effect-with-CSS3-and-jQuery.jpg</image>
		<description><![CDATA[
      		<p>
I've used my Kinect for 1 year now, and one thing I like is the Kinect dashboard that is reacting in 3D with my hand; you know the tiles...<br/>
So I tried; and succeeded!; to mimic the same 3d effect on html elements with some CSS3 and jQuery, and I made a jQuery plugin so it’s much more easier for you to add this effect on your website.
</p>
<p class="accent">Because this plugin is awesome, it work only on webkit browsers (Google Chrome & Safari) because of the CSS3's rotate3d function.</p>

<h2>First step</h2>
<p>To use this little plugin, first of all you just need to add jquery and the tile plugin to your html page:</p>

<pre class="prettyprint">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
	&lt;meta charset=&quot;utf-8&quot;&gt;
	&lt;title&gt;Tile&lt;/title&gt;
	
	&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
	&lt;script src=&quot;js/jquery.tile.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
	
&lt;/head&gt;
&lt;body&gt;
	
&lt;/body&gt;
&lt;/html&gt;
</pre>

<h2>Second step</h2>
<p>Now we can call the plugin on an element in the page. So in the body we add a div with some style:</p>

<pre class="prettyprint">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
	&lt;meta charset=&quot;utf-8&quot;&gt;
	&lt;title&gt;Tile&lt;/title&gt;
	
	&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
	&lt;script src=&quot;js/jquery.tile.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
	
	&lt;style&gt;
		body {
			background-color: #838383;
		}
		#tile {
			background-color: #45a8d3;
			box-shadow: 0px 0px 5px #444;
			height: 200px;
			width: 200px;
		}
	&lt;/style&gt;
	
&lt;/head&gt;
&lt;body&gt;
	&lt;div id=&quot;tile&quot;&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>

<p>And in the head we call the plugin:</p>

<pre class="prettyprint">
&lt;script type=&quot;text/javascript&quot;&gt;
		$(function(){
		
			$(&quot;#tile&quot;).tile();
		
		});
&lt;/script&gt;
</pre>

<p>And BAMM! you get something like that:</p>

<script type="text/javascript" src="http://www.damienlegrand.com/public/demo/jquery.tile.min.js"></script>
<div id="demo">

<div id="tile1" style="float: left; width:150px; height: 150px; background-color: #7db935; box-shadow: 0px 0px 5px #888; margin-right: 50px; margin-left: 50px; margin-bottom: 50px;"></div>
<div id="tile2" style="float: left; width:150px; height: 150px; background-color: #32a641; box-shadow: 0px 0px 5px #888; margin-right: 50px; margin-bottom: 50px;"></div>
<div id="tile3" style="float: left; width:150px; height: 150px; background-color: #584294; box-shadow: 0px 0px 5px #888; margin-bottom: 50px;"></div>
<script type="text/javascript">
		$(function(){
		
			$("#tile1").tile();
			$("#tile2").tile({degree: 5, inverse: true});
			$("#tile3").tile({perspective: 200, degree:5, inverse: true});
		
		});
</script>

</div>

</br>
<h2>Configuration</h2>
<p>You can even personalize some settings like the perspective, the degree and the inversion by doing this:</p>

<pre class="prettyprint">
$(&quot;#tile&quot;).tile({
	perspective: 400,
	degree: 10,
	inverse: true
});
</pre>

<h2>Source</h2>
<p>You can find source files on gitHub <a href="https://github.com/snoozeman/Tile---jQuery-Plugin" target="_blank">here</a></p>      		]]></description>
		<pubDate>Sat, 7 January 2012 8:40:33 UTC</pubDate>
	</item>

        
    
        <item>

		<title>Distributed Objects with Java &amp; Cocoa</title>
		<link>http://www.damienlegrand.com/index.php/blog/article/Distributed-Objects-with-Java-Cocoa</link>
		<guid>http://www.damienlegrand.com/index.php/blog/article/Distributed-Objects-with-Java-Cocoa</guid>
		<image>http://www.damienlegrand.com/public/img/upload/large/Distributed-Objects-with-Java-Cocoa.jpg</image>
		<description><![CDATA[
      		<p> I’m currently learning interesting things about distributed programming in Java. Because I’m not a Java fan, I tried [and succeeded] to redo a simple RMI example from Java to Cocoa in Objective-C.</p>

<h2>Remote method invocation</h2>

<p> Before showing you how an application can communicate with another one on a network in Objective-C, I’ll explain you a bit how things work, and how we do it in Java to see the differences between the two languages.</p>

</br>
<h5>Principle</h5>

<p> RMI is a java API that let you call methods on an object which is not on the same computer. So for an easy example, let see the communication between a server application and a client application.</p>
<p>So the server just need to vend an object, so the client can reach a pointer to this object and call methods on it; but to do so, the client need to know the interface of this object. </p>

</br>
<h5>Java RMI</h5>

<p>Before programming the server, we need to create an interface (here for a Person object) and define it on the server side.</p>
<p>So we create a new file «PersonStructure.java» in a new java project and put this code to define the interface:</p>

<pre class="prettyprint">
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface PersonStructure extends Remote{
	public String getName() throws RemoteException;
	public void setName(String name) throws RemoteException;
}
</pre>

<p>Here our interface need to extend Remote, if not, the object can’t be vend.</p>
<p>Now we need to define a Person class that will implements our interface, so let’s do it be creating a new file Person.java with this code:</p>

<pre class="prettyprint">
public class Person extends UnicastRemoteObject implements PersonStructure {
	private String name;
	private static final long serialVersionUID = 1L;
	
	protected Person(String name) throws RemoteException {
		super();
		this.name = name;
	}

	@Override
	public String getName() throws RemoteException {
		return this.name;
	}

	@Override
	public void setName(String name) throws RemoteException {
		System.out.println(&quot;the new name is = &quot; + name);
		this.name = name;
	}
}
</pre>

<p>You can see here that our class Person need to extend UnicastRemoteObject to be shared by a server...</p>
<p>Now we can do our server that will vend the Person object. Create a «Server.java» file with this:</p>

<pre class="prettyprint">
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

public class Server {
	public static void main(String[] args) {
		try {
			//Start a new RmiRegistry 
			LocateRegistry.createRegistry(1099);

			Person person = new Person(&quot;Doe&quot;);
			
			//We share our person
			Naming.bind(&quot;///person_server&quot;, person);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
</pre>

<p>Now here we have our server sharing the person object on the localhost (the 3 slash in the bind). It’s in this bind that you can specify a hostname or an ip address (i.e. "//localhost/server_name" or "//127.0.0.1/server_name").</p>
<p>To have a simple example we stay in the same project to create our client. So create «Client.java» with a main method:</p>

<pre class="prettyprint">
import java.rmi.Naming;

public class Client {
	public static void main(String[] args) {
		try {
			PersonStructure obj = (PersonStructure) Naming.lookup(&quot;person_server&quot;);
			System.out.println(&quot;Name of the person shared by the server = &quot;+ obj.getName());
			obj.setName(&quot;Steve&quot;);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
</pre>

<p>Now you can run the project with the main method of the Server class and after that run the same project but with the main method of the Client Class; and it’s Magic! the client can get and set the person’s name which is on the server.</p>

</br>
<h2>Objective-C & Distributed Objects</h2>

<p>Now we can see how we do the same example but with Cocoa applications. So in Xcode create a new Cocoa Application and name it Server.</p>
<p>Create a new file (cmd+N), choose the Objective-C protocol template and name it PersonStructure. Now we define the structure of a person with this:</p>

<pre class="prettyprint">
@protocol PersonStructure &lt; NSObject &gt;

- (NSString *)getName;
- (void)setName:(NSString *)name;

@end
</pre>

<p>Now we can define our Person class (create a new class which will subclass NSObject):</p>

<p><i>In Person.h:</i></p>

<pre class="prettyprint">
#import &quot;PersonStructure.h&quot;

@interface Person : NSObject &lt; PersonStructure &gt; {
    NSString *_name;
}

- (id)initWithName:(NSString *)name;
 
@end
</pre>

<p><i>In Person.m:</i></p>

<pre class="prettyprint">
@implementation Person

- (id)initWithName:(NSString *)name
{
    self = [super init];
    if(self)
    {
        _name = [name retain];
    }
    
    return self;
}

- (NSString *)getName
{
    return _name;
}

- (void)setName:(NSString *)name
{
	NSLog(&quot;the new name is = %@&quot;, name);
    [_name release];
    _name = [name retain];
}

- (void)dealloc
{
    [_name release];
    [super dealloc];
}

@end
</pre>

<p>You can see here that I’m managing memory by myself with the retains, releases and deallocs, but it’s not necessary if your project use the automatic reference counting (ARC).</p>
<p>Know we just need to start our server in the AppDelegate:</p>

<pre class="prettyprint">
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Create the Person to vend
    Person *person = [[Person alloc] initWithName:@&quot;Doe&quot;];
    
    NSConnection *serverConnection = [NSConnection serviceConnectionWithName:@&quot;person_server&quot; rootObject:person];
    
    //Start the server
    [serverConnection runInNewThread];
}
</pre>

<p>Our server is done. Now we need to create a new project Client. In this project we have to drag and drop the PersonStructure. h file from the server project.</p>
<p>Finally we can access the person object from the server application by adding this code in the Client’s AppDelegate:</p>

<pre class="prettyprint">
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    //Until we find the server
    NSDistantObject *serverObject = nil;
    while (serverObject == nil)
    {
        serverObject = [[NSConnection rootProxyForConnectionWithRegisteredName:@&quot;person_server&quot; host:nil] retain];
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.]];
    }
    
    //We cast the remote object in the interface we know 
    id&lt; PersonStructure &gt; remoteObject = (id&lt; PersonStructure &gt;)serverObject;

    //we use our remote object
    NSLog(@&quot;Person's name on server = %@&quot;, [remoteObject getName]);
    
    [remoteObject setName:@&quot;Steve&quot;];
}
</pre>

<p>And we are done! You can now run the server and the client, and you’ll see that the client can communicate with our server.</p>

</br>
<h2>Conclusion</h2>
<p> Distributed Objects is really an interesting technique to know. This comparison between Java and Objective-C confirm (for me =D) that Objective-C still more elegant and simpler than Java. (i.e. In java the distributed object as to extends Remote and UnicastRemoteObject than in Objective-C every object can be a distributed object). </p>      		]]></description>
		<pubDate>Sat, 22 October 2011 14:44:22 UTC</pubDate>
	</item>

        
    
        <item>

		<title>Beatbox App on iPad &#45; Part Two</title>
		<link>http://www.damienlegrand.com/index.php/blog/article/Beatbox-App-on-iPad-Part-Two</link>
		<guid>http://www.damienlegrand.com/index.php/blog/article/Beatbox-App-on-iPad-Part-Two</guid>
		<image>http://www.damienlegrand.com/public/img/upload/large/Beatbox-App-on-iPad-Part-Two.jpg</image>
		<description><![CDATA[
      		<p> On the first part of this tutorial I was showing you how to make the interface and the navigation of our beatbox app. So now in this second and final part, I’ll show you how to implement functionalities. These functionalities are : </p>

<ul>
<li>Saving a name on each button</li>
<li>Play a sound when user touch a button in playing mode</li>
<li>Record a sound when user touch a button in recording mode </li>
</ul>

</br>
<h2>Button’s Name</h2>
<p>To save names, we will use the NSUserDefaults Class. To do so, add this attribute in the PadButtonViewController.h, inside the interface brackets:</p>

<pre class="prettyprint">
NSUserDefaults *def;
</pre>

<p>And in the initWithNibName:bundle: method in the .m file add this line:</p>

<pre class="prettyprint">
def = [NSUserDefaults standardUserDefaults];
</pre>

<p> Now that we have an instance of NSUserDefaults we can save an object with a corresponding key. This have to be done when the user type something in the text field, and our method changePadName can perform that task. So put this code inside : </p>

<pre class="prettyprint">
[pad setTitle:textField.text forState:UIControlStateNormal];
[def setObject:textField.text forKey:[NSString stringWithFormat:@&quot;pad-%d&quot;, identifier]];
[def synchronize];
</pre>

<p>To have that name set when the app start put this line in the viewDidLoad method:</p>

<pre  class="prettyprint">
[pad setTitle:[def objectForKey:[NSString stringWithFormat:@&quot;pad-%d&quot;, identifier]] forState:UIControlStateNormal];
</pre>

<p>And we are done with the button’s name!</p>

</br>
<h2>Audio</h2>

<p> Now that the big part! To do some playing/recording we will use the AVFoundation and the CoreAudio Frameworks. To include these framework in the project, click on the project name and add theme in the «Link Binaries With Libraries» list.</p>

<div class="images">
<a href="http://www.damienlegrand.com/public/img/illustrations/beatbox-include-framework_b.png" rel="box" title="Frameworks"><img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-include-framework.png" title="Frameworks" alt="Window to add frameworks in the project" /></a>
</div>

<p>We can now import these frameworks in PadButtonViewController.h file:</p>

<p>
#import &#60;AVFoundation&#47;AVFoundation.h&#62;</br>
#import &#60;CoreAudio&#47;CoreAudioTypes.h&#62;
</p>

<p>As this controller will be the recorder's delegate, we have to change our @interface like this :</p>

<pre class="prettyprint">
@interface PadButtonViewController : UIViewController &lt;avaudiorecorderdelegate&gt; {
</pre>

<p>And inside the interface brackets: </p>

<pre class="prettyprint">
NSURL *file;
NSError *error;
AVAudioPlayer *player;
AVAudioRecorder *recorder;
BOOL hasRecordDone;
</pre>

<p>After the bracket add these methods:</p>

<pre class="prettyprint">
- (void)configAudio;
- (void)configPlayer;
- (void)configRecorder;
- (void)startRecording;
- (void)stopRecording;
- (void)startPlaying;
- (void)stopPlaying;
</pre>

<p>Then in the initWithNibName:bundle: method add this:</p>

<pre class="prettyprint">
hasRecordDone = NO;
</pre>

<p>To use the hardware, we need to create the good session. In the changeState method (PadViewController.m), after the for loop add this:</p>

<pre class="prettyprint">
if (theSwitch.on) {
        NSError *error;
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        [audioSession setActive:NO error: &amp;error];
        [audioSession setCategory:AVAudioSessionCategoryRecord error:&amp;error];
        [audioSession setActive:YES error: &amp;error];
    }else {
        NSError *error;
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        [audioSession setActive:NO error: &amp;error];
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:&amp;error];
        [audioSession setActive:YES error: &amp;error];
}
</pre>

<p>We actually need to set the session at the start of the app too, so in viewDidLoad add :</p>

<pre class="prettyprint">
NSError *error;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&amp;error];
[audioSession setActive:YES error: &amp;error];
</pre>

<p>As you can see we are using some NSError, but we will not handle errors in this tutorial.</br>
Now return in the PadButtonController.m file and to configure the audio add this code:</p>

<pre class="prettyprint">
//We set here the name of the audio file that we will use
- (void)configAudio
{
    file = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @&quot;padsound-%d&quot;, identifier]]];
	[file retain];
    
    [self configPlayer]; //by default we configure the player
}

- (void)configPlayer
{
    if(player != nil)
    {
        [player release];
        player = nil;
    }
    
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:&amp;error];
    player.numberOfLoops = -1;
    [player prepareToPlay];
}

- (void)configRecorder
{
    if(recorder != nil)
    {
        [recorder release];
        recorder = nil;
    }
    
    NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init];
    [recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; 
    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
    
    recorder = [[ AVAudioRecorder alloc] initWithURL:file settings:recordSetting error:&amp;error];
    [recorder setDelegate:self];
    [recorder prepareToRecord];
    
    [recordSetting release];
}
</pre>

<p>In the dealloc method add this:</p>

<pre class="prettyprint">
- (void)dealloc
{
    [recorder release];
    [player release];
    
    [super dealloc];
}
</pre>

<p>The configAudio method need to be call at the execution, but we need the identifier attribute to be set before, so we override the setIdentifier method to automatically call the configAudio method:</p>

<pre class="prettyprint">
- (void)setIdentifier:(int)value
{
    identifier = value; 
    [self configAudio];
}
</pre>

<p>Now add this code to perform de recording and the playing:</p>

<pre class="prettyprint">
- (void)startRecording
{
    if (hasRecordDone == NO) [self configRecorder];
    hasRecordDone = YES;
    [recorder record];
}

- (void)stopRecording
{
    [recorder stop];
}

- (void)startPlaying
{
    [player play];
}

- (void)stopPlaying
{
    [player stop];
    player.currentTime = 0;
}
</pre>

<p>In the setRecordingMode method, in the else (after the Playing color) add this:</p>

<pre class="prettyprint">
if(hasRecordDone) [self configPlayer];
hasRecordDone = NO;
</pre>

<p>Now we just need to call these method when the user touch the button, and change the button's color so the user know what's happening:</p>

<pre class="prettyprint">
- (IBAction)touchDown
{
    if(file == nil) [self configAudio];
    if (recordingMode)
    {
        [self startRecording];
        pad.backgroundColor = [UIColor orangeColor];
    }
    else
    {
        [self startPlaying];
        pad.backgroundColor = [UIColor blueColor];
    }
}

- (IBAction)touchUp
{
    if (recordingMode)
    {
        [self stopRecording];
        pad.backgroundColor = [UIColor redColor];
    }
    else
    {
        [self stopPlaying];
        pad.backgroundColor = [UIColor colorWithWhite:0.25 alpha:1];
    }
}
</pre>

</br>
<h2>Conclusion</h2>
<p>Making this app learned me a lot on the iOS SDK and I hope this little tutorial learned you something too.</br>
I'll soon try to put this app on the App Store.</p>      		]]></description>
		<pubDate>Sun, 31 July 2011 12:01:27 UTC</pubDate>
	</item>

        
    
        <item>

		<title>Beatbox App on iPad</title>
		<link>http://www.damienlegrand.com/index.php/blog/article/Beatbox-App-on-iPad</link>
		<guid>http://www.damienlegrand.com/index.php/blog/article/Beatbox-App-on-iPad</guid>
		<image>http://www.damienlegrand.com/public/img/upload/large/Beatbox-App-on-iPad.jpg</image>
		<description><![CDATA[
      		<p>I’m currently learning how to develop apps on iOS (iPhone, iPad, iPod) and I share with you how I’ve done to make one of my first app. As I am starting the development on iOS, this tutorial can be useful for developers beginning on that platform.</p>

<br/>
<h2>The App</h2>

<p>This app is made with Xcode 4 and run on iOS 4.3, but before starting we need to define the specifications of the app. I have made it simple ;)</p>
<p>The app is a beatbox, so we will need some buttons to play a unique sound on each one when the user touches it. But if we want play to some sounds, we actually need to have these sounds, so we will let the user record his own, with a record mode. Finally the user will have the possibility to save a name on each button, so he can remember easily the button’s sound.</br>
Here is a quick video showing what the app is able to do. (You will see that I’m not a musician :D).
</p>
<br/>
<div class="images">
<iframe src="http://player.vimeo.com/video/26808448?portrait=0" width="640" height="480" frameborder="0"></iframe>
</div>

</br>
<h2>Setup of our new app</h2>

<h4 class="accent">Project Files</h4>
<p>First, we create a new window based project. This beat box can be done with a View based project, but I think is better to start from nothing, to understand how everything works.</p>

<div class="images">
<a href="http://www.damienlegrand.com/public/img/illustrations/beatbox-new-project_b.png" rel="box" title="Choose Project Type"><img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-new-project.png" title="Choose Project Type" alt="Window in xcode 4 to choose a new project type" /></a>&nbsp;
<a href="http://www.damienlegrand.com/public/img/illustrations/beatbox-new-project_2_b.png" rel="box" title="Setting New Project"><img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-new-project_2.png" title="Setting New Project" alt="Window in xcode 4 to set information about the new project" /></a>
</div>

</br>
<p>Secondly, we will need two UIViewController. The first one controlling a switch making the app entering in a record mode, and some instances of our second UIViewController. This second UIViewController will control two UIView (One with a button, and another with a text field allowing the user to change the button’s name) and perform the playing/recording actions.</p>

<div class="images">
<img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-schema.png" title="Project's Interface Schema" alt="Schema showing the two different controller of the project" />
</div>

</br>
<p>So we create our two UIViewController subclasses (CMD+N) called PadViewController and PadButtonViewController. Don’t forget to click on "With XIB for user interface".</p>

<div class="images">
<a href="http://www.damienlegrand.com/public/img/illustrations/beatbox-new-class_b.png" rel="box" title="Create a new Class"><img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-new-class.png" title="Create a new Class" alt="Create a new subclass of UIViewController" /></a>
</div>

</br>
<h4 class="accent">Interface</h4>
<p>Now we can make our interface with connections between the Controller and the View.</br>
Open PadViewController.h and add these attributs which will let us connect the controls to the controller in Interface Builder.
</p>

<pre  class="prettyprint">
@interface PadViewController : UIViewController {
    NSMutableArray *pads; //will be a collection of PadButtonViewController
}

@property(nonatomic, retain) IBOutlet UISwitch *rec;
@property(nonatomic, retain) NSMutableArray *pads;

@end
</pre>

<p>And in PadViewController.m inside the implementation:</p>
<pre  class="prettyprint">
@synthesize pads;
@synthesize rec;

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations - here Landscape Left and Right
	return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft
            || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
</pre>

<p>Now we can open PadViewController.xib and make our interface. We will need to place two labels and one switch. To connect the switch to our controller, just ctrl-click on File's Owner (the orange cube) and drag to the switch contol. After that, make sure that the switch state is on off. You should have something like this :</p>

<div class="images">
<a href="http://www.damienlegrand.com/public/img/illustrations/beatbox-interface_b.png" rel="box" title="PadViewController.xib interface"><img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-interface.png" title="PadViewController.xib interface" alt="Screen of the main interface" /></a>&nbsp;
<img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-connection.png" title="File's Owner Connections" alt="File's Owner Connections of PadViewController.xib" />
</div>

<p> As we are done with the PadViewController interface, we can start the PadButtonViewController interface, so in PadButtonViewController.h we put this : </p>

<pre  class="prettyprint">
@interface PadButtonViewController : UIViewController {
    int identifier;
}

@property(nonatomic, retain) IBOutlet UIButton *infoButton;
@property(nonatomic, retain) IBOutlet UITextField *textField;
@property(nonatomic, retain) IBOutlet UIView *moreView;
@property(nonatomic, retain) IBOutlet UIButton *pad;
@property(nonatomic) int identifier;

@end
</pre>

<p>And in PadButtonViewController.m we put inside of the implementation :</p>

<pre  class="prettyprint">
@synthesize pad, infoButton;
@synthesize moreView;
@synthesize textField;
@synthesize identifier;

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return NO;
}
</pre>

<p> Then in PadButtonViewController.xib we can make our interface; First delete the current view, and drag and drop two views, then change their sizes : </p>

<div class="images">
<img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-view-choice.png" title="View Element" alt="View in the list of interface elements" />
<img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-view-size.png" title="Size Configuration" alt="Configuration of the view's size" />
</div>

<p>In the first view we can put a button with a custom type, which will take the same size of the view. This button need to have a dark background.</br>
In the second view, which will be our "moreView", we put a label and a text field.</br>
In the two view we place a button in a bottom right with type "Info Dark" or "Info Light". The Info Button on the first view need to be hidden. It can be done in the Attributes Inspector > View > check the Hidden.</br>
Now we can make connections between File’s Owner and interface elements. (The infoButton IBoutlet have to be connected only with the info button on the first view)</p>

<div class="images">
<a href="http://www.damienlegrand.com/public/img/illustrations/beatbox-padbutton-interface_b.png" rel="box" title="PadViewController.xib interface"><img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-padbutton-interface.png" title="PadButtonViewController.xib interface" alt="Screen of the button interface" /></a>&nbsp;
<img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-connection-button.png" title="File's Owner Connections" alt="File's Owner Connections of PadButtonViewController.xib" />
</div>

<p>￼￼To mix all these interfaces, first of all we call the PadViewController when the app is launched in the My_BeatBoxAppDelegate.</br>
So in My_BeatBoxAppDelegate.h :<p>

<pre  class="prettyprint">
#import &quot;PadViewController.h&quot;

@interface My_BeatBoxAppDelegate : NSObject &lt;uiapplicationdelegate&gt; {
    PadViewController *padView;
}
</pre>

<p>And in My_BeatBoxAppDelegate.m :</p>

<pre  class="prettyprint">
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    padView = [[PadViewController alloc] init];
    [self.window addSubview:padView.view];
    [self.window makeKeyAndVisible];
    return YES;
}
</pre>

<p> Now we have to create 6 PadButtonViewController in PadViewController and put them in the middle of the view.</br>
So we import the PadButtonViewController.h in the PadViewController.h, and when the view is loaded we create these buttons : </p>

<pre  class="prettyprint">
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    pads = [[NSMutableArray alloc] init];
    for (int i = 1; i &lt;= 6; i++) {
        PadButtonViewController *pad = [[PadButtonViewController alloc] initWithNibName:@&quot;PadButtonViewController&quot; bundle:nil];
        [pads addObject:pad];
        pad.identifier = i;
        [self.view addSubview:pad.view];
    }
}
</pre>

<p>As you can see I’m setting an identifier on each PadButtonViewController. It will be useful to know which sound to load when the user touch one of these buttons.</br>
To place the view at the good place we can set the frame on each one in their respective viewDidLoad (PadButtonViewController.m) :</p>

<pre  class="prettyprint">
- (void)viewDidLoad
{
    [super viewDidLoad];
    if (identifier != 0) {
        
        int marge = 30;
        
        int width = 225;
        int height = 200;
        
        int line = 0;
        int pos = (identifier-1);
        if (identifier &gt; 3){
            line = 1;
            pos = pos - 3;
        }
        self.view.frame = CGRectMake( 144.5 + (pos * (width+marge)), 169 + (line*(height + marge)), width, height);
    }
}
</pre>

<p>Oh, and for the good practice, we have to nil every Outlets in the viewDidUnload :</p>

<pre  class="prettyprint">
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    pad = nil;
    infoButton = nil;
    moreView = nil;
    textField = nil;
}
</pre>

<p>We do the same in for PadViewController :</p>

<pre  class="prettyprint">
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    rec = nil;
}
</pre>

<p>We are done with the interface, now we need some interactions.</p>

</br>
<h2>Interactions</h2>

<p>Our app will have two states :</p>

<ul>
<li>Playing Mode</li>
<li>Recording Mode</li>
</ul>
</br>
<p>So the switch on the PadViewController, will help us know in which mode we are. But in PadButtonViewController we need to add an attribut (Boolean) to know in which mode the button is, and another one to know if the user is on the more Info view. So in PadButtonViewController.h, inside the @interface brackets we add : 
</p>

<pre  class="prettyprint">
BOOL recordingMode;
BOOL infoMode;
</pre>

<p>and after the bracket :</p>

<pre  class="prettyprint">
@property(nonatomic) BOOL recordingMode;
@property(nonatomic) BOOL infoMode;

- (IBAction)changePadName;
- (IBAction)moreInfo;
- (IBAction)touchDown;
- (IBAction)touchUp;
</pre>

<p>You can see that we add some IBAction methods, and we need to define them in the .m file, inside the implementation :</p>

<pre  class="prettyprint">
@synthesize recordingMode, infoMode;

//Called when the user type something in the text field on the moreInfo view
- (IBAction)changePadName
{

}

//Called when the user touch the info buttons in the bottom right of the views
- (IBAction)moreInfo
{

}

//Called when the user touch the button 'pad'
- (IBAction)touchDown
{

}

//Called when the user touch up the button or drag his finger outside of the button
- (IBAction)touchUp
{

}
</pre>

<p>Now we can go in the PadButtonViewController.xib file and connect these IBAction to the good interface elements. You should have that in the File's Owner Connection Inspector: </p>

<div class="images">
<img src="http://www.damienlegrand.com/public/img/illustrations/beatbox-connection-actions-button.png" title="File's Owner Received Actions" alt="File's Owner Received Actions of PadButtonViewController.xib" />
</div>

<p>The PadViewController need just one IBAction. It will be called when the value is changed on the switch. So in PadViewController.h :</p>

<pre  class="prettyprint">
- (IBAction)changeState:(id)sender;
</pre>

<p>and in the .m file :</p>

<pre  class="prettyprint">
- (IBAction)changeState:(id)sender
{

}
</pre>

<p>Now we can connect it to the switch in the .xib file.</p>

<br/>
<h2>The change of state</h2>

<p>As I said before, this app has two states. The user can use the switch to define the state he want to use. So when it's turned on, the PadViewController has to say to all the PadButtonViewController that they have to change their state to a recording mode; And in playing mode when it's turned off.</br>
The user also need to know in which state the app is. So we will change the buttons background color to red.</p>

<p>So inside the "changeState" method in the PadViewController.m file put this code :</p>

<pre  class="prettyprint">
UISwitch *theSwitch = (UISwitch *)sender;
for (PadButtonViewController *pad in pads) {
        [pad setRecordingMode:theSwitch.on];
}
</pre>

<p>So we set the switch's state to our PadButtonViewControllers by setting the "recordingMode" attribute. But in order the change the button's color, we have to override the setter method of this attribute in the PadButtonViewController.m :</p>

<pre  class="prettyprint">
-(void)setRecordingMode:(BOOL)value
{
    recordingMode = value;
    [UIView animateWithDuration:0.7
                                        delay:0 
                                      options:UIViewAnimationOptionBeginFromCurrentState 
                                 animations:^{
                                     if (recordingMode) {
                                         //Recording color
                                         pad.backgroundColor = [UIColor redColor];
                                     }else{
                                         //Playing Color
                                         pad.backgroundColor = [UIColor colorWithWhite:0.25 alpha:1];
                                     }
                                 } 
                               completion:nil];
    
    infoButton.hidden = !value; //if in recording mode we show the info button so the user can go on the moreView
}
</pre>

<p>You can see here that we are making an animation. This animation is actually making a smoothly change of color. After that we are showing our info button only if the PadButtonViewController is in recording mode.</p>

<p>Then we have to make the transition between the button in recording mode and the more view. We will use the flip animation. So in the the "moreInfo" method add this code :</p>

<pre  class="prettyprint">
[UIView beginAnimations: @&quot;flip&quot; context: nil];
[UIView setAnimationDuration: 0.5f];
[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:self.view cache: YES];
    
infoMode = !infoMode;
if (infoMode)
{
    [self.view addSubview:moreView];
}
else
{
    [moreView removeFromSuperview];
}
[UIView commitAnimations];
</pre>

<p>We now have an issue! When the user flip on the "more view" of one or more PadButtonViewController, and switch to the playing mode, the more view still here. To solve this just put this line of code in the for loop of the changeState method (PadViewController.m) :</p>

<pre  class="prettyprint">
if(!theSwitch.on &amp;&amp; pad.infoMode) [pad moreInfo];
</pre>

<p>Now we need to define the default states of our PadButtonViewControllers. The right place to do that is in the initWithNibName:bundle: method :</p>

<pre  class="prettyprint">
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        identifier = 0;
        infoButton.hidden = YES;
        recordingMode = NO;
        infoMode = NO;
    }
    return self;
}
</pre>

</br>
<h2>What's next ?</h2>

<p>Now that we can navigate through our application, the next step will be to add some interaction with the main button to perform some playing and recording. We will use the AVFoundation framework to do this, and I'll show you how in a future article.</p>

<ul>
<li><a href="http://www.damienlegrand.com/blog/article/Beatbox-App-on-iPad-Part-Two">Beatbox App on iPad - Part Two</a></li>
</ul>      		]]></description>
		<pubDate>Tue, 26 July 2011 16:01:29 UTC</pubDate>
	</item>

        
    
        <item>

		<title>HTML5 Canvas with Processing.js</title>
		<link>http://www.damienlegrand.com/index.php/blog/article/HTML5-Canvas-with-Processingjs</link>
		<guid>http://www.damienlegrand.com/index.php/blog/article/HTML5-Canvas-with-Processingjs</guid>
		<image>http://www.damienlegrand.com/public/img/upload/large/HTML5-Canvas-with-Processingjs.jpg</image>
		<description><![CDATA[
      		<p>Recently I was searching for some documentation about the HTML5’s canvas element. And what I found is <a href="http://processingjs.org/" target="_blank">Processing.js</a>, which is a project that let you code visual applications and generate it as web standard. What is puzzling is that in fact, you are not coding with JavaScript, but with the Processing language, similar to Java. At beginning I was lost; I was wondering how to get values from a form in my Processing.js application. But after some time I find a solution to use basic JavaScript with Processing.js.</p>

<br/>
<h2>Brief Introduction to Processing</h2>
<p>The Processing.js’s logic is pretty easy to understand. First of all you have two important functions to override:
<ul>
<li>setup()</li>
<li>draw()</li>
</ul>
</p>
<p>
Processing call setup() at the start of the application. It means that you can set here some global variables. And the draw() function is called every time to let you draw some animations.
</p>

<pre class="prettyprint">
int size_x = 900;
int size_y = 300;
int frame_rate = 100; 

void setup(){
        size( size_x, size_y );
        frameRate( frame_rate );
}

void draw(){
	background(0,0,0);
	rect(0,0,100,100);
}
</pre>

<p>Here it’s a simple example of a processing code. We have three global variables. In our setup function we use these global variables to set the size of our final canvas, and the frame rate with a value of 100; so the draw function will be called 100 times per seconds. In result here, we have no animation, but just a white square of 100 pixels at the top left, on a black background.<br/>
If we want that result visible in our html page, this code has to be in a .pjs file. In the html we need to import processing.js with this line of code:
</p>

<pre class="prettyprint">
&lt;script language=&quot;javascript&quot; src=&quot;processing.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
</pre>

<p>And finally in the body we have to add a canvas element importing our .pjs file:</p>

<pre class="prettyprint">
&lt;canvas data-processing-sources=&quot;code.pjs&quot;&gt;&lt;/canvas&gt;
</pre>

<br/>
<h2>How to get values from user in Processing’s code</h2>
<p>As I said, I had some issues on that. What is important here to understand is that Processing doesn’t use the same variable types as JavaScript.<br/>
So the procedure is simple. We need a JavaScript function in our html returning a value. This function can be called in the processing code (.pjs) and be cast, so the value corresponds to the variable type. Here is a quick example.
</p>

<pre class="prettyprint">
&lt;script language=&quot;javascript&quot; type=&quot;text/javascript&quot;&gt;
                function getNbInput(){
                        return $('input').length;
                }        
&lt;/script&gt;
</pre>

<p>Here is a simple function returning the number of input in our html. Note that here I’m using jQuery which have to be imported before.</p>

<p>Now in our .pjs:</p>

<pre class="prettyprint">
void draw(){
	int nb_input = (int)getNbInput();
	for(int i = 0; i &lt; nb_input; i++){
		String message = “Input Number ”+(i+1);
		text(message, 0, i*20);
	}
}
</pre>

<p>Here we save the number of input from our JavaScript function casted as an integer in the nb_input variable, and print a list of message corresponding to the number of input in the DOM.</p>

<br/>
<h2>Demo</h2>
<p>You can see a quick demo of a chart animation using input’s values, you just need to click on the animation. Nevertheless, if you want to see more demos, you can find some on <a href="http://processingjs.org/exhibition" target="_blank">http://processingjs.org/exhibition</a></p>

<link href='http://www.damienlegrand.com/public/demo/chart.css' rel='stylesheet' type='text/css'/>
<script language="javascript" src="http://www.damienlegrand.com/public/demo/processing-1.2.1.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
        
                //*******************************//
                //    Functions to access dom    //
                //*******************************//
        
                function getNbInput(){
                        return $('#demo tr').length;
                }
                
                function getNameAtIndex(i){
                        var elem = $('#demo tr').get(i);
                        var name = $('td:first-child', elem).text();
                        return name;
                }
                
                function getValAtIndex(i){
                        var elem = $('#demo tr').get(i);
                        var val = $('input', elem).val();
                        return val;
                }
                
                $(function(){
                        $('canvas').click(function(){
                                $('#demo input.demo_input').attr("disabled", true);
                        });
                });
        </script>
<div id="demo">

<div class="wrapper">
                <h1>Chart</h1>
                <table border=0 cellpadding="5" cellspacing="0" class="form">
                        <tr>
                                <td class="name">January</td>
                                <td><input name="1" class="demo_input" value="124"/></td>
                        </tr>
                        <tr>
                                <td class="name">February</td>
                                <td><input name="2" class="demo_input" value="42"/></td>
                        </tr>
                        <tr>
                                <td class="name">March</td>
                                <td><input name="3" class="demo_input" value="205"/></td>
                        </tr>
                        <tr>
                                <td class="name">April</td>
                                <td><input name="4" class="demo_input" value="175"/></td>
                        </tr>
                        <tr>
                                <td class="name">May</td>
                                <td><input name="5" class="demo_input" value="237"/></td>
                        </tr>
                        <tr>
                                <td class="name">June</td>
                                <td><input name="6" class="demo_input" value="100"/></td>
                        </tr>
                </table>
                <table border=0 cellpadding="5" cellspacing="0" class="form">
                        <tr>
                                <td class="name">July</td>
                                <td><input name="7" class="demo_input" value="43"/></td>
                        </tr>
                        <tr>
                                <td class="name">August</td>
                                <td><input name="8" class="demo_input" value="14"/></td>
                        </tr>
                        <tr>
                                <td class="name">September</td>
                                <td><input name="9" class="demo_input" value="64"/></td>
                        </tr>
                        <tr>
                                <td class="name">October</td>
                                <td><input name="10" class="demo_input" value="82"/></td>
                        </tr>
                        <tr>
                                <td class="name">November</td>
                                <td><input name="11" class="demo_input" value="115"/></td>
                        </tr>
                        <tr>
                                <td class="name">December</td>
                                <td><input name="12" class="demo_input" value="163"/></td>
                        </tr>
                </table>
                <canvas id="demo_graph" data-processing-sources="http://www.damienlegrand.com/public/demo/chart.pjs"></canvas>
                <div style="clear: both"></div>
</div>

</div>

<br/>
<h2>Download</h2>
<p>Even if the demo is not perfect, you can still download the code source from the demo here: <a href="http://www.damienlegrand.com/public/files/chart.zip">Sources</a></p>      		]]></description>
		<pubDate>Fri, 8 July 2011 13:37:44 UTC</pubDate>
	</item>

        
    
        <item>

		<title>How to Parse CSV with PHP</title>
		<link>http://www.damienlegrand.com/index.php/blog/article/How-to-Parse-CSV-with-PHP</link>
		<guid>http://www.damienlegrand.com/index.php/blog/article/How-to-Parse-CSV-with-PHP</guid>
		<image>http://www.damienlegrand.com/public/img/upload/large/How-to-Parse-CSV-with-PHP.jpg</image>
		<description><![CDATA[
      		<h2>What is CSV?</h2>
<p>CSV, for Comma Separated Values, is a format where tabular data are stored separated by commas and line breaks. It is really easy to use and understand as you can see with the next exemple:</p>

<pre class="prettyprint">
Name,Movie
Darth Vader,Star Wars
Keyser Soze,Usual Suspect
Hannibal Lecter,Silence of the Lambs
</pre>

<br/>
<h2>Why CSV?</h2>
<p>In every company, people are using spreadsheet applications (Excel), so it’s always useful for a developer to play with spreadsheet’s data. And what is interesting is that Excel can save it as CSV.</p>

<div class="images">
<img src="http://www.damienlegrand.com/public/img/illustrations/csv_excel.png" title="CSV Format" alt="Select the CSV format to save a spreadsheet" />
</div>

<br/>
<h2>My CSV Class</h2>
<p>I’ve made a little class that you can use as a starter or a little tool to play with some CSV. <s>Just be carful, this class work only with PHP >= 5.3.</s> Now work with previous versions.</p>
<br/>
<h4>Methods</h4>
<ul>
<li>SetDelimiter($delimiter) (Normally, it’s always a comma (the C from CSV…) but we never know)</li>
<li>SetRowDelimiter($delimiter_row)</li>
<li>SetCsvFromString($string)</li>
<li>SetCsvFromFile($path)</li>
<li>AddToCsvFromString($string)</li>
<li>AddToCsvFromFile($path)</li>
<li>GetArray()</li>
<li>GetHtmlTable($attrs)</li>
<li>GetRowNumber()</li>
<li>GetColumnNumber()</li>
</ul>

<br/>
<h2>Example of use</h2>

<pre class="prettyprint">
$csv = new CSV();
$csv-&gt;SetCsvFromFile('test.csv');
$csv-&gt;AddToCsvFromString($_POST['csv']);
echo $csv-&gt;GetHtmlTable();
echo '&lt;div class=&quot;highlight&quot;&gt;There are '.$csv-&gt;GetColumnNumber().' columns&lt;/div&gt;';
echo '&lt;div class=&quot;highlight&quot;&gt;There are '.$csv-&gt;GetRowNumber().' rows of data&lt;/div&gt;';
</pre>

<p>So this little code takes data from “test.csv” file and adds more data with the content of the post variable named "csv". After that we can print an html table representing the final CSV. And finally we show how many columns and rows we have. As you can see this class is really easy to use.</p>

<br/>
<h2>Demo</h2>
<p>This demo use the class to take a CSV from the form and generate an HTML Table with it.</p>

<link href='http://www.damienlegrand.com/public/demo/csv.css' rel='stylesheet' type='text/css'/>
<script language="javascript" src="http://www.damienlegrand.com/public/demo/csv.js" type="text/javascript"></script>
<div id="demo">

<div class="wrapper">
                <h1>CSV</h1>
                <form>
                        <textarea name="csv" id="csv">First Name,Last Name,Age
Damien 1,Legrand 1,21
Damien 2,Legrand 2,22
Damien 3,Legrand 3,23
Damien 4,Legrand 4,24
Damien 5,Legrand 5,25
Damien 6,Legrand 6,26
Damien 7,Legrand 7,27
Damien 8,Legrand 8,28
Damien 9,Legrand 9,29
Damien 10,Legrand 10,30
Damien 11,Legrand 11,31
Damien 12,Legrand 12,32
Damien 13,Legrand 13,33
Damien 14,Legrand 14,34</textarea>
                        <input type="submit" name="submit" class="submit" value="Generate Table from CSV"/>
                </form>
                <div class="return">
                        
                </div>
<div style="clear:both"></div>
</div>

</div>

<br/>
<h2>Download</h2>
<p>You can of course download source code with a demo inside ;) : <a href="http://www.damienlegrand.com/public/files/csv.zip">CSV Source Code</a></p>      		]]></description>
		<pubDate>Wed, 6 July 2011 14:24:11 UTC</pubDate>
	</item>

        
    
        <item>

		<title>How to Make a Sliding Box with jQuery</title>
		<link>http://www.damienlegrand.com/index.php/blog/article/How-to-Make-a-Sliding-Box-with-jQuery</link>
		<guid>http://www.damienlegrand.com/index.php/blog/article/How-to-Make-a-Sliding-Box-with-jQuery</guid>
		<image>http://www.damienlegrand.com/public/img/upload/large/How-to-Make-a-Sliding-Box-with-jQuery.jpg</image>
		<description><![CDATA[
      		<p>In this article I will show you how to make a sliding image showing the caption on mouse over, and because we are now in a world where websites need to be clear and fun to use, we will use for the fun part, animations from jQuery, and for the clean part the overflow CSS property.</p>

<br/>
<h2>What is the overflow property?</h2>

<p>A container having the property overflow set with <b>scroll</b>, <b>auto</b> or <b>hidden</b> constrain his content to be render inside. The scroll value will add scrollbar around the container to see all his content, as the auto value, if the content is really overflowing. Here we will use the hidden value, which will give us the opportunity to hide the caption under the image.</p>

<br/>
<h2>First Part: The HTML</h2>

<p>
First of all we need to use the basic html template and inserting in the body the content that we want to show.
Here is the content: <br/>
</p>

<pre class="prettyprint">
&lt;div id=&quot;test&quot;&gt;
		
     &lt;div id=&quot;content&quot;&gt;
                	
          &lt;img src=&quot;image/stormtrooper.jpg&quot; width=&quot;500px&quot; height=&quot;333px&quot;/&gt;
	  &lt;div id=&quot;sub&quot;&gt;This is a Stormtrooper from the Galactic Empire's Army&lt;/div&gt;
				
     &lt;/div&gt;
			
&lt;/div&gt;
</pre>

<p>The div with the identifier “Test” is our container doing an overflow: hidden. The div with the identifier “content” is the container of the different things we want to show (an image and a caption which is in the "sub" div). As we want to slide the "content" div in the "test" div, we need to set an absolute position on "content" relative to the "test" div. So let start with the CSS.</p>

<br/>
<h2>Second Part: The CSS</h2>

<p>To have a great design, the next CSS uses property from CSS3, so it certainly won’t work in every browser like Internet Explorer 6 or 7 or hummm 8. (Hope it works on IE9 as they say that it’s fully HTML5…)</p>

<pre class="prettyprint">
#test {
        height: 333px;
        margin: 100px auto auto auto;
        overflow: hidden;
        position: relative;
        width: 500px;
        
        -webkit-box-shadow:     0px 4px 3px rgba(0,0,0,0.2),
                                          0px 8px 13px rgba(0,0,0,0.1),
                                          0px 18px 23px rgba(0,0,0,0.1),
                                          0px -10px 12px rgba(0,0,0,0.03);
        
        -moz-box-shadow:        0px 4px 3px rgba(0,0,0,0.2),
                                0px 8px 13px rgba(0,0,0,0.1),
                                0px 18px 23px rgba(0,0,0,0.1),
                                0px -10px 12px rgba(0,0,0,0.03);
        
        box-shadow:             0px 4px 3px rgba(0,0,0,0.2),
                                0px 8px 13px rgba(0,0,0,0.1),
                                0px 18px 23px rgba(0,0,0,0.1),
                                0px -10px 12px rgba(0,0,0,0.03);
}

#content {
        position: absolute;
        width: 100%;
}

#content img {
        float: left;
}

#sub{
        float: left;
        height: 100px;
        padding: 42px 5px 0px 5px;
        width: 490px;
        
        background-image: -moz-linear-gradient(#686868, #232323);
        background-image: -webkit-linear-gradient(#686868, #232323); 
        background-image: -o-linear-gradient(#686868, #232323);

        color: #ffffff;
        font-size: 14px;
        text-align: center;
        text-shadow: 1px 1px 0px rgba(0,0,0,0.5);
} 
</pre>

<p>Here we set the same size for the ‘test’ container as the image we have to show and of course we hide what is overflowing in it.<br/>
To put the "content" div in the absolute top left of the "test" div, the position of "test" has to be set as relative and "content" has absolute.
</p>

<br/>
<h2>Final Part: jQuery</h2>

<p>Now we need to animate the slide. We want that the image go up with the caption showing under when the cursor is over the image. To do this, first we need to import jQuery in our html file with this line of code:</p>
<pre class="prettyprint">
&lt;script type=&quot;text/javascript&quot; src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js&quot;&gt;&lt;/script&gt;
</pre>

<br/>
<p>And now we can make the animation happening with the hover event.</p>

<pre class="prettyprint">
$(function(){
	$(&quot;#test&quot;).hover(function(){
		$(&quot;#content&quot;, this).stop().animate({&quot;top&quot;: &quot;-100px&quot;}, 250);
	},function(){
		$(&quot;#content&quot;, this).stop().animate({&quot;top&quot;: &quot;0px&quot;}, 200);
	});
});
</pre>

<br/>
<p>So here we use the jQuery event function "hover" on our "test" div. This function takes two functions as parameters. The first function is called when the mouse enter over the "test" element, and the second is called when the mouse leave the "test" element. And what we just need to do in these functions is to animate the top property of the "content" div and set duration to the animation, so that our content can slide up.
You can notice that the stop function is used before doing the animation. It’s useful to stop the animation if the mouse doesn’t stay enough time over the element.
</p>

<br/>
<h2>Demo</h2>
<p>Put your mouse over this image and see the magic happen :p</p>

<link rel="stylesheet" type="text/css" href="http://www.damienlegrand.com/public/demo/slidingbox.css" />
<script type="text/javascript" src="http://www.damienlegrand.com/public/demo/slidingbox.js"></script>
<div id="demo">
<div class="test">
		
     <div class="content">
                	
          <img src="http://www.damienlegrand.com/public/demo/slidingbox.jpg" width="500px" height="333px" title="Stormtrooper" alt="stormtrooper showing how to use jquery and css"/>
	  <div class="sub">This is a Stormtrooper from the Galactic Empire's Army</div>
				
     </div>
			
</div>
</div>

<br/>
<h2>Download</h2>
<p>You can download the code source just here : <a href="http://www.damienlegrand.com/public/files/slidingbox.zip">HERE</a></p>      		]]></description>
		<pubDate>Tue, 5 July 2011 14:37:56 UTC</pubDate>
	</item>

        
    
        <item>

		<title>Generate a Pdf with PHP</title>
		<link>http://www.damienlegrand.com/index.php/blog/article/Generate-a-Pdf-with-PHP</link>
		<guid>http://www.damienlegrand.com/index.php/blog/article/Generate-a-Pdf-with-PHP</guid>
		<image>http://www.damienlegrand.com/public/img/upload/large/Generate-a-Pdf-with-PHP.jpg</image>
		<description><![CDATA[
      		<p>I had to make PDF in PHP, so I found FPDF which is a fantastic tool to draw a pdf file. But I had to make some different kinds of pdf with a unique template. So I made a subclass of FPDF and called it EasyPdf.<br/>
I share with you my work and hope it will help some developers.</p>

<h2>What EasyPdf can do ?</h2>
<ul>
<li>Print a header with a big title and an image under.</li>
<li>Print a text with a title.</li>
<li>Print a list from an array with a title.</li>
<li>Print table of data.</li>
<li>Print the page number on footer.</li>
<li>Set a background image to print on each page.</li>
<li>Set a header text to print on each page.</li>
<li>Set a footer text to print on each page.</li>
</ul>
<br/>
<h2>Example of use</h2>
<p>I think I've well commented this exemple, so enjoy.</p>
<br/>
<pre class="prettyprint">

&lt;?php
include('easypdf.php');

//PDF is not in UTF-8 so € and º don't work
//if we don't convert it in another encodage
define('EUR', iconv('UTF-8', 'windows-1252', &quot;€&quot;));
define('DEG', iconv('UTF-8', 'windows-1252', &quot;º&quot;));

$footer = &quot;Lorem ipsum dolor sit amet, consectetur adipiscing.&quot;;
$footer .= &quot;nClass aptent taciti sociosqu ad litora torquent&quot;;

//Create new PDF
$pdf = new EasyPdf(false, $footer);

//Configure PDF
$pdf-&gt;SetBackgroundImage('./images/pdf-background.jpg');
$pdf-&gt;SetAccentColor(50, 50, 100);
$pdf-&gt;SetTableFillColor(150, 150, 200);
$pdf-&gt;HeaderPage(&quot;Big Title&quot;, './images/header.jpg');

//Data
$information = array(
    'Reference' =&gt; '123456qwerty',
    'Date' =&gt; '2011-07-01',
    'Price' =&gt; '123,456.78'.EUR,
    'Comment' =&gt; &quot;Lorem ipsum dolor sit amet.nUt pellentesque pulvinar laoreet.&quot;,
);
$more_info = array(
    'First Name' =&gt; 'Legrand',
    'Last Name' =&gt; 'Damien',
    'Age' =&gt; 23
);
$text = &quot;Lorem ipsum dolor sit amet, consectetur adipiscing.&quot;;
$text .= &quot; Ut pellentesque pulvinar laoreet.&quot;;
$text .= &quot; Cras sapien enim, dapibus vitae molestie sed,&quot;;
$text .= &quot; volutpat eget ligula. Donec justo diam,&quot;;
$text .= &quot; fermentum non tincidunt id, congue vitae enim.&quot;;
$text .= &quot; Ut blandit interdum sapien, eget venenatis quam.&quot;;
$text .= &quot; Nullam accumsan odio quis tellus interdum semper.&quot;;
$text .= &quot; Mauris pharetra libero eget ante aliquet ornare.&quot;;
$text .= &quot; nClass aptent taciti sociosqu ad litora torquent,&quot;;
$text .= &quot; per inceptos himenaeos. Curabitur vel eros nisi.&quot;;
$text .= &quot; Cras gravida facilisis risus, sed semper tortor.&quot;;
$text .= &quot; Suspendisse ac mi sit amet sapien consectetur.&quot;;
$text .= &quot; Lorem ipsum dolor sit amet, consectetur.&quot;;
$text .= &quot; Pellentesque a tincidunt tortor.&quot;;

//Add some different kinds of lists
$pdf-&gt;AddList($information, 'Big List');
$pdf-&gt;AddListMin($more_info, &quot;List Left&quot;);
$pdf-&gt;AddListMin($more_info, &quot;List Right&quot;, 'R', true, true);

//Add a text block
$pdf-&gt;AddText($text, &quot;Lorem Ipsum Title&quot;);

//Change page and add a header text
$pdf-&gt;header = &quot;Header Text&quot;; //false for delete
$pdf-&gt;AddPage();

//Add a table
$pdf-&gt;SetHeadingTable('', 'Price', 'QTY');
$pdf-&gt;SetColumnAlignTable('L', 'C', 'C');
$pdf-&gt;SetColumnSizeTable(90, 50, 50);

$tot_price = 0;
$tot_qty = 0;

for($i = 1; $i &lt;= 8; $i++)
{
        $name = &quot;Row N&quot;.DEG.$i;
        $price = 111*$i;

        //Add a new row to the table
        $pdf-&gt;AddRowTable($name, $price.EUR, $i);
        
        $tot_price += $price*$i;
}

$pdf-&gt;AddTotalRowTable('TOTAL', '', number_format($tot_price, 2).EUR);
$pdf-&gt;AddTable(&quot;Order&quot;);

$pdf-&gt;ClearTable();

//And add another table and change colors

//Print a title
$pdf-&gt;AddTitle(&quot;Product&quot;);

//Change colors
$pdf-&gt;SetAccentColor(120, 110, 200);
$pdf-&gt;SetTableFillColor(220, 210, 255);
$pdf-&gt;SetLineColor(255, 255, 255); //White lines

$pdf-&gt;SetHeadingTable('Name', 'Price', 'Stock', 'Other');
$pdf-&gt;SetColumnAlignTable('L', 'C', 'C', 'R');
$pdf-&gt;SetColumnSizeTable(75, 50, 50, 15);

for($i = 1; $i &lt;= 8; $i++)
{
        $name = &quot;Product N&quot;.DEG.$i;
        $price = 1112*$i;

        //Add a new row to the table
        $pdf-&gt;AddRowTable($name, $price.EUR, $i*10, 'YES');
}

//Print the table without the title and with small font
$pdf-&gt;AddTable(false, true);

$pdf-&gt;SetAccentColor(45, 200, 120);
$pdf-&gt;SetLineColor(0, 0, 0);

//Different kinds of titles
for($i = 1; $i &lt;= 6; $i++)
{
        $pdf-&gt;AddTitle(&quot;Title $i&quot;, $i);
        $pdf-&gt;Ln(5);
}

//Information about the PDF
$pdf-&gt;SetAuthor('Damien Legrand');
$pdf-&gt;SetTitle('EasyPdf Exemple');

//Print the PDF
$pdf-&gt;Output();

</pre>

<br/>
<h2>Demo</h2>
<p>And this is what you get with this little script : <a href="http://www.damienlegrand.com/public/demo/demo_EasyPdf.pdf" target="_blank">PDF</a></p>

<br/>
<h2>Download</h2>
<p>You can download EasyPdf with FPDF 1.7 here : <a href="http://www.damienlegrand.com/public/files/easypdf.zip">EasyPdf</a><br/>
And FPDF can be found on this website : <a href="http://www.fpdf.org/" target="_blank">www.fpdf.org</a></p>      		]]></description>
		<pubDate>Sat, 2 July 2011 6:28:45 UTC</pubDate>
	</item>

        
    
</channel>
</rss> 