Created singleton object can't be detected in main function (Scala) - package

Singleton object LongLines which I created can't be recognized in object with main function (FindingLines). I put their files (LongLines.scala, FindingLines.scala ) in /src/main/scala/com/files/lines directory. Program code should have to find in particular file the lines which length is greater than parameter width.
Codes:
1) LongLines.scala (version from book I learn):
package com.files.lines
import scala.io.Source
object LongLines {
def processFile(filename: String, width: Int) {
val source = Source.fromFile(filename)
for (line <- source.getLines())
processLine(filename, width, line)
}
private def processLine(filename: String,
width: Int, line: String) {
if (line.length > width)
println(filename +": "+ line.trim)
}
}
2) LongLines.scala (my own version):
package com.files.lines
import scala.io.Source._
import java.nio.files.Paths._
object LongLines {
def processFile(filePath: String, width:Int): Unit = {
val path = get(filePath)
val fileName = path.getFileName.toString
val lines = fromFile(filePath).getLines().toList
for (line<-lines) processLines(fileName,line,width)
}
private def processLines(fileName: String, line: String, width: Int): Unit = {
if (line.length() > width) println(s"$fileName: $line");
}
}
3) FindingLines.scala (book version I used - only version):
package com.files.lines
object FindLongLines {
def main(args: Array[String]) = {
val width = args(0).toInt
for (arg <- args.drop(1))
LongLines.processFile(arg, width)
}
}
Error (compiled from linux terminal):
After I compiled program with my version and book version of LongLines.scala (separately, of course):
scalac FindingLines.scala
I've got this error:
FindLongLines.scala:15: error: not found: value LongLines
LongLines.processFile(arg, width)
^
one error found

Solution:
1) I removed "package com.file.lines" from both files (FindingLines.scala, LongLines.scala) - that means I need not to remove those files in this package (directory). Those two files could stay in src/main/scala directory.
2) scalac FindingLines.scala LongLines.scala
3) scala FindingLines.scala 45 ~/workspace/Rational/src/Rational.scala

Related

Why can't I test that a class's instance is defined

I have a helper class which creates instance of another class
class TestEnv {
val questionsController = new QuestionsController(...)
}
I am unit testing QuestionsController and have created a basic test case
class QuestionsControllerUnitSpec extends PlaySpec with BeforeAndAfterAll with BeforeAndAfterEach with OneAppPerSuiteWithComponents{
override def beforeEach() = {
println("------------new test -----------------")
}
override def components: BuiltInComponents = new BuiltInComponentsFromContext(context) with NoHttpFiltersComponents {
import play.api.mvc.Results
import play.api.routing.Router
import play.api.routing.sird._
lazy val router: Router = Router.from({
case GET(p"/") => defaultActionBuilder {
Results.Ok("success!")
}
})
}
"Question Controller " should {
"be created" in {
val testEnv = new TestEnv(components = components)
val qc:QuestionsController = testEnv.questionsController
qc mustBe defined //I get compilation error
}
}
}
I get the following compilation error
Error:(52, 10) could not find implicit value for parameter definition: org.scalatest.enablers.Definition[controllers.QuestionsController]
qc mustBe defined
Error:(52, 10) not enough arguments for method mustBe: (implicit definition: org.scalatest.enablers.Definition[controllers.QuestionsController])org.scalatest.Assertion.
Unspecified value parameter definition.
qc mustBe defined
I checked the definition of mustBe in MustMatchers.class. It is defined as def mustBe(right : org.scalatest.words.DefinedWord)(implicit definition : org.scalatest.enablers.Definition[T]) : org.scalatest.Assertion = { /* compiled code */ }
Why am I getting the error.
defined matcher syntax can be used with user defined types if we provide implicit implementation of Definition trait. For example, say we have a user defined class
class Foo {
val bar = 3
}
and we provide implicit definition
implicit val fooDefinition = new Definition[Foo] {
override def isDefined(foo: Foo): Boolean = foo.bar != null
}
then we can use defined syntax
(new Foo()) mustBe defined
If similar implicit implementation of Definition[QuestionsController] is provided, then the compiler error should be resolved.
I am happy to accept a different answer if it can provide more accurate answer. I suppose I am testing the wrong thing. What I am doing is similar to declaring an integer and checking if the integer exists! Instead I should be checking the value of the integer.
About matchers, more information is at http://doc.scalatest.org/3.0.1/#org.scalatest.MustMatchers. More information on Definition is on http://doc.scalatest.org/3.0.1/#org.scalatest.enablers.Definition

How to read plain text file in kotlin?

There may be various way to read plain text file in kotlin.
I want know what are the possible ways and how I can use them.
1. Using BufferedReader
import java.io.File
import java.io.BufferedReader
fun main(args: Array<String>) {
val bufferedReader: BufferedReader = File("example.txt").bufferedReader()
val inputString = bufferedReader.use { it.readText() }
println(inputString)
}
2. Using InputStream
Read By Line
import java.io.File
import java.io.InputStream
fun main(args: Array<String>) {
val inputStream: InputStream = File("example.txt").inputStream()
val lineList = mutableListOf<String>()
inputStream.bufferedReader().forEachLine { lineList.add(it) }
lineList.forEach{println("> " + it)}
}
Read All Lines
import java.io.File
import java.io.InputStream
fun main(args: Array<String>) {
val inputStream: InputStream = File("example.txt").inputStream()
val inputString = inputStream.bufferedReader().use { it.readText() }
println(inputString)
}
3. Use File directly
import java.io.File
import java.io.BufferedReader
fun main(args: Array<String>) {
val lineList = mutableListOf<String>()
File("example.txt").useLines { lines -> lines.forEach { lineList.add(it) }}
lineList.forEach { println("> " + it) }
}
I think the simplest way to code is using kotlin.text and java.io.File
import java.io.File
fun main(args: Array<String>) {
val text = File("sample.txt").readText()
println(text)
}
The answers above here are all based on Kotlin Java. Here is a Kotlin Native way to read text files:
val bufferLength = 64 * 1024
val buffer = allocArray<ByteVar>(bufferLength)
for (i in 1..count) {
val nextLine = fgets(buffer, bufferLength, file)?.toKString()
if (nextLine == null || nextLine.isEmpty()) break
val records = parseLine(nextLine, ',')
val key = records[column]
val current = keyValue[key] ?: 0
keyValue[key] = current + 1
}
fun parseLine(line: String, separator: Char) : List<String> {
val result = mutableListOf<String>()
val builder = StringBuilder()
var quotes = 0
for (ch in line) {
when {
ch == '\"' -> {
quotes++
builder.append(ch)
}
(ch == '\n') || (ch == '\r') -> {}
(ch == separator) && (quotes % 2 == 0) -> {
result.add(builder.toString())
builder.setLength(0)
}
else -> builder.append(ch)
}
}
return result
}
See: https://github.com/JetBrains/kotlin-native/blob/master/samples/csvparser/src/csvParserMain/kotlin/CsvParser.kt
Anisuzzaman's answer lists several possibilities.
The main differences between them are in whether the file is read into memory as a single String, read into memory and split into lines, or read line-by-line.
Obviously, reading the entire file into memory in one go can take a lot more memory, so that's something to avoid unless it's really necessary.  (Text files can get arbitrarily big!)  So processing line-by-line with BufferedReader.useLines() is often a good approach.
The remaining differences are mostly historical.  Very early versions of Java used InputStream &c which didn't properly distinguish between characters and bytes; Reader &c were added to correct that.  Java 8 added ways to read line-by-line more efficiently using streams (e.g. Files.lines()).  And more recently, Kotlin has added its own extension functions (e.g. BufferedReader.useLines()) which make it even simpler.
To read a text file, it must first be created. In Android Studio, you would create the text file like this:
1) Select "Project" from the top of the vertical toolbar to open the project "tool window"
2) From the drop-down menu at the top of the "tool window", select "Android"
3) Right-click on "App" and select "New"
then -> "Folder" (the one with the green Android icon beside it)
then -> "Assets Folder"
4) Right-click on the "assets" folder after it appears in the "tool window"
5) Select "New" -> "File"
6) Name the file, and included the extension ".txt" if it is text file, or ".html" if it is for WebView
7) Edit the file or cut and paste text into it. The file will now display under the "Project" files in the "tool window" and you will be able to double-click it to edit it at any time.
TO ACCESS THIS FILE, use a prefix of "application.assets." followed by someFunction(fileName). For example (in Kotlin):
val fileName = "townNames.txt"
val inputString = application.assets.open(fileName).bufferedReader().use { it.readText() }
val townList: List<String> = inputString.split("\n")
how to apply Documents path on that:
fun main(args: Array<String>) {
val inputStream: InputStream = File("example.txt").inputStream()
val inputString = inputStream.bufferedReader().use { it.readText() }
println(inputString)
}

Dart TreeSanitzer: No static getter 'trusted' declared in class 'NodeTreeSanitizer'

I'm using the Bootjack Datepicker and after upgrading Dart to 1.12.1, I'm all of a sudden seeing only half a calendar with no days and with this exception:
Exception: No static getter 'trusted' declared in class
'NodeTreeSanitizer'. NoSuchMethodError: method not found: 'trusted'
Receiver: Type: class 'NodeTreeSanitizer'
This is the only line of code needed to wire the calendar:
Calendar.use();
If you need to manually wire the calendar, you can manually call:
Calendar.wire(querySelector("div.calendar"));
Both of them are giving me the exception in calendar.dart
The code that seems to be breaking is:
void _dayView() {
TableElement calBody = element.querySelector('.cnt');
Element dow = calBody.tBodies[0].createFragment(_DOW_TEMPLATE).children[0];
List<Element> children = dow.children;
List<String> swkDays = _dfmt.dateSymbols.SHORTWEEKDAYS;
int ofs = (_firstDayOfWeek + 1) % 7;
//render week days
for (int i = swkDays.length; --i >= 0;) {
children[i].text = swkDays[(i + ofs) % 7];
}
var buffer = new StringBuffer();
for (int i = 6; --i >= 0;) {
buffer.write(_DAYROW_TEMPLATE);
}
calBody.tBodies[0]
..append(dow)
..appendHtml(buffer.toString(), treeSanitizer: NodeTreeSanitizer.trusted); <<<<<<<< ERROR
}
Looking at appendHtml, I can see treeSanitizer is an optional param, so that syntax looks fine. In the abstract class NodeTreeSanitizer, I can see: static const trusted = const _TrustedHtmlTreeSanitizer();, so that seems to be fine as well.
Any idea what could be causing this error?
I've logged a bug here in the meantime: https://github.com/rikulo/bootjack-datepicker/issues/2
Looks like your Dartium version is outdated.
Please compare the output of dart --version (command line) and the Dart version on the about://version page in Dartium.

How to split a File Source into Strings or Words

I have a file with content like this:
"Some","Words","separated","by","comma","and","quoted","with","double","quotes"
The File is to large to read it into just on String.
What is the simplest way to split it into a Traversable of Strings, with each element being a word?
If it matters: While the content of the file won't fit in a single String the resulting Traversable might be a List without a problem.
Here is an adaptation of your own solution, using JavaConversions to manipulate the Java iterator as a Scala one.
import java.util.Scanner
import java.io.File
import scala.collection.JavaConversions._
val scanner = new Scanner(new File("...")).useDelimiter(",")
scanner.map(_.trim).map(quoted => quoted.substring(1, quoted.length - 1))
This gives you an iterator. You can always convert it to a list using e.g. .toList.
Here is a version using stringLit and repsep from Scala parser combinators. I won't vouch for its efficiency, though.
import scala.util.parsing.combinator.syntactical.StdTokenParsers
import scala.util.parsing.combinator.lexical.StdLexical
import scala.util.parsing.input.StreamReader
import java.io.FileReader
object P extends StdTokenParsers {
type Tokens = StdLexical
val lexical = new StdLexical
lexical.delimiters += ","
def words : Parser[List[String]] = repsep(stringLit, ",")
def getWords(fileName : String) : List[String] = {
val scanner = new lexical.Scanner(StreamReader(new FileReader(fileName)))
// better error handling wouldn't hurt.
words(scanner).get
}
}
I did it using the java.util.Scanner while it does work, I'd appreciate a more scalaesc version.
val scanner = new Scanner(new File("""bigFile.txt""")).useDelimiter(",")
var wordList: Vector[String] = Vector()
while (scanner.hasNext()) {
val quoted = scanner.next()
val word = quoted.replace("\"", "")
wordList = wordList :+ word
}

Get a list of all the files in a directory (recursive)

I'm trying to get (not print, that's easy) the list of files in a directory and its sub directories.
I've tried:
def folder = "C:\\DevEnv\\Projects\\Generic";
def baseDir = new File(folder);
files = baseDir.listFiles();
I only get the directories. I've also tried:
def files = [];
def processFileClosure = {
println "working on ${it.canonicalPath}: "
files.add (it.canonicalPath);
}
baseDir.eachFileRecurse(FileType.FILES, processFileClosure);
But "files" is not recognized in the scope of the closure.
How do I get the list?
This code works for me:
import groovy.io.FileType
def list = []
def dir = new File("path_to_parent_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
list << file
}
Afterwards the list variable contains all files (java.io.File) of the given directory and its subdirectories:
list.each {
println it.path
}
Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:
import static groovy.io.FileType.FILES
def dir = new File(".");
def files = [];
dir.traverse(type: FILES, maxDepth: 0) { files.add(it) };
See also [1] for more examples.
[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html
The following works for me in Gradle / Groovy for build.gradle for an Android project, without having to import groovy.io.FileType (NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):
FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
println "Proguard file located and processed: " + it
}
This is what I came up with for a gradle build script:
task doLast {
ext.FindFile = { list, curPath ->
def files = file(curPath).listFiles().sort()
files.each { File file ->
if (file.isFile()) {
list << file
}
else {
list << file // If you want the directories in the list
list = FindFile( list, file.path)
}
}
return list
}
def list = []
def theFile = FindFile(list, "${project.projectDir}")
list.each {
println it.path
}
}
With Kotlin Gradle script one can do it like this:
// ...
val yamls = layout.files({
file("src/main/resources/mixcr_presets").walk()
.filter { it.extension == "yaml" }
.toList()
})
// ...

Resources