Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • lamp/cs206
  • bwermeil/cs206-2020
  • zabifade/cs206-2020
  • cauderan/cs206-2020
  • malonga/cs206-2020
  • dumoncel/cs206
  • bounekhe/cs206
  • bergerault/cs206
  • flealsan/cs206
  • hsu/cs206
  • mouchel/cs206
  • vebraun/cs206
  • vcanard/cs206
  • ybelghmi/cs206
  • belghmi/cs206
  • bousbina/cs206
  • waked/cs206
  • gtagemou/cs206
  • arahmoun/cs206
  • elhachem/cs206
  • benrahha/cs206
  • benslima/cs206
22 results
Show changes
Showing
with 0 additions and 1011 deletions
// Used for Coursera submission (StudentPlugin)
// libraryDependencies += "org.scalaj" %% "scalaj-http" % "2.4.2"
// libraryDependencies += "com.typesafe.play" %% "play-json" % "2.7.4"
// Used for Base64 (StudentPlugin)
libraryDependencies += "commons-codec" % "commons-codec" % "1.10"
// addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.28")
addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.5.3")
package m2
////////////////////////////////////////
// NO NEED TO MODIFY THIS SOURCE FILE //
////////////////////////////////////////
trait Lib {
/** If an array has `n` elements and `n < THRESHOLD`, then it should be processed sequentially */
final val THRESHOLD: Int = 33
/** Compute the two values in parallel
*
* Note: Most tests just compute those two sequentially to make any bug simpler to debug
*/
def parallel[T1, T2](op1: => T1, op2: => T2): (T1, T2)
/** A limited array. It only contains the required operations for this exercise. */
trait Arr[T] {
/** Get the i-th element of the array (0-based) */
def apply(i: Int): T
/** Update the i-th element of the array with the given value (0-based) */
def update(i: Int, x: T): Unit
/** Number of elements in this array */
def length: Int
/** Create a copy of this array without the first element */
def tail: Arr[T]
/** Create a copy of this array by mapping all the elements with the given function */
def map[U](f: T => U): Arr[U]
}
object Arr {
/** Create an array with the given elements */
def apply[T](xs: T*): Arr[T] = {
val arr: Arr[T] = Arr.ofLength(xs.length)
for i <- 0 until xs.length do arr(i) = xs(i)
arr
}
/** Create an array with the given length. All elements are initialized to `null`. */
def ofLength[T](n: Int): Arr[T] =
newArrOfLength(n)
}
/** Create an array with the given length. All elements are initialized to `null`. */
def newArrOfLength[T](n: Int): Arr[T]
/** A number representing `radicand^(1.0/degree)` */
case class Root(radicand: Int, degree: Int) {
def toDouble: Double = scala.math.pow(radicand, 1.0/degree)
}
/** Tree result of an upsweep operation. Specialized for `Root` results. */
trait TreeRes { val res: Root }
/** Leaf result of an upsweep operation. Specialized for `Root` results. */
case class Leaf(from: Int, to: Int, res: Root) extends TreeRes
/** Tree node result of an upsweep operation. Specialized for `Root` results. */
case class Node(left: TreeRes, res: Root, right: TreeRes) extends TreeRes
}
package m2
trait M2 extends Lib {
// Functions and classes of Lib can be used in here
/** Compute the rolling geometric mean of an array.
*
* For an array `arr = Arr(x1, x2, x3, ..., xn)` the result is
* `Arr(math.pow(x1, 1), math.pow((x1 + x2), 1.0/2), math.pow((x1 + x2 + x3), 1.0/3), ..., math.pow((x1 + x2 + x3 + ... + xn), 1.0/n))`
*/
def rollingGeoMeanParallel(arr: Arr[Int]): Arr[Double] = {
if (arr.length == 0) return Arr.ofLength(0)
val out: Arr[Double] = Arr.ofLength(arr.length)
val tree = upsweep(arr, 0, arr.length)
downsweep(arr, Root(1, 0), tree, out)
out
}
// No need to modify this
def scanOp(acc: Root, x: Root) =
Root(acc.radicand * x.radicand, acc.degree + x.degree)
def upsweep(input: Arr[Int], from: Int, to: Int): TreeRes = {
if (to - from < THRESHOLD)
Leaf(from, to, reduceSequential(input, from + 1, to, Root(input(from), 1)))
else {
val mid = from + (to - from)/2
val (tL, tR) = parallel(
upsweep(input, from, mid),
upsweep(input, mid, to)
)
Node(tL, scanOp(tL.res, tR.res), tR)
}
}
def downsweep(input: Arr[Int], a0: Root, tree: TreeRes, output: Arr[Double]): Unit = {
tree match {
case Node(left, _, right) =>
parallel(
downsweep(input, a0, left, output),
downsweep(input, scanOp(a0, left.res), right, output)
)
case Leaf(from, to, _) =>
downsweepSequential(input, from, to, a0, output)
}
}
def downsweepSequential(input: Arr[Int], from: Int, to: Int, a0: Root, output: Arr[Double]): Unit = {
if (from < to) {
var i = from
var a = a0
while (i < to) {
a = scanOp(a, Root(input(i), 1))
output(i) = a.toDouble
i = i + 1
}
}
}
def reduceSequential(input: Arr[Int], from: Int, to: Int, a0: Root): Root = {
var a = a0
var i = from
while (i < to) {
a = scanOp(a, Root(input(i), 1))
i = i + 1
}
a
}
}
package m2
class M2Suite extends munit.FunSuite {
test("Rolling geometric mean result test (5pts)") {
RollingGeoMeanBasicLogicTest.basicTests()
RollingGeoMeanBasicLogicTest.normalTests()
RollingGeoMeanBasicLogicTest.largeTests()
}
test("[TASK 1] Rolling geometric mean parallelism test (30pts)") {
RollingGeoMeanCallsToParallel.parallelismTest()
RollingGeoMeanParallel.basicTests()
RollingGeoMeanParallel.normalTests()
RollingGeoMeanParallel.largeTests()
}
test("[TASK 2] Rolling geometric mean no `map` test (35pts)") {
RollingGeoMeanNoMap.basicTests()
RollingGeoMeanNoMap.normalTests()
RollingGeoMeanNoMap.largeTests()
}
test("[TASK 3] Rolling geometric mean no `tail` test (30pts)") {
RollingGeoMeanNoTail.basicTests()
RollingGeoMeanNoTail.normalTests()
RollingGeoMeanNoTail.largeTests()
}
object RollingGeoMeanBasicLogicTest extends M2 with LibImpl with RollingGeoMeanTest {
def parallel[T1, T2](op1: => T1, op2: => T2): (T1, T2) = (op1, op2)
def newArrFrom[T](arr: Array[AnyRef]): Arr[T] = new ArrImpl(arr)
}
object RollingGeoMeanCallsToParallel extends M2 with LibImpl with RollingGeoMeanTest {
private var count = 0
def parallel[T1, T2](op1: => T1, op2: => T2): (T1, T2) =
count += 1
(op1, op2)
def newArrFrom[T](arr: Array[AnyRef]): Arr[T] = new ArrImpl(arr)
def parallelismTest() = {
assertParallelCount(Arr(), 0)
assertParallelCount(Arr(1), 0)
assertParallelCount(Arr(1, 2, 3, 4), 0)
assertParallelCount(Arr(Array.tabulate(16)(identity): _*), 0)
assertParallelCount(Arr(Array.tabulate(32)(identity): _*), 0)
assertParallelCount(Arr(Array.tabulate(33)(identity): _*), 2)
assertParallelCount(Arr(Array.tabulate(64)(identity): _*), 2)
assertParallelCount(Arr(Array.tabulate(128)(identity): _*), 6)
assertParallelCount(Arr(Array.tabulate(256)(identity): _*), 14)
assertParallelCount(Arr(Array.tabulate(1000)(identity): _*), 62)
assertParallelCount(Arr(Array.tabulate(1024)(identity): _*), 62)
}
def assertParallelCount(arr: Arr[Int], expected: Int): Unit = {
try {
count = 0
rollingGeoMeanParallel(arr)
assert(count == expected, {
val extra = if (expected == 0) "" else s" ${expected/2} for the `upsweep` and ${expected/2} for the `downsweep`"
s"\n$arr\n\nERROR: Expected $expected instead of $count calls to `parallel(...)` for an array of ${arr.length} elements. Current parallel threshold is $THRESHOLD.$extra"
})
} finally {
count = 0
}
}
}
object RollingGeoMeanNoMap extends M2 with LibImpl with RollingGeoMeanTest {
def parallel[T1, T2](op1: => T1, op2: => T2): (T1, T2) = (op1, op2)
def newArrFrom[T](arr: Array[AnyRef]): Arr[T] = new ArrImpl[T](arr) {
override def map[U](f: T => U): Arr[U] = throw Exception("Should not call Arr.map")
}
}
object RollingGeoMeanNoTail extends M2 with LibImpl with RollingGeoMeanTest {
def parallel[T1, T2](op1: => T1, op2: => T2): (T1, T2) = (op1, op2)
def newArrFrom[T](arr: Array[AnyRef]): Arr[T] = new ArrImpl[T](arr) {
override def tail: Arr[T] = throw Exception("Should not call Arr.tail")
}
}
object RollingGeoMeanParallel extends M2 with LibImpl with RollingGeoMeanTest {
import scala.concurrent.duration._
val TIMEOUT = Duration(10, SECONDS)
def parallel[T1, T2](op1: => T1, op2: => T2): (T1, T2) = {
import concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
Await.result(Future(op1).zip(Future(op2)), TIMEOUT) // FIXME not timing-out
}
def newArrFrom[T](arr: Array[AnyRef]): Arr[T] = new ArrImpl(arr)
}
trait LibImpl extends Lib {
def newArrFrom[T](arr: Array[AnyRef]): Arr[T]
def newArrOfLength[T](n: Int): Arr[T] =
newArrFrom(new Array(n))
class ArrImpl[T](val arr: Array[AnyRef]) extends Arr[T]:
def apply(i: Int): T =
arr(i).asInstanceOf[T]
def update(i: Int, x: T): Unit =
arr(i) = x.asInstanceOf[AnyRef]
def length: Int =
arr.length
def map[U](f: T => U): Arr[U] =
newArrFrom(arr.map(f.asInstanceOf[AnyRef => AnyRef]))
def tail: Arr[T] =
newArrFrom(arr.tail)
override def toString: String =
arr.mkString("Arr(", ", ", ")")
override def equals(that: Any): Boolean =
that match
case that: ArrImpl[_] => Array.equals(arr, that.arr)
case _ => false
}
trait RollingGeoMeanTest extends M2 {
def tabulate[T](n: Int)(f: Int => T): Arr[T] =
val arr = Arr.ofLength[T](n)
for i <- 0 until n do
arr(i) = f(i)
arr
def asSeq(arr: Arr[Double]) =
val array = new Array[Double](arr.length)
for i <- 0 to (arr.length - 1) do
array(i) = arr(i)
array.toSeq
def scanOp_(acc: Root, x: Root) =
Root(acc.radicand * x.radicand, acc.degree + x.degree)
def result(ds: Seq[Int]): Arr[Double] =
Arr(ds.map(x => Root(x, 1)).scan(Root(1, 0))(scanOp_).tail.map(_.toDouble): _*)
def check(input: Seq[Int]) =
assertEquals(
// .toString calls are a terrible kludge so that NaNs compare equal to eachother...
asSeq(rollingGeoMeanParallel(Arr(input: _*))).map(_.toString),
asSeq(result(input)).map(_.toString)
)
def basicTests() = {
check(Seq())
check(Seq(1))
check(Seq(1, 2, 3, 4))
check(Seq(4, 4, 4, 4))
}
def normalTests() = {
check(Seq.tabulate(64)(identity))
check(Seq(4, 4, 4, 4))
check(Seq(4, 8, 6, 4))
check(Seq(4, 3, 2, 1))
check(Seq.tabulate(64)(identity).reverse)
check(Seq.tabulate(128)(i => 128 - 2*i).reverse)
}
def largeTests() = {
check(Seq.tabulate(500)(identity))
check(Seq.tabulate(512)(identity))
check(Seq.tabulate(1_000)(identity))
check(Seq.tabulate(10_000)(identity))
}
}
}
Use the following commands to make a fresh clone of your repository:
```
git clone -b m20 git@gitlab.epfl.ch:lamp/student-repositories-s21/cs206-GASPAR.git m20
```
## Useful links
* [A guide to the Scala parallel collections](https://docs.scala-lang.org/overviews/parallel-collections/overview.html)
* [The API documentation of the Scala parallel collections](https://www.javadoc.io/doc/org.scala-lang.modules/scala-parallel-collections_2.13/latest/scala/collection/index.html)
* [The API documentation of the Scala standard library](https://www.scala-lang.org/files/archive/api/2.13.4)
* [The API documentation of the Java standard library](https://docs.oracle.com/en/java/javase/15/docs/api/index.html)
**If you have issues with the IDE, try [reimporting the
build](https://gitlab.epfl.ch/lamp/cs206/-/blob/master/labs/example-lab.md#ide-features-like-type-on-hover-or-go-to-definition-do-not-work),
if you still have problems, use `compile` in sbt instead.**
## Exercise
In this question, you will complete the definition of two concurrent data
structures **without using `synchronized`**: `SeqCount` and `MultiWriterSeqCount`.
## Part 1: SeqCount (defined in `SeqCount.scala`)
An instance of this class stores two integers (initially set to 0), the stored
values can be updated using `write` and retrieved using `copy`. Only one thread
at a time is allowed to call `write` but multiple threads can call `copy` at
once.
Your task in this part is to implement `copy` such that this method never
returns _partially updated values_, for example given two threads operating
concurrently on a `SeqCount` `sc`:
```scala
// Thread 1
sc.write(1, 2)
```
```scala
// Thread 2
val result = sc.copy()
```
`result` must either be `(0, 0)` (since the initial values are 0) or `(1, 2)`,
but it must not be `(1, 0)`, `(0, 2)` or any other value.
To successfully implement this method you will need to use `generation`: this
method returns the current value of a volatile variable which is initially set
to 0, gets incremented by one at the beginning of `write`, and incremented by
one again at the end of `write`.
**You are not allowed to use `synchronized` or directly call any of
`myGeneration`, `myX` or `myY` (use the pre-defined getters and setters
instead).**
Hints:
- Remember that a write to a volatile field _happens-before_ every subsequent
read of that field.
- `generation` will always be even when a write has completed and always
odd when a write is in progress.
- `copy` can be implemented as a tail-recursive method.
## Part 2: MultiWriterSeqCount (defined in `MultiWriterSeqCount.scala`)
Like `SeqCount`, this class stores two integers updated using `write` and
retrieved using `copy`, but unlike `SeqCount` multiple threads are allowed to
call `write` at the same time: these writes will all succeed but they are
allowed to complete in any order, for example given three threads operating
concurrently on a `MultiWriterSeqCount` `msc`:
```scala
// Thread 1
msc.write(1, 2)
```
```scala
// Thread 2
msc.write(10, 20)
```
```scala
// Thread 3
val result = msc.copy()
```
`result` must either be `(0, 0)`, `(1, 2)` or `(10, 20)`.
In this class, the generation is stored in an atomic variable instead of a
volatible field therefore it's important to note that:
- a `set` on an atomic variable _happens-before_ every subsequent `get` of that
variable.
- A call to `compareAndSet` both gets and set an atomic variable.
Your task in this part is to implement both `copy` and `write`.
**You are not allowed to use `synchronized` or directly call any of
`myGeneration`, `myX` or `myY` (use the pre-defined getters and setters
instead).**
Hints:
- you should be able to just copy-paste the implementation of `copy` you
implemented in Part 1
- you will need to make use of `compareAndSetGeneration` in `write`
- `write` can be implemented as a tail-recursive method.
# General
*.DS_Store
*.swp
*~
# Dotty
*.class
*.tasty
*.hasTasty
# sbt
target/
# IDE
.bsp
.bloop
.metals
.vscode
# datasets
stackoverflow-grading.csv
wikipedia-grading.dat
// Student tasks (i.e. submit, packageSubmission)
enablePlugins(StudentTasks)
course := "midterm"
assignment := "m20"
scalaVersion := "3.0.0-RC1"
scalacOptions ++= Seq("-language:implicitConversions", "-deprecation")
libraryDependencies += "org.scalameta" %% "munit" % "0.7.22"
val MUnitFramework = new TestFramework("munit.Framework")
testFrameworks += MUnitFramework
// Decode Scala names
testOptions += Tests.Argument(MUnitFramework, "-s")
testSuite := "m20.M20Suite"
File deleted
package sbt // To access the private[sbt] compilerReporter key
package filteringReporterPlugin
import Keys._
import ch.epfl.lamp._
object FilteringReporterPlugin extends AutoPlugin {
override lazy val projectSettings = Seq(
// Turn off warning coming from scalameter that we cannot fix without changing scalameter
compilerReporter in (Compile, compile) ~= { reporter => new FilteringReporter(reporter) }
)
}
class FilteringReporter(reporter: xsbti.Reporter) extends xsbti.Reporter {
def reset(): Unit = reporter.reset()
def hasErrors: Boolean = reporter.hasErrors
def hasWarnings: Boolean = reporter.hasWarnings
def printSummary(): Unit = reporter.printSummary()
def problems: Array[xsbti.Problem] = reporter.problems
def log(problem: xsbti.Problem): Unit = {
if (!problem.message.contains("An existential type that came from a Scala-2 classfile cannot be"))
reporter.log(problem)
}
def comment(pos: xsbti.Position, msg: String): Unit =
reporter.comment(pos, msg)
override def toString = s"CollectingReporter($reporter)"
}
package ch.epfl.lamp
import sbt._
import sbt.Keys._
/**
* Coursera uses two versions of each assignment. They both have the same assignment key and part id but have
* different item ids.
*
* @param key Assignment key
* @param partId Assignment partId
* @param itemId Item id of the non premium version
* @param premiumItemId Item id of the premium version (`None` if the assignment is optional)
*/
case class CourseraId(key: String, partId: String, itemId: String, premiumItemId: Option[String])
/**
* Settings shared by all assignments, reused in various tasks.
*/
object MOOCSettings extends AutoPlugin {
override def requires = super.requires && filteringReporterPlugin.FilteringReporterPlugin
object autoImport {
val course = SettingKey[String]("course")
val assignment = SettingKey[String]("assignment")
val options = SettingKey[Map[String, Map[String, String]]]("options")
val courseraId = settingKey[CourseraId]("Coursera-specific information identifying the assignment")
val testSuite = settingKey[String]("Fully qualified name of the test suite of this assignment")
.withRank(KeyRanks.Invisible)
// Convenient alias
type CourseraId = ch.epfl.lamp.CourseraId
val CourseraId = ch.epfl.lamp.CourseraId
}
import autoImport._
override val globalSettings: Seq[Def.Setting[_]] = Seq(
// supershell is verbose, buggy and useless.
useSuperShell := false
)
override val projectSettings: Seq[Def.Setting[_]] = Seq(
parallelExecution in Test := false,
// Report test result after each test instead of waiting for every test to finish
logBuffered in Test := false,
name := s"${course.value}-${assignment.value}"
)
}
package ch.epfl.lamp
import sbt._
import Keys._
// import scalaj.http._
import java.io.{File, FileInputStream, IOException}
import org.apache.commons.codec.binary.Base64
// import play.api.libs.json.{Json, JsObject, JsPath}
import scala.util.{Failure, Success, Try}
/**
* Provides tasks for submitting the assignment
*/
object StudentTasks extends AutoPlugin {
override def requires = super.requires && MOOCSettings
object autoImport {
val packageSourcesOnly = TaskKey[File]("packageSourcesOnly", "Package the sources of the project")
val packageBinWithoutResources = TaskKey[File]("packageBinWithoutResources", "Like packageBin, but without the resources")
val packageSubmissionZip = TaskKey[File]("packageSubmissionZip")
val packageSubmission = inputKey[Unit]("package solution as an archive file")
lazy val Grading = config("grading") extend(Runtime)
}
import autoImport._
import MOOCSettings.autoImport._
override lazy val projectSettings = Seq(
packageSubmissionSetting,
fork := true,
connectInput in run := true,
outputStrategy := Some(StdoutOutput),
) ++
packageSubmissionZipSettings ++
inConfig(Grading)(Defaults.testSettings ++ Seq(
unmanagedJars += file("grading-tests.jar"),
definedTests := (definedTests in Test).value,
internalDependencyClasspath := (internalDependencyClasspath in Test).value
))
/** **********************************************************
* SUBMITTING A SOLUTION TO COURSERA
*/
val packageSubmissionZipSettings = Seq(
packageSubmissionZip := {
val submission = crossTarget.value / "submission.zip"
val sources = (packageSourcesOnly in Compile).value
val binaries = (packageBinWithoutResources in Compile).value
IO.zip(Seq(sources -> "sources.zip", binaries -> "binaries.jar"), submission, None)
submission
},
artifactClassifier in packageSourcesOnly := Some("sources"),
artifact in (Compile, packageBinWithoutResources) ~= (art => art.withName(art.name + "-without-resources"))
) ++
inConfig(Compile)(
Defaults.packageTaskSettings(packageSourcesOnly, Defaults.sourceMappings) ++
Defaults.packageTaskSettings(packageBinWithoutResources, Def.task {
val relativePaths =
(unmanagedResources in Compile).value.flatMap(Path.relativeTo((unmanagedResourceDirectories in Compile).value)(_))
(mappings in (Compile, packageBin)).value.filterNot { case (_, path) => relativePaths.contains(path) }
})
)
val maxSubmitFileSize = {
val mb = 1024 * 1024
10 * mb
}
/** Check that the jar exists, isn't empty, isn't crazy big, and can be read
* If so, encode jar as base64 so we can send it to Coursera
*/
def prepareJar(jar: File, s: TaskStreams): String = {
val errPrefix = "Error submitting assignment jar: "
val fileLength = jar.length()
if (!jar.exists()) {
s.log.error(errPrefix + "jar archive does not exist\n" + jar.getAbsolutePath)
failSubmit()
} else if (fileLength == 0L) {
s.log.error(errPrefix + "jar archive is empty\n" + jar.getAbsolutePath)
failSubmit()
} else if (fileLength > maxSubmitFileSize) {
s.log.error(errPrefix + "jar archive is too big. Allowed size: " +
maxSubmitFileSize + " bytes, found " + fileLength + " bytes.\n" +
jar.getAbsolutePath)
failSubmit()
} else {
val bytes = new Array[Byte](fileLength.toInt)
val sizeRead = try {
val is = new FileInputStream(jar)
val read = is.read(bytes)
is.close()
read
} catch {
case ex: IOException =>
s.log.error(errPrefix + "failed to read sources jar archive\n" + ex.toString)
failSubmit()
}
if (sizeRead != bytes.length) {
s.log.error(errPrefix + "failed to read the sources jar archive, size read: " + sizeRead)
failSubmit()
} else encodeBase64(bytes)
}
}
/** Task to package solution to a given file path */
lazy val packageSubmissionSetting = packageSubmission := {
val args: Seq[String] = Def.spaceDelimited("[path]").parsed
val s: TaskStreams = streams.value // for logging
val jar = (packageSubmissionZip in Compile).value
val base64Jar = prepareJar(jar, s)
val path = args.headOption.getOrElse((baseDirectory.value / "submission.jar").absolutePath)
scala.tools.nsc.io.File(path).writeAll(base64Jar)
}
/*
/** Task to submit a solution to coursera */
val submit = inputKey[Unit]("submit solution to Coursera")
lazy val submitSetting = submit := {
// Fail if scalafix linting does not pass.
scalafixLinting.value
val args: Seq[String] = Def.spaceDelimited("<arg>").parsed
val s: TaskStreams = streams.value // for logging
val jar = (packageSubmissionZip in Compile).value
val assignmentDetails =
courseraId.?.value.getOrElse(throw new MessageOnlyException("This assignment can not be submitted to Coursera because the `courseraId` setting is undefined"))
val assignmentKey = assignmentDetails.key
val courseName =
course.value match {
case "capstone" => "scala-capstone"
case "bigdata" => "scala-spark-big-data"
case other => other
}
val partId = assignmentDetails.partId
val itemId = assignmentDetails.itemId
val premiumItemId = assignmentDetails.premiumItemId
val (email, secret) = args match {
case email :: secret :: Nil =>
(email, secret)
case _ =>
val inputErr =
s"""|Invalid input to `submit`. The required syntax for `submit` is:
|submit <email-address> <submit-token>
|
|The submit token is NOT YOUR LOGIN PASSWORD.
|It can be obtained from the assignment page:
|https://www.coursera.org/learn/$courseName/programming/$itemId
|${
premiumItemId.fold("") { id =>
s"""or (for premium learners):
|https://www.coursera.org/learn/$courseName/programming/$id
""".stripMargin
}
}
""".stripMargin
s.log.error(inputErr)
failSubmit()
}
val base64Jar = prepareJar(jar, s)
val json =
s"""|{
| "assignmentKey":"$assignmentKey",
| "submitterEmail":"$email",
| "secret":"$secret",
| "parts":{
| "$partId":{
| "output":"$base64Jar"
| }
| }
|}""".stripMargin
def postSubmission[T](data: String): Try[HttpResponse[String]] = {
val http = Http("https://www.coursera.org/api/onDemandProgrammingScriptSubmissions.v1")
val hs = List(
("Cache-Control", "no-cache"),
("Content-Type", "application/json")
)
s.log.info("Connecting to Coursera...")
val response = Try(http.postData(data)
.headers(hs)
.option(HttpOptions.connTimeout(10000)) // scalaj default timeout is only 100ms, changing that to 10s
.asString) // kick off HTTP POST
response
}
val connectMsg =
s"""|Attempting to submit "${assignment.value}" assignment in "$courseName" course
|Using:
|- email: $email
|- submit token: $secret""".stripMargin
s.log.info(connectMsg)
def reportCourseraResponse(response: HttpResponse[String]): Unit = {
val code = response.code
val respBody = response.body
/* Sample JSON response from Coursera
{
"message": "Invalid email or token.",
"details": {
"learnerMessage": "Invalid email or token."
}
}
*/
// Success, Coursera responds with 2xx HTTP status code
if (response.is2xx) {
val successfulSubmitMsg =
s"""|Successfully connected to Coursera. (Status $code)
|
|Assignment submitted successfully!
|
|You can see how you scored by going to:
|https://www.coursera.org/learn/$courseName/programming/$itemId/
|${
premiumItemId.fold("") { id =>
s"""or (for premium learners):
|https://www.coursera.org/learn/$courseName/programming/$id
""".stripMargin
}
}
|and clicking on "My Submission".""".stripMargin
s.log.info(successfulSubmitMsg)
}
// Failure, Coursera responds with 4xx HTTP status code (client-side failure)
else if (response.is4xx) {
val result = Try(Json.parse(respBody)).toOption
val learnerMsg = result match {
case Some(resp: JsObject) =>
(JsPath \ "details" \ "learnerMessage").read[String].reads(resp).get
case Some(x) => // shouldn't happen
"Could not parse Coursera's response:\n" + x
case None =>
"Could not parse Coursera's response:\n" + respBody
}
val failedSubmitMsg =
s"""|Submission failed.
|There was something wrong while attempting to submit.
|Coursera says:
|$learnerMsg (Status $code)""".stripMargin
s.log.error(failedSubmitMsg)
}
// Failure, Coursera responds with 5xx HTTP status code (server-side failure)
else if (response.is5xx) {
val failedSubmitMsg =
s"""|Submission failed.
|Coursera seems to be unavailable at the moment (Status $code)
|Check https://status.coursera.org/ and try again in a few minutes.
""".stripMargin
s.log.error(failedSubmitMsg)
}
// Failure, Coursera repsonds with an unexpected status code
else {
val failedSubmitMsg =
s"""|Submission failed.
|Coursera replied with an unexpected code (Status $code)
""".stripMargin
s.log.error(failedSubmitMsg)
}
}
// kick it all off, actually make request
postSubmission(json) match {
case Success(resp) => reportCourseraResponse(resp)
case Failure(e) =>
val failedConnectMsg =
s"""|Connection to Coursera failed.
|There was something wrong while attempting to connect to Coursera.
|Check your internet connection.
|${e.toString}""".stripMargin
s.log.error(failedConnectMsg)
}
}
*/
def failSubmit(): Nothing = {
sys.error("Submission failed")
}
/**
* *****************
* DEALING WITH JARS
*/
def encodeBase64(bytes: Array[Byte]): String =
new String(Base64.encodeBase64(bytes))
}
sbt.version=1.4.7
// Used for Coursera submission (StudentPlugin)
// libraryDependencies += "org.scalaj" %% "scalaj-http" % "2.4.2"
// libraryDependencies += "com.typesafe.play" %% "play-json" % "2.7.4"
// Used for Base64 (StudentPlugin)
libraryDependencies += "commons-codec" % "commons-codec" % "1.10"
// addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.28")
addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.5.3")
package m20
import instrumentation._
import scala.annotation.tailrec
/** Multi-writer, multi-reader data structure containing a pair of integers. */
class MultiWriterSeqCount extends Monitor:
/** Do not directly use this variable, use `generation`, `setGeneration` and
* `compareAndSetGeneration` instead.
*/
protected val myGeneration: AbstractAtomicVariable[Int] = new AtomicVariable(0)
protected def generation: Int = myGeneration.get
protected def setGeneration(newGeneration: Int): Unit =
myGeneration.set(newGeneration)
protected def compareAndSetGeneration(expected: Int, newValue: Int): Boolean =
myGeneration.compareAndSet(expected, newValue)
/** Do not directly use this variable, use `x` and `setX` instead. */
protected var myX: Int = 0
protected def x: Int = myX
protected def setX(newX: Int): Unit =
myX = newX
/** Do not directly use this variable, use `y` and `setY` instead. */
protected var myY: Int = 0
protected def y: Int = myY
protected def setY(newY: Int): Unit =
myY = newY
/** Write new values into this data structure.
* This method is always safe to call.
* The implementation of this method is not allowed to call `synchronized`.
*/
@tailrec
final def write(newX: Int, newY: Int): Unit =
val old = generation
if old % 2 != 0 then
write(newX, newY)
else
if !compareAndSetGeneration(old, old + 1) then
write(newX, newY)
else
setX(newX)
setY(newY)
setGeneration(old + 2)
/** Copy the values previously written into this data structure into a tuple.
* This method is always safe to call.
* The implementation of this method is not allowed to call `synchronized`.
*/
@tailrec
final def copy(): (Int, Int) =
val old = generation
if old % 2 != 0 then
copy()
else
val result = (x, y)
if generation != old then
copy()
else
result
end MultiWriterSeqCount
package m20
import instrumentation._
import scala.annotation.tailrec
/** Single-writer, multi-reader data structure containing a pair of integers. */
class SeqCount extends Monitor:
/** Do not directly use this variable, use `generation` and `setGeneration` instead. */
@volatile protected var myGeneration: Int = 0
protected def generation: Int = myGeneration
protected def setGeneration(newGeneration: Int): Unit =
myGeneration = newGeneration
/** Do not directly use this variable, use `x` and `setX` instead. */
protected var myX: Int = 0
protected def x: Int = myX
protected def setX(newX: Int): Unit =
myX = newX
/** Do not directly use this variable, use `y` and `setY` instead. */
protected var myY: Int = 0
protected def y: Int = myY
protected def setY(newY: Int): Unit =
myY = newY
/** Write new values into this data structure.
* This method must only be called from one thread at a time.
*/
final def write(newX: Int, newY: Int): Unit =
setGeneration(generation + 1)
setX(newX)
setY(newY)
setGeneration(generation + 1)
/** Copy the values previously written into this data structure into a tuple.
* This method is always safe to call.
* The implementation of this method is not allowed to call `synchronized`.
*/
@tailrec
final def copy(): (Int, Int) =
val old = generation
if old % 2 != 0 then
copy()
else
val result = (x, y)
if generation != old then
copy()
else
result
end SeqCount
package m20.instrumentation
import java.util.concurrent.atomic._
abstract class AbstractAtomicVariable[T] {
def get: T
def set(value: T): Unit
def compareAndSet(expect: T, newval: T) : Boolean
}
class AtomicVariable[T](initial: T) extends AbstractAtomicVariable[T] {
private val atomic = new AtomicReference[T](initial)
override def get: T = atomic.get()
override def set(value: T): Unit = atomic.set(value)
override def compareAndSet(expected: T, newValue: T): Boolean = {
val current = atomic.get
if (current == expected) {
atomic.compareAndSet(current, newValue)
}
else {
false
}
}
}
package m20.instrumentation
class Dummy
trait Monitor {
implicit val dummy: Dummy = new Dummy
def wait()(implicit i: Dummy) = waitDefault()
def synchronized[T](e: => T)(implicit i: Dummy) = synchronizedDefault(e)
def notify()(implicit i: Dummy) = notifyDefault()
def notifyAll()(implicit i: Dummy) = notifyAllDefault()
private val lock = new AnyRef
// Can be overriden.
def waitDefault(): Unit = lock.wait()
def synchronizedDefault[T](toExecute: =>T): T = lock.synchronized(toExecute)
def notifyDefault(): Unit = lock.notify()
def notifyAllDefault(): Unit = lock.notifyAll()
}