tree on mac os x ft. dart

Long time ago I wrote a small dart script which prints a light nice tree in the console. You can find it on github here: https://github.com/mrwonderman/dart-tree

Simply check it out and then use the following steps to integrate it. After that you can use it for example, the terminal of mac os x, which hasn’t got a native tree command.

1. edit your .profile file in your home directory

Screen Shot 2013-07-04 at 21.51.17

2. add a new line, which contains something like that:

Screen Shot 2013-07-04 at 21.53.09

vi can be a bit tricky. You need to press ‘i’ first to switch to the insert view. Then write the new line, press the ESC-key and write ‘:w’ and press enter. This saves the document. Type ‘:q’ to close the document. Use the location where you checked out the tree.dart script. Maybe you need to add dart to your PATH var, if you haven’t already:

Screen Shot 2013-07-04 at 21.55.49

3. Restart the terminal and run tree in a folder of your choice:

Screen Shot 2013-07-04 at 21.58.52

If you have any questions or feature-request, do let me know on github.

Dart: Calculate all occurrences of a substring

I recently wanted to calculate all occurrences of a substring in a string with Dart. The code I used is nearly the same as you would use in Java to do this. So here’s my snippet for Dart:

int countOccurences(mainString, search) {
 int lInx = 0;
 int count =0;
 while(lInx != -1){
 lInx = mainString.indexOf(search,lInx);
 if( lInx != -1){
 count++;
 lInx+=search.length;
 }
 }
 return count;
}

You can now simply call it like that:

int countAll = countOccurences(sameRandomString, "smile");

Dart: functions

I wanted to give you some short snippets about functions in dart. They can really help you. The first thing is how you can write a method in one line:

sayHello() => "Hello";

This is helpful for dummy stuff and so on. But now something more special. This parameters in square brackets is known as optional positional parameter. An example:

String saySomething(String thingToSay, [String name]){
 if(name != null){
 return "$thingToSay $name";
 } else {
 return thingToSay;
 }
 }

You then can call this method in 2 ways.

  1. print(saySomething(“I really like pasta”));
  2. print(saySomething(“I really like”, “Dart”));

But when you want to write more readable code, then try the optional named parameter.  For this you can use curly brackets. You can give a default value too. An example:

screamAndShout(String scream, {int times: 1}){
 for(int i = 0; i<times;i++){
 print(scream.toUpperCase());
 }
 }

The usage looks like this:

  1. screamAndShout(“i love dart”, times : 4);
  2. screamAndShout(“i love dart”);

I think all of this things can really help.

Dart: Math Constants

Another small feature of the dart math library are math constants. Just import the following line:

import 'dart:math' as math;

This are all the math constants the library knows:

E (Base of the natural logarithms)

print(math.E);

Result: 2.718281828459045

PI

print(math.PI);

Result: 3.141592653589793

SQRT2 (Square root of 2)

print(math.SQRT2);

Result: 1.4142135623730951

LN10 (Natural logarithm of 10)

print(math.LN10);

Result: 2.302585092994046

LN2 (Natural logarithm of 2)

print(math.LN2);

Result: 0.6931471805599453

LOG10E (Base -10 logarithm of [E])

print(math.LOG10E);

Result: 0.4342944819032518

LOG2E (Base -2 logarithm of [E])

print(math.LOG2E);

Result: 1.4426950408889634

SQRT1_2 (Square root of 0.5)

print(math.SQRT1_2);

Result: 0.7071067811865476

Dart: Trigonometry

Here are some examples for this topic.

import 'dart:math' as math;

void main() {
var beta = 40;
var radians = beta * (math.PI / 180);
print("beta = $beta°: $radians");

var sinBeta = double.parse(math.sin(radians).toStringAsPrecision(3));
var cosBeta = double.parse(math.cos(radians).toStringAsPrecision(3));
var tanBeta = double.parse(math.tan(radians).toStringAsPrecision(3));

print("sinus : $sinBeta");
print("cosinus : $cosBeta");
print("tangens : $tanBeta");
}

Its very simple, and there is something real cool about Dart that we see here:

toStringAsPrecision(3)

This automatically rounds the number up or down. So the number -1.117214930923896 gets -1.12. I think this really makes many things easier when you work with this kind of math things. Another nice thing that you can see here is the following print-method:

print("beta = $beta°");

No need to use tokens like ‘+’ or ‘.’. Just use ‘$’. By the way, the output looked like that:

beta = 40°: 0.6981317007977318
sinus : 0.643
cosinus : 0.766
tangens : 0.839

Dart: sqljocky example

This time we want to get the data from the database directly. We will use the sqljocky package to do this. First of all we create a new console dart application. After that we need to get the package from the pub.

  1. Create a pubspec.yaml file in the project and add the following text:
     name: my_app
     dependencies:
      web_ui: any
  2. Rightclick on the pubspec.yaml file and choose Tools > Pub Install.
    Screen Shot 2013-01-27 at 12.44.10
  3. Now you can see a new package in the packages folder:
    Screen Shot 2013-01-27 at 12.50.26

In the .dart file we now need to add the import to the package:

import 'package:sqljocky/sqljocky.dart';

Now we can access this package. The following code is doing the whole action:

void main() {
 var con = new ConnectionPool(host: 'localhost', port: 3306, user: 'root', password: null, db: 'mymusic', max: 5);
 con.query('select albumName, interpret from cd').then((result)
 {
  var row;
  for (row in result) {
  print('album: ${row[0]} (${row[1]})');
 }
}
);
}

The code is real simple. The library is really doing a lot for us. To read from the result of the select-statement we can use a simple foreach snippet:

