scala console error when testing sample IO using zio - zio

Hi I've below ZIO ConsoleIO test.
import zio._
import zio.Console
import zio.test.Assertion.equalTo
import zio.test._
object ConsoleIOSpec extends ZIOSpecDefault {
val greet: ZIO[Any, Nothing, Unit] = for {
name <- Console.readLine.orDie
_ <- Console.printLine(s"Hello, $name").orDie
} yield ()
def spec = suite("ExampleSpec")(
test("greet says hello to the user") {
for {
_ <- TestConsole.feedLines("Jack")
_ <- greet
value <- TestConsole.output
} yield assert(value) (equalTo(Vector("Hello, Jack")))
}
)
}
The code is on this github here. When I run the test I get the below error -
ExampleSpec / greet says hello to the user
✗ Vector1("Hello, Jack
") was not equal to Vector1("Hello, Jack")
value did not satisfy equalTo(Vector("Hello, Jack"))
value = Vector1("Hello, Jack
")
at /Users/rnatarajan/Documents/Coding/others/zionomicon/c2-testing/src/test/scala/ConsoleIOSpec.scala:18
Output Produced by Test
| Jack
| Hello, Jack
I've attached the error screenshot -
This is code from zionomicon book section 3.3 Test Implementations Of Standard ZIO Services.
How to fix this issue?

Method "Console.printLine" prints the string in parameter, and a carriage return at the end of it, as you can see with the double quotes in a new line.
To fix the problem, you can replace "Console.printLine" with "Console.print", or take into account the return carriage at the end of the output.

Related

ZIO.fail not fail

I want learn methods refineXXX of zio library.
For this purpose I write simple code
import zio.ZIOAppDefault
import zio.Unsafe.unsafe
import zio._
import java.sql.SQLException
object Bot extends ZIOAppDefault {
val codeWithExc: ZIO[Any,Throwable,Int] =
ZIO.fail(new SQLException("message of SQL error."))
val MainApp: ZIO[Any, Throwable, Int] = for {
_ <- Console.printLine("Begin")
res <- codeWithExc
_ <- Console.printLine(s" res = $res")
} yield res
def run: URIO[ZIOAppArgs, ExitCode] =
for {
res <- MainApp.exitCode
} yield res
}
unsafe{ implicit u =>
Runtime.default.unsafe.run(Bot.run.provide(ZIOAppArgs.empty))
}
When I run it in IDEA worksheet I see output:
Begin
res0: zio.Exit[Nothing,zio.ExitCode] = Success(ExitCode(1))
and expect fail in res <- codeWithExc and death of the main fiber.
The problem here is that You are mapping ZIO to .exitCode which returns URIO that cannot really fail. Failure will be mapped to success and the only reason to tell that it did actually fail is to verify that ExitCode was not 0. If You change Your code and replace that with something like below, it will look work correctly:
def run = MainApp

Cannot convert value of type 'UnsafeBufferPointer' to expected argument type 'rawPointer'

extension NSData {
func hexString() -> String {
return UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(bytes), count: length)
.reduce("") { $0 + String(format: "%02x", $1) }
}
}
Since Xcode 11 getting the Mac address from hex in swift is just making me loopy. I was told this was a good way to do it, but all I get are errors.
I get the MAC address incased in a string from a Ble device connecting to iOS , of course in 11, 12 and under I get the Mac address in the format I need.
I get the Mac address like this from the Ble device. <hexvalue>
I have code that removes the < and > that works, but ever since the updates Apple did, I know get this as an example : "{length = 6, bytes = 0x686578636172}\n
How do I just simply remove the extra crap now? all I need is the hex. I can convert that to the Mac by inserting :, that's easy. debugDescription doesn't work. .description doesn't work and I understand it was never intended to be used that way, but I am plopped into a code base that uses it like that in a lot of files.
try this
import Foundation
extension Data {
func hexString() -> String {
self.compactMap {
String(format: "%02x", $0)
}.joined()
}
}
var data = Data("Hello World".utf8)
data.append(contentsOf: [1,2,3,4,5])
print(data.hexString())
prints
48656c6c6f20576f726c640102030405
or even better
import Foundation
extension Data {
var hexString: String {
self.compactMap {
String(format: "%02x", $0)
}.joined()
}
}
var data = Data("Hello World".utf8)
data.append(contentsOf: [1,2,3,4,5])
print(data.hexString)

Can't get Speech SDK to return LUIS intents in swift

Started with the basic helloworld example this recognises speech correctly however I want to get intents back so modified the ViewController.swift as follows:
func recognizeFromMic() {
var speechConfig: SPXSpeechConfiguration?
do {
try speechConfig = SPXSpeechConfiguration(subscription: sub, region: region)
} catch {
print("error \(error) happened")
speechConfig = nil
}
speechConfig?.speechRecognitionLanguage = "en-US"
let audioConfig = SPXAudioConfiguration()
let languageUnderstandingModel = SPXLanguageUnderstandingModel(subscription: luisSub, withAppId: luisAppId, andRegion: luisRegion)
let reco = try! SPXIntentRecognizer(speechConfiguration: speechConfig!, audioConfiguration: audioConfig)
reco.addAllIntents(from: languageUnderstandingModel!)
reco.addRecognizingEventHandler() {reco, evt in
print("intermediate recognition result: \(evt.result?.text ?? "(no result)")")
self.logResultReason(reason: (evt.result?.reason)!);
self.updateLabel(text: evt.result?.text, color: .gray)
}
updateLabel(text: "Listening ...", color: .gray)
print("Listening...")
let result = try! reco.recognizeOnce()
print("recognition result: \(result.text ?? "(no result)")")
self.logResultReason(reason: result.reason);
updateLabel(text: result.text, color: .black)
}
func logResultReason(reason: SPXResultReason) {
switch reason {
case .canceled:
print("cancelled")
break
case .noMatch:
print("no Match")
break
case .recognizedIntent:
print("Intent")
break
case .recognizingIntent:
print("Recognizing Intent")
break
case .recognizingSpeech:
print("Recognizing Speech")
break
case .recognizedSpeech:
print("Speech")
break
default:
print("Other")
}
}
The output is
Token:
Listening...
2019-12-16 20:43:57.974675+1300 helloworld[51677:4869822] [plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x6000024d32c0> F8BB1C28-BAE8-11D6-9C31-00039315CD46
2019-12-16 20:43:58.156465+1300 helloworld[51677:4869886] PropertyID=1667788144 is NULL
intermediate recognition result: how
Recognizing Speech
intermediate recognition result: hello
Recognizing Speech
intermediate recognition result: hello world
Recognizing Speech
recognition result:
cancelled
There is long pause (30+ seconds) before the "recognition result" message is output. Looking on LUIS I can see that no utterances have been sent to endpoint. The LUIS subscription, appId I have used extensively for bots from C# and JS so reasonably confident that these are correct (I haven't included here for obvious reasons).
Hopefully something simple I have missed - any help greatly appreciated
Solution turned out to be related to setting up new paid for subscription and assigning that to LUIS model as resource.

Loop through Map in Groovy?

I have a very simple task I am trying to do in Groovy but cannot seem to get it to work. I am just trying to loop through a map object in groovy and print out the key and value but this code does not work.
// A simple map
def map = [
iPhone : 'iWebOS',
Android: '2.3.3',
Nokia : 'Symbian',
Windows: 'WM8'
]
// Print the values
for (s in map) {
println s + ": " + map[s]
}
I am trying to get the output to look like this:
iPhone: iWebOS
Android: 2.3.3
Nokia: Symbian
Windows: WM8
Could someone please elaborate on how to do this??
Quite simple with a closure:
def map = [
'iPhone':'iWebOS',
'Android':'2.3.3',
'Nokia':'Symbian',
'Windows':'WM8'
]
map.each{ k, v -> println "${k}:${v}" }
Alternatively you could use a for loop as shown in the Groovy Docs:
def map = ['a':1, 'b':2, 'c':3]
for ( e in map ) {
print "key = ${e.key}, value = ${e.value}"
}
/*
Result:
key = a, value = 1
key = b, value = 2
key = c, value = 3
*/
One benefit of using a for loop as opposed to an each closure is easier debugging, as you cannot hit a break point inside an each closure (when using Netbeans).
When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value
Another option:
def map = ['a':1, 'b':2, 'c':3]
map.each{
println it.key +" "+ it.value
}

remove duplicates from collection

I want to get a list of all Locales that have a different language, where the ISO3 code is used to identify the language of a Locale. I thought the following should work
class ISO3LangComparator implements Comparator<Locale> {
int compare(Locale locale1, Locale locale2) {
locale1.ISO3Language <=> locale2.ISO3Language
}
}
def allLocales = Locale.getAvailableLocales().toList()
def uniqueLocales = allLocales.unique {new ISO3LangComparator()}
// Test how many locales there are with iso3 code 'ara'
def arabicLocaleCount = uniqueLocales.findAll {it.ISO3Language == 'ara'}.size()
// This assertion fails
assert arabicLocaleCount <= 1
You are using the wrong syntax: you are using Collection.unique(Closure closure):
allLocales.unique {new ISO3LangComparator()}
You should use Collection.unique(Comparator comparator)
allLocales.unique (new ISO3LangComparator())
So simply use () instead of {}, and your problem is solved.
what Adam said.
or...
allLocales.unique{it.ISO3Language}
and you forget about the comparator

Resources