Archiv nach Kategorien: Tutorials

SBT Native Packager – Multi Module / Assembly and Custom Formats

Lately the questions on Stackoverflow and the Issues around sbt-native-packager were often about topics concerning

  • Multi Module Builds
    Aggregating multiple projects into a single native package
  • SBT-Assembly jar
    Aggregate everything into a  fat-jar and package this instead of each single jarfile
  • Change Mappings
    Changing default mappings, remove ones you don’t need or add new ones
  • Custom Formats
    Creating your own packaging type. The SBT part will only take you minutes.

Within the next 0.7.x and 0.8.x release we will update the docs as well, but until then you can checkout the sbt-native-packager-examples on github.

From Java 7 Futures to Akka actors with Scala

This blog post will show you how a step by step transition from a “java 7 and j.u.c.Future” based implementation to an “akka actor written in scala solution” looks like. It will take four steps, which are

  1. Java 7 and futures
  2. Java 8 and parallel streams
  3. Scala and futures
  4. Scala and actors with the ask pattern
  5. Scala and actors (almost) without the ask pattern

The complete code repository can be found on github.

Weiterlesen »

How to add a maven-plugin jar as dependency to sbt

I want to use the jdeb library to integrate in one of my own libraries.
Since it is a maven-plugin it’s packaged as a maven plugin. SBT
does not resolve the jars if you just add it as a dependency. This
will do the trick:

"org.vafer" % "jdeb" % "1.2" artifacts (Artifact("jdeb", "jar", "jar"))

This one is for sbt 0.13.5!

Playframework and RequireJS

RequireJS Logo

As a backend developer I like tools that help me to structure my code. Doing more and more frontend stuff I finally got time to learn some of the basics of RequireJS. Unfortunately the tutorials how to compose playframework and requireJS with multipage applications is not too big. There’s is some with AngularJS, but I didn’t want to port my applications to two new systems.

Application structure

For a sample application, I implemented to pages:

Both will have their own data-entry-point and dependencies. The index page looks like this

@(message: String)
 
@main("RequireJS with Play") {
    // html here
 
 @helper.requireJs(core = routes.Assets.at("javascripts/require.js").url,
                   module = routes.Assets.at("javascripts/main/main").url)
 
}

The routes file is very basic, too:

GET    /                controllers.Application.index
GET    /dashboard       controllers.Application.dashboard
POST   /api/sample      controllers.Application.sample
 
### Additions needed
GET    /jsroutes.js     controllers.Application.jsRoutes()
### Enable www.WebJars.org based resources to be returned
GET    /webjars/*file   controllers.WebJarAssets.at(file)
GET    /assets/*file    controllers.Assets.at(path="/public", file)

The javascript folder layout

  • assets/javascripts
    • common.js
    • main.js
    • dashboard
      • chart.js
      • main.js
    • lib
      • math.js

How does it work?

First you define a file common.js, which is used to configure requirejs.

(function(requirejs) {
    "use strict";
 
    requirejs.config({
        baseUrl : "/assets/javascripts",
        shim : {
            "jquery" : {
                exports : "$"
            },
            "jsRoutes" : {
                exports : "jsRoutes"
            }
        },
        paths : {
            "math" : "lib/math",
            // Map the dependencies to CDNs or WebJars directly
            "_" : "//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.1/underscore-min",
            "jquery" : "//localhost:9000/webjars/jquery/2.0.3/jquery.min",
            "bootstrap" : "//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min",
            "jsRoutes" : "//localhost:9000/jsroutes"
        // A WebJars URL would look like
        // //server:port/webjars/angularjs/1.0.7/angular.min
        }
    });
 
    requirejs.onError = function(err) {
        console.log(err);
    };
})(requirejs);

The baseUrl is important, as this will be the root path from now on. IMHO this makes things easier than, relative paths.

The shim configuration is used to export your jsRoutes, which is defined in my Application.scala file. Of course you can add as many as you want.

The paths section is a bit tricky. Currently it seems there’s no better way than hardcoding the urls, like “jsRoutes” : “//localhost:9000/jsroutes”, when you use WebJars.

Define and Require

Ordering is crucial! For my /dasbhoard page the /dasbhoard/main.js is my entry point

// first load the configuration
require(["../common"], function(common) {
   console.log('Dashboard started');
 
   // Then load submodules. Remember the baseUrl is set:
   // Even you are in the dasboard folder you have to reference dashboard/chart
   // directly
   require(["jquery", "math", "dashboard/chart"], function($, math, chart){
       console.log("Title is : " + $('h1').text());
       console.log("1 + 3 = " + math.sum(1,3));
       console.log(chart);
 
       chart.load({ page : 'dashboard'}, function(data){
           console.log(data);
       }, function(status, xhr, error) {
           console.log(status);
       });
 
   });
});

For the chart.js

// first the configuration, then other dependencies
define([ "../common", "jsRoutes" ], {
    load : function(data, onSuccess, onFail) {
        var r = jsRoutes.controllers.Application.sample();
        r.contentType = 'application/json';
        r.data = JSON.stringify(data);
        $.ajax(r).done(onSuccess).fail(onFail);
    }
})

Links

Gradient Decent with Scala

Currently I’m watching a Scala and a Maschine Learning course on coursera.org and
wanted to try some simple stuff for myself. I choose Gradient Decent would be a
perfect start to try some functional programming.

The code

import scala.math._
 
object GradientDecent extends App {
 
  val alpha = 0.1 //size of steps taken in gradient decent
  val samples = List((Vector(0.0, 0.0), 2.0), (Vector(3.0, 1.0), 12.0), (Vector(2.0, 2.0), 18.0))
 
  var tetas = Vector(0.0, 0.0, 0.0)
  for (i 
        teta - (alpha / samples.size) * samples.foldLeft(0.0) {
          case (sum, (x, y)) => decentTerm(sum, 1, x, y, tetas)
        }
      case (teta, i) =>
        teta - (alpha / samples.size) * samples.foldLeft(0.0) {
          case (sum, (x, y)) => decentTerm(sum, x(i - 1), x, y, tetas)
        }
    }
  }
 
  def decentTerm(sum: Double, x_j: Double, x: Vector[Double], y: Double, tetas: Vector[Double]) = {
    sum + x_j * (h(x, tetas) - y)
  }
 
  def h(x: Vector[Double], teta: Vector[Double]): Double = {
    teta(0) + {
      for (i  sum + x)
  }
 
}

And thats pretty much everything. This is just a first version and I’m sure somebody would find ways
to optimize it. However even this hacked version is very short and handsome :)

Update
The code snippet here is a gradient decent for performing linear regression.