Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Count solution attempts #18

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions niancat-slack/niancatslack.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ def body(cls, user_name, solution, **kwargs):
return json.dumps({'user': user_name, 'solution': solution})


class UserStats:
pattern = '!statistik'
url_format = '/user/{user_name}/stats'
visibility = Visibility.Private
method = Method.GET
body = None


class NiancatSlack(SlackrestApp):
def __init__(self, base_url, notification_channel_id):
commands = [GetPuzzle, SetPuzzle, ListUnsolution, AddUnsolution, ConfirmUnsolution, CheckSolution]
Expand Down
2 changes: 1 addition & 1 deletion niancat/assembly.sbt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// import AssemblyKeys._

// assemblySettings
// assemblySettings
35 changes: 18 additions & 17 deletions niancat/build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,25 @@

val Http4sVersion = "0.15.11a"

lazy val root = (project in file(".")).
settings(
inThisBuild(List(
lazy val root = (project in file(".")).settings(
inThisBuild(
List(
organization := "io.github.dandeliondeathray",
scalaVersion := "2.12.10",
version := "1.0rc1"
)),
name := "niancat",
exportJars := true,
retrieveManaged := true,
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.1" % "test",
libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.1",
libraryDependencies += "org.scalamock" %% "scalamock-scalatest-support" % "3.5.0" % "test",
libraryDependencies ++= Seq(
"org.http4s" %% "http4s-blaze-server" % Http4sVersion,
"org.http4s" %% "http4s-circe" % Http4sVersion,
"org.http4s" %% "http4s-dsl" % Http4sVersion,
"ch.qos.logback" % "logback-classic" % "1.2.1",
"io.circe" %% "circe-generic" % "0.6.1"
version := "1.0rc1"
)
),
name := "niancat",
exportJars := true,
retrieveManaged := true,
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.1" % "test",
libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.1",
libraryDependencies += "org.scalamock" %% "scalamock-scalatest-support" % "3.5.0" % "test",
libraryDependencies ++= Seq(
"org.http4s" %% "http4s-blaze-server" % Http4sVersion,
"org.http4s" %% "http4s-circe" % Http4sVersion,
"org.http4s" %% "http4s-dsl" % Http4sVersion,
"ch.qos.logback" % "logback-classic" % "1.2.1",
"io.circe" %% "circe-generic" % "0.6.1"
)
)
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ package io.github.dandeliondeathray.niancat
trait Dictionary {
def has(word: Word): Boolean
def toSeq: Seq[Word]
def solutions(puzzle: Puzzle): Seq[Word]
def solutionId(puzzle: Option[Puzzle], word: Word): Option[Int]
}

Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import org.http4s.server.{Server, ServerApp}
import org.http4s.server.blaze.BlazeBuilder

object NiancatSlackApp extends ServerApp {
val port : Int = envOrNone("HTTP_PORT") map (_.toInt) getOrElse 8080
val ip : String = "0.0.0.0"
val pool : ExecutorService = Executors.newSingleThreadExecutor()
val port: Int = envOrNone("HTTP_PORT") map (_.toInt) getOrElse 8080
val ip: String = "0.0.0.0"
val pool: ExecutorService = Executors.newSingleThreadExecutor()

override def server(args: List[String]): Task[Server] = {
if (args.size == 2 && args(0) == "filter") {
Expand All @@ -20,8 +20,7 @@ object NiancatSlackApp extends ServerApp {
}

if (args.size != 0) {
println(
"""
println("""
Usage: niancat
or
niancat filter <dictionary>
Expand Down Expand Up @@ -56,9 +55,6 @@ object NiancatSlackApp extends ServerApp {
.start
}




def filter(dictionaryFile: String): Unit = {
val maybeDictionary: Try[NineLetterDictionary] = Try {
val lines = Source.fromFile(dictionaryFile).getLines().toSeq
Expand All @@ -76,4 +72,4 @@ object NiancatSlackApp extends ServerApp {

(filtered.toSeq map ((w: Word) => w.letters) sorted) foreach (println(_))
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ case class AddUnsolutionBody(unsolution: String)

object NiancatService {
def service(dictionary: Dictionary) = {
val puzzleSolution = new DictionaryPuzzleSolution(dictionary)
val engine = new PuzzleEngine(dictionary, puzzleSolution)
val state = new NiancatState()
val engine = new PuzzleEngine(state, dictionary)
val responder = new NiancatApiResponder()

HttpService {
Expand All @@ -28,12 +28,12 @@ object NiancatService {
}
case req @ POST -> Root / "v1" / "puzzle" => {
val yesterdayWasWeeekday = List(
DayOfWeek.TUESDAY,
DayOfWeek.WEDNESDAY,
DayOfWeek.THURSDAY,
DayOfWeek.FRIDAY,
DayOfWeek.SATURDAY
) contains LocalDate.now().getDayOfWeek()
DayOfWeek.TUESDAY,
DayOfWeek.WEDNESDAY,
DayOfWeek.THURSDAY,
DayOfWeek.FRIDAY,
DayOfWeek.SATURDAY
) contains LocalDate.now().getDayOfWeek()

req.as(jsonOf[SetPuzzleBody]) flatMap { setPuzzleBody =>
val command = SetPuzzle(Puzzle(setPuzzleBody.puzzle), yesterdayWasWeeekday)
Expand Down Expand Up @@ -72,6 +72,12 @@ object NiancatService {
Ok(Json.fromValues(messageResponses map (_.toJSON)))
}
}
case GET -> Root / "v1" / "user" / user / "stats" => {
val command = GetUserStats(User(user))
val response = command(engine)
val messageResponses = responder.messageResponses(response)
Ok(Json.fromValues(messageResponses map (_.toJSON)))
}
case GET -> Root / "health" => {
Ok()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package io.github.dandeliondeathray.niancat

import org.scalactic.NormMethods._
import PuzzleNormalizer._
import WordNormalizer._

case class SolutionResult(wordsAndSolvers: Map[Word, Seq[User]] = Map(), streaks: Map[User, Int] = Map())

trait State {
def puzzle(): Option[Puzzle]
def unsolutions(): Map[User, Seq[String]]
def unconfirmedUnsolutions(): Map[User, String]

def result(allSolutions: Seq[Word]): Option[SolutionResult]
def reset(p: Puzzle, isWeekday: Boolean): Unit
def solved(user: User, word: Word, isWeekday: Boolean): Unit
def hasSolved(user: User, word: Word): Boolean
def streak(user: User): Int
def userState(user: User): UserState

def countAttempt(user: User, validAttempt: Boolean)
def storeUnsolution(user: User, text: String)
def storeUnconfirmedUnsolution(user: User, text: String)
}

case class UserState(
validAttempts: Int = 0,
invalidAttempts: Int = 0,
) {
def totalAttempts: Int = invalidAttempts + validAttempts
}

class NiancatState extends State {
private var _puzzle: Option[Puzzle] = None
private var _unsolutions: Map[User, Seq[String]] = Map()
private var _unconfirmedUnsolutions: Map[User, String] = Map()
private var solutions: Seq[(Word, User)] = Seq()
private var streaks: Map[User, Int] = Map()
private var userStates: Map[User, UserState] = Map()

override def puzzle(): Option[Puzzle] = _puzzle

override def unsolutions() = _unsolutions

override def unconfirmedUnsolutions() = _unconfirmedUnsolutions

override def result(allSolutions: Seq[Word]): Option[SolutionResult] = {
puzzle match {
case None => None
case Some(p) => {
val allSolutionsMap: Map[Word, Seq[User]] = (allSolutions map (_ -> Seq[User]())).toMap
val foundSolutions: Map[Word, Seq[User]] = (solutions groupBy (_._1) mapValues (_.map(_._2).toSeq))
Some(SolutionResult(allSolutionsMap ++ foundSolutions, streaks.toMap))
}
}
}

override def reset(p: Puzzle, isWeekday: Boolean): Unit = {
_puzzle = Some(p.norm)
if (isWeekday) {
streaks = streaks filter { case (user, _) => solutions.map(_._2) contains user }
}
solutions = Seq()
_unsolutions = Map()
_unconfirmedUnsolutions = Map()
userStates = Map()
}
override def solved(user: User, word: Word, isWeekday: Boolean): Unit = {
val userHasFoundThisSolutionBefore = solutions contains ((word.norm, user))
if (!userHasFoundThisSolutionBefore) {
solutions :+= (word.norm, user)
if (isWeekday) {
streaks += user -> ((streaks getOrElse (user, 0)) + 1)
}
}
}

override def hasSolved(user: User, word: Word): Boolean = {
solutions contains ((word.norm, user))
}
override def streak(user: User): Int = streaks getOrElse (user, 0)
override def userState(user: User): UserState = userStates getOrElse (user, UserState())

override def countAttempt(user: User, validAttempt: Boolean): Unit = {
val currentState = userState(user)
val updatedState =
if (validAttempt)
currentState.copy(validAttempts = currentState.validAttempts + 1)
else
currentState.copy(invalidAttempts = currentState.invalidAttempts + 1)
userStates = userStates.updated(user, updatedState)
}

override def storeUnsolution(user: User, text: String): Unit = {
val unsolutionsForUser: Seq[String] = _unsolutions.getOrElse(user, Seq[String]())
_unsolutions += (user -> (unsolutionsForUser :+ text))
_unconfirmedUnsolutions -= user
}

override def storeUnconfirmedUnsolution(user: User, text: String): Unit = {
_unconfirmedUnsolutions += (user -> text)
}
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,41 @@
package io.github.dandeliondeathray.niancat

import WritingSystemHelper._
import org.scalactic._
import NormMethods._
import org.scalactic.NormMethods._
import WordNormalizer._
import PuzzleNormalizer._

/**
* Created by Erik Edin on 2017-05-09.
*/
class NineLetterDictionary(strings: Seq[String]) extends Dictionary {
val dictionary = strings map (Word(_).norm) filter (_.isNineLetters) toSet
val answers: Map[String, Seq[String]] = dictionary.toSeq map (_.norm.letters) groupBy sortByCodePoints

override def has(word: Word): Boolean = dictionary.contains(word.norm)
override def toSeq: Seq[Word] = dictionary.toSeq

override def solutions(puzzle: Puzzle): Seq[Word] =
answers getOrElse (sortByCodePoints(puzzle.norm.letters), Seq()) map Word

override def solutionId(puzzle: Option[Puzzle], word: Word): Option[Int] = {
puzzle
.map(solutions)
.map(_ indexOf (word.norm))
.filter(_ != -1)
.map(_ + 1)
}

private def sortByCodePoints(s: String): String = {
val codePoints = s.codePoints() sorted () toArray
val sb = new java.lang.StringBuilder()
codePoints foreach (sb.appendCodePoint(_))
sb.toString()
}
}

object NineLetterDictionary {
def apply(strings: String*): NineLetterDictionary = {
new NineLetterDictionary(strings)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package io.github.dandeliondeathray.niancat
import java.text.Normalizer
import org.scalactic._
import NormMethods._

object StringNormalizer {
implicit val stringNormalizer = new Normalization[String] {
def normalized(s: String): String = {
val decomposed = Normalizer.normalize(s, Normalizer.Form.NFKD).replaceAll("[- _\u0301\u0341]", "").toUpperCase
Normalizer.normalize(decomposed, Normalizer.Form.NFKC)
}
}
}
import StringNormalizer._

object PuzzleNormalizer {
implicit val puzzleNormalizer = new Normalization[Puzzle] {
def normalized(puzzle: Puzzle): Puzzle = Puzzle(puzzle.letters.norm)
}
}

object WordNormalizer {
implicit val wordNormalizer = new Normalization[Word] {
def normalized(word: Word): Word = {
Word(stringNormalizer.normalized(word.letters))
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ case class Get() extends PuzzleCommand {
def apply(engine: PuzzleEngine): Response = engine.get()
}

case class GetUserStats(user: User) extends PuzzleCommand {
def apply(engine: PuzzleEngine): Response = engine.getUserStats(user)
}

case class CheckSolution(word: Word, user: User, isWeekday: Boolean) extends PuzzleCommand {
def apply(engine: PuzzleEngine): Response = {
engine.check(user, word, isWeekday)
Expand Down Expand Up @@ -75,6 +79,10 @@ class SlackParser extends Parser {
return if (visibility == PrivateChannel()) ListUnsolutions(user) else Ignored()
}

if (words(0) == "!statistik") {
return if (visibility == PrivateChannel()) GetUserStats(user) else Ignored()
}

if (visibility == PublicChannel()) {
return Ignored()
} else {
Expand Down
Loading