Skip to content

Instantly share code, notes, and snippets.

@sam
sam / NamedTestKits.scala
Created September 24, 2015 18:29
Hard to get current class-name for your TestKit ActorSystem. This hack gets around constructor issues.
// The TestKit class is just:
class TestKit(_system: ActorSystem) extends { implicit val system = _system } with TestKitBase
// TestKitBase uses `system` in it's constructor so _it must be defined before extending TestKitBase_!
// You can't use `this` within alternate constructors however, so the solution isn't as easy as:
class MySpec extends TestKit(ActorSystem(this.getClass.getSimpleName))
// So let's ignore `TestKit` and focus on `TestKitBase`. That way we can have our own constructors that execute before
// TestKitBase's constructor.
@sam
sam / FutureExample.scala
Created September 23, 2015 20:51
Demonstrating Future.sequence always returns the mapped Sequence in the same order it was passed.
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
val a = Future { 1 } // completes immediately.
val b = Future { Thread.sleep(1000); 2 } // is the last to complete.
val c = Future { Thread.sleep(100); 3 } // completes after 1 but before 2.
Future.sequence(Seq(a, b, c)) map println
// > List(1, 2, 3)
@sam
sam / Campbell.scala
Last active August 29, 2015 14:23
Chris Campbell's method of resizing an image while retaining quality (employed in ImgScalr).
def resize(current: Long, target: Long, iteration: Long = 1): Unit = {
val step = Math.max(current - (current / 7), target)
printf("[%04d] RESIZE FROM %d TO %d\n", iteration, current, step)
if(step > target)
resize(step, target, iteration + 1)
}
@sam
sam / FormWithEvery.scala
Created January 29, 2015 15:33
[PlayFramework-2.0] Trouble figuring out custom mappings, pre-filled default data, and ScalaUtils "at-least-one" Every[T] collection type.
// This code won't compile without some Play dependencies being satisfied.
// Like Controller, formats.parsing, etc. It's just for reference.
object ArticlesController extends Controller {
import java.util.Locale
// Our application has several translations for an Article:
val locales: List[Locale] = Seq(Locale.US, Locale.JAPAN)
def create = Action {
@sam
sam / Main.scala
Created January 23, 2015 19:04
Benchmarking various means of collapsing a readable triple-quoted string into a single line appropriate as a portion of a URI.
object Main extends testing.Benchmark {
val r = """[\r\n\s]""".r
val s = """
| Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
| tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
| veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
| commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
| velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
@sam
sam / RequestMethods.scala
Created October 27, 2014 18:32
Have a reverse route match multiple Request Methods in Play Framework
object MyController extends Controller with StrictLogging {
def index =
AdminAction.async { implicit request =>
request.method match {
case "GET" =>
Future.successful(Ok("GET"))
case "POST" =>
@sam
sam / Escape.scala
Created August 5, 2014 22:34
Escape all in String
object Lucene {
object Escape extends (String => String) {
private val prefix: Char => PartialFunction[Char, String] = c => { case `c` => s"\\$c" }
private val escapist: PartialFunction[Char, String] = prefix('\\') orElse
prefix('+') orElse
prefix('-') orElse
prefix('!') orElse
@sam
sam / Sender.scala
Created July 29, 2014 14:18
Akka Props are a closure?
// It seems like Props is a closure that gets reused? The first pass will work.
// The next will cause the BatchUpdate Actor to send deadLetters. As if the sender
// terminated prematurely.
query {
Rows(multiStoryQuery(revs.map(_._1)).list)
} pipeTo context.actorOf(Props(new BatchUpdate(context.sender(), revs)), s"batch-update-story-${Math.abs(Random.nextInt())}")
// This works however. So the problem actually seems to be that successive iterations of the above
// version go to the same (now stopped) passed sender.
@sam
sam / Overrides.scala
Created July 2, 2014 19:03
To Override or Not To Override (that is the question)
// To Override or Not To Override (that is the question):
trait Foo {
def close: Unit
def bar(baz: String): Int
def zed(y: Int): Int = y * 2
}
case class Foo(a: String, b: Int)
object Foo {
def apply(a: String, b: String) = new Foo(a, b.toInt)
}
val format = jsonFormat2[Foo](new {
def apply(a: String, b: Int): Foo = Foo(a, b)
def unapply(f: Foo) = Foo.unapply(f)