var row;
for (row in result) {
 print('album: ${row[0]} (${row[1]})');
}

The output in the console looks like that:

Screen Shot 2013-01-27 at 13.10.04

This are the things I really love about dart. Just a few easy lines of code for a great result.

Dart: Parse JSON to object

As we saw in the first post: http://www.signer.pro/lets-meet-dart/ its real easy to work with Dart. We want to parse the JSON-Objects, that you can get here(http://api.signer.pro/client.php?action=getCds) to Dart-Objects. First of all we will write a normal console application and after that a web application where we display the data a bit nicer.

Dart Console Application

First of all we create a cd-class with all the information we need:

class Cd {
  num id;
  String album;
  String interpret;

 Cd(num id, String album, String interpret){
  this.id = id;
  this.album = album;
  this.interpret = interpret;
 }

 Cd.fromJson(Map json){
  id = json['id'];
  album= json['album'];
  interpret = json['interpret'];
 }
}

Some of the relevant data types in our example are num and String. There is also bool, but we don’t need that one in the example.

So after we wrote the Dart-Object, let’s work with the main-method:

void main() {
List<Cd> listOfCds = new List<Cd>();
var httpClient = new HttpClient();
var conn = httpClient.getUrl(new Uri('http://api.signer.pro/client.php?action=getCds'));
conn.onResponse = (HttpClientResponse resp) {
var input = resp.inputStream;
input.onData = () {
var data = input.read();
var text = new String.fromCharCodes(data);
List l = JSON.parse(text);
l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});
listOfCds.forEach((cd) {
print("album = ${cd.album} interpret = ${cd.interpret}");
});
};
input.onClosed = () => httpClient.shutdown();
};
}

We created a httpClient with the URL to the API. Then we get the response and get the text with the following command:

var text = new String.fromCharCodes(data);

Then we parse the JSON-text into a List. Because we’ve got a JSON-Array with some JSON-Objects. And now something that I love the most of the Dart-Language:

l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});

This way, we can simply loop through a list and do something with the objects. In this case we map the value with the key ‘id’ or ‘album’ and create a Cd-Object with it. After that we add it to a list of Cd’s we defined earlier.

pp1

So, as wee see this is working pretty well. And now we do almost the some for a small web application.

Dart Web Application

As in the console application we define a CD-Object. After that we use the following code in the main-method:

void main() {
List<Cd> listOfCds = new List<Cd>();
ParagraphElement p = new ParagraphElement();
p.text = "loading..";
query("#container").append(p);
var request = new HttpRequest.get('http://api.signer.pro/client.php?action=getCds', (req) {
var text = req.responseText;
List l = JSON.parse(text);
l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});
UListElement ule = new UListElement();
listOfCds.forEach((cd) {
LIElement lie = new LIElement();
lie.text = "${cd.album} (${cd.interpret})";
ule.children.add(lie);
});
p.remove();
query("#container").append(ule);
});
}

We needed to modify the code a bit, so it matches the the  ‘dart:html’ library. But the rest of the code is very similar to the code in the first example above. The HTML looks like that:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ConnectAPI</title>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet"></link>
</head>
<body>
<h1>ConnectAPI</h1>
<div class="span12" id="container">
</div>
<script type="application/dart" src="ConnectAPI.dart"></script>
<script src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
</body>
</html>

As you see, I’m using bootstrap again for the website. So the result in the browser looks like that:

pp2

Let’s meet Dart

dart

It’s a long time ago, I first heard something about Dart. It’s the Google answer for JavaScript. You can download it over here: http://www.dartlang.org/downloads.html

When you create a new project you’ll get a .css, .dart and a .html file. We want to do a simple counter, so when you click on it, this value will increase.

We start with the HTML-File. This contains a basic website structure. I would use bootstrap for early development, but at the moment we don’t need it.

<!DOCTYPE html>
 <html>
 <head>
 <meta charset="utf-8">
 <title>HelloWorld</title>
 <link rel="stylesheet" href="HelloWorld.css">
 </head>
 <body>
 <h1>HelloWorld</h1>
 <p>Hello world from Dart!</p>
 <script type="application/dart" src="HelloWorld.dart"></script>
 <script src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
 </body>
 </html>

New we add a new add a new parameter tag with a uniq id below the “Hello world from Dart”-thing.

<p id="counter"></p>

The next step is the CSS-File so we can fully concentrate about dart-source-code  later. Remove everything except the body and p part and then add the following one for the counter:[/html]

#counter {
 font-size: 24pt;
 text-align: center;
 margin-top: 140px;
 }

Now we can go to the .dart-File. You can remove almost everything, but keep the

import 'dart:html';
void main() {
}

We start with the following code:

void main() {
 query("#counter")
 ..text = "0"
 ..on.click.add(countOneUp);
 }

This is simply setting the text of our HTML-element, with the id ‘counter’, and adding an OnClickEvent. This is very similar to Java, not the syntax, but the structure how you work with it. So now we need to create the OnClickEvent.

void countOneUp(Event event) {
 var tempCount = query("#counter").text;
 int i = int.parse(tempCount);
 i++;
 query("#counter").text = i.toString();
 }

If you know how Java-Syntax is working, this code isn’t hard to understand. But I think the query-command is quite confusing if you us it the first few times. As you see, I did a lot of filetype-parsing.

To run the application simply hit Ctrl + R (I don’t know how this is on Mac ^^). A modified version of chromium is now starting and will run the application. It should look like this now:

You can find the examples here: http://dart.signer.pro/.

As you see, Dart can be pretty nice. But I haven’t done much more at the moment. If I know more, I’ll let you know.