Programmatically adding PHP generated TypoScript to the backend configuration

Today I’ve struggled with adding PHP generated TypoScript configuration to the backend. There doesn’t seem to be an API for this, unfortunately, so I had to dig a little bit into the TYPO3 source.

Turns out that t3lib_befunc#getPagesTSconfig, which is responsible for retrieving TypoScript configuration for the backend, makes use of the following global variable as the “default TypoScript configuration”:

$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig']

So, being short of a proper API, I ended up simply appending my generated configuration to the defaultPageTSconfig string (in my ext_localconf.php file).

Is there a better way to achieve the same thing? If so, let me know :)

InstantiationException when creating Akka Actor

This post might help you if you get an exception such as the following when creating an Akka Actor with actorOf(Props[SomeActor]):

[ERROR] 15:32:44.249 :: akka://…/user/foo :: akka.actor.ActorCell :: error while creating actor
    java.lang.InstantiationException: package.of.SomeActor
    at java.lang.Class.newInstance0(Class.java:340)

The reason I got this error was simply because I didn’t have a constructor with zero arguments, that is, my Actor’s class signature looked like this:

class SomeActor(val attrs:Map[String, String] = Map()) extends Actor

I assumed that, since map has a default value, it would work just like a no-argument constructor, but that was foolish, of course. Akka invokes java.lang.Class.newInstance, which in turn calls java.lang.Class.newInstance0, which (as far as I know) is a special case of newInstance for constructors with no arguments. Given that this special case is not applicable for our Actor class, an exception is thrown.

I worked around this problem like this:

class SomeActor(val attrs:Map[String, String] = Map()) extends Actor {
    def this() = this(Map())
}

Why is my Akka Actor getting “deadLetters” as sender?

That is a question that kept my busy for almost an hour… I had an Actor defined like this (simplified, of course):

trait Foo { self: Actor =>
    []
}

class Bar extends Actor with Foo {
    []
    def receive = {
        case x => sender ! x
    }
}

Weirdly enough, when I was sending messages to that actor, the responses always came from the deadLetters Actor belonging to my actor system. The reason for this behavior was the fact that I used self as the name for the Foo trait’s self-type, because “There is already an implicit val self defined in Actor which refers to an actor’s own ActorRef”, and if you override that, well, it breaks.

Therefore, if I change my trait to read something like this

trait Foo { actor: Actor =>
    []
}

everything works as expected.

Whenever Gem and Capistrano – Specifying the cronjob user

If you are using Capistrano in a project that relies on the Whenever gem to manage your crontab, it will update the crontab of the user that you use for your Capistrano deploys. So if, for example, you’d deploy with the user capistrano and your app runs under the user www-data, you could run into all sorts of trouble, e.g. permissions in case your cronjob creates new files.

Specifying the user under whom the cronjob command should be executed is relatively easy though. This mailing list entry tells us that we should add --user your_user as a parameter to the whenever command. The problem with that is that you don’t execute the command yourself, but the whenever gem’s Capistrano recipe does. So all we need to do is change the whenever_update_flags variable to meet our wishes. First the original line, and after that our modification:

# Old
_cset(:whenever_update_flags) { "–update-crontab #{fetch :whenever_identifier} –set #{fetch :whenever_variables}" }

# New
_cset(:whenever_update_flags) { "–update-crontab #{fetch :whenever_identifier} –set #{fetch :whenever_variables} –user www-data" }

You probably don’t want to change the whenever gem directly, so placing that line anywhere in the deploy.rb file should work just fine.

Multiple unapply methods for pattern matching in Scala

TLDR: Take my directly to the solution.

I found this nice trick on the Scala forums. Lets imagine we have a case class such as the following:

case class Foo(a:String, b:String, c:String = null, d:String = null)

This case class, as you probably know, can now be “pattern matched” like this:

Foo("foo", "bar", "baz", "wobble") match {
    case Foo("foo", b, _, _) => b
    case _ => "What?"
}

But what if, most of the time, you only need the first two arguments, and the others are mostly irrelevant for your pattern matching. You wouldn’t want to write Foo(a, _, _ ,_) all the time, right? One possibility would be to write the unapply(x:Foo) method yourself:

class Foo(val a:String, val b:String, val c:String = null, val d:String = null)

object Foo {
    def unapply(x:Foo): Option[(String, String)] = Some(x.a, x.b)
}

new Foo("foo", "bar", "baz", "wobble") match {
    case Foo("foo", b) => b
    case _ => "What?"
}

But what if you would like to use both unapply methods at some point? In that case you have to define multiple objects with different unapply methods, because unfortunately, unlike apply, unapply can’t be overloaded (because it always takes the the same argument).

So here is my approach to multiple unapply methods:

case class Foo(val a:String, val b:String, val c:String = null, val d:String = null)

object Foo_ {
    def unapply(x:Foo): Option[(String, String)] = Some(x.a, x.b)
}

new Foo("foo", "bar", "baz", "wobble") match {
    case Foo_("foo", b) => b
    case Foo(a, _, _, d) => (a, d)
    case _ => "What?"
}

While it isn’t exactly awesome because you have to introduce a new object Foo_, I like it better than always having to write out all 4 (or more) parameters.

If you have a better approach to this problem, please let me know :)

Teamspeak 3 installation script for Debian/Ubuntu

I installed a Teamspeak server today, and because I had a little time and wanted to brush up my bash scripting skills anyway, I coded a Teamspeak 3 server installation script that should work on most Debian systems (such as Ubuntu). Because of possible legal issues I didn’t include the download of the installation files itself in the script, so you’ll have to download those yourself (use either “Server amd64″ or “Server x86″ depending on your system).

After downloading the installation archive (don’t extract), you can execute the following to install your very own Teamspeak 3 server:

wget https://raw.github.com/gist/3730343/39db4465b5f7f97213f015bedb888e74c7db8526/install_teamspeak.sh && \
    chmod +x install_teamspeak.sh && \
    ./install_teamspeak.sh <insert path to installation archive here>

If you’d like to take a look at the script, don’t let me keep you. If you run into any problems, please leave me a comment :)

Paste Mode in the Scala REPL

This is going to be quick but nonetheless awesome. Activate “Paste Mode” by typing :paste in the Scala REPL:

scala> :paste
// Entering paste mode (ctrl-D to finish)

class PasteMe {
    def didThat = "hooray"
}

^D
// Exiting paste mode, now interpreting.

Have fun with Paste Mode :)

Scala Trait self-types or “How do I tell my trait where it’s going to be mixed in?”

A feature of Scala whose syntax I tend to forget are self-types, with which you can tell a trait where it is going to be mixed in, just like this:

class Foo {
    def x = 5
}

trait Bar { self: Foo =>
    def y = x + 10
}

The self: Foo => part tells the trait that it is going to be mixed into a class of type Foo and that it can therefore use all methods from this type. This is why the Bar trait is then able to call the x method from the Foo class:

scala> (new Foo with Bar).y
res4: Int = 15

Whereas the following will fail miserably:

scala> (new Object with Bar).y
<console>:10: error: illegal inheritance;
  self-type java.lang.Object with Bar does not conform to Bar’s selftype Bar with Foo
          (new Object with Bar).y

Akka Logging within a TypedActor

The basic example for an Actor (not TypedActor) that uses logging from the Akka documentation is the following:

class MyActor extends Actor {
  val log = Logging(context.system, this)
  def receive = {
    case "test" => log.info("received test")
    case _      => log.info("received unknown message")
  }
}

So one might think that it is possible to do the same within a TypedActor:

class TypedActorImpl extends TypedActorTrait {
    val log = Logging(TypedActor.context.system, this)

    def squareDontCare(i:Int, i:Int):Unit {
        log.info("Weeeee!")
        i * i // Nobody cares :(
    }
}

This breaks because “you need to provide an implicit akka.event.LogSource for the type of “this” when you call Logging” (Viktor Klang), and understandably there is no implicit defined for our TypedActorImpl. But don’t despair! There is an implicit that converts an ActorRef to a LogSource, and we can access a TypedActor‘s ActorRef by using TypedActor.context.self.

So here’s the complete working example for a TypedActor:

class TypedActorImpl extends TypedActorTrait {
    val log = Logging(TypedActor.context.system, TypedActor.context.self)

    def squareDontCare(i:Int, i:Int):Unit {
        log.info("Weeeee!")
        i * i // Nobody cares :(
    }
}

Troubleshooting

You probably used something else than TypedActor.context.self for the second parameter of Logging():

error: could not find implicit value for evidence parameter of type akka.event.LogSource[...]

You probably used TypedActor.self instead of TypedActor.context.self for the second parameter of Logging():

error: ambiguous implicit values:
both value fromString in object LogSource of type => akka.event.LogSource[String]
and value fromActor in object LogSource of type => akka.event.LogSource[akka.actor.Actor]
match expected type akka.event.LogSource[Nothing]

LaTeX code listings with Minted

While typesetting an article I had some code highlighting issues with the standard LaTeX listing package, so I departed on an epic journey in search of a better alternative. Seriously though, I found Minted, which is pretty awesome because it uses the Python library Pygments for highlighting, and is therefore a lot more powerful than the standard LaTeX stuff:

After some twisting and tweaking, and with the help of the Minted documentation and some awesome people on Stackoverflow, I came up with the following code listing style, which I deem acceptable:

Here’s a little excerpt from my LateX:

% This is how minted is configured
\usepackage{minted}
\usepackage{caption}
\floatsetup[listing]{style=Plaintop}

\DeclareCaptionFont{white}{\scriptsize\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\linewidth-2\fboxsep}{#1#2#3}}}
\captionsetup[listing]{format=listing,labelfont=white,textfont=white}

\newmintedfile{javascript}{numbersep=5pt, linenos, fontsize=\footnotesize, frame=bottomline, framesep=3mm
}

% This is how a listing is created, in this case for JavaScript
\begin{listing}
    \javascriptfile{../code/design/agent-directory-entry.json}
    \caption{Example of an agent directory entry in JSON representation}
    \label{code:design:agent-directory-entry}
\end{listing
}