path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/lttrung/notepro/domain/usecases/impl/UpdatePinStatusUseCaseImpl.kt | lttrung2001 | 587,661,881 | false | null | package com.lttrung.notepro.domain.usecases.impl
import com.lttrung.notepro.domain.repositories.MemberRepositories
import com.lttrung.notepro.domain.usecases.UpdatePinStatusUseCase
import io.reactivex.rxjava3.core.Single
import javax.inject.Inject
class UpdatePinStatusUseCaseImpl @Inject constructor(
private val memberRepositories: MemberRepositories
) : UpdatePinStatusUseCase {
override fun execute(noteId: String, isPin: Boolean): Single<Boolean> {
return memberRepositories.updatePin(noteId, isPin)
}
} | 0 | Kotlin | 0 | 0 | c4d5b4d167b092fc003f5a61849b043b6ea47367 | 530 | note-pro | MIT License |
app/src/test/java/com/example/bletracker/fake/LocatorAPIServiceTest.kt | sowalks | 749,925,143 | false | {"Kotlin": 103956} | package com.example.bletracker.fake
import com.example.bletracker.data.utils.network.LocatorApiService
import com.example.bletracker.rules.TestDispatcherRule
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import org.junit.Rule
import org.junit.Test
import retrofit2.Retrofit
class LocatorAPIServiceTest {
private val baseURL =
" http://127.0.0.1:5000"
//Simple test for now for duplicates and was successes.
@get:Rule
val testDispatcher = TestDispatcherRule()
@Test
fun locatorApiService_verify_server_get_deviceID() =
runTest{
val retrofit: Retrofit = Retrofit.Builder()
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.baseUrl(baseURL)
.build()
val retrofitTestService: LocatorApiService = retrofit.create(LocatorApiService::class.java)
val id = retrofitTestService.getDeviceID()
}
@Test
fun locatorApiService_verify_server_get_locations() =
runTest{
val retrofit: Retrofit = Retrofit.Builder()
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.baseUrl(baseURL)
.build()
val retrofitTestService: LocatorApiService = retrofit.create(LocatorApiService::class.java)
val entries = retrofitTestService.getLocations(FakeDataSource.deviceID).entries
assertEquals("Entries Recieved should be ${FakeDataSource.locatorEntries.entries.size}, is ${entries.size} ",entries.size,FakeDataSource.locatorEntries.entries.size
)
assertEquals("Entries 0 tagID is ${entries[0].tagID}",entries[0].tagID,FakeDataSource.locatorEntries.entries[0].tagID
)
assertEquals(retrofitTestService.getLocations(FakeDataSource.deviceID).entries[1].tagID,FakeDataSource.locatorEntries.entries[1].tagID
)
}
@Test
fun locatorApiService_verify_server_submitlog() =
runTest{
val retrofit: Retrofit = Retrofit.Builder()
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.baseUrl(baseURL)
.build()
val retrofitTestService: LocatorApiService = retrofit.create(LocatorApiService::class.java)
val res = retrofitTestService.submitLog(FakeDataSource.logEntries)
assertEquals("Status Recieved should be ${FakeDataSource.logStatusDuplicate1}, is $res .",res,FakeDataSource.logStatusDuplicate1)
}
@Test
fun locatorApiService_verify_server_registrate() =
runTest{
val retrofit: Retrofit = Retrofit.Builder()
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.baseUrl(baseURL)
.build()
val retrofitTestService: LocatorApiService = retrofit.create(LocatorApiService::class.java)
val res = retrofitTestService.registerTag(FakeDataSource.registrator)
assertEquals("Status Recieved should be ${FakeDataSource.statusFail12}, is $res .",res,FakeDataSource.statusFail12)
}
}
| 0 | Kotlin | 0 | 0 | d3c493542a3208958a9a047f6ccb7342815cd7e2 | 3,376 | android-ble-tracker | Apache License 2.0 |
coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/Batch.kt | Consensys | 681,656,806 | false | {"Go": 3732756, "Kotlin": 2036043, "TypeScript": 1677629, "Solidity": 1011831, "Java": 190613, "Shell": 25336, "Python": 25050, "Jupyter Notebook": 14509, "Makefile": 13574, "Dockerfile": 8023, "JavaScript": 7341, "C": 5181, "Groovy": 2557, "CSS": 787, "Nix": 315, "Batchfile": 117} | package net.consensys.zkevm.domain
fun createBatch(
startBlockNumber: Long,
endBlockNumber: Long,
status: Batch.Status = Batch.Status.Proven
): Batch {
return Batch(
startBlockNumber = startBlockNumber.toULong(),
endBlockNumber = endBlockNumber.toULong(),
status = status
)
}
| 27 | Go | 2 | 26 | 48547c9f3fb21e9003d990c9f62930f4facee0dd | 299 | linea-monorepo | Apache License 2.0 |
app/src/main/java/com/skapps/eys/Model/Task.kt | sahinkaradeniz | 541,543,695 | false | null | package com.skapps.eys.Model
import android.media.Image
import com.google.firebase.firestore.FieldValue
data class Task(
var taskID: String,
var classID: String,
var className:String,
var teacherID: String,
var teacherName: String,
var teacherPhoto: String,
var teacherDepartment: String,
var taskText: String,
var taskImage: String,
var document: String,
var date:String
) {
}
| 0 | Kotlin | 0 | 0 | 5681bc8e2548eb7ffc81222409493196026c7576 | 424 | EducationalManagementSystem | MIT License |
compiler/testData/diagnostics/tests/inference/pcla/fixationOnDemand/miscellaneous/NestedDependentPCLACall.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | fun testA() {
fun <SOT> nestedPCLA(shallowAnchor: SOT, lambda: (TypeVariableOwner<SOT>) -> Any?): SOT = null!!
val resultAA = PCLA { fotvOwner ->
val nestedResultAA = nestedPCLA(fotvOwner.provide()) { sotvOwner ->
// FOTv <: SOTv
fotvOwner.constrain(ScopeOwner())
// ScopeOwner <: FOTv <: SOTv
sotvOwner.provide().<!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE, DEBUG_INFO_UNRESOLVED_WITH_TARGET, UNRESOLVED_REFERENCE!>function<!>()
// SOTv := FOTv := ScopeOwner
// expected: Interloper </: ScopeOwner
fotvOwner.constrain(Interloper)
// expected: Interloper </: ScopeOwner
sotvOwner.constrain(Interloper)
}
// expected: ScopeOwner
<!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>nestedResultAA<!>
}
// expected: ScopeOwner
<!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultAA<!>
}
fun testB() {
fun <SOT> nestedPCLA(invariantAnchor: Anchor<SOT>, lambda: (TypeVariableOwner<SOT>) -> Any?): SOT = null!!
val resultBA = PCLA { fotvOwner ->
val nestedResultBA = nestedPCLA(fotvOwner.provideAnchor()) { sotvOwner ->
// Anchor<FOTv> <: Anchor<SOTv> => FOTv == SOTv
fotvOwner.constrain(ScopeOwner())
// ScopeOwner <: FOTv == SOTv
fotvOwner.provide().<!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE, DEBUG_INFO_UNRESOLVED_WITH_TARGET, UNRESOLVED_REFERENCE!>function<!>()
// FOTv := SOTv := ScopeOwner
// expected: Interloper </: ScopeOwner
fotvOwner.constrain(Interloper)
// expected: Interloper </: ScopeOwner
sotvOwner.constrain(Interloper)
}
// expected: ScopeOwner
<!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>nestedResultBA<!>
}
// expected: ScopeOwner
<!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultBA<!>
val resultBB = PCLA { fotvOwner ->
val nestedResultBB = nestedPCLA(fotvOwner.provideAnchor()) { sotvOwner ->
// Anchor<FOTv> <: Anchor<SOTv> => FOTv == SOTv
sotvOwner.constrain(ScopeOwner())
// ScopeOwner <: SOTv == FOTv
sotvOwner.provide().<!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE, DEBUG_INFO_UNRESOLVED_WITH_TARGET, UNRESOLVED_REFERENCE!>function<!>()
// SOTv := FOTv := ScopeOwner
// expected: Interloper </: ScopeOwner
fotvOwner.constrain(Interloper)
// expected: Interloper </: ScopeOwner
sotvOwner.constrain(Interloper)
}
// expected: ScopeOwner
<!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>nestedResultBB<!>
}
// expected: ScopeOwner
<!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultBB<!>
}
fun testC() {
fun <SOT> nestedPCLA(covariantAnchor: Anchor<out SOT>, lambda: (TypeVariableOwner<SOT>) -> Any?): SOT = null!!
val resultCA = PCLA { fotvOwner ->
val nestedResultCA = nestedPCLA(fotvOwner.provideAnchor()) { sotvOwner ->
// Anchor<out FOTv> <: Anchor<out SOTv> => FOTv <: SOTv
fotvOwner.constrain(ScopeOwner())
// ScopeOwner <: FOTv <: SOTv
sotvOwner.provide().<!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE, DEBUG_INFO_UNRESOLVED_WITH_TARGET, UNRESOLVED_REFERENCE!>function<!>()
// SOTv := FOTv := ScopeOwner
// expected: Interloper </: ScopeOwner
fotvOwner.constrain(Interloper)
// expected: Interloper </: ScopeOwner
sotvOwner.constrain(Interloper)
}
// expected: ScopeOwner
<!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>nestedResultCA<!>
}
// expected: ScopeOwner
<!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultCA<!>
}
fun testD() {
fun <SOT> nestedPCLA(contravariantAnchor: Anchor<in SOT>, lambda: (TypeVariableOwner<SOT>) -> Any?): SOT = null!!
val resultDA = PCLA { fotvOwner ->
val nestedResultDA = nestedPCLA(fotvOwner.provideAnchor()) { sotvOwner ->
// Anchor<in FOTv> <: Anchor<in SOTv> => SOTv <: FOTv
sotvOwner.constrain(ScopeOwner())
// ScopeOwner <: SOTv <: FOTv
fotvOwner.provide().<!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE, DEBUG_INFO_UNRESOLVED_WITH_TARGET, UNRESOLVED_REFERENCE!>function<!>()
// FOTv := SOTv := ScopeOwner
// expected: Interloper </: ScopeOwner
fotvOwner.constrain(Interloper)
// expected: Interloper </: ScopeOwner
sotvOwner.constrain(Interloper)
}
// expected: ScopeOwner
<!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>nestedResultDA<!>
}
// expected: ScopeOwner
<!DEBUG_INFO_EXPRESSION_TYPE("BaseType")!>resultDA<!>
}
class Anchor<AT>
class TypeVariableOwner<T> {
fun constrain(subtypeValue: T) {}
fun provide(): T = null!!
fun provideAnchor(): Anchor<T> = null!!
}
fun <FOT> PCLA(lambda: (TypeVariableOwner<FOT>) -> Any?): FOT = null!!
interface BaseType
class ScopeOwner: BaseType {
fun function() {}
}
object Interloper: BaseType
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 5,074 | kotlin | Apache License 2.0 |
src/test/kotlin/ResultSpec.kt | GoosvandenBekerom | 127,311,976 | false | null | import com.goosvandenbekerom.roulette.core.DOUBLE_ZERO
import com.goosvandenbekerom.roulette.core.Result
import com.goosvandenbekerom.roulette.core.RouletteColor
import com.goosvandenbekerom.roulette.core.ZERO
import com.goosvandenbekerom.roulette.core.exception.NonExistingRouletteResult
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.function.Executable
class ResultSpec : Spek({
given("a result") {
context("of number 5") {
val result = Result(5)
it("should be of the color red") {
assertEquals(RouletteColor.RED, result.color)
}
}
context("of number $ZERO") {
val result = Result(ZERO)
it("should be of the color green") {
assertEquals(RouletteColor.GREEN, result.color)
}
}
context("of number $DOUBLE_ZERO") {
val result = Result(DOUBLE_ZERO)
it("should be of the color green") {
assertEquals(RouletteColor.GREEN, result.color)
}
}
context("of number 10") {
val result = Result(10)
it("should be of the color black") {
assertEquals(RouletteColor.BLACK, result.color)
}
}
context("of number 11") {
val result = Result(11)
it("should be of the color black") {
assertEquals(RouletteColor.BLACK, result.color)
}
}
context("of number 18") {
val result = Result(18)
it("should be of the color red") {
assertEquals(RouletteColor.RED, result.color)
}
}
context("of number 19") {
val result = Result(19)
it("should be of the color red") {
assertEquals(RouletteColor.RED, result.color)
}
}
context("of number 28") {
val result = Result(28)
it("should be of the color black") {
assertEquals(RouletteColor.BLACK, result.color)
}
}
context("of number 29") {
val result = Result(29)
it("should be of the color black") {
assertEquals(RouletteColor.BLACK, result.color)
}
}
context("of a positive non existing roulette number") {
it("should throw a non existing number error") {
assertThrows(NonExistingRouletteResult::class.java, Executable { Result(100) })
}
}
context("of a negative non existing roulette number") {
it("should throw a non existing number error") {
assertThrows(NonExistingRouletteResult::class.java, Executable { Result(-100) })
}
}
}
}) | 0 | Kotlin | 0 | 0 | 51dd5d6bb0d8c8c1ecdfce0eeca8f23db08e410d | 3,021 | roulette.core | MIT License |
samples/todo-android/app/src/androidTest/java/com/squareup/sample/mainactivity/TodoAppTest.kt | mitchtabian | 402,168,674 | true | {"Kotlin": 939971, "Shell": 2095, "Ruby": 1695, "Java": 806} | package com.squareup.sample.mainactivity
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.uiautomator.UiDevice
import com.squareup.sample.todo.R
import com.squareup.workflow1.ui.internal.test.inAnyView
import com.squareup.workflow1.ui.internal.test.actuallyPressBack
import org.hamcrest.Matchers.allOf
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class TodoAppTest {
@Rule @JvmField val scenarioRule = ActivityScenarioRule(ToDoActivity::class.java)
private val uiDevice by lazy { UiDevice.getInstance(getInstrumentation()) }
@Test fun navigatesToListAndBack_portrait() {
uiDevice.setOrientationNatural()
inAnyView(withText("Groceries"))
.check(matches(allOf(isDisplayed())))
.perform(click())
inAnyView(withId(R.id.item_container))
.check(matches(isDisplayed()))
actuallyPressBack()
inAnyView(withId(R.id.todo_lists_container))
.check(matches(isDisplayed()))
}
}
| 0 | null | 0 | 2 | de7f495df9bf97ad9f47e1f7a8c4abfd69783056 | 1,452 | workflow-kotlin | Apache License 2.0 |
crowdproj-ad-app-ktor/src/commonMain/kotlin/plugins/Routing.kt | crowdproj | 420,616,237 | false | null | package com.crowdproj.ad.app.plugins
import com.benasher44.uuid.uuid4
import com.crowdproj.ad.api.v1.models.*
import com.crowdproj.ad.app.helpers.controllerHelperV1
import configs.CwpAdAppSettings
import com.crowdproj.ad.logs.LogLevel
import com.crowdproj.ad.logs.log
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.autohead.*
import io.ktor.server.plugins.callid.*
import io.ktor.server.plugins.callid.CallId
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.cors.routing.CORS
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlin.reflect.KClass
private val clazz: KClass<*> = Application::configureRouting::class
fun Application.configureRouting(appConfig: CwpAdAppSettings) {
install(Routing)
install(IgnoreTrailingSlash)
install(AutoHeadResponse)
install(CallId) {
generate {
"rq-${uuid4()}"
}
}
install(CORS) {
println("COORRRS: ${appConfig.appUrls}")
allowNonSimpleContentTypes = true
allowSameOrigin = true
allowMethod(HttpMethod.Options)
allowMethod(HttpMethod.Post)
allowMethod(HttpMethod.Get)
allowHeader("*")
appConfig.appUrls.forEach {
val split = it.split("://")
println("$split")
val host = when (split.size) {
2 -> split[1].split("/")[0].apply { log(mes = "COR: $this", clazz = clazz, level = LogLevel.INFO) } to
listOf(split[0])
1 -> split[0].split("/")[0].apply { log(mes = "COR: $this", clazz = clazz, level = LogLevel.INFO) } to
listOf("http", "https")
else -> null
}
println("ALLOW_HOST: $host")
}
allowHost("*")
}
install(ContentNegotiation) {
json(appConfig.json)
}
routing {
trace { application.log.trace(it.buildText()) }
get("/") { call.respondText("Ads Service is working") }
post("v1/create") {
call.controllerHelperV1<AdCreateRequest, AdCreateResponse>(appConfig)
}
post("v1/read") {
call.controllerHelperV1<AdReadRequest, AdReadResponse>(appConfig)
}
post("v1/update") {
call.controllerHelperV1<AdUpdateRequest, AdUpdateResponse>(appConfig)
}
post("v1/delete") {
call.controllerHelperV1<AdDeleteRequest, AdDeleteResponse>(appConfig)
}
post("v1/search") {
call.controllerHelperV1<AdSearchRequest, AdSearchResponse>(appConfig)
}
post("v1/offers") {
call.controllerHelperV1<AdOffersRequest, AdOffersResponse>(appConfig)
}
}
}
| 0 | Kotlin | 0 | 0 | 8539106fe3103ffe448f28c108a2089bde445250 | 2,798 | crowdproj-ad | Apache License 2.0 |
finch-java-core/src/main/kotlin/com/tryfinch/api/errors/FinchException.kt | Finch-API | 581,317,330 | false | {"Kotlin": 2752476, "Shell": 3626, "Java": 1235, "Dockerfile": 366} | package com.tryfinch.api.errors
open class FinchException
@JvmOverloads
constructor(message: String? = null, cause: Throwable? = null) : RuntimeException(message, cause)
| 0 | Kotlin | 1 | 5 | 834892a9bc7e4745edf99c7244e1851cfdd559d1 | 171 | finch-api-java | Apache License 2.0 |
freya/src/test/kotlin/io/violabs/freya/message/UserProducerIntegrationTest.kt | violabs | 640,711,709 | false | null | package io.violabs.freya.message
import io.violabs.core.TestUtils
import io.violabs.core.domain.UserMessage
import io.violabs.freya.KafkaTestConfig
import io.violabs.freya.domain.AppUser
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.context.annotation.Import
@SpringBootTest
@Import(KafkaTestConfig::class)
class UserProducerIntegrationTest(
@Autowired private val userProducer: UserProducer,
@Autowired private val userKafkaConsumer: KafkaTestConfig.UserKafkaConsumer
) {
@Test
fun `should send user data to kafka`() = runBlocking {
val user = AppUser(1, "test", "test", "test", "test")
val message = UserMessage(1, "localhost:8080/user/1", UserMessage.Type.USER_CREATED)
userProducer.sendUserData(user)
delay(2000)
val receivedMessage = withTimeoutOrNull(15_000) { userKafkaConsumer.consume() }
TestUtils.assertEquals(message, receivedMessage)
}
} | 2 | Kotlin | 0 | 0 | 8bca074f2cc4d8bc38ea2222cda55eaa9d2cb13e | 1,171 | vanir | Apache License 2.0 |
array/src/commonMain/kotlin/array/functions.kt | lokedhs | 236,192,362 | false | null | package array
/**
* Class representing a function in KAP. Any subclass of this class that contains
* a reference to another function should store this reference in the [fns] property.
* This ensures that any closures created from this function will properly delegate
* to dependent functions.
*
* @param pos The position where the function was defined.
* @param fns A list of functions that is used to implement this function.
*/
abstract class APLFunction(val pos: Position, val fns: List<APLFunction> = emptyList()) {
open fun evalArgsAndCall1Arg(context: RuntimeContext, rightArgs: Instruction): APLValue {
val rightValue = rightArgs.evalWithContext(context)
return eval1Arg(context, rightValue, null)
}
open fun evalArgsAndCall2Arg(context: RuntimeContext, leftArgs: Instruction, rightArgs: Instruction): APLValue {
val rightValue = rightArgs.evalWithContext(context)
val leftValue = leftArgs.evalWithContext(context)
return eval2Arg(context, leftValue, rightValue, null)
}
open fun eval1Arg(context: RuntimeContext, a: APLValue, axis: APLValue?): APLValue =
throwAPLException(Unimplemented1ArgException(pos))
open fun eval2Arg(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue =
throwAPLException(Unimplemented2ArgException(pos))
open fun identityValue(): APLValue =
throwAPLException(APLIncompatibleDomainsException("Function does not have an identity value", pos))
open fun deriveBitwise(): APLFunctionDescriptor? = null
open val optimisationFlags get() = OptimisationFlags(0)
open fun eval1ArgLong(context: RuntimeContext, a: Long, axis: APLValue?): Long =
throw IllegalStateException("Illegal call to specialised function: ${this::class.simpleName}")
open fun eval1ArgDouble(context: RuntimeContext, a: Double, axis: APLValue?): Double =
throw IllegalStateException("Illegal call to specialised function: ${this::class.simpleName}")
open fun eval2ArgLongLong(context: RuntimeContext, a: Long, b: Long, axis: APLValue?): Long =
throw IllegalStateException("Illegal call to specialised function: ${this::class.simpleName}")
open fun eval2ArgDoubleDouble(context: RuntimeContext, a: Double, b: Double, axis: APLValue?): Double =
throw IllegalStateException("Illegal call to specialised function: ${this::class.simpleName}")
open fun evalInverse1Arg(context: RuntimeContext, a: APLValue, axis: APLValue?): APLValue =
throwAPLException(InverseNotAvailable(pos))
/**
* Compute `x` given the equation `a FN x = b`.
*
* @throws InverseNotAvailable if the inverse cannot be computed
*/
open fun evalInverse2ArgB(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue =
throwAPLException(InverseNotAvailable(pos))
/**
* Compute `x` given the equation `x FN b = a`.
*
* @throws InverseNotAvailable if the inverse cannot be computed
*/
open fun evalInverse2ArgA(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue =
throwAPLException(InverseNotAvailable(pos))
open fun computeClosure(parser: APLParser): Pair<APLFunction, List<Instruction>> {
return if (fns.isEmpty()) {
Pair(this, emptyList())
} else {
val closureList = fns.map { fn -> fn.computeClosure(parser) }
val instrs = closureList.flatMap(Pair<APLFunction, List<Instruction>>::second)
if (instrs.isEmpty()) {
Pair(this, emptyList())
} else {
val newFn = copy(closureList.map(Pair<APLFunction, List<Instruction>>::first))
Pair(newFn, instrs)
}
}
}
open fun copy(fns: List<APLFunction>): APLFunction {
throw IllegalStateException("copy function must be implemented. class = ${this::class.simpleName}")
}
open fun evalWithStructuralUnder1Arg(baseFn: APLFunction, context: RuntimeContext, a: APLValue): APLValue {
throwAPLException(StructuralUnderNotSupported(pos))
}
open fun evalWithStructuralUnder2Arg(baseFn: APLFunction, context: RuntimeContext, a: APLValue, b: APLValue): APLValue {
throwAPLException(StructuralUnderNotSupported(pos))
}
open fun capturedEnvironments(): List<Environment> = emptyList()
fun allCapturedEnvironments(): List<Environment> {
val result = ArrayList<Environment>()
fun recurse(fn: APLFunction) {
result.addAll(fn.capturedEnvironments())
fn.fns.forEach(::recurse)
}
recurse(this)
return result
}
fun markEscapeEnvironment() {
allCapturedEnvironments().forEach(Environment::markCanEscape)
}
open val name1Arg get() = this::class.simpleName ?: "unnamed"
open val name2Arg get() = this::class.simpleName ?: "unnamed"
fun inversibleStructuralUnder1Arg(underFn: APLFunction, baseFn: APLFunction, context: RuntimeContext, a: APLValue): APLValue {
val v = underFn.eval1Arg(context, a, null)
val baseRes = baseFn.eval1Arg(context, v, null)
return underFn.evalInverse1Arg(context, baseRes, null)
}
fun inversibleStructuralUnder2Arg(
underFn: APLFunction,
baseFn: APLFunction,
context: RuntimeContext,
a: APLValue,
b: APLValue
): APLValue {
val v = underFn.eval2Arg(context, a, b, null)
val baseRes = baseFn.eval1Arg(context, v, null)
return underFn.evalInverse2ArgB(context, a, baseRes, null)
}
}
abstract class NoAxisAPLFunction(pos: Position, fns: List<APLFunction> = emptyList()) : APLFunction(pos, fns) {
private fun checkAxisNotNull(axis: APLValue?) {
if (axis != null) {
throwAPLException(AxisNotSupported(pos))
}
}
override fun eval1Arg(context: RuntimeContext, a: APLValue, axis: APLValue?): APLValue {
checkAxisNotNull(axis)
return eval1Arg(context, a)
}
open fun eval1Arg(context: RuntimeContext, a: APLValue): APLValue =
throwAPLException(Unimplemented1ArgException(pos))
override fun eval2Arg(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue {
checkAxisNotNull(axis)
return eval2Arg(context, a, b)
}
open fun eval2Arg(context: RuntimeContext, a: APLValue, b: APLValue): APLValue =
throwAPLException(Unimplemented2ArgException(pos))
override fun evalInverse1Arg(context: RuntimeContext, a: APLValue, axis: APLValue?): APLValue {
checkAxisNotNull(axis)
return evalInverse1Arg(context, a)
}
open fun evalInverse1Arg(context: RuntimeContext, a: APLValue): APLValue =
throwAPLException(InverseNotAvailable(pos))
override fun evalInverse2ArgB(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue {
checkAxisNotNull(axis)
return evalInverse2ArgA(context, a, b)
}
open fun evalInverse2ArgA(context: RuntimeContext, a: APLValue, b: APLValue): APLValue =
throwAPLException(InverseNotAvailable(pos))
override fun evalInverse2ArgA(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue {
checkAxisNotNull(axis)
return evalInverse2ArgB(context, a, b)
}
open fun evalInverse2ArgB(context: RuntimeContext, a: APLValue, b: APLValue): APLValue =
throwAPLException(InverseNotAvailable(pos))
}
abstract class DelegatedAPLFunctionImpl(pos: Position, fns: List<APLFunction> = emptyList()) : APLFunction(pos, fns) {
override fun evalArgsAndCall1Arg(context: RuntimeContext, rightArgs: Instruction) =
innerImpl().evalArgsAndCall1Arg(context, rightArgs)
override fun evalArgsAndCall2Arg(context: RuntimeContext, leftArgs: Instruction, rightArgs: Instruction) =
innerImpl().evalArgsAndCall2Arg(context, leftArgs, rightArgs)
override fun eval1Arg(context: RuntimeContext, a: APLValue, axis: APLValue?) =
innerImpl().eval1Arg(context, a, axis)
override fun eval2Arg(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?) =
innerImpl().eval2Arg(context, a, b, axis)
override fun identityValue() = innerImpl().identityValue()
override fun deriveBitwise() = innerImpl().deriveBitwise()
override val optimisationFlags: OptimisationFlags get() = innerImpl().optimisationFlags
override fun eval1ArgLong(context: RuntimeContext, a: Long, axis: APLValue?) =
innerImpl().eval1ArgLong(context, a, axis)
override fun eval1ArgDouble(context: RuntimeContext, a: Double, axis: APLValue?) =
innerImpl().eval1ArgDouble(context, a, axis)
override fun eval2ArgLongLong(context: RuntimeContext, a: Long, b: Long, axis: APLValue?) =
innerImpl().eval2ArgLongLong(context, a, b, axis)
override fun eval2ArgDoubleDouble(context: RuntimeContext, a: Double, b: Double, axis: APLValue?) =
innerImpl().eval2ArgDoubleDouble(context, a, b, axis)
override fun evalInverse1Arg(context: RuntimeContext, a: APLValue, axis: APLValue?): APLValue =
innerImpl().evalInverse1Arg(context, a, axis)
override fun evalWithStructuralUnder1Arg(baseFn: APLFunction, context: RuntimeContext, a: APLValue) =
innerImpl().evalWithStructuralUnder1Arg(baseFn, context, a)
override fun evalInverse2ArgB(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue =
innerImpl().evalInverse2ArgB(context, a, b, axis)
override fun evalInverse2ArgA(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue =
innerImpl().evalInverse2ArgA(context, a, b, axis)
override fun evalWithStructuralUnder2Arg(baseFn: APLFunction, context: RuntimeContext, a: APLValue, b: APLValue) =
innerImpl().evalWithStructuralUnder2Arg(baseFn, context, a, b)
override fun computeClosure(parser: APLParser) =
innerImpl().computeClosure(parser)
// abstract override fun copy(fns: List<APLFunction>): APLFunction
@Suppress("LeakingThis")
override val name1Arg = innerImpl().name1Arg
@Suppress("LeakingThis")
override val name2Arg = innerImpl().name2Arg
abstract fun innerImpl(): APLFunction
}
/**
* A function that is declared directly in a { ... } expression.
*/
class DeclaredFunction(
val name: String,
val instruction: Instruction,
val leftArgName: EnvironmentBinding,
val rightArgName: EnvironmentBinding,
val env: Environment
) : APLFunctionDescriptor {
inner class DeclaredFunctionImpl(pos: Position) : APLFunction(pos) {
private val leftArgRef = StackStorageRef(leftArgName)
private val rightArgRef = StackStorageRef(rightArgName)
override fun eval1Arg(context: RuntimeContext, a: APLValue, axis: APLValue?): APLValue {
return withLinkedContext(env, "declaredFunction1arg(${name})", pos) {
context.setVar(rightArgRef, a)
instruction.evalWithContext(context)
}
}
override fun eval2Arg(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue {
return withLinkedContext(env, "declaredFunction2arg(${name})", pos) {
context.setVar(leftArgRef, a)
context.setVar(rightArgRef, b)
instruction.evalWithContext(context)
}
}
override fun capturedEnvironments() = listOf(env)
override val name1Arg: String get() = name
override val name2Arg: String get() = name
}
override fun make(pos: Position) = DeclaredFunctionImpl(pos)
}
/**
* A special declared function which ignores its arguments. Its primary use is inside defsyntax rules
* where the functions are only used to provide code structure and not directly called by the user.
*/
class DeclaredNonBoundFunction(val instruction: Instruction) : APLFunctionDescriptor {
inner class DeclaredNonBoundFunctionImpl(pos: Position) : APLFunction(pos) {
override fun eval1Arg(context: RuntimeContext, a: APLValue, axis: APLValue?): APLValue {
return instruction.evalWithContext(context)
}
override fun eval2Arg(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue {
return instruction.evalWithContext(context)
}
}
override fun make(pos: Position) = DeclaredNonBoundFunctionImpl(pos)
}
class LeftAssignedFunction(val underlying: APLFunction, val leftArgs: Instruction, pos: Position) : APLFunction(pos) {
override fun eval1Arg(context: RuntimeContext, a: APLValue, axis: APLValue?): APLValue {
val leftArg = leftArgs.evalWithContext(context)
return underlying.eval2Arg(context, leftArg, a, axis)
}
override fun eval2Arg(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue {
throwAPLException(LeftAssigned2ArgException(pos))
}
override fun evalInverse1Arg(context: RuntimeContext, a: APLValue, axis: APLValue?): APLValue {
val leftArg = leftArgs.evalWithContext(context)
return underlying.evalInverse2ArgB(context, leftArg, a, axis)
}
override fun evalInverse2ArgB(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue {
throwAPLException(LeftAssigned2ArgException(pos))
}
override fun evalInverse2ArgA(context: RuntimeContext, a: APLValue, b: APLValue, axis: APLValue?): APLValue {
throwAPLException(LeftAssigned2ArgException(pos))
}
override fun evalWithStructuralUnder1Arg(baseFn: APLFunction, context: RuntimeContext, a: APLValue): APLValue {
val leftArg = leftArgs.evalWithContext(context)
return underlying.evalWithStructuralUnder2Arg(baseFn, context, leftArg, a)
}
override fun evalWithStructuralUnder2Arg(baseFn: APLFunction, context: RuntimeContext, a: APLValue, b: APLValue): APLValue {
throwAPLException(LeftAssigned2ArgException(pos))
}
override fun computeClosure(parser: APLParser): Pair<APLFunction, List<Instruction>> {
val sym = parser.tokeniser.engine.createAnonymousSymbol()
val binding = parser.currentEnvironment().bindLocal(sym)
val (innerFn, relatedInstrs) = underlying.computeClosure(parser)
val ref = StackStorageRef(binding)
val list = mutableListOf<Instruction>(AssignmentInstruction(arrayOf(ref), leftArgs, pos))
list.addAll(relatedInstrs)
return Pair(LeftAssignedFunction(innerFn, VariableRef(sym, ref, pos), pos), list)
}
override val name1Arg get() = underlying.name2Arg
}
class AxisValAssignedFunctionDirect(baseFn: APLFunction, val axis: Instruction) : NoAxisAPLFunction(baseFn.pos, listOf(baseFn)) {
private val baseFn get() = fns[0]
override fun evalArgsAndCall1Arg(context: RuntimeContext, rightArgs: Instruction): APLValue {
val rightValue = rightArgs.evalWithContext(context)
val axisValue = axis.evalWithContext(context)
return baseFn.eval1Arg(context, rightValue, axisValue)
}
override fun evalArgsAndCall2Arg(context: RuntimeContext, leftArgs: Instruction, rightArgs: Instruction): APLValue {
val rightValue = rightArgs.evalWithContext(context)
val axisValue = axis.evalWithContext(context)
val leftValue = leftArgs.evalWithContext(context)
return baseFn.eval2Arg(context, leftValue, rightValue, axisValue)
}
override fun eval1Arg(context: RuntimeContext, a: APLValue): APLValue {
return baseFn.eval1Arg(context, a, axis.evalWithContext(context))
}
override fun eval2Arg(context: RuntimeContext, a: APLValue, b: APLValue): APLValue {
return baseFn.eval2Arg(context, a, b, axis.evalWithContext(context))
}
override fun evalInverse1Arg(context: RuntimeContext, a: APLValue): APLValue {
return baseFn.evalInverse1Arg(context, a, axis.evalWithContext(context))
}
override fun evalInverse2ArgA(context: RuntimeContext, a: APLValue, b: APLValue): APLValue {
return baseFn.evalInverse2ArgB(context, a, b, axis.evalWithContext(context))
}
override fun evalInverse2ArgB(context: RuntimeContext, a: APLValue, b: APLValue): APLValue {
return baseFn.evalInverse2ArgA(context, a, b, axis.evalWithContext(context))
}
override fun computeClosure(parser: APLParser): Pair<APLFunction, List<Instruction>> {
val sym = parser.tokeniser.engine.createAnonymousSymbol()
val binding = parser.currentEnvironment().bindLocal(sym)
val (innerFn, relatedInstrs) = baseFn.computeClosure(parser)
val ref = StackStorageRef(binding)
return Pair(
AxisValAssignedFunctionAxisReader(innerFn, VariableRef(sym, ref, pos)),
relatedInstrs + AssignmentInstruction(arrayOf(ref), axis, pos))
}
}
class AxisValAssignedFunctionAxisReader(baseFn: APLFunction, val axisReader: Instruction) : NoAxisAPLFunction(baseFn.pos, listOf(baseFn)) {
private val baseFn get() = fns[0]
override fun eval1Arg(context: RuntimeContext, a: APLValue): APLValue {
return baseFn.eval1Arg(context, a, axisReader.evalWithContext(context))
}
override fun eval2Arg(context: RuntimeContext, a: APLValue, b: APLValue): APLValue {
return baseFn.eval2Arg(context, a, b, axisReader.evalWithContext(context))
}
override fun evalInverse1Arg(context: RuntimeContext, a: APLValue): APLValue {
return baseFn.evalInverse1Arg(context, a, axisReader.evalWithContext(context))
}
override fun evalInverse2ArgA(context: RuntimeContext, a: APLValue, b: APLValue): APLValue {
return baseFn.evalInverse2ArgB(context, a, b, axisReader.evalWithContext(context))
}
override fun evalInverse2ArgB(context: RuntimeContext, a: APLValue, b: APLValue): APLValue {
return baseFn.evalInverse2ArgA(context, a, b, axisReader.evalWithContext(context))
}
}
class MergedLeftArgFunction(fn0: APLFunction, fn1: APLFunction) : NoAxisAPLFunction(fn0.pos, listOf(fn0, fn1)) {
private val fn0 get() = fns[0]
private val fn1 get() = fns[1]
override fun eval1Arg(context: RuntimeContext, a: APLValue): APLValue {
val res = fn1.eval1Arg(context, a, null)
return fn0.eval1Arg(context, res, null)
}
override fun evalInverse1Arg(context: RuntimeContext, a: APLValue): APLValue {
val res = fn0.evalInverse1Arg(context, a, null)
return fn1.evalInverse1Arg(context, res, null)
}
override fun copy(fns: List<APLFunction>): APLFunction {
return MergedLeftArgFunction(fns[0], fns[1])
}
}
| 0 | Kotlin | 2 | 42 | da36cfa80b2344840c6f9a468447dc82d76520e0 | 18,677 | array | MIT License |
src/main/kotlin/no/nav/bidrag/beregn/bidragsevne/BidragsevneCoreImpl.kt | navikt | 273,502,209 | false | {"Kotlin": 867869} | package no.nav.bidrag.beregn.bidragsevne
import no.nav.bidrag.beregn.bidragsevne.bo.BarnIHusstandPeriode
import no.nav.bidrag.beregn.bidragsevne.bo.BeregnBidragsevneGrunnlag
import no.nav.bidrag.beregn.bidragsevne.bo.BeregnetBidragsevneResultat
import no.nav.bidrag.beregn.bidragsevne.bo.BostatusPeriode
import no.nav.bidrag.beregn.bidragsevne.bo.InntektPeriode
import no.nav.bidrag.beregn.bidragsevne.bo.ResultatPeriode
import no.nav.bidrag.beregn.bidragsevne.bo.SaerfradragPeriode
import no.nav.bidrag.beregn.bidragsevne.bo.SkatteklassePeriode
import no.nav.bidrag.beregn.bidragsevne.dto.BarnIHusstandPeriodeCore
import no.nav.bidrag.beregn.bidragsevne.dto.BeregnBidragsevneGrunnlagCore
import no.nav.bidrag.beregn.bidragsevne.dto.BeregnetBidragsevneResultatCore
import no.nav.bidrag.beregn.bidragsevne.dto.BostatusPeriodeCore
import no.nav.bidrag.beregn.bidragsevne.dto.InntektPeriodeCore
import no.nav.bidrag.beregn.bidragsevne.dto.ResultatBeregningCore
import no.nav.bidrag.beregn.bidragsevne.dto.ResultatPeriodeCore
import no.nav.bidrag.beregn.bidragsevne.dto.SaerfradragPeriodeCore
import no.nav.bidrag.beregn.bidragsevne.dto.SkatteklassePeriodeCore
import no.nav.bidrag.beregn.bidragsevne.periode.BidragsevnePeriode
import no.nav.bidrag.beregn.felles.FellesCore
import no.nav.bidrag.beregn.felles.bo.Avvik
import no.nav.bidrag.beregn.felles.bo.Periode
import no.nav.bidrag.beregn.felles.dto.PeriodeCore
import no.nav.bidrag.domain.enums.BostatusKode
import no.nav.bidrag.domain.enums.SaerfradragKode
class BidragsevneCoreImpl(private val bidragsevnePeriode: BidragsevnePeriode) : FellesCore(), BidragsevneCore {
override fun beregnBidragsevne(grunnlag: BeregnBidragsevneGrunnlagCore): BeregnetBidragsevneResultatCore {
val beregnBidragsevneGrunnlag = mapTilBusinessObject(grunnlag)
val avvikListe = bidragsevnePeriode.validerInput(beregnBidragsevneGrunnlag)
val beregnBidragsevneResultat =
if (avvikListe.isEmpty()) {
bidragsevnePeriode.beregnPerioder(beregnBidragsevneGrunnlag)
} else {
BeregnetBidragsevneResultat(emptyList())
}
return mapFraBusinessObject(avvikListe = avvikListe, resultat = beregnBidragsevneResultat)
}
private fun mapTilBusinessObject(grunnlag: BeregnBidragsevneGrunnlagCore) =
BeregnBidragsevneGrunnlag(
beregnDatoFra = grunnlag.beregnDatoFra,
beregnDatoTil = grunnlag.beregnDatoTil,
inntektPeriodeListe = mapInntektPeriodeListe(grunnlag.inntektPeriodeListe),
skatteklassePeriodeListe = mapSkatteklassePeriodeListe(grunnlag.skatteklassePeriodeListe),
bostatusPeriodeListe = mapBostatusPeriodeListe(grunnlag.bostatusPeriodeListe),
barnIHusstandPeriodeListe = mapBarnIHusstandPeriodeListe(grunnlag.barnIHusstandPeriodeListe),
saerfradragPeriodeListe = mapSaerfradragPeriodeListe(grunnlag.saerfradragPeriodeListe),
sjablonPeriodeListe = mapSjablonPeriodeListe(grunnlag.sjablonPeriodeListe)
)
private fun mapFraBusinessObject(avvikListe: List<Avvik>, resultat: BeregnetBidragsevneResultat) =
BeregnetBidragsevneResultatCore(
resultatPeriodeListe = mapResultatPeriode(resultat.resultatPeriodeListe),
sjablonListe = mapSjablonGrunnlagListe(resultat.resultatPeriodeListe),
avvikListe = mapAvvik(avvikListe)
)
private fun mapInntektPeriodeListe(inntektPeriodeListeCore: List<InntektPeriodeCore>): List<InntektPeriode> {
val inntektPeriodeListe = mutableListOf<InntektPeriode>()
inntektPeriodeListeCore.forEach {
inntektPeriodeListe.add(
InntektPeriode(
referanse = it.referanse,
inntektPeriode = Periode(datoFom = it.periode.datoFom, datoTil = it.periode.datoTil),
type = it.type,
belop = it.belop
)
)
}
return inntektPeriodeListe
}
private fun mapSkatteklassePeriodeListe(skatteklassePeriodeListeCore: List<SkatteklassePeriodeCore>): List<SkatteklassePeriode> {
val skatteklassePeriodeListe = mutableListOf<SkatteklassePeriode>()
skatteklassePeriodeListeCore.forEach {
skatteklassePeriodeListe.add(
SkatteklassePeriode(
referanse = it.referanse,
skatteklassePeriode = Periode(datoFom = it.periode.datoFom, datoTil = it.periode.datoTil),
skatteklasse = it.skatteklasse
)
)
}
return skatteklassePeriodeListe
}
private fun mapBostatusPeriodeListe(bostatusPeriodeListeCore: List<BostatusPeriodeCore>): List<BostatusPeriode> {
val bostatusPeriodeListe = mutableListOf<BostatusPeriode>()
bostatusPeriodeListeCore.forEach {
bostatusPeriodeListe.add(
BostatusPeriode(
referanse = it.referanse,
bostatusPeriode = Periode(datoFom = it.periode.datoFom, datoTil = it.periode.datoTil),
kode = BostatusKode.valueOf(it.kode)
)
)
}
return bostatusPeriodeListe
}
private fun mapBarnIHusstandPeriodeListe(barnIHusstandPeriodeListeCore: List<BarnIHusstandPeriodeCore>): List<BarnIHusstandPeriode> {
val barnIHusstandPeriodeListe = mutableListOf<BarnIHusstandPeriode>()
barnIHusstandPeriodeListeCore.forEach {
barnIHusstandPeriodeListe.add(
BarnIHusstandPeriode(
referanse = it.referanse,
barnIHusstandPeriode = Periode(datoFom = it.periode.datoFom, datoTil = it.periode.datoTil),
antallBarn = it.antallBarn
)
)
}
return barnIHusstandPeriodeListe
}
private fun mapSaerfradragPeriodeListe(saerfradragPeriodeListeCore: List<SaerfradragPeriodeCore>): List<SaerfradragPeriode> {
val saerfradragPeriodeListe = mutableListOf<SaerfradragPeriode>()
saerfradragPeriodeListeCore.forEach {
saerfradragPeriodeListe.add(
SaerfradragPeriode(
referanse = it.referanse,
saerfradragPeriode = Periode(datoFom = it.periode.datoFom, datoTil = it.periode.datoTil),
kode = SaerfradragKode.valueOf(it.kode)
)
)
}
return saerfradragPeriodeListe
}
private fun mapResultatPeriode(resultatPeriodeListe: List<ResultatPeriode>): List<ResultatPeriodeCore> {
val resultatPeriodeCoreListe = mutableListOf<ResultatPeriodeCore>()
resultatPeriodeListe.forEach {
val (belop, inntekt25Prosent) = it.resultat
resultatPeriodeCoreListe.add(
ResultatPeriodeCore(
periode = PeriodeCore(datoFom = it.periode.datoFom, datoTil = it.periode.datoTil),
resultat = ResultatBeregningCore(belop = belop, inntekt25Prosent = inntekt25Prosent),
grunnlagReferanseListe = mapReferanseListe(it)
)
)
}
return resultatPeriodeCoreListe
}
private fun mapReferanseListe(resultatPeriode: ResultatPeriode): List<String> {
val (inntektListe, skatteklasse, bostatus, barnIHusstand, saerfradrag) = resultatPeriode.grunnlag
val sjablonListe = resultatPeriode.resultat.sjablonListe
val referanseListe = mutableListOf<String>()
inntektListe.forEach {
referanseListe.add(it.referanse)
}
referanseListe.add(skatteklasse.referanse)
referanseListe.add(bostatus.referanse)
referanseListe.add(barnIHusstand.referanse)
referanseListe.add(saerfradrag.referanse)
referanseListe.addAll(sjablonListe.map { lagSjablonReferanse(it) }.distinct())
return referanseListe.sorted()
}
private fun mapSjablonGrunnlagListe(resultatPeriodeListe: List<ResultatPeriode>) =
resultatPeriodeListe
.flatMap { mapSjablonListe(it.resultat.sjablonListe) }
.distinct()
}
| 5 | Kotlin | 0 | 1 | a52e83c8b545e21efd26fcb235f47cebeb11c8ba | 8,177 | bidrag-beregn-barnebidrag-core | MIT License |
src/main/kotlin/no/anksoft/pginmem/statements/AlterSequenceStatement.kt | anders88 | 316,929,720 | false | null | package no.anksoft.pginmem.statements
import no.anksoft.pginmem.DbPreparedStatement
import no.anksoft.pginmem.DbTransaction
import no.anksoft.pginmem.StatementAnalyzer
import java.sql.SQLException
class AlterSequenceStatement(val statementAnalyzer: StatementAnalyzer, private val dbTransaction: DbTransaction) : DbPreparedStatement(dbTransaction) {
override fun executeUpdate(): Int {
val name:String = statementAnalyzer.addIndex(2).word()?:throw SQLException("Expected sequence name")
if (statementAnalyzer.addIndex().word() != "restart") {
throw SQLException("Expected restart in alter sequence")
}
val sequence = dbTransaction.sequence(name)
dbTransaction.resetSequence(sequence)
return 0
}
}
| 0 | Kotlin | 0 | 0 | 6545f69079ed989b36f678e9a821291efb653265 | 767 | pginmem | Apache License 2.0 |
app/src/main/java/ru/claus42/anothertodolistapp/domain/models/DataResult.kt | klauz42 | 679,216,403 | false | {"Kotlin": 257915} | package ru.claus42.anothertodolistapp.domain.models
sealed class DataResult<out T> {
data class Success<T>(val data: T) : DataResult<T>()
data class Error<T>(val error: Throwable) : DataResult<T>()
data object OK : DataResult<Nothing>()
data object Loading : DataResult<Nothing>()
companion object {
inline fun <T> on(f: () -> T): DataResult<T> = try {
Success(f())
} catch (exception: Exception) {
Error(exception)
}
inline fun onWithoutData(f: () -> Unit): DataResult<Nothing> = try {
f()
OK
} catch (exception: Exception) {
Error(exception)
}
fun loading() = Loading
fun ok() = OK
}
} | 0 | Kotlin | 0 | 0 | 5b1a0521dcff700285ba47d23c42266c99b27ca0 | 740 | Another-Todo-List-App | MIT License |
src/main/kotlin/no/nav/tilleggsstonader/sak/ekstern/stønad/dto/VedtaksinformasjonTilsynBarnDto.kt | navikt | 685,490,225 | false | {"Kotlin": 2179594, "Gherkin": 62339, "HTML": 39535, "Shell": 924, "Dockerfile": 164} | package no.nav.tilleggsstonader.sak.ekstern.stønad.dto
data class VedtaksinformasjonTilsynBarnDto(
val harInnvilgetVedtak: Boolean,
)
| 4 | Kotlin | 1 | 0 | b887af4db79e564d52bae5901aebe519c12ce739 | 139 | tilleggsstonader-sak | MIT License |
app/src/main/java/dev/kietyo/scrap/compose/FolderItemWithAsyncImage.kt | Kietyo | 619,106,574 | false | null | package dev.kietyo.scrap.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import dev.kietyo.scrap.GalleryItem
import dev.kietyo.scrap.viewmodels.GalleryViewModel
@Composable
fun FolderItemWithAsyncImage(
galleryViewModel: GalleryViewModel,
item: GalleryItem.FolderWithAsyncImage,
onImageClick: () -> Unit,
) {
val myImageContentScale = galleryViewModel.imageContentScaleFlow.collectAsState()
val alignmentState = galleryViewModel.alignmentFlow.collectAsState()
FolderItemWithAsyncImageTemplate(
FolderItemData.WithImage(
item.imageRequest,
myImageContentScale,
alignmentState
),
folderName = item.folderName,
onImageClick = onImageClick,
)
} | 0 | Kotlin | 0 | 0 | a536ded9e5ef5f01ad98a95b1538a15be8dc9e8b | 788 | kieto-gallery2 | Apache License 2.0 |
app/src/main/java/com/example/diapplication/ui/theme/Dimensions.kt | rendivy | 661,304,960 | false | {"Kotlin": 104188} | package com.example.diapplication.ui.theme
import androidx.compose.ui.unit.dp
val SpacingSmall = 16.dp
val SpacingMedium = 32.dp
val SpacingRegular = 24.dp
val SpacingPartTiny = 8.dp
val SpacingTiny = 4.dp
val SmallIconSize = 21.dp
val tinyIconSize = 18.dp
val PlusMediumIconSize = 36.dp
val MediumIconSize = 24.dp
val RegularIconSize = 32.dp
val BigIconSize = 85.dp
val LargeIconSize = 148.dp
val PartLargeIconSize = 128.dp | 1 | Kotlin | 0 | 0 | 7c7964c70284d7c2537d6f3fd81fdd1dd9906f8b | 427 | MonoWeather | MIT License |
packages/library-base/src/commonMain/kotlin/io/realm/kotlin/schema/RealmClassKind.kt | realm | 235,075,339 | false | {"Kotlin": 4564631, "C++": 126122, "SWIG": 26070, "Shell": 23822, "C": 5126, "CMake": 2858, "Ruby": 1586, "Java": 1470} | /*
* Copyright 2023 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.kotlin.schema
/**
* Enum describing what kind of Realm object it is.
*/
public enum class RealmClassKind {
/**
* Standard Realm objects are the default kind of object in Realm, and they extend the
* [io.realm.kotlin.types.RealmObject] interface.
*/
STANDARD,
/**
* Embedded Realm objects extend the [io.realm.kotlin.types.EmbeddedRealmObject] interface.
*
* These kinds of classes must always have exactly one parent object when added to a realm. This
* means they are deleted when the parent object is delete or the embedded object property is
* overwritten.
*
* See [io.realm.kotlin.types.EmbeddedRealmObject] for more details.
*/
EMBEDDED,
/**
* Asymmetric Realm objects extend the [io.realm.kotlin.types.mongodb.AsymmetricRealmObject] interface.
*
* These kind of classes can only be used in a synced realm and are "write-only", i.e. once
* you written an asymmetric object to a Realm, it is no longer possible access or query them.
*
* See [io.realm.kotlin.types.mongodb.AsymmetricRealmObject] for more details.
*/
ASYMMETRIC
}
| 243 | Kotlin | 57 | 942 | 50797be5a0dfde9b4eb5c00a528c04b49d5706d6 | 1,758 | realm-kotlin | Apache License 2.0 |
app/src/main/java/com/cobresun/brun/pantsorshorts/MainActivity.kt | Cobresun | 144,660,254 | false | null | /**
* PANTS OR SHORTS
*
* App that informs the user whether or not they should wear pants because it is cold,
* or shorts if it is hot, depending on the weather of the user's city, based on user preference.
*
* Produced by Brian Norman and Sunny Nagam
* Cobresun - August 2018
*/
package com.cobresun.brun.pantsorshorts
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.location.Location
import android.net.ConnectivityManager
import android.net.Network
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.livedata.observeAsState
import androidx.core.content.ContextCompat
import com.cobresun.brun.pantsorshorts.location.Locator
import com.google.android.gms.location.*
import com.google.android.gms.tasks.Task
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject
lateinit var connectivityManager: ConnectivityManager
@Inject
lateinit var fusedLocationClient: FusedLocationProviderClient
@Inject
lateinit var locator: Locator
private lateinit var networkCallback: ConnectivityManager.NetworkCallback
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
EntryView(
isLoading = viewModel.isLoading.observeAsState(true),
cityName = viewModel.cityName.observeAsState(),
currentTemp = viewModel.currentTemp.observeAsState(),
highTemp = viewModel.highTemp.observeAsState(),
lowTemp = viewModel.lowTemp.observeAsState(),
clothing = viewModel.clothingSuggestion.observeAsState(),
mainButtonCallback = { viewModel.calibrateThreshold() },
toggleTemperatureUnitCallback = { viewModel.toggleTemperatureUnit() }
)
}
networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
createLocationRequest()
}
override fun onLost(network: Network) {
Toast.makeText(
applicationContext,
getString(R.string.no_internet),
Toast.LENGTH_SHORT
).show()
}
override fun onUnavailable() {
Toast.makeText(
applicationContext,
R.string.internet_unavailable,
Toast.LENGTH_SHORT
).show()
}
}
}
override fun onResume() {
super.onResume()
connectivityManager.registerDefaultNetworkCallback(networkCallback)
}
override fun onPause() {
super.onPause()
connectivityManager.unregisterNetworkCallback(networkCallback)
}
fun createLocationRequest() {
val locationRequest = LocationRequest.create().apply {
interval = 10000
fastestInterval = 5000
}
val builder = LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest)
val client: SettingsClient = LocationServices.getSettingsClient(this)
val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build())
task.addOnSuccessListener {
handleLocationSettingsResponse()
}
}
@SuppressLint("MissingPermission")
private fun handleLocationSettingsResponse() {
if (!isLocationPermissionGranted()) {
return
}
fusedLocationClient.lastLocation
.addOnSuccessListener { location ->
location?.let {
handleLocation(location)
} ?: showLocationNotFoundMessage()
}
}
private fun isLocationPermissionGranted(): Boolean {
return ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
private fun handleLocation(location: Location) {
val city = locator.getCityName(location)
city?.let { viewModel.setCityName(city) }
when {
viewModel.shouldFetchWeather() -> fetchWeather(location)
else -> viewModel.loadAndDisplayPreviousData()
}
}
private fun fetchWeather(location: Location) {
CoroutineScope(Dispatchers.Main).launch {
viewModel.fetchWeather(location.latitude, location.longitude)
viewModel.writeAndDisplayNewData()
}
}
private fun showLocationNotFoundMessage() {
Toast.makeText(
applicationContext,
getString(R.string.location_not_found),
Toast.LENGTH_LONG
).show()
}
}
| 7 | Kotlin | 0 | 6 | 2d0f44294aff95b7eeeefd20a998462ee9539ac3 | 5,192 | PantsOrShorts | MIT License |
backend/src/apiTest/kotlin/metrik/fixtures/MultiPipelineFixtureData.kt | thoughtworks | 351,856,572 | false | null | package metrik.fixtures
import metrik.project.domain.model.Commit
import metrik.project.domain.model.Execution
import metrik.project.domain.model.PipelineConfiguration
import metrik.project.domain.model.PipelineType
import metrik.project.domain.model.Stage
import metrik.project.domain.model.Status
val multiPipeline1 = PipelineConfiguration(
id = "600a701221048076f92c4e43",
projectId = "<KEY>",
name = "multiPipeline1",
username = "E9fnMY3UGE6Oms35JzLGgQ==",
credential = "FVSR/5o1BYh6dJQBeQaNvQ==",
url = "http://localhost:8001/job/4km-multi-pipeline-test-1/",
type = PipelineType.JENKINS
)
val multiPipeline2 = PipelineConfiguration(
id = "601a2f129deac2220dd07570",
projectId = "<KEY>",
name = "multiPipeline2",
username = "E9fnMY3UGE6Oms35JzLGgQ==",
credential = "FVSR/5o1BYh6dJQBeQaNvQ==",
url = "http://localhost:8001/job/4km-multi-pipeline-test-2/",
type = PipelineType.JENKINS
)
val multiPipelineExecution1 = Execution(
pipelineId = "600a701221048076f92c4e43",
number = 1,
duration = 621278,
result = Status.FAILED,
timestamp = 1578281700000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578281700100,
durationMillis = 286484,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to DEV",
startTimeMillis = 1578281986684,
durationMillis = 22294,
pauseDurationMillis = 0
),
Stage(
status = Status.FAILED,
name = "Deploy to UAT",
startTimeMillis = 1578282009078,
durationMillis = 300119,
pauseDurationMillis = 299981
)
),
changeSets = listOf(
Commit(
commitId = "<PASSWORD>",
timestamp = 1578281400000,
date = "2021-01-6 00:00:00 +0800"
)
)
)
val multiPipelineExecution2 = Execution(
pipelineId = "600a701221048076f92c4e43",
number = 2,
duration = 621278,
result = Status.FAILED,
timestamp = 1578353350000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578353400000,
durationMillis = 286484,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to DEV",
startTimeMillis = 1578353400100,
durationMillis = 22294,
pauseDurationMillis = 0
),
Stage(
status = Status.FAILED,
name = "Deploy to UAT",
startTimeMillis = 1578353422494,
durationMillis = 300119,
pauseDurationMillis = 299981
)
),
changeSets = listOf(
Commit(
commitId = "<PASSWORD>",
timestamp = 1578351600000,
date = "2021-01-7 00:00:00 +0800"
)
)
)
val multiPipelineExecution3 = Execution(
pipelineId = "600a701221048076f92c4e43",
number = 3,
duration = 621278,
result = Status.SUCCESS,
timestamp = 1578483000000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578483000100,
durationMillis = 1800000,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to DEV",
startTimeMillis = 1578484800200,
durationMillis = 22294,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to UAT",
startTimeMillis = 1578484822594,
durationMillis = 300119,
pauseDurationMillis = 299981
)
),
changeSets = listOf(
Commit(
commitId = "<PASSWORD>",
timestamp = 1578474000000,
date = "2021-01-8 00:00:00 +0800"
),
Commit(
commitId = "b9b775059d120a0dbf09fd40d2becea69a112543",
timestamp = 1578475800000,
date = "2021-01-8 00:00:00 +0800"
)
)
)
val multiPipelineExecution4 = Execution(
pipelineId = "600a701221048076f92c4e43",
number = 4,
duration = 621278,
result = Status.FAILED,
timestamp = 1578532200000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578532200100,
durationMillis = 286484,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to DEV",
startTimeMillis = 1578532486784,
durationMillis = 22294,
pauseDurationMillis = 0
),
Stage(
status = Status.FAILED,
name = "Deploy to UAT",
startTimeMillis = 1578532509178,
durationMillis = 300119,
pauseDurationMillis = 299981
)
),
changeSets = listOf(
Commit(
commitId = "b9b775059d120a0dbf09fd40d2becea69a112405",
timestamp = 1578531900000,
date = "2021-01-9 00:00:00 +0800"
)
)
)
val multiPipelineExecution5 = Execution(
pipelineId = "600a701221048076f92c4e43",
number = 5,
duration = 621278,
result = Status.OTHER,
timestamp = 1578618000000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578618000100,
durationMillis = 286484,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to DEV",
startTimeMillis = 1578618286684,
durationMillis = 22294,
pauseDurationMillis = 0
),
Stage(
status = Status.OTHER,
name = "Deploy to UAT",
startTimeMillis = 1578618309078,
durationMillis = 300119,
pauseDurationMillis = 299981
)
),
changeSets = listOf(
Commit(
commitId = "b9b775059d120a0dbf09fd40d2becea69a112405",
timestamp = 1578618000000,
date = "2021-01-10 00:00:00 +0800"
)
)
)
val multiPipelineExecution6 = Execution(
pipelineId = "600a701221048076f92c4e43",
number = 6,
duration = 40000,
result = Status.OTHER,
timestamp = 1578704400000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578704400100,
durationMillis = 30000,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to DEV",
startTimeMillis = 1578704430200,
durationMillis = 5000,
pauseDurationMillis = 0
),
Stage(
status = Status.OTHER,
name = "Deploy to UAT",
startTimeMillis = 1578704435300,
durationMillis = 5000,
pauseDurationMillis = 2000
)
),
changeSets = listOf(
Commit(
commitId = "b9b775059d120a0dbf09fd40d2becea69a112400",
timestamp = 1578700800000,
date = "2020-1-11 00:00:00 +0800"
)
)
)
val multiPipelineExecution7 = Execution(
pipelineId = "600a701221048076f92c4e43",
number = 7,
duration = 40000,
result = Status.SUCCESS,
timestamp = 1578783600000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578783600100,
durationMillis = 30000,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to DEV",
startTimeMillis = 1578783630200,
durationMillis = 5000,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to UAT",
startTimeMillis = 1578783635300,
durationMillis = 5000,
pauseDurationMillis = 2000
)
),
changeSets = listOf(
Commit(
commitId = "<PASSWORD>",
timestamp = 1578783600000,
date = "2020-1-12 00:00:00 +0800"
)
)
)
val multiPipelineExecution8 = Execution(
pipelineId = "600a701221048076f92c4e43",
number = 8,
duration = 40000,
result = Status.FAILED,
timestamp = 1578873600000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578873600100,
durationMillis = 30000,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to DEV",
startTimeMillis = 1578873630200,
durationMillis = 5000,
pauseDurationMillis = 0
),
Stage(
status = Status.FAILED,
name = "Deploy to UAT",
startTimeMillis = 1578873635300,
durationMillis = 5000,
pauseDurationMillis = 2000
)
),
changeSets = listOf(
Commit(
commitId = "<PASSWORD>",
timestamp = 1578870000000,
date = "2020-1-13 00:00:00 +0800"
)
)
)
val multiPipelineExecution9 = Execution(
pipelineId = "600a701221048076f92c4e43",
number = 9,
duration = 40000,
result = Status.SUCCESS,
timestamp = 1578963600000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578963600100,
durationMillis = 30000,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to DEV",
startTimeMillis = 1578963630200,
durationMillis = 5000,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to UAT",
startTimeMillis = 1578963635300,
durationMillis = 5000,
pauseDurationMillis = 2000
)
),
changeSets = listOf(
Commit(
commitId = "b9b775059d120a0dbf09fd40d2becea69a112400",
timestamp = 1578960000000,
date = "2020-1-14 00:00:00 +0800"
)
)
)
val multiPipelineExecution10 = Execution(
pipelineId = "601a2f129deac2220dd07570",
number = 10,
duration = 621278,
result = Status.FAILED,
timestamp = 1578281700000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578281700100,
durationMillis = 286484,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "API Test",
startTimeMillis = 1578281986684,
durationMillis = 22294,
pauseDurationMillis = 0
),
Stage(
status = Status.FAILED,
name = "Deploy to Staging",
startTimeMillis = 1578282009078,
durationMillis = 300119,
pauseDurationMillis = 299981
)
),
changeSets = listOf(
Commit(
commitId = "b9b775059d120a0dbf09fd40d2becea69a112348",
timestamp = 1578281400000,
date = "2021-01-6 00:00:00 +0800"
)
)
)
val multiPipelineExecution11 = Execution(
pipelineId = "601a2f129deac2220dd07570",
number = 11,
duration = 621278,
result = Status.FAILED,
timestamp = 1610672400000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578353400000,
durationMillis = 286484,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "API Test",
startTimeMillis = 1578353400100,
durationMillis = 22294,
pauseDurationMillis = 0
),
Stage(
status = Status.FAILED,
name = "Deploy to Staging",
startTimeMillis = 1578353422494,
durationMillis = 300119,
pauseDurationMillis = 299981
)
),
changeSets = listOf(
Commit(
commitId = "b9b775059d120a0dbf09fd40d2becea69a112405",
timestamp = 1578351600000,
date = "2021-01-7 00:00:00 +0800"
)
)
)
val multiPipelineExecution12 = Execution(
pipelineId = "601a2f129deac2220dd07570",
number = 12,
duration = 621278,
result = Status.SUCCESS,
timestamp = 1578483000000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578483000100,
durationMillis = 1800000,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "API Test",
startTimeMillis = 1578484800200,
durationMillis = 22294,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to Staging",
startTimeMillis = 1578484822594,
durationMillis = 300119,
pauseDurationMillis = 299981
)
),
changeSets = listOf(
Commit(
commitId = "<PASSWORD>",
timestamp = 1578474000000,
date = "2021-01-8 00:00:00 +0800"
),
Commit(
commitId = "b9b775059d120a0dbf09fd40d2becea69a112543",
timestamp = 1578475800000,
date = "2021-01-8 00:00:00 +0800"
)
)
)
val multiPipelineExecution13 = Execution(
pipelineId = "601a2f129deac2220dd07570",
number = 13,
duration = 621278,
result = Status.FAILED,
timestamp = 1578551400000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578551400100,
durationMillis = 286484,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "API Test",
startTimeMillis = 1578551686684,
durationMillis = 22294,
pauseDurationMillis = 0
),
Stage(
status = Status.FAILED,
name = "Deploy to Staging",
startTimeMillis = 1578551708998,
durationMillis = 300119,
pauseDurationMillis = 299981
)
),
changeSets = listOf(
Commit(
commitId = "b9b775059d120a0dbf09fd40d2becea69a112348",
timestamp = 1578547800000,
date = "2021-01-9 00:00:00 +0800"
)
)
)
val multiPipelineExecution14 = Execution(
pipelineId = "601a2f129deac2220dd07570",
number = 14,
duration = 621278,
result = Status.OTHER,
timestamp = 1578618000000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578618000100,
durationMillis = 286484,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "API Test",
startTimeMillis = 1578618286684,
durationMillis = 22294,
pauseDurationMillis = 0
),
Stage(
status = Status.OTHER,
name = "Deploy to Staging",
startTimeMillis = 1578618309078,
durationMillis = 300119,
pauseDurationMillis = 299981
)
),
changeSets = listOf(
Commit(
commitId = "b9b775059d120a0dbf09fd40d2becea69a112405",
timestamp = 1578618000000,
date = "2021-01-10 00:00:00 +0800"
)
)
)
val multiPipelineExecution15 = Execution(
pipelineId = "601a2f129deac2220dd07570",
number = 15,
duration = 40000,
result = Status.SUCCESS,
timestamp = 1578704400000,
url = "http://localhost:8001/job/4km-mttr/",
stages = listOf(
Stage(
status = Status.SUCCESS,
name = "build",
startTimeMillis = 1578704400100,
durationMillis = 30000,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "API Test",
startTimeMillis = 1578704430200,
durationMillis = 5000,
pauseDurationMillis = 0
),
Stage(
status = Status.SUCCESS,
name = "Deploy to Staging",
startTimeMillis = 1578704435300,
durationMillis = 5000,
pauseDurationMillis = 2000
)
),
changeSets = listOf(
Commit(
commitId = "b9b775059d120a0dbf09fd40d2becea69a112400",
timestamp = 1578700800000,
date = "2020-1-11 00:00:00 +0800"
)
)
)
val multiPipelineBuilds = listOf(
multiPipelineExecution1,
multiPipelineExecution2,
multiPipelineExecution3,
multiPipelineExecution4,
multiPipelineExecution5,
multiPipelineExecution6,
multiPipelineExecution7,
multiPipelineExecution8,
multiPipelineExecution9,
multiPipelineExecution10,
multiPipelineExecution11,
multiPipelineExecution12,
multiPipelineExecution13,
multiPipelineExecution14,
multiPipelineExecution15
)
| 19 | null | 86 | 348 | def6a52cb7339f6a422451710083177b9c79689a | 18,339 | metrik | MIT License |
app/src/main/java/com/enecuum/app/utils/IconGenerator.kt | Enecuum | 334,141,314 | false | null | package com.enecuum.app.utils
import android.content.Context
import android.graphics.Bitmap
import com.enecuum.app.extensions.invert
object IconGenerator {
fun generate(context: Context, data: String, destWidthRes: Int): Bitmap? {
val identicon = IdenticonGenerator.generate(data.toLowerCase())
val destWidth = context.resources.getDimension(destWidthRes).toInt()
return Bitmap.createScaledBitmap(identicon, destWidth, destWidth, false).invert()
}
} | 0 | Kotlin | 1 | 0 | f684608e30373068d7d94566606c5c4530f184f1 | 483 | android-slim-app | MIT License |
mulighetsrommet-api/src/test/kotlin/no/nav/mulighetsrommet/api/services/SsbNusServiceTest.kt | navikt | 435,813,834 | false | {"Kotlin": 1403251, "TypeScript": 1245645, "SCSS": 42691, "JavaScript": 22644, "PLpgSQL": 12960, "HTML": 2287, "Dockerfile": 1190, "CSS": 421, "Shell": 396} | package no.nav.mulighetsrommet.api.services
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.equals.shouldBeEqual
import io.mockk.mockk
import kotliquery.queryOf
import no.nav.mulighetsrommet.api.clients.ssb.ClassificationItem
import no.nav.mulighetsrommet.api.clients.ssb.SsbNusClient
import no.nav.mulighetsrommet.api.clients.ssb.SsbNusData
import no.nav.mulighetsrommet.api.createDatabaseTestConfig
import no.nav.mulighetsrommet.api.fixtures.MulighetsrommetTestDomain
import no.nav.mulighetsrommet.api.repositories.NusElement
import no.nav.mulighetsrommet.api.repositories.SsbNusRepository
import no.nav.mulighetsrommet.database.kotest.extensions.FlywayDatabaseTestListener
import no.nav.mulighetsrommet.domain.Tiltakskode
import org.intellij.lang.annotations.Language
class SsbNusServiceTest : FunSpec(
{
val database = extension(FlywayDatabaseTestListener(createDatabaseTestConfig()))
context("SsbNusService") {
val client: SsbNusClient = mockk(relaxed = true)
val repository = SsbNusRepository(database.db)
val service = SsbNusService(client, repository)
val domain = MulighetsrommetTestDomain()
beforeEach {
domain.initialize(database.db)
repository.upsert(
data = SsbNusData(
validFrom = "",
classificationItems = listOf(
ClassificationItem(
code = "3",
parentCode = null,
level = "1",
name = "Videregående, grunnutdanning",
),
ClassificationItem(
code = "30",
parentCode = "3",
level = "2",
name = "Allmenne fag",
),
ClassificationItem(
code = "31",
parentCode = "3",
level = "2",
name = "Humanistiske og estetiske fag",
),
ClassificationItem(
code = "32",
parentCode = "3",
level = "2",
name = "Lærerutdanninger og utdanninger i pedagogikk",
),
ClassificationItem(
code = "35",
parentCode = "3",
level = "2",
name = "Naturvitenskapelige fag, håndverksfag og tekniske fag",
),
ClassificationItem(
code = "355",
parentCode = "35",
level = "4",
name = "Utdanninger i elektrofag, mekaniske fag og maskinfag",
),
ClassificationItem(
code = "3551",
parentCode = "355",
level = "4",
name = "Elektro",
),
ClassificationItem(
code = "3552",
parentCode = "355",
level = "4",
name = "Mekaniske fag",
),
ClassificationItem(
code = "357",
parentCode = "35",
level = "4",
name = "Bygg- og anleggsfag",
),
ClassificationItem(
code = "3571",
parentCode = "357",
level = "4",
name = "Bygg og anlegg",
),
ClassificationItem(
code = "4",
parentCode = null,
level = "1",
name = "Videregående, avsluttende utdanning",
),
ClassificationItem(
code = "40",
parentCode = "4",
level = "2",
name = "Allmenne fag",
),
ClassificationItem(
code = "41",
parentCode = "4",
level = "2",
name = "Humanistiske og estetiske fag",
),
ClassificationItem(
code = "42",
parentCode = "4",
level = "2",
name = "Lærerutdanninger og utdanninger i pedagogikk",
),
ClassificationItem(
code = "45",
parentCode = "4",
level = "2",
name = "Naturvitenskapelige fag, håndverksfag og tekniske fag",
),
ClassificationItem(
code = "455",
parentCode = "45",
level = "4",
name = "Utdanninger i elektrofag, mekaniske fag og maskinfag",
),
ClassificationItem(
code = "4551",
parentCode = "455",
level = "4",
name = "Elektro",
),
ClassificationItem(
code = "4552",
parentCode = "455",
level = "4",
name = "Mekaniske fag",
),
ClassificationItem(
code = "457",
parentCode = "45",
level = "4",
name = "Bygg- og anleggsfag",
),
ClassificationItem(
code = "4571",
parentCode = "457",
level = "4",
name = "Bygg og anlegg",
),
),
),
version = "2437",
)
@Language("PostgreSQL")
val query = """
insert into tiltakstype_nus_kodeverk(tiltakskode, code, version)
values
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '3', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '30', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '31', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '32', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '35', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '3551', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '3552', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '3571', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '4', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '40', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '41', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '42', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '45', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '4551', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '4552', '2437'),
('GRUPPE_FAG_OG_YRKESOPPLAERING'::tiltakskode, '4571', '2437')
""".trimIndent()
database.db.run(queryOf(query).asExecute)
}
test("getData skal returnere korrekt format på dataene") {
val result = service.getNusData(Tiltakskode.GRUPPE_FAG_OG_YRKESOPPLAERING, "2437")
result shouldBeEqual NusDataResponse(
data = listOf(
NusData(
nivaa = "Videregående, grunnutdanning",
kategorier = listOf(
createNusElement("30", "Allmenne fag", "3", "2"),
createNusElement(
"31",
"Humanistiske og estetiske fag",
"3",
"2",
),
createNusElement(
"32",
"Lærerutdanninger og utdanninger i pedagogikk",
"3",
"2",
),
createNusElement(
"35",
"Naturvitenskapelige fag, håndverksfag og tekniske fag",
"3",
"2",
),
createNusElement("3551", "Elektro", "355", "4"),
createNusElement("3552", "Mekaniske fag", "355", "4"),
createNusElement("3571", "Bygg og anlegg", "357", "4"),
),
),
NusData(
nivaa = "Videregående, avsluttende utdanning",
kategorier = listOf(
createNusElement("40", "Allmenne fag", "4", "2"),
createNusElement(
"41",
"Humanistiske og estetiske fag",
"4",
"2",
),
createNusElement(
"42",
"Lærerutdanninger og utdanninger i pedagogikk",
"4",
"2",
),
createNusElement(
"45",
"Naturvitenskapelige fag, håndverksfag og tekniske fag",
"4",
"2",
),
createNusElement("4551", "Elektro", "455", "4"),
createNusElement("4552", "Mekaniske fag", "455", "4"),
createNusElement("4571", "Bygg og anlegg", "457", "4"),
),
),
),
)
}
}
},
)
private fun createNusElement(code: String, name: String, parent: String, level: String): NusElement {
return NusElement(
tiltakskode = Tiltakskode.GRUPPE_FAG_OG_YRKESOPPLAERING,
code = code,
version = "2437",
name = name,
parent = parent,
level = level,
)
}
| 8 | Kotlin | 1 | 5 | 097910be922941e5d51add61893dae6e271bd747 | 12,341 | mulighetsrommet | MIT License |
core/src/main/kotlin/com/fibelatti/core/extension/SDKVersionChecks.kt | fibelatti | 158,119,258 | false | null | package com.fibelatti.core.extension
import android.os.Build
fun isLollipopOrLater(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
inline fun inLollipopOrLater(body: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) body()
}
fun isLollipopMr1OrLater(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1
inline fun inLollipopMr1OrLater(body: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) body()
}
fun isMarshmallowOrLater(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
inline fun inMarshmallowOrLater(body: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) body()
}
fun isNougatOrLater(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
inline fun inNougatOrLater(body: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) body()
}
fun isNougatMr1OrLater(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1
inline fun inNougatMr1OrLater(body: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) body()
}
fun isOreoOrLater(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
inline fun inOreoOrLater(body: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) body()
}
fun isPieOrLater(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
inline fun inPieOrLater(body: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) body()
}
| 0 | Kotlin | 0 | 4 | 8689cb557e91c9ac4809ab1820bf6f257d96711f | 1,484 | fibelatti-core | Apache License 2.0 |
bruig/flutterui/plugin/android/src/main/kotlin/org/bisonrelay/golib_plugin/GolibPlugin.kt | companyzero | 577,336,758 | false | {"Go": 2029675, "Dart": 1008980, "C++": 50442, "CMake": 35309, "Swift": 7945, "Ruby": 7138, "Kotlin": 5023, "C": 4033, "HTML": 3683, "Shell": 3501, "Objective-C": 723, "Java": 670} | package org.bisonrelay.golib_plugin
import androidx.annotation.NonNull
import golib.Golib
import io.flutter.embedding.engine.plugins.FlutterPlugin
import android.os.Handler
import android.os.Looper
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
/** GolibPlugin */
class GolibPlugin: FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel : MethodChannel
private val executorService: ExecutorService = Executors.newFixedThreadPool(2)
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "golib_plugin")
channel.setMethodCallHandler(this)
this.initReadStream(flutterPluginBinding)
this.initCmdResultLoop(flutterPluginBinding)
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else if (call.method == "hello") {
Golib.hello()
result.success(null);
} else if (call.method == "getURL") {
// Will perform a network access, so launch on separate coroutine.
val url: String? = call.argument("url");
executorService.execute {
val handler = Handler(Looper.getMainLooper())
try {
val res = Golib.getURL(url);
handler.post{ result.success(res) }
} catch (e: Exception) {
handler.post{ result.error(e::class.qualifiedName ?: "UnknownClass", e.toString(), null); }
}
}
} else if (call.method == "setTag") {
val tag: String? = call.argument("tag");
Golib.setTag(tag);
result.success(null);
} else if (call.method == "nextTime") {
val nt: String? = Golib.nextTime()
result.success(nt);
} else if (call.method == "writeStr") {
val s: String? = call.argument("s");
Golib.writeStr(s);
result.success(null);
} else if (call.method == "readStr") {
val s: String? = Golib.readStr()
result.success(s);
} else if (call.method == "asyncCall") {
val typ: Int = call.argument("typ") ?: 0
val id: Int = call.argument("id") ?: 0
val handle: Int = call.argument("handle") ?: 0
val payload: String? = call.argument("payload")
Golib.asyncCallStr(typ, id, handle, payload)
} else {
result.notImplemented()
}
}
fun initReadStream(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
val handler = Handler(Looper.getMainLooper())
val channel : EventChannel = EventChannel(flutterPluginBinding.binaryMessenger, "readStream")
var sink : EventChannel.EventSink? = null;
channel.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(listener: Any?, newSink: EventChannel.EventSink?) {
// TODO: support multiple readers?
sink = newSink;
}
override fun onCancel(listener: Any?) {
sink = null;
}
});
Golib.readLoop(object : golib.ReadLoopCB {
override fun f(msg: String) {
handler.post{ sink?.success(msg) }
}
})
}
fun initCmdResultLoop(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
val handler = Handler(Looper.getMainLooper())
val channel : EventChannel = EventChannel(flutterPluginBinding.binaryMessenger, "cmdResultLoop")
var sink : EventChannel.EventSink? = null;
channel.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(listener: Any?, newSink: EventChannel.EventSink?) {
// TODO: support multiple readers?
sink = newSink;
}
override fun onCancel(listener: Any?) {
sink = null;
}
});
Golib.cmdResultLoop(object : golib.CmdResultLoopCB {
override fun f(id: Int, typ: Int, payload: String, err: String) {
val res: Map<String,Any> = mapOf("id" to id, "type" to typ, "payload" to payload, "error" to err)
handler.post{ sink?.success(res) }
}
})
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
// TODO: stop readstream?
}
}
| 57 | Go | 11 | 29 | 3d4adcbece569fd3d1822f7b594c24ca53ce4792 | 4,761 | bisonrelay | ISC License |
milkyway-bsky/src/main/kotlin/com/milkcocoa/info/milkyway/models/bsky/record/feed/ThreadGateRecord.kt | milkcocoa0902 | 777,786,753 | false | {"Kotlin": 269361} | package com.milkcocoa.info.milkyway.models.bsky.record.feed
import com.milkcocoa.info.milkyway.models.Record
import com.milkcocoa.info.milkyway.models.bsky.feed.threadgate.GateRule
import com.milkcocoa.info.milkyway.types.BskyRecordType
import com.milkcocoa.info.milkyway.util.DateTimeSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.time.LocalDateTime
@SerialName("app.bsky.feed.threadgate")
@Serializable
data class ThreadGateRecord(
val allow: List<GateRule>,
@Serializable(with = DateTimeSerializer::class)
val createdAt: LocalDateTime,
val post: String
) : Record<BskyRecordType> {
override val type: BskyRecordType
get() = BskyRecordType.ThreadGateRecord
} | 0 | Kotlin | 0 | 0 | b1a215337f7dc18bca8b7bf69a6fc5b16937df9c | 748 | Milkyway | MIT License |
buildSrc/src/main/java/io/github/quantones/harpocrate/jnisecret/utils/GitIgnoreUtils.kt | Quantones | 433,165,854 | false | {"Kotlin": 26924} | package io.github.quantones.harpocrate.jnisecret.utils
import org.gradle.api.Project
import java.io.File
object GitIgnoreUtils {
const val GITIGNORE_FILENAME = ".gitignore"
const val GITINGORE_CPP = "*.cpp"
const val GITIGNORE_CMAKELISTS = Config.CMAKE_FILENAME
fun setGitIgnore(path: String, content: String) {
val file = File(path, GITIGNORE_FILENAME)
if(file.exists()) {
val fileContent = file.readText()
if(!fileContent.contains(content)) {
file.appendText("\n$content")
}
} else {
file.writeText(content)
file.createNewFile()
}
}
fun addToProjectGitIgnore(project: Project, toAdd: String, create: Boolean = true) {
val file = File("${project.projectDir}", GITIGNORE_FILENAME)
if(!file.exists() && create) {
file.createNewFile()
} else if(!file.exists() && !create) {
return
}
val content = file.readText()
if(!content.contains(toAdd)) {
file.appendText("\n$toAdd")
}
}
} | 0 | Kotlin | 1 | 3 | 253e0fa806c1e95a993d979162a462cb6c2f6b39 | 1,111 | JniSecret | MIT License |
lib/sisyphus-protobuf/src/main/kotlin/com/bybutter/sisyphus/protobuf/dynamic/DynamicField.kt | ButterCam | 264,589,207 | false | null | package com.bybutter.sisyphus.protobuf.dynamic
import com.bybutter.sisyphus.protobuf.EnumSupport
import com.bybutter.sisyphus.protobuf.Message
import com.bybutter.sisyphus.protobuf.MessageSupport
import com.bybutter.sisyphus.protobuf.ProtoEnum
import com.bybutter.sisyphus.protobuf.ProtoReflection
import com.bybutter.sisyphus.protobuf.coded.Reader
import com.bybutter.sisyphus.protobuf.coded.WireType
import com.bybutter.sisyphus.protobuf.coded.Writer
import com.bybutter.sisyphus.protobuf.findEnumSupport
import com.bybutter.sisyphus.protobuf.findMessageSupport
import com.bybutter.sisyphus.protobuf.primitives.FieldDescriptorProto
interface DynamicField<T> {
fun descriptor(): FieldDescriptorProto
fun writeTo(writer: Writer)
fun get(): T
fun set(value: T)
fun has(): Boolean
fun clear(): T?
fun read(reader: Reader, field: Int, wire: Int)
override fun hashCode(): Int
override fun equals(other: Any?): Boolean
companion object {
operator fun invoke(message: DynamicMessageSupport, descriptor: FieldDescriptorProto): DynamicField<*> {
return if (descriptor.label == FieldDescriptorProto.Label.REPEATED) {
when (descriptor.type) {
FieldDescriptorProto.Type.DOUBLE -> RepeatedDoubleDynamicField(descriptor)
FieldDescriptorProto.Type.FLOAT -> RepeatedFloatDynamicField(descriptor)
FieldDescriptorProto.Type.INT64 -> RepeatedInt64DynamicField(descriptor)
FieldDescriptorProto.Type.UINT64 -> RepeatedUInt64DynamicField(descriptor)
FieldDescriptorProto.Type.INT32 -> RepeatedInt32DynamicField(descriptor)
FieldDescriptorProto.Type.FIXED64 -> RepeatedFixed64DynamicField(descriptor)
FieldDescriptorProto.Type.FIXED32 -> RepeatedFixed32DynamicField(descriptor)
FieldDescriptorProto.Type.BOOL -> RepeatedBooleanDynamicField(descriptor)
FieldDescriptorProto.Type.STRING -> RepeatedStringDynamicField(descriptor)
FieldDescriptorProto.Type.GROUP -> TODO()
FieldDescriptorProto.Type.MESSAGE -> RepeatedMessageDynamicField<Message<*, *>>(
descriptor
)
FieldDescriptorProto.Type.BYTES -> RepeatedBytesDynamicField(descriptor)
FieldDescriptorProto.Type.UINT32 -> RepeatedUInt32DynamicField(descriptor)
FieldDescriptorProto.Type.ENUM -> RepeatedEnumDynamicField<ProtoEnum<*>>(
descriptor
)
FieldDescriptorProto.Type.SFIXED32 -> RepeatedSFixed32DynamicField(descriptor)
FieldDescriptorProto.Type.SFIXED64 -> RepeatedSFixed64DynamicField(descriptor)
FieldDescriptorProto.Type.SINT32 -> RepeatedSInt32DynamicField(descriptor)
FieldDescriptorProto.Type.SINT64 -> RepeatedSInt64DynamicField(descriptor)
}
} else {
when (descriptor.type) {
FieldDescriptorProto.Type.DOUBLE -> DoubleDynamicField(descriptor)
FieldDescriptorProto.Type.FLOAT -> FloatDynamicField(descriptor)
FieldDescriptorProto.Type.INT64 -> Int64DynamicField(descriptor)
FieldDescriptorProto.Type.UINT64 -> UInt64DynamicField(descriptor)
FieldDescriptorProto.Type.INT32 -> Int32DynamicField(descriptor)
FieldDescriptorProto.Type.FIXED64 -> Fixed64DynamicField(descriptor)
FieldDescriptorProto.Type.FIXED32 -> Fixed32DynamicField(descriptor)
FieldDescriptorProto.Type.BOOL -> BooleanDynamicField(descriptor)
FieldDescriptorProto.Type.STRING -> StringDynamicField(descriptor)
FieldDescriptorProto.Type.GROUP -> TODO()
FieldDescriptorProto.Type.MESSAGE -> MessageDynamicField<Message<*, *>>(
descriptor
)
FieldDescriptorProto.Type.BYTES -> BytesDynamicField(descriptor)
FieldDescriptorProto.Type.UINT32 -> UInt32DynamicField(descriptor)
FieldDescriptorProto.Type.ENUM -> EnumDynamicField<ProtoEnum<*>>(descriptor)
FieldDescriptorProto.Type.SFIXED32 -> SFixed32DynamicField(descriptor)
FieldDescriptorProto.Type.SFIXED64 -> SFixed64DynamicField(descriptor)
FieldDescriptorProto.Type.SINT32 -> SInt32DynamicField(descriptor)
FieldDescriptorProto.Type.SINT64 -> SInt64DynamicField(descriptor)
}
}
}
}
}
class DoubleDynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<Double>(descriptor) {
override var value: Double = defaultValue()
override fun defaultValue(): Double {
return 0.0
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.FIXED64)
.double(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED64.ordinal) {
set(reader.double())
}
}
}
class RepeatedDoubleDynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<Double>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.FIXED64)
.double(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED64.ordinal) {
get() += reader.double()
}
}
}
class FloatDynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<Float>(descriptor) {
override var value: Float = defaultValue()
override fun defaultValue(): Float {
return 0.0f
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.FIXED32)
.float(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED32.ordinal) {
set(reader.float())
}
}
}
class RepeatedFloatDynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<Float>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.FIXED32)
.float(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED32.ordinal) {
get() += reader.float()
}
}
}
class Int64DynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<Long>(descriptor) {
override var value: Long = defaultValue()
override fun defaultValue(): Long {
return 0
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.VARINT)
.int64(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.VARINT.ordinal) {
set(reader.int64())
}
}
}
class RepeatedInt64DynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<Long>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.VARINT)
.int64(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
reader.packed(wire) {
get() += reader.int64()
}
}
}
class UInt64DynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<ULong>(descriptor) {
override var value: ULong = defaultValue()
override fun defaultValue(): ULong {
return 0UL
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.VARINT)
.uint64(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.VARINT.ordinal) {
set(reader.uint64())
}
}
}
class RepeatedUInt64DynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<ULong>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.VARINT)
.uint64(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
reader.packed(wire) {
get() += reader.uint64()
}
}
}
class Int32DynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<Int>(descriptor) {
override var value: Int = defaultValue()
override fun defaultValue(): Int {
return 0
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.VARINT)
.int32(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.VARINT.ordinal) {
set(reader.int32())
}
}
}
class RepeatedInt32DynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<Int>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.VARINT)
.int32(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
reader.packed(wire) {
get() += reader.int32()
}
}
}
class Fixed64DynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<ULong>(descriptor) {
override var value: ULong = defaultValue()
override fun defaultValue(): ULong {
return 0UL
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.FIXED64)
.fixed64(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED64.ordinal) {
set(reader.fixed64())
}
}
}
class RepeatedFixed64DynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<ULong>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.FIXED64)
.fixed64(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED64.ordinal) {
get() += reader.fixed64()
}
}
}
class Fixed32DynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<UInt>(descriptor) {
override var value: UInt = defaultValue()
override fun defaultValue(): UInt {
return 0U
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.FIXED32)
.fixed32(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED32.ordinal) {
set(reader.fixed32())
}
}
}
class RepeatedFixed32DynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<UInt>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.FIXED32)
.fixed32(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED32.ordinal) {
get() += reader.fixed32()
}
}
}
class BooleanDynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<Boolean>(descriptor) {
override var value: Boolean = defaultValue()
override fun defaultValue(): Boolean {
return false
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.VARINT)
.bool(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.VARINT.ordinal) {
set(reader.bool())
}
}
}
class RepeatedBooleanDynamicField(descriptor: FieldDescriptorProto) :
AbstractRepeatedDynamicField<Boolean>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.VARINT)
.bool(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.VARINT.ordinal) {
get() += reader.bool()
}
}
}
class StringDynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<String>(descriptor) {
override var value: String = defaultValue()
override fun defaultValue(): String {
return ""
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.LENGTH_DELIMITED)
.string(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.LENGTH_DELIMITED.ordinal) {
set(reader.string())
}
}
}
class RepeatedStringDynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<String>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.LENGTH_DELIMITED)
.string(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.LENGTH_DELIMITED.ordinal) {
get() += reader.string()
}
}
}
class BytesDynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<ByteArray>(descriptor) {
override var value: ByteArray = defaultValue()
override fun defaultValue(): ByteArray {
return byteArrayOf()
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.LENGTH_DELIMITED)
.bytes(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.VARINT.ordinal) {
set(reader.bytes())
}
}
}
class RepeatedBytesDynamicField(descriptor: FieldDescriptorProto) :
AbstractRepeatedDynamicField<ByteArray>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.LENGTH_DELIMITED)
.bytes(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.LENGTH_DELIMITED.ordinal) {
get() += reader.bytes()
}
}
}
class UInt32DynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<UInt>(descriptor) {
override var value: UInt = defaultValue()
override fun defaultValue(): UInt {
return 0U
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.VARINT)
.uint32(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.VARINT.ordinal) {
set(reader.uint32())
}
}
}
class RepeatedUInt32DynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<UInt>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.VARINT)
.uint32(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
reader.packed(wire) {
get() += reader.uint32()
}
}
}
class SFixed64DynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<Long>(descriptor) {
override var value: Long = defaultValue()
override fun defaultValue(): Long {
return 0
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.FIXED64)
.sfixed64(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED64.ordinal) {
set(reader.sfixed64())
}
}
}
class RepeatedSFixed64DynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<Long>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.FIXED64)
.sfixed64(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED64.ordinal) {
get() += reader.sfixed64()
}
}
}
class SFixed32DynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<Int>(descriptor) {
override var value: Int = defaultValue()
override fun defaultValue(): Int {
return 0
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.FIXED32)
.sfixed32(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED32.ordinal) {
set(reader.sfixed32())
}
}
}
class RepeatedSFixed32DynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<Int>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.FIXED32)
.sfixed32(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.FIXED32.ordinal) {
get() += reader.sfixed32()
}
}
}
class SInt64DynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<Long>(descriptor) {
override var value: Long = defaultValue()
override fun defaultValue(): Long {
return 0
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.VARINT)
.sint64(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.VARINT.ordinal) {
set(reader.sint64())
}
}
}
class RepeatedSInt64DynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<Long>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.VARINT)
.sint64(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
reader.packed(wire) {
get() += reader.sint64()
}
}
}
class SInt32DynamicField(descriptor: FieldDescriptorProto) : AbstractDynamicField<Int>(descriptor) {
override var value: Int = defaultValue()
override fun defaultValue(): Int {
return 0
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.VARINT)
.sint32(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.VARINT.ordinal) {
set(reader.sint32())
}
}
}
class RepeatedSInt32DynamicField(descriptor: FieldDescriptorProto) : AbstractRepeatedDynamicField<Int>(descriptor) {
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.VARINT)
.sint32(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
reader.packed(wire) {
get() += reader.sint32()
}
}
}
class EnumDynamicField<T : ProtoEnum<T>>(
descriptor: FieldDescriptorProto
) : AbstractDynamicField<T>(descriptor) {
private val support = ProtoReflection.findEnumSupport(descriptor().typeName) as EnumSupport<T>
override var value: T = defaultValue()
override fun defaultValue(): T {
return support()
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.VARINT)
.enum(get())
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.VARINT.ordinal) {
set(support(reader.int32()))
}
}
}
class RepeatedEnumDynamicField<T : ProtoEnum<T>>(
descriptor: FieldDescriptorProto
) : AbstractRepeatedDynamicField<T>(descriptor) {
private val support = ProtoReflection.findEnumSupport(descriptor().typeName) as EnumSupport<T>
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.VARINT)
.enum(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
reader.packed(wire) {
get() += support(reader.int32())
}
}
}
class MessageDynamicField<T : Message<T, *>>(
descriptor: FieldDescriptorProto
) : AbstractDynamicField<T?>(descriptor) {
private val support = ProtoReflection.findMessageSupport(descriptor().typeName) as MessageSupport<T, *>
override var value: T? = defaultValue()
override fun defaultValue(): T? {
return null
}
override fun writeTo(writer: Writer) {
if (has()) {
writer.tag(descriptor().number, WireType.LENGTH_DELIMITED)
.message(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.LENGTH_DELIMITED.ordinal) {
set(support.parse(reader, reader.int32()))
} else {
reader.skip(WireType.valueOf(wire))
}
}
}
class RepeatedMessageDynamicField<T : Message<T, *>>(
descriptor: FieldDescriptorProto
) : AbstractRepeatedDynamicField<T>(descriptor) {
private val support = ProtoReflection.findMessageSupport(descriptor().typeName) as MessageSupport<T, *>
override fun writeTo(writer: Writer) {
for (value in get()) {
writer.tag(descriptor().number, WireType.LENGTH_DELIMITED)
.message(value)
}
}
override fun read(reader: Reader, field: Int, wire: Int) {
if (wire == WireType.LENGTH_DELIMITED.ordinal) {
get() += support.parse(reader, reader.int32())
} else {
reader.skip(WireType.valueOf(wire))
}
}
}
| 11 | null | 11 | 56 | cc78b3e077dc0d02166794b83bfcd89ed70c396d | 22,818 | sisyphus | MIT License |
app/src/main/java/com/jskako/githubrepobrowser/presentation/main/components/ProfilePictureComposable.kt | jskako | 546,837,084 | false | null | package com.jskako.githubrepobrowser.presentation.main.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Card
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import coil.compose.rememberAsyncImagePainter
import androidx.compose.ui.unit.dp
import com.jskako.githubrepobrowser.R
import com.jskako.githubrepobrowser.domain.model.GithubRepository
@Composable
fun ProfilePictureComposable (
item: GithubRepository,
menuItems: List<String>,
onClickCallbacks: List<() -> Unit>,
) {
var showMenu by remember { mutableStateOf(false) }
Card(
shape = CircleShape,
border = BorderStroke(2.dp, color = Helper.getGreenColor()),
modifier = Modifier
.size(48.dp)
.padding(2.dp)
.clickable {
showMenu = true
},
) {
Image(
painter = rememberAsyncImagePainter(item.owner.avatar_url),
contentScale = ContentScale.Crop,
modifier = Modifier.size(48.dp),
contentDescription = stringResource(R.string.picture_holder_title)
)
}
PopupMenu(
menuItems = menuItems,
onClickCallbacks = onClickCallbacks,
showMenu = showMenu,
onDismiss = ({ showMenu = false })
)
} | 0 | Kotlin | 0 | 0 | 966de10bd68ef3b8b51b49fc9143bd27199c5d9a | 1,829 | GithubRepoBrowser | Apache License 2.0 |
core/src/main/kotlin/org/jetbrains/jewel/modifiers/Background.kt | JetBrains | 440,164,967 | false | null | package org.jetbrains.jewel.modifiers
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.DrawModifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.drawOutline
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.platform.InspectorInfo
import androidx.compose.ui.platform.InspectorValueInfo
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import org.jetbrains.jewel.components.ImageSlice
import org.jetbrains.jewel.components.ImageSliceValues
import org.jetbrains.jewel.shape.QuadRoundedCornerShape
import org.jetbrains.jewel.shape.addQuadRoundRect
fun Modifier.background(image: ImageBitmap, maintainAspect: Boolean = true): Modifier =
then(
DrawImageBackgroundModifier(
image,
maintainAspect,
debugInspectorInfo {
name = "background"
properties["image"] = image
}
)
)
fun Modifier.background(image: ImageBitmap, slices: ImageSliceValues): Modifier =
background(ImageSlice(image, slices))
fun Modifier.background(imageSlice: ImageSlice): Modifier =
then(
DrawImageSliceBackgroundModifier(
imageSlice,
debugInspectorInfo {
name = "background"
properties["image"] = imageSlice.image
properties["slices"] = imageSlice.slices
}
)
)
fun Modifier.background(
color: Color,
shape: Shape = RectangleShape
) = this.then(
Background(
color = color,
shape = shape,
inspectorInfo = debugInspectorInfo {
name = "background"
value = color
properties["color"] = color
properties["shape"] = shape
}
)
)
fun Modifier.background(
brush: Brush,
shape: Shape = RectangleShape
) = this.then(
Background(
brush = brush,
shape = shape,
inspectorInfo = debugInspectorInfo {
name = "background"
value = brush
properties["brush"] = brush
properties["shape"] = shape
}
)
)
private class Background constructor(
private val color: Color? = null,
private val brush: Brush? = null,
private val alpha: Float = 1.0f,
private val shape: Shape,
inspectorInfo: InspectorInfo.() -> Unit
) : DrawModifier, InspectorValueInfo(inspectorInfo) {
private var lastSize: Size? = null
private var lastLayoutDirection: LayoutDirection? = null
private var lastOutline: Outline? = null
override fun ContentDrawScope.draw() {
if (shape === RectangleShape) {
drawRect()
} else {
drawOutline()
}
drawContent()
}
private fun ContentDrawScope.drawRect() {
color?.let { drawRect(color = it) }
brush?.let { drawRect(brush = it, alpha = alpha) }
}
private fun ContentDrawScope.drawOutline() {
val outline =
if (size == lastSize && layoutDirection == lastLayoutDirection) {
lastOutline!!
} else {
shape.createOutline(size, layoutDirection, this)
}
if (outline is Outline.Rounded && shape is QuadRoundedCornerShape) {
val path = Path().apply {
addQuadRoundRect(outline.roundRect)
}
color?.let { drawPath(path, color = color) }
brush?.let { drawPath(path, brush = brush, alpha = alpha) }
} else {
color?.let { drawOutline(outline, color = color) }
brush?.let { drawOutline(outline, brush = brush, alpha = alpha) }
}
lastOutline = outline
lastSize = size
}
override fun hashCode(): Int {
var result = color?.hashCode() ?: 0
result = 31 * result + (brush?.hashCode() ?: 0)
result = 31 * result + alpha.hashCode()
result = 31 * result + shape.hashCode()
return result
}
override fun equals(other: Any?): Boolean {
val otherModifier = other as? Background ?: return false
return color == otherModifier.color &&
brush == otherModifier.brush &&
alpha == otherModifier.alpha &&
shape == otherModifier.shape
}
override fun toString(): String =
"Background(color=$color, brush=$brush, alpha=$alpha, shape=$shape)"
}
abstract class CustomBackgroundModifier(
inspectorInfo: InspectorInfo.() -> Unit
) : DrawModifier,
InspectorValueInfo(inspectorInfo) {
override fun ContentDrawScope.draw() {
drawBackground()
drawContent()
}
abstract fun DrawScope.drawBackground()
}
private class DrawImageBackgroundModifier(
val image: ImageBitmap,
val maintainAspect: Boolean,
inspectorInfo: InspectorInfo.() -> Unit
) : CustomBackgroundModifier(inspectorInfo) {
override fun DrawScope.drawBackground() {
val width = size.width.toInt()
val height = size.height.toInt()
if (maintainAspect) {
val imageWidth = image.width
val imageHeight = image.height
val imageAspect = imageWidth.toDouble() / imageHeight
val areaAspect = width.toDouble() / height
val srcWidth = if (imageAspect > areaAspect) (imageHeight * areaAspect).toInt() else imageWidth
val srcHeight = if (imageAspect < areaAspect) (imageWidth / areaAspect).toInt() else imageHeight
drawImage(image, srcSize = IntSize(srcWidth, srcHeight), dstSize = IntSize(width, height))
} else {
drawImage(image, dstSize = IntSize(width, height))
}
}
}
private class DrawImageSliceBackgroundModifier(
val imageSlice: ImageSlice,
inspectorInfo: InspectorInfo.() -> Unit
) : CustomBackgroundModifier(inspectorInfo) {
override fun DrawScope.drawBackground() = imageSlice.draw(this)
}
| 17 | Kotlin | 11 | 318 | 817adc042a029698983c9686d0f1497204bfdf14 | 6,376 | jewel | Apache License 2.0 |
core/ui/src/main/java/com/jerry/moneytracker/core/ui/component/CategoryGroupBox.kt | jchodev | 786,353,909 | false | {"Kotlin": 411089} | package com.jerry.moneytracker.core.ui.component
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import com.jerry.moneytracker.core.designsystem.theme.MoneyTrackerTheme
import com.jerry.moneytracker.core.designsystem.theme.dimens
import com.jerry.moneytracker.core.model.data.Category
import com.jerry.moneytracker.core.model.data.CategoryType
import com.jerry.moneytracker.core.model.data.TransactionType
import com.jerry.moneytracker.core.ui.ext.getColors
import com.jerry.moneytracker.core.ui.ext.getImageVector
import com.jerry.moneytracker.core.ui.ext.getString
import com.jerry.moneytracker.core.ui.preview.DevicePreviews
@Composable
fun CategoryGroupBox(
modifier: Modifier = Modifier.fillMaxWidth(),
transactionType: TransactionType = TransactionType.INCOME,
category: Category,
onCategorySelected: (Category) -> Unit = {}
){
OutlinedCard(
modifier = modifier
.fillMaxWidth()
//.background(color = Color.Green) // for testing
.padding(MaterialTheme.dimens.dimen16)
) {
//Main Category
Row (
modifier = Modifier
.fillMaxWidth()
.background(color = MaterialTheme.colorScheme.primaryContainer)
.padding(MaterialTheme.dimens.dimen16)
.clickable {
onCategorySelected.invoke(category)
},
verticalAlignment = Alignment.CenterVertically
) {
CategoryIcon(
size = MaterialTheme.dimens.dimen56,
icon = category.type.getImageVector(),
contentDescription = category.type.getString(),
bgColor = transactionType.getColors().second,
iconColor = transactionType.getColors().first
)
Spacer(modifier = Modifier.width(MaterialTheme.dimens.dimen16))
Text(
text = category.type.getString(),
style = MaterialTheme.typography.headlineSmall.copy(
color = MaterialTheme.colorScheme.onPrimaryContainer
),
textAlign = TextAlign.Center
)
}
//sub category
if (category.items.isNotEmpty()){
LazyRow(Modifier.padding(MaterialTheme.dimens.dimen16)) {
items(category.items.size) { index ->
val item = category.items[index]
CategoryItem(
bgColor = transactionType.getColors().second,
iconColor = transactionType.getColors().first,
category = item,
textColor = MaterialTheme.colorScheme.onTertiaryContainer,
onCategorySelected = onCategorySelected,
)
if (index < category.items.size - 1) {
Spacer(modifier = Modifier.width(MaterialTheme.dimens.dimen8))
}
}
}
}
}
}
@DevicePreviews
@Composable
private fun CategoryGroupPreview(){
MoneyTrackerTheme {
CategoryGroupBox(
category = Category(
type = CategoryType.FOOD_AND_BEVERAGES,
items = listOf(
Category(type = CategoryType.FOOD_AND_BEVERAGES),
Category(type = CategoryType.FOOD_AND_BEVERAGES),
Category(type = CategoryType.FOOD_AND_BEVERAGES),
)
),
)
}
}
@DevicePreviews
@Composable
private fun CategoryGroupSinglePreview(){
MoneyTrackerTheme {
CategoryGroupBox(
category = Category(
type = CategoryType.FOOD_AND_BEVERAGES
),
)
}
}
@DevicePreviews
@Composable //EXPENSES
private fun CategoryGroupExpensesPreview(){
MoneyTrackerTheme {
CategoryGroupBox(
transactionType = TransactionType.EXPENSES,
category = Category(
type = CategoryType.FOOD_AND_BEVERAGES,
items = listOf(
Category(type = CategoryType.FOOD_AND_BEVERAGES),
Category(type = CategoryType.FOOD_AND_BEVERAGES),
Category(type = CategoryType.FOOD_AND_BEVERAGES),
)
),
)
}
}
@DevicePreviews
@Composable
private fun CategoryGroupExpensesSinglePreview(){
MoneyTrackerTheme {
CategoryGroupBox(
transactionType = TransactionType.EXPENSES,
category = Category(
type = CategoryType.FOOD_AND_BEVERAGES
),
)
}
} | 0 | Kotlin | 0 | 0 | 9c8d64bd5c8683a73599365c366c7020005abd8e | 5,274 | money-tracker-android | MIT License |
src/main/kotlin/io/github/sununiq/response/Result.kt | Sitrone | 119,047,159 | false | null | package io.github.sununiq.response
import io.github.sununiq.request.Request
/**
* 结果集
* item : 结果
* requests : 结果页面解析出来的新的请求
*/
data class Result<T>(
val item: T,
val requests: ArrayList<Request<T>> = ArrayList<Request<T>>()
)
fun <T> Result<T>.addRequest(request: Request<T>) = this.requests.add(request)
fun <T> Result<T>.addRequests(requests: MutableList<Request<T>>) = requests.forEach { this.addRequest(it) } | 0 | Kotlin | 0 | 1 | d48182825d88b7805cfbc3dc9e932c5376e440bd | 437 | GooSpider | Apache License 2.0 |
app/src/main/java/com/concredito/clientes/model/RejectObservation.kt | FigueroaGit | 749,615,668 | false | {"Kotlin": 180223} | package com.concredito.clientes.model
import com.google.gson.annotations.SerializedName
data class RejectObservation(
@SerializedName("id")
val id: String,
@SerializedName("observaciones")
val observations: String,
@SerializedName("prospectoId")
val prospectId: String,
)
| 0 | Kotlin | 0 | 0 | 92ce5c3f0c2f9990fd2daff3ab083bfdd028f761 | 298 | ClientesProspectos | Apache License 2.0 |
src/main/kotlin/days/Day13.kt | vovarova | 572,952,098 | false | {"Kotlin": 103799} | package days
import java.util.*
import javax.script.ScriptEngineManager
class Day13() : Day(13) {
sealed interface Element {
fun toCollection(): ElementCollection
data class SingleElement(val value: Int) : Element {
override fun toCollection(): ElementCollection = ElementCollection(mutableListOf(this))
override fun toString(): String {
return value.toString()
}
}
data class ElementCollection(val elements: MutableList<Element> = mutableListOf()) : Element {
override fun toCollection(): ElementCollection = this
override fun toString(): String {
return "[" + elements.map { it.toString() }.joinToString(separator = ",") + "]"
}
}
}
data class ElementPair(val left: Element, val right: Element) {
fun inRightOrder(): Boolean {
return comparison(left.toCollection(), right.toCollection()) != ComparisonResult.INVALID_ORDER
}
fun inRightOrderNonRecursive(): Boolean {
return comparisonNonRecursive(left.toCollection(), right.toCollection())
}
enum class ComparisonResult {
RIGHT_ORDER,
INVALID_ORDER,
CONTINUE
}
fun comparisonNonRecursive(
left: Element.ElementCollection,
right: Element.ElementCollection
): Boolean {
val execStack = LinkedList<Pair<Iterator<Element>, Iterator<Element>>>()
execStack.add(Pair(left.elements.iterator(), right.elements.iterator()))
while (execStack.isNotEmpty()) {
val peek = execStack.peekLast()
when (peek.first.hasNext() to peek.second.hasNext()) {
true to false -> return false
false to true -> return true
false to false -> {
execStack.pollLast()
continue
}
}
val leftElement = peek.first.next()
val rightElement = peek.second.next()
if ((leftElement is Element.SingleElement) && (rightElement is Element.SingleElement)) {
if (leftElement.value > rightElement.value) {
return false
} else if (leftElement.value < rightElement.value) {
return true
}
} else {
execStack.addLast(
Pair(
leftElement.toCollection().elements.iterator(),
rightElement.toCollection().elements.iterator()
)
)
}
}
return true
}
fun comparison(left: Element.ElementCollection, right: Element.ElementCollection): ComparisonResult {
for (i in 0 until Math.min(left.elements.size, right.elements.size)) {
val leftElement = left.elements[i]
val rightElement = right.elements[i]
if ((leftElement is Element.SingleElement) && (rightElement is Element.SingleElement)) {
if (leftElement.value > rightElement.value) {
return ComparisonResult.INVALID_ORDER
} else if (leftElement.value < rightElement.value) {
return ComparisonResult.RIGHT_ORDER
}
} else {
when (comparison(leftElement.toCollection(), rightElement.toCollection())) {
ComparisonResult.INVALID_ORDER -> return ComparisonResult.INVALID_ORDER
ComparisonResult.CONTINUE -> {}
ComparisonResult.RIGHT_ORDER -> return ComparisonResult.RIGHT_ORDER
}
}
}
return if (left.elements.size == right.elements.size) {
ComparisonResult.CONTINUE
} else if (left.elements.size > right.elements.size) {
ComparisonResult.INVALID_ORDER
} else {
ComparisonResult.RIGHT_ORDER
}
}
}
class ElementsPairCollection(input: List<String>) {
val pairs: MutableList<ElementPair> = mutableListOf()
init {
for (i in input.indices.step(3)) {
val left = parseElementCollection(input[i])
val right = parseElementCollection(input[i + 1])
pairs.add(ElementPair(left, right))
}
}
companion object {
fun parseElementCollection(value: String): Element.ElementCollection {
val rootCollection = Element.ElementCollection()
val elementsStack = LinkedList<Element.ElementCollection>()
.also { it.add(rootCollection) }
val tokenSplit = value
.replace("[", "-[-").replace("]", "-]-").split("-", ",")
.filter { it.isNotEmpty() }
for (i in 1 until tokenSplit.size) {
when (tokenSplit[i]) {
"[" -> Element.ElementCollection().also { elementsStack.peekLast().elements.add(it) }
.also { elementsStack.add(it) }
"]" -> elementsStack.pollLast()
else -> elementsStack.peekLast().elements.add(Element.SingleElement(tokenSplit[i].toInt()))
}
}
return rootCollection
}
}
}
override fun partOne(): Any {
val elementsPairCollection = ElementsPairCollection(inputList)
elementsPairCollection.pairs.forEach { println(it) }
return elementsPairCollection.pairs.mapIndexed { i, pair ->
i + 1 to pair.inRightOrder()
}.filter { it.second }.map { it.first }.sum()
}
override fun partTwo(): Any {
val addedEl6 =
Element.ElementCollection(mutableListOf(Element.ElementCollection(mutableListOf(Element.SingleElement(6)))))
val addedEl2 =
Element.ElementCollection(mutableListOf(Element.ElementCollection(mutableListOf(Element.SingleElement(2)))))
val elementsPairCollection = ElementsPairCollection(inputList)
val sortedElements = elementsPairCollection.pairs.flatMap { listOf(it.left, it.right) }.toMutableList().apply {
add(addedEl6)
add(addedEl2)
}.also {
it.sortWith { el1, el2 ->
ElementPair(el1, el2).inRightOrder().let {
if (it) {
-1
} else {
1
}
}
}
}
return (sortedElements.indexOf(addedEl6) + 1) * (sortedElements.indexOf(addedEl2) + 1)
}
} | 0 | Kotlin | 0 | 0 | e34e353c7733549146653341e4b1a5e9195fece6 | 6,962 | adventofcode_2022 | Creative Commons Zero v1.0 Universal |
Chapter4/src/main/kotlin/main.kt | helloworldsmart | 344,480,484 | false | {"Text": 1, "Ignore List": 17, "Markdown": 1, "Gradle Kotlin DSL": 14, "INI": 18, "Shell": 8, "Batchfile": 8, "Kotlin": 10, "XML": 43, "SQL": 1, "Java Properties": 2, "Maven POM": 2, "Java": 6} | fun main() {
var myDog = Dog("Fido", 70, "Mixed")
println(myDog.name)
myDog.weight = 75
myDog.bark()
var dogs = arrayOf(Dog("Fido", 70, "Mixed"),
Dog("Ripper", 10, "Poodle"))
dogs[1].weight = 15
dogs[1].bark()
}
class Dog(val name: String, var weight: Int, val breed: String) {
fun bark() {
println(if (weight < 20) "Yip!" else "Woof!")
}
} | 1 | null | 1 | 1 | efd021879506a85f584057e2262f9753bd553292 | 410 | Kotlin101 | Apache License 2.0 |
app/src/main/java/com/example/reduxvideosample/components/OverlayComponent.kt | younghyuk | 402,287,556 | false | {"Kotlin": 18328} | package com.example.reduxvideosample.components
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.constraintlayout.widget.ConstraintSet.*
import com.example.redux.Store
import com.example.redux.StoreSubscriber
import com.example.reduxvideosample.R
import com.example.reduxvideosample.redux.AppState
class OverlayComponent(
container: ViewGroup,
private val store: Store<AppState>
) : UiComponent, StoreSubscriber<AppState> {
private val context = container.context
private val uiView = LayoutInflater.from(context)
.inflate(R.layout.component_overlay, container, false) as ConstraintLayout
private lateinit var soundComponent: SoundComponent
private lateinit var fullscreenComponent: FullscreenComponent
init {
container.addView(uiView)
initComponents(uiView)
layoutUiComponents(uiView)
}
override fun getContainerId(): Int = uiView.id
override fun subscribe() {
store.subscribe(this)
soundComponent.subscribe()
fullscreenComponent.subscribe()
}
override fun unsubscribe() {
store.unsubscribe(this)
soundComponent.unsubscribe()
fullscreenComponent.unsubscribe()
}
private fun initComponents(container: ViewGroup) {
soundComponent = SoundComponent(container, store)
fullscreenComponent = FullscreenComponent(container, store)
}
private fun layoutUiComponents(container: ConstraintLayout) {
val constraintSet = ConstraintSet()
constraintSet.clone(container)
soundComponent.getContainerId().let {
constraintSet.connect(it, START, PARENT_ID, START, dpToPx(context, 10))
constraintSet.connect(it, BOTTOM, PARENT_ID, BOTTOM, dpToPx(context, 10))
}
fullscreenComponent.getContainerId().let {
constraintSet.connect(it, END, PARENT_ID, END, dpToPx(context, 10))
constraintSet.connect(it, BOTTOM, PARENT_ID, BOTTOM, dpToPx(context, 10))
}
constraintSet.applyTo(container)
}
override fun newState(state: AppState) {}
}
| 0 | Kotlin | 0 | 1 | fc4569566be381ea9641dafed3f6a83f5c77151c | 2,236 | redux-video-sample | MIT License |
chapter-7/fcis/src/main/kotlin/fcis/shell/rest/Mappings.kt | PacktPublishing | 689,888,064 | false | {"Kotlin": 107850} | package fcis.shell.rest
import fcis.core.Contract
import fcis.core.ErrorType
import org.springframework.http.HttpStatus
fun Contract.toDto(): ContractDto =
ContractDto(
partyA.household.name,
partyB.household.name,
this.partyA.serviceProvided,
this.partyB.serviceProvided,
this.contractState.name,
)
fun ErrorType.toHttpStatus(): HttpStatus =
when (this) {
ErrorType.HOUSEHOLD_NOT_FOUND -> HttpStatus.NOT_FOUND
ErrorType.SAME_HOUSEHOLD_IN_CONTRACT -> HttpStatus.BAD_REQUEST
}
| 0 | Kotlin | 3 | 2 | a7dca00c5c37148d98dbef91b5ffbb02c579cb9b | 551 | Software-Architecture-with-Kotlin | MIT License |
app/src/main/java/io/github/wulkanowy/ui/modules/homework/add/HomeworkAddPresenter.kt | wulkanowy | 87,721,285 | false | null | package io.github.wulkanowy.ui.modules.homework.add
import io.github.wulkanowy.data.Status
import io.github.wulkanowy.data.db.entities.Homework
import io.github.wulkanowy.data.repositories.HomeworkRepository
import io.github.wulkanowy.data.repositories.SemesterRepository
import io.github.wulkanowy.data.repositories.StudentRepository
import io.github.wulkanowy.ui.base.BasePresenter
import io.github.wulkanowy.ui.base.ErrorHandler
import io.github.wulkanowy.utils.flowWithResource
import io.github.wulkanowy.utils.toLocalDate
import kotlinx.coroutines.flow.onEach
import timber.log.Timber
import java.time.LocalDate
import javax.inject.Inject
class HomeworkAddPresenter @Inject constructor(
errorHandler: ErrorHandler,
studentRepository: StudentRepository,
private val homeworkRepository: HomeworkRepository,
private val semesterRepository: SemesterRepository
) : BasePresenter<HomeworkAddView>(errorHandler, studentRepository) {
override fun onAttachView(view: HomeworkAddView) {
super.onAttachView(view)
view.initView()
Timber.i("Homework details view was initialized")
}
fun showDatePicker(date: LocalDate?) {
view?.showDatePickerDialog(date ?: LocalDate.now())
}
fun onAddHomeworkClicked(subject: String?, teacher: String?, date: String?, content: String?) {
var isError = false
if (subject.isNullOrBlank()) {
view?.setErrorSubjectRequired()
isError = true
}
if (date.isNullOrBlank()) {
view?.setErrorDateRequired()
isError = true
}
if (content.isNullOrBlank()) {
view?.setErrorContentRequired()
isError = true
}
if (!isError) {
saveHomework(subject!!, teacher.orEmpty(), date!!.toLocalDate(), content!!)
}
}
private fun saveHomework(subject: String, teacher: String, date: LocalDate, content: String) {
flowWithResource {
val student = studentRepository.getCurrentStudent()
val semester = semesterRepository.getCurrentSemester(student)
val entryDate = LocalDate.now()
homeworkRepository.saveHomework(
Homework(
semesterId = semester.semesterId,
studentId = student.studentId,
date = date,
entryDate = entryDate,
subject = subject,
content = content,
teacher = teacher,
teacherSymbol = "",
attachments = emptyList(),
).apply { isAddedByUser = true }
)
}.onEach {
when (it.status) {
Status.LOADING -> Timber.i("Homework insert start")
Status.SUCCESS -> {
Timber.i("Homework insert: Success")
view?.run {
showSuccessMessage()
closeDialog()
}
}
Status.ERROR -> {
Timber.i("Homework insert result: An exception occurred")
errorHandler.dispatch(it.error!!)
}
}
}.launch("add_homework")
}
}
| 76 | Kotlin | 24 | 141 | 820b99dbc7ab78132a5abd99833c9d1d1f36eea5 | 3,284 | wulkanowy | Apache License 2.0 |
TLDMaths/src/test/kotlin/uk/tldcode/math/tldmaths/PrimeTest.kt | Thelonedevil | 78,237,775 | false | null | package uk.tldcode.math.tldmaths
import org.junit.Test
import kotlin.test.assertEquals
class PrimeTest {
@Test
fun Primes_20() {
assertEquals("2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71", Prime().take(20).joinToString(", "))
}
} | 0 | Kotlin | 0 | 0 | c35095888fe85506840b7c1ec04e21673153370c | 284 | TLDMaths | Apache License 2.0 |
src/main/kotlin/dev/anotherfractal/fracdustry/registry/FRItemRegistry.kt | MikhailTapio | 430,373,168 | false | null | package dev.anotherfractal.fracdustry.registry
import dev.anotherfractal.fracdustry.blocks.materials.FROreBlock.BAUXITE_ORE
import dev.anotherfractal.fracdustry.blocks.materials.FROreBlock.CASSITERITE_ORE
import dev.anotherfractal.fracdustry.blocks.materials.FROreBlock.DEEPSLATE_BAUXITE_ORE
import dev.anotherfractal.fracdustry.blocks.materials.FROreBlock.DEEPSLATE_CASSITERITE_ORE
import dev.anotherfractal.fracdustry.blocks.materials.FROreBlock.DEEPSLATE_ILMENITE_ORE
import dev.anotherfractal.fracdustry.blocks.materials.FROreBlock.DEEPSLATE_SPODUMENE_ORE
import dev.anotherfractal.fracdustry.blocks.materials.FROreBlock.ILMENITE_ORE
import dev.anotherfractal.fracdustry.blocks.materials.FROreBlock.SPODUMENE_ORE
import dev.anotherfractal.fracdustry.items.materials.FRIngotItem
import dev.anotherfractal.fracdustry.items.materials.FRPlateItem
import dev.anotherfractal.fracdustry.registry.FRBlockRegistry.THERMAL_GENERATOR_BLOCK
import net.fabricmc.fabric.api.item.v1.FabricItemSettings
import net.minecraft.item.BlockItem
import net.minecraft.util.Identifier
import net.minecraft.util.registry.Registry
object FRItemRegistry {
fun registerAll() {
Registry.register(Registry.ITEM, Identifier("fracdustry", "aluminum_ingot"), FRIngotItem.ALUMINUM_INGOT)
Registry.register(Registry.ITEM, Identifier("fracdustry", "bronze_ingot"), FRIngotItem.BRONZE_INGOT)
Registry.register(Registry.ITEM, Identifier("fracdustry", "lithium_ingot"), FRIngotItem.LITHIUM_INGOT)
Registry.register(Registry.ITEM, Identifier("fracdustry", "steel_ingot"), FRIngotItem.STEEL_INGOT)
Registry.register(Registry.ITEM, Identifier("fracdustry", "tin_ingot"), FRIngotItem.TIN_INGOT)
Registry.register(Registry.ITEM, Identifier("fracdustry", "titanium_ingot"), FRIngotItem.TITANIUM_INGOT)
Registry.register(Registry.ITEM, Identifier("fracdustry", "aluminum_plate"), FRPlateItem.ALUMINUM_PLATE)
Registry.register(Registry.ITEM, Identifier("fracdustry", "bronze_plate"), FRPlateItem.BRONZE_PLATE)
Registry.register(Registry.ITEM, Identifier("fracdustry", "copper_plate"), FRPlateItem.COPPER_PLATE)
Registry.register(Registry.ITEM, Identifier("fracdustry", "steel_plate"), FRPlateItem.STEEL_PLATE)
Registry.register(Registry.ITEM, Identifier("fracdustry", "tin_plate"), FRPlateItem.TIN_PLATE)
Registry.register(Registry.ITEM, Identifier("fracdustry", "titanium_plate"), FRPlateItem.TITANIUM_PLATE)
Registry.register(Registry.ITEM, Identifier("fracdustry", "iron_plate"), FRPlateItem.IRON_PLATE)
Registry.register(
Registry.ITEM,
Identifier("fracdustry", "bauxite_ore"),
BlockItem(BAUXITE_ORE, FabricItemSettings())
)
Registry.register(
Registry.ITEM,
Identifier("fracdustry", "cassiterite_ore"),
BlockItem(CASSITERITE_ORE, FabricItemSettings())
)
Registry.register(
Registry.ITEM,
Identifier("fracdustry", "ilmenite_ore"),
BlockItem(ILMENITE_ORE, FabricItemSettings())
)
Registry.register(
Registry.ITEM,
Identifier("fracdustry", "spodumene_ore"),
BlockItem(SPODUMENE_ORE, FabricItemSettings())
)
Registry.register(
Registry.ITEM,
Identifier("fracdustry", "deepslate_bauxite_ore"),
BlockItem(DEEPSLATE_BAUXITE_ORE, FabricItemSettings())
)
Registry.register(
Registry.ITEM,
Identifier("fracdustry", "deepslate_cassiterite_ore"),
BlockItem(DEEPSLATE_CASSITERITE_ORE, FabricItemSettings())
)
Registry.register(
Registry.ITEM,
Identifier("fracdustry", "deepslate_ilmenite_ore"),
BlockItem(DEEPSLATE_ILMENITE_ORE, FabricItemSettings())
)
Registry.register(
Registry.ITEM,
Identifier("fracdustry", "deepslate_spodumene_ore"),
BlockItem(DEEPSLATE_SPODUMENE_ORE, FabricItemSettings())
)
Registry.register(
Registry.ITEM,
Identifier("fracdustry", "thermal_generator"),
BlockItem(THERMAL_GENERATOR_BLOCK, FabricItemSettings())
)
}
} | 0 | Kotlin | 0 | 0 | 7b03a4e4b78a887555275db2ebdc8c4f764eed32 | 4,275 | FracdustryReimagined | MIT License |
app/src/main/java/volovyk/guerrillamail/data/emails/remote/mailtm/MailTmApiClient.kt | oleksandrvolovyk | 611,731,548 | false | {"Kotlin": 108022, "Java": 767} | package volovyk.guerrillamail.data.emails.remote.mailtm
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory
import volovyk.guerrillamail.BuildConfig
object MailTmApiClient {
val client: Retrofit
get() {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BASIC
val converterFactory = JacksonConverterFactory.create(
ObjectMapper().configure(
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false
).registerKotlinModule()
)
val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
return Retrofit.Builder()
.baseUrl(BuildConfig.MAILTM_API_BASE_URL)
.addConverterFactory(converterFactory)
.client(client)
.build()
}
} | 0 | Kotlin | 0 | 0 | c4571a428c6af08018d790529bb50f08fd32b762 | 1,186 | guerrilla-mail-android-client | MIT License |
app/src/main/java/dev/efantini/hipopeople/shared/Constants.kt | PizzaMarinara | 491,572,565 | false | {"Kotlin": 82953} | package dev.efantini.hipopeople.shared
object Constants {
const val GITHUB_API_URL = "https://api.github.com/"
}
| 0 | Kotlin | 0 | 0 | 53d3f2eac14ef1f035a57280f0ef4a5ca5e4faf9 | 118 | HipoPeople | MIT License |
library/src/main/java/cesarferreira/sneakpeek/FlingDirections.kt | cesarferreira | 124,465,015 | false | {"Java": 24713, "Kotlin": 15855} | package cesarferreira.sneakpeek
import android.support.annotation.IntDef
import cesarferreira.sneakpeek.SneakPeek.FLING_DOWNWARDS
import cesarferreira.sneakpeek.SneakPeek.FLING_UPWARDS
@IntDef(FLING_UPWARDS, FLING_DOWNWARDS)
annotation class FlingDirections | 0 | Java | 0 | 0 | 78c3f11850ddb9b0f095d368b3f178cf0ef5e59b | 260 | SneakPeek | MIT License |
app/src/main/java/com/fero/skripsi/data/source/remote/ApiService.kt | feronikanm | 424,480,461 | false | null | package com.fero.skripsi.data.source.remote
import com.fero.skripsi.model.*
import com.fero.skripsi.utils.Constant.URL_DETAIL_KATEGORI_DELETE
import com.fero.skripsi.utils.Constant.URL_DETAIL_KATEGORI_GET_BY_KATEGORI
import com.fero.skripsi.utils.Constant.URL_DETAIL_KATEGORI_GET_BY_PENJAHIT
import com.fero.skripsi.utils.Constant.URL_DETAIL_KATEGORI_INSERT
import com.fero.skripsi.utils.Constant.URL_DETAIL_KATEGORI_UPDATE
import com.fero.skripsi.utils.Constant.URL_KATEGORI_GET
import com.fero.skripsi.utils.Constant.URL_PELANGGAN_GET
import com.fero.skripsi.utils.Constant.URL_PELANGGAN_GET_BY_ID
import com.fero.skripsi.utils.Constant.URL_PELANGGAN_INSERT
import com.fero.skripsi.utils.Constant.URL_PELANGGAN_UPDATE
import com.fero.skripsi.utils.Constant.URL_PENJAHIT_GET
import com.fero.skripsi.utils.Constant.URL_PENJAHIT_GET_BY_ID
import com.fero.skripsi.utils.Constant.URL_PENJAHIT_GET_BY_NILAI
import com.fero.skripsi.utils.Constant.URL_PENJAHIT_INSERT
import com.fero.skripsi.utils.Constant.URL_PENJAHIT_UPDATE
import com.fero.skripsi.utils.Constant.URL_PESANAN_DELETE
import com.fero.skripsi.utils.Constant.URL_PESANAN_GET_BY_ID
import com.fero.skripsi.utils.Constant.URL_PESANAN_GET_BY_PELANGGAN
import com.fero.skripsi.utils.Constant.URL_PESANAN_GET_BY_PENJAHIT
import com.fero.skripsi.utils.Constant.URL_PESANAN_INSERT
import com.fero.skripsi.utils.Constant.URL_PESANAN_UPDATE
import com.fero.skripsi.utils.Constant.URL_RATING_INSERT
import com.fero.skripsi.utils.Constant.URL_UKURAN_DETAIL_KATEGORI_DELETE
import com.fero.skripsi.utils.Constant.URL_UKURAN_DETAIL_KATEGORI_GET_BY_DETAIL_KATEGORI
import com.fero.skripsi.utils.Constant.URL_UKURAN_DETAIL_KATEGORI_INSERT
import com.fero.skripsi.utils.Constant.URL_UKURAN_DETAIL_PESANAN_DELETE
import com.fero.skripsi.utils.Constant.URL_UKURAN_DETAIL_PESANAN_GET_BY_PESANAN
import com.fero.skripsi.utils.Constant.URL_UKURAN_DETAIL_PESANAN_INSERT
import com.fero.skripsi.utils.Constant.URL_UKURAN_DETAIL_PESANAN_UPDATE
import com.fero.skripsi.utils.Constant.URL_UKURAN_GET
import io.reactivex.Observable
import retrofit2.Call
import retrofit2.http.*
interface ApiService {
@GET(URL_PENJAHIT_GET_BY_NILAI)
fun getDataPenjahitNilai() : Observable<List<DetailKategoriNilai>>
@GET(URL_PENJAHIT_GET)
fun getDataPenjahit() : Observable<List<DetailKategoriNilai>>
@GET(URL_KATEGORI_GET)
fun getDataKategori() : Observable<List<DetailKategoriNilai>>
@GET(URL_PELANGGAN_GET)
fun getPelanggan(): Call<List<Pelanggan>>
@GET(URL_PENJAHIT_GET)
fun getPenjahit(): Call<List<Penjahit>>
@GET(URL_PELANGGAN_GET_BY_ID)
fun getDataPelangganById(
@Path("id_pelanggan") id_pelanggan_path: Int
): Call<List<Pelanggan>>
@GET(URL_PENJAHIT_GET_BY_ID)
fun getDataPenjahitById(
@Path("id_penjahit") id_penjahit_path: Int
): Call<List<Penjahit>>
@FormUrlEncoded
@POST(URL_PELANGGAN_INSERT)
fun insertDataPelanggan(
@Field("namaPelanggan") nama_pelanggan: String,
@Field("emailPelanggan") email_pelanggan: String,
@Field("passwordPelanggan") password_pelanggan: String,
@Field("telpPelanggan") telp_pelanggan: String,
@Field("latitudePelanggan") latitude_pelanggan: String,
@Field("longitudePelanggan") longitude_pelanggan: String,
@Field("alamatPelanggan") alamat_pelanggan: String,
@Field("jkPelanggan") jk_pelanggan: String,
@Field("foto_pelanggan") foto_pelanggan: String,
): Call<Success<Pelanggan>>
@FormUrlEncoded
@POST(URL_PELANGGAN_UPDATE)
fun updateDataPelanggan(
@Path("id_pelanggan") id_pelanggan_path: Int,
@Field("namaPelanggan") nama_pelanggan: String,
@Field("emailPelanggan") email_pelanggan: String,
@Field("passwordPelanggan") password_pelanggan: String,
@Field("telpPelanggan") telp_pelanggan: String,
@Field("latitudePelanggan") latitude_pelanggan: String,
@Field("longitudePelanggan") longitude_pelanggan: String,
@Field("alamatPelanggan") alamat_pelanggan: String,
@Field("jkPelanggan") jk_pelanggan: String,
@Field("foto_pelanggan") foto_pelanggan: String,
): Call<Success<Pelanggan>>
@FormUrlEncoded
@POST(URL_PENJAHIT_INSERT)
fun insertDataPenjahit(
@Field("namaPenjahit") nama_penjahit: String,
@Field("emailPenjahit") email_penjahit: String,
@Field("passwordPenjahit") password_penjahit: String,
@Field("telpPenjahit") telp_penjahit: String,
@Field("namaToko") nama_toko: String,
@Field("keteranganToko") keterangan_toko: String,
@Field("latitudePenjahit") latitude_penjahit: String,
@Field("longitudePenjahit") longitude_penjahit: String,
@Field("alamatPenjahit") alamat_penjahit: String,
@Field("spesifikasiPenjahit") spesifikasi_penjahit: String,
@Field("jangkauanKategoriPenjahit") jangkauan_kategori_penjahit: String,
@Field("hariBuka") hari_buka: String,
@Field("jamBuka") jam_buka: Any,
@Field("jamTutup") jam_tutup: String,
@Field("foto_penjahit") foto_penjahit: String,
): Call<Success<Penjahit>>
@FormUrlEncoded
@POST(URL_PENJAHIT_UPDATE)
fun updateDataPenjahit(
@Path("id_penjahit") id_penjahit_path: Int,
@Field("namaPenjahit") nama_penjahit: String,
@Field("emailPenjahit") email_penjahit: String,
@Field("passwordPenjahit") password_penjahit: String,
@Field("telpPenjahit") telp_penjahit: String,
@Field("namaToko") nama_toko: String,
@Field("keteranganToko") keterangan_toko: String,
@Field("latitudePenjahit") latitude_penjahit: String,
@Field("longitudePenjahit") longitude_penjahit: String,
@Field("alamatPenjahit") alamat_penjahit: String,
@Field("spesifikasiPenjahit") spesifikasi_penjahit: String,
@Field("jangkauanKategoriPenjahit") jangkauan_kategori_penjahit: String,
@Field("hariBuka") hari_buka: String,
@Field("jamBuka") jam_buka: Any,
@Field("jamTutup") jam_tutup: String,
@Field("foto_penjahit") foto_penjahit: String,
): Call<Success<Penjahit>>
@GET(URL_DETAIL_KATEGORI_GET_BY_PENJAHIT)
fun getDetailKategori(
@Path("id_penjahit") id_penjahit_path: Int
): Observable<List<DetailKategoriPenjahit>>
@GET(URL_DETAIL_KATEGORI_GET_BY_PENJAHIT)
fun getDetailKategoriInPelanggan(
@Path("id_penjahit") id_penjahit_path: Int
): Observable<List<DetailKategoriNilai>>
@FormUrlEncoded
@POST(URL_DETAIL_KATEGORI_INSERT)
fun insertDataDetailKategori(
@Field("idPenjahit") id_penjahit: Int,
@Field("idKategori") id_kategori: Int,
@Field("keteranganKategori") keterangan_kategori: String,
@Field("bahanJahit") bahan_jahit: String,
@Field("hargaBahan") harga_bahan: String,
@Field("ongkosPenjahit") ongkos_penjahit: String,
@Field("perkiraanLamaWaktuPengerjaan") perkiraan_lama_waktu_pengerjaan: String,
): Call<Success<DetailKategori>>
@POST(URL_DETAIL_KATEGORI_DELETE)
fun deleteDataDetailKategori(
@Path("id_detail_kategori") id_detail_kategori_path: Int
): Call<Success<Int>>
@FormUrlEncoded
@POST(URL_DETAIL_KATEGORI_UPDATE)
fun updateDataDetailKategori(
@Path("id_detail_kategori") id_detail_kategori_path: Int,
@Field("idPenjahit") id_penjahit: Int,
@Field("idKategori") id_kategori: Int,
@Field("keteranganKategori") keterangan_kategori: String,
@Field("bahanJahit") bahan_jahit: String,
@Field("hargaBahan") harga_bahan: String?,
@Field("ongkosPenjahit") ongkos_penjahit: String?,
@Field("perkiraanLamaWaktuPengerjaan") perkiraan_lama_waktu_pengerjaan: String,
): Call<Success<DetailKategori>>
@GET(URL_DETAIL_KATEGORI_GET_BY_KATEGORI)
fun getDataPenjahitByKategori(
@Path("id_kategori") id_kategori_path: Int
): Observable<List<DetailKategoriNilai>>
@GET(URL_UKURAN_GET)
fun getDataUkuran() : Observable<List<UkuranDetailKategori>>
@GET(URL_UKURAN_DETAIL_KATEGORI_GET_BY_DETAIL_KATEGORI)
fun getUkuranByDetailKategori(
@Path("id_detail_kategori") id_detail_kategori_path: Int
): Observable<List<UkuranDetailKategori>>
@FormUrlEncoded
@POST(URL_UKURAN_DETAIL_KATEGORI_INSERT)
fun insertDataUkuranDetailKategori(
@Field("idDetailKategori") id_detail_kategori: Int,
@Field("idUkuran") id_ukuran: Int,
): Call<Success<UkuranDetailKategori>>
@POST(URL_UKURAN_DETAIL_KATEGORI_DELETE)
fun deleteDataUkuranDetailKategori(
@Path("id_ukuran_detail_kategori") id_ukuran_detail_kategori_path: Int
): Call<ResponseDeleteSuccess>
@FormUrlEncoded
@POST(URL_RATING_INSERT)
fun insertDataRating(
@Field("idPenjahit") id_penjahit: Int?,
@Field("kriteria1") kriteria_1: Int?,
@Field("kriteria2") kriteria_2: Int?,
@Field("kriteria3") kriteria_3: Int?,
@Field("kriteria4") kriteria_4: Int?,
): Call<Success<Rating>>
// @GET(URL_PESANAN_GET_BY_ID)
// fun getDataPesananById(
// @Path("id_pesanan") id_pesanan_path: Int
// ): Observable<Pesanan>
@GET(URL_PESANAN_GET_BY_ID)
fun getDataPesananById(
@Path("id_pesanan") id_pesanan_path: Int
): Call<Pesanan>
@GET(URL_PESANAN_GET_BY_ID)
fun getDataDetailPesananById(
@Path("id_pesanan") id_pesanan_path: Int
): Call<List<DetailPesanan>>
@GET(URL_PESANAN_GET_BY_PELANGGAN)
fun getDataPesananByPelanggan(
@Path("id_pelanggan") id_pelanggan_path: Int
): Observable<List<Pesanan>>
@GET(URL_PESANAN_GET_BY_PENJAHIT)
fun getDataPesananByPenjahit(
@Path("id_penjahit") id_penjahit_path: Int
): Observable<List<Pesanan>>
@FormUrlEncoded
@POST(URL_PESANAN_INSERT)
fun insertDataPesanan(
@Field("idPelanggan") id_pelanggan: Int?,
@Field("idPenjahit") id_penjahit: Int?,
@Field("idDetailKategori") id_detail_kategori: Int?,
@Field("tanggalPesanan") tanggal_pesanan: String?,
@Field("tanggalPesananSelesai") tanggal_pesanan_selesai: String?,
@Field("lamaWaktuPengerjaan") lama_waktu_pengerjaan: String?,
@Field("catatanPesanan") catatan_pesanan: String?,
@Field("desainJahitan") desain_jahitan: String?,
@Field("bahanJahit") bahan_jahit: String?,
@Field("asalBahan") asal_bahan: String?,
@Field("panjangBahan") panjang_bahan: String?,
@Field("lebarBahan") lebar_bahan: String?,
@Field("statusBahan") status_bahan: String?,
@Field("hargaBahan") harga_bahan: Int?,
@Field("ongkosPenjahit") ongkos_penjahit: Int?,
@Field("jumlahJahitan") jumlah_jahitan: Int?,
@Field("biayaJahitan") biaya_jahitan: Int?,
@Field("totalBiaya") total_biaya: Int?,
@Field("statusPesanan") status_pesanan: String?,
): Call<Success<Pesanan>>
@FormUrlEncoded
@POST(URL_PESANAN_UPDATE)
fun updateDataPesanan(
@Path("id_pesanan") id_pesanan_path: Int?,
@Field("idPelanggan") id_pelanggan: Int?,
@Field("idPenjahit") id_penjahit: Int?,
@Field("idDetailKategori") id_detail_kategori: Int?,
@Field("tanggalPesanan") tanggal_pesanan: String?,
@Field("tanggalPesananSelesai") tanggal_pesanan_selesai: String?,
@Field("lamaWaktuPengerjaan") lama_waktu_pengerjaan: String?,
@Field("catatanPesanan") catatan_pesanan: String?,
@Field("desainJahitan") desain_jahitan: String?,
@Field("bahanJahit") bahan_jahit: String?,
@Field("asalBahan") asal_bahan: String?,
@Field("panjangBahan") panjang_bahan: String?,
@Field("lebarBahan") lebar_bahan: String?,
@Field("statusBahan") status_bahan: String?,
@Field("hargaBahan") harga_bahan: Int?,
@Field("ongkosPenjahit") ongkos_penjahit: Int?,
@Field("jumlahJahitan") jumlah_jahitan: Int?,
@Field("biayaJahitan") biaya_jahitan: Int?,
@Field("totalBiaya") total_biaya: Int?,
@Field("statusPesanan") status_pesanan: String?,
): Call<Success<Pesanan>>
@POST(URL_PESANAN_DELETE)
fun deleteDataPesanan(
@Path("id_pesanan") id_pesanan_path: Int
): Call<Success<Pesanan>>
@GET(URL_UKURAN_DETAIL_PESANAN_GET_BY_PESANAN)
fun getDataUkuranByPesanan(
@Path("id_pesanan") id_pesanan_path: Int
): Observable<List<UkuranDetailPesanan>>
@GET(URL_UKURAN_DETAIL_KATEGORI_GET_BY_DETAIL_KATEGORI)
fun getDataUkuranPesananByDetailKategori(
@Path("id_detail_kategori") id_detail_kategori_path: Int
): Observable<List<UkuranDetailPesanan>>
@FormUrlEncoded
@POST(URL_UKURAN_DETAIL_PESANAN_INSERT)
fun insertDataUkuranDetailPesanan(
@Field("idPesanan") id_pesanan: Int?,
@Field("idUkuran") id_ukuran: Int?,
@Field("ukuranPesanan") ukuran_pesanan: Int?,
): Call<Success<UkuranDetailPesanan>>
@FormUrlEncoded
@POST(URL_UKURAN_DETAIL_PESANAN_UPDATE)
fun updateDataUkuranDetailPesanan(
@Path("id_ukuran_detail_pesanan") id_ukuran_detail_pesanan_path: Int?,
@Field("idPesanan") id_pesanan: Int?,
@Field("idUkuran") id_ukuran: Int?,
@Field("ukuranPesanan") ukuran_pesanan: Int?,
): Call<Success<UkuranDetailPesanan>>
@POST(URL_UKURAN_DETAIL_PESANAN_DELETE)
fun deleteDataUkuranDetailPesanan(
@Path("id_ukuran_detail_pesanan") id_ukuran_detail_pesanan_path: Int
): Call<Success<UkuranDetailPesanan>>
} | 0 | Kotlin | 4 | 9 | f85a2d7fb7330b08e3c41986e8f4bce8784bb482 | 13,710 | gojahit-client | Apache License 2.0 |
utilities/src/main/java/com/dongtronic/diabot/logic/diabetes/GlucoseUnit.kt | discord-diabetes | 151,116,011 | false | {"Kotlin": 408572, "Dockerfile": 527, "Procfile": 67} | package com.dongtronic.diabot.logic.diabetes
enum class GlucoseUnit(vararg units: String) {
// nightscout uses "mmol/l" and "mmol"
// https://github.com/nightscout/cgm-remote-monitor#required
MMOL("mmol/L", "mmol"),
MGDL("mg/dL"),
// this unit shouldn't be identified by name
AMBIGUOUS("Ambiguous");
/**
* A list of names which identify this particular [GlucoseUnit]
*/
val units: List<String> = units.toList()
companion object {
const val CONVERSION_FACTOR = 18.0156
/**
* Attempts to find a [GlucoseUnit] which matches the unit name given.
* This function does not match [GlucoseUnit.AMBIGUOUS].
*
* @param unit The name of the unit to look up
* @return [GlucoseUnit] if a unit was matched, null if no matches were found
*/
fun byName(unit: String): GlucoseUnit? {
return values().firstOrNull { glucoseUnit ->
if (glucoseUnit == AMBIGUOUS) {
return@firstOrNull false
}
glucoseUnit.units.any { name ->
name.equals(unit, ignoreCase = true)
}
}
}
}
}
| 18 | Kotlin | 14 | 19 | 8be95fd823503913f612978442c06ca8653afb5a | 1,219 | diabot | MIT License |
src/main/kotlin/feature/root/component/RootComponent.kt | boolean-false | 809,920,499 | false | {"Kotlin": 84532} | package feature.root.component
import androidx.compose.runtime.Stable
import com.arkivanov.decompose.router.stack.ChildStack
import com.arkivanov.decompose.value.Value
import feature.add_release.component.AddReleaseComponent
import feature.game_list.component.GameListComponent
import feature.logs_screen.component.LogsScreenComponent
@Stable
interface RootComponent {
val stack: Value<ChildStack<*, Child>>
sealed class Child {
class GameList(
val component: GameListComponent
) : Child()
class LogList(
val component: LogsScreenComponent
) : Child()
class AddGameRelease(
val component: AddReleaseComponent
) : Child()
}
} | 0 | Kotlin | 0 | 1 | 8bf1ca636f3e641d6ebc0ab2367c067af1ea558b | 725 | VLauncher | MIT License |
autofill/autofill/src/main/java/com/duckduckgo/autofill/store/LastUpdatedTimeProvider.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} | package com.duckduckgo.autofill.store
interface LastUpdatedTimeProvider {
fun getInMillis(): Long
}
class RealLastUpdatedTimeProvider : LastUpdatedTimeProvider {
override fun getInMillis(): Long = System.currentTimeMillis()
}
| 0 | Kotlin | 0 | 0 | ed9a0dcca1ffae0851cd1fab0cd3981a928d4d4f | 236 | SmartBrowser | Apache License 2.0 |
app/src/main/java/io/keepalive/android/AppController.kt | keepalivedev | 718,764,639 | false | null | package io.keepalive.android
import android.app.Application
import android.content.pm.ApplicationInfo
import android.os.Build
import android.util.Log
class AppController : Application() {
companion object {
const val TAG = "AppController"
// notification channel IDs
const val ARE_YOU_THERE_NOTIFICATION_CHANNEL_ID = "AlertNotificationChannel"
const val CALL_SENT_NOTIFICATION_CHANNEL_ID = "CallSentNotificationChannel"
const val SMS_SENT_NOTIFICATION_CHANNEL_ID = "SMSSentNotificationChannel"
// notification IDs
const val ARE_YOU_THERE_NOTIFICATION_ID = 1
const val SMS_ALERT_SENT_NOTIFICATION_ID = 2
const val CALL_ALERT_SENT_NOTIFICATION_ID = 3
const val SMS_ALERT_FAILURE_NOTIFICATION_ID = 4
// when doing a sanity check to see if we can see ANY events, this is the # of hours
// to use with getLastPhoneActivity(). if the user has a higher value set it
// will use that instead
const val LAST_ACTIVITY_MAX_PERIOD_CHECK_HOURS = 48F
// according to the docs we shouldn't set alarms for less than 10 minutes?
const val ALARM_MINIMUM_TIME_PERIOD_MINUTES = 10
// max SMS length as defined by the OS?
const val SMS_MESSAGE_MAX_LENGTH = 160
// request code used with AlarmReceiver intent
const val ACTIVITY_ALARM_REQUEST_CODE = 99
// request code used with AppHibernationActivity intent
const val APP_HIBERNATION_ACTIVITY_RESULT_CODE = 98
// we have to check this several times so use a variable so its more clear what its for
const val MIN_API_LEVEL_FOR_DEVICE_LOCK_UNLOCK = Build.VERSION_CODES.P
}
override fun onCreate() {
super.onCreate()
DebugLogger.d(TAG, "KeepAlive starting up!")
// alternative is to check BuildConfig.DEBUG?
if ((this.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
Log.d(TAG, "We're in debug mode?")
}
}
} | 7 | null | 8 | 81 | f5d84066b41a1cebaf9ce962e09e6c340220d9ca | 2,027 | KeepAlive | Apache License 2.0 |
galleryImagePicker/src/main/java/com/samuelunknown/galleryImagePicker/domain/useCase/getFoldersUseCase/GetFoldersUseCaseImpl.kt | Samuel-Unknown | 409,861,199 | false | {"Kotlin": 78145} | package com.samuelunknown.galleryImagePicker.domain.useCase.getFoldersUseCase
import android.content.ContentResolver
import android.provider.MediaStore
import com.samuelunknown.galleryImagePicker.domain.model.FolderDto
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
internal class GetFoldersUseCaseImpl(
private val contentResolver: ContentResolver
) : GetFoldersUseCase {
override suspend fun execute(): List<FolderDto> = withContext(Dispatchers.IO) {
val projection = arrayOf(
MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME
)
val sortOrder = "${MediaStore.Images.Media.BUCKET_DISPLAY_NAME} ASC"
contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
sortOrder
)?.use { cursor ->
val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_ID)
val bucketDisplayNameColumn =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)
List(cursor.count) {
cursor.moveToNext()
val folderId = cursor.getString(idColumn)
val folderName = cursor.getString(bucketDisplayNameColumn)
if (folderId.isNullOrEmpty() || folderName.isNullOrEmpty()) {
null
} else {
FolderDto(id = folderId, name = folderName)
}
}.distinct().filterNotNull()
} ?: emptyList()
}
} | 0 | Kotlin | 2 | 8 | e9a179911b811df77055ff0a4bdbaaf70db7e75f | 1,625 | Gallery-Image-Picker | Apache License 2.0 |
falu-core/src/main/java/io/falu/core/models/FaluFileUploadArgs.kt | faluapp | 345,511,436 | false | null | package io.falu.core.models
import androidx.annotation.RestrictTo
import okhttp3.MediaType
import java.io.File
import java.util.*
/**
* Falu requires request of type `multipart/form-data` when uploading files.
* The request contains the file being uploaded, and the other arguments for file creation.
*/
data class FaluFileUploadArgs(
/**
* Contents of the file. It should follow the specifications of RFC 2388.
*/
internal var file: File,
/**
* Purpose for a file, possible values include:- `business.icon`, `business.logo`,`customer.signature`,
* `customer.selfie` `customer.tax.document`,`message.media`,`identity.document`,`identity.video`
*/
internal var purpose: String,
/**
* Time at which the file expires.
*/
internal var date: Date? = null,
) {
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
internal lateinit var mediaType: MediaType
}
| 4 | Kotlin | 0 | 0 | bddb9ecbb053d2ef6222b5d60b2cbfa30fb8766b | 918 | falu-android | MIT License |
src/main/kotlin/io/mverse/kslack/api/methods/request/dnd/DndTeamInfoRequest.kt | mverse | 161,946,116 | true | {"Kotlin": 403852} | package io.mverse.kslack.api.methods.request.dnd
import io.mverse.kslack.api.methods.SlackApiRequest
data class DndTeamInfoRequest(
/**
* Authentication token. Requires scope: `dnd:read`
*/
override var token: String? = null,
/**
* Comma-separated list of users to fetch Do Not Disturb status for
*/
val users: List<String>? = null): SlackApiRequest | 0 | Kotlin | 0 | 0 | 9ebf1dc13f6a3d89a03af11a83074a4d636cb071 | 373 | jslack | MIT License |
product-farm-api/src/main/kotlin/io/github/ayushmaanbhav/productFarm/service/CloneProductService.kt | ayushmaanbhav | 633,602,472 | false | null | package io.github.ayushmaanbhav.productFarm.service
import io.github.ayushmaanbhav.productFarm.api.product.dto.CloneProductRequest
import jakarta.transaction.Transactional
import org.springframework.stereotype.Component
@Component
class CloneProductService(
private val productService: ProductService,
private val abstractAttributeService: AbstractAttributeService,
private val attributeService: AttributeService,
private val productFunctionalityService: ProductFunctionalityService,
) {
@Transactional
fun clone(parentProductId: String, request: CloneProductRequest) {
productService.clone(parentProductId, request)
abstractAttributeService.clone(parentProductId, request.productId)
attributeService.clone(parentProductId, request.productId)
productFunctionalityService.clone(parentProductId, request.productId)
}
}
| 0 | Kotlin | 0 | 0 | 7e32f243ef9092d1878d5a66a051f1657fb6e8cd | 879 | product-farm | Apache License 2.0 |
vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/kafka/client/consumer/KafkaConsumer.kt | jo5ef | 138,613,796 | true | {"Maven POM": 7, "Ignore List": 1, "EditorConfig": 1, "Text": 1, "Markdown": 1, "JAR Manifest": 2, "Java": 198, "AsciiDoc": 66, "XML": 10, "Java Properties": 1, "Groovy": 14, "Ruby": 26, "Kotlin": 276, "JavaScript": 40, "FreeMarker": 1, "JSON": 1} | package io.vertx.kotlin.kafka.client.consumer
import io.vertx.kafka.client.common.PartitionInfo
import io.vertx.kafka.client.common.TopicPartition
import io.vertx.kafka.client.consumer.KafkaConsumer
import io.vertx.kafka.client.consumer.KafkaConsumerRecord
import io.vertx.kafka.client.consumer.KafkaConsumerRecords
import io.vertx.kafka.client.consumer.OffsetAndMetadata
import io.vertx.kafka.client.consumer.OffsetAndTimestamp
import io.vertx.kotlin.coroutines.awaitEvent
import io.vertx.kotlin.coroutines.awaitResult
suspend fun <K,V> KafkaConsumer<K,V>.exceptionHandlerAwait() : Throwable {
return awaitEvent{
this.exceptionHandler(it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.handlerAwait() : KafkaConsumerRecord<K,V> {
return awaitEvent{
this.handler(it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.endHandlerAwait() : Unit {
return awaitEvent{
this.endHandler({ v -> it.handle(null) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.subscribeAwait(topic : String) : Unit {
return awaitResult{
this.subscribe(topic, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.subscribeAwait(topics : Set<String>) : Unit {
return awaitResult{
this.subscribe(topics, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.assignAwait(topicPartition : TopicPartition) : Unit {
return awaitResult{
this.assign(topicPartition, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.assignAwait(topicPartitions : Set<TopicPartition>) : Unit {
return awaitResult{
this.assign(topicPartitions, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.assignmentAwait() : Set<TopicPartition> {
return awaitResult{
this.assignment(it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.unsubscribeAwait() : Unit {
return awaitResult{
this.unsubscribe({ ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.subscriptionAwait() : Set<String> {
return awaitResult{
this.subscription(it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.pauseAwait(topicPartition : TopicPartition) : Unit {
return awaitResult{
this.pause(topicPartition, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.pauseAwait(topicPartitions : Set<TopicPartition>) : Unit {
return awaitResult{
this.pause(topicPartitions, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.pausedAwait() : Set<TopicPartition> {
return awaitResult{
this.paused(it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.resumeAwait(topicPartition : TopicPartition) : Unit {
return awaitResult{
this.resume(topicPartition, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.resumeAwait(topicPartitions : Set<TopicPartition>) : Unit {
return awaitResult{
this.resume(topicPartitions, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.partitionsRevokedHandlerAwait() : Set<TopicPartition> {
return awaitEvent{
this.partitionsRevokedHandler(it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.partitionsAssignedHandlerAwait() : Set<TopicPartition> {
return awaitEvent{
this.partitionsAssignedHandler(it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.seekAwait(topicPartition : TopicPartition, offset : Long) : Unit {
return awaitResult{
this.seek(topicPartition, offset, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.seekToBeginningAwait(topicPartition : TopicPartition) : Unit {
return awaitResult{
this.seekToBeginning(topicPartition, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.seekToBeginningAwait(topicPartitions : Set<TopicPartition>) : Unit {
return awaitResult{
this.seekToBeginning(topicPartitions, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.seekToEndAwait(topicPartition : TopicPartition) : Unit {
return awaitResult{
this.seekToEnd(topicPartition, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.seekToEndAwait(topicPartitions : Set<TopicPartition>) : Unit {
return awaitResult{
this.seekToEnd(topicPartitions, { ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.commitAwait() : Unit {
return awaitResult{
this.commit({ ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.committedAwait(topicPartition : TopicPartition) : OffsetAndMetadata {
return awaitResult{
this.committed(topicPartition, it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.partitionsForAwait(topic : String) : List<PartitionInfo> {
return awaitResult{
this.partitionsFor(topic, it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.batchHandlerAwait() : KafkaConsumerRecords<K,V> {
return awaitEvent{
this.batchHandler(it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.closeAwait() : Unit {
return awaitResult{
this.close({ ar -> it.handle(ar.mapEmpty()) })}
}
suspend fun <K,V> KafkaConsumer<K,V>.positionAwait(partition : TopicPartition) : Long {
return awaitResult{
this.position(partition, it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.offsetsForTimesAwait(topicPartition : TopicPartition, timestamp : Long) : OffsetAndTimestamp {
return awaitResult{
this.offsetsForTimes(topicPartition, timestamp, it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.beginningOffsetsAwait(topicPartition : TopicPartition) : Long {
return awaitResult{
this.beginningOffsets(topicPartition, it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.endOffsetsAwait(topicPartition : TopicPartition) : Long {
return awaitResult{
this.endOffsets(topicPartition, it)
}
}
suspend fun <K,V> KafkaConsumer<K,V>.pollAwait(timeout : Long) : KafkaConsumerRecords<K,V> {
return awaitResult{
this.poll(timeout, it)
}
}
| 0 | Java | 0 | 0 | 15be5c0e93e68aa64e4daffe97d60580c081d1cc | 6,069 | vertx-stack-generation | Apache License 2.0 |
app/src/main/java/org/p2p/wallet/feerelayer/model/SwapDataConverter.kt | p2p-org | 306,035,988 | false | {"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252} | package org.p2p.wallet.feerelayer.model
import org.p2p.wallet.feerelayer.api.SwapDataRequest
import org.p2p.wallet.feerelayer.api.SwapSplRequest
import org.p2p.wallet.feerelayer.api.SwapSplTransitiveRequest
object SwapDataConverter {
fun toNetwork(data: SwapData): SwapDataRequest = when (data) {
is SwapData.Direct -> SwapDataRequest(
spl = toSpl(data),
splTransitive = null
)
is SwapData.SplTransitive -> SwapDataRequest(
spl = null,
splTransitive = SwapSplTransitiveRequest(
from = toSpl(data.from),
to = toSpl(data.to),
transitTokenMintPubkey = data.transitTokenMintPubkey,
needsCreateTransitTokenAccount = data.needsCreateTransitTokenAccount
),
)
}
private fun toSpl(data: SwapData.Direct): SwapSplRequest =
SwapSplRequest(
programId = data.programId,
accountPubkey = data.accountPubkey,
authorityPubkey = data.authorityPubkey,
transferAuthorityPubkey = data.transferAuthorityPubkey,
sourcePubkey = data.sourcePubkey,
destinationPubkey = data.destinationPubkey,
poolTokenMintPubkey = data.poolTokenMintPubkey,
poolFeeAccountPubkey = data.poolFeeAccountPubkey,
amountIn = data.amountIn.toLong(),
minimumAmountOut = data.minimumAmountOut.toLong(),
)
}
| 8 | Kotlin | 18 | 34 | d091e18b7d88c936b7c6c627f4fec96bcf4a0356 | 1,463 | key-app-android | MIT License |
beckon/src/main/java/com/technocreatives/beckon/Exceptions.kt | technocreatives | 364,517,134 | false | null | package com.technocreatives.beckon
import java.util.*
@Deprecated("Use BleActionError")
data class WriteDataException(val macAddress: String, val uuid: UUID, val status: Int) :
Throwable(), BeckonError
@Deprecated("Use BleActionError")
data class ReadDataException(val macAddress: String, val uuid: UUID, val status: Int) :
Throwable(),
BeckonError
@Deprecated("Use BleActionError")
data class SubscribeDataException(val macAddress: String, val uuid: UUID, val status: Int) :
Throwable(), BeckonError
sealed interface BeckonActionError: BeckonError
data class BleActionError(
val macAddress: String,
val uuid: UUID,
val status: Int,
val property: Property
) : BeckonActionError
data class MtuRequestError(val macAddress: String, val status: Int) : BeckonError
object BeckonTimeOutError : BeckonError
sealed interface RequirementFailed : BeckonActionError
data class CharacteristicNotFound(val characteristic: Characteristic) : RequirementFailed
data class ServiceNotFound(val characteristic: Characteristic) : RequirementFailed
data class PropertyNotSupport(val characteristic: Characteristic) : RequirementFailed
// todo use BeckonException instead of Throwable
//typealias BeckonResult<T> = Either<Throwable, T>
sealed interface BeckonError {
fun toException(): BeckonException {
return BeckonException(this)
}
}
data class BeckonException(val beckonError: BeckonError) : Throwable()
sealed class ScanError : BeckonError {
data class ScanFailed(val errorCode: Int) : ScanError()
}
sealed class ConnectionError : BeckonError {
data class BleConnectFailed(val macAddress: MacAddress, val status: Int) : ConnectionError()
data class CreateBondFailed(val macAddress: String, val status: Int) : ConnectionError()
data class RemoveBondFailed(val macAddress: String, val status: Int) : ConnectionError()
data class BluetoothGattNull(val macAddress: MacAddress) : ConnectionError()
data class Timeout(val macAddress: MacAddress) : ConnectionError()
data class RequirementFailed(val fails: List<CharacteristicFailed>) : ConnectionError()
data class ConnectedDeviceNotFound(val macAddress: MacAddress) : ConnectionError()
data class DisconnectDeviceFailed(val macAddress: String, val status: Int) : ConnectionError()
data class GeneralError(val macAddress: MacAddress, val throwable: Throwable) :
ConnectionError()
}
sealed class BeckonDeviceError : BeckonError {
data class SavedDeviceNotFound(val address: MacAddress) : BeckonDeviceError()
data class BondedDeviceNotFound(val savedMetadata: SavedMetadata) : BeckonDeviceError()
data class ConnectedDeviceNotFound(val savedMetadata: SavedMetadata) : BeckonDeviceError()
data class Connecting(val savedMetadata: SavedMetadata) : BeckonDeviceError()
fun macAddress(): MacAddress {
return when (this) {
is SavedDeviceNotFound -> address
is BondedDeviceNotFound -> savedMetadata.macAddress
is ConnectedDeviceNotFound -> savedMetadata.macAddress
is Connecting -> savedMetadata.macAddress
}
}
}
| 1 | Kotlin | 1 | 8 | 2e252df19c02104821c393225ee8d5abefa07b74 | 3,135 | beckon-android | Apache License 2.0 |
src/test/kotlin/com/tsovedenski/parser/ManyParserTest.kt | fintara | 116,526,005 | false | null | package com.tsovedenski.parser
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
/**
* Created by <NAME> on 06/01/2018.
*/
object ManyParserTest : Spek({
describe("many") {
it("succeeds with 0 occurences") {
assertSuccess(many(digit), "ABCD1234", listOf(), "ABCD1234")
}
it("succeeds with 1 occurence") {
assertSuccess(many(letter), "A1BCD1234", listOf('A'), "1BCD1234")
}
it("succeeds with 4 occurences") {
assertSuccess(many(letter), "ABCD1234", "ABCD".toList(), "1234")
}
it("succeeds with alphaNum") {
assertSuccess(many(alphaNum), "Ab12Cd34eF@3", "Ab12Cd34eF".toList(), "@3")
}
}
describe("many1") {
it("fails with 0 occurences") {
assertError(many1(digit), "ABCD1234")
}
it("succeeds with 1 occurence") {
assertSuccess(many1(letter), "A1BCD1234", listOf('A'), "1BCD1234")
}
it("succeeds with 4 occurences") {
assertSuccess(many1(letter), "ABCD1234", "ABCD".toList(), "1234")
}
}
}) | 0 | Kotlin | 0 | 4 | 61d21e6f4fc7fb09302127da83e5c476a2b19ee6 | 1,175 | parser | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/ec2/CfnTransitGatewayMulticastGroupSourcePropsDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.ec2
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.ec2.CfnTransitGatewayMulticastGroupSourceProps
@Generated
public fun buildCfnTransitGatewayMulticastGroupSourceProps(initializer: @AwsCdkDsl
CfnTransitGatewayMulticastGroupSourceProps.Builder.() -> Unit):
CfnTransitGatewayMulticastGroupSourceProps =
CfnTransitGatewayMulticastGroupSourceProps.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | a1cf8fbfdfef9550b3936de2f864543edb76348b | 528 | aws-cdk-kt | Apache License 2.0 |
src/client/kotlin/org/teamvoided/dusk_autumn/entity/bird/render/BirdEntityModel.kt | TeamVoided | 737,359,498 | false | {"Kotlin": 665878, "Java": 10584} | package org.teamvoided.dusk_autumn.entity.bird.render
import net.minecraft.client.model.*
import net.minecraft.client.render.RenderLayer
import net.minecraft.client.render.entity.model.SinglePartEntityModel
import org.teamvoided.dusk_autumn.entity.BirdEntity
class BirdEntityModel(root: ModelPart) :
SinglePartEntityModel<BirdEntity>(RenderLayer::getEntityTranslucent) {
private val bone: ModelPart = root.getChild("bone")
private val block: ModelPart = bone.getChild("block")
override fun setAngles(
entity: BirdEntity,
limbAngle: Float,
limbDistance: Float,
animationProgress: Float,
headYaw: Float,
headPitch: Float
) {
block.yaw = headYaw * 0.017453292F;
block.pitch = headPitch * 0.017453292F;
}
override fun getPart(): ModelPart = this.bone
companion object {
val texturedModelData: TexturedModelData
get() {
val modelData = ModelData()
val modelPartData: ModelPartData = modelData.root
val modelPartData2: ModelPartData = modelPartData.addChild(
"bone",
ModelPartBuilder.create(),
ModelTransform.pivot(0f, 16f, 0f)
)
modelPartData2.addChild(
"block",
ModelPartBuilder.create().uv(0, 0)
.cuboid(-2.0f, -2.0f, -2.0f, 4.0f, 10.0f, 4.0f, Dilation.NONE),
ModelTransform.pivot(0f, 0f, 0f)
).addChild(
"beak",
ModelPartBuilder.create().uv(0, 0)
.cuboid(-1.0f, 0.0f, -4.0f, 2.0f, 2.0f, 2.0f, Dilation.NONE),
ModelTransform.pivot(0.0f, 0.0f, 0.0f)
)
return TexturedModelData.of(modelData, 16, 16)
}
}
} | 0 | Kotlin | 0 | 0 | 57aa70f1786d82b32f0b41aa8b9b34bf6b5cd08b | 1,893 | DusksAndDungeons | MIT License |
kzmq-tests/src/commonTest/kotlin/org/zeromq/tests/sockets/PushTests.kt | ptitjes | 386,722,015 | false | null | /*
* Copyright (c) 2021-2024 <NAME> and Kzmq contributors.
* Use of this source code is governed by the Apache 2.0 license.
*/
package org.zeromq.tests.sockets
import io.kotest.assertions.*
import io.kotest.common.*
import io.kotest.core.spec.style.*
import io.kotest.matchers.*
import kotlinx.coroutines.*
import org.zeromq.*
import org.zeromq.tests.utils.*
import kotlin.time.Duration.Companion.seconds
@OptIn(ExperimentalKotest::class)
@Suppress("unused")
class PushTests : FunSpec({
withContexts("simple connect-bind") { ctx1, ctx2, protocol ->
val address = randomAddress(protocol)
val pushSocket = ctx1.createPush().apply { connect(address) }
val pullSocket = ctx2.createPull().apply { bind(address) }
waitForConnections()
val message = Message("Hello, 0MQ!".encodeToByteArray())
pushSocket.send(message)
pullSocket shouldReceiveExactly listOf(message)
pushSocket.close()
pullSocket.close()
}
withContexts("simple bind-connect") { ctx1, ctx2, protocol ->
val address = randomAddress(protocol)
val pushSocket = ctx1.createPush().apply { bind(address) }
val pullSocket = ctx2.createPull().apply { connect(address) }
waitForConnections()
val message = Message("Hello, 0MQ!".encodeToByteArray())
pushSocket.send(message)
pullSocket shouldReceiveExactly listOf(message)
pushSocket.close()
pullSocket.close()
}
withContexts("lingers after disconnect").config(
// TODO investigate why these pairs are flaky
skip = setOf("cio-jeromq", "jeromq-cio"),
) { ctx1, ctx2, protocol ->
val address = randomAddress(protocol)
val messageCount = 100
val pullSocket = ctx2.createPull().apply { bind(address) }
val pushSocket = ctx1.createPush().apply { connect(address) }
waitForConnections()
var sent = 0
while (sent < messageCount) {
val message = Message(sent.encodeToByteArray())
pushSocket.send(message)
sent++
}
pushSocket.disconnect(address)
var received = 0
while (received < messageCount) {
val message = pullSocket.receive()
message.singleOrThrow().decodeToInt() shouldBe received
received++
}
received shouldBe messageCount
pushSocket.close()
pullSocket.close()
}
withContexts("lingers after close").config(
// TODO investigate why these tests are flaky
skip = setOf("cio"),
) { ctx1, ctx2, protocol ->
val address = randomAddress(protocol)
val messageCount = 100
val pullSocket = ctx2.createPull().apply { bind(address) }
val pushSocket = ctx1.createPush().apply { connect(address) }
waitForConnections()
var sent = 0
while (sent < messageCount) {
val message = Message(sent.encodeToByteArray())
pushSocket.send(message)
sent++
}
pushSocket.close()
var received = 0
while (received < messageCount) {
val message = pullSocket.receive()
message.singleOrThrow().decodeToInt() shouldBe received
received++
}
received shouldBe messageCount
pullSocket.close()
}
withContexts("SHALL consider a peer as available only when it has an outgoing queue that is not full") { ctx1, ctx2, protocol ->
val address1 = randomAddress(protocol)
val address2 = randomAddress(protocol)
val firstBatch = List(5) { index -> Message(ByteArray(1) { index.toByte() }) }
val secondBatch = List(10) { index -> Message(ByteArray(1) { (index + 10).toByte() }) }
val push = ctx1.createPush()
val pull1 = ctx2.createPull()
val pull2 = ctx2.createPull()
use(push, pull1, pull2) {
push.apply {
connect(address1)
sendHighWaterMark = 5
connect(address2)
}
pull1.apply { bind(address1) }
waitForConnections()
// Send each message of the first batch once per receiver
firstBatch.forEach { message -> repeat(2) { push.send(message) } }
// Send each message of the second batch once
secondBatch.forEach { message -> push.send(message) }
pull2.apply { bind(address2) }
waitForConnections()
all {
pull1 shouldReceiveExactly firstBatch + secondBatch
pull2 shouldReceiveExactly firstBatch
}
}
}
withContexts("SHALL route outgoing messages to available peers using a round-robin strategy") { ctx1, ctx2, protocol ->
val pullCount = 5
val address = randomAddress(protocol)
val push = ctx1.createPush().apply { bind(address) }
val pulls = List(pullCount) { ctx2.createPull().apply { connect(address) } }
waitForConnections(pullCount)
val messages = List(10) { index -> Message(ByteArray(1) { index.toByte() }) }
// Send each message once per receiver
messages.forEach { message -> repeat(pulls.size) { push.send(message) } }
all {
// Check each receiver got every messages
pulls.forEach { it shouldReceiveExactly messages }
}
}
withContext("SHALL suspend on sending when it has no available peers").config(
// TODO investigate why this fails with these engines
skip = setOf("jeromq", "zeromq.js"),
) { ctx, _ ->
val push = ctx.createPush()
val message = Message("Won't be sent".encodeToByteArray())
withTimeoutOrNull(1.seconds) {
push.send(message)
} shouldBe null
}
// TODO How is it different from previous test?
withContext("SHALL not accept further messages when it has no available peers").config(
// TODO investigate why this fails with these engines
skip = setOf("jeromq", "zeromq.js"),
) { ctx, _ ->
val push = ctx.createPush()
val message = Message("Won't be sent".encodeToByteArray())
withTimeoutOrNull(1.seconds) {
push.send(message)
} shouldBe null
}
withContexts("SHALL NOT discard messages that it cannot queue") { ctx1, ctx2, protocol ->
val address = randomAddress(protocol)
val push = ctx1.createPush().apply { connect(address) }
val messages = List(10) { index -> Message(ByteArray(1) { index.toByte() }) }
// Send each message once
messages.forEach { message -> push.send(message) }
val pull = ctx2.createPull().apply { bind(address) }
waitForConnections()
// Check each receiver got every messages
pull shouldReceiveExactly messages
}
})
| 21 | Kotlin | 0 | 6 | 1e6c7a35b7dc93b34a8f6da9d56fd5b3335dd790 | 6,897 | kzmq | Apache License 2.0 |
app/src/main/kotlin/com/zj/weather/view/city/CityListPage.kt | zhujiang521 | 422,904,634 | false | null | package com.zj.weather.view.city
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import com.zj.model.room.entity.CityInfo
import com.zj.utils.defaultCityState
import com.zj.utils.lce.NoContent
import com.zj.weather.R
import com.zj.weather.view.city.viewmodel.CityListViewModel
import com.zj.weather.view.city.widget.CityListItem
import com.zj.weather.view.city.widget.TitleBar
@Composable
fun CityListPage(
cityListViewModel: CityListViewModel,
onBack: () -> Unit
) {
val cityInfoList by cityListViewModel.cityInfoList.collectAsState(initial = arrayListOf())
CityListPage(
cityInfoList = cityInfoList, onBack = onBack, toWeatherDetails = {
defaultCityState.value = it
onBack()
}
) {
cityListViewModel.deleteCityInfo(it)
}
}
@Composable
fun CityListPage(
cityInfoList: List<CityInfo>,
onBack: () -> Unit,
toWeatherDetails: (CityInfo) -> Unit,
deleteCityInfo: (CityInfo) -> Unit
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = dimensionResource(id = R.dimen.page_margin))
.statusBarsPadding()
.navigationBarsPadding()
) {
// 标题栏
TitleBar(R.string.city_title, onBack)
if (cityInfoList.isNotEmpty()) {
val listState = rememberLazyListState()
LazyColumn(state = listState) {
items(cityInfoList) { cityInfo ->
CityListItem(
cityInfo,
cityInfo.isLocation != 1,
toWeatherDetails, deleteCityInfo
)
}
}
} else {
NoContent(tip = stringResource(id = R.string.add_location_warn2))
}
}
}
@Preview(showBackground = false, name = "城市列表")
@Composable
fun CityListPagePreview() {
val cityInfo = CityInfo(
name = "朱江",
province = "微子国",
city = "南街"
)
val cityList = arrayListOf<CityInfo>()
for (index in 0..10) {
cityList.add(cityInfo)
}
CityListPage(cityInfoList = cityList, {}, {}, {})
}
| 5 | null | 78 | 479 | a731e0b502fc22baf832307bb60b263c16376dab | 2,841 | PlayWeather | MIT License |
app/src/main/java/animation/constrainlayout/sample/com/sharedviewtransition/ui/views/SquareImageView.kt | crehmann | 134,263,987 | false | {"Kotlin": 10524} | package animation.constrainlayout.sample.com.sharedviewtransition.ui.views
import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
class SquareImageView : ImageView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = getMeasuredWidth()
setMeasuredDimension(width, width)
}
} | 0 | Kotlin | 0 | 0 | a869f2dd698e4000d8d616266f7ccab9a5e24397 | 681 | SharedViewTransitionExample | MIT License |
libs/rest/rest-server-impl/src/main/kotlin/net/corda/rest/server/impl/context/ClientRequestContext.kt | corda | 346,070,752 | false | null | package net.corda.httprpc.server.impl.context
import io.javalin.core.security.BasicAuthCredentials
import io.javalin.core.util.Header
import io.javalin.http.UploadedFile
import io.javalin.http.util.ContextUtil
import io.javalin.plugin.json.JsonMapper
import net.corda.httprpc.server.impl.security.RestAuthenticationProvider
/**
* Abstract HTTP request or WebSocket request
*/
interface ClientRequestContext {
companion object {
const val METHOD_SEPARATOR = ":"
}
/**
* Gets the request method.
*/
val method: String
/**
* Gets a request header by name, or null.
*/
fun header(header: String): String?
/**
* Gets a map of all the keys and values.
*/
val pathParamMap: Map<String, String>
/**
* Gets a map with all the query param keys and values.
*/
val queryParams: Map<String, List<String>>
/**
* Gets the request query string, or null.
*/
val queryString: String?
/**
* Gets the path that was used to match request (also includes before/after paths)
*/
val matchedPath: String
/**
* Gets the request path.
*/
val path: String
/**
* Gets a map with all the form param keys and values.
*/
val formParams: Map<String, List<String>> get() = emptyMap()
/**
* Gets the request body as a [String].
*/
val body: String get() = throw UnsupportedOperationException()
/**
* Gets applicable JSON mapper
*/
val jsonMapper: JsonMapper get() = throw UnsupportedOperationException()
/**
* Maps a JSON body to a Java/Kotlin class using the registered [io.javalin.plugin.json.JsonMapper]
*/
fun <T> bodyAsClass(clazz: Class<T>): T = throw UnsupportedOperationException()
/**
* Gets a list of [UploadedFile]s for the specified name, or empty list.
*/
fun uploadedFiles(fileName: String): List<UploadedFile> = throw UnsupportedOperationException()
/**
* Add special header values to the response to indicate which authentication methods are supported.
* More information can be found [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate).
*/
fun addWwwAuthenticateHeaders(restAuthProvider: RestAuthenticationProvider) {}
fun getResourceAccessString(): String {
// Examples of strings will look like:
// GET:/api/v1/permission/getpermission?id=c048679a-9654-4359-befc-9d2d22695a43
// POST:/api/v1/user/createuser
return method + METHOD_SEPARATOR + path.trimEnd('/') + if (!queryString.isNullOrBlank()) "?$queryString" else ""
}
/**
* Checks whether basic-auth credentials from the request exists.
*
* Returns a Boolean which is true if there is an Authorization header with
* Basic auth credentials. Returns false otherwise.
*/
fun basicAuthCredentialsExist(): Boolean = ContextUtil.hasBasicAuthCredentials(header(Header.AUTHORIZATION))
/**
* Gets basic-auth credentials from the request, or throws.
*
* Returns a wrapper object [BasicAuthCredentials] which contains the
* Base64 decoded username and password from the Authorization header.
*/
fun basicAuthCredentials(): BasicAuthCredentials = ContextUtil.getBasicAuthCredentials(header(Header.AUTHORIZATION))
} | 82 | null | 7 | 69 | 0766222eb6284c01ba321633e12b70f1a93ca04e | 3,354 | corda-runtime-os | Apache License 2.0 |
src/test/kotlin/algorithms/leetcode/medium/AddTwoNumbersKtTest.kt | DenisLatushko | 615,981,611 | false | {"Kotlin": 110863} | package algorithms.leetcode.medium
import algorithms.utils.ListNode
import algorithms.utils.toInvertedList
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
import kotlin.test.assertEquals
@RunWith(Parameterized::class)
class AddTwoNumbersKtTest(
private val numberX: ListNode?,
private val numberY: ListNode?,
private val expectedResult: ListNode
) {
@Test
fun `given 2 numbers when add then to each other then result is a sum of two of them`() {
val actualResult = addTwoNumbers(numberX, numberY)
assertEquals(expectedResult, actualResult)
}
companion object {
private val num1 = 111.toInvertedList()
private val num2 = 222.toInvertedList()
private val num3 = 0.toInvertedList()
private val num4 = 1111.toInvertedList()
private val num5 = 999.toInvertedList()
private val num6 = 9999.toInvertedList()
@JvmStatic
@Parameters(name = "Given numbers {0} and {1} when add then result is {2}")
fun data() = listOf(
arrayOf(num1, num2, 333.toInvertedList()),
arrayOf(num3, num3, num3),
arrayOf(num1, num3, num1),
arrayOf(num3, num1, num1),
arrayOf(num1, num4, 1222.toInvertedList()),
arrayOf(num4, num1, 1222.toInvertedList()),
arrayOf(null, null, 0.toInvertedList()),
arrayOf(null, num1, num1),
arrayOf(num1, null, num1),
arrayOf(num5, num5, 1998.toInvertedList()),
arrayOf(num5, num6, 10998.toInvertedList())
)
}
} | 0 | Kotlin | 0 | 0 | 1f01e1329c57b10e28b87c625a32c7d259bac471 | 1,670 | leetcode | Apache License 2.0 |
CocktailCatalog/app/src/main/java/com/example/cocktailcatalog/api/deserializers/DrinkListByIngrediendDeserializer.kt | ketiovv | 326,156,879 | false | null | package com.example.cocktailcatalog.api.deserializers
import com.example.cocktailcatalog.models.entities.Drink
import com.example.cocktailcatalog.models.entities.DrinkList
import com.google.gson.*
import java.lang.reflect.Type
class DrinkListByIngrediendDeserializer: JsonDeserializer<DrinkList> {
override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?
): DrinkList {
//Log.d("Test/Deserializer", "Using a custom deserializer for the Login request")
val gson = Gson()
val drinkList = DrinkList()
// var drink = gson.fromJson(json, Drink::class.java)
val jsonObject = json!!.asJsonObject
//Log.d("myTag", jsonObject.asString)
var jsonDrinks = jsonObject.get("drinks")
if(!jsonDrinks.isJsonNull)
{
if (jsonDrinks.isJsonArray) {
jsonDrinks = jsonObject.getAsJsonArray("drinks")
for (d in jsonDrinks) {
val drin = d.asJsonObject
var jsonId = drin.get("idDrink")
var id = gson.fromJson(jsonId, String::class.java)
var jsonName = drin.get("strDrink")
var name = gson.fromJson(jsonName, String::class.java)
drinkList.add(Drink(id, name, "", "", "", "", "", false))
}
}
else{
drinkList.add(Drink("","","","","","","",false))
}
}
else{
drinkList.add(Drink("","","","","","","",false))
}
return drinkList
}
} | 0 | Kotlin | 0 | 1 | d5ae9336422405098f123296db0bc26bcc8d6494 | 1,641 | cocktail-catalog | MIT License |
fugle-kt-core/src/main/kotlin/io/github/chehsunliu/fuglekt/core/DefaultFugleAsyncClient.kt | chehsunliu | 483,977,892 | false | null | package io.github.chehsunliu.fuglekt.core
import io.github.chehsunliu.fuglekt.core.model.GetCandlesResponse
import io.github.chehsunliu.fuglekt.core.model.GetChartResponse
import io.github.chehsunliu.fuglekt.core.model.GetDealtsResponse
import io.github.chehsunliu.fuglekt.core.model.GetMetaResponse
import io.github.chehsunliu.fuglekt.core.model.GetQuoteResponse
import io.github.chehsunliu.fuglekt.core.model.GetVolumesResponse
import java.io.IOException
import java.time.LocalDate
import java.util.concurrent.CompletableFuture
import java.util.zip.GZIPInputStream
import kotlinx.coroutines.future.await
import kotlinx.serialization.SerializationException
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.Call
import okhttp3.Callback
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
internal class DefaultFugleAsyncClient(private val baseUrl: HttpUrl, private val token: String) :
FugleAsyncClient {
private val client = OkHttpClient()
override suspend fun getMeta(symbolId: String, oddLot: Boolean?): GetMetaResponse {
val urlBuilder =
HttpUrl.Builder()
.configureUrlBuilder()
.addEncodedPathSegments("realtime/v0.3/intraday/meta")
.addQueryParameter("symbolId", symbolId)
if (oddLot != null) {
urlBuilder.addQueryParameter("oddLot", oddLot.toString())
}
val request = Request.Builder().configureRequestBuilder().get().url(urlBuilder.build()).build()
return execute<GetMetaResponse>(request).await()
}
override suspend fun getQuote(symbolId: String, oddLot: Boolean?): GetQuoteResponse {
val urlBuilder =
HttpUrl.Builder()
.configureUrlBuilder()
.addEncodedPathSegments("realtime/v0.3/intraday/quote")
.addQueryParameter("symbolId", symbolId)
if (oddLot != null) {
urlBuilder.addQueryParameter("oddLot", oddLot.toString())
}
val request = Request.Builder().configureRequestBuilder().get().url(urlBuilder.build()).build()
return execute<GetQuoteResponse>(request).await()
}
override suspend fun getChart(symbolId: String, oddLot: Boolean?): GetChartResponse {
val urlBuilder =
HttpUrl.Builder()
.configureUrlBuilder()
.addEncodedPathSegments("realtime/v0.3/intraday/chart")
.addQueryParameter("symbolId", symbolId)
if (oddLot != null) {
urlBuilder.addQueryParameter("oddLot", oddLot.toString())
}
val request = Request.Builder().configureRequestBuilder().get().url(urlBuilder.build()).build()
return execute<GetChartResponse>(request).await()
}
override suspend fun getDealts(
symbolId: String,
limit: Int?,
offset: Int?,
oddLot: Boolean?
): GetDealtsResponse {
val urlBuilder =
HttpUrl.Builder()
.configureUrlBuilder()
.addEncodedPathSegments("realtime/v0.3/intraday/dealts")
.addQueryParameter("symbolId", symbolId)
if (limit != null) {
urlBuilder.addQueryParameter("limit", limit.toString())
}
if (offset != null) {
urlBuilder.addQueryParameter("offset", offset.toString())
}
if (oddLot != null) {
urlBuilder.addQueryParameter("oddLot", oddLot.toString())
}
val request = Request.Builder().configureRequestBuilder().get().url(urlBuilder.build()).build()
return execute<GetDealtsResponse>(request).await()
}
override suspend fun getVolumes(symbolId: String, oddLot: Boolean?): GetVolumesResponse {
val urlBuilder =
HttpUrl.Builder()
.configureUrlBuilder()
.addEncodedPathSegments("realtime/v0.3/intraday/volumes")
.addQueryParameter("symbolId", symbolId)
if (oddLot != null) {
urlBuilder.addQueryParameter("oddLot", oddLot.toString())
}
val request = Request.Builder().configureRequestBuilder().get().url(urlBuilder.build()).build()
return execute<GetVolumesResponse>(request).await()
}
override suspend fun getCandles(
symbolId: String,
startDate: LocalDate,
endDate: LocalDate
): GetCandlesResponse {
val url =
HttpUrl.Builder()
.configureUrlBuilder()
.addEncodedPathSegments("marketdata/v0.3/candles")
.addQueryParameter("symbolId", symbolId)
.addQueryParameter("from", startDate.toString())
.addQueryParameter("to", endDate.toString())
.build()
val request = Request.Builder().configureRequestBuilder().get().url(url).build()
return execute<GetCandlesResponse>(request).await()
}
override fun close() {
client.dispatcher.executorService.shutdown()
}
private fun HttpUrl.Builder.configureUrlBuilder(): HttpUrl.Builder =
this.scheme(baseUrl.scheme)
.host(baseUrl.host)
.port(baseUrl.port)
.addQueryParameter("apiToken", token)
private fun Request.Builder.configureRequestBuilder(): Request.Builder =
this.addHeader("Accept", "*/*").addHeader("Accept-Encoding", "gzip")
private inline fun <reified T> execute(request: Request): CompletableFuture<T> {
val future = CompletableFuture<T>()
client
.newCall(request)
.enqueue(
object : Callback {
override fun onFailure(call: Call, e: IOException) {
future.completeExceptionally(e)
}
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) {
future.completeExceptionally(FugleKtException.from(response))
return
}
val body =
if (response.headers("Content-Encoding").any {
it.equals("gzip", ignoreCase = true)
}) {
GZIPInputStream(response.body!!.byteStream())
.bufferedReader(Charsets.UTF_8)
.use { it.readText() }
} else {
response.body!!.string()
}
try {
future.complete(Json.decodeFromString<T>(body))
} catch (e: SerializationException) {
future.completeExceptionally(e)
}
}
})
return future
}
}
| 1 | Kotlin | 0 | 2 | 25c78eaadbc08e3779ec99cf9b44758b784c20c4 | 6,402 | fugle-kt | Apache License 2.0 |
src/main/kotlin/character/Guild.kt | drakon64 | 622,012,311 | false | {"Kotlin": 174367} | package cloud.drakon.ktlodestone.character
import cloud.drakon.ktlodestone.iconlayers.IconLayers
import cloud.drakon.ktlodestone.searchLodestoneCharacter
/** A character's Free Company or PvP Team. */
data class Guild(
/** The name of the Free Company or PvP Team. */
val name: String,
/** The ID of the Free Company or PvP Team. */
val id: String,
/** The layers that make up the icon of the Free Company or PvP Team. Always `null` when returned by [searchLodestoneCharacter]. */
val iconLayers: IconLayers?,
)
| 4 | Kotlin | 0 | 1 | 9927f7d6181ac69140fbc58967ad3bc4c924b1f0 | 538 | KtLodestone | MIT License |
tests/YearTests.kt | fluidsonic | 187,854,304 | false | null | import io.fluidsonic.time.*
import kotlin.test.*
class YearTests {
@Test
fun testIsLeap() {
val leapYears = listOf(
2000, 2004, 2008, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, 2044, 2048,
2052, 2056, 2060, 2064, 2068, 2072, 2076, 2080, 2084, 2088, 2092, 2096, 2104,
)
for (year in 1999 .. 2107)
if (leapYears.contains(year))
assertTrue(Year.isLeap(year), message = "Expected $year to be a leap year but it isn't.")
else
assertFalse(Year.isLeap(year), message = "Expected $year to not be a leap year but it is.")
}
}
| 1 | Kotlin | 4 | 40 | a3e47f6fee989fd098cd52873acea7b10239ae0e | 555 | fluid-time | Apache License 2.0 |
src/main/kotlin/me/mrkirby153/KirBot/command/executors/fun/CommandSelfroles.kt | mrkirby153 | 77,095,266 | false | null | package me.mrkirby153.KirBot.command.executors.`fun`
import me.mrkirby153.KirBot.command.CommandCategory
import me.mrkirby153.KirBot.command.CommandException
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.annotations.CommandDescription
import me.mrkirby153.KirBot.command.annotations.IgnoreWhitelist
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.user.CLEARANCE_ADMIN
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.FuzzyMatchException
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Role
class CommandSelfroles {
@Command(name = "selfrole", category = CommandCategory.UTILITY)
@CommandDescription("Displays a list of self-assignable roles")
fun execute(context: Context, cmdContext: CommandContext) {
var msg = "Self-assignable roles are:\n```\n"
val selfroles = context.kirbotGuild.getSelfroles()
selfroles.mapNotNull {
context.guild.getRoleById(it)
}.forEach {
msg += "\n${it.id} - ${it.name}"
if (msg.length > 1900) {
msg += "```"
context.channel.sendMessage(msg).queue()
msg = "```"
}
}
msg += "```"
context.channel.sendMessage(msg).queue()
}
@Command(name = "join", arguments = ["<role:string...>"], parent = "selfrole", category = CommandCategory.UTILITY, permissions = [Permission.MANAGE_ROLES])
@CommandDescription("Join a self-assignable role")
fun join(context: Context, cmdContext: CommandContext) {
val role = cmdContext.get<String>("role")!!
val foundRole = findSelfassignRole(context, role)
if (foundRole.id in context.member!!.roles.map { it.id })
throw CommandException("You are already in `${foundRole.name}`")
if (foundRole.position >= context.guild.selfMember.roles.sortedByDescending { it.position }.first().position)
throw CommandException(
"That role is above my highest role. I can't assign that to you!")
context.guild.addRoleToMember(context.member!!, foundRole).queue()
context.send().success("Joined role `${foundRole.name}`", true).queue()
}
@Command(name = "leave", arguments = ["<role:string...>"], parent = "selfrole", category = CommandCategory.UTILITY, permissions = [Permission.MANAGE_PERMISSIONS])
@CommandDescription("Leave a self-assignable role")
fun leave(context: Context, cmdContext: CommandContext) {
val role = cmdContext.get<String>("role")!!
val foundRole = findSelfassignRole(context, role)
if (foundRole.id !in context.member!!.roles.map { it.id })
throw CommandException("You are not in `${foundRole.name}`")
if (foundRole.position >= context.guild.selfMember.roles.sortedByDescending { it.position }.first().position)
throw CommandException(
"That role is above my highest role. I can't remove that from you!")
context.guild.addRoleToMember(context.member!!, foundRole).queue()
context.send().success("Left role `${foundRole.name}`", true).queue()
}
@Command(name = "add", arguments = ["<role:string...>"], clearance = CLEARANCE_ADMIN,
parent = "selfrole", category = CommandCategory.UTILITY)
@CommandDescription("Add a role to the list of self-assignable roles")
@IgnoreWhitelist
fun add(context: Context, cmdContext: CommandContext) {
try {
val role = cmdContext.get<String>("role")!!
val foundRole = context.kirbotGuild.matchRole(role) ?: throw CommandException(
"No role was found for that query")
if (foundRole.id in context.kirbotGuild.getSelfroles())
throw CommandException("`${foundRole.name}` already is a selfrole!")
context.kirbotGuild.createSelfrole(foundRole.id)
context.send().success(
"Added `${foundRole.name}` to the list of self assignable roles!").queue()
} catch (e: FuzzyMatchException.TooManyMatchesException) {
throw CommandException(
"Too many matches for that query. Try a more specific query or the role's id instead")
} catch (e: FuzzyMatchException.NoMatchesException) {
throw CommandException("No role was found for that query")
}
}
@Command(name = "remove", arguments = ["<role:string...>"], clearance = CLEARANCE_ADMIN,
parent = "selfrole", category = CommandCategory.UTILITY)
@CommandDescription("Removes a role from the list of self-assignable roles")
@IgnoreWhitelist
fun remove(context: Context, cmdContext: CommandContext) {
val role = cmdContext.get<String>("role")!!
try {
val foundRole = context.kirbotGuild.matchRole(role) ?: throw CommandException(
"No role was found for that query")
if (foundRole.id !in context.kirbotGuild.getSelfroles())
throw CommandException("`${foundRole.name}` isn't a selfrole!")
context.kirbotGuild.removeSelfrole(foundRole.id)
context.send().success(
"Removed `${foundRole.name}` from the list of self assignable roles!").queue()
} catch (e: FuzzyMatchException.TooManyMatchesException) {
throw CommandException(
"Too many matches for that query. Try a more specific query or the role's id instead")
} catch (e: FuzzyMatchException.NoMatchesException) {
throw CommandException("No role was found for that query")
}
}
private fun findSelfassignRole(context: Context, query: String): Role {
try {
val foundRole = context.kirbotGuild.matchRole(query)
if (foundRole == null || foundRole.id !in context.kirbotGuild.getSelfroles())
throw CommandException("No self-assignable role was found with that query")
return foundRole
} catch (e: FuzzyMatchException.TooManyMatchesException) {
throw CommandException(
"Too many roles were found for the query. Try a more specific query or the role id")
} catch (e: FuzzyMatchException.NoMatchesException) {
throw CommandException("No role was found for that query")
}
}
} | 0 | Kotlin | 1 | 6 | 32d929ccf02c647a7e0ba16d33718405b1cf6dc1 | 6,433 | KirBot | MIT License |
bindings/gtk/gtk4/src/nativeMain/kotlin/org/gtkkn/bindings/gtk/CssLocation.kt | gtk-kn | 609,191,895 | false | {"Kotlin": 10448515, "Shell": 2740} | // This is a generated file. Do not modify.
package org.gtkkn.bindings.gtk
import kotlinx.cinterop.CPointed
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.pointed
import kotlinx.cinterop.reinterpret
import org.gtkkn.extensions.glib.Record
import org.gtkkn.extensions.glib.RecordCompanion
import org.gtkkn.native.gtk.GtkCssLocation
import kotlin.ULong
/**
* Represents a location in a file or other source of data parsed
* by the CSS engine.
*
* The @bytes and @line_bytes offsets are meant to be used to
* programmatically match data. The @lines and @line_chars offsets
* can be used for printing the location in a file.
*
* Note that the @lines parameter starts from 0 and is increased
* whenever a CSS line break is encountered. (CSS defines the C character
* sequences "\r\n", "\r", "\n" and "\f" as newlines.)
* If your document uses different rules for line breaking, you might want
* run into problems here.
*/
public class CssLocation(
pointer: CPointer<GtkCssLocation>,
) : Record {
public val gtkCssLocationPointer: CPointer<GtkCssLocation> = pointer
/**
* number of bytes parsed since the beginning
*/
public var bytes: ULong
get() = gtkCssLocationPointer.pointed.bytes
set(`value`) {
gtkCssLocationPointer.pointed.bytes = value
}
/**
* number of characters parsed since the beginning
*/
public var chars: ULong
get() = gtkCssLocationPointer.pointed.chars
set(`value`) {
gtkCssLocationPointer.pointed.chars = value
}
/**
* number of full lines that have been parsed. If you want to
* display this as a line number, you need to add 1 to this.
*/
public var lines: ULong
get() = gtkCssLocationPointer.pointed.lines
set(`value`) {
gtkCssLocationPointer.pointed.lines = value
}
/**
* Number of bytes parsed since the last line break
*/
public var lineBytes: ULong
get() = gtkCssLocationPointer.pointed.line_bytes
set(`value`) {
gtkCssLocationPointer.pointed.line_bytes = value
}
/**
* Number of characters parsed since the last line break
*/
public var lineChars: ULong
get() = gtkCssLocationPointer.pointed.line_chars
set(`value`) {
gtkCssLocationPointer.pointed.line_chars = value
}
public companion object : RecordCompanion<CssLocation, GtkCssLocation> {
override fun wrapRecordPointer(pointer: CPointer<out CPointed>): CssLocation =
CssLocation(pointer.reinterpret())
}
}
| 0 | Kotlin | 0 | 13 | c033c245f1501134c5b9b46212cd153c61f7efea | 2,626 | gtk-kn | Creative Commons Attribution 4.0 International |
krpc/krpc-test/src/jvmMain/kotlin/kotlinx/rpc/krpc/test/KRPCTestServer.kt | Kotlin | 739,292,079 | false | {"Kotlin": 501936, "Java": 1587, "JavaScript": 1134, "Shell": 1072, "Dockerfile": 69} | /*
* Copyright 2023-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.rpc.krpc.test
import kotlinx.rpc.krpc.RPCConfig
import kotlinx.rpc.krpc.RPCTransport
import kotlinx.rpc.krpc.server.KRPCServer
/**
* Implementation of [KRPCServer] that can be used to test custom [RPCTransport].
*
* NOTE: one [RPCTransport] is meant to be used by only one server,
* but this class allows for abuse. Be cautious about how you handle [RPCTransport] with this class.
*/
class KRPCTestServer(
config: RPCConfig.Server,
transport: RPCTransport,
) : KRPCServer(config, transport)
| 23 | Kotlin | 17 | 733 | b946964ca7838d40ba68ad98fe4056f3ed17c635 | 650 | kotlinx-rpc | Apache License 2.0 |
compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/inline/WrapInlineDeclarationsWithReifiedTypeParametersLowering.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.ir.backend.js.lower.inline
import org.jetbrains.kotlin.backend.common.BackendContext
import org.jetbrains.kotlin.backend.common.BodyLoweringPass
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.ir.backend.js.ir.JsIrBuilder
import org.jetbrains.kotlin.ir.backend.js.utils.isInlineFunWithReifiedParameter
import org.jetbrains.kotlin.ir.builders.declarations.addFunction
import org.jetbrains.kotlin.ir.builders.declarations.addValueParameter
import org.jetbrains.kotlin.ir.declarations.IrDeclaration
import org.jetbrains.kotlin.ir.declarations.IrDeclarationContainer
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.expressions.IrBody
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrFunctionReference
import org.jetbrains.kotlin.ir.expressions.impl.IrFunctionReferenceImpl
import org.jetbrains.kotlin.ir.types.IrTypeArgument
import org.jetbrains.kotlin.ir.types.IrTypeSubstitutor
import org.jetbrains.kotlin.ir.util.typeSubstitutionMap
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.name.Name
// Replace callable reference on inline function with reified parameter
// with callable reference on new non inline function with substituted types
class WrapInlineDeclarationsWithReifiedTypeParametersLowering(val context: BackendContext) : BodyLoweringPass {
private val irFactory
get() = context.irFactory
override fun lower(irBody: IrBody, container: IrDeclaration) {
irBody.transformChildrenVoid(object : IrElementTransformerVoid() {
override fun visitFunctionReference(expression: IrFunctionReference): IrExpression {
expression.transformChildrenVoid()
val owner = expression.symbol.owner as? IrSimpleFunction
?: return expression
if (!owner.isInlineFunWithReifiedParameter()) {
return expression
}
val substitutionMap = expression.typeSubstitutionMap
.entries
.map { (key, value) ->
key to (value as IrTypeArgument)
}
val typeSubstitutor = IrTypeSubstitutor(
substitutionMap.map { it.first },
substitutionMap.map { it.second },
context.irBuiltIns
)
val function = irFactory.addFunction(container.parent as IrDeclarationContainer) {
name = Name.identifier("${owner.name}${"$"}wrap")
returnType = owner.returnType
visibility = DescriptorVisibilities.PRIVATE
origin = JsIrBuilder.SYNTHESIZED_DECLARATION
}.also { function ->
owner.valueParameters.forEach { valueParameter ->
function.addValueParameter(
valueParameter.name,
typeSubstitutor.substitute(valueParameter.type)
)
}
function.body = irFactory.createBlockBody(
expression.startOffset,
expression.endOffset
) {
statements.add(
JsIrBuilder.buildReturn(
function.symbol,
JsIrBuilder.buildCall(owner.symbol).also { call ->
call.dispatchReceiver = expression.dispatchReceiver
call.extensionReceiver = expression.extensionReceiver
function.valueParameters.forEachIndexed { index, valueParameter ->
call.putValueArgument(index, JsIrBuilder.buildGetValue(valueParameter.symbol))
}
for (i in 0 until expression.typeArgumentsCount) {
call.putTypeArgument(i, expression.getTypeArgument(i))
}
},
owner.returnType
)
)
}
}
return IrFunctionReferenceImpl.fromSymbolOwner(
expression.startOffset,
expression.endOffset,
expression.type,
function.symbol,
function.typeParameters.size,
expression.reflectionTarget
)
}
})
}
} | 157 | Kotlin | 5209 | 42,102 | 65f712ab2d54e34c5b02ffa3ca8c659740277133 | 5,274 | kotlin | Apache License 2.0 |
app/src/main/java/com/vmcorp/foodisu/depenpencyInjection/mealsViewModel/MealsViewModelComponent.kt | dev-VinayM | 324,406,820 | false | null | package com.vmcorp.foodisu.depenpencyInjection.mealsViewModel
import com.vmcorp.foodisu.view.HomeActivity
import dagger.Component
@Component(modules = [MealsViewModelModule::class])
interface MealsViewModelComponent {
fun inject(homeActivity: HomeActivity)
} | 0 | Kotlin | 0 | 0 | ed79648872a13fe85b263233985d4a2f1009de9e | 264 | Foodisu | MIT License |
app/src/main/java/com/akstae/studingenglishapp/friendsMenu.kt | Sorenty | 847,428,348 | false | {"Kotlin": 30172} | package com.akstae.studingenglishapp
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class friendsMenu : AppCompatActivity() {
private lateinit var soundButtonHelper: SoundButtonHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.friends_list)
soundButtonHelper = SoundButtonHelper(this)
val backButton: Button = findViewById(R.id.backButton)
soundButtonHelper.setSoundOnClickListener(backButton, View.OnClickListener {
val intent = Intent(this, MainMenu::class.java)
startActivity(intent)
})
}
} | 0 | Kotlin | 0 | 0 | 6920dec5f2a874c880dafcddd476a3168c0a3412 | 793 | Learn-Eng-Game | MIT License |
src/main/java/tornadofx/App.kt | cliffred | 58,454,600 | true | {"Kotlin": 168325, "Java": 3181, "CSS": 593} | package tornadofx
import javafx.application.Application
import javafx.scene.Scene
import javafx.scene.layout.Pane
import javafx.stage.Stage
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
open class App : Application() {
open val primaryView: KClass<out View> = DeterminedByParameter::class
override fun start(stage: Stage) {
FX.registerApplication(this, stage)
try {
val view = find(determinePrimaryView())
stage.apply {
scene = Scene(view.root)
view.properties["tornadofx.scene"] = scene
scene.stylesheets.addAll(FX.stylesheets)
titleProperty().bind(view.titleProperty)
show()
}
FX.initialized.value = true
} catch (ex: Exception) {
Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ex)
}
}
@Suppress("UNCHECKED_CAST")
private fun determinePrimaryView(): KClass<out View> {
if (primaryView == DeterminedByParameter::class) {
val viewClassName = parameters.named?.get("view-class") ?: throw IllegalArgumentException("No provided --view-class parameter and primaryView was not overridden. Choose one strategy to specify the primary View")
val viewClass = Class.forName(viewClassName)
if (View::class.java.isAssignableFrom(viewClass)) return viewClass.kotlin as KClass<out View>
throw IllegalArgumentException("Class specified by --class-name is not a subclass of tornadofx.View")
} else {
return primaryView
}
}
inline fun <reified T : Injectable> inject(): ReadOnlyProperty<App, T> = object : ReadOnlyProperty<App, T> {
override fun getValue(thisRef: App, property: KProperty<*>) = find(T::class)
}
class DeterminedByParameter : View() {
override val root = Pane()
}
} | 0 | Kotlin | 0 | 0 | c2f0095b5363fe53db3c305fab85a5690bd22942 | 1,981 | tornadofx | Apache License 2.0 |
src/main/templates/common/io/github/aecsocket/klam/Vec3.kt | aecsocket | 616,665,512 | false | null | @file:Suppress("NOTHING_TO_INLINE")
package io.github.aecsocket.klam
data class {{ T }}Vec3(
@JvmField val x: {{ Type }},
@JvmField val y: {{ Type }},
@JvmField val z: {{ Type }},
) {
companion object {
val {{ Zero }} get() = {{ T }}Vec3({{ zero }}, {{ zero }}, {{ zero }})
val {{ One }} get() = {{ T }}Vec3({{ one }}, {{ one }}, {{ one }})
val X get() = {{ T }}Vec3({{ one }}, {{ zero }}, {{ zero }})
val Y get() = {{ T }}Vec3({{ zero }}, {{ one }}, {{ zero }})
val Z get() = {{ T }}Vec3({{ zero }}, {{ zero }}, {{ one }})
}
constructor(v: {{ T }}Vec2, z: {{ Type }}) : this(v.x, v.y, z)
constructor(s: {{ Type }}) : this(s, s, s)
{% if isNumber %}
constructor(v: {{ S }}Vec3) : this(v.x.{{ sToT }}, v.y.{{ sToT }}, v.z.{{ sToT }})
{% endif %}
operator fun get(index: Int) = when (index) {
0 -> x
1 -> y
2 -> z
else -> throw IndexOutOfBoundsException(index)
}
fun x(x: {{ Type }}) = {{ T }}Vec3(x, y, z)
fun y(y: {{ Type }}) = {{ T }}Vec3(x, y, z)
fun z(z: {{ Type }}) = {{ T }}Vec3(x, y, z)
fun toArray() = {{ arrayOf }}(x, y, z)
fun asString(fmt: String) = "($fmt, $fmt, $fmt)".format(x, y, z)
override fun toString() = asString("{{ toStringFormat }}")
inline fun map(block: ({{ Type }}) -> {{ Type }}) = {{ T }}Vec3(block(x), block(y), block(z))
{% if isNumber %}
inline operator fun unaryMinus() = {{ T }}Vec3(-x, -y, -z)
inline operator fun inc() = {{ T }}Vec3(x + {{ one }}, y + {{ one }}, z + {{ one }})
inline operator fun dec() = {{ T }}Vec3(x - {{ one }}, y - {{ one }}, z - {{ one }})
@JvmName("add")
inline operator fun plus (s: {{ Type }}) = {{ T }}Vec3(x + s, y + s, z + s)
@JvmName("sub")
inline operator fun minus(s: {{ Type }}) = {{ T }}Vec3(x - s, y - s, z - s)
@JvmName("mul")
inline operator fun times(s: {{ Type }}) = {{ T }}Vec3(x * s, y * s, z * s)
@JvmName("div")
inline operator fun div (s: {{ Type }}) = {{ T }}Vec3(x / s, y / s, z / s)
@JvmName("add")
inline operator fun plus (v: {{ T }}Vec3) = {{ T }}Vec3(x + v.x, y + v.y, z + v.z)
@JvmName("sub")
inline operator fun minus(v: {{ T }}Vec3) = {{ T }}Vec3(x - v.x, y - v.y, z - v.z)
@JvmName("mul")
inline operator fun times(v: {{ T }}Vec3) = {{ T }}Vec3(x * v.x, y * v.y, z * v.z)
@JvmName("div")
inline operator fun div (v: {{ T }}Vec3) = {{ T }}Vec3(x / v.x, y / v.y, z / v.z)
{% else %}
inline operator fun not() = {{ T }}Vec3(!x, !y, !z)
{% endif %}
fun compareTo(v: {{ T }}Vec3) = IVec3(x.compareTo(v.x), y.compareTo(v.y), z.compareTo(v.z))
inline infix fun eq(v: {{ T }}Vec3) = BVec3(x.compareTo(v.x) == 0, y.compareTo(v.y) == 0, z.compareTo(v.z) == 0)
inline infix fun ne(v: {{ T }}Vec3) = BVec3(x.compareTo(v.x) != 0, y.compareTo(v.y) != 0, z.compareTo(v.z) != 0)
{% if isNumber %}
inline infix fun lt(v: {{ T }}Vec3) = BVec3(x < v.x, y < v.y, z < v.z)
inline infix fun le(v: {{ T }}Vec3) = BVec3(x <= v.x, y <= v.y, z <= v.z)
inline infix fun gt(v: {{ T }}Vec3) = BVec3(x > v.x, y > v.y, z > v.z)
inline infix fun ge(v: {{ T }}Vec3) = BVec3(x >= v.x, y >= v.y, z >= v.z)
{% endif %}
}
{% if isNumber %}
@JvmName("add")
inline operator fun {{ Type }}.plus (v: {{ T }}Vec3) = {{ T }}Vec3(this + v.x, this + v.y, this + v.z)
@JvmName("sub")
inline operator fun {{ Type }}.minus(v: {{ T }}Vec3) = {{ T }}Vec3(this - v.x, this - v.y, this - v.z)
@JvmName("mul")
inline operator fun {{ Type }}.times(v: {{ T }}Vec3) = {{ T }}Vec3(this * v.x, this * v.y, this * v.z)
@JvmName("div")
inline operator fun {{ Type }}.div (v: {{ T }}Vec3) = {{ T }}Vec3(this / v.x, this / v.y, this / v.z)
inline fun min(a: {{ T }}Vec3, b: {{ T }}Vec3) = {{ T }}Vec3(kotlin.math.min(a.x, b.x), kotlin.math.min(a.y, b.y), kotlin.math.min(a.z, b.z))
inline fun max(a: {{ T }}Vec3, b: {{ T }}Vec3) = {{ T }}Vec3(kotlin.math.max(a.x, b.x), kotlin.math.max(a.y, b.y), kotlin.math.max(a.z, b.z))
inline fun minComponent(v: {{ T }}Vec3) = kotlin.math.min(v.x, kotlin.math.min(v.y, v.z))
inline fun maxComponent(v: {{ T }}Vec3) = kotlin.math.max(v.x, kotlin.math.max(v.y, v.z))
inline fun clamp(v: {{ T }}Vec3, min: {{ T }}Vec3, max: {{ T }}Vec3) = {{ T }}Vec3(clamp(v.x, min.x, max.x), clamp(v.y, min.y, max.y), clamp(v.z, min.z, max.z))
inline fun clamp(v: {{ T }}Vec3, min: {{ Type }}, max: {{ Type }}) = {{ T }}Vec3(clamp(v.x, min, max), clamp(v.y, min, max), clamp(v.z, min, max))
inline fun abs(v: {{ T }}Vec3) = {{ T }}Vec3(kotlin.math.abs(v.x), kotlin.math.abs(v.y), kotlin.math.abs(v.z))
{% if isDecimal %}
inline fun lengthSq(v: {{ T }}Vec3) = sqr(v.x) + sqr(v.y) + sqr(v.z)
inline fun length(v: {{ T }}Vec3) = kotlin.math.sqrt(lengthSq(v))
inline fun normalize(v: {{ T }}Vec3): {{ T }}Vec3 {
val l = {{ one }} / length(v)
return {{ T }}Vec3(v.x * l, v.y * l, v.z * l)
}
inline fun distanceSq(a: {{ T }}Vec3, b: {{ T }}Vec3) = lengthSq(b - a)
inline fun distance(a: {{ T }}Vec3, b: {{ T }}Vec3) = length(b - a)
inline fun mix(a: {{ T }}Vec3, b: {{ T }}Vec3, f: {{ Type }}) = {{ T }}Vec3(mix(a.x, b.x, f), mix(a.y, b.y, f), mix(a.z, b.z, f))
inline fun dot(a: {{ T }}Vec3, b: {{ T }}Vec3) = a.x * b.x + a.y * b.y + a.z * b.z
inline fun cross(a: {{ T }}Vec3, b: {{ T }}Vec3) = {{ T }}Vec3(
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x,
)
{% endif %}
{% else %}
inline fun all(v: {{ T }}Vec3) = v.x && v.y && v.z
inline fun any(v: {{ T }}Vec3) = v.x || v.y || v.z
inline fun none(v: {{ T }}Vec3) = !v.x && !v.y && !v.z
{% endif %}
fun JRandom.next{{ T }}Vec3() = {{ T }}Vec3({{ nextRandom }}(), {{ nextRandom }}(), {{ nextRandom }}())
fun KRandom.next{{ T }}Vec3() = {{ T }}Vec3({{ nextRandom }}(), {{ nextRandom }}(), {{ nextRandom }}())
//region Alternate accessors
{{ vecAlternateAccessors3 }}
//endregion
//region Swizzles
{{ vecSwizzles3 }}
//endregion
| 0 | Kotlin | 0 | 0 | bc344b2996d70c8b17d3f7ae8626f55d40bfb6bd | 5,956 | klam | MIT License |
app/src/main/java/com/example/grooveix/ui/fragment/PlaylistTracksFragment.kt | DmitryLebovski | 747,392,361 | false | {"Kotlin": 147621} | package com.example.grooveix.ui.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DefaultItemAnimator
import com.example.grooveix.R
import com.example.grooveix.databinding.FragmentPlaylistTracksBinding
import com.example.grooveix.ui.activity.MainActivity
import com.example.grooveix.ui.adapter.TrackAdapter
import com.example.grooveix.ui.media.MusicDatabase
import com.example.grooveix.ui.media.MusicViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class PlaylistTracksFragment : Fragment() {
private var _binding: FragmentPlaylistTracksBinding? = null
private val binding get() = _binding!!
private var playlistId: Long = -1
private var musicDatabase: MusicDatabase? = null
private lateinit var musicViewModel: MusicViewModel
private lateinit var adapter: TrackAdapter
private lateinit var mainActivity: MainActivity
private lateinit var onBackPressedCallback: OnBackPressedCallback
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentPlaylistTracksBinding.inflate(inflater, container, false)
mainActivity = activity as MainActivity
musicDatabase = MusicDatabase.getDatabase(requireContext())
musicViewModel = ViewModelProvider(mainActivity)[MusicViewModel::class.java]
arguments?.let {
playlistId = it.getLong("playlistId", -1)
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
adapter = TrackAdapter(mainActivity)
binding.recyclerView.adapter = adapter
binding.recyclerView.itemAnimator = DefaultItemAnimator()
onBackPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
backStack()
}
}
mainActivity.onBackPressedDispatcher.addCallback(viewLifecycleOwner, onBackPressedCallback)
CoroutineScope(Dispatchers.IO).launch {
val tracks = musicViewModel.getTracksInPlaylist(playlistId)
val playListName = musicViewModel.getPlaylistInfo(playlistId)
withContext(Dispatchers.Main) {
binding.noTracks.isGone = true
binding.recyclerView.isVisible = true
if (tracks.isEmpty()) {
binding.noTracks.isVisible = true
binding.recyclerView.isGone = true
binding.shufflePlaylist.isInvisible = true
}
binding.collapsingToolbar.title = playListName.name
adapter.processNewTracks(tracks)
}
binding.shufflePlButton.setOnClickListener {
mainActivity.playNewPlayQueue(tracks, shuffle = true)
mainActivity.showPlayer()
}
binding.btnClose.setOnClickListener {
backStack()
}
}
mainActivity.onBackPressedDispatcher.addCallback(viewLifecycleOwner, onBackPressedCallback)
}
fun backStack() {
mainActivity.supportFragmentManager.beginTransaction().replace(R.id.playlist_tracks_view, PlaylistFragment()).commit()
}
} | 0 | Kotlin | 0 | 3 | fd9444974c1b998627a98fdbb4f56a9706a5d028 | 3,748 | grooveix | Apache License 2.0 |
cms-bl/src/main/kotlin/com/github/knextsunj/cms/service/validation/impl/CityValidationServiceImpl.kt | knextsunj | 662,745,409 | false | {"Java": 33791, "Kotlin": 24980} | package com.github.knextsunj.cms.service.validation.impl
import com.github.knextsunj.cms.domain.City
import com.github.knextsunj.cms.domain.State
import com.github.knextsunj.cms.repository.CityRepository
import com.github.knextsunj.cms.service.validation.GenericValidationService
import com.github.knextsunj.cms.util.CmsUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
@Component("cityValidationService")
open class CityValidationServiceImpl : GenericValidationService {
@Autowired
open lateinit var cityRepository: CityRepository
override fun deDup(name: String?): Boolean? {
var city: City? = cityRepository.findCityByName(name);
return CmsUtil.isNull(city);
}
} | 1 | null | 1 | 1 | 0f402e9e8885a6480104e26ca072e1692717fb1b | 768 | cms-microservices | Apache License 2.0 |
compose/animation/animation-core/src/commonMain/kotlin/androidx/compose/animation/core/AnimateAsState.kt | zengjuly | 330,313,148 | false | null | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.core
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.unit.Bounds
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
private val defaultAnimation = spring<Float>()
/**
* Fire-and-forget animation function for [Float]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedFloat][androidx.compose.animation.animatedFloat] for cancelable
* animations.
*
* @sample androidx.compose.animation.core.samples.AlphaAnimationSample
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. [spring]
* will be used by default.
* @param visibilityThreshold An optional threshold for deciding when the animation value is
* considered close enough to the targetValue.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateAsState(
targetValue: Float,
animationSpec: AnimationSpec<Float> = defaultAnimation,
visibilityThreshold: Float = 0.01f,
finishedListener: ((Float) -> Unit)? = null
): State<Float> {
val resolvedAnimSpec =
if (animationSpec === defaultAnimation) {
remember(visibilityThreshold) { spring(visibilityThreshold = visibilityThreshold) }
} else {
animationSpec
}
val animationState: AnimationState<Float, AnimationVector1D> = remember {
AnimationState(targetValue)
}
val currentEndListener by rememberUpdatedState(finishedListener)
LaunchedEffect(targetValue, animationSpec) {
animationState.animateTo(
targetValue,
resolvedAnimSpec,
// If the previous animation was interrupted (i.e. not finished), make it sequential.
!animationState.isFinished
)
currentEndListener?.invoke(animationState.value)
}
return animationState
}
/**
* Fire-and-forget animation function for [Dp]. This Composable function is overloaded for
* different parameter types such as [Float], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedValue][androidx.compose.animation.animatedValue] for cancelable
* animations.
*
* @sample androidx.compose.animation.core.samples.DpAnimationSample
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateAsState(
targetValue: Dp,
animationSpec: AnimationSpec<Dp> = remember {
spring(visibilityThreshold = Dp.VisibilityThreshold)
},
finishedListener: ((Dp) -> Unit)? = null
): State<Dp> {
return animateAsState(
targetValue,
Dp.VectorConverter,
animationSpec,
finishedListener = finishedListener
)
}
/**
* Fire-and-forget animation function for [DpOffset]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedValue][androidx.compose.animation.animatedValue] for cancelable
* animations.
*
* val position: DpOffset by animateAsState(
* if (selected) DpOffset(0.dp, 0.dp) else DpOffset(20.dp, 20.dp))
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateAsState(
targetValue: DpOffset,
animationSpec: AnimationSpec<DpOffset> = remember {
spring(visibilityThreshold = DpOffset.VisibilityThreshold)
},
finishedListener: ((DpOffset) -> Unit)? = null
): State<DpOffset> {
return animateAsState(
targetValue, DpOffset.VectorConverter, animationSpec, finishedListener = finishedListener
)
}
/**
* Fire-and-forget animation function for [Size]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedValue][androidx.compose.animation.animatedValue] for cancelable
* animations.
*
* val size: Size by animateAsState(
* if (selected) Size(20f, 20f) else Size(10f, 10f))
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateAsState(
targetValue: Size,
animationSpec: AnimationSpec<Size> = remember {
spring(visibilityThreshold = Size.VisibilityThreshold)
},
finishedListener: ((Size) -> Unit)? = null
): State<Size> {
return animateAsState(
targetValue,
Size.VectorConverter,
animationSpec,
finishedListener = finishedListener
)
}
/**
* Fire-and-forget animation function for [Bounds]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedValue][androidx.compose.animation.animatedValue] for cancelable
* animations.
*
* val bounds: Bounds by animateAsState(
* if (collapsed) Bounds(0.dp, 0.dp, 10.dp, 20.dp) else Bounds(0.dp, 0.dp, 100.dp, 200.dp))
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateAsState(
targetValue: Bounds,
animationSpec: AnimationSpec<Bounds> = remember {
spring(visibilityThreshold = Bounds.VisibilityThreshold)
},
finishedListener: ((Bounds) -> Unit)? = null
): State<Bounds> {
return animateAsState(
targetValue,
Bounds.VectorConverter,
animationSpec,
finishedListener = finishedListener
)
}
/**
* Fire-and-forget animation function for [Offset]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Float],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedValue][androidx.compose.animation.animatedValue] for cancelable
* animations.
*
* @sample androidx.compose.animation.core.samples.AnimateOffsetSample
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateAsState(
targetValue: Offset,
animationSpec: AnimationSpec<Offset> = remember {
spring(visibilityThreshold = Offset.VisibilityThreshold)
},
finishedListener: ((Offset) -> Unit)? = null
): State<Offset> {
return animateAsState(
targetValue, Offset.VectorConverter, animationSpec, finishedListener = finishedListener
)
}
/**
* Fire-and-forget animation function for [Rect]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedValue][androidx.compose.animation.animatedValue] for cancelable
* animations.
*
* val bounds: Rect by animateAsState(
* if (enabled) Rect(0f, 0f, 100f, 100f) else Rect(8f, 8f, 80f, 80f))
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateAsState(
targetValue: Rect,
animationSpec: AnimationSpec<Rect> = remember {
spring(visibilityThreshold = Rect.VisibilityThreshold)
},
finishedListener: ((Rect) -> Unit)? = null
): State<Rect> {
return animateAsState(
targetValue, Rect.VectorConverter, animationSpec, finishedListener = finishedListener
)
}
/**
* Fire-and-forget animation function for [Int]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedValue][androidx.compose.animation.animatedValue] for cancelable
* animations.
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateAsState(
targetValue: Int,
animationSpec: AnimationSpec<Int> = remember { spring(visibilityThreshold = 1) },
finishedListener: ((Int) -> Unit)? = null
): State<Int> {
return animateAsState(
targetValue, Int.VectorConverter, animationSpec, finishedListener = finishedListener
)
}
/**
* Fire-and-forget animation function for [IntOffset]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedValue][androidx.compose.animation.animatedValue] for cancelable
* animations.
*
* @sample androidx.compose.animation.core.samples.AnimateOffsetSample
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateAsState(
targetValue: IntOffset,
animationSpec: AnimationSpec<IntOffset> = remember {
spring(visibilityThreshold = IntOffset.VisibilityThreshold)
},
finishedListener: ((IntOffset) -> Unit)? = null
): State<IntOffset> {
return animateAsState(
targetValue, IntOffset.VectorConverter, animationSpec, finishedListener = finishedListener
)
}
/**
* Fire-and-forget animation function for [IntSize]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedValue][androidx.compose.animation.animatedValue] for cancelable
* animations.
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateAsState(
targetValue: IntSize,
animationSpec: AnimationSpec<IntSize> = remember {
spring(visibilityThreshold = IntSize.VisibilityThreshold)
},
finishedListener: ((IntSize) -> Unit)? = null
): State<IntSize> {
return animateAsState(
targetValue, IntSize.VectorConverter, animationSpec, finishedListener = finishedListener
)
}
/**
* Fire-and-forget animation function for [AnimationVector]. This Composable function is overloaded
* for different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset]
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedValue][androidx.compose.animation.animatedValue] for cancelable
* animations.
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param visibilityThreshold An optional threshold to define when the animation value can be
* considered close enough to the targetValue to end the animation.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun <T : AnimationVector> animateAsState(
targetValue: T,
animationSpec: AnimationSpec<T> = remember {
spring(visibilityThreshold = visibilityThreshold)
},
visibilityThreshold: T? = null,
finishedListener: ((T) -> Unit)? = null
): State<T> {
return animateAsState(
targetValue,
remember { TwoWayConverter<T, T>({ it }, { it }) },
animationSpec,
finishedListener = finishedListener
)
}
/**
* Fire-and-forget animation function for any value. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight whe [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [animatedValue][androidx.compose.animation.animatedValue] for cancelable
* animations.
*
* @sample androidx.compose.animation.core.samples.ArbitraryValueTypeTransitionSample
*
* data class MySize(val width: Dp, val height: Dp)
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param visibilityThreshold An optional threshold to define when the animation value can be
* considered close enough to the targetValue to end the animation.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun <T, V : AnimationVector> animateAsState(
targetValue: T,
typeConverter: TwoWayConverter<T, V>,
animationSpec: AnimationSpec<T> = remember {
spring(visibilityThreshold = visibilityThreshold)
},
visibilityThreshold: T? = null,
finishedListener: ((T) -> Unit)? = null
): State<T> {
val animationState: AnimationState<T, V> = remember(typeConverter) {
AnimationState(targetValue, typeConverter = typeConverter)
}
val listener by rememberUpdatedState(finishedListener)
LaunchedEffect(targetValue, animationSpec) {
animationState.animateTo(
targetValue,
animationSpec,
// If the previous animation was interrupted (i.e. not finished), make it sequential.
!animationState.isFinished
)
listener?.invoke(animationState.value)
}
return animationState
} | 11 | null | 1 | 1 | c18398cedc5052beb4255b8eb681d3ed3b062e24 | 22,997 | androidx | Apache License 2.0 |
project/jimmer-sql-kotlin/src/main/kotlin/org/babyfish/jimmer/sql/kt/ast/table/impl/KNullableTableExImpl.kt | xuwupeng2000 | 553,372,749 | false | {"Markdown": 18, "Text": 1, "Ignore List": 5, "JSON": 2, "Gradle": 8, "Shell": 10, "Batchfile": 8, "Java": 488, "Kotlin": 245, "SQL": 9, "YAML": 11, "INI": 11, "JavaScript": 4, "JSON with Comments": 1, "MDX": 61, "SVG": 3, "TSX": 3, "CSS": 3, "Gradle Kotlin DSL": 14, "GraphQL": 2} | package org.babyfish.jimmer.sql.kt.ast.table.impl
import org.babyfish.jimmer.sql.ast.Selection
import org.babyfish.jimmer.sql.ast.impl.PropExpressionImpl
import org.babyfish.jimmer.sql.ast.impl.table.TableImplementor
import org.babyfish.jimmer.sql.fetcher.Fetcher
import org.babyfish.jimmer.sql.kt.ast.expression.KPropExpression
import org.babyfish.jimmer.sql.kt.ast.expression.impl.NullablePropExpressionImpl
import org.babyfish.jimmer.sql.kt.ast.table.KNullableTableEx
import org.babyfish.jimmer.sql.kt.toImmutableProp
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
internal class KNullableTableExImpl<E: Any>(
javaTable: TableImplementor<E>
) : KTableExImpl<E>(javaTable), KNullableTableEx<E> {
@Suppress("UNCHECKED_CAST")
override fun <X : Any, EXP : KPropExpression<X>> get(prop: String): EXP =
NullablePropExpressionImpl(javaTable.get<PropExpressionImpl<X>>(prop)) as EXP
override fun <X : Any> join(prop: String): KNullableTableEx<X> =
KNullableTableExImpl(javaTable.join(prop))
override fun <X : Any> joinReference(prop: KProperty1<E, X?>): KNullableTableEx<X> =
KNullableTableExImpl(javaTable.join(prop.name))
override fun <X : Any> joinList(prop: KProperty1<E, List<X>>): KNullableTableEx<X> =
KNullableTableExImpl(javaTable.join(prop.name))
override fun <X: Any> inverseJoin(targetType: KClass<X>, backProp: String): KNullableTableEx<X> =
KNullableTableExImpl(javaTable.inverseJoin(targetType.java, backProp))
override fun <X : Any> inverseJoinReference(backProp: KProperty1<X, E?>): KNullableTableEx<X> =
KNullableTableExImpl(
javaTable.inverseJoin(
backProp.toImmutableProp().declaringType.javaClass,
backProp.name
)
)
override fun <X : Any> inverseJoinList(backProp: KProperty1<X, List<E>>): KNullableTableEx<X> =
KNullableTableExImpl(
javaTable.inverseJoin(
backProp.toImmutableProp().declaringType.javaClass,
backProp.name
)
)
override fun fetch(fetcher: Fetcher<E>): Selection<E?> =
javaTable.fetch(fetcher)
} | 1 | null | 1 | 1 | 8fb76adbc55dbee774724eda129c2c1fb9bd449f | 2,183 | jimmer | MIT License |
app/src/main/java/app/profile/ProfilesActivity.kt | AndreyShpilevou | 525,789,850 | false | {"Java Properties": 2, "YAML": 2, "Gradle": 4, "Shell": 1, "Markdown": 1, "Git Attributes": 1, "Batchfile": 1, "Text": 3, "Ignore List": 1, "Proguard": 4, "XML": 62, "Java": 872, "HTML": 9, "JAR Manifest": 1, "GLSL": 8, "Makefile": 1, "C++": 41, "C": 110, "Kotlin": 45} | package app.profile
import android.annotation.SuppressLint
import app.activities.BaseActivity
import android.widget.AdapterView.OnItemClickListener
import android.content.SharedPreferences
import androidx.activity.result.contract.ActivityResultContract
import android.content.Intent
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.*
import ru.playsoftware.j2meloader.R
import android.view.ContextMenu.ContextMenuInfo
import android.widget.AdapterView.AdapterContextMenuInfo
import android.widget.AdapterView
import androidx.appcompat.widget.PopupMenu
import androidx.core.view.isVisible
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import app.utils.Constants.ACTION_EDIT_PROFILE
import app.utils.Constants.PREF_DEFAULT_PROFILE
import app.utils.dp
import app.views.*
class ProfilesActivity : BaseActivity(), EditNameAlert.Callback, OnItemClickListener {
private lateinit var emptyView: View
private lateinit var profilesAdapter: ProfilesAdapter
private lateinit var preferences: SharedPreferences
private val editProfileLauncher = registerForActivityResult(
object : ActivityResultContract<String?, String?>() {
override fun createIntent(context: Context, input: String?): Intent {
return Intent(
ACTION_EDIT_PROFILE, Uri.parse(input),
applicationContext, ConfigActivity::class.java
)
}
override fun parseResult(resultCode: Int, intent: Intent?): String? {
return if (resultCode == RESULT_OK && intent != null) {
intent.dataString!!
} else null
}
}
) { name: String? ->
if (name != null) {
profilesAdapter.addItem(Profile(name))
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(true)
setTitle(R.string.profiles)
preferences = PreferenceManager.getDefaultSharedPreferences(this)
val profiles = ProfilesManager.profiles
profilesAdapter = ProfilesAdapter(profiles)
frameLayout {
recyclerView {
layoutManager = LinearLayoutManager(context)
setPadding(0, 3.dp, 0, 100.dp)
clipToPadding = false
adapter = profilesAdapter
}.lparams(matchParent, matchParent)
emptyView = textView {
text = "no data"
isVisible = profiles.isEmpty()
}.lparams(wrapContent, wrapContent){
gravity = Gravity.CENTER
}
}
val def = preferences.getString(PREF_DEFAULT_PROFILE, null)
if (def != null) {
for (i in profiles.indices.reversed()) {
val profile = profiles[i]
if (profile.name == def) {
profilesAdapter.setDefault(profile)
break
}
}
}
profilesAdapter.control = object : ProfilesAdapter.Control{
override fun onClickItem(position: Int, view: View) {
val popup = PopupMenu(this@ProfilesActivity, view)
popup.inflate(R.menu.profile)
popup.setOnMenuItemClickListener { item ->
val profile = profilesAdapter.getItem(position)
when (item.itemId) {
R.id.action_context_default -> {
preferences.edit().putString(PREF_DEFAULT_PROFILE, profile.name).apply()
profilesAdapter.setDefault(profile)
return@setOnMenuItemClickListener true
}
R.id.action_context_edit -> {
val intent = Intent(
ACTION_EDIT_PROFILE,
Uri.parse(profile.name),
applicationContext, ConfigActivity::class.java
)
startActivity(intent)
return@setOnMenuItemClickListener true
}
R.id.action_context_rename -> {
EditNameAlert.newInstance(getString(R.string.enter_new_name), position)
.show(supportFragmentManager, "alert_rename_profile")
}
R.id.action_context_delete -> {
profile.delete()
profilesAdapter.removeItem(position)
}
}
return@setOnMenuItemClickListener false
}
popup.show()
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_profiles, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val itemId = item.itemId
if (itemId == android.R.id.home) {
finish()
return true
} else if (itemId == R.id.add) {
EditNameAlert.newInstance(getString(R.string.enter_name), -1)
.show(supportFragmentManager, "alert_create_profile")
return true
}
return super.onOptionsItemSelected(item)
}
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo) {
val inflater = menuInflater
inflater.inflate(R.menu.profile, menu)
val info = menuInfo as AdapterContextMenuInfo
val profile = profilesAdapter.getItem(info.position)
if (!profile.hasConfig() && !profile.hasOldConfig()) {
menu.findItem(R.id.action_context_default).isVisible = false
menu.findItem(R.id.action_context_edit).isVisible = false
}
}
override fun onContextItemSelected(item: MenuItem): Boolean {
val info = item.menuInfo as AdapterContextMenuInfo
val index = info.position
val profile = profilesAdapter.getItem(index)
val itemId = item.itemId
if (itemId == R.id.action_context_default) {
preferences.edit().putString(PREF_DEFAULT_PROFILE, profile.name).apply()
profilesAdapter.setDefault(profile)
return true
} else if (itemId == R.id.action_context_edit) {
val intent = Intent(
ACTION_EDIT_PROFILE,
Uri.parse(profile.name),
applicationContext, ConfigActivity::class.java
)
startActivity(intent)
return true
} else if (itemId == R.id.action_context_rename) {
EditNameAlert.newInstance(getString(R.string.enter_new_name), index)
.show(supportFragmentManager, "alert_rename_profile")
} else if (itemId == R.id.action_context_delete) {
profile.delete()
profilesAdapter.removeItem(index)
}
return super.onContextItemSelected(item)
}
@SuppressLint("NotifyDataSetChanged")
override fun onNameChanged(id: Int, newName: String) {
Log.d("onNameChanged", "$id $newName")
if (id == -1) {
editProfileLauncher.launch(newName)
return
}
val profile = profilesAdapter.getItem(id)
profile.renameTo(newName)
profilesAdapter.notifyDataSetChanged()
if (profilesAdapter.isDefault(profile)) {
preferences.edit().putString(PREF_DEFAULT_PROFILE, newName).apply()
}
}
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
parent.showContextMenuForChild(view)
}
} | 1 | null | 1 | 1 | c8fd5077b2900e15ad7e3a1dbba54972e4e67684 | 8,010 | ME-to-Android | Apache License 2.0 |
app/src/main/java/com/ivieleague/kotlin_components_starter/StartVC.kt | shanelk | 49,988,485 | true | {"Kotlin": 11946, "Java": 704} | package com.ivieleague.kotlin_components_starter
import android.graphics.Bitmap
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import com.lightningkite.kotlincomponents.animation.transitionView
import com.lightningkite.kotlincomponents.image.getImageFromGallery
import com.lightningkite.kotlincomponents.logging.logD
import com.lightningkite.kotlincomponents.logging.logE
import com.lightningkite.kotlincomponents.networking.Networking
import com.lightningkite.kotlincomponents.observable.Observable
import com.lightningkite.kotlincomponents.ui.inputDialog
import com.lightningkite.kotlincomponents.ui.progressButton
import com.lightningkite.kotlincomponents.viewcontroller.StandardViewController
import com.lightningkite.kotlincomponents.viewcontroller.containers.VCStack
import com.lightningkite.kotlincomponents.viewcontroller.implementations.VCActivity
import com.lightningkite.kotlincomponents.viewcontroller.linearLayout
import org.jetbrains.anko.*
/**
* A ViewController with various tests on it.
* Created by josep on 11/6/2015.
*/
class StartVC(val stack: VCStack) : StandardViewController() {
val imageObs: Observable<Bitmap?> = object : Observable<Bitmap?>(null) {
override fun set(v: Bitmap?) {
this.value?.recycle()
super.set(v)
}
}
var image: Bitmap? by imageObs
val loadingObs: Observable<Boolean> = Observable(false)
var loading: Boolean by loadingObs
val textObs = Observable("Start Text")
var text by textObs
override fun makeView(activity: VCActivity): View = linearLayout(activity) {
orientation = LinearLayout.VERTICAL
setGravity(Gravity.CENTER)
textView("Hello World") {
gravity = Gravity.CENTER
}
editText() {
bindString(textObs)
}
textView() {
bindString(textObs)
}
button("Get an Image") {
onClick {
activity.getImageFromGallery(1000) {
image = it
}
}
}
progressButton("Enter an image URL") {
onClick {
activity.inputDialog("Enter an image URL", "URL") { url ->
if (url != null) {
running = true
loading = true
Networking.get(url) {
running = false
loading = false
if (it.isSuccessful) {
image = it.bitmap()
} else {
image = null
logE(url)
logE(it.code)
logE(it.string())
}
}
}
}
}
}
progressButton("Lorem Pixel") {
onClick {
running = true
loading = true
Networking.get("http://lorempixel.com/300/300") {
running = false
loading = false
if (it.isSuccessful) {
image = it.bitmap()
} else {
image = null
}
}
}
}
transitionView {
textView("Loading...") {
gravity = Gravity.CENTER
}.tag("loading")
textView("No image.") {
gravity = Gravity.CENTER
}.tag("none")
imageView() {
connect(imageObs) {
if (it == null) return@connect
imageBitmap = it
}
}.tag("image")
connect(loadingObs) {
if (it) {
animate("loading")
}
}
connect(imageObs) {
logD(it)
if (it == null) {
animate("none")
} else {
animate("image")
}
}
}
button("Test Socket IO") {
onClick {
stack.push(SocketIOVC(stack))
}
}
button("I wanna do something else") {
onClick {
stack.push(AnotherVC(stack))
}
}
}
} | 0 | Kotlin | 0 | 0 | 7e2dc82844e3a487d1994e033b317f0b5529559a | 4,484 | kotlin-components-starter | MIT License |
microstream-ktor/src/main/kotlin/be/rubus/kotlin/microstream/routes/UserBookRoutes.kt | rdebusscher | 574,523,783 | false | null | package be.rubus.kotlin.microstream.routes
import be.rubus.kotlin.microstream.exception.ExceptionResponse
import be.rubus.kotlin.microstream.service.UserBookService
import be.rubus.kotlin.microstream.service.UserService
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Route.userBookRouting() {
route("/user/{userId}") {
get("/book") {
val userId = URLParameters.extractUserId(this)
call.respond(UserService.getById(userId).books)
}
post("/book/{bookId?}") {
val userId = URLParameters.extractUserId(this)
val bookId = call.parameters["bookId"] ?: return@post call.respond(
call.respond(
HttpStatusCode.BadRequest,
ExceptionResponse("Missing book id", HttpStatusCode.BadRequest.value)
)
)
UserBookService.addBookToUser(userId, bookId)
}
}
}
| 0 | Kotlin | 0 | 0 | cf8e9308acf6817dcc02f121d1658ce15f7085fb | 1,006 | kotlin-projects | Apache License 2.0 |
godot/src/main/kotlin/fail/stderr/usb/kerbol/KerbolConstants.kt | stderr-fail | 824,200,675 | false | {"Kotlin": 106132, "GDScript": 21821, "Java": 8583, "Shell": 446} | package fail.stderr.usb.kerbol
class KerbolConstants {
// ksp orbit references https://github.com/Arrowstar/ksptot/blob/master/bodies.ini
// https://wiki.kerbalspaceprogram.com/wiki/Kerbol
companion object {
val KERBOL_MU = 1.1723328e18
val KERBIN_MU = 3.5316000e12
val MUN_MU = 6.5138398e10
}
} | 0 | Kotlin | 0 | 1 | 89b63cc0e6789a9486e8716e9482eb7fd5e300a9 | 318 | untitled-space-bureau | MIT License |
app-data/src/main/java/com/kotlin/android/app/data/entity/common/MovieSubItemRating.kt | R-Gang-H | 538,443,254 | false | null | package com.kotlin.android.app.data.entity.common
import com.kotlin.android.app.data.ProguardRule
/**
* @author ZhouSuQiang
* @email <EMAIL>
* @date 2021/5/28
*/
data class MovieSubItemRating(
var index: Long = 0,
var rating: Float? = 0.0f,
var title: String? = ""
) : ProguardRule | 0 | Kotlin | 0 | 1 | e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28 | 311 | Mtime | Apache License 2.0 |
extensions/src/test/java/com/github/kacso/androidcommons/extensions/DoubleExtensionsTest.kt | kacso | 204,923,341 | false | {"Gradle": 16, "Java Properties": 2, "Shell": 1, "Text": 4, "Ignore List": 13, "Batchfile": 1, "Markdown": 616, "Kotlin": 181, "XML": 69, "INI": 8, "Proguard": 9, "Java": 1} | package com.github.kacso.androidcommons.extensions
import org.junit.Test
import org.junit.jupiter.api.Assertions
class DoubleExtensionsTest {
@Test
fun testFormatter() {
val PI = 3.14159265359
Assertions.assertEquals("3", PI.format(0))
Assertions.assertEquals("3.14", PI.format(2))
Assertions.assertEquals("3.141592653590000", PI.format(15))
}
} | 0 | Kotlin | 1 | 5 | 9620f80428f4b00a8b683f4e94294e9e64c85b99 | 392 | android-commons | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/assessments/jpa/repositories/refdata/AssessmentSchemaRepository.kt | ministryofjustice | 289,880,556 | false | null | package uk.gov.justice.digital.assessments.jpa.repositories.refdata
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import uk.gov.justice.digital.assessments.jpa.entities.AssessmentSchemaCode
import uk.gov.justice.digital.assessments.jpa.entities.refdata.AssessmentSchemaEntity
@Repository
interface AssessmentSchemaRepository : JpaRepository<AssessmentSchemaEntity, Long> {
fun findByAssessmentSchemaCode(assessmentSchemaCode: AssessmentSchemaCode): AssessmentSchemaEntity?
}
| 2 | Kotlin | 1 | 1 | 3eb0ee16233324fa99ff2e19f3bdb084eb28304a | 544 | hmpps-assessments-api | MIT License |
app/src/main/java/com/capstone/sofitapp/ui/SplashScreen.kt | sofit-c23-ps233 | 641,226,823 | false | null | package com.capstone.sofitapp.ui
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.viewModels
import com.capstone.sofitapp.data.model.ViewModelFactory
import com.capstone.sofitapp.databinding.ActivitySplashScreenBinding
import com.capstone.sofitapp.ui.main.MainActivity
import com.capstone.sofitapp.ui.main.MainViewModel
class SplashScreen : AppCompatActivity() {
private lateinit var binding: ActivitySplashScreenBinding
private val mainViewModel by viewModels<MainViewModel> { ViewModelFactory.getInstance(this) }
private val duration = 3000L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySplashScreenBinding.inflate(layoutInflater)
setContentView(binding.root)
Handler(Looper.getMainLooper()).postDelayed({
mainViewModel.getSession().observe(this@SplashScreen) {
if (it.isLogin) {
startActivity(Intent(this, MainActivity::class.java))
} else {
startActivity(Intent(this, WelcomeActivity::class.java))
}
finish()
}
},duration)
}
} | 0 | Kotlin | 0 | 0 | 4840ad804898295101be6644fa866c66a65fcf8f | 1,314 | SoFit-androidApp | MIT License |
app/src/main/java/com/example/orbital_lab_to_ground_control/MainActivity.kt | OzuaX | 421,991,277 | false | {"Kotlin": 9862} | package com.example.orbital_lab_to_ground_control
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tvResultado = findViewById<TextView>(R.id.tvResultado)
val etNome = findViewById<TextView>(R.id.etNome)
val btEnviar = findViewById<Button>(R.id.btEnviar)
btEnviar.setOnClickListener {
if (etNome.text.isNotBlank()) {
tvResultado.text = getString(R.string.hello_name, etNome.text.toString())
// tvResultado.text = "Sim! ${etNome.text}! "
}else{
etNome.error = getString(R.string.type_here)
}
}
}
} | 0 | Kotlin | 0 | 0 | 205482c67adeb4262ceeedf0760a049f4a84c016 | 906 | OLtoGC | MIT License |
progressimageviewlib/src/main/java/com/shshy/progressimageview/ProgressImageView.kt | ShshyDevooo | 265,416,925 | false | null | package com.shshy.progressimageview
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import androidx.appcompat.widget.AppCompatImageView
import kotlin.math.pow
import kotlin.math.sqrt
/**
* @author ShiShY
* @Description:
* @data 2020/5/19 11:34
*/
class ProgressImageView : AppCompatImageView {
private var showProgress: Boolean = false
private var currentProgress: Int = 0
private var coverColor: Int = Color.argb(127, 0, 0, 0)
private lateinit var textPaint: Paint
private var textSize = 14f
private var textColor = Color.WHITE
private var textCirclePadding = 10f
private lateinit var progressPaint: Paint
private var progressStrokeWidth = 10f
private var isCircle = false
private var rectRadius = 0f
private var circleRadius = 0f
private var showProgressStroke = true
private var progressStrokeColor = Color.WHITE
private val clipPath = Path()
private val viewRect: RectF = RectF()
private val clipPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val progressXfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
private lateinit var radiusXfermode: PorterDuffXfermode
private lateinit var coverPaint: Paint
private var shadowAni: ValueAnimator? = null
private lateinit var shadowPaint: Paint
private val viewPath: Path = Path()
private val srcPath: Path = Path()
constructor(context: Context?) : super(context) {
init(null)
}
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
init(attrs)
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(attrs)
}
private fun init(attrs: AttributeSet?) {
val typeArray = context.obtainStyledAttributes(attrs, R.styleable.ProgressImageView)
textSize = typeArray.getDimension(R.styleable.ProgressImageView_piv_textSize, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, textSize, context.resources.displayMetrics))
showProgress = typeArray.getBoolean(R.styleable.ProgressImageView_piv_showProgress, true)
currentProgress = typeArray.getInteger(R.styleable.ProgressImageView_piv_progress, 0)
coverColor = typeArray.getColor(R.styleable.ProgressImageView_piv_coverColor, coverColor)
textColor = typeArray.getColor(R.styleable.ProgressImageView_piv_textColor, textColor)
textCirclePadding = typeArray.getDimension(R.styleable.ProgressImageView_piv_circlePadding, textCirclePadding)
progressStrokeWidth = typeArray.getDimension(R.styleable.ProgressImageView_piv_progressStrokeWidth, progressStrokeWidth)
isCircle = typeArray.getBoolean(R.styleable.ProgressImageView_piv_isCircle, isCircle)
rectRadius = typeArray.getDimension(R.styleable.ProgressImageView_piv_radius, rectRadius)
showProgressStroke = typeArray.getBoolean(R.styleable.ProgressImageView_piv_showProgressStroke, showProgressStroke)
progressStrokeColor = typeArray.getColor(R.styleable.ProgressImageView_piv_progressStrokeColor, progressStrokeColor)
typeArray.recycle()
textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
textPaint.textSize = textSize
textPaint.color = textColor
textPaint.style = Paint.Style.FILL
textPaint.textAlign = Paint.Align.CENTER
coverPaint = Paint(Paint.ANTI_ALIAS_FLAG)
coverPaint.color = coverColor
progressPaint = Paint(Paint.ANTI_ALIAS_FLAG)
progressPaint.strokeWidth = progressStrokeWidth
progressPaint.style = Paint.Style.FILL
progressPaint.color = coverColor
shadowPaint = Paint(Paint.ANTI_ALIAS_FLAG)
shadowPaint.style = Paint.Style.FILL
shadowPaint.xfermode = progressXfermode
shadowPaint.color = coverColor
radiusXfermode = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1) {
PorterDuffXfermode(PorterDuff.Mode.DST_IN)
} else {
PorterDuffXfermode(PorterDuff.Mode.DST_OUT)
}
}
override fun onDraw(canvas: Canvas?) {
clipPath.reset()
val radiusSaveCount = saveRadiusOrCircleLayer(canvas)
if (radiusSaveCount != null && radiusSaveCount != -1) {
if (isCircle) {
clipPath.addCircle(width.toFloat() / 2, height.toFloat() / 2, circleRadius, Path.Direction.CCW)
} else {
clipPath.addRoundRect(viewRect, rectRadius, rectRadius, Path.Direction.CCW)
}
}
if (showProgress) {
super.onDraw(canvas)
//画蒙板
val layoutCount = canvas?.saveLayer(viewRect, null, Canvas.ALL_SAVE_FLAG)
if (radiusSaveCount != null && radiusSaveCount != -1)
canvas?.drawPath(clipPath, coverPaint)
else
canvas?.drawRect(viewRect, coverPaint)
//进度扇形
val text = if (currentProgress < 10) "0$currentProgress%" else "$currentProgress%"
progressPaint.xfermode = progressXfermode
val progress = (currentProgress / 100f) * 360
progressPaint.style = Paint.Style.FILL
progressPaint.color = coverColor
val arcRect = getArcRect()
canvas?.drawArc(arcRect, 270f, progress, true, progressPaint)
progressPaint.xfermode = null
canvas?.restoreToCount(layoutCount ?: 0)
//进度描边
if (showProgressStroke) {
progressPaint.style = Paint.Style.STROKE
progressPaint.color = progressStrokeColor
progressPaint.strokeWidth = progressStrokeWidth
canvas?.drawArc(arcRect, (270f + progress) % 360, 360f - progress, false, progressPaint)
}
//进度文字
canvas?.drawText(text, width.toFloat() / 2, getCenterBaseLine(), textPaint)
//如果有圆角或者是圆形图片
if (radiusSaveCount != null && radiusSaveCount != -1) {
clipImageRadiusOrCircle(radiusSaveCount, canvas)
canvas?.restoreToCount(radiusSaveCount)
}
} else {
super.onDraw(canvas)
if (radiusSaveCount != null && radiusSaveCount != -1) {
clipImageRadiusOrCircle(radiusSaveCount, canvas, true)
canvas?.restoreToCount(radiusSaveCount)
} else {
if (shadowAni?.isRunning == true) {
drawShadowAnimate(viewPath, canvas)
}
}
}
}
private fun saveRadiusOrCircleLayer(canvas: Canvas?): Int? {
return if (rectRadius != 0f || isCircle)
canvas?.saveLayer(viewRect, null, Canvas.ALL_SAVE_FLAG)
else
-1
}
//将此Image切成圆角或圆形,shouldAnimate是否需要显示蒙层消失动画
private fun clipImageRadiusOrCircle(saveCount: Int?, canvas: Canvas?, shouldAnimate: Boolean = false) {
if (saveCount != null && saveCount != -1) {
clipPaint.reset()
clipPaint.xfermode = radiusXfermode
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1)
canvas?.drawPath(clipPath, clipPaint)
else {
srcPath.reset()
srcPath.addRect(viewRect, Path.Direction.CCW)
srcPath.op(clipPath, Path.Op.DIFFERENCE)
canvas?.drawPath(srcPath, clipPaint)
}
clipPaint.xfermode = null
if (shouldAnimate && shadowAni?.isRunning == true) {
drawShadowAnimate(clipPath, canvas)
}
}
}
//根据蒙层消失动画值画蒙层
private fun drawShadowAnimate(path: Path, canvas: Canvas?) {
val shadowCount = canvas?.saveLayer(viewRect, null, Canvas.ALL_SAVE_FLAG)
canvas?.drawPath(path, coverPaint)
canvas?.drawCircle(width.toFloat() / 2, height.toFloat() / 2, shadowAni?.animatedValue as Float, shadowPaint)
canvas?.restoreToCount(shadowCount ?: 0)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
if (isCircle) {
circleRadius = Math.min(width, height) / 2f
viewRect.set(width / 2f - circleRadius, height / 2f - circleRadius, width / 2f + circleRadius, height / 2f + circleRadius)
} else
viewRect.set(0f, 0f, width.toFloat(), height.toFloat())
viewPath.reset()
viewPath.addRect(viewRect, Path.Direction.CCW)
super.onSizeChanged(w, h, oldw, oldh)
}
//进度扇形矩形
private fun getArcRect(): RectF {
val arcRadius = getArcRadius()
return RectF(width / 2 - arcRadius, height / 2 - arcRadius, width / 2 + arcRadius, height / 2 + arcRadius)
}
//进度扇形半径
private fun getArcRadius(): Float {
val textWidth = textPaint.measureText("100%")
return textWidth / 2 + textCirclePadding
}
private fun getCenterBaseLine(): Float {
val fontMetrics = textPaint.fontMetrics
return height.toFloat() / 2 + (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom
}
fun setProgress(progress: Int) {
currentProgress = progress
if (currentProgress >= 100) {
showProgress = false
dismissShadowAnimation()
}
postInvalidate()
}
fun showProgress(show: Boolean) {
this.showProgress = show
postInvalidate()
}
fun getProgress(): Int {
return currentProgress
}
//蒙层消失动画
private fun dismissShadowAnimation() {
Handler(Looper.getMainLooper()).post {
val maxRadius =
sqrt((width.toDouble() / 2).pow(2.toDouble()) + (height.toDouble() / 2).pow(2.toDouble()))
shadowAni = ValueAnimator.ofFloat(getArcRadius(), maxRadius.toFloat())
shadowAni?.addUpdateListener { postInvalidate() }
shadowAni?.duration = 500
shadowAni?.start()
}
}
} | 0 | Kotlin | 0 | 1 | f9e3c8b6ba043871a570ff59a916529c917e561d | 10,099 | ProgressImageView | Apache License 2.0 |
allure-android/src/main/kotlin/ru/tinkoff/allure/android/AllureAndroidLifecycle.kt | davidbugayov | 130,863,181 | false | {"Gradle": 8, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "YAML": 1, "Markdown": 2, "Kotlin": 65, "Java": 6, "Proguard": 3, "XML": 15} | package ru.tinkoff.allure.android
import android.os.Build
import android.os.Environment
import ru.tinkoff.allure.AllureLifecycle
import ru.tinkoff.allure.android.Constants.RESULTS_FOLDER
import ru.tinkoff.allure.io.FileSystemResultsReader
import ru.tinkoff.allure.io.FileSystemResultsWriter
import java.io.File
/**
* @author Badya on 06.06.2017.
*/
object AllureAndroidLifecycle : AllureLifecycle(
FileSystemResultsReader(obtainDirectory(RESULTS_FOLDER)),
FileSystemResultsWriter(obtainDirectory(RESULTS_FOLDER)))
fun obtainDirectory(path: String): File {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
File(Environment.getExternalStorageDirectory(), path)
} else {
// we can't get context through InstrumentationRegistry
// because it may not be ready yet when obtainDirectory method calls.
// So we try to get context through ContextHolder and write
// test in /data/data/<target_app_bundle_id>/allure-results
val context = ContextHolder.getTargetAppContext()
val applicationInfo = context.applicationInfo
File(applicationInfo.dataDir, path)
}.apply { if (!exists()) mkdirs() }
} | 1 | null | 1 | 1 | 7e9e0fbb09c682cd467e21269cb660b1e0e24421 | 1,199 | allure-android | Apache License 2.0 |
allure-android/src/main/kotlin/ru/tinkoff/allure/android/AllureAndroidLifecycle.kt | davidbugayov | 130,863,181 | false | {"Gradle": 8, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "YAML": 1, "Markdown": 2, "Kotlin": 65, "Java": 6, "Proguard": 3, "XML": 15} | package ru.tinkoff.allure.android
import android.os.Build
import android.os.Environment
import ru.tinkoff.allure.AllureLifecycle
import ru.tinkoff.allure.android.Constants.RESULTS_FOLDER
import ru.tinkoff.allure.io.FileSystemResultsReader
import ru.tinkoff.allure.io.FileSystemResultsWriter
import java.io.File
/**
* @author Badya on 06.06.2017.
*/
object AllureAndroidLifecycle : AllureLifecycle(
FileSystemResultsReader(obtainDirectory(RESULTS_FOLDER)),
FileSystemResultsWriter(obtainDirectory(RESULTS_FOLDER)))
fun obtainDirectory(path: String): File {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
File(Environment.getExternalStorageDirectory(), path)
} else {
// we can't get context through InstrumentationRegistry
// because it may not be ready yet when obtainDirectory method calls.
// So we try to get context through ContextHolder and write
// test in /data/data/<target_app_bundle_id>/allure-results
val context = ContextHolder.getTargetAppContext()
val applicationInfo = context.applicationInfo
File(applicationInfo.dataDir, path)
}.apply { if (!exists()) mkdirs() }
} | 1 | null | 1 | 1 | 7e9e0fbb09c682cd467e21269cb660b1e0e24421 | 1,199 | allure-android | Apache License 2.0 |
src/main/kotlin/me/bzvol/fifimod/enchantment/ModEnchantments.kt | bzvol | 508,218,419 | false | {"Kotlin": 162220} | package me.bzvol.fifimod.enchantment
import me.bzvol.fifimod.FifiMod
import net.minecraft.world.entity.EquipmentSlot
import net.minecraft.world.item.enchantment.Enchantment
import net.minecraftforge.eventbus.api.IEventBus
import net.minecraftforge.registries.DeferredRegister
import net.minecraftforge.registries.ForgeRegistries
import thedarkcolour.kotlinforforge.forge.registerObject
object ModEnchantments {
private val REGISTRY = DeferredRegister.create(ForgeRegistries.ENCHANTMENTS, FifiMod.MOD_ID)
private val OVERRIDE_REGISTRY = DeferredRegister.create(ForgeRegistries.ENCHANTMENTS, "minecraft")
private val ENDLESS by OVERRIDE_REGISTRY.registerObject("infinity") {
EndlessEnchantment(Enchantment.Rarity.VERY_RARE, EquipmentSlot.MAINHAND)
}
fun register(eventBus: IEventBus) {
REGISTRY.register(eventBus)
OVERRIDE_REGISTRY.register(eventBus)
}
} | 0 | Kotlin | 0 | 0 | 95903762a1876342bfeae2b11c272f71d97621a3 | 904 | FifiMod | MIT License |
src/main/kotlin/uy/kohesive/elasticsearch/dataimport/Udfs.kt | shockwavemk | 176,933,128 | true | {"Kotlin": 56038, "Java": 980} | package uy.kohesive.elasticsearch.dataimport
import org.apache.spark.sql.SparkSession
import org.jsoup.Jsoup
import org.jsoup.parser.Parser
import org.jsoup.safety.Whitelist
import uy.kohesive.elasticsearch.dataimport.udf.Udfs
import java.sql.Date
import java.sql.Timestamp
object DataImportHandlerUdfs {
fun registerSparkUdfs(spark: SparkSession) {
Udfs.registerStringToStringUdf(spark, "fluffly", fluffly)
Udfs.registerStringToStringUdf(spark, "stripHtml", stripHtmlCompletely)
Udfs.registerStringToStringUdf(spark, "normalizeQuotes", normalizeQuotes)
Udfs.registerStringToStringUdf(spark, "unescapeHtmlEntites", unescapeHtmlEntities)
Udfs.registerAnyAnyToTimestampUdf(spark, "combineDateTime", combineDateTime)
}
@JvmStatic val whiteListMap = mapOf(
"none" to Whitelist.none(),
"basic" to Whitelist.basic(),
"basicwithimages" to Whitelist.basicWithImages(),
"relaxed" to Whitelist.relaxed(),
"simpletext" to Whitelist.simpleText(),
"simple" to Whitelist.simpleText()
)
@JvmStatic val fluffly = fun (v: String): String = "fluffly " + v
@JvmStatic val stripHtmlCompletely = fun (v: String): String {
return Jsoup.parseBodyFragment(v).text()
}
@JvmStatic val normalizeQuotes = fun (v: String): String {
return v.replace("\\'", "'").replace("''", "\"")
}
@JvmStatic val unescapeHtmlEntities = fun (v: String): String {
return Parser.unescapeEntities(v, false)
}
@JvmStatic val combineDateTime = fun (date: Date?, time: Timestamp?): Timestamp? {
// https://stackoverflow.com/questions/26649530/merge-date-and-time-into-timestamp
if (date == null || time == null) {
return null
}
// val dd = (date.time / 86400000L * 86400000L) - date.timezoneOffset * 60000
// val tt = time.time - time.time / 86400000L * 86400000L
// return Timestamp(dd + tt)
return Timestamp(date.year, date.month, date.date, time.hours, time.minutes, time.seconds, 0)
}
} | 0 | Kotlin | 0 | 0 | 029412ffef2169a34a80ce7b516e019687238c0b | 2,103 | elasticsearch-data-import-handler | Apache License 2.0 |
offroad/android/app/src/main/java/ai/comma/plus/offroad/HomePackage.kt | commaai | 178,753,388 | false | null | package ai.comma.plus.offroad
import com.facebook.react.bridge.ModuleSpec
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.shell.MainReactPackage
/**
* Created by batman on 11/2/17.
*/
class HomePackage : MainReactPackage() {
override fun getNativeModules(context: ReactApplicationContext?): MutableList<ModuleSpec> {
val modules = super.getNativeModules(context)
val ourModules = mutableListOf(
ModuleSpec.nativeModuleSpec(ChffrPlusModule::class.java, {
ChffrPlusModule(context!!)
}),
ModuleSpec.nativeModuleSpec(OfflineGeocoderModule::class.java, {
OfflineGeocoderModule(context!!)
}),
ModuleSpec.nativeModuleSpec(LoggingModule::class.java, {
LoggingModule(context!!, BuildConfig.LOGENTRIES_PROJECT_TOKEN)
}),
ModuleSpec.nativeModuleSpec(WifiModule::class.java, {
WifiModule(context!!)
}),
ModuleSpec.nativeModuleSpec(CellularModule::class.java, {
CellularModule(context!!)
}),
ModuleSpec.nativeModuleSpec(LayoutModule::class.java, {
LayoutModule(context!!)
})
)
return (modules + ourModules).toMutableList()
}
} | 8 | null | 68 | 46 | 8822b13da6aa270f0e7cf2c2786440806a850447 | 1,407 | openpilot-apks | MIT License |
app/src/main/java/dev/berwyn/jellybox/MainActivity.kt | berwyn | 586,199,884 | false | null | package dev.berwyn.jellybox
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.CompositionLocalProvider
import androidx.core.view.WindowCompat
import dagger.hilt.android.AndroidEntryPoint
import dev.berwyn.jellybox.data.ApplicationState
import dev.berwyn.jellybox.ui.JellyboxApp
import dev.berwyn.jellybox.ui.util.LocalActivity
import dev.berwyn.jellybox.ui.util.detectNavigationType
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@Inject
lateinit var appState: ApplicationState
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
CompositionLocalProvider(LocalActivity provides this) {
appState.navigationType = detectNavigationType()
JellyboxApp(
navigationType = appState.navigationType,
navigationHidden = appState.navigationHidden,
)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8e484fcece73e27a0514b5ba97bedabde7685c25 | 1,152 | jellybox | Apache License 2.0 |
app/src/main/java/com/nonetxmxy/mmzqfxy/model/PayCodeMessage.kt | AnFxy | 623,415,411 | false | null | package com.nonetxmxy.mmzqfxy.model
data class PayCodeMessage(
val QWZRFcNqe: String, // 付款码号
val giwxW: Double, // 还款金额
val UsYfImNVu: String, // 手机号
val wWa: String, // 姓名
val ZxQ: String, // 还款日期
val oslNs: String, // 还款截止时间
val munR: String?, // 条形码图片 url
)
| 0 | Kotlin | 0 | 0 | 5fa1b0610746a42a8adad1f7da282842356851d1 | 291 | M22 | Apache License 2.0 |
simulator/src/main/kotlin/components/svg/AppendDef.kt | jGleitz | 239,469,794 | false | null | package de.joshuagleitze.transformationnetwork.simulator.components.svg
import kotlinext.js.jsObject
import react.RBuilder
import react.RComponent
import react.RHandler
import react.RProps
import react.RState
private interface AppendDefProps : RProps {
var id: String
}
private interface AppendDefState : RState {
var instanceId: String
}
private var idCounter = 0
private class AppendDef : RComponent<AppendDefProps, AppendDefState>() {
init {
state = jsObject {
instanceId = idCounter++.toString()
}
}
override fun RBuilder.render() {
SvgDefContext.Consumer { defReceiver ->
if (defReceiver == null) return@Consumer
val defElementIds = defReceiver.getDefMappings()
if (!defElementIds.containsKey(props.id)) {
defReceiver.appendDefMapping(props.id, state.instanceId)
}
if ((defElementIds[props.id] ?: state.instanceId) == state.instanceId) {
with(defReceiver) {
appendDef {
props.children()
}
}
}
}
}
}
fun RBuilder.AppendDef(id: String, handler: RHandler<*>) = child(AppendDef::class) {
attrs.id = id
handler()
} | 3 | Kotlin | 0 | 1 | d5d0bd7722abe3260bc204f128337c25c0fb340e | 1,284 | transformationnetwork-simulator | MIT License |
app/src/main/java/com/fsh/android/wanandroidmvvm/common/state/LogoutState.kt | fshsoft | 506,052,730 | false | {"Kotlin": 370644} | package com.fsh.android.wanandroidmvvm.common.state
import android.content.Context
import com.fsh.android.wanandroidmvvm.R
import com.fsh.android.wanandroidmvvm.common.state.callback.CollectListener
import com.fsh.android.wanandroidmvvm.common.utils.startActivity
import com.fsh.android.wanandroidmvvm.module.account.view.LoginActivity
import org.jetbrains.anko.toast
/**
* Created with Android Studio.
* Description:
*/
class LogoutState :UserState {
override fun collect(context: Context, position: Int, listener: CollectListener) {
startLoginActivity(context)
}
override fun login(context: Context) {
startLoginActivity(context)
}
override fun startRankActivity(context: Context) {
startLoginActivity(context)
}
override fun startCollectActivity(context: Context) {
startLoginActivity(context)
}
override fun startShareActivity(context: Context) {
startLoginActivity(context)
}
override fun startAddShareActivity(context: Context) {
startLoginActivity(context)
}
override fun startTodoActivity(context: Context) {
startLoginActivity(context)
}
private fun startLoginActivity(context: Context) {
context?.let {
it.toast(it.getString(R.string.please_login))
startActivity<LoginActivity>(it)
}
}
override fun startEditTodoActivity(context: Context) {
startLoginActivity(context)
}
} | 0 | Kotlin | 0 | 1 | 820418b44745e38e422f35d290754d2d330e24a1 | 1,471 | WanAndroidMVVM | Apache License 2.0 |
jwt/src/main/java/me/uport/sdk/jwt/model/JwtHeader.kt | uport-project | 180,781,299 | false | null | package me.uport.sdk.jwt.model
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonConfiguration
/**
* Standard JWT header
*/
@Serializable
class JwtHeader(
val typ: String = "JWT",
val alg: String = ES256K
) {
fun toJson(): String = jsonAdapter.stringify(serializer(), this)
companion object {
const val ES256K = "ES256K"
const val ES256K_R = "ES256K-R"
fun fromJson(headerString: String): JwtHeader =
jsonAdapter.parse(serializer(), headerString)
private val jsonAdapter =
Json(JsonConfiguration.Stable.copy(isLenient = true, ignoreUnknownKeys = true))
}
}
| 12 | Kotlin | 5 | 8 | 91930d08b566b47bb2c07cce540416dfc35be05c | 711 | kotlin-did-jwt | Apache License 2.0 |
app/src/main/java/com/engdiary/mureng/ui/social_best/AnswerAdapter.kt | YAPP-18th | 331,208,681 | false | null | package com.engdiary.mureng.ui.social_best
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.engdiary.mureng.R
import com.engdiary.mureng.data.domain.Diary
import com.engdiary.mureng.databinding.ItemSocialAnswerBinding
import com.engdiary.mureng.databinding.ItemSocialBestAnswerBinding
import com.engdiary.mureng.databinding.ItemSocialUserAnswerBinding
import com.engdiary.mureng.di.MurengApplication
import com.engdiary.mureng.util.setOnSingleClickListener
import jp.wasabeef.blurry.Blurry
/**
* Social_Best Tab 인기 답변 RecyclerView Adapter
*/
class AnswerAdapter(
val type: AnswerRecyclerType,
val vm: BestPopularViewModel
) :
ListAdapter<Diary, RecyclerView.ViewHolder>(AnswerDiffUtilCallBack) {
companion object {
const val TYPE_BEST = 0
const val TYPE_BEST_MORE = 1
const val TYPE_DETAIL = 2
}
override fun getItemCount(): Int {
return super.getItemCount()
}
override fun getItemViewType(position: Int): Int {
return when (type) {
AnswerRecyclerType.TYPE_BEST -> {
TYPE_BEST
}
AnswerRecyclerType.TYPE_BEST_MORE -> {
TYPE_BEST_MORE
}
else -> {
TYPE_DETAIL
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
return when (viewType) {
TYPE_BEST -> {
val binding: ItemSocialAnswerBinding = DataBindingUtil.inflate(
layoutInflater, R.layout.item_social_answer, parent, false
)
AnswerViewHolder(binding).apply {
binding.root.setOnSingleClickListener {
vm.answerItemClick(binding.diary!!)
}
}
}
TYPE_BEST_MORE -> {
val binding: ItemSocialBestAnswerBinding = DataBindingUtil.inflate(
layoutInflater, R.layout.item_social_best_answer, parent, false
)
AnswerBestViewHolder(binding).apply {
binding.root.setOnSingleClickListener {
vm.answerItemClick(binding.diary!!)
}
binding.clBestMoreAnswerHeart.setOnClickListener {
vm.answerItemHeartClick(binding.diary!!)
binding.diary = binding.diary!!.apply {
if (likeYn) likeCount -= 1
else likeCount += 1
likeYn = !this.likeYn!!
}
}
}
}
else -> {
val binding: ItemSocialUserAnswerBinding = DataBindingUtil.inflate(
layoutInflater, R.layout.item_social_user_answer, parent, false
)
AnswerUserViewHolder(binding).apply {
binding.root.setOnSingleClickListener {
vm.answerItemClick(binding.diary!!)
}
binding.clSocialUserHeart.setOnClickListener {
vm.answerItemHeartClick(binding.diary!!)
binding.diary = binding.diary!!.apply {
if (likeYn) likeCount -= 1
else likeCount += 1
likeYn = !this.likeYn!!
}
}
}
}
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder.itemViewType) {
TYPE_BEST -> {
(holder as AnswerViewHolder).bind(getItem(position), vm)
}
TYPE_BEST_MORE -> {
(holder as AnswerBestViewHolder).bind(getItem(position), vm)
}
else -> {
(holder as AnswerUserViewHolder).bind(getItem(position))
}
}
}
}
class AnswerViewHolder(private val binding: ItemSocialAnswerBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(diaryData: Diary, vm: BestPopularViewModel) {
binding.diary = diaryData
binding.vm = vm
}
}
class AnswerUserViewHolder(private val binding: ItemSocialUserAnswerBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(diaryData: Diary) {
binding.diary = diaryData
}
}
class AnswerBestViewHolder(private val binding: ItemSocialBestAnswerBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(diaryData: Diary, vm: BestPopularViewModel) {
binding.diary = diaryData
binding.vm = vm
}
}
object AnswerDiffUtilCallBack : DiffUtil.ItemCallback<Diary>() {
override fun areItemsTheSame(
oldItem: Diary,
newItem: Diary,
): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(
oldItem: Diary,
newItem: Diary,
): Boolean {
return oldItem.hashCode() == newItem.hashCode()
}
}
enum class AnswerRecyclerType { TYPE_BEST, TYPE_BEST_MORE, TYPE_DETAIL }
| 11 | Kotlin | 1 | 3 | 4052cc746ef8be6c922ca7ef523ace28134bd052 | 5,443 | Android-Team-1-Frontend | Apache License 2.0 |
hubdle-gradle-plugin/main/kotlin/com/javiersc/hubdle/extensions/kotlin/HubdleKotlinExtension.kt | JavierSegoviaCordoba | 348,863,451 | false | null | package com.javiersc.hubdle.extensions.kotlin
import com.javiersc.hubdle.extensions.HubdleDslMarker
import com.javiersc.hubdle.extensions._internal.getHubdleExtension
import com.javiersc.hubdle.extensions.apis.HubdleConfigurableExtension
import com.javiersc.hubdle.extensions.apis.HubdleEnableableExtension
import com.javiersc.hubdle.extensions.apis.enableAndExecute
import com.javiersc.hubdle.extensions.kotlin.android.HubdleKotlinAndroidExtension
import com.javiersc.hubdle.extensions.kotlin.android.application.hubdleAndroidApplication
import com.javiersc.hubdle.extensions.kotlin.android.library.hubdleAndroidLibrary
import com.javiersc.hubdle.extensions.kotlin.features.HubdleKotlinFeaturesExtension
import com.javiersc.hubdle.extensions.kotlin.jvm.HubdleKotlinJvmExtension
import com.javiersc.hubdle.extensions.kotlin.jvm.hubdleKotlinJvm
import com.javiersc.hubdle.extensions.kotlin.multiplatform.HubdleKotlinMultiplatformExtension
import com.javiersc.hubdle.extensions.kotlin.multiplatform.hubdleKotlinMultiplatform
import javax.inject.Inject
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.provider.Property
@HubdleDslMarker
public open class HubdleKotlinExtension
@Inject
constructor(
project: Project,
) : HubdleEnableableExtension(project) {
override val isEnabled: Property<Boolean> = property { false }
public val features: HubdleKotlinFeaturesExtension
get() = getHubdleExtension()
@HubdleDslMarker
public fun features(action: Action<HubdleKotlinFeaturesExtension> = Action {}) {
features.enableAndExecute(action)
}
public val android: HubdleKotlinAndroidExtension
get() = getHubdleExtension()
@HubdleDslMarker
public fun android(action: Action<HubdleKotlinAndroidExtension> = Action {}) {
android.enableAndExecute(action)
}
public val jvm: HubdleKotlinJvmExtension
get() = getHubdleExtension()
@HubdleDslMarker
public fun jvm(action: Action<HubdleKotlinJvmExtension> = Action {}) {
jvm.enableAndExecute(action)
}
public val multiplatform: HubdleKotlinMultiplatformExtension
get() = getHubdleExtension()
@HubdleDslMarker
public fun multiplatform(action: Action<HubdleKotlinMultiplatformExtension> = Action {}) {
multiplatform.enableAndExecute(action)
}
}
internal val HubdleEnableableExtension.hubdleKotlin: HubdleKotlinExtension
get() = getHubdleExtension()
internal val HubdleEnableableExtension.hubdleKotlinAny: Set<HubdleConfigurableExtension>
get() =
setOf(
hubdleAndroidApplication,
hubdleAndroidLibrary,
hubdleKotlinJvm,
hubdleKotlinMultiplatform,
)
| 14 | Kotlin | 8 | 16 | ca21470528b8f62b91c2f16e14d8ef62b39bf3b9 | 2,725 | hubdle | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.