Skip to content

Instantly share code, notes, and snippets.

@jdelafon
Last active July 3, 2017 12:44
Show Gist options
  • Save jdelafon/30a676def3756b728114a1e37552ffa2 to your computer and use it in GitHub Desktop.
Save jdelafon/30a676def3756b728114a1e37552ffa2 to your computer and use it in GitHub Desktop.
Scala receipes
/**
* Return a Map[String,Any] of the field -> value pairs of the attributes of a class `c`.
*/
def classToMap(c: AnyRef): Map[String, Any] =
// 'fold' syntax, starting with an empty map
(Map[String, Any]() /: c.getClass.getDeclaredFields) {(a, f) =>
f.setAccessible(true)
a + (f.getName -> f.get(c))
}
/**
* Return the value associated to class field `fieldName` given as a String.
*/
def getValue(c: AnyRef, fieldName: String) = {
val vals = c.getClass.getDeclaredFields
.filter { f: Field =>
f.getName == fieldName
} map { f: Field =>
f.setAccessible(true)
f.get(c)
}
vals.head
}
/*
* Delete all files older than 1 hours in THAT_DIR with a given extension
* Useful ref: http://alvinalexander.com/scala/how-to-list-files-in-directory-filter-names-scala
*/
// Get current time in milliseconds from 1970
import java.io.File
import java.util.Calendar
val now:Date = Calendar.getInstance().getTime
val millis = now.getTime // yeah, getTime again...
val delta = 1 * 3600 * 1000 // 1h
new File(THAT_DIR).listFiles
.filter(_.isFile)
.filter(_.getName.matches(".*?\\.bam.*"))
.filter(_.lastModified < now - delta).foreach(_.delete)
/*
* Create a random string
*/
import scala.util.Random
(Random.alphanumeric take 20).mkString
/*
* Read a JDBC database
*/
db.withConnection { conn =>
val cursor = conn.createStatement
val res = cursor.executeQuery("SELECT ....")
while (res.next()) { ... }
}
/*
* Read (chr,start,end) from a BAM file with htsjdk
*/
import htsjdk.samtools.{SamReader, SamReaderFactory}
val reader: SamReader = SamReaderFactory.makeDefault().open(new File(filename))
val it = reader.iterator
while (it.hasNext) {
val read = it.next
println(read.getReferenceName, read.getAlignmentStart, read.getAlignmentEnd)
}
/*
* Execute command-line
* Useful ref: http://alvinalexander.com/scala/scala-execute-exec-external-system-commands-in-scala
*/
// Redirect stdout to file. Return the command's return code (0 = success)
val cmd = s"samtools view -hb $bam" #>> new File(dest)
val success = cmd.! == 0
// Pipe. Return the stdout
val cmd = s"samtools view -hb $bam" #| "base64"
val encoded:String = cmd.!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment