Skip to content

Instantly share code, notes, and snippets.

abstract class Exp {
def evaluate(x: Double): Double
def derivative(): Exp
def toStringCanonical(): String
}
object Exp {
def main(args: Array[String]): Unit = {
println(parse("2*x^2").derivative().toStringCanonical())
}
@shashir
shashir / DecisionTree.scala
Last active March 7, 2016 01:27
Decision tree learning using ID3 algorithm
// https://github.com/shashir/cs7641/blob/master/lessons/ml_p1_lesson_01_decision_trees.md#id3-algorithm
import scala.collection.mutable.{Set => MSet}
case class Tree[T](
value: T,
children: MSet[Tree[T]] = MSet.empty[Tree[T]]
) {
override def toString(): String = {
value +
@shashir
shashir / ArgMinMax.scala
Created March 4, 2016 23:43
argmin and argmax
object ArgMinMax {
import scala.reflect.ClassTag
def argmin[X: ClassTag, Y <% Ordered[Y] : ClassTag](n: Iterable[X], f: X => Y): X = {
val (argmin: X, min: Y) = n.tail.fold((n.head, f(n.head))) { case ((a: X, m: Y), x: X) =>
val fOfx: Y = f(x)
if (fOfx < m) (x, fOfx) else (a, m)
}
return argmin
}
@shashir
shashir / Histogram.scala
Created February 22, 2016 20:50
Generates a color histogram of an image to compute image distance Raw
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
case class Histogram(
resolution: Int,
pixels: Int,
histogram: Array[Array[Array[Int]]]
) {
def distance(that: Histogram): Double = {
@shashir
shashir / Matrix.scala
Last active March 14, 2016 23:45
Matrix -- simple no library
import scala.reflect.ClassTag
case class Matrix[T : ClassTag](
rows: Int,
cols: Int,
matrix: Array[Array[T]]
)(implicit num: Numeric[T]) {
import num._
require(matrix.length == rows, "Row number incorrect.")
@shashir
shashir / QLearner.py
Last active February 21, 2018 16:49
QLearner
import numpy as np
import random as rand
import datetime
class QLearner(object):
def __init__(self, \
num_states=100, \
num_actions = 4, \
alpha = 0.2, \
gamma = 0.9, \
@shashir
shashir / log line regex
Last active December 10, 2015 00:17
Regex to split log line
("[^"]*")|[^" ]+
@shashir
shashir / MySQLDownloader.scala
Created November 19, 2015 19:24
Scala JDBC querying (useful for building basic ORM)
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
import java.sql.Statement
import scala.annotation.tailrec
import com.typesafe.scalalogging.slf4j.Logger
import org.slf4j.LoggerFactory
@shashir
shashir / run.sh
Created November 10, 2015 02:38
Run remote commands (simple)
#!/bin/bash
SERVERS=(
# list of servers
)
# USER=
# SSH_KEY=
echo "Command to run is: $1"
for server in ${SERVERS[@]}; do
@shashir
shashir / TicTacToe.java
Created October 7, 2015 09:53
Simple TicTacToe demo using if blocks for El Camino High School
import java.util.Scanner;
public class TicTacToe {
public static char X = 'X';
public static char O = 'O';
public static char B = ' ';
public static void main(String[] args) {
/*
* Squares are associated with following variables.