content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package ru.otus.otuskotlin.coroutines.homework.hard
import okhttp3.OkHttpClient
import okhttp3.Request
object HttpClient : OkHttpClient() {
fun get(uri: String) =
Request.Builder().url(uri).build()
.let {
newCall(it)
}
}
| otus/lessons/m2l1-coroutines/src/test/kotlin/homework/hard/HttpClient.kt | 3884842941 |
package ru.otus.otuskotlin.coroutines.homework.hard
import kotlinx.coroutines.*
import ru.otus.otuskotlin.coroutines.homework.hard.dto.Dictionary
import java.io.File
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.test.Test
class HWHard {
@Test
fun hardHw(): Unit = runBlocking {
val dictionaryApi = DictionaryApi()
val words = FileReader.readFile().split(" ", "\n").toSet()
val dictionaries = findWords(dictionaryApi, words, Locale.EN)
println(dictionaries.count())
dictionaries.filterNotNull().map { dictionary ->
print("For word ${dictionary.word} i found examples: ")
println(
dictionary.meanings
.mapNotNull { definition ->
val r = definition.definitions
.mapNotNull { it.example.takeIf { it?.isNotBlank() == true } }
.takeIf { it.isNotEmpty() }
r
}
.takeIf { it.isNotEmpty() }
)
}
}
private suspend fun findWords(
dictionaryApi: DictionaryApi,
words: Set<String>,
@Suppress("SameParameterValue") locale: Locale
): List<Dictionary?> = coroutineScope {
val list = mutableListOf<Dictionary?>()
words.forEach {
launch(Dispatchers.IO) {
try {
list.add(dictionaryApi.findWord(locale, it))
}
catch (ex: Exception) {
println(ex.message)
}
}
}
list
}
object FileReader {
fun readFile(): String =
File(
this::class.java.classLoader.getResource("words.txt")?.toURI()
?: throw RuntimeException("Can't read file")
).readText()
}
}
| otus/lessons/m2l1-coroutines/src/test/kotlin/homework/hard/HWHard.kt | 644705797 |
package ru.otus.otuskotlin.coroutines.homework.hard
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import okhttp3.Response
import ru.otus.otuskotlin.coroutines.homework.hard.dto.Dictionary
class DictionaryApi(
private val objectMapper: ObjectMapper = jacksonObjectMapper()
) {
fun findWord(locale: Locale, word: String): Dictionary? { // make something with context
val url = "$DICTIONARY_API/${locale.code}/$word"
println("Searching $url")
return getBody(HttpClient.get(url).execute())?.firstOrNull()
}
private fun getBody(response: Response): List<Dictionary>? {
if (!response.isSuccessful) {
return emptyList()
}
return response.body?.let {
objectMapper.readValue(it.string())
}
}
}
| otus/lessons/m2l1-coroutines/src/test/kotlin/homework/hard/DictionaryApi.kt | 3100344166 |
package ru.otus.otuskotlin.coroutines.homework.hard
internal const val DICTIONARY_API = "https://api.dictionaryapi.dev/api/v2/entries"
| otus/lessons/m2l1-coroutines/src/test/kotlin/homework/hard/constants.kt | 3321923094 |
package ru.otus.otuskotlin.coroutines
import kotlinx.coroutines.*
import kotlin.test.Test
class Ex8Exceptions {
@Test
fun invalid() {
try {
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
Integer.parseInt("a")
}
} catch (e: Exception) {
println("CAUGHT!")
}
Thread.sleep(2000)
println("COMPLETED!")
}
@Test
fun invalid2() {
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
try {
launch {
Integer.parseInt("a")
}
} catch (e: Exception) {
println("CAUGHT!")
}
}
Thread.sleep(2000)
println("COMPLETED!")
}
private fun handler(where: String) = CoroutineExceptionHandler { context, exception ->
println("CAUGHT at $where ${context[CoroutineName]}: $exception")
}
@Test
fun handler() {
val scope = CoroutineScope(Dispatchers.Default + handler("top"))
scope.launch(handler("launch")) {
Integer.parseInt("a")
}
Thread.sleep(2000)
println("COMPLETED!")
}
@Test
fun handler2() {
val scope = CoroutineScope(Dispatchers.Default + handler("top"))
scope.launch(CoroutineName("1")) {
launch(handler("child") + CoroutineName("1.1")) {
Integer.parseInt("a")
}
}
Thread.sleep(2000)
println("COMPLETED!")
}
@Test
fun cancel() {
val scope = CoroutineScope(Dispatchers.Default + handler("top"))
scope.launch {
launch { // 3 если сюда добавить handler(), то ничего не изменится
launch {
delay(100) // 1 дочерние отменены
println("cor1")
}
launch {
delay(100)
println("cor2")
}
Integer.parseInt("a")
}
launch { // 2 сиблинг тоже отменен
delay(100)
println("cor3")
}
}
Thread.sleep(2000)
scope.launch {
// 4 scope отменен, в нем больше ничего не запустить
println("No chancel")
}
val scope2 = CoroutineScope(Dispatchers.Default)
scope2.launch { // другой скоуп никак не затронут
println("I am alive")
}
Thread.sleep(500)
println("COMPLETED!")
}
@Test
fun supervisorJob() {
val scope = CoroutineScope(Dispatchers.Default + handler("top") + SupervisorJob())
scope.launch {
launch {
delay(100) // 1 сиблинги отменены
println("cor1")
}
launch {
delay(100)
println("cor2")
}
launch {
delay(50)
Integer.parseInt("a")
}
delay(100)
// 1 сама джоба отменена
println("super")
}
Thread.sleep(2000)
scope.launch {
// 3 жив
println("I am alive")
}
Thread.sleep(500)
println("COMPLETED!")
}
@Test
fun supervisorJob2() {
val scope = CoroutineScope(Dispatchers.Default + handler("top") + SupervisorJob())
scope.launch {// ***
launch {
delay(100)
println("cor1")
}
launch(SupervisorJob()) {
delay(50)
Integer.parseInt("a") // 1 - комментируем
// 1 - ops
println("cor2")
}
delay(100)
println("super")
}
// scope.cancel() // 1 - раскомментируем
Thread.sleep(2000)
println("COMPLETED!")
}
@Test
fun supervisorJob3() {
val scope = CoroutineScope(Dispatchers.Default + handler("top"))
scope.launch {// ***
launch {
delay(100)
println("cor1")
}
launch(SupervisorJob(coroutineContext.job)) {
launch {
delay(10)
Integer.parseInt("a") // 1 - комментируем
}
launch {
delay(50)
// отменится
println("cor2")
}
delay(50)
// отменится
println("cor3")
}
delay(100)
println("super")
}
// scope.cancel() // 1 - раскомментируем
Thread.sleep(2000)
println("COMPLETED!")
}
@Test
fun handler3() {
val scope = CoroutineScope(Dispatchers.Default + handler("top"))
scope.launch(CoroutineName("1")) {
launch(handler("child") + CoroutineName("1.1") + SupervisorJob(coroutineContext.job)) {
Integer.parseInt("a")
}
}
Thread.sleep(2000)
println("COMPLETED!")
}
@Test
fun async1() {
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
launch {
delay(100)
println("cor1")
}
val x = async {
Integer.parseInt("a")
}
delay(100)
println("1")
try {
x.await()
} catch (e: Exception) {
println("CAUGHT!")
}
}
Thread.sleep(2000)
println("COMPLETED!")
}
@Test
fun async2() {
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
launch {
delay(100)
println("cor1")
}
val x = async(SupervisorJob(coroutineContext.job) + handler("async")) {
Integer.parseInt("a")
}
delay(100)
println("1")
try {
x.await()
} catch (e: Exception) {
println("CAUGHT!")
}
}
Thread.sleep(2000)
println("COMPLETED!")
}
}
| otus/lessons/m2l1-coroutines/src/test/kotlin/ex8-Exceptions.kt | 1183243920 |
package ru.otus.otuskotlin.coroutines
import kotlinx.coroutines.*
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext
import kotlin.test.Test
class Ex6Scope {
@Test
fun create1() {
val scope = CoroutineScope(Dispatchers.Main)
println("scope: $scope")
}
@Test
fun create2() {
val scope = CoroutineScope(Dispatchers.Main + Job() + CoroutineName("create2"))
println("scope: $scope")
}
@Test
fun create3() {
val scope = CoroutineScope(SomeData(10, 20))
val data = scope.coroutineContext[SomeData]
println("scope: $scope, $data")
}
private fun CoroutineScope.scopeToString(): String =
"Job = ${coroutineContext[Job]}, Dispatcher = ${coroutineContext[ContinuationInterceptor]}, Data = ${coroutineContext[SomeData]}"
@Test
fun defaults() {
val scope = CoroutineScope(SomeData(10, 20))
scope.launch {
println("Child1: ${scopeToString()}")
}
scope.launch(SomeData(1, 2)) {
println("Child2: ${scopeToString()}")
}
println("This: ${scope.scopeToString()}")
}
data class SomeData(val x: Int, val y: Int) : AbstractCoroutineContextElement(SomeData) {
companion object : CoroutineContext.Key<SomeData>
}
}
| otus/lessons/m2l1-coroutines/src/test/kotlin/ex6-Scope.kt | 1417962132 |
package ru.otus.otuskotlin.coroutines
import kotlinx.coroutines.*
import kotlin.concurrent.thread
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlin.test.Test
class Ex10Dispatchers {
private fun CoroutineScope.createCoro() {
repeat(30) {
launch {
println("coroutine $it, start")
Thread.sleep(500)
println("coroutine $it, end")
}
}
}
@Test
fun default() = runBlocking {
createCoro()
}
@Test
fun io() = runBlocking {
withContext(Dispatchers.IO) { createCoro() }
}
@Test
fun custom() = runBlocking {
// val dispatcher = Executors.newFixedThreadPool(8).asCoroutineDispatcher()
@OptIn(DelicateCoroutinesApi::class)
val dispatcher = newFixedThreadPoolContext(8, "single")
dispatcher.use {
withContext(Job() + dispatcher) { createCoro() }
}
}
@Test
fun unconfined(): Unit = runBlocking(Dispatchers.Default) {
withContext(Dispatchers.Unconfined) {
launch() {
println("start coroutine ${Thread.currentThread().name}")
suspendCoroutine {
println("suspend function, start")
thread {
println("suspend function, background work")
Thread.sleep(1000)
it.resume("Data!")
}
}
println("end coroutine")
}
}
}
}
| otus/lessons/m2l1-coroutines/src/test/kotlin/ex9-Dispatchers.kt | 3261080345 |
package ru.otus.otuskotlin.coroutines
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlin.test.Test
import kotlin.time.measureTime
class Ex7Async {
@Test
fun async1(): Unit = runBlocking {// ***
val res1 = async {
delay(1000)
println("async1")
42
}
val res2 = async {
delay(500)
println("async2")
42
}
println("completed: ${res1.await()}, ${res2.await()}")
}
@Test
fun asyncLazy(): Unit = runBlocking {// ***
val res1 = async(start = CoroutineStart.LAZY) {
println("async1 stated")
delay(1000)
println("async1")
42
}
val res2 = async(start = CoroutineStart.LAZY) {
println("async2 stated")
delay(500)
println("async2")
66
}
// res1.start()
// res2.start()
delay(1000)
println("we are here")
val dur = measureTime {
println("completed: ${res1.await()}, ${res2.await()}")
}
println("Duration: $dur")
}
}
| otus/lessons/m2l1-coroutines/src/test/kotlin/ex7-Async.kt | 1985634062 |
package ru.otus.otuskotlin.oop
import kotlin.test.Test
import kotlin.test.assertEquals
class GenericTest {
@Test
fun invariant() {
assertEquals(3, (IntSome(1) + IntSome(2)).value)
}
@Test
fun covariant() {
assertEquals(3, CovariantCls().parse("3"))
}
@Test
fun contravariant() {
assertEquals("3", ContravariantCls().toStr(3))
}
private interface ISome<T: ISome<T>> {
operator fun plus(other: T): T
}
private class IntSome(val value: Int): ISome<IntSome> {
override fun plus(other: IntSome): IntSome = IntSome(value + other.value)
}
private interface IParse<out T> {
fun parse(str: String): T
}
private class CovariantCls: IParse<Int> {
override fun parse(str: String): Int = str.toInt()
}
private interface IToString<in T> {
fun toStr(i: T): String
}
private class ContravariantCls: IToString<Int> {
override fun toStr(i: Int): String = i.toString()
}
}
| otus/lessons/m1l4-oop/src/test/kotlin/ex7-GenericTest.kt | 1753532803 |
package ru.otus.otuskotlin.oop
import org.junit.Test
class ObjectsExample {
companion object {
init {
println("companion inited") // init when ObjectsExample will be loaded
}
fun doSmth() {
println("companion object")
}
}
object A {
init {
println("A inited") // lazy init whet getting A first time
}
fun doSmth() {
println("object A")
}
}
}
class ObjectsTest {
@Test
fun test() {
ObjectsExample()
ObjectsExample.doSmth()
ObjectsExample.A.doSmth()
ObjectsExample.A.doSmth()
}
}
| otus/lessons/m1l4-oop/src/test/kotlin/ex2-objectsTest.kt | 1157333106 |
package ru.otus.otuskotlin.oop
import org.junit.Test
import kotlin.test.assertEquals
internal class ClassDelegationTest {
@Test
fun delegate() {
val base = MyClass()
val delegate = MyDelegate(base)
println("Calling base")
assertEquals("x", base.x())
assertEquals("y", base.y())
println("Calling delegate")
assertEquals("delegate for (x)", delegate.x())
assertEquals("y", delegate.y())
}
interface IDelegate {
fun x(): String
fun y(): String
}
class MyClass() : IDelegate {
override fun x(): String {
println("MyClass.x()")
return "x"
}
override fun y(): String {
println("MyClass.x()")
return "y"
}
}
class MyDelegate(
private val del: IDelegate
) : IDelegate by del {
override fun x(): String {
println("Calling x")
val str = del.x()
println("Calling x done")
return "delegate for ($str)"
}
}
}
| otus/lessons/m1l4-oop/src/test/kotlin/ex6-classDelegationTest.kt | 2102148201 |
package ru.otus.otuskotlin.oop
import kotlin.test.*
interface Figure {
fun area(): Int
}
open class Rectangle(val width: Int, val height: Int) : Figure {
override fun area(): Int = width * height;
override fun toString(): String = "Rectangle(${width}x${height})"
override fun equals(other: Any?): Boolean {
if (other !is Rectangle) {
return false
}
return width == other.width && height == other.height
}
override fun hashCode(): Int {
return width * height
}
}
fun diffArea(first: Figure, second: Figure) = first.area() - second.area()
class Square(width: Int): Rectangle(width, width), Figure
class Hw1KtTest {
// task 1 - make a Rectangle class that will have width and height
// as well as the area calculation method - area()
// the test below should pass - uncomment the code in it
@Test
fun rectangleArea() {
val r = Rectangle(10, 20)
assertEquals(200, r.area())
assertEquals(10, r.width)
assertEquals(20, r.height)
}
// task 2 - make the Rectangle.toString() method
// the test below should pass - uncomment the code in it
@Test
fun rectangleToString() {
val r = Rectangle(10, 20)
assertEquals("Rectangle(10x20)", r.toString())
}
// task 3 - make Rectangle.equals() and Rectangle.hashCode() methods
// the test below should pass - uncomment the code in it
@Test
fun rectangleEquals() {
val a = Rectangle(10, 20)
val b = Rectangle(10, 20)
val c = Rectangle(20, 10)
assertEquals(a, b)
assertEquals(a.hashCode(), b.hashCode())
assertFalse (a === b)
assertNotEquals(a, c)
}
// task 4 - make the Square class
// the test below should pass - uncomment the code in it
@Test
fun squareEquals() {
val a = Square(10)
val b = Square(10)
val c = Square(20)
assertEquals(a, b)
assertEquals(a.hashCode(), b.hashCode())
assertFalse (a === b)
assertNotEquals(a, c)
println(a)
}
// task 5 - make the Figure interface with the area() method, inherit Rectangle and Square from it
// the test below should pass - uncomment the code in it
@Test
fun figureArea() {
var f : Figure = Rectangle(10, 20)
assertEquals(f.area(), 200)
f = Square(10)
assertEquals(f.area(), 100)
}
// task 6 - make the diffArea(a, b) method
// the test below should pass - uncomment the code in it
@Test
fun diffArea() {
val a = Rectangle(10, 20)
val b = Square(10)
assertEquals(diffArea(a, b), 100)
}
}
| otus/lessons/m1l4-oop/src/test/kotlin/hw1-KtTest.kt | 2515354539 |
package ru.otus.otuskotlin.oop
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
enum class HighLowEnum {
LOW,
HIGH
}
enum class HighLowWithData(val level: Int, val description: String) {
LOW(10, "low level"),
HIGH(20, "high level")
}
enum class FooBarEnum : Iterable<FooBarEnum> {
FOO {
override fun doSmth() {
println("do foo")
}
},
BAR {
override fun doSmth() {
println("do bar")
}
};
abstract fun doSmth()
override fun iterator(): Iterator<FooBarEnum> = listOf(FOO, BAR).iterator()
}
class EnumsTest {
@Test
fun enum() {
var e = HighLowEnum.LOW
println(e)
e = HighLowEnum.valueOf("HIGH")
println(e)
println(e.ordinal)
assertEquals(1, e.ordinal)
println(HighLowEnum.entries.joinToString())
}
@Test
fun enumWithData() {
var e = HighLowWithData.LOW
println(e)
e = HighLowWithData.valueOf("HIGH")
println(e)
println(e.ordinal)
assertEquals(1, e.ordinal)
assertEquals(20, e.level)
println(HighLowEnum.entries.joinToString())
}
@Test
fun interfacedEnums() {
assertEquals(listOf(FooBarEnum.FOO, FooBarEnum.BAR), FooBarEnum.BAR.iterator().asSequence().toList())
assertEquals(listOf(FooBarEnum.FOO, FooBarEnum.BAR), FooBarEnum.FOO.iterator().asSequence().toList())
}
@Test
fun enumFailures() {
assertFails {
// Здесь будет исключение в рантайме
HighLowEnum.valueOf("high")
}
val res = runCatching { HighLowEnum.valueOf("high") }
.getOrDefault(HighLowEnum.HIGH)
assertEquals(HighLowEnum.HIGH, res)
}
}
| otus/lessons/m1l4-oop/src/test/kotlin/ex3-enumsTest.kt | 2806546573 |
package ru.otus.otuskotlin.oop
import org.junit.Test
import kotlin.test.assertEquals
sealed interface Base
data object ChildA : Base
class ChildB : Base {
override fun equals(other: Any?): Boolean {
return this === other
}
override fun hashCode(): Int {
return System.identityHashCode(this)
}
}
// Uncomment this to get compilation error
//class ChildC : Base
class SealedTest {
@Test
fun test() {
val obj: Base = ChildA
val result = when (obj) {
is ChildA -> "a"
is ChildB -> "b"
}
println(result)
assertEquals(result, "a")
}
}
| otus/lessons/m1l4-oop/src/test/kotlin/ex4-sealedClassesTest.kt | 550629167 |
package ru.otus.otuskotlin.oop
import org.junit.Test
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
import kotlin.test.assertEquals
internal class PropDelegationTest {
@Test
fun roDelegate() {
val example = DelegateExample()
println(example.constVal)
assertEquals(example.constVal, 100501)
}
@Test
fun rwDelegate() {
val example = DelegateExample()
example.varVal = 15
println(example.varVal)
assertEquals(example.varVal, 15)
}
@Test
fun lazyDelegate() {
val example = DelegateExample()
println(example.lazyVal)
assertEquals(example.lazyVal, 42)
}
private class ConstValue(private val value: Int) : ReadOnlyProperty<Any?, Int> {
override fun getValue(thisRef: Any?, property: KProperty<*>): Int {
return value
}
}
private class VarValue(private var value: Int) : ReadWriteProperty<Any?, Int> {
override fun getValue(thisRef: Any?, property: KProperty<*>): Int {
return value
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
this.value = value
}
}
private class DelegateExample {
val constVal by ConstValue(100501)
var varVal by VarValue(100501)
val lazyVal by lazy {
println("calculate...")
42
}
}
}
| otus/lessons/m1l4-oop/src/test/kotlin/ex5-propDelegationTest.kt | 3342861725 |
package ru.otus.otuskotlin.oop
import org.junit.Test
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
import kotlin.test.assertEquals
internal class DelegationKtTest {
@Test
fun test() {
val example = DelegateExample()
println(example.constVal)
assertEquals(example.constVal, 100501)
println(example.lazyVal)
assertEquals(example.lazyVal, 42)
}
private class ConstValue(private val value: Int) : ReadWriteProperty<Any?, Int> {
override fun getValue(thisRef: Any?, property: KProperty<*>): Int {
return value
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
TODO("Not yet implemented")
}
}
private class DelegateExample {
val constVal by ConstValue(100501)
val lazyVal by lazy {
println("calculate...")
42
}
}
}
| otus/lessons/m1l4-oop/src/test/kotlin/ex5-delegationTest.kt | 3884717978 |
package ru.otus.otuskotlin.oop
import java.math.BigDecimal
import java.text.NumberFormat
import java.util.*
import kotlin.test.Test
import kotlin.test.assertEquals
class Cash(
val amount: BigDecimal,
private val currency: Currency
) {
constructor(
amount: String,
currency: Currency
) : this(BigDecimal(amount), currency)
fun format(locale: Locale): String {
val formatter = NumberFormat.getCurrencyInstance(locale)
formatter.currency = currency
return formatter.format(amount)
}
operator fun minus(other: Cash): Cash {
require(currency == other.currency) {
"Summand should be of the same currency"
}
return Cash(amount - other.amount, currency)
}
companion object {
val NONE = Cash(BigDecimal.ZERO, Currency.getInstance("RUR"))
}
}
abstract class BaseClass() {
}
interface IClass {
}
@Suppress("unused")
class InheritedClass(
arg: String,
val prop: String = arg,
) : IClass, BaseClass() {
init {
println("Init in constructor with $arg")
}
fun some() {
this.prop
}
}
class CashTest {
@Test
fun test() {
val a = Cash("10", Currency.getInstance("USD"))
val b = Cash("20", Currency.getInstance("USD"))
val c = b - a
//c.amount = BigDecimal.TEN; // ERROR!
println(c.amount)
println(a)
println(c.format(Locale.FRANCE))
assertEquals(c.amount, BigDecimal.TEN)
@Suppress("RedundantCompanionReference")
assertEquals(Cash.Companion.NONE, Cash.NONE)
}
}
| otus/lessons/m1l4-oop/src/test/kotlin/ex1-cashTest.kt | 3699703544 |
import kotlin.reflect.KClass
import kotlin.test.Test
import kotlin.test.assertContains
import kotlin.test.assertEquals
class GenericTest {
@Test
fun genericTest() {
assertEquals("String", variant2<String>())
}
@Test
fun elementAsListTest() {
assertContains(elementAsList(12), 12)
}
/*
fun <T> willNotCompile(variable: T) {
println(T::class.java)
}
*/
fun variant1(klass: KClass<*>): String = klass.simpleName ?: "(unknown)"
inline fun <reified T> variant2() = variant1(T::class)
fun <T> elementAsList(el: T): List<T> = listOf(el)
}
| otus/lessons/m1l3-func/src/test/kotlin/ex3-generic.kt | 4192987394 |
import junit.framework.TestCase.assertFalse
import kotlin.test.Test
import kotlin.test.assertEquals
class IteratorTest {
private val list = mutableListOf("string", "1", "2")
@Test
fun immutable() {
val iter: Iterator<String> = list.iterator()
// iter.remove() // Not allowed
assertEquals("string", iter.next())
}
@Test
fun mutable() {
val mutIter: MutableIterator<String> = list.listIterator()
mutIter.next()
mutIter.remove()
assertEquals("1", mutIter.next())
assertFalse(list.contains("string"))
}
}
| otus/lessons/m1l3-func/src/test/kotlin/ex5-iterator.kt | 261407343 |
import kotlin.test.Test
import kotlin.test.assertContains
import kotlin.test.assertEquals
class CollectionsTest {
private val list = mutableListOf("one", "one", "two")
private val set = mutableSetOf("one", "one", "two")
private val map = mapOf(
"one" to "1a",
"one" to "1",
"two" to "2",
"three" to "3",
)
@Test
fun list() {
assertEquals(listOf("one", "one", "two"), list)
assertContains(list, "one")
}
@Test
fun set() {
assertEquals(setOf("one", "two"), set)
assertContains(set, "one")
}
@Test
fun map() {
assertEquals(setOf("one", "two", "three"), map.keys)
assertContains(map, "two")
}
}
| otus/lessons/m1l3-func/src/test/kotlin/ex6-collections.kt | 1304126067 |
import kotlin.test.Test
import kotlin.test.assertEquals
class FunctionsTest {
@Test
fun simpleFun() {
val param = 0.1
val expected = param*param
assertEquals(expected, simple(param))
}
@Test
fun defaultArgs() {
assertEquals("str: 1, 12", defaultArgs(1))
}
@Test
fun namedArgs() {
val res = defaultArgs(s = "string", x = 8, y = 7)
assertEquals("string: 8, 7", res)
}
@Test
fun extensions() {
assertEquals("My String is string", "string".myExtenstion())
}
}
private fun simple(x: Double): Double = x*x
private fun defaultArgs(x: Int, y: Int = 12, s: String = "str") = "$s: $x, $y"
private fun String.myExtenstion() = "My String is $this"
| otus/lessons/m1l3-func/src/test/kotlin/ex1-functions.kt | 2150075639 |
import kotlin.test.Test
import kotlin.test.assertEquals
class InfixTest {
@Test
fun test() {
assertEquals("str: n is 5", "str" myInfix 5)
}
private infix fun String.myInfix(n: Int) = "$this: n is $n"
}
| otus/lessons/m1l3-func/src/test/kotlin/ex4-infix.kt | 2887548054 |
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
class TypesTest {
@Test
fun resFun() {
unitRes()
assertEquals(220, intRes())
}
@Test
fun nothingFun() {
assertFails {
nothingRes()
}
assertEquals(1, withNothing(12))
assertFails {
withNothing(13)
}
}
}
private fun unitRes(): Unit = println("Result is unit")
private fun intRes(): Int = 22 * 10
private fun nothingRes(): Nothing = throw Exception("My Exception")
private fun withNothing(i: Int) = when(i) {
12 -> 1
else -> nothingRes()
}
| otus/lessons/m1l3-func/src/test/kotlin/ex2-types.kt | 4256153690 |
import junit.framework.TestCase.assertFalse
import junit.framework.TestCase.assertTrue
import kotlin.test.Test
import kotlin.test.assertContains
import kotlin.test.assertEquals
class RangesTest {
@Test
fun inclusive() {
val range: IntRange = (1..5)
assertContains(range, 1)
assertContains(range, 5)
}
@Test
fun exclusive() {
val prog: LongProgression = (1L until 5L)
assertContains(prog, 1L)
assertFalse(prog.contains(5))
}
@Test
fun exclusive1() {
val prog: LongProgression = (1L..<5L)
assertContains(prog, 1L)
assertFalse(prog.contains(5))
}
@Test
fun countDown() {
val prog: IntProgression = (5 downTo 1)
assertEquals(5, prog.first())
assertEquals(1, prog.last())
}
@Test
fun step() {
val prog: IntProgression = (1..5 step 2)
assertTrue(prog.contains(1))
assertFalse(prog.contains(2))
}
@Test
fun iterate() {
for(i in 1..3) {
assertTrue(i in (1..3))
}
}
@Test
fun iterate1() {
(1..8 step 2). forEach {
assertTrue(it in (1..8))
}
}
}
| otus/lessons/m1l3-func/src/test/kotlin/ex7-ranges.kt | 2318503512 |
import kotlin.test.Test
import kotlin.test.assertEquals
/*
* Реализовать функцию, которая преобразует список словарей строк в ФИО
* Функцию сделать с использованием разных функций для разного числа составляющих имени
* Итого, должно получиться 4 функции
*
* Для успешного решения задания, требуется раскомментировать тест, тест должен выполняться успешно
* */
class HomeWork1Test {
@Test
fun mapListToNamesTest() {
val input = listOf(
mapOf(
"first" to "Иван",
"middle" to "Васильевич",
"last" to "Рюрикович",
),
mapOf(
"first" to "Петька",
),
mapOf(
"first" to "Сергей",
"last" to "Королев",
),
)
val expected = listOf(
"Рюрикович Иван Васильевич",
"Петька",
"Королев Сергей",
)
val res = mapListToNames(input)
assertEquals(expected, res)
}
private fun mapListToNames(input: List<Map<String, String>>): List<String> {
return input.map {map ->
val first = map["first"] ?: ""
val middle = map["middle"] ?: ""
val last = map["last"] ?: ""
when {
first.isNotEmpty() && middle.isNotEmpty() && last.isNotEmpty() -> "$last $first $middle"
first.isNotEmpty() && last.isNotEmpty() -> "$last $first"
else -> first
}
}
}
}
| otus/lessons/m1l3-func/src/test/kotlin/hw1.kt | 1263150918 |
import kotlin.test.Test
import kotlin.test.assertEquals
class FirstTest {
@Test
fun firstTest() {
assertEquals(3, 1 + 2)
}
} | otus/lessons/m1l1-first/src/test/kotlin/FirstTest.kt | 4246663721 |
package com.otus.otuskotlin.marketplace
fun main() {
println("Hello World!")
} | otus/lessons/m1l1-first/src/main/kotlin/Main.kt | 311601728 |
import org.junit.Test
import kotlin.test.assertIs
class TypesTest {
@Test
fun declare() {
val b: Byte = 1
assertIs<Byte>(b)
assertIs<Int>(1)
val b2: Byte = 1 + 2 // WARNING
assertIs<Byte>(b2)
assertIs<Int>(1 + 2)
val b3 = 2.toByte()
assertIs<Byte>(b3)
//val ub: UByte = 1 // ERROR
val ub2: UByte = 1U
assertIs<UByte>(ub2)
val l = 1L
assertIs<Long>(l)
val f = 1.2f
assertIs<Float>(f)
// val f2 : Float = 1.2 // ERROR
val d = 1.2
assertIs<Double>(d)
}
@Test
fun conversions() {
val a = 1
//val b: Long = a // ERROR
val b: Long = a.toLong()
assertIs<Long>(b)
val f: Float = 1.0f
assertIs<Float>(f)
val d = a * 1.0
assertIs<Double>(d)
val l = a + 2L
assertIs<Long>(l)
// val ui = a + 2U // ERROR
val ui2 = a.toUInt() + 2U
assertIs<UInt>(ui2)
}
}
| otus/lessons/m1l2-basic/src/test/kotlin/ex1-types.kt | 152924811 |
import org.junit.Assert.assertThrows
import org.junit.Test
private var x = 1
class NpeTest {
@Test
fun safety() {
// val error1: String = null // ERROR
var ok: String? = null
when (x) {
1 -> "Hello"
}
// println(ok.length) // ERROR
// val notNull: String = ok // ERROR
val mayBeNull: String? = ok
if (ok != null)
println(ok.length)
ok = "hello"
println(ok.length)
}
private fun someCheck(v: String?) = v != null
@Test
fun operators() {
var ok: String? = null
println(ok?.length?.toLong())
println(ok?.length ?: -1)
assertThrows(NullPointerException::class.java) {
println(ok!!.length) // RUNTIME ERROR
}
if (someCheck(ok))
println(ok!!.length)
}
@Test
fun check() {
var nullable = null
val whatTypeIAm = nullable?.toDouble()
val guessType = whatTypeIAm ?: 4.5
val guessType2 = nullable?.toLong() ?: 5
val guessType3 = guessType?.toInt() ?: 2
}
}
| otus/lessons/m1l2-basic/src/test/kotlin/ex4-npe.kt | 4024830461 |
import org.junit.Test
import kotlin.test.assertEquals
class StringsTest {
@Test
fun strings() {
val string = "Hello, otus!\n"
val elementOfString: Char = string[1] // string.get(1) 'e'
assertEquals('e', elementOfString)
val codeExample = """
val string = "Hello, otus!\n"
val elementOfString: Char = string[1] // string.get(1) 'e'
"""
println("====\n" + codeExample + "\n====")
val codeExample2 = """
val string = "Hello, otus!\n"
val elementOfString: Char = string[1] // string.get(1) 'e'
""".trimIndent()
println(codeExample2)
}
fun f(): String {
for (i in 1 .. 3)
println(i)
return "hello"
}
@Test
fun templates() {
val a = 1
val b = 2
val string = "$a + $b = ${a+b}"
assertEquals("1 + 2 = 3", string)
assertEquals("${"hello, $a"}", "hello, 1")
// не стоит увлекаться :)
val c = "${
when(a) {
1 -> f()
else -> "world"
}
}"
assertEquals(c, "hello")
}
}
| otus/lessons/m1l2-basic/src/test/kotlin/ex3-strings.kt | 2185239213 |
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ArraysTest {
@Test
fun arrays() {
val arrayOfInt = arrayOf(1, 2, 3)
println("Unreadable content: $arrayOfInt")
println(arrayOfInt.contentToString())
val emptyArray = emptyArray<Int>() // arrayOf()
assertTrue(emptyArray.isEmpty())
val arrayCalculated = Array(5) { i -> (i * i) }
println("Computed content: ${arrayCalculated.contentToString()}")
val intArray = intArrayOf(1, 2, 3) // int[]
assertFalse(intArray.isEmpty())
val element = arrayOfInt[2] // 3
val elementByFunction = arrayOfInt.get(2) // 3
assertEquals(element, elementByFunction)
}
}
| otus/lessons/m1l2-basic/src/test/kotlin/ex2-arrays.kt | 263032491 |
import org.junit.Assert.assertThrows
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.fail
private var x = 1
class ExceptionsTest {
@Test
fun throwJvmTest() {
assertThrows(Exception::class.java) {
throw Exception("my exception")
}
}
@Test
fun throwKotlinTest() {
assertFails {
throw Exception("my exception")
}
}
@Test
fun caughtTest() {
try {
throw Exception("caughtTest")
} catch (e: RuntimeException) {
fail("This must be not a Runtime Exception")
} catch (e: Throwable) {
println("Success")
} finally {
println("Final")
}
}
@Test
fun caughtExpressionTest() {
val x = try {
throw Exception("caughtTest")
} catch (e: RuntimeException) {
fail("This must be not a Runtime Exception")
} catch (e: Throwable) {
12
} finally {
println("Final")
}
assertEquals(12, x)
}
/*
* В некоторых случаях можно избежать завала приложения по ошибке.
* В этом примере мы спасаем приложение от Java heap space ошибки
* */
@Test
fun memoryOverflowTest() {
val x = try {
LongArray(2_000_000_000) {
it.toLong()
}
} catch (e: Throwable) {
longArrayOf(1)
}
assertEquals(1, x.size)
}
}
| otus/lessons/m1l2-basic/src/test/kotlin/ex5-exceptions.kt | 129356932 |
package ru.otus.otuskotlin.m1l2
fun main(vararg args: String) {
println("Args: $args")
}
| otus/lessons/m1l2-basic/src/main/kotlin/Main.kt | 4181838518 |
package ru.otus.otuskotlin.flows
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import ru.otus.otuskotlin.flows.homework.*
import kotlin.test.Test
import java.time.Instant
import kotlin.random.Random
/**
* Повышенная сложность.
* Поизучайте различные виды реализации получения данных: flow, блокирующий (flow + Thread.sleep), callback.
* Посмотрите как отражается на производительности реализация.
*/
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class FlowTest {
private fun detectors() : List<Detector> {
val random = Random.Default
val seq = sequence {
while (true) {
yield(random.nextDouble())
}
}
return listOf(
CoroutineDetector("coroutine", seq, 500L),
BlockingDetector("blocking", seq, 800L),
CallbackDetector("callback", seq, 2_000L)
)
}
@Test
fun rawDetectorsData(): Unit = runBlocking {
// сырые данные от датчиков
detectors()
.map { it.samples() }
.merge()
.onEach { println(it) }
.launchIn(this)
delay(2000)
coroutineContext.cancelChildren()
}
@Test
fun oncePerSecondOrLast(): Unit = runBlocking {
// данные от датчиков раз в секунду от каждого (если нового нет, то последнее)
val desiredPeriod = 1000L
detectors()
.map {
it.samples()
.transformLatest { sample ->
//println("Start transformLatest for ${sample.serialNumber}")
emit(sample)
while (true) {
delay(desiredPeriod)
//println("Add old value to flow in transformLatest for = ${sample.serialNumber}")
emit(sample.copy(timestamp = Instant.now()))
}
}
.sample(desiredPeriod)
}
.merge()
.onEach { println(it) }
.launchIn(this)
delay(5_000)
coroutineContext.cancelChildren()
}
@Test
fun launchIn(): Unit = runBlocking {
val desiredPeriod = 1000L
val samples = detectors()
.map {
it.samples()
.transformLatest { sample ->
// println("Start transformLatest for ${sample.serialNumber}")
emit(sample)
while (true) {
delay(desiredPeriod)
// println("Add old value to flow in transformLatest for = ${sample.serialNumber}")
emit(sample.copy(timestamp = Instant.now()))
}
}
.sample(desiredPeriod)
}
.merge()
.shareIn(this, SharingStarted.Lazily)
samples
.rollingMax(compareBy { it.value })
.sample(desiredPeriod)
.onEach { println(it) }
.launchIn(this)
delay(5_000)
coroutineContext.cancelChildren()
}
@Test
fun shareOncePerSecondData(): Unit = runBlocking {
val desiredPeriod = 1000L
val flows = detectors()
.map {
it.samples()
.transformLatest { sample ->
emit(sample)
while (true) {
delay(desiredPeriod)
emit(sample.copy(timestamp = Instant.now()))
}
}
.sample(desiredPeriod)
}
var index = 0
val samples = combineTransform(flows) {
it.forEach { s -> println("$index: value = $s") }
index++
emit(it.maxBy { s -> s.value })
}
.shareIn(this, SharingStarted.Lazily)
samples
.onEach { println(it) }
.launchIn(this)
delay(5_000)
coroutineContext.cancelChildren()
}
}
| otus/lessons/m2l2-flows/src/test/kotlin/ex4-FlowHardExampleTest.kt | 1779574702 |
package ru.otus.otuskotlin.flows
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.flow
import kotlin.test.Test
/**
* Демонстрация квазипараллельной работы flow и корутин по сравнению с последовательностями.
* Обратите внимание на скорость выполнения тестов
* Dispatchers.IO.limitedParallelism(1) обеспечивает штатное и корректное выделение ровного одного потока для
* корутин-контекста.
*/
class FlowVsSequenceTest {
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun sequenceTest(): Unit = runBlocking(Dispatchers.IO.limitedParallelism(1)) {
val simpleSequence = sequence {
for (i in 1..5) {
// delay(1000) // can't use it here
// Thread.sleep блокирует корутину
Thread.sleep(1000)
yield(i)
}
}
launch {
for (k in 1..5) {
println("I'm not blocked $k")
delay(1000)
}
}
simpleSequence.forEach { println(it) }
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun flowTest(): Unit = runBlocking(Dispatchers.IO.limitedParallelism(1)) {
val simpleFlow = flow {
for (i in 1..5) {
delay(1000)
emit(i)
}
}
launch {
for (k in 1..5) {
println("I'm not blocked $k")
delay(1000)
}
}
simpleFlow.collect { println(it) }
println("Flow end")
}
}
| otus/lessons/m2l2-flows/src/test/kotlin/ex3-FlowVsSequenceTest.kt | 1050498964 |
package ru.otus.otuskotlin.flows
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.*
import java.util.*
import kotlin.concurrent.scheduleAtFixedRate
import kotlin.test.Test
import kotlin.test.assertEquals
class FlowOperatorsTest {
/**
* Простейшая цепочка flow
*/
@Test
fun simple(): Unit = runBlocking {
flowOf(1, 2, 3, 4) // билдер
.onEach { println(it) } // операции ...
.map { it + 1 }
.filter { it % 2 == 0 }
.collect { println("Result number $it") } // терминальный оператор
}
/**
* Хелпер-функция для печати текущего потока
*/
private fun <T> Flow<T>.printThreadName(msg: String) =
this.onEach { println("Msg = $msg, thread name = ${Thread.currentThread().name}") }
/**
* Демонстрация переключения корутин-контекста во flow
*/
@OptIn(ExperimentalCoroutinesApi::class, DelicateCoroutinesApi::class)
@Test
fun coroutineContextChange(): Unit = runBlocking {
// Просто создали диспетчера и безопасно положили его в apiDispatcher
newSingleThreadContext("Api-Thread").use { apiDispatcher ->
// еще один...
newSingleThreadContext("Db-Thread").use { dbDispatcher ->
// Контекст переключается в ОБРАТНОМ ПОРЯДКЕ, т.е. СНИЗУ ВВЕРХ
flowOf(10, 20, 30) // apiDispatcher
.filter { it % 2 == 0 } // apiDispatcher
.map {
delay(2000)
it
} // apiDispatcher
.printThreadName("api call") // apiDispatcher
.flowOn(apiDispatcher) // Переключаем контекст выполнения на apiDispatcher
.map { it + 1 } // dbDispatcher
.printThreadName("db call") // dbDispatcher
.flowOn(dbDispatcher) // Переключаем контекст выполнения на dbDispatcher
.printThreadName("last operation") // Default
.onEach { println("On each $it") } // Default
.collect() // Запустится в контексте по умолчанию, т.е. в Dispatchers.Default
}
}
}
/**
* Демонстрация тригеров onStart, onCompletion, catch, onEach
*/
@Test
fun startersStopers(): Unit = runBlocking {
flow {
while (true) {
emit(1)
delay(1000)
emit(2)
delay(1000)
emit(3)
delay(1000)
throw RuntimeException("Custom error!")
}
}
.onStart { println("On start") } // Запустится один раз только вначале
.onCompletion { println(" On completion") } // Запустится один раз только вконце
.catch { println("Catch: ${it.message}") } // Запустится только при генерации исключения
.onEach { println("On each: $it") } // Генерируется для каждого сообщения
.collect { }
}
/**
* Демонстрация буферизации.
* Посмотрите как меняется порядок следования сообщений при применении буфера.
* Буфер можно выставить в 0, либо поставить любое положительное значение.
* Попробуйте поменять тип буфера и посмотрите как изменится поведение. Лучше менять при размере буфера 3.
* Имейте в виду, что инициализация генерации и обработки элемента в цепочке всегда происходит в терминальном
* операторе.
*/
@Test
fun buffering(): Unit = runBlocking {
val timeInit = System.currentTimeMillis()
var sleepIndex = 1 // Счетчик инкрементится в терминальном операторе после большой задержки
var el = 1 // Простой номер сообщения
// flow {
// while (sleepIndex < 5) {
// delay(5)
// println("emitting $sleepIndex ${System.currentTimeMillis() - timeInit}ms")
// emit(el++ to sleepIndex)
// }
// }
flowOf(1, 2, 3, 4, 5)
.onEach { println("Send to flow: $it ${System.currentTimeMillis() - timeInit}ms") }
.buffer(3, BufferOverflow.DROP_LATEST) // Здесь включаем буфер размером 3 элемента
// .buffer(3, BufferOverflow.DROP_OLDEST) // Попробуйте разные варианты типов и размеров буферов
// .buffer(3, BufferOverflow.SUSPEND)
.onEach { println("Processing : $it ${System.currentTimeMillis() - timeInit}ms") }
.collect {
println("Sleep ${System.currentTimeMillis() - timeInit}ms")
sleepIndex++
delay(2_000)
}
}
/**
* Демонстрация реализации кастомного оператора для цепочки.
*/
@Test
fun customOperator(): Unit = runBlocking {
fun <T> Flow<T>.zipWithNext(): Flow<Pair<T, T>> = flow {
var prev: T? = null
collect { el ->
prev?.also { pr -> emit(pr to el) } // Здесь корректная проверка на NULL при использовании var
prev = el
}
}
flowOf(1, 2, 3, 4)
.zipWithNext()
.collect { println(it) }
}
/**
* Терминальный оператор toList.
* Попробуйте другие: collect, toSet, first, single (потребуется изменить билдер)
*/
@Test
fun toListTermination(): Unit = runBlocking {
val list = flow {
emit(1)
delay(100)
emit(2)
delay(100)
}
.onEach { println("$it") }
.toList()
println("List: $list")
}
/**
* Работа с бесконечными билдерами flow
*/
@Test
fun infiniteBuilder(): Unit = runBlocking {
val list = flow {
var index = 0
// здесь бесконечный цикл, не переполнения не будет из-за take
while (true) {
emit(index++)
delay(100)
}
}
.onEach { println("$it") }
.take(10) // Попробуйте поменять аргумент и понаблюдайте за размером результирующего списка
.toList()
println("List: $list")
}
@Test
fun callbackFlow(): Unit = runBlocking {
val fl = callbackFlow {
val timer = Timer()
timer.scheduleAtFixedRate(6L, 1000L) {
trySendBlocking("text")
}
awaitClose { timer.cancel() }
}
fl.take(3).collect {
println("RES: $it")
}
assertEquals(3, fl.take(3).count())
}
}
| otus/lessons/m2l2-flows/src/test/kotlin/ex2-FlowOperatorsTest.kt | 1995337094 |
package ru.otus.otuskotlin.flows.homework
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import java.math.BigDecimal
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* Задание.
* Добавить необходимые фильтры для того, чтоб тесты заработали как надо.
*
* Описание. У нас БД в памяти. В ней нужно найти объект, описанный фильтром SearchFilter.
*/
class Exercise1Filter {
@Test
fun filter() = runBlocking {
val flt = SearchFilter(
title = "шнурки",
type = AdType.DEMAND,
visibilitiesOr = setOf(AdVisibility.OWNER, AdVisibility.GROUP),
priceMin = BigDecimal("10.00"),
)
val res = LIST
.asFlow()
.run { flt.title?.let { t -> this.filter { it.title == t } } ?: this }
.run { flt.type?.let { t -> this.filter { it.type == t } } ?: this }
.run { flt.priceMin?.let { t -> this.filter { it.price >= t }} ?: this }
.run { flt.priceMax?.let { t -> this.filter { it.price <= t }} ?: this }
.run { flt.visibilitiesOr?.let { t -> this.filter { t.contains(it.visibility) } } ?: this }
.toList()
assertEquals(1, res.size)
assertEquals("5", res.first().id)
}
companion object {
data class SearchFilter(
val title: String? = null,
val visibilitiesOr: Set<AdVisibility>? = null,
val priceMin: BigDecimal? = null,
val priceMax: BigDecimal? = null,
val type: AdType? = null,
)
data class Ad(
val id: String,
val title: String,
val visibility: AdVisibility,
val price: BigDecimal,
val type: AdType,
)
enum class AdVisibility { PUBLIC, GROUP, OWNER }
enum class AdType { DEMAND, SUPPLY }
val LIST = listOf(
Ad("1", "носок", AdVisibility.PUBLIC, BigDecimal("22.13"), AdType.SUPPLY),
Ad("2", "носок", AdVisibility.PUBLIC, BigDecimal("22.13"), AdType.DEMAND),
Ad("3", "носок", AdVisibility.PUBLIC, BigDecimal("40.13"), AdType.DEMAND),
Ad("4", "носок", AdVisibility.OWNER, BigDecimal("40.13"), AdType.DEMAND),
Ad("5", "шнурки", AdVisibility.OWNER, BigDecimal("40.13"), AdType.DEMAND),
Ad("6", "шнурки", AdVisibility.OWNER, BigDecimal("40.13"), AdType.SUPPLY),
Ad("7", "шнурки", AdVisibility.GROUP, BigDecimal("40.13"), AdType.DEMAND),
)
}
}
| otus/lessons/m2l2-flows/src/test/kotlin/homework/hw1-Filter.kt | 2989043159 |
package ru.otus.otuskotlin.flows.homework
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.*
import java.time.Instant
import java.util.*
import kotlin.concurrent.schedule
data class Sample(
val serialNumber: String,
val value: Double,
val timestamp: Instant = Instant.now()
)
interface Detector {
fun samples(): Flow<Sample>
}
class CoroutineDetector(
private val serialNumber: String,
private val sampleDistribution: Sequence<Double>,
private val samplePeriod: Long
) : Detector {
override fun samples(): Flow<Sample> =
flow {
val values = sampleDistribution.iterator()
while (true) {
emit(Sample(serialNumber, values.next()))
delay(samplePeriod)
}
}
}
class BlockingDetector(
private val serialNumber: String,
private val sampleDistribution: Sequence<Double>,
private val samplePeriod: Long
) : Detector {
override fun samples(): Flow<Sample> =
flow {
val values = sampleDistribution.iterator()
while (true) {
emit(Sample(serialNumber, values.next()))
Thread.sleep(samplePeriod)
}
}.flowOn(Dispatchers.IO)
}
class CallbackDetector(
private val serialNumber: String,
private val sampleDistribution: Sequence<Double>,
private val samplePeriod: Long
) : Detector {
override fun samples(): Flow<Sample> =
callbackFlow {
val values = sampleDistribution.iterator()
val timer = Timer()
timer.schedule(0L, samplePeriod) {
trySendBlocking(Sample(serialNumber, values.next()))
}
timer.schedule(10_000L) { close() }
awaitClose { timer.cancel() }
}
}
fun <T> Flow<T>.rollingMax(comparator: Comparator<T>): Flow<T> =
runningReduce { max, current -> maxOf(max, current, comparator) }
| otus/lessons/m2l2-flows/src/test/kotlin/homework/FlowClasses.kt | 3742098699 |
package ru.otus.otuskotlin.flows
| otus/lessons/m2l2-flows/src/test/kotlin/package.kt | 1359432074 |
package ru.otus.otuskotlin.flows
import kotlin.test.Test
import kotlin.test.assertEquals
class SequenceTest {
/**
* В коллекции операторы преобразования выполняются преобразования сверху вниз последовательно для всей коллекции
*/
@Test
fun collectionIsNotLazy() {
listOf(1, 2, 3, 4)
.map {
println("map for $it -> ${it*it}")
it to it * it
}
.first {
println("first for ${it.first}")
it.first == 3
}
}
/**
* В последовательности цепочка обработок такая же как в коллекции, но обработки выполнены только необходимые
*/
@Test
fun sequenceIsLazy() {
listOf(1, 2, 3, 4).asSequence()
.map {
println("map for $it -> ${it*it}")
it to it * it
}
.first {
println("first for ${it.first}")
it.first == 3
}
}
/**
* Здесь используется блокирующая задержка на 3 секунды. Никакой параллельной обработки последовательности не дают.
* Вы должны увидеть недостаток, который покрывается в корутинах и в Flow.
*/
@Test
fun blockingCall() {
val sequence = sequenceOf(1, 2, 3)
.map {
println("Make blocking call to API")
Thread.sleep(3000)
it + 1
}
.toList()
println("Sequence: $sequence")
}
/**
* Демонстрация холодного поведения. Последовательность вызывается оба раза с нуля.
*/
@Test
fun coldFeature() {
// Это просто конфигурирование последовательности, ничего не вычисляется в этом месте
val seq = sequence {
var x = 0
for (i in (1..15)) {
x += i
yield(x)
}
}
val s1 = seq.map { it } // не запущено выполнение, результата еще нет
val s2 = seq.map { it * 2 } // тоже
// Здесь seq вызывается оба раза и выполняется с нуля
println("S1: ${s1.toList()}") // терминальный оператор здесь,
println("S2: ${s2.toList()}") // т.е. только здесь запускается выполнение и получение результата
}
@Test
fun generators() {
val seq = sequence {
for(i in 1..10) {
yield(i)
}
}
assertEquals(55, seq.sum())
// Бесконечная последовательность
val seq1 = generateSequence(1) { it + 1}
assertEquals(55, seq1.take(10).sum())
}
}
| otus/lessons/m2l2-flows/src/test/kotlin/ex1-SequenceTest.kt | 3388909709 |
package ru.otus.otuskotlin.flows
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.test.Test
/**
* Deprecated. Каналы более не применяются.
*/
class ChannelTest {
@Test
fun test1(): Unit = runBlocking {
val channel = Channel<Int>()
launch {
for (x in 1..5) channel.send(x * x)
channel.close()
}
for (value in channel) {
println(value)
}
println("Done!")
}
@Test
fun test2(): Unit = runBlocking {
val channel = Channel<Int>()
launch {
for (x in 1..5) channel.send(x * x)
}
launch {
for (x in 10..15) channel.send(x * x)
}
launch {
delay(2000)
channel.close()
}
for (value in channel) {
println(value)
}
}
@Test
fun test3(): Unit = runBlocking {
val channel = Channel<Int>()
launch {
for (x in 1..5) channel.send(x * x)
}
launch {
for (x in 10..15) channel.send(x * x)
}
launch {
delay(2000)
channel.close()
}
launch {
for (value in channel) {
println("First consumer: $value")
}
}
launch {
for (value in channel) {
println("Second consumer: $value")
}
}
}
@Test
fun test4(): Unit = runBlocking {
val channel = Channel<Int>(
capacity = 5,
onBufferOverflow = BufferOverflow.SUSPEND
) {
// never call, because onBufferOverflow = SUSPEND
println("Call for value: $it")
}
launch {
for (x in 1..10) {
val value = x * x
channel.send(value)
println("Send value: $value")
}
}
launch {
delay(11000)
channel.close()
}
launch {
for (value in channel) {
println("Consumer: $value")
delay(1000)
}
}
}
}
| otus/lessons/m2l2-flows/src/test/kotlin/ex6-ChannelTest.kt | 1198554803 |
package ru.otus.otuskotlin.flows
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.test.Test
class FlowSharedTest {
/**
* Пример работы SharedFlow
*/
@Test
fun shared(): Unit = runBlocking {
val shFlow = MutableSharedFlow<String>()
launch { shFlow.collect { println("XX $it") } } // Подписчики сами никогда не завершатся
launch { shFlow.collect { println("YY $it") } }
(1..10).forEach {
delay(100)
shFlow.emit("number $it")
}
coroutineContext.cancelChildren() // Таким образом мы закроем подписчиков
}
/**
* Корректное разнесение функция публикации и получения
*/
@Test
fun collector(): Unit = runBlocking {
val mshFlow = MutableSharedFlow<String>()
val shFlow = mshFlow.asSharedFlow() // Только для подписчиков
val collector: FlowCollector<String> = mshFlow // Только для публикации
launch {
mshFlow.collect {
println("MUT $it")
}
}
launch {
shFlow.collect {
println("IMMUT $it")
}
}
delay(100)
(1..20).forEach {
collector.emit("zz: $it")
}
delay(1000)
coroutineContext.cancelChildren()
}
/**
* Пример конвертации Flow в SharedFlow
*/
@Test
fun otherShared(): Unit = runBlocking {
val coldFlow = flowOf(100, 101, 102, 103, 104, 105).onEach { println("Cold: $it") }
launch { coldFlow.collect() }
launch { coldFlow.collect() }
val hotFlow = flowOf(200, 201, 202, 203, 204, 205)
.onEach { println("Hot: $it") }
.shareIn(this, SharingStarted.Lazily) // Здесь превращаем Flow в SharedFlow
launch { hotFlow.collect() }
launch { hotFlow.collect() }
delay(500)
coroutineContext.cancelChildren()
}
/**
* Работа с состояниями
*/
@Test
fun state(): Unit = runBlocking {
val mshState = MutableStateFlow("state1")
val shState = mshState.asStateFlow()
val collector: FlowCollector<String> = mshState
launch { mshState.collect { println("MUT $it") } }
launch { shState.collect { println("IMMUT $it") } }
launch {
(1..20).forEach {
delay(20)
collector.emit("zz: $it")
}
}
delay(100)
println("FINAL STATE: ${shState.value}") // State реализует value, с помощью которого всегда можем
// получить актуальное состояние
coroutineContext.cancelChildren()
}
}
| otus/lessons/m2l2-flows/src/test/kotlin/ex5-FlowSharedTest.kt | 523417764 |
@file:Suppress("unused")
package ru.otus.otuskotlin.m1l5.builders
import kotlin.test.Test
import kotlin.test.assertEquals
class JavaBuilderTestCase {
@Test
fun `test building java-like breakfast`() {
val breakfast = BreakfastBuilder()
.withEggs(3)
.withBacon(true)
.withTitle("Simple")
.withDrink(Drink.COFFEE)
.build()
assertEquals(3, breakfast.eggs)
assertEquals(true, breakfast.bacon)
assertEquals("Simple", breakfast.title)
assertEquals(Drink.COFFEE, breakfast.drink)
}
private enum class Drink {
WATER,
COFFEE,
TEA,
NONE,
}
private abstract class Meal {
data class Breakfast(
val eggs: Int,
val bacon: Boolean,
val drink: Drink,
val title: String,
) : Meal()
data class Dinner(
val title: String,
) : Meal()
}
private class BreakfastBuilder {
var eggs = 0
var bacon = false
var drink = Drink.NONE
var title = ""
fun withEggs(eggs: Int): BreakfastBuilder {
this.eggs = eggs
return this
}
fun withBacon(bacon: Boolean): BreakfastBuilder {
this.bacon = bacon
return this
}
fun withDrink(drink: Drink): BreakfastBuilder {
this.drink = drink
return this
}
fun withTitle(title: String): BreakfastBuilder {
this.title = title
return this
}
fun build() = Meal.Breakfast(eggs, bacon, drink, title)
}
}
| otus/lessons/m1l5-dsl/src/test/kotlin/builders/JavaBuilderTestCase.kt | 2353643679 |
@file:Suppress("unused")
package ru.otus.otuskotlin.m1l5.builders
import kotlin.test.Test
import kotlin.test.assertEquals
class KotlinBuilderTestCase {
@Test
fun `test building java-like breakfast`() {
val breakfast = breakfast {
eggs = 3 // BreakfastBuilder().eggs = 3
bacon = true
title = "Simple"
drink = Drink.COFFEE
}
assertEquals(3, breakfast.eggs)
assertEquals(true, breakfast.bacon)
assertEquals("Simple", breakfast.title)
assertEquals(Drink.COFFEE, breakfast.drink)
}
enum class Drink {
WATER,
COFFEE,
TEA,
NONE,
}
abstract class Meal {
data class Breakfast(
val eggs: Int,
val bacon: Boolean,
val drink: Drink,
val title: String,
) : Meal()
data class Dinner(
val title: String,
) : Meal()
}
private class KotlinLikeBuilder {
var eggs = 0
var bacon = false
var drink = Drink.NONE
var title = ""
fun build() = Meal.Breakfast(eggs, bacon, drink, title)
}
private fun breakfast(block: KotlinLikeBuilder.() -> Unit): Meal.Breakfast {
val builder = KotlinLikeBuilder()
builder.block()
return builder.build()
}
}
| otus/lessons/m1l5-dsl/src/test/kotlin/builders/KotlinBuilderTestCase.kt | 2901852991 |
package ru.otus.otuskotlin.m1l5
import ru.otus.otuskotlin.m1l5.dsl.buildUser
import ru.otus.otuskotlin.m1l5.dsl.fri
import ru.otus.otuskotlin.m1l5.dsl.mon
import ru.otus.otuskotlin.m1l5.dsl.tomorrow
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class UserTestCase {
@Test
fun `test user`() {
val user = buildUser {
name {
first = "Kirill"
last = "Krylov"
}
contacts {
email = "[email protected]"
phone = "81234567890"
}
actions {
add(Action.UPDATE)
add(Action.ADD)
+Action.DELETE
+Action.READ
}
availability {
mon("11:30")
fri("18:00")
tomorrow("10:00")
}
}
assertTrue(user.id.isNotEmpty())
assertEquals("Kirill", user.firstName)
assertEquals("", user.secondName)
assertEquals("Krylov", user.lastName)
assertEquals("[email protected]", user.email)
assertEquals("81234567890", user.phone)
assertEquals(setOf(Action.UPDATE, Action.ADD, Action.DELETE, Action.READ), user.actions)
assertEquals(3, user.available.size)
}
}
| otus/lessons/m1l5-dsl/src/test/kotlin/03-UserTestCase.kt | 2417241981 |
@file:Suppress("unused")
package ru.otus.otuskotlin.m1l5
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
data class Query(
val from: String
)
@DslMarker
annotation class QueryDsl
fun query(block: SqlSelectBuilder.() -> Unit) = SqlSelectBuilder().apply(block)
@QueryDsl
class SqlSelectBuilder {
private var selectQuery = "*"
private var fromQuery = ""
private var whereQuery = ""
fun from(tableArgs: String) {
fromQuery = tableArgs
}
fun select(vararg selectArgs: String) {
selectQuery = selectArgs.joinToString(", ")
}
fun where(block: WhereBuilder.() -> Unit) {
val ctx = WhereBuilder().apply(block).build()
if (ctx.isNotEmpty()) {
whereQuery = " $ctx"
}
}
private fun validate() {
if (fromQuery.isEmpty()) {
throw Exception("You should pass table")
}
}
fun build(): String {
validate()
return "select $selectQuery from $fromQuery$whereQuery"
}
}
@QueryDsl
class WhereBuilder {
private var whereQuery = ""
infix fun<T> String.eq(arg: T) {
whereQuery = eq(this, arg)
}
infix fun<T> String.nonEq(arg: T) {
whereQuery = nonEq(this, arg)
}
fun or(block: WhereOrQuery.() -> Unit) {
val ctx = WhereOrQuery().apply(block).build()
whereQuery = ctx
}
fun build(): String {
if (whereQuery.isEmpty()) {
return ""
}
return "where $whereQuery"
}
}
@QueryDsl
class WhereOrQuery {
private var whereQuery = mutableListOf<String>()
infix fun<T> String.eq(arg: T) {
whereQuery.add(eq(this, arg))
}
infix fun<T> String.nonEq(arg: T) {
whereQuery.add(nonEq(this, arg))
}
fun build(): String {
if (whereQuery.isEmpty()) {
return ""
}
return whereQuery.joinToString(" or ", "(", ")")
}
}
fun<T> eq(param: String,arg: T): String = when (arg) {
is Int -> "$param = $arg"
is String -> "$param = '$arg'"
null -> "$param is null"
else -> throw Exception("Unsupported type")
}
fun<T> nonEq(param: String, arg: T): String = when (arg) {
is Int -> "$param != $arg"
is String -> "$param != '$arg'"
null -> "$param !is null"
else -> throw Exception("Unsupported type")
}
// Реализуйте dsl для составления sql запроса, чтобы все тесты стали зелеными.
class Hw1Sql {
private fun checkSQL(expected: String, sql: SqlSelectBuilder) {
assertEquals(expected, sql.build())
}
@Test
fun `simple select all from table`() {
val expected = "select * from table"
val real = query {
from("table")
}
checkSQL(expected, real)
}
@Test
fun `check that select can't be used without table`() {
assertFailsWith<Exception> {
query {
select("col_a")
}.build()
}
}
@Test
fun `select certain columns from table`() {
val expected = "select col_a, col_b from table"
val real = query {
select("col_a", "col_b")
from("table")
}
checkSQL(expected, real)
}
@Test
fun `select certain columns from table 1`() {
val expected = "select col_a, col_b from table"
val real = query {
select("col_a", "col_b")
from("table")
}
checkSQL(expected, real)
}
/**
* __eq__ is "equals" function. Must be one of char:
* - for strings - "="
* - for numbers - "="
* - for null - "is"
*/
@Test
fun `select with complex where condition with one condition`() {
val expected = "select * from table where col_a = 'id'"
val real = query {
from("table")
where { "col_a" eq "id" }
}
checkSQL(expected, real)
}
/**
* __nonEq__ is "non equals" function. Must be one of chars:
* - for strings - "!="
* - for numbers - "!="
* - for null - "!is"
*/
@Test
fun `select with complex where condition with two conditions`() {
val expected = "select * from table where col_a != 0"
val real = query {
from("table")
where {
"col_a" nonEq 0
}
}
checkSQL(expected, real)
}
@Test
fun `when 'or' conditions are specified then they are respected`() {
val expected = "select * from table where (col_a = 4 or col_b !is null)"
val real = query {
from("table")
where {
or {
"col_a" eq 4
"col_b" nonEq null
}
}
}
checkSQL(expected, real)
}
}
| otus/lessons/m1l5-dsl/src/test/kotlin/hw1-Sql.kt | 211048658 |
package ru.otus.otuskotlin.m1l5
import kotlin.test.Test
import kotlin.test.assertEquals
class PrimitiveTestCase {
@Test
fun builderLessTest() {
class SomeTest(
val x: Int = 0,
val s: String = "string $x",
)
val inst = SomeTest(5)
assertEquals("string 5", inst.s)
}
}
| otus/lessons/m1l5-dsl/src/test/kotlin/01-PrimitiveTestCase.kt | 2894739603 |
package ru.otus.otuskotlin.m1l5
import kotlin.test.Test
import kotlin.test.assertEquals
class SimpleTestCase {
@Test
fun `minimal test`() {
val s = sout {
1 + 123
}
assertEquals("string 124", s)
}
private fun sout(block: () -> Int?): String {
val result = block()
println(result)
return "string $result"
}
@Test
fun `sout with prefix`() {
soutWithContext {
"${time()}: my line."
}
}
class MyContext {
fun time() = System.currentTimeMillis()
// // Same as:
// fun time(): Long {
// return System.currentTimeMillis()
// }
}
private fun soutWithContext(block: MyContext.() -> Any?) {
val context = MyContext()
val result = block(context)
println(result)
}
@Test
fun `dsl functions`() {
val (key, value) = Pair("key", "value")
assertEquals(key, "key")
assertEquals(value, "value")
val pairNew = "key" to "value"
assertEquals(pairNew.first, "key")
assertEquals(pairNew.second, "value")
val myTimeOld = "12".time("30")
assertEquals(myTimeOld, "12:30")
val myTime = "12" time "30"
assertEquals(myTime, "12:30")
}
private infix fun String.time(value: String): String {
return "$this:$value"
}
}
| otus/lessons/m1l5-dsl/src/test/kotlin/02-SimpleTestCase.kt | 906494486 |
package ru.otus.otuskotlin.m1l5
import java.time.LocalDateTime
data class User(
val id: String,
val firstName: String,
val secondName: String,
val lastName: String,
val phone: String,
val email: String,
val actions: Set<Action>,
val available: List<LocalDateTime>,
)
| otus/lessons/m1l5-dsl/src/main/kotlin/User.kt | 3240315158 |
package ru.otus.otuskotlin.m1l5
enum class Action {
READ,
DELETE,
WRITE,
ADD,
UPDATE,
CREATE
}
| otus/lessons/m1l5-dsl/src/main/kotlin/Action.kt | 1052486986 |
package ru.otus.otuskotlin.m1l5.dsl
import ru.otus.otuskotlin.m1l5.Action
@UserDsl
class ActionsContext {
private val _actions: MutableSet<Action> = mutableSetOf()
fun build(): Set<Action> = _actions.toSet()
fun add(action: Action) = _actions.add(action)
@Suppress("MemberVisibilityCanBePrivate")
fun add(value: String) = add(Action.valueOf(value))
operator fun Action.unaryPlus() = add(this)
operator fun String.unaryPlus() = add(this)
}
| otus/lessons/m1l5-dsl/src/main/kotlin/dsl/ActionsContext.kt | 3344445581 |
package ru.otus.otuskotlin.m1l5.dsl
@UserDsl
class ContactsContext {
var email: String = ""
var phone: String = ""
}
| otus/lessons/m1l5-dsl/src/main/kotlin/dsl/ContactsContext.kt | 4262686263 |
package ru.otus.otuskotlin.m1l5.dsl
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.temporal.TemporalAdjusters
@UserDsl
class AvailabilityContext {
private val _availabilities: MutableList<LocalDateTime> = mutableListOf()
val availabilities: List<LocalDateTime>
get() = _availabilities.toList()
fun add(dateTime: LocalDateTime) {
_availabilities.add(dateTime)
}
fun dayTimeOfWeek(day: DayOfWeek, time: String) {
val dDay = LocalDate.now().with(TemporalAdjusters.next(day))
val dTime = LocalTime.parse(time)
add(LocalDateTime.of(dDay, dTime))
}
}
| otus/lessons/m1l5-dsl/src/main/kotlin/dsl/AvailabilityContext.kt | 4153554831 |
package ru.otus.otuskotlin.m1l5.dsl
import ru.otus.otuskotlin.m1l5.Action
import ru.otus.otuskotlin.m1l5.User
import java.time.LocalDateTime
import java.util.*
@UserDsl
class UserBuilder {
private var id = UUID.randomUUID().toString()
private var firstName = ""
private var secondName = ""
private var lastName = ""
private var phone = ""
private var email = ""
private var actions = emptySet<Action>()
private var available = emptyList<LocalDateTime>()
fun name(block: NameContext.() -> Unit) {
val ctx = NameContext().apply(block)
firstName = ctx.first
secondName = ctx.second
lastName = ctx.last
}
fun contacts(block: ContactsContext.() -> Unit) {
val ctx = ContactsContext().apply(block)
phone = ctx.phone
email = ctx.email
}
fun actions(block: ActionsContext.() -> Unit) {
val ctx = ActionsContext().apply(block)
actions = ctx.build()
}
fun availability(block: AvailabilityContext.() -> Unit) {
val ctx = AvailabilityContext().apply(block)
available = ctx.availabilities
}
fun build() = User(
id = id,
firstName = firstName,
secondName = secondName,
lastName = lastName,
phone = phone,
email = email,
actions = actions,
available = available,
)
}
| otus/lessons/m1l5-dsl/src/main/kotlin/dsl/UserBuilder.kt | 2650311557 |
@file:Suppress("unused")
package ru.otus.otuskotlin.m1l5.dsl
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
fun AvailabilityContext.sun(time: String) = dayTimeOfWeek(DayOfWeek.SUNDAY, time)
fun AvailabilityContext.mon(time: String) = dayTimeOfWeek(DayOfWeek.MONDAY, time)
fun AvailabilityContext.tue(time: String) = dayTimeOfWeek(DayOfWeek.TUESDAY, time)
fun AvailabilityContext.wed(time: String) = dayTimeOfWeek(DayOfWeek.WEDNESDAY, time)
fun AvailabilityContext.thu(time: String) = dayTimeOfWeek(DayOfWeek.THURSDAY, time)
fun AvailabilityContext.fri(time: String) = dayTimeOfWeek(DayOfWeek.FRIDAY, time)
fun AvailabilityContext.sat(time: String) = dayTimeOfWeek(DayOfWeek.SATURDAY, time)
fun AvailabilityContext.tomorrow(time: String) {
val dDay = LocalDate.now().plusDays(1)
val dTime = LocalTime.parse(time)
add(LocalDateTime.of(dDay, dTime))
}
| otus/lessons/m1l5-dsl/src/main/kotlin/dsl/AvailabilityContextExtensions.kt | 1469525335 |
package ru.otus.otuskotlin.m1l5.dsl
@UserDsl
class NameContext {
var first: String = ""
var second: String = ""
var last: String = ""
}
| otus/lessons/m1l5-dsl/src/main/kotlin/dsl/NameContext.kt | 1501828785 |
package ru.otus.otuskotlin.m1l5.dsl
fun buildUser(block: UserBuilder.() -> Unit) = UserBuilder().apply(block).build()
| otus/lessons/m1l5-dsl/src/main/kotlin/dsl/BuildUser.kt | 2971429688 |
package ru.otus.otuskotlin.m1l5.dsl
@DslMarker
annotation class UserDsl
| otus/lessons/m1l5-dsl/src/main/kotlin/dsl/UserDsl.kt | 4120756291 |
package com.otus.otuskotlin.marketplace
fun main() {
println("Hello World!")
} | otus/fastify/fastify-api/src/main/kotlin/Main.kt | 311601728 |
package com.example.strarterandroid
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.strarterandroid", appContext.packageName)
}
} | StrarterAndroid/app/src/androidTest/java/com/example/strarterandroid/ExampleInstrumentedTest.kt | 3166166225 |
package com.example.strarterandroid
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | StrarterAndroid/app/src/test/java/com/example/strarterandroid/ExampleUnitTest.kt | 3112410050 |
package com.example.strarterandroid.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | StrarterAndroid/app/src/main/java/com/example/strarterandroid/ui/theme/Color.kt | 3395562587 |
package com.example.strarterandroid.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun StrarterAndroidTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | StrarterAndroid/app/src/main/java/com/example/strarterandroid/ui/theme/Theme.kt | 4007062376 |
package com.example.strarterandroid.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | StrarterAndroid/app/src/main/java/com/example/strarterandroid/ui/theme/Type.kt | 428821123 |
package com.example.strarterandroid
import android.app.Application
import com.example.strarterandroid.di.appModule
import org.koin.android.ext.koin.androidContext
import org.koin.android.logger.AndroidLogger
import org.koin.core.context.GlobalContext.startKoin
import org.koin.core.logger.Level
class App : Application(){
override fun onCreate() {
super.onCreate()
startKoin {
AndroidLogger(Level.NONE)
androidContext(this@App)
modules(appModule)
}
}
} | StrarterAndroid/app/src/main/java/com/example/strarterandroid/App.kt | 2375120929 |
package com.example.strarterandroid.di
import com.example.strarterandroid.network.ApiCall
import com.example.strarterandroid.network.IMainApi
import com.example.strarterandroid.network.MainApiRepoImp
import com.example.strarterandroid.network.RetrofitHelper
import com.example.strarterandroid.pricentation.MainViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
val appModule = module {
single {
Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(MoshiConverterFactory.create())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build()
.create(ApiCall::class.java)
}
single<IMainApi> {
MainApiRepoImp(get())
}
viewModel {
MainViewModel(get())
}
} | StrarterAndroid/app/src/main/java/com/example/strarterandroid/di/AppModules.kt | 2376788768 |
package com.example.strarterandroid.core
sealed class MainViewState {
// ideal state
object Idle: MainViewState()
// loading state
object Loading: MainViewState()
// success state
data class Success(val data: Any): MainViewState()
// error state
data class Error(val error: String): MainViewState()
} | StrarterAndroid/app/src/main/java/com/example/strarterandroid/core/MainViewState.kt | 3426402302 |
package com.example.strarterandroid.core
sealed class MainIntent {
object callApi: MainIntent()
} | StrarterAndroid/app/src/main/java/com/example/strarterandroid/core/MainIntent.kt | 1205979734 |
package com.example.strarterandroid.network
import com.example.strarterandroid.network.model.PostModel
import io.reactivex.rxjava3.core.Single
import retrofit2.http.GET
interface ApiCall {
@GET("posts/1")
fun callApi() : Single<PostModel>
} | StrarterAndroid/app/src/main/java/com/example/strarterandroid/network/ApiCall.kt | 1651245760 |
package com.example.strarterandroid.network
import com.example.strarterandroid.network.model.PostModel
import io.reactivex.rxjava3.core.Single
interface IMainApi {
fun callApi() : Single<PostModel>
} | StrarterAndroid/app/src/main/java/com/example/strarterandroid/network/IMainApi.kt | 636607466 |
package com.example.strarterandroid.network.model
data class PostModel(
val body: String,
val id: Int,
val title: String,
val userId: Int
) | StrarterAndroid/app/src/main/java/com/example/strarterandroid/network/model/PostModel.kt | 1173374449 |
package com.example.strarterandroid.network
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
object RetrofitHelper {
fun <T> createService(baseUrl: String, client: OkHttpClient, service: Class<T>): T {
return Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(MoshiConverterFactory.create())
.build()
.create(service)
}
} | StrarterAndroid/app/src/main/java/com/example/strarterandroid/network/RetrofitHelper.kt | 604218838 |
package com.example.strarterandroid.network
import com.example.strarterandroid.network.model.PostModel
import io.reactivex.rxjava3.core.Single
import retrofit2.Call
class MainApiRepoImp(
private val apiCall: ApiCall
) : IMainApi {
override fun callApi() : Single<PostModel> {
return apiCall.callApi()
}
} | StrarterAndroid/app/src/main/java/com/example/strarterandroid/network/MainApiRepoImp.kt | 5678062 |
package com.example.strarterandroid.pricentation
import android.annotation.SuppressLint
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.strarterandroid.core.MainIntent
import com.example.strarterandroid.core.MainViewState
import com.example.strarterandroid.network.IMainApi
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
class MainViewModel(
private val mainApiRepoImp: IMainApi
) : ViewModel() {
val intentChannel = Channel<MainIntent>(Channel.UNLIMITED)
private val _viewState = MutableStateFlow<MainViewState>(MainViewState.Idle)
val viewState: StateFlow<MainViewState> get() = _viewState
init {
process()
}
@SuppressLint("CheckResult")
fun callApi() {
mainApiRepoImp.callApi()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
_viewState.value = MainViewState.Success(response)
Log.e("Post Response", "callApi: $response.")
}, { error ->
_viewState.value = MainViewState.Error(error.message.toString())
Log.e("API Error", "Error calling API", error)
})
}
private fun process() {
viewModelScope.launch {
intentChannel.consumeAsFlow().collect {
when (it) {
is MainIntent.callApi -> callApi()
}
}
}
}
} | StrarterAndroid/app/src/main/java/com/example/strarterandroid/pricentation/MainViewModel.kt | 217960073 |
package com.example.strarterandroid.pricentation
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import com.example.strarterandroid.core.MainIntent
import com.example.strarterandroid.core.MainViewState
import com.example.strarterandroid.network.model.PostModel
import com.example.strarterandroid.ui.theme.StrarterAndroidTheme
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
class MainActivity : ComponentActivity() {
private var text = "remmber"
private val mainViewModel: MainViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
StrarterAndroidTheme {
// val viewModel = getViewModel<MainViewModel>()
Render()
Column {
Text(text = text)
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = { send() }) {
Text(text = "Send")
}
}
}
}
}
// MVI pattern
private fun send() {
// send data to the view model by using the intent channel
lifecycleScope.launch {
mainViewModel.intentChannel.send(MainIntent.callApi)
}
}
@Composable
fun Render() {
// will get data here from the view model by using Flow
// why Flow? because it's a stream of data that can be observed and if repeated it will give the same result
LaunchedEffect(Unit) {
mainViewModel.viewState.collect {
text = when (it) {
is MainViewState.Idle -> "Idle"
is MainViewState.Loading -> "Loading"
is MainViewState.Success -> (it.data as PostModel).title
is MainViewState.Error -> it.error
}
}
}
}
}
| StrarterAndroid/app/src/main/java/com/example/strarterandroid/pricentation/MainActivity.kt | 306774793 |
package com.example.buildsrc
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.buildsrc", appContext.packageName)
}
} | StrarterAndroid/buildsrc/src/androidTest/java/com/example/buildsrc/ExampleInstrumentedTest.kt | 2615107132 |
package com.example.buildsrc
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | StrarterAndroid/buildsrc/src/test/java/com/example/buildsrc/ExampleUnitTest.kt | 1750037119 |
package com.example.buildsrc
object Libs {
// add your dependencies here for koin
// koin for DI implementation("io.insert-koin:koin-android:3.4.3") and implementation("io.insert-koin:koin-androidx-compose:3.4.3")
object Koin {
const val koin = "io.insert-koin:koin-android:3.4.3"
const val koinAndroidxCompose = "io.insert-koin:koin-androidx-compose:3.4.3"
}
object ComposeLibs {
const val version = "1.0.5"
const val activity = "androidx.activity:activity-compose:1.4.0"
const val ui = "androidx.compose.ui:ui:$version"
const val material = "androidx.compose.material:material:$version"
const val uiToolingPreview = "androidx.compose.ui:ui-tooling-preview:$version"
private const val navVersion = "2.4.2"
const val navigation = "androidx.navigation:navigation-compose:$navVersion"
//androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
//debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
}
object CoroutinesLibs {
const val coroutinesCore = "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0"
const val coroutinesAndroid = "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0"
}
object Ktor {
const val ktorClientCore = "io.ktor:ktor-client-core:1.6.3"
const val ktorClientAndroid = "io.ktor:ktor-client-android:1.6.3"
const val ktorClientJson = "io.ktor:ktor-client-json:1.6.3"
const val ktorClientLogging = "io.ktor:ktor-client-logging:1.6.3"
const val ktorClientSerialization = "io.ktor:ktor-client-serialization:1.6.3"
const val ktorClientSerializationJvm = "io.ktor:ktor-client-serialization-jvm:1.6.3"
const val ktorClientSerializationNative = "io.ktor:ktor-client-serialization-native:1.6.3"
const val ktorClientMock = "io.ktor:ktor-client-mock:1.6.3"
const val ktorClientOkhttp = "io.ktor:ktor-client-okhttp:1.6.3"
}
}
| StrarterAndroid/buildsrc/src/main/java/com/example/buildsrc/Libs.kt | 2859185410 |
package com.example.buildsrc
object Config {
val baseUrl = BaseUrl
object BaseUrl {
//TODO: move urls to gradle.properties
const val production = "https://jsonplaceholder.typicode.com/"
const val develop = "https://jsonplaceholder.typicode.com/"
const val staging = "https://jsonplaceholder.typicode.com/"
}
} | StrarterAndroid/buildsrc/src/main/java/com/example/buildsrc/Config.kt | 2586814959 |
package controllers
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.*
import persistence.XMLSerializer
import java.io.File
class MenuAPITest {
} | filament-app/src/test/kotlin/controllers/MenuAPITest.kt | 3743254797 |
package controllers
import models.Filament
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.*
import persistence.XMLSerializer
import java.io.File
class FilamentApiTest {
private var eSun: Filament? = null
private var flashForge: Filament? = null
private var ninjaFlex: Filament? = null
private var polyMaker: Filament? = null
private var eryone: Filament? = null
private var populatedFilaments: FilamentApi? = FilamentApi(XMLSerializer(File("filaments.xml")))
private var emptyFilaments: FilamentApi? = FilamentApi(XMLSerializer(File("filaments.xml")))
@BeforeEach
fun setup() {
eSun = Filament(0, "eSun", "PLA+", "Black", 1)
flashForge = Filament(1, "flashForge", "PLA", "Orange", 2)
ninjaFlex = Filament(2, "ninjaFlex", "TPU", "White", 1)
polyMaker = Filament(3, "polyMaker", "ABS", "Brown", 1)
eryone = Filament(4, "eryone", "PETG", "Blue", 1)
//adding 5 Filament to the filaments api
populatedFilaments!!.add(eSun!!)
populatedFilaments!!.add(flashForge!!)
populatedFilaments!!.add(ninjaFlex!!)
populatedFilaments!!.add(polyMaker!!)
populatedFilaments!!.add(eryone!!)
}
@AfterEach
fun tearDown() {
eSun = null
flashForge = null
ninjaFlex = null
polyMaker = null
eryone = null
populatedFilaments = null
emptyFilaments = null
}
@Nested
inner class AddFilaments {
@Test
fun `adding a filament to a populated list adds to ArrayList`() {
val newFilament = Filament(0, "creality", "PLA", "Purple", 3)
assertEquals(5, populatedFilaments!!.numberOfFilaments())
assertTrue(populatedFilaments!!.add(newFilament))
assertEquals(6, populatedFilaments!!.numberOfFilaments())
assertEquals(newFilament, populatedFilaments!!.findFilament(populatedFilaments!!.numberOfFilaments() - 1))
}
@Test
fun `adding a Filament to an empty list adds to ArrayList`() {
val newFilament = Filament(0, "sunlu", "ASA", "Green", 1)
assertEquals(0, emptyFilaments!!.numberOfFilaments())
assertTrue(emptyFilaments!!.add(newFilament))
assertEquals(1, emptyFilaments!!.numberOfFilaments())
assertEquals(newFilament, emptyFilaments!!.findFilament(emptyFilaments!!.numberOfFilaments() - 1))
}
}
@Nested
inner class ListFilaments {
@Test
fun `listAllFilaments returns No Filaments Stored message when ArrayList is empty`() {
assertEquals(0, emptyFilaments!!.numberOfFilaments())
assertTrue(emptyFilaments!!.listAllFilaments().contains("no filaments stored"))
}
@Test
fun `listAllFilaments returns filaments when ArrayList has filaments stored`() {
assertEquals(5, populatedFilaments!!.numberOfFilaments())
val filamentsString = populatedFilaments!!.listAllFilaments()
assertTrue(filamentsString.contains("eSun"))
assertTrue(filamentsString.contains("flashForge"))
assertTrue(filamentsString.contains("ninjaFlex"))
assertTrue(filamentsString.contains("polyMaker"))
assertTrue(filamentsString.contains("Eryone"))
}
}
//@Nested
//inner class DeleteFilaments {
// @Test
//fun `deleting a Filament that does not exist, returns null`() {
// assertNull(emptyFilaments!!.delete(0))
//assertNull(populatedFilaments!!.delete(-1))
//assertNull(populatedFilaments!!.delete(5))
//}
//@Test
//fun `deleting a Filament that exists deletes and returns deleted object`() {
// assertEquals(5, populatedFilaments!!.numberOfFilaments())
// assertEquals(eryone, populatedFilaments!!.deleteFilament(4))
// assertEquals(4, populatedFilaments!!.numberOfFilaments())
// assertEquals(eSun, populatedFilaments!!.deleteFilament(0))
// assertEquals(3, populatedFilaments!!.numberOfFilaments())
// }
// }
@Nested
inner class UpdateFilaments {
@Test
fun `updating a filament that does not exist returns false`() {
assertFalse(populatedFilaments!!.update(6, Filament(6, "colorFabb", "Nylon", "Jade Green", 3)))
assertFalse(populatedFilaments!!.update(-1, Filament(-1, "Hatchbox", "Flex", "Red", 1)))
assertFalse(emptyFilaments!!.update(0, Filament(0, "MatterHackers", "PVA", "Cyan", 2)))
}
@Test
fun `updating a filament that exists returns true and updates`() {
//check filament 5 exists and check the contents
assertEquals(eryone, populatedFilaments!!.findFilament(4))
assertEquals("eryone", populatedFilaments!!.findFilament(4)!!.filamentBrand)
assertEquals("ABS", populatedFilaments!!.findFilament(3)!!.filamentType)
assertEquals("Blue", populatedFilaments!!.findFilament(4)!!.filamentColor)
//update filament 5 with new information and ensure contents updated successfully
assertTrue(populatedFilaments!!.update(4, Filament(4, "RepRap", "TPU", "Blue", 1)))
assertEquals("RepRap", populatedFilaments!!.findFilament(4)!!.filamentBrand)
assertEquals("TPU", populatedFilaments!!.findFilament(2)!!.filamentType)
assertEquals("Blue", populatedFilaments!!.findFilament(4)!!.filamentColor)
}
}
@Nested
inner class SearchBrands {
@Test
fun `search filaments by Brand returns no brands when no brands with that brand exist`() {
//Searching a populated collection for a Brand that doesn't exist.
assertEquals(5, populatedFilaments!!.numberOfFilaments())
val searchResults = populatedFilaments!!.searchFilamentsByBrand("no results expected")
assertTrue(searchResults.isEmpty())
//Searching an empty collection
assertEquals(0, emptyFilaments!!.numberOfFilaments())
assertTrue(emptyFilaments!!.searchFilamentsByBrand("").isEmpty())
}
}
@Nested
inner class SearchType {
@Test
fun `search filaments by Type returns no types when no brands with that type exist`() {
//Searching a populated collection for a Type that doesn't exist.
assertEquals(5, populatedFilaments!!.numberOfFilaments())
val searchResults = populatedFilaments!!.searchFilamentsByBrand("no results expected")
assertTrue(searchResults.isEmpty())
//Searching an empty collection
assertEquals(0, emptyFilaments!!.numberOfFilaments())
assertTrue(emptyFilaments!!.searchFilamentsByBrand("").isEmpty())
}
}
//@Test
//fun `search filament by brand returns filaments when filaments with that brand exist`() {
//assertEquals(5, populatedFilaments!!.numberOfFilaments())
//Searching a populated collection for a brand that exists (case matches exactly)
//var searchResults = populatedFilaments!!.searchFilamentsByBrand("ninjaFlex")
//assertTrue(searchResults.contains("ninjaFlex"))
//assertFalse(searchResults.contains("poyMaker"))
//Searching a populated collection for a partial brand that exists (case matches exactly)
//searchResults = populatedFilaments!!.searchFilamentsByBrand("Flex")
//assertTrue(searchResults.contains("ninjaFlex"))
//assertTrue(searchResults.contains("shogunFlex"))
//assertFalse(searchResults.contains("eryone"))
//Searching a populated collection for a partial title that exists (case doesn't match)
//searchResults = populatedFilaments!!.searchFilamentsByBrand("lxf")
//assertTrue(searchResults.contains("ninjaFlex"))
//assertTrue(searchResults.contains("poyMaker"))
//assertFalse(searchResults.contains("Eryone"))
}
| filament-app/src/test/kotlin/controllers/FilamentApiTest.kt | 1756887235 |
package controllers
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.*
import persistence.XMLSerializer
import java.io.File
class CatalogueAPITest {
} | filament-app/src/test/kotlin/controllers/CatalogueAPITest.kt | 2068997771 |
package utils
class MenuColorManager {
var colorChoice: String = "bright yellow" // Default color
fun changeColor(newColor: String) {
// Implement logic to change and store the new menu color
colorChoice = newColor
}
fun getColoredMenu(menuText: String): String {
return when (colorChoice) {
"red" -> "\u001B[31m$menuText\u001B[0m" // Red color
"blue" -> "\u001B[34m$menuText\u001B[0m" // Blue color
"green" -> "\u001B[32m$menuText\u001B[0m" // Green color
"yellow" -> "\u001B[33m$menuText\u001B[0m" // Yellow color
"magenta" -> "\u001B[35m$menuText\u001B[0m" // Magenta Color
"cyan" -> "\u001B[36m$menuText\u001B[0m" // Cyan Color
"black" -> "\u001B[30m$menuText\u001B[0m" // Black Color
//bright colors
"bright red" -> "\u001B[91m$menuText\u001B[0m" // Bright Red Color
"bright blue" -> "\u001B[94m$menuText\u001B[0m" // Bright Blue Color
"bright green" -> "\u001B[92m$menuText\u001B[0m" // Bright Green Color
"bright yellow" -> "\u001B[93m$menuText\u001B[0m" // Bright Yellow Color
"bright magenta" -> "\u001B[95m$menuText\u001B[0m" // Bright Magenta Color
"bright cyan" -> "\u001B[96m$menuText\u001B[0m" // Bright Cyan Color
"grey"-> "\u001B[90m$menuText\u001B[0m" // Grey Color
"white" -> "\u001B[97m$menuText\u001B[0m" // White color
else -> menuText // Default color
}
}
} | filament-app/src/main/kotlin/utils/ColorManager.kt | 389184869 |
package utils
import java.lang.NumberFormatException
import java.util.Scanner
/**
* This class provides methods for the robust handling of I/O using Scanner.
* It creates a new Scanner object for each read from the user, thereby eliminating the Scanner bug
* (where the buffers don't flush correctly after an int read).
*
* The methods also parse the numeric data entered to ensure it is correct. If it isn't correct,
* the user is prompted to enter it again.
*
* @author Siobhan Drohan and Mairead Meagher
* @version 1.0
*/
object ScannerInput {
/**
* Read an int from the user.
* If the entered data isn't actually an int the user is prompted again to enter the int.
*
* @param prompt The information printed to the console for the user to read
* @return The number read from the user and verified as an int.
*/
@JvmStatic
fun readNextInt(prompt: String?): Int {
do {
try {
print(prompt)
return Scanner(System.`in`).next().toInt()
} catch (e: NumberFormatException) {
System.err.println("\tEnter a number please.")
}
} while (true)
}
/**
* Read a double from the user. If the entered data isn't actually a double,
* the user is prompted again to enter the double.
*
* @param prompt The information printed to the console for the user to read
* @return The number read from the user and verified as a double.
*/
fun readNextDouble(prompt: String?): Double {
do {
try {
print(prompt)
return Scanner(System.`in`).next().toDouble()
} catch (e: NumberFormatException) {
System.err.println("\tEnter a number please.")
}
} while (true)
}
/**
* Read a line of text from the user. There is no validation done on the entered data.
*
* @param prompt The information printed to the console for the user to read
* @return The String read from the user.
*/
@JvmStatic
fun readNextLine(prompt: String?): String {
print(prompt)
return Scanner(System.`in`).nextLine()
}
/**
* Read a single character of text from the user. There is no validation done on the entered data.
*
* @param prompt The information printed to the console for the user to read
* @return The char read from the user.
*/
@JvmStatic
fun readNextChar(prompt: String?): Char {
print(prompt)
return Scanner(System.`in`).next()[0]
}
}
| filament-app/src/main/kotlin/utils/ScannerInput.kt | 2107808979 |
package utils
import models.Catalogue
import models.Filament
import java.util.Scanner
object Utilities {
@JvmStatic
fun formatListString(filamentsToFormat: List<Filament>): String =
filamentsToFormat
.joinToString(separator = "\n") { filament -> "$filament" }
}
object Utility {
@JvmStatic
fun formatListString(cataloguesToFormat: List<Catalogue>): String =
cataloguesToFormat
.joinToString(separator = "\n") { catalogue -> "$catalogue" }
} | filament-app/src/main/kotlin/utils/Utilities.kt | 4161587072 |
package models
data class Menu(
var colorChoice: String){
} | filament-app/src/main/kotlin/models/Menu.kt | 1447910720 |
package models
import utils.Utilities
data class Catalogue(
var catalogueId: Int= 0, // Unique identifier for the catalogue
var catalogueBrand: String, // Brand of the filament
var catalogueComponent: String, // Type of material used to make the filament
var cataloguePrintTemp: String, // The optimal printing temperature for filament
var catalogueBedTemp: String, // The optimal bed printing temperature for filament
) | filament-app/src/main/kotlin/models/Catalogue.kt | 1096089201 |
package models
import utils.Utilities
data class Filament(
var filamentId: Int= 0, // Unique identifier for the filament
var filamentBrand: String, // Brand of the filament
var filamentType: String, // Type of filament (e.g., PLA, ABS)
var filamentColor: String, // The pigment of the filament
var filamentQuantity: Int, // Quantity available in stock
)
| filament-app/src/main/kotlin/models/Filament.kt | 2028373602 |
// Importing necessary classes and packages
import controllers.MenuAPI
import controllers.FilamentApi
import controllers.CatalogueAPI
import models.Catalogue
import models.Filament
import models.Menu
import persistence.JSONSerializer
import utils.MenuColorManager
import utils.ScannerInput.readNextInt
import utils.ScannerInput.readNextLine
import utils.ScannerInput
import java.io.File
import kotlin.system.exitProcess
// Creating instances of the API classes and other utilities
private val menuAPI = MenuAPI()
//private val filamentApi = FilamentApi(XMLSerializer(File("filament.xml")))
private val filamentApi = FilamentApi(JSONSerializer(File("filaments.json")))
private val catalogueAPI = CatalogueAPI(JSONSerializer(File("catalogues.json")))
val menuColorManager = MenuColorManager()
// Main function to start the application
fun main() = runMenu()
// Function to run the main menu in a loop
fun runMenu() {
do {
when (val option = mainMenu()) {
1 -> addFilament()
2 -> listFilaments()
3 -> updateFilament()
4 -> deleteFilament()
5 -> searchFilamentBrand()
6 -> searchFilamentType()
7 -> addCatalogue()
8 -> listInfo()
9 -> updateCatalogue()
10 -> deleteCatalogue()
//11 -> sortCatalogueInfoBy()
12 -> changeMenu()
0 -> exitApp()
else -> println("Invalid menu choice: $option")
}
} while (true)
}
// Function to display the main menu and get the user's choice
fun mainMenu(): Int { return readNextInt(menuColorManager.getColoredMenu(
"""
> ---------------------------------------------------------------------------------
| / __ \ _____ _ _ _ _ _ _ / __ \ |
|/ / \ \ | ___(_) | __ _ _ __ ___ ___ _ __ | |_| | | |_ _| |__ / / \ \|
|\ \__/ / | |_ | | |/ _` | '_ ` _ \ / _ \ '_ \| __| |_| | | | | '_ \ \ \__/ /|
| \____/ | _| | | | (_| | | | | | | __/ | | | |_| _ | |_| | |_) | \____/ |
| / \ |_| |_|_|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|\__,_|_.__/ / \ |
|---------------------------------------------------------------------------------|
| FILAMENT CATALOG APP |
|---------------------------------------------------------------------------------|
| FILAMENT MENU |
| 1) Add a Filament |
| 2) List Filaments |
| 3) Update Filament |
| 4) Delete Filament |
| 5) Search Filament by Brand |
| 6) Search Filament by Type |
|---------------------------------------------------------------------------------|
| CATALOG MENU |
| 7) Add Catalogue Info |
| 8) List Info | |
| 9) Update Catalogue Info |
| 10) Delete Catalogue Info |
| 11) Sort Catalogue Info by |
----------------------------------------------------------------------------------|
| SETTINGS |
| 12) Change Menu Color |
| 0) Exit App |
-----------------------------------------------------------------------------------
> ==>>
""".trimMargin(">")
))
}
// Function to add a filament
fun addFilament() {
// Getting details from the user
val filamentBrand = readNextLine("Enter the brand of filament: ")
val filamentType = readNextLine("Enter the type of filament (PLA,TPU,PETG,ABS, etc): ")
val filamentColor = readNextLine("Enter the color of filament: ")
val filamentQuantity = readNextInt("Enter the quantity of filament: ")
// Adding the filament using FilamentApi
val isAdded = filamentApi.add(Filament(filamentBrand = filamentBrand, filamentType = filamentType, filamentColor = filamentColor, filamentQuantity = filamentQuantity))
// Displaying success or failure message
if (isAdded) {
println("Added Successfully")
} else {
println("Add Failed")
}
}
// Function to list all filaments
fun listFilaments() {
println(filamentApi.listAllFilaments())
}
// Function to update a filament
fun updateFilament(){
// Displaying the list of filaments
listFilaments()
// Checking if filaments exist
if (filamentApi.numberOfFilaments() > 0) {
// Asking the user to choose the filament to update
val id = readNextInt("Enter the id of the filament to update: ")
// Checking if the chosen filament exists
if (filamentApi.findFilament(id) != null) {
// Getting new details from the user
val filamentBrand = readNextLine("Enter the brand of filament: ")
val filamentType = readNextLine("Enter the type of filament: ")
val filamentColor = readNextLine("Enter the color of filament: ")
val filamentQuantity = readNextInt("Enter the quantity of filament: ")
// Updating the filament using FilamentApi
if (filamentApi.update(id, Filament(0, filamentBrand, filamentType, filamentColor, filamentQuantity))){
println("Update Successful")
} else {
println("Update Failed")
}
} else {
println("Filament not found with ID: $id")
}
}
}
// Function to delete a filament
fun deleteFilament() {
// Displaying the list of filaments
listFilaments()
// Checking if filaments exist
if (filamentApi.numberOfFilaments() > 0) {
// Asking the user to choose the filament to delete
val id = readNextInt("Enter the id of the note to delete: ")
// Displaying success or failure message
val filamentToDelete = filamentApi.delete(id)
if (filamentToDelete) {
println("Delete Successful!")
} else {
println("Delete NOT Successful")
}
}
}
// Function to search filaments by brand
fun searchFilamentBrand() {
// Getting the brand to search for
val searchBrand = readNextLine("Enter the description to search by: ")
// Searching for filaments by brand using FilamentApi
val searchResults = filamentApi.searchFilamentsByBrand(searchBrand)
// Displaying search results
if (searchResults.isEmpty()) {
println("No filaments found")
} else {
println(searchResults)
}
}
// Function to search filaments by type
fun searchFilamentType() {
// Getting the type to search for
val searchType = readNextLine("Enter the description to search by: ")
// Searching for filaments by type using FilamentApi
val searchResults = filamentApi.searchFilamentsByType(searchType)
// Displaying search results
if (searchResults.isEmpty()) {
println("No filaments found")
} else {
println(searchResults)
}
}
// Function to add a catalogue
fun addCatalogue() {
// Getting details from the user
var catalogueBrand: String = readNextLine("Enter the brand of filament: ")
val catalogueComponent = readNextLine("Enter the Type of material used to make the filament): ")
val cataloguePrintTemp = readNextLine("The optimal printing temperature for filament: ")
val catalogueBedTemp = readNextLine("The optimal bed printing temperature for filament: ")
// Adding the catalogue using CatalogueAPI
val isAdded = catalogueAPI.addCatalogue(Catalogue(catalogueBrand = catalogueBrand, catalogueComponent = catalogueComponent, cataloguePrintTemp = cataloguePrintTemp, catalogueBedTemp = catalogueBedTemp))
// Displaying success or failure message
if (isAdded) {
println("Added Successfully")
} else {
println("Add Failed")
}
}
// Function to list all catalogues
fun listInfo() {
println(catalogueAPI.listAllInfo())
}
// Function to delete a catalogue
fun deleteCatalogue(){
// Displaying the list of catalogues
listInfo()
// Checking if catalogues exist
if (catalogueAPI.numberOfCatalogues() > 0) {
// Asking the user to choose the catalogue to delete
val id = readNextInt("Enter the id of the catalogue to delete: ")
// Deleting the catalogue using CatalogueAPI
val filamentToDelete = catalogueAPI.deleteCatalogue(id)
// Displaying success or failure message
if (filamentToDelete) {
println("Delete Successful!")
} else {
println("Delete NOT Successful")
}
}
}
// Function to update a catalogue
fun updateCatalogue(){
// Displaying the list of catalogues
listInfo()
// Checking if catalogues exist
if (catalogueAPI.numberOfCatalogues() > 0) {
// Asking the user to choose the catalogue to update
val id = readNextInt("Enter the id of the filament to update: ")
// Checking if the chosen catalogue exists
if (catalogueAPI.findCatalogue(id) != null) {
// Getting new details from the user
val catalogueBrand = readNextLine("Enter the brand of filament: ")
val catalogueComponent = readNextLine("Enter the Type of material used to make the filament:")
val cataloguePrintTemp = readNextLine("Enter the the optimal printing temperature for filament: ")
val catalogueBedTemp = readNextLine("Enter the optimal bed printing temperature for filament: ")
// Updating the catalogue using CatalogueAPI
if (catalogueAPI.updateCatalogue(id, Catalogue(0, catalogueBrand, catalogueComponent, cataloguePrintTemp, catalogueBedTemp))){
println("Update Successful")
} else {
println("Update Failed")
}
} else {
println("Filament not found with ID: $id")
}
}
}
// Function to change the menu color
fun changeMenu() {
//logger.info { "changeColour() function invoked" }
val colorChoice = readNextLine("Enter the name of a Color: ")
menuColorManager.changeColor(colorChoice)
val isChanged = menuAPI.change(Menu(colorChoice))
if (isChanged) {
println("Change Successfully")
} else {
println("Change Failed")
}
}
fun exitApp() {
println("Exiting...bye for now")
exitProcess(0)
}
| filament-app/src/main/kotlin/Main.kt | 2847959432 |
package persistence
interface Serializer {
@Throws(Exception::class)
fun write(obj: Any?)
@Throws(Exception::class)
fun read(): Any?
} | filament-app/src/main/kotlin/persistence/Serializer.kt | 3410809213 |
package persistence
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver
import models.Filament
import java.io.File
import java.io.FileReader
import java.io.FileWriter
class JSONSerializer(private val file: File) : Serializer {
@Throws(Exception::class)
override fun read(): Any {
val xStream = XStream(JettisonMappedXmlDriver())
xStream.allowTypes(arrayOf(Filament::class.java))
val inputStream = xStream.createObjectInputStream(FileReader(file))
val obj = inputStream.readObject() as Any
inputStream.close()
return obj
}
@Throws(Exception::class)
override fun write(obj: Any?) {
val xStream = XStream(JettisonMappedXmlDriver())
val outputStream = xStream.createObjectOutputStream(FileWriter(file))
outputStream.writeObject(obj)
outputStream.close()
}
} | filament-app/src/main/kotlin/persistence/JSONSerializer.kt | 1012095595 |
package persistence
import java.io.File
import kotlin.Throws
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.io.xml.DomDriver
import models.Filament
import java.io.FileReader
import java.io.FileWriter
import java.lang.Exception
class XMLSerializer(private val file: File) : Serializer {
@Throws(Exception::class)
override fun read(): Any {
val xStream = XStream(DomDriver())
xStream.allowTypes(arrayOf(Filament::class.java))
val inputStream = xStream.createObjectInputStream(FileReader(file))
val obj = inputStream.readObject() as Any
inputStream.close()
return obj
}
@Throws(Exception::class)
override fun write(obj: Any?) {
val xStream = XStream(DomDriver())
val outputStream = xStream.createObjectOutputStream(FileWriter(file))
outputStream.writeObject(obj)
outputStream.close()
}
} | filament-app/src/main/kotlin/persistence/XMLSerializer.kt | 1183875511 |
package controllers
import models.Filament
import java.util.ArrayList
import utils.Utilities.formatListString
import persistence.Serializer
class FilamentApi(serializerType: Serializer) {
private var serializer: Serializer = serializerType
private var filaments = ArrayList<Filament>()
private var lastId = 0
private fun getId() = lastId++
fun add(filament: Filament): Boolean {
filament.filamentId = getId()
return filaments.add(filament)
}
fun delete (id:Int) = filaments.removeIf{ filament -> filament.filamentId ==id}
fun update(id: Int, filament: Filament?): Boolean {
val foundFilament = findFilament(id)
// if the note exists, use the note details passed as parameters to update the found note in the ArrayList.
if ((foundFilament != null) && (filament != null)) {
foundFilament.filamentBrand = filament.filamentBrand
foundFilament.filamentType = filament.filamentType
foundFilament.filamentColor = filament.filamentColor
foundFilament.filamentQuantity = filament.filamentQuantity
return true
}
// if the note was not found, return false, indicating that the update was not successful
return false
}
fun listAllFilaments() =
if (filaments.isEmpty()) "no filaments stored"
else formatListString(filaments)
fun numberOfFilaments():Int = filaments.size
//searching
fun findFilament(filamentId : Int) = filaments.find{ filament -> filament.filamentId == filamentId }
fun searchFilamentsByBrand(searchString: String) =
formatListString(
filaments.filter { filament -> filament.filamentBrand.contains(searchString, ignoreCase = true) }
)
fun searchFilamentsByType(searchString: String) =
formatListString(
filaments.filter { filament -> filament.filamentType.contains(searchString, ignoreCase = true) }
)
} | filament-app/src/main/kotlin/controllers/FilamentApi.kt | 2518019202 |
package controllers
import models.Catalogue
import persistence.Serializer
import utils. Utility
import java.util.ArrayList
class CatalogueAPI(serializerType: Serializer) {
private var serializer: Serializer = serializerType
private var catalogues = ArrayList<Catalogue>()
private var lastId = 0
private fun getId() = lastId++
fun addCatalogue(catalogueId: Catalogue): Boolean {
catalogueId.catalogueId = getId()
return catalogues.add(catalogueId)
}
fun deleteCatalogue(id: Int) = catalogues.removeIf { catalogue -> catalogue.catalogueId == id }
fun updateCatalogue(id: Int, catalogue: Catalogue?): Boolean {
val foundCatalogue = findCatalogue(id)
if (foundCatalogue != null && catalogue != null) {
foundCatalogue.catalogueBrand = catalogue.catalogueBrand
foundCatalogue.catalogueComponent = catalogue.catalogueComponent
foundCatalogue.cataloguePrintTemp = catalogue.cataloguePrintTemp
foundCatalogue.catalogueBedTemp = catalogue.catalogueBedTemp
return true
}
// if the catalogue was not found, return false, indicating that the update was not successful
return false
}
fun listAllInfo() =
if (catalogues.isEmpty()) "no info stored"
else Utility.formatListString(catalogues)
fun numberOfCatalogues():Int = catalogues.size
fun findCatalogue(catalogueId : Int) = catalogues.find{ filament -> filament.catalogueId == catalogueId }
} | filament-app/src/main/kotlin/controllers/CatalogueAPI.kt | 207963704 |
package controllers
import models.Menu
private var menus = ArrayList<Menu>()
class MenuAPI {
fun change(menu: Menu): Boolean {
return menus.add(menu)
}
} | filament-app/src/main/kotlin/controllers/MenuAPI.kt | 1713613179 |
package apps.sumit.rollthedice
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("apps.sumit.rollthedice", appContext.packageName)
}
} | Roll_the_Dice_Retrofit_and_Ktor_UI/app/src/androidTest/java/apps/sumit/rollthedice/ExampleInstrumentedTest.kt | 512704678 |
package apps.sumit.rollthedice
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Roll_the_Dice_Retrofit_and_Ktor_UI/app/src/test/java/apps/sumit/rollthedice/ExampleUnitTest.kt | 2651813666 |
package apps.sumit.rollthedice.di
import apps.sumit.rollthedice.common.Constants.BASE_URL
import apps.sumit.rollthedice.data.remote.DiceAPI
import apps.sumit.rollthedice.data.remote.repository.RepositoryImpl
import apps.sumit.rollthedice.domain.repository.Repository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideApi(): DiceAPI {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(DiceAPI::class.java)
}
@Provides
@Singleton
fun provideDiceRepository(api: DiceAPI): Repository {
return RepositoryImpl(api)
}
} | Roll_the_Dice_Retrofit_and_Ktor_UI/app/src/main/java/apps/sumit/rollthedice/di/AppModule.kt | 2477092693 |
package apps.sumit.rollthedice.common
sealed class Resource<T>(val data: T? = null, val message: String? = null) {
class Success<T>(data: T) : Resource<T>(data)
class Error<T>(message: String) : Resource<T>(message = message)
class Loading<T>(data: T? = null) : Resource<T>(data)
} | Roll_the_Dice_Retrofit_and_Ktor_UI/app/src/main/java/apps/sumit/rollthedice/common/Resource.kt | 759361701 |
package apps.sumit.rollthedice.common
object Constants {
const val BASE_URL = "https://roll-the-dice-retrofit-and-ktor-backend.onrender.com/"
} | Roll_the_Dice_Retrofit_and_Ktor_UI/app/src/main/java/apps/sumit/rollthedice/common/Constants.kt | 139613962 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.