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
data/src/main/java/com/qure/data/local/FishingSpotDao.kt
hegleB
613,354,773
false
{"Kotlin": 515292}
package com.qure.data.local import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.qure.data.entity.fishingspot.FishingSpotBookmarkEntity @Dao internal interface FishingBookmarkDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertFishingSpot(fishingSpotBookmarkEntity: FishingSpotBookmarkEntity) @Query("select * from fishing_spot_bookmark_table") suspend fun getFishingSpots(): List<FishingSpotBookmarkEntity> @Query("select EXISTS(SELECT * from fishing_spot_bookmark_table where number = :number)") suspend fun checkFishingSpot(number: Int): Boolean @Delete suspend fun deleteFishingSpot(fishingSpotBookmarkEntity: FishingSpotBookmarkEntity) @Query("delete from fishing_spot_bookmark_table") suspend fun deleteAllFishingSpots() }
0
Kotlin
0
1
6625bdb6336f9e493aa8285c4f02725d47a1c9f1
902
FishingMemory
The Unlicense
src/main/java/name/tachenov/flakardia/ui/InitFrame.kt
stachenov
750,509,456
false
{"Kotlin": 65219, "Java": 152}
package name.tachenov.flakardia.ui import javax.swing.JFrame import javax.swing.JLabel class InitFrame : JFrame("Flakardia") { init { defaultCloseOperation = DISPOSE_ON_CLOSE add(JLabel("Configuring...")) } }
0
Kotlin
0
0
951461f467f0019b02ea4bf62506c90e48604f65
237
flakardia
MIT License
app/src/main/java/space/mrandika/kelaperan/ui/component/list/GalleryList.kt
mrandika
643,831,454
false
null
package space.mrandika.kelaperan.ui.component.list import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import space.mrandika.kelaperan.model.GalleryItem import space.mrandika.kelaperan.ui.component.item.GalleryItem @Composable fun GalleryList( foodName: String, items: List<GalleryItem>, modifier: Modifier = Modifier ) { LazyRow( modifier = Modifier.padding(top = 8.dp) ) { items(items, key = { it.id }) { gallery -> GalleryItem(name = foodName, imageUrl = gallery.imageUrl) } } }
0
Kotlin
0
0
386adc0683efb4aa3eb2406ad145d37173b1fbdf
749
android-kelaperan_compose
MIT License
domain/src/main/java/com/iamkurtgoz/domain/entities/RatingResponse.kt
iamkurtgoz
464,093,153
false
null
package com.iamkurtgoz.domain.entities data class RatingResponse( val count: Int?, val rate: Double? )
0
Kotlin
1
25
57f7a95021a125e0cdae4924c32891f6b70b0c5a
111
ECommerceAndroidCompose
MIT License
app/src/main/java/com/rpsouza/blogapp/presenter/MainActivity.kt
rpsouzadev
813,352,021
false
{"Kotlin": 23785}
package com.rpsouza.blogapp.presenter import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.rpsouza.blogapp.databinding.ActivityMainBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) } }
0
Kotlin
0
0
e5e18bb0fba4f565c2715212eec19aa86fa2610d
664
Blog-App
MIT License
app/src/main/java/com/gzaber/forexviewer/data/repository/favorites/model/Favorite.kt
gzaber
734,830,877
false
{"Kotlin": 22805}
package com.gzaber.forexviewer.data.repository.favorites.model data class Favorite( val id: Int? = null, val symbol: String )
0
Kotlin
0
0
c2707685078db7e3b4397bed4f6fd264e319d5cc
135
ForexViewer
MIT License
einvoice/src/main/java/com/kevinchung/einvoice/data/CarrierHeaderRsp.kt
kevinchung0921
272,900,709
false
null
package com.kevinchung.einvoice.data data class CarrierHeaderRsp ( val v: String, val msg: String, val onlyWinningInv: String, val details: List<CarrierHeader> )
1
Kotlin
3
1
682ae3d991e72f685d762ebd407dc89b81218203
178
einvoice_sdk
MIT License
app/src/main/java/com/soulll/todoapp/data/viewmodel/ToDoViewModel.kt
michaeldadzie
309,843,093
false
null
package com.soulll.todoapp.data.viewmodel import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.viewModelScope import androidx.room.Query import com.soulll.todoapp.data.ToDoDatabase import com.soulll.todoapp.data.models.ToDoData import com.soulll.todoapp.data.repository.ToDoRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class ToDoViewModel(application: Application):AndroidViewModel(application) { private val toDoDao = ToDoDatabase.getDatabase(application).toDoDao() private val repository: ToDoRepository val getAllData: LiveData<List<ToDoData>> val sortByHighPriority: LiveData<List<ToDoData>> val sortByLowPriority: LiveData<List<ToDoData>> init { repository = ToDoRepository(toDoDao) getAllData = repository.getAllData sortByHighPriority = repository.sortByHighPriority sortByLowPriority = repository.sortByLowPriority } fun insertData(toDoData: ToDoData) { viewModelScope.launch (Dispatchers.IO){ repository.insertData(toDoData) } } fun updateData(toDoData: ToDoData){ viewModelScope.launch(Dispatchers.IO){ repository.updateData(toDoData) } } fun deleteItem(toDoData: ToDoData){ viewModelScope.launch(Dispatchers.IO){ repository.deleteItem(toDoData) } } fun deleteAll() { viewModelScope.launch(Dispatchers.IO) { repository.deleteAll() } } fun searchDatabase(searchQuery: String): LiveData<List<ToDoData>> { return repository.searchDatabase(searchQuery) } }
0
Kotlin
0
3
75d5393b3444b6f1db7560e8da35bc5ba2e0a4fb
1,714
ToDo
MIT License
data/src/main/java/com/riyaz/data/remote/IpGeolocationApi.kt
Riyaz002
786,449,280
false
{"Kotlin": 58927}
package com.riyaz.data.remote import com.riyaz.data.BuildConfig import com.riyaz.data.remote.model.location.LocationInfoDTO import retrofit2.Call import retrofit2.http.GET import retrofit2.http.QueryMap interface IpGeolocationApi { @GET("ipgeo") fun getLocationInfo( @QueryMap query: HashMap<String, String> = hashMapOf("apiKey" to BuildConfig.IP_GEOLOCATION_API_KEY) ): Call<LocationInfoDTO> companion object{ const val BASE_URL = "https://api.ipgeolocation.io/" } }
0
Kotlin
0
0
88b0376dfd05b49e280a040e9420be3523310490
507
Weatheria
Apache License 2.0
app/src/main/java/ch/admin/foitt/pilotwallet/feature/login/domain/usecase/IsDevicePinSet.kt
e-id-admin
775,912,525
false
{"Kotlin": 1521284}
package ch.admin.foitt.pilotwallet.feature.login.domain.usecase import androidx.annotation.CheckResult fun interface IsDevicePinSet { @CheckResult operator fun invoke(): Boolean }
1
Kotlin
1
4
6572b418ec5abc5d94b18510ffa87a1e433a5c82
190
eidch-pilot-android-wallet
MIT License
src/main/kotlin/org/jungmha/utils/ShiftTo.kt
rushmi0
729,413,199
false
{"Kotlin": 202535, "PLpgSQL": 11138, "HTML": 3377, "Dockerfile": 102}
package org.jungmha.utils import org.jungmha.utils.ShiftTo.encodeBase64 import java.io.File import java.math.BigInteger import java.nio.ByteBuffer import java.nio.ByteOrder import java.security.MessageDigest import java.util.* object ShiftTo { private val hexDigits: String = "0123456789abcdef" fun String.HexToBinary(): String { val stringBuilder = StringBuilder(length * 4) for (hexChar in this) { val decimalValue = hexDigits.indexOf(hexChar) val binaryChunk = decimalValue.toString(2).padStart(4, '0') stringBuilder.append(binaryChunk) } return stringBuilder.toString() } fun String.BinaryToHex(): String { require(length % 4 == 0) { "Invalid binary string length" } val stringBuilder = StringBuilder(length / 4) for (i in 0 until length step 4) { val binarySegment = substring(i, i + 4) val decimalValue = binarySegment.toInt(2) val hexDigit = decimalValue.toString(16) stringBuilder.append(hexDigit) } return stringBuilder.toString() } fun ByteArray.ByteArrayToBigInteger(): BigInteger { return BigInteger(1, this) } fun String.BinaryToByteArray(): ByteArray { return this.chunked(8).map { it.toInt(2).toByte() }.toByteArray() } fun ByteArray.ByteArrayToBinary(): String { return joinToString("") { byte -> byte.toUByte().toString(2).padStart(8, '0') } } fun ByteArray.ByteArrayToHex(): String { return joinToString("") { byte -> byte.toUByte().toString(16).padStart(2, '0') } } fun BigInteger.DeciToHex(): String { var number = this val result = StringBuilder() if (number == BigInteger.ZERO) { return "0" } while (number > BigInteger.ZERO) { val remainder = number % BigInteger.valueOf(16) result.insert(0, hexDigits[remainder.toInt()]) number /= BigInteger.valueOf(16) } return result.toString() } fun BigInteger.DeciToBin(): String { var decimalValue = this var binaryResult = "" if (decimalValue == BigInteger.ZERO) { return "0" } while (decimalValue > BigInteger.ZERO) { val remainder = decimalValue % BigInteger.valueOf(2) binaryResult = remainder.toString() + binaryResult decimalValue /= BigInteger.valueOf(2) } return binaryResult } fun Int.DeciToByte(): ByteArray { val bytes = ByteArray(4) bytes[0] = (this shr 24 and 0xFF).toByte() bytes[1] = (this shr 16 and 0xFF).toByte() bytes[2] = (this shr 8 and 0xFF).toByte() bytes[3] = (this and 0xFF).toByte() return bytes } fun Long.DeciToByte(): ByteArray { val bytes = ByteArray(8) bytes[0] = (this shr 56 and 0xFF).toByte() bytes[1] = (this shr 48 and 0xFF).toByte() bytes[2] = (this shr 40 and 0xFF).toByte() bytes[3] = (this shr 32 and 0xFF).toByte() bytes[4] = (this shr 24 and 0xFF).toByte() bytes[5] = (this shr 16 and 0xFF).toByte() bytes[6] = (this shr 8 and 0xFF).toByte() bytes[7] = (this and 0xFF).toByte() return bytes } fun Int.DeciToHex(): String { var number = this val result = StringBuilder() if (number == 0) { return "0" } while (number > 0) { val remainder = number % 16 result.insert(0, hexDigits[remainder]) number /= 16 } return result.toString() } fun Byte.ByteToHex(): String { val hex = CharArray(2) hex[0] = hexDigits[(this.toInt() shr 4) and 0x0f] hex[1] = hexDigits[this.toInt() and 0x0f] return String(hex) } fun ByteArray.ByteArrayToList(): List<Int> { val integers = mutableListOf<Int>() for (i in this.indices) { integers.add(this[i].toInt() and 0xff) } return integers } fun Int.DeciToHexByte(): String { return "%02X".format(this) } fun String.FlipByteOrder(): String { return this.chunked(2).reversed().joinToString("") } fun String.HexToByteArray(): ByteArray = ByteArray(this.length / 2) { this.substring(it * 2, it * 2 + 2).toInt(16).toByte() } fun String.littleEndianToDeci(): Long { var result: Long = 0 var multiplier: Long = 1 val bytes = this.HexToByteArray() for (element in bytes) { val byteValue: Long = element.toLong() and 0xFF result += byteValue * multiplier multiplier *= 256 } return result } fun String.splitHexData(): List<String> { val result = mutableListOf<String>() for (i in indices step 2) { val hex = this.substring(i, i + 2) result.add(hex) } return result } fun Int.intToByteArray(): ByteArray { val buffer = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN) buffer.putInt(this) return buffer.array() } fun ByteArray.SHA256(): ByteArray { return MessageDigest.getInstance("SHA-256").digest(this) } fun String.SHA256(): ByteArray { return toByteArray().SHA256() } fun String.encodeBase64(): String { return Base64.getEncoder().encodeToString(this.HexToByteArray()) } fun Int.encodeBase64(): String { return this.DeciToHex().encodeBase64() } fun ByteArray.encodeBase64(): String { return Base64.getEncoder().encodeToString(this) } fun String.decodeBase64(): ByteArray { return Base64.getDecoder().decode(this) } fun String.toFileName(): String { val fileName = File(this).name return fileName.substringAfterLast(File.separator) } }
0
Kotlin
0
1
8cdccd37f0f1966bbadfea1ea485c3e35cc832c8
5,986
Jungmha
MIT License
src/commonTest/kotlin/suite/TestSuiteMultipleOperations.kt
pallavirawat
205,637,107
true
{"Kotlin": 941656, "Ruby": 4462}
package suite import clientAdmin1 import com.algolia.search.helper.toAttribute import com.algolia.search.model.indexing.BatchOperation import com.algolia.search.model.multipleindex.BatchOperationIndex import com.algolia.search.model.multipleindex.IndexQuery import com.algolia.search.model.multipleindex.MultipleQueriesStrategy import com.algolia.search.model.multipleindex.RequestObjects import com.algolia.search.model.search.Query import com.algolia.search.model.task.TaskStatus import kotlinx.serialization.json.content import kotlinx.serialization.json.json import runBlocking import shouldBeTrue import shouldEqual import kotlin.test.AfterTest import kotlin.test.Test internal class TestSuiteMultipleOperations { private val suffix = "multiple_operations" private val indexName1 = testSuiteIndexName(suffix) private val indexName2 = indexName1.copy(raw = indexName1.raw + "_dev") private val firstname = "firstname" private val jimmie = "Jimmie" private val json = json { firstname to jimmie } @AfterTest fun clean() { runBlocking { cleanIndex(clientAdmin1, suffix) } } @Test fun test() { runBlocking { val operations = listOf( BatchOperationIndex(indexName1, BatchOperation.AddObject(json)), BatchOperationIndex(indexName1, BatchOperation.AddObject(json)), BatchOperationIndex(indexName2, BatchOperation.AddObject(json)), BatchOperationIndex(indexName2, BatchOperation.AddObject(json)) ) clientAdmin1.apply { val response = multipleBatchObjects(operations) response.waitAll().all { it is TaskStatus.Published }.shouldBeTrue() val requests = operations.mapIndexed { index, request -> RequestObjects(request.indexName, response.objectIDs[index]!!) } multipleGetObjects(requests).let { it.results.size shouldEqual 4 it.results[0]?.get(firstname)?.content shouldEqual jimmie it.results[0]?.get(firstname)?.content shouldEqual jimmie it.results[0]?.get(firstname)?.content shouldEqual jimmie it.results[0]?.get(firstname)?.content shouldEqual jimmie } val query = Query(query = "", hitsPerPage = 2, facets = setOf("color".toAttribute(), "brand".toAttribute())) val indexQueries = listOf( IndexQuery(indexName1, query), IndexQuery(indexName2, query) ) multipleQueries(indexQueries).let { it.results.size shouldEqual 2 it.results[0].hits.size shouldEqual 2 it.results[1].hits.size shouldEqual 2 } multipleQueries(indexQueries, MultipleQueriesStrategy.StopIfEnoughMatches).let { it.results.size shouldEqual 2 it.results[0].hits.size shouldEqual 2 it.results[1].hits.size shouldEqual 0 } } } } }
0
Kotlin
0
0
a7127793476d4453873266222ea71b1fce5c8c32
3,215
algoliasearch-client-kotlin
MIT License
app/src/main/java/com/santebreezefsm/features/newcollectionreport/PendingCollDtlsListner.kt
DebashisINT
671,482,089
false
null
package com.santebreezefsm.features.newcollectionreport interface PendingCollDtlsListner { fun getInfoDtlsOnLick(obj: PendingCollDtlsData) }
0
Kotlin
0
0
62b1c8071b5e8a3e9cdee19c774a43487b36d373
145
FSMSante
Apache License 2.0
app/src/main/java/com/madrat/kursovaya/screens/generatemealplan/model/GenerateMealPlanResponse.kt
MadRatSRP
245,657,269
false
{"Kotlin": 74907}
package com.madrat.kursovaya.screens.generatemealplan.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class GenerateMealPlanResponse( @field:SerializedName("meals") @field:Expose val meals: ArrayList<Meal>, @field:SerializedName("nutrients") @field:Expose val nutrients: Nutrients )
0
Kotlin
0
0
4f0239c4e7931ca2dcf3b33c368e16de5ad868a8
363
Coursework_API
Apache License 2.0
profile/src/test/java/rdx/works/profile/snapshot/SnapshotHeaderTests.kt
radixdlt
513,047,280
false
{"Kotlin": 4211156, "HTML": 215350, "Java": 18496, "Ruby": 2757, "Shell": 1962}
package rdx.works.profile.snapshot import org.junit.Test import rdx.works.profile.data.model.DeviceInfo import rdx.works.profile.data.model.Header import rdx.works.profile.data.model.ProfileSnapshot import java.time.Instant import kotlin.test.assertFalse import kotlin.test.assertTrue class SnapshotHeaderTests { @Test fun `test version compatibility too low`() { val version = ProfileSnapshot.MINIMUM - 1 val header = Header( creatingDevice = device, lastUsedOnDevice = device, id = id, lastModified = date, snapshotVersion = version, contentHint = Header.ContentHint( numberOfNetworks = 1, numberOfAccountsOnAllNetworksInTotal = 1, numberOfPersonasOnAllNetworksInTotal = 0 ) ) assertFalse(header.isCompatible) } @Test fun `test version compatibility ok`() { val header = Header( creatingDevice = device, lastUsedOnDevice = device, id = id, lastModified = date, snapshotVersion = ProfileSnapshot.MINIMUM, contentHint = Header.ContentHint( numberOfNetworks = 1, numberOfAccountsOnAllNetworksInTotal = 1, numberOfPersonasOnAllNetworksInTotal = 0 ) ) assertTrue(header.isCompatible) } companion object { private val deviceInfo = DeviceInfo(name = "unit test", manufacturer = "computer", model = "computer") private val date = Instant.ofEpochSecond(0) private const val id = "BABE1442-3C98-41FF-AFB0-D0F5829B020D" private val device = Header.Device( description = deviceInfo.displayName, id = id, date = date ) } }
6
Kotlin
11
6
9cda46c4b492dd48bb42fb8f1e011440082c7807
1,847
babylon-wallet-android
Apache License 2.0
lib/src/main/java/io/sellmair/quantum/internal/Locked.kt
sellmair
147,240,457
false
null
package io.sellmair.quantum.internal import java.util.concurrent.locks.Lock import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /* ################################################################################################ INTERNAL API ################################################################################################ */ internal class Locked<T : Any>(private val value: T, private val lock: ReentrantLock = ReentrantLock()) : Lock by lock { inline operator fun <R> invoke(operation: T.() -> R): R = withLock { operation(value) } val isHeldByCurrentThread get() = lock.isHeldByCurrentThread val isNotHeldByCurrentThread get() = !isHeldByCurrentThread }
1
Kotlin
3
71
a235277f9ce915ce54d933416a9724cbf424e776
766
quantum
MIT License
live/src/main/java/com/sky/live/widget/VapAnimationView.kt
SkyZhang007
475,327,762
false
{"Kotlin": 343559, "Java": 198743}
package com.sky.live.widget import android.content.Context import android.util.AttributeSet import android.widget.FrameLayout import com.tencent.qgame.animplayer.AnimConfig import com.tencent.qgame.animplayer.AnimView import com.tencent.qgame.animplayer.inter.IAnimListener import java.io.File /** * 类功能: * 类作者:Sky * 类日期:2022/4/1. **/ class VapAnimationView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { companion object { const val TAG = "AnimationView" const val TYPE_MP4 = 0 } private var animationType: Int? = 0 private var loopCount: Int = 0 private var animationLink: String? = null private val animView: AnimView by lazy { AnimView(context) } init { addView(animView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) } fun setAnimationType(type: Int?) { animationType = type } fun setAnimationLink(link: String) { animationLink = link } fun start() { if (animationLink.isNullOrEmpty() || animationLink.isNullOrEmpty()) { return } startInner(animationLink!!) } private fun startInner(path: String) { animView.run { stopPlay() postDelayed({ setAnimListener(object : IAnimListener { override fun onFailed(errorType: Int, errorMsg: String?) { } override fun onVideoComplete() { } override fun onVideoDestroy() { } override fun onVideoRender(frameIndex: Int, config: AnimConfig?) { } override fun onVideoStart() { } }) setLoop( if (loopCount <= 0) { Int.MAX_VALUE } else { loopCount } ) startPlay(File(path)) }, 100) } } fun setLoopCount(count: Int) { loopCount = count } fun stop() { animView.stopPlay() } fun release() { animView.stopPlay() } }
0
Kotlin
0
0
52bd077971d7b6f4e695d6da27a10058ad14fd13
2,319
Sky-Base
Apache License 2.0
redwood-protocol-widget/src/commonMain/kotlin/app/cash/redwood/protocol/widget/ProtocolBridge.kt
cashapp
305,409,146
false
{"Kotlin": 1531483, "Swift": 14188, "Java": 1583, "Objective-C": 1499, "HTML": 235, "C": 43}
/* * Copyright (C) 2021 Square, 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 app.cash.redwood.protocol.widget import app.cash.redwood.Modifier import app.cash.redwood.protocol.Change import app.cash.redwood.protocol.ChangesSink import app.cash.redwood.protocol.ChildrenChange import app.cash.redwood.protocol.ChildrenChange.Add import app.cash.redwood.protocol.ChildrenChange.Move import app.cash.redwood.protocol.ChildrenChange.Remove import app.cash.redwood.protocol.ChildrenTag import app.cash.redwood.protocol.Create import app.cash.redwood.protocol.EventSink import app.cash.redwood.protocol.Id import app.cash.redwood.protocol.ModifierChange import app.cash.redwood.protocol.ModifierElement import app.cash.redwood.protocol.PropertyChange import app.cash.redwood.widget.ChangeListener import app.cash.redwood.widget.Widget import kotlin.native.ObjCName /** * Bridges the serialized Redwood protocol back to widgets on the display side. * * This type will consume [Change]s and apply their [ChildrenChange] operations to the widget tree. * [PropertyChange]s and [ModifierChange]s are forwarded to their respective widgets. * Events from widgets are forwarded to [eventSink]. */ @ObjCName("ProtocolBridge", exact = true) public class ProtocolBridge<W : Any>( container: Widget.Children<W>, private val factory: ProtocolNode.Factory<W>, private val eventSink: EventSink, ) : ChangesSink { private val nodes = mutableMapOf<Id, ProtocolNode<W>>( Id.Root to RootProtocolNode(container), ) private val changedWidgets = mutableSetOf<ChangeListener>() override fun sendChanges(changes: List<Change>) { for (i in changes.indices) { val change = changes[i] val id = change.id when (change) { is Create -> { val node = factory.create(change.tag) ?: continue val old = nodes.put(change.id, node) require(old == null) { "Insert attempted to replace existing widget with ID ${change.id.value}" } } is ChildrenChange -> { val node = node(id) val children = node.children(change.tag) ?: continue when (change) { is Add -> { val child = node(change.childId) children.insert(change.index, child.widget) } is Move -> { children.move(change.fromIndex, change.toIndex, change.count) } is Remove -> { children.remove(change.index, change.count) @Suppress("ConvertArgumentToSet") // Compose side guarantees set semantics. nodes.keys.removeAll(change.removedIds) } } val widget = node.widget if (widget is ChangeListener) { changedWidgets += widget } } is ModifierChange -> { val node = node(id) node.updateModifier(change.elements) val widget = node.widget if (widget is ChangeListener) { changedWidgets += widget } } is PropertyChange -> { val node = node(change.id) node.apply(change, eventSink) val widget = node.widget if (widget is ChangeListener) { changedWidgets += widget } } } } if (changedWidgets.isNotEmpty()) { for (widget in changedWidgets) { widget.onEndChanges() } changedWidgets.clear() } } private fun node(id: Id): ProtocolNode<W> { return checkNotNull(nodes[id]) { "Unknown widget ID ${id.value}" } } } private class RootProtocolNode<W : Any>( private val children: Widget.Children<W>, ) : ProtocolNode<W>, Widget<W> { override fun updateModifier(elements: List<ModifierElement>) { throw AssertionError("unexpected: $elements") } override fun apply(change: PropertyChange, eventSink: EventSink) { throw AssertionError("unexpected: $change") } override fun children(tag: ChildrenTag) = when (tag) { ChildrenTag.Root -> children else -> throw AssertionError("unexpected: $tag") } override val widget: Widget<W> get() = this override fun attachTo(container: Widget.Children<W>) { throw AssertionError() } override val value: W get() = throw AssertionError() override var modifier: Modifier get() = throw AssertionError() set(_) { throw AssertionError() } }
105
Kotlin
51
1,272
a35475e9d6a7e981398477ec9c8a191d135ddb13
4,942
redwood
Apache License 2.0
app/src/main/java/com/d20/rpgdice/MainActivity.kt
ElNotaCode
551,013,033
false
{"Kotlin": 12404}
package com.d20.rpgdice import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import android.view.Menu import android.view.MenuItem import com.d20.rpgdice.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) val navController = findNavController(R.id.nav_host_fragment_content_main) appBarConfiguration = AppBarConfiguration(navController.graph) setupActionBarWithNavController(navController, appBarConfiguration) } private fun share() { val intent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT,resources.getString(R.string.share_text)) type = "text/plain" putExtra(Intent.EXTRA_TITLE,resources.getString(R.string.share_extra_text)) } val shareIntent = Intent.createChooser(intent,null) startActivity(shareIntent) } //TODO: mejora share //https://www.youtube.com/watch?v=_ij640TqtMo override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> { findNavController(R.id.nav_host_fragment_content_main).navigate(R.id.to_SettingsFragment) true } R.id.action_share -> { share() true } else -> super.onOptionsItemSelected(item) } } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment_content_main) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
0
Kotlin
0
0
24de243cb873cdf16b5edfe82c8c868348d1ffd9
2,699
RPG-Dice
Creative Commons Zero v1.0 Universal
app/src/main/kotlin/com/ivanovsky/passnotes/domain/interactor/server_login/GetDebugCredentialsUseCase.kt
aivanovski
95,774,290
false
null
package com.ivanovsky.passnotes.domain.interactor.server_login import com.ivanovsky.passnotes.BuildConfig import com.ivanovsky.passnotes.data.entity.ServerCredentials class GetDebugCredentialsUseCase { fun getDebugWebDavCredentials(): ServerCredentials? { if (!BuildConfig.DEBUG) return null val url = BuildConfig.DEBUG_WEB_DAV_URL val username = BuildConfig.DEBUG_WEB_DAV_USERNAME val password = BuildConfig.DEBUG_WEB_DAV_PASSWORD return if (url.isNotEmpty() || username.isNotEmpty() || password.isNotEmpty()) { ServerCredentials(url, username, password) } else { null } } }
0
Kotlin
0
0
bd4fd41a58c3d16489319e5982317ffe8b798e79
668
passnotes
Apache License 2.0
jax-rs/src/test/kotlin/test/jaxrs/queryparameters/onfunction/QueryParameterOnFunction.kt
thanhpv1991
318,412,498
true
{"Kotlin": 721334, "RAML": 5024, "Shell": 1492}
package test.jaxrs.queryparameters.onfunction import javax.ws.rs.GET import javax.ws.rs.Path import javax.ws.rs.QueryParam @Path("/todos") @Suppress("UNUSED_PARAMETER") class QueryParameterOnFunction { @GET fun todo(@QueryParam("filter") filter: String) { } }
0
null
0
0
1b42ea6eca45d3f1360cecf4d1f207ef4007d300
271
hikaku
Apache License 2.0
plugin-location/src/main/kotlin/me/leon/toolsfx/plugin/LocationServiceType.kt
Leon406
381,644,086
false
null
package me.leon.toolsfx.plugin import me.leon.Digests import me.leon.ext.fromJson import me.leon.ext.readFromNet import me.leon.toolsfx.domain.AmapGeo import me.leon.toolsfx.domain.BaiduGeo import tornadofx.* enum class LocationServiceType(val type: String) : ILocationService { WGS2GCJ("wgs2gcj") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.wgs2GCJ( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, WGS2BD09("wgs2bd09") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.wgs2BD09( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, GCJ2BD09("gcj2bd09") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.gcj2BD09( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, GCJ2WGS("gcj2wgs") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.gcj2WGSExactly( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, BD092WGS("bd092wgs") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.bd092WGSExactly( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, BD092GCJ("bd092gcj") { override fun process(raw: String, params: MutableMap<String, String>) = CoordinatorTransform.bd092GCJ( raw.substringAfter(",").toDouble(), raw.substringBefore(",").toDouble() ) .reversed() .joinToString(",") { String.format("%.6f", it) } }, DISTANCE("distance") { override fun process(raw: String, params: MutableMap<String, String>): String { val (p1, p2) = raw.split("-") val (p1Lng, p1Lat) = p1.split(",").map { it.toDouble() } val (p2Lng, p2Lat) = p2.split(",").map { it.toDouble() } return String.format( "%.2f m", CoordinatorTransform.distance(p1Lat, p1Lng, p2Lat, p2Lng) ) } }, GEO_AMPA("geoAmap") { override fun process(raw: String, params: MutableMap<String, String>): String { val address = "address=${raw.urlEncoded}" val queries = "address=${raw}&key=<KEY>&output=json" return ("https://restapi.amap.com/v3/geocode/geo?" + "$address&key=<KEY>&output=json" + "&sig=${Digests.hash("md5",queries+"57b0452167c85d33217472e4e53028ec")}") .also { println(it) } .readFromNet() .also { println(it) } .fromJson(AmapGeo::class.java) .geoInfo() } }, GEO_BD("geoBaidu") { override fun process(raw: String, params: MutableMap<String, String>): String { return ("http://api.map.baidu.com/geocoding/v3/?address=${raw.urlEncoded}" + "&output=json&ak=V0AKhZ3wN8CTU3zx8lGf4QvwyOs5rGIn") .readFromNet() .fromJson(BaiduGeo::class.java) .geoInfo() } }, } val locationServiceTypeMap = LocationServiceType.values().associateBy { it.type } fun String.locationServiceType() = locationServiceTypeMap[this] ?: LocationServiceType.WGS2GCJ
4
null
80
941
bfbdc980e6c0eade4612be955845ba4d8bcefde4
4,252
ToolsFx
ISC License
main/src/main/kotlin/io/github/chrislo27/rhre3/sfxdb/PlayalongEnums.kt
chrislo27
157,302,663
false
null
package io.github.chrislo27.rhre3.sfxdb enum class PlayalongInput(val id: String, val deprecatedIDs: List<String> = listOf(), val isTouchScreen: Boolean = false) { BUTTON_A("A"), BUTTON_B("B"), BUTTON_DPAD("+"), BUTTON_A_OR_DPAD("A_+"), BUTTON_DPAD_UP("+_up"), BUTTON_DPAD_DOWN("+_down"), BUTTON_DPAD_LEFT("+_left"), BUTTON_DPAD_RIGHT("+_right"), TOUCH_TAP("touch_tap", isTouchScreen = true), TOUCH_FLICK("touch_flick", isTouchScreen = true), TOUCH_RELEASE("touch_release", isTouchScreen = true), TOUCH_QUICK_TAP("touch_quick_tap", isTouchScreen = true), TOUCH_SLIDE("touch_slide", isTouchScreen = true); companion object { val VALUES: List<PlayalongInput> = values().toList() private val ID_MAP: Map<String, PlayalongInput> = VALUES.flatMap { pi -> listOf(pi.id to pi) + pi.deprecatedIDs.map { i -> i to pi } }.toMap() private val INDICES_MAP: Map<PlayalongInput, Int> = VALUES.associateWith(VALUES::indexOf) private val REVERSE_INDICES_MAP: Map<PlayalongInput, Int> = VALUES.associateWith { VALUES.size - 1 - VALUES.indexOf(it) } operator fun get(id: String): PlayalongInput? = ID_MAP[id] fun indexOf(playalongInput: PlayalongInput?): Int = if (playalongInput == null) -1 else INDICES_MAP.getOrDefault(playalongInput, -1) fun reverseIndexOf(playalongInput: PlayalongInput?): Int = if (playalongInput == null) -1 else REVERSE_INDICES_MAP.getOrDefault(playalongInput, -1) } } enum class PlayalongMethod(val instantaneous: Boolean, val isRelease: Boolean) { PRESS(true, false), PRESS_AND_HOLD(false, false), LONG_PRESS(false, false), RELEASE_AND_HOLD(false, true), RELEASE(true, true); // RELEASE is for Quick Tap companion object { val VALUES = values().toList() private val ID_MAP: Map<String, PlayalongMethod> = VALUES.associateBy { it.name } operator fun get(id: String): PlayalongMethod? = ID_MAP[id] } }
0
Kotlin
1
8
0594be395088e88386213bd4eb6a208798907938
1,989
RSDE
Apache License 2.0
library/src/main/java/info/hannes/cvscanner/util/CVProcessor.kt
hannesa2
232,034,729
false
null
package info.hannes.cvscanner.util import org.opencv.core.* import org.opencv.imgproc.Imgproc import timber.log.Timber import java.util.* import kotlin.math.* object CVProcessor { const val PASSPORT_ASPECT_RATIO = 3.465f / 4.921f private const val FIXED_HEIGHT = 800 fun buildMatFromYUV(nv21Data: ByteArray?, width: Int, height: Int): Mat { val yuv = Mat(height + height / 2, width, CvType.CV_8UC1) yuv.put(0, 0, nv21Data) val rgba = Mat() Imgproc.cvtColor(yuv, rgba, Imgproc.COLOR_YUV2RGBA_NV21, CvType.CV_8UC4) return rgba } fun detectBorder(original: Mat): Rect { val src = original.clone() Timber.d("1 original: $src") Imgproc.GaussianBlur(src, src, Size(3.0, 3.0), 0.0) Timber.d("2.1 --> Gaussian blur done\n blur: $src") Imgproc.cvtColor(src, src, Imgproc.COLOR_RGBA2GRAY) Timber.d("2.2 --> Grayscaling done\n gray: $src") val sobelX = Mat() val sobelY = Mat() Imgproc.Sobel(src, sobelX, CvType.CV_32FC1, 2, 0, 5, 1.0, 0.0) Timber.d("3.1 --> Sobel done.\n X: $sobelX") Imgproc.Sobel(src, sobelY, CvType.CV_32FC1, 0, 2, 5, 1.0, 0.0) Timber.d("3.2 --> Sobel done.\n Y: $sobelY") val sum_img = Mat() Core.addWeighted(sobelX, 0.5, sobelY, 0.5, 0.5, sum_img) //Core.add(sobelX, sobelY, sum_img); Timber.d("4 --> Addition done. sum: $sum_img") sobelX.release() sobelY.release() val gray = Mat() Core.normalize(sum_img, gray, 0.0, 255.0, Core.NORM_MINMAX, CvType.CV_8UC1) Timber.d("5 --> Normalization done. gray: $gray") sum_img.release() val row_proj = Mat() val col_proj = Mat() Core.reduce(gray, row_proj, 1, Core.REDUCE_AVG, CvType.CV_8UC1) Timber.d("6.1 --> Reduce done. row: $row_proj") Core.reduce(gray, col_proj, 0, Core.REDUCE_AVG, CvType.CV_8UC1) Timber.d("6.2 --> Reduce done. col: $col_proj") gray.release() Imgproc.Sobel(row_proj, row_proj, CvType.CV_8UC1, 0, 2) Timber.d("7.1 --> Sobel done. row: $row_proj") Imgproc.Sobel(col_proj, col_proj, CvType.CV_8UC1, 2, 0) Timber.d("7.2 --> Sobel done. col: $col_proj") val result = Rect() var half_pos = (row_proj.total() / 2).toInt() val row_sub = Mat(row_proj, Range(0, half_pos), Range(0, 1)) Timber.d("8.1 --> Copy sub matrix done. row: $row_sub") result.y = Core.minMaxLoc(row_sub).maxLoc.y.toInt() Timber.d("8.2 --> Minmax done. Y: ${result.y}") row_sub.release() val row_sub2 = Mat(row_proj, Range(half_pos, row_proj.total().toInt()), Range(0, 1)) Timber.d("8.3 --> Copy sub matrix done. row: $row_sub2") result.height = (Core.minMaxLoc(row_sub2).maxLoc.y + half_pos - result.y).toInt() Timber.d("8.4 --> Minmax done. Height: ${result.height}") row_sub2.release() half_pos = (col_proj.total() / 2).toInt() val col_sub = Mat(col_proj, Range(0, 1), Range(0, half_pos)) Timber.d("9.1 --> Copy sub matrix done. col: $col_sub") result.x = Core.minMaxLoc(col_sub).maxLoc.x.toInt() Timber.d("9.2 --> Minmax done. X: ${result.x}") col_sub.release() val col_sub2 = Mat(col_proj, Range(0, 1), Range(half_pos, col_proj.total().toInt())) Timber.d("9.3 --> Copy sub matrix done. col: $col_sub2") result.width = (Core.minMaxLoc(col_sub2).maxLoc.x + half_pos - result.x).toInt() Timber.d("9.4 --> Minmax done. Width: ${result.width}") col_sub2.release() row_proj.release() col_proj.release() src.release() return result } fun getScaleRatio(srcSize: Size): Double { return srcSize.height / FIXED_HEIGHT } fun findContours(src: Mat): List<MatOfPoint> { val img = src.clone() //find contours val ratio = getScaleRatio(img.size()) val width = (img.size().width / ratio).toInt() val height = (img.size().height / ratio).toInt() val newSize = Size(width.toDouble(), height.toDouble()) val resizedImg = Mat(newSize, CvType.CV_8UC4) Imgproc.resize(img, resizedImg, newSize) img.release() Imgproc.medianBlur(resizedImg, resizedImg, 7) val cannedImg = Mat(newSize, CvType.CV_8UC1) Imgproc.Canny(resizedImg, cannedImg, 70.0, 200.0, 3, true) resizedImg.release() Imgproc.threshold(cannedImg, cannedImg, 70.0, 255.0, Imgproc.THRESH_OTSU) val dilatedImg = Mat(newSize, CvType.CV_8UC1) val morph = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, Size(3.0, 3.0)) Imgproc.dilate(cannedImg, dilatedImg, morph, Point((-1).toDouble(), (-1).toDouble()), 2, 1, Scalar(1.0)) cannedImg.release() morph.release() val contours = ArrayList<MatOfPoint>() val hierarchy = Mat() Imgproc.findContours(dilatedImg, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE) hierarchy.release() dilatedImg.release() Timber.d("contours found: ${contours.size}") contours.sortWith(Comparator { o1, o2 -> java.lang.Double.compare(Imgproc.contourArea(o2), Imgproc.contourArea(o1)) }) return contours } fun findContoursForMRZ(src: Mat): List<MatOfPoint> { val img = src.clone() src.release() val ratio = getScaleRatio(img.size()) val width = (img.size().width / ratio).toInt() val height = (img.size().height / ratio).toInt() val newSize = Size(width.toDouble(), height.toDouble()) val resizedImg = Mat(newSize, CvType.CV_8UC4) Imgproc.resize(img, resizedImg, newSize) val gray = Mat() Imgproc.cvtColor(resizedImg, gray, Imgproc.COLOR_BGR2GRAY) Imgproc.medianBlur(gray, gray, 3) //Imgproc.blur(gray, gray, new Size(3, 3)); var morph = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, Size(13.0, 5.0)) val dilatedImg = Mat() Imgproc.morphologyEx(gray, dilatedImg, Imgproc.MORPH_BLACKHAT, morph) gray.release() val gradX = Mat() Imgproc.Sobel(dilatedImg, gradX, CvType.CV_32F, 1, 0) dilatedImg.release() Core.convertScaleAbs(gradX, gradX, 1.0, 0.0) val minMax = Core.minMaxLoc(gradX) Core.convertScaleAbs( gradX, gradX, 255 / (minMax.maxVal - minMax.minVal), -(minMax.minVal * 255 / (minMax.maxVal - minMax.minVal)) ) Imgproc.morphologyEx(gradX, gradX, Imgproc.MORPH_CLOSE, morph) val thresh = Mat() Imgproc.threshold(gradX, thresh, 0.0, 255.0, Imgproc.THRESH_OTSU) gradX.release() morph.release() morph = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, Size(21.0, 21.0)) Imgproc.morphologyEx(thresh, thresh, Imgproc.MORPH_CLOSE, morph) Imgproc.erode(thresh, thresh, Mat(), Point((-1).toDouble(), (-1).toDouble()), 4) morph.release() val col = resizedImg.size().width.toInt() val p = (resizedImg.size().width * 0.05).toInt() val row = resizedImg.size().height.toInt() for (i in 0 until row) { for (j in 0 until p) { thresh.put(i, j, 0.0) thresh.put(i, col - j, 0.0) } } val contours: List<MatOfPoint> = ArrayList() val hierarchy = Mat() Imgproc.findContours(thresh, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE) hierarchy.release() Timber.d("contours found: ${contours.size}") Collections.sort(contours) { o1, o2 -> java.lang.Double.valueOf(Imgproc.contourArea(o2)).compareTo(Imgproc.contourArea(o1)) } return contours } fun findContoursAfterClosing(src: Mat): List<MatOfPoint?> { val img = src.clone() //find contours val ratio = getScaleRatio(img.size()) val width = (img.size().width / ratio).toInt() val height = (img.size().height / ratio).toInt() val newSize = Size(width.toDouble(), height.toDouble()) val resizedImg = Mat(newSize, CvType.CV_8UC4) Imgproc.resize(img, resizedImg, newSize) img.release() Imgproc.medianBlur(resizedImg, resizedImg, 5) val cannedImg = Mat(newSize, CvType.CV_8UC1) Imgproc.Canny(resizedImg, cannedImg, 70.0, 200.0, 3, true) resizedImg.release() Imgproc.threshold(cannedImg, cannedImg, 70.0, 255.0, Imgproc.THRESH_OTSU) val dilatedImg = Mat(newSize, CvType.CV_8UC1) val morph = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, Size(3.0, 3.0)) Imgproc.dilate(cannedImg, dilatedImg, morph, Point((-1).toDouble(), (-1).toDouble()), 2, 1, Scalar(1.0)) cannedImg.release() morph.release() var contours = ArrayList<MatOfPoint?>() var hierarchy = Mat() Imgproc.findContours(dilatedImg, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE) hierarchy.release() Timber.d("contours found: ${contours.size}") contours.sortWith(Comparator { o1, o2 -> java.lang.Double.valueOf(Imgproc.contourArea(o2)).compareTo(Imgproc.contourArea(o1)) }) val box = Imgproc.boundingRect(contours[0]) Imgproc.line(dilatedImg, box.tl(), Point(box.br().x, box.tl().y), Scalar(255.0, 255.0, 255.0), 2) contours = ArrayList() hierarchy = Mat() Imgproc.findContours(dilatedImg, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE) hierarchy.release() dilatedImg.release() Timber.d("contours found: ${contours.size}") contours.sortWith(Comparator { o1, o2 -> java.lang.Double.valueOf(Imgproc.contourArea(o2)).compareTo(Imgproc.contourArea(o1)) }) return contours } fun getQuadForPassport(img: Mat, frameWidthIn: Double, frameHeightIn: Double): Quadrilateral? { var frameWidth = frameWidthIn var frameHeight = frameHeightIn val requiredCoverageRatio = 0.60 val ratio = getScaleRatio(img.size()) val width = img.size().width / ratio val height = img.size().height / ratio if (frameHeight == 0.0 || frameWidth == 0.0) { frameWidth = width frameHeight = height } else { frameWidth = frameWidth / ratio frameHeight = frameHeight / ratio } val newSize = Size(width, height) val resizedImg = Mat(newSize, CvType.CV_8UC4) Imgproc.resize(img, resizedImg, newSize) Imgproc.medianBlur(resizedImg, resizedImg, 13) val cannedImg = Mat(newSize, CvType.CV_8UC1) Imgproc.Canny(resizedImg, cannedImg, 70.0, 200.0, 3, true) resizedImg.release() val morphR = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_RECT, Size(5.0, 5.0)) Imgproc.morphologyEx(cannedImg, cannedImg, Imgproc.MORPH_CLOSE, morphR, Point((-1).toDouble(), (-1).toDouble()), 1) val lines = MatOfFloat4() Imgproc.HoughLinesP(cannedImg, lines, 1.0, Math.PI / 180, 30, 30.0, 150.0) if (lines.rows() >= 3) { val hLines = ArrayList<Line>() val vLines = ArrayList<Line>() for (i in 0 until lines.rows()) { val vec = lines[i, 0] val l = Line(vec[0], vec[1], vec[2], vec[3]) if (l.isNearHorizontal) hLines.add(l) else if (l.isNearVertical) vLines.add(l) } if (hLines.size >= 2 && vLines.size >= 2) { hLines.sortWith(Comparator { o1, o2 -> ceil(o1.start.y - o2.start.y).toInt() }) vLines.sortWith(Comparator { o1, o2 -> ceil(o1.start.x - o2.start.x).toInt() }) val nhLines = Line.joinSegments(hLines) val nvLines = Line.joinSegments(vLines) if (nvLines.size > 1 && nhLines.size > 0 || nvLines.size > 0 && nhLines.size > 1) { nhLines.sortedWith(Comparator { o1, o2 -> ceil(o2.length() - o1.length()).toInt() }) nvLines.sortedWith(Comparator { o1, o2 -> Math.ceil(o2.length() - o1.length()).toInt() }) var left: Line? = null var right: Line? = null var bottom: Line? = null var top: Line? = null for (l in nvLines) { if (l.length() / frameHeight < requiredCoverageRatio || left != null && right != null) break if (left == null && l.isInleft(width)) { left = l continue } if (right == null && !l.isInleft(width)) right = l } for (l in nhLines) { if (l.length() / frameWidth < requiredCoverageRatio || top != null && bottom != null) break if (bottom == null && l.isInBottom(height)) { bottom = l continue } if (top == null && !l.isInBottom(height)) top = l } var foundPoints: Array<Point>? = null if (left != null && right != null && (bottom != null || top != null)) { val vLeft = if (bottom != null) bottom.intersect(left) else top!!.intersect(left) val vRight = if (bottom != null) bottom.intersect(right) else top!!.intersect(right) Timber.d("got the edges") if (vLeft != null && vRight != null) { val pwidth = Line(vLeft, vRight).length() val pHeight = pwidth / PASSPORT_ASPECT_RATIO val tLeft = getPointOnLine(vLeft, left.end, pHeight) val tRight = getPointOnLine(vRight, right.end, pHeight) foundPoints = arrayOf(vLeft, vRight, tLeft, tRight) } } else if (top != null && bottom != null && (left != null || right != null)) { val vTop = if (left != null) left.intersect(top) else right!!.intersect(top) val vBottom = if (left != null) left.intersect(bottom) else right!!.intersect(bottom) Timber.d("got the edges") if (vTop != null && vBottom != null) { val pHeight = Line(vTop, vBottom).length() val pWidth = pHeight * PASSPORT_ASPECT_RATIO val tTop = getPointOnLine(vTop, top.end, pWidth) val tBottom = getPointOnLine(vBottom, bottom.end, pWidth) foundPoints = arrayOf(tTop, tBottom, vTop, vBottom) } } if (foundPoints != null) { val sPoints = sortPoints(foundPoints) if (isInside(sPoints, newSize) && isLargeEnough(sPoints, Size(frameWidth, frameHeight), requiredCoverageRatio)) { return Quadrilateral(null, sPoints) } else Timber.d("Not inside") } } } } return null } private fun getPointOnLine(origin: Point, another: Point, distance: Double): Point { val dFactor = distance / Line(origin, another).length() val X = (1 - dFactor) * origin.x + dFactor * another.x val Y = (1 - dFactor) * origin.y + dFactor * another.y return Point(X, Y) } fun getQuadrilateral(contours: List<MatOfPoint>, srcSize: Size): Quadrilateral? { val ratio = getScaleRatio(srcSize) val height = java.lang.Double.valueOf(srcSize.height / ratio).toInt() val width = java.lang.Double.valueOf(srcSize.width / ratio).toInt() val size = Size(width.toDouble(), height.toDouble()) for (c in contours) { val c2f = MatOfPoint2f(*c.toArray()) val peri = Imgproc.arcLength(c2f, true) val approx = MatOfPoint2f() Imgproc.approxPolyDP(c2f, approx, 0.02 * peri, true) val points = approx.toArray() // select biggest 4 angles polygon if (points.size == 4) { val foundPoints = sortPoints(points) val inside = isInside(foundPoints, size) val largeEnough = isLargeEnough(foundPoints, size, 0.25) if (inside && largeEnough) { Timber.i("SCANNER found square inside and largeEnough") return Quadrilateral(c, foundPoints) } else { //showToast(context, "Try getting closer to the ID"); Timber.v("SCANNER Not inside defined inside=$inside largeEnough=$largeEnough") } } else Timber.v("SCANNER approx size: ${points.size} do nothing, it's not squared") } //showToast(context, "Make sure the ID is on a contrasting background"); return null } fun getQuadForPassport(contours: List<MatOfPoint>, srcSize: Size, frameSize: Int): Quadrilateral? { val requiredAspectRatio = 5 val requiredCoverageRatio = 0.80f var rectContour: MatOfPoint? = null var foundPoints: Array<Point>? = null val ratio = getScaleRatio(srcSize) val width = java.lang.Double.valueOf(srcSize.width / ratio).toInt() val frameWidth = java.lang.Double.valueOf(frameSize / ratio).toInt() for (c in contours) { val bRect = Imgproc.boundingRect(c) val aspectRatio = bRect.width / bRect.height.toFloat() val coverageRatio = if (frameSize != 0) bRect.width / frameWidth.toFloat() else bRect.width / width.toFloat() Timber.d("AR: $aspectRatio, CR: $coverageRatio, frameWidth: $frameWidth") if (aspectRatio > requiredAspectRatio && coverageRatio > requiredCoverageRatio) { val c2f = MatOfPoint2f(*c.toArray()) val peri = Imgproc.arcLength(c2f, true) val approx = MatOfPoint2f() Imgproc.approxPolyDP(c2f, approx, 0.02 * peri, true) val points = approx.toArray() Timber.d("SCANNER approx size: ${points.size}") // select biggest 4 angles polygon if (points.size == 4) { rectContour = c foundPoints = sortPoints(points) break } else if (points.size == 2) { if (rectContour == null) { rectContour = c foundPoints = points } else { //try to merge val box1 = Imgproc.minAreaRect(MatOfPoint2f(*c.toArray())) val box2 = Imgproc.minAreaRect(MatOfPoint2f(*rectContour.toArray())) val ar = (box1.size.width / box2.size.width).toFloat() if (box1.size.width > 0 && box2.size.width > 0 && 0.5 < ar && ar < 2.0) { if (abs(box1.angle - box2.angle) <= 0.1 || abs(Math.PI - (box1.angle - box2.angle)) <= 0.1 ) { val minAngle = Math.min(box1.angle, box2.angle) val relX = box1.center.x - box2.center.x val rely = box1.center.y - box2.center.y val distance = Math.abs(rely * Math.cos(minAngle) - relX * Math.sin(minAngle)) if (distance < 1.5 * (box1.size.height + box2.size.height)) { val allPoints = Arrays.copyOf(foundPoints!!, 4) System.arraycopy(points, 0, allPoints, 2, 2) Timber.d("SCANNER after merge approx size: ${allPoints.size}") if (allPoints.size == 4) { foundPoints = sortPoints(allPoints) rectContour = MatOfPoint(*foundPoints) break } } } } rectContour = null foundPoints = null } } } } if (foundPoints != null && foundPoints.size == 4) { val lowerLeft = foundPoints[3] val lowerRight = foundPoints[2] val topLeft = foundPoints[0] var w = Math.sqrt((lowerRight.x - lowerLeft.x).pow(2.0) + (lowerRight.y - lowerLeft.y).pow(2.0)) var h = Math.sqrt((topLeft.x - lowerLeft.x).pow(2.0) + (topLeft.y - lowerLeft.y).pow(2.0)) var px = ((lowerLeft.x + w) * 0.03).toInt() var py = ((lowerLeft.y + h) * 0.03).toInt() lowerLeft.x = lowerLeft.x - px lowerLeft.y = lowerLeft.y + py px = ((lowerRight.x + w) * 0.03).toInt() py = ((lowerRight.y + h) * 0.03).toInt() lowerRight.x = lowerRight.x + px lowerRight.y = lowerRight.y + py val pRatio = 3.465f / 4.921f w = sqrt((lowerRight.x - lowerLeft.x).pow(2.0) + Math.pow(lowerRight.y - lowerLeft.y, 2.0)) h = pRatio * w h = h - h * 0.04 foundPoints[1] = Point(lowerRight.x, lowerRight.y - h) foundPoints[0] = Point(lowerLeft.x, lowerLeft.y - h) return Quadrilateral(rectContour, foundPoints) } return null } fun sortPoints(src: Array<Point>): Array<Point> { val srcPoints = ArrayList<Point>(listOf(*src)) val result: Array<Point> = src.clone() val sumComparator = Comparator<Point> { lhs, rhs -> (lhs.y + lhs.x).compareTo(rhs.y + rhs.x) } val diffComparator = Comparator<Point> { lhs, rhs -> (lhs.y - lhs.x).compareTo(rhs.y - rhs.x) } // top-left corner = minimal sum result[0] = Collections.min(srcPoints, sumComparator) // bottom-right corner = maximal sum result[2] = Collections.max(srcPoints, sumComparator) // top-right corner = minimal difference result[1] = Collections.min(srcPoints, diffComparator) // bottom-left corner = maximal difference result[3] = Collections.max(srcPoints, diffComparator) return result } fun isInsideBaseArea(rp: Array<Point>, size: Size): Boolean { val width = java.lang.Double.valueOf(size.width).toInt() val height = java.lang.Double.valueOf(size.height).toInt() val baseMeasure = height / 4 val bottomPos = height - baseMeasure val leftPos = width / 2 - baseMeasure val rightPos = width / 2 + baseMeasure return rp[0].x <= leftPos && rp[0].y <= baseMeasure && rp[1].x >= rightPos && rp[1].y <= baseMeasure && rp[2].x >= rightPos && rp[2].y >= bottomPos && rp[3].x <= leftPos && rp[3].y >= bottomPos } private fun isInside(points: Array<Point>, size: Size): Boolean { val width = java.lang.Double.valueOf(size.width).toInt() val height = java.lang.Double.valueOf(size.height).toInt() val isInside = points[0].x >= 0 && points[0].y >= 0 && points[1].x <= width && points[1].y >= 0 && points[2].x <= width && points[2].y <= height && points[3].x >= 0 && points[3].y <= height Timber.d("w: " + width + ", h: " + height + "Points: " + points[0] + ", " + points[1] + ", " + points[2] + ", " + points[3] + ", result: " + isInside) return isInside } private fun isLargeEnough(points: Array<Point>, size: Size, ratio: Double): Boolean { val contentWidth = Math.max(Line(points[0], points[1]).length(), Line(points[3], points[2]).length()) val contentHeight = Math.max(Line(points[0], points[3]).length(), Line(points[1], points[2]).length()) val widthRatio = contentWidth / size.width val heightRatio = contentHeight / size.height Timber.d("ratio: wr-" + widthRatio + ", hr-" + heightRatio + ", w: " + size.width + ", h: " + size.height + ", cw: " + contentWidth + ", ch: " + contentHeight) return widthRatio >= ratio && heightRatio >= ratio } fun getUpScaledPoints(points: Array<Point>, scaleFactor: Double): Array<Point> { val reScaledPoints = points.clone() for (i in 0..3) { val x = java.lang.Double.valueOf(points[i].x * scaleFactor).toInt() val y = java.lang.Double.valueOf(points[i].y * scaleFactor).toInt() reScaledPoints[i] = Point(x.toDouble(), y.toDouble()) } return reScaledPoints } /** * @param src - actual image * @param pts - points scaled up with respect to actual image */ fun fourPointTransform(src: Mat?, pts: Array<Point>): Mat { val tl = pts[0] val tr = pts[1] val br = pts[2] val bl = pts[3] val widthA = sqrt(Math.pow(br.x - bl.x, 2.0) + (br.y - bl.y).pow(2.0)) val widthB = sqrt(Math.pow(tr.x - tl.x, 2.0) + (tr.y - tl.y).pow(2.0)) val dw = Math.max(widthA, widthB) val maxWidth = java.lang.Double.valueOf(dw).toInt() val heightA = sqrt(Math.pow(tr.x - br.x, 2.0) + (tr.y - br.y).pow(2.0)) val heightB = sqrt(Math.pow(tl.x - bl.x, 2.0) + (tl.y - bl.y).pow(2.0)) val dh = max(heightA, heightB) val maxHeight = java.lang.Double.valueOf(dh).toInt() val doc = Mat(maxHeight, maxWidth, CvType.CV_8UC4) val srcMat = Mat(4, 1, CvType.CV_32FC2) val dstMat = Mat(4, 1, CvType.CV_32FC2) srcMat.put(0, 0, tl.x, tl.y, tr.x, tr.y, br.x, br.y, bl.x, bl.y) dstMat.put(0, 0, 0.0, 0.0, dw, 0.0, dw, dh, 0.0, dh) val m = Imgproc.getPerspectiveTransform(srcMat, dstMat) Imgproc.warpPerspective(src, doc, m, doc.size()) return doc } fun adjustBrightnessAndContrast(src: Mat, clipPercentageIn: Double): Mat { var clipPercentage = clipPercentageIn val histSize = 256 val alpha: Double val beta: Double var minGray: Double var maxGray: Double val gray: Mat if (src.type() == CvType.CV_8UC1) { gray = src.clone() } else { gray = Mat() Imgproc.cvtColor(src, gray, if (src.type() == CvType.CV_8UC3) Imgproc.COLOR_RGB2GRAY else Imgproc.COLOR_RGBA2GRAY) } if (clipPercentage == 0.0) { val minMaxGray = Core.minMaxLoc(gray) minGray = minMaxGray.minVal maxGray = minMaxGray.maxVal } else { val hist = Mat() val size = MatOfInt(histSize) val channels = MatOfInt(0) val ranges = MatOfFloat(0f, 256f) Imgproc.calcHist(listOf(gray), channels, Mat(), hist, size, ranges, false) gray.release() val accumulator = DoubleArray(histSize) accumulator[0] = hist[0, 0][0] for (i in 1 until histSize) { accumulator[i] = accumulator[i - 1] + hist[i, 0][0] } hist.release() val max = accumulator[accumulator.size - 1] clipPercentage = clipPercentage * (max / 100.0) clipPercentage = clipPercentage / 2.0f minGray = 0.0 while (minGray < histSize && accumulator[minGray.toInt()] < clipPercentage) { minGray++ } maxGray = histSize - 1.toDouble() while (maxGray >= 0 && accumulator[maxGray.toInt()] >= max - clipPercentage) { maxGray-- } } val inputRange = maxGray - minGray alpha = (histSize - 1) / inputRange beta = -minGray * alpha val result = Mat() src.convertTo(result, -1, alpha, beta) if (result.type() == CvType.CV_8UC4) { Core.mixChannels(Arrays.asList(src), Arrays.asList(result), MatOfInt(3, 3)) } return result } fun sharpenImage(src: Mat?): Mat { val sharped = Mat() Imgproc.GaussianBlur(src, sharped, Size(0.0, 0.0), 3.0) Core.addWeighted(src, 1.5, sharped, -0.5, 0.0, sharped) return sharped } class Quadrilateral internal constructor(var contour: MatOfPoint?, var points: Array<Point>) }
5
null
6
7
675a7973e3a4d30bf81bd62087d7bb13601a586c
28,688
CVScanner
Apache License 2.0
library/src/main/java/renetik/android/store/property/value/CSJsonListValueStoreProperty.kt
renetik
506,380,036
false
{"Kotlin": 79215}
package renetik.android.store.property.value import renetik.android.event.common.onDestructed import renetik.android.event.registration.CSRegistration import renetik.android.event.registration.cancelRegistrations import renetik.android.store.CSStore import renetik.android.store.type.CSJsonObjectStore import kotlin.reflect.KClass class CSJsonListValueStoreProperty<T : CSJsonObjectStore>( store: CSStore, key: String, val type: KClass<T>, onApply: ((value: List<T>) -> Unit)? = null ) : CSValueStoreProperty<List<T>>(store, key, onApply) { override val default: List<T> = emptyList() override fun get(store: CSStore): List<T> = store.getJsonObjectList(key, type) ?: this.default override fun set(store: CSStore, value: List<T>) = store.setJsonObjectList(key, value) private val valuesOnChanged = mutableListOf<CSRegistration>() .also { onDestructed(it::cancelRegistrations) } override fun onLoadedValueChanged(value: List<T>?) { valuesOnChanged.cancelRegistrations() value?.forEach { valuesOnChanged + it.eventChanged.onChange { set(store, value) } } } }
0
Kotlin
0
1
2fc804025649e4f507dd525256e66519fb6cd914
1,117
renetik-android-store
MIT License
src/main/kotlin/algorithmic_toolbox/week5/money_change_again/ChangeDP.kt
eniltonangelim
369,331,780
false
null
package algorithmic_toolbox.week5 import java.util.* fun getChange(m: Int): Int { val denominations = intArrayOf(1, 3, 4) var minNumberCoins = IntArray(m+1) Arrays.fill(minNumberCoins, 1, m + 1, Int.MAX_VALUE) for (i in 1..m) { for (j in denominations) { if (i >= j) minNumberCoins[i] = Math.min(minNumberCoins[i], minNumberCoins[i - j] + 1) } } return minNumberCoins[m] } fun main(args: Array<String>) { val scanner = Scanner(System.`in`) val m = scanner.nextInt() println(getChange(m)) }
0
Kotlin
0
0
031bccb323339bec05e8973af7832edc99426bc1
575
AlgorithmicToolbox
MIT License
sphinx/screens/dashboard/dashboard/src/main/java/chat/sphinx/dashboard/navigation/DashboardNavDrawerNavigator.kt
stakwork
340,103,148
false
{"Kotlin": 4002503, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453}
package chat.sphinx.dashboard.navigation import androidx.navigation.NavController import io.matthewnelson.concept_navigation.BaseNavigationDriver import io.matthewnelson.concept_navigation.Navigator abstract class DashboardNavDrawerNavigator( navigationDriver: BaseNavigationDriver<NavController> ): Navigator<NavController>(navigationDriver) { abstract suspend fun toAddSatsScreen() abstract suspend fun toAddressBookScreen() abstract suspend fun toProfileScreen() abstract suspend fun toAddFriendDetail() abstract suspend fun toCreateTribeDetail() abstract suspend fun toSupportTicketDetail() abstract suspend fun logout() }
96
Kotlin
8
18
4fd9556a4a34f14126681535558fe1e39747b323
661
sphinx-kotlin
MIT License
sample/kotlin-multiplatform/module/src/androidMain/kotlin/com/ktprovider/sample/module/App.kt
985892345
657,472,390
false
{"Kotlin": 32420}
package com.ktprovider.sample.module import android.app.Application import com.g985892345.provider.ktprovider.sample.kotlinmultiplatform.module.ModuleKtProviderInitializer /** * . * * @author 985892345 * 2024/1/14 15:04 */ class App : Application() { override fun onCreate() { super.onCreate() ModuleKtProviderInitializer.tryInitKtProvider() // init service } }
0
Kotlin
0
6
680769310bc6fa5545f86e327ad146bc86350668
380
KtProvider
Apache License 2.0
app/src/main/java/com/example/toncontest/ui/theme/components/main/transaction/send/SendCardHeader.kt
L0mTiCk
625,185,980
false
null
package com.example.toncontest.ui.theme.components.main.transaction.send import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.example.toncontest.data.main.MainStrings import com.example.toncontest.ui.theme.components.main.CardTitle @Composable fun SendCardHeader(navController: NavController) { Row( modifier = Modifier.height(56.dp).offset(x = (-20).dp), verticalAlignment = Alignment.CenterVertically ) { IconButton( onClick = { navController.popBackStack() }, modifier = Modifier .size(48.dp) ) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Back arrow" ) } CardTitle(text = MainStrings.sendScreenTitle) } }
0
Kotlin
0
0
2115bf7c3bc4558a40d2ab9181b295940848df7b
1,342
TONContest
MIT License
common_app/src/commonMain/kotlin/com/lt/common_app/ScrollableAppBarActivity.kt
ltttttttttttt
370,338,027
false
{"Kotlin": 459537, "HTML": 1287, "Swift": 480, "CSS": 210, "Ruby": 109}
/* * Copyright lt 2023 * * 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 com.lt.common_app import M import androidx.compose.foundation.* import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import com.lt.common_app.base.BaseComposeActivity import com.lt.compose_views.chain_scrollable_component.ChainScrollableComponent import com.lt.compose_views.chain_scrollable_component.ChainScrollableComponentState import com.lt.compose_views.chain_scrollable_component.mode.ChainMode import com.lt.compose_views.chain_scrollable_component.scrollable_appbar.ScrollableAppBar import com.lt.compose_views.other.FpsText import com.lt.compose_views.util.ComposePosition import com.lt.ltttttttttttt.common_app.generated.resources.Res import com.lt.ltttttttttttt.common_app.generated.resources.top_bar_bk import kotlinx.coroutines.launch import org.jetbrains.compose.resources.painterResource import kotlin.math.abs import kotlin.math.roundToInt // Author: <NAME> // Email: <EMAIL> // Date: 2022/9/5 22:24 // Description: // Documentation: class ScrollableAppBarActivity : BaseComposeActivity() { private var composePosition by mutableStateOf(ComposePosition.Top) private var chainMode by mutableStateOf(ChainMode.ChainContentFirst) private val maxDp = 200.dp private val minDp = 56.dp @Composable override fun ComposeContent() { Column(modifier = Modifier.fillMaxSize()) { AppBar() Menu() ChainScrollable() } } @Composable private fun Menu() { Row { Text(text = "方向:$composePosition") Button(onClick = { composePosition = when (chainMode) { ChainMode.ChainContentFirst, ChainMode.ChainAfterContent -> when (composePosition) { ComposePosition.Top -> ComposePosition.Bottom ComposePosition.Bottom -> ComposePosition.Start ComposePosition.Start -> ComposePosition.End ComposePosition.End -> ComposePosition.Top } ChainMode.ContentFirst -> when (composePosition) { ComposePosition.Top, ComposePosition.Bottom -> ComposePosition.Start ComposePosition.Start, ComposePosition.End -> ComposePosition.Top } } }) { Text(text = "切方向") } FpsText(modifier = Modifier) Text(text = "模式:$chainMode", M.width(80.dp)) Button(onClick = { chainMode = when (chainMode) { ChainMode.ChainContentFirst -> { composePosition = ComposePosition.Top ChainMode.ContentFirst } ChainMode.ContentFirst -> ChainMode.ChainAfterContent ChainMode.ChainAfterContent -> ChainMode.ChainContentFirst } }) { Text(text = "切模式") } } } @OptIn(ExperimentalFoundationApi::class) @Composable fun ColumnScope.ChainScrollable() { ChainScrollableComponent( minScrollPosition = minDp, maxScrollPosition = maxDp, chainContent = { state -> Box( modifier = Modifier .let { if (composePosition.isHorizontal()) it .fillMaxHeight() .width(maxDp) else it .fillMaxWidth() .height(maxDp) } .offset { when (composePosition) { ComposePosition.Start -> IntOffset( state .getScrollPositionValue() .roundToInt(), 0 ) ComposePosition.End -> IntOffset( state .getScrollPositionValue() .roundToInt(), 0 ) ComposePosition.Top -> IntOffset( 0, state .getScrollPositionValue() .roundToInt() ) ComposePosition.Bottom -> IntOffset( 0, state .getScrollPositionValue() .roundToInt() ) } } .background(Color.LightGray) ) { Text( text = "${state.getScrollPositionValue()} ${state.getScrollPositionPercentage()}", modifier = Modifier.align( when (composePosition) { ComposePosition.Start -> Alignment.CenterEnd ComposePosition.End -> Alignment.CenterStart ComposePosition.Top -> Alignment.BottomCenter ComposePosition.Bottom -> Alignment.TopCenter } ) ) } }, modifier = Modifier .fillMaxWidth() .weight(1f), chainMode = chainMode, composePosition = composePosition, ) { if (false) { LazyColumn( contentPadding = PaddingValues(top = maxDp), modifier = Modifier.fillMaxSize() ) { items(100) { Text("item $it") } } } else { if (composePosition.isHorizontal()) Row( Modifier .fillMaxSize() .horizontalScroll(rememberScrollState()) .padding( start = if (composePosition == ComposePosition.Start) maxDp else 0.dp, top = if (composePosition == ComposePosition.Top) maxDp else 0.dp, end = if (composePosition == ComposePosition.End) maxDp else 0.dp, bottom = if (composePosition == ComposePosition.Bottom) maxDp else 0.dp, ) ) { repeat(30) { Text("item $it") } } else Column( Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) .padding( start = if (composePosition == ComposePosition.Start) maxDp else 0.dp, top = if (composePosition == ComposePosition.Top) maxDp else 0.dp, end = if (composePosition == ComposePosition.End) maxDp else 0.dp, bottom = if (composePosition == ComposePosition.Bottom) maxDp else 0.dp, ) ) { repeat(100) { Text("item $it") } } } } } @OptIn(ExperimentalFoundationApi::class) @Composable fun ColumnScope.AppBar() { val lazyListState = rememberLazyListState() ScrollableAppBar( title = "toolbar", background = painterResource(Res.drawable.top_bar_bk), maxScrollPosition = maxDp, modifier = Modifier .weight(1f) .fillMaxWidth(), //onScrollStop = scrollStop(lazyListState) ) { LazyColumn( contentPadding = PaddingValues(top = maxDp), modifier = Modifier.fillMaxSize(), state = lazyListState, ) { items(30) { index -> Text( "I'm item $index", modifier = Modifier.padding(16.dp) ) } } } } //停止拖动时,使appbar归位 private fun scrollStop(lazyListState: LazyListState): (ChainScrollableComponentState, Float) -> Boolean = function@{ state, delta -> val percentage = state.getScrollPositionPercentage() if (percentage == 1f || percentage == 0f) return@function true state.coroutineScope.launch { val startPositionValue = abs((state.getScrollPositionValue() + delta) / (state.maxPx - state.minPx)) if (percentage > 0.5f) { state.setScrollPositionWithAnimate(state.minPx - state.maxPx) lazyListState.animateScrollBy(startPositionValue - state.minPx) } else { state.setScrollPositionWithAnimate(0f) lazyListState.animateScrollBy(startPositionValue) } } true } }
5
Kotlin
34
410
a28664c0f5c3700c2cdbfe9b2e0aa7b82f1e000d
11,072
ComposeViews
Apache License 2.0
src/test/resources/testdata/core/distance/godclass/TestTopLevel.kt
JetBrains-Research
245,192,395
false
{"INI": 3, "Gradle": 1, "Shell": 1, "Text": 2, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Kotlin": 43, "Java": 29, "SVG": 1, "XML": 1}
private val a = 1 private val b = 1 private val c = 1 private val d = 1 private val e = 1 fun fun1() { print(a) print(b) print(c) } fun fun2() { print(d) print(e) }
2
Kotlin
1
0
444bbe19ba451c62fa9f739d022c09144fd57ab7
187
kotlin-code-smells-detector
MIT License
platform/platform-impl/src/com/intellij/internal/statistic/JdkSettingsUsageCollector.kt
voidfunction
68,095,895
true
{"Java": 164997432, "Python": 25421481, "Kotlin": 4481293, "Groovy": 3223131, "HTML": 1896177, "JavaScript": 570364, "C": 211556, "CSS": 201445, "C++": 197528, "Lex": 147047, "XSLT": 113040, "Jupyter Notebook": 93222, "Shell": 65719, "Batchfile": 60580, "NSIS": 51270, "Roff": 37534, "Objective-C": 27941, "TeX": 25473, "AMPL": 20665, "Scala": 11698, "TypeScript": 9469, "Protocol Buffer": 6680, "J": 5050, "Makefile": 2352, "Thrift": 1846, "CoffeeScript": 1759, "CMake": 1675, "C#": 1264, "Ruby": 1217, "Perl": 903, "Smalltalk": 338, "AspectJ": 182, "Visual Basic": 77, "HLSL": 57, "Perl 6": 26, "Erlang": 10}
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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 com.intellij.internal.statistic import com.intellij.internal.statistic.beans.GroupDescriptor import com.intellij.internal.statistic.beans.UsageDescriptor import java.lang.management.ManagementFactory /** * @author <NAME> */ class JdkSettingsUsageCollector: UsagesCollector() { override fun getUsages(): Set<UsageDescriptor> { return ManagementFactory.getRuntimeMXBean().inputArguments .map { s -> UsageDescriptor(s) } .toSet() } override fun getGroupId(): GroupDescriptor { return GroupDescriptor.create("user.jdk.settings") } }
0
Java
0
1
959e2dd60954983690ca49335ca8b897ba6570dc
1,169
intellij-community
Apache License 2.0
nj2k/src/org/jetbrains/kotlin/nj2k/symbols/JKPackageSymbol.kt
lemnik
210,408,032
true
{"Kotlin": 40095288, "Java": 7591534, "JavaScript": 160572, "HTML": 75060, "Lex": 23159, "TypeScript": 21255, "IDL": 11582, "ANTLR": 9803, "CSS": 8084, "Shell": 7727, "Groovy": 6940, "Batchfile": 5362, "Swift": 2253, "Ruby": 668, "Objective-C": 293, "Scala": 80}
/* * Copyright 2010-2019 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.nj2k.symbols import com.intellij.psi.PsiPackage import org.jetbrains.kotlin.nj2k.JKSymbolProvider import org.jetbrains.kotlin.nj2k.types.JKTypeFactory sealed class JKPackageSymbol : JKSymbol { abstract override val target: PsiPackage } class JKMultiversePackageSymbol( override val target: PsiPackage, override val typeFactory: JKTypeFactory ) : JKPackageSymbol(), JKMultiverseSymbol<PsiPackage>
0
null
0
0
2bdbed978ba36c0d536210f7bdc8bf7b701ea133
650
kotlin
Apache License 2.0
tmp/arrays/youTrackTests/5543.kt
DaniilStepanov
228,623,440
false
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
// Original bug: KT-24786 enum class E { A, B, C } var x = E.A fun g(): E { x = E.B return E.C } fun main(args: Array<String>) { println(when (x) { g() -> x E.A -> x else -> "something else" }) }
1
null
12
1
602285ec60b01eee473dcb0b08ce497b1c254983
245
bbfgradle
Apache License 2.0
camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/config/ExternalCameraPipeComponent.kt
androidx
256,589,781
false
null
/* * Copyright 2021 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.camera.camera2.pipe.config import androidx.annotation.RequiresApi import dagger.Component import javax.inject.Singleton @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java @Singleton @Component(modules = [ThreadConfigModule::class]) internal interface ExternalCameraPipeComponent { fun cameraGraphBuilder(): ExternalCameraGraphComponent.Builder }
23
null
740
4,353
3492e5e1782b1524f2ab658f1728c89a35c7336d
1,029
androidx
Apache License 2.0
components/messaging-streaming/src/main/kotlin/com/vmware/tanzu/data/IoT/vehicles/messaging/streaming/creational/StreamSetup.kt
Tanzu-Solutions-Engineering
353,470,254
false
null
package com.vmware.tanzu.data.IoT.vehicles.messaging.streaming.creational /** * Interface to initialize streams * @author Gregory Green */ interface StreamSetup{ fun initialize(streamName: String); }
1
null
1
4
fb8392e3174a305f5ca83427a75856bb6392d791
210
IoT-connected-vehicles-showcase
Apache License 2.0
app/src/main/java/com/naufaldi_athallah_rifqi/todo_do/data/models/local/UserDao.kt
naufaldirfq
327,917,012
false
{"Gradle": 3, "Java Properties": 2, "Markdown": 3, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "JSON": 1, "Proguard": 1, "XML": 46, "Kotlin": 36, "Java": 8}
package com.naufaldi_athallah_rifqi.todo_do.data.models.local import androidx.lifecycle.LiveData import androidx.room.* @Dao interface UserDao { @Query("SELECT * FROM UserLocal") fun getAllUserList() : LiveData<List<UserLocal>> @Insert fun addUser(userLocal: UserLocal) @Update(onConflict = OnConflictStrategy.REPLACE) fun updateUser(userLocal: UserLocal) @Delete fun deleteUser(userLocal: UserLocal?) @Query("SELECT * FROM UserLocal WHERE id==:id") fun getUserWithId(id:Int):UserLocal }
1
null
1
1
8669a0b597a61db406a129474c55f8117d3d6196
533
todo-do-sourcecode
MIT License
app/src/androidTest/java/it/italiancoders/mybudget/action/ClickOnView.kt
fattazzo
129,799,746
true
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 135, "XML": 144, "Java": 1, "JSON": 4}
/* * Project: myBudget-mobile-android * File: ClickOnView.kt * * Created by fattazzo * Copyright © 2018 <NAME>. All rights reserved. * * MIT License * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package it.italiancoders.mybudget.action import android.support.test.espresso.UiController import android.support.test.espresso.ViewAction import android.support.test.espresso.action.ViewActions import android.view.View import org.hamcrest.Matcher class ClickOnView(private var textViewId: Int) : ViewAction { private var click = ViewActions.click() override fun getConstraints(): Matcher<View> { return click.constraints } override fun getDescription(): String { return " click on View with id: $textViewId" } override fun perform(uiController: UiController, view: View) { click.perform(uiController, view.findViewById(textViewId)) } }
0
Kotlin
0
0
67bed5db00ef3d8c255f571d66b1be27f9451652
1,929
myBudget-mobile-android
MIT License
compiler/fir/tree/src/org/jetbrains/kotlin/fir/declarations/FirAnonymousObject.kt
damenez
176,209,431
true
{"Kotlin": 34311187, "Java": 7464957, "JavaScript": 152998, "HTML": 73765, "Lex": 23159, "IDL": 10758, "ANTLR": 9803, "Shell": 7727, "Groovy": 6893, "Batchfile": 5362, "CSS": 4679, "Objective-C": 182, "Scala": 80}
/* * Copyright 2010-2019 JetBrains s.r.o. 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.fir.declarations import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.fir.VisitedSupertype import org.jetbrains.kotlin.fir.expressions.FirExpression import org.jetbrains.kotlin.fir.visitors.FirVisitor interface FirAnonymousObject : @VisitedSupertype FirClass, FirExpression { override val classKind: ClassKind get() = ClassKind.OBJECT override fun <R, D> accept(visitor: FirVisitor<R, D>, data: D): R = visitor.visitAnonymousObject(this, data) override fun <R, D> acceptChildren(visitor: FirVisitor<R, D>, data: D) { super<FirClass>.acceptChildren(visitor, data) super<FirExpression>.acceptChildren(visitor, data) } }
0
Kotlin
0
2
9a2178d96bd736c67ba914b0f595e42d1bba374d
887
kotlin
Apache License 2.0
src/main/kotlin/com/intershop/gradle/javacc/extension/JavaCCExtension.kt
peter-kehl
198,101,394
true
{"YAML": 1, "Gradle Kotlin DSL": 2, "Shell": 2, "Text": 1, "Batchfile": 1, "AsciiDoc": 1, "Ignore List": 1, "Groovy": 2, "Java": 62, "Ant Build System": 2, "Kotlin": 7, "Java Properties": 1}
/* * Copyright 2018 Intershop Communications AG. * * 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. */ @file:Suppress("UnstableApiUsage") package com.intershop.gradle.javacc.extension import org.gradle.api.Action import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.Project import org.gradle.api.provider.Property import org.gradle.api.provider.Provider @Suppress("UnstableApiUsage") open class JavaCCExtension (project: Project) { companion object { // names for the plugin const val JAVACC_EXTENSION_NAME = "javacc" const val JAVACC_GROUP_NAME = "JAVACC Code Generation" const val JAVACC_CONFIGURATION_NAME = "javacc" // default versions const val JAVACC_VERSION = "4.2" const val CODEGEN_OUTPUTPATH = "generated/javacc" } val configs: NamedDomainObjectContainer<JavaCC> = project.container(JavaCC::class.java, JavaCCFactory(project)) fun configs(configureAction: Action<in NamedDomainObjectContainer<JavaCC>>) { configureAction.execute(configs) } // javacc version configuration @Suppress("UnstableApiUsage") private val javaCCVersionProperty: Property<String> = project.objects.property(String::class.java) init { javaCCVersionProperty.set(JAVACC_VERSION) } // javaCCVersion parameter val javaCCVersionProvider: Provider<String> get() = javaCCVersionProperty var javaCCVersion: String get() = javaCCVersionProperty.get() set(value) = javaCCVersionProperty.set(value) }
0
Java
0
0
83feaf842ca65d961f02773d0cb9a107051da60f
2,057
javacc-gradle-plugin
Apache License 2.0
core/database/src/main/kotlin/cn/wj/android/cashbook/core/database/table/AssetTable.kt
WangJie0822
365,932,300
false
{"Kotlin": 1658612, "Java": 1405038, "Batchfile": 535}
/* * Copyright 2021 The Cashbook 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 * * https://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 cn.wj.android.cashbook.core.database.table import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey /** * 资产信息数据库表 * * @param id 资产主键,自增长 * @param booksId 所属账本主键 * @param name 资产名称 * @param balance 资产余额,信用卡为已使用额度 * @param totalAmount 总额度,信用卡使用 * @param billingDate 账单日,信用卡使用 * @param repaymentDate 还款日,信用卡使用 * @param type 资产大类 * @param classification 资产分类 * @param invisible 是否隐藏 * @param openBank 开户行 * @param cardNo 卡号 * @param remark 备注 * @param sort 排序 * @param modifyTime 修改时间 * * > [王杰](mailto:<EMAIL>) 创建于 2021/6/3 */ @Entity(tableName = TABLE_ASSET) data class AssetTable( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = TABLE_ASSET_ID) val id: Long?, @ColumnInfo(name = TABLE_ASSET_BOOKS_ID) val booksId: Long, @ColumnInfo(name = TABLE_ASSET_NAME) val name: String, @ColumnInfo(name = TABLE_ASSET_BALANCE) val balance: Double, @ColumnInfo(name = TABLE_ASSET_TOTAL_AMOUNT) val totalAmount: Double, @ColumnInfo(name = TABLE_ASSET_BILLING_DATE) val billingDate: String, @ColumnInfo(name = TABLE_ASSET_REPAYMENT_DATE) val repaymentDate: String, @ColumnInfo(name = TABLE_ASSET_TYPE) val type: Int, @ColumnInfo(name = TABLE_ASSET_CLASSIFICATION) val classification: Int, @ColumnInfo(name = TABLE_ASSET_INVISIBLE) val invisible: Int, @ColumnInfo(name = TABLE_ASSET_OPEN_BANK) val openBank: String, @ColumnInfo(name = TABLE_ASSET_CARD_NO) val cardNo: String, @ColumnInfo(name = TABLE_ASSET_REMARK) val remark: String, @ColumnInfo(name = TABLE_ASSET_SORT) val sort: Int, @ColumnInfo(name = TABLE_ASSET_MODIFY_TIME) val modifyTime: Long, )
7
Kotlin
11
71
6c39b443a1e1e46cf3c4533db3ab270df1f1b9e8
2,294
Cashbook
Apache License 2.0
feature-wallet-api/src/main/java/io/novafoundation/nova/feature_wallet_api/data/source/CoinPriceLocalDataSource.kt
novasamatech
415,834,480
false
{"Kotlin": 8137060, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.feature_wallet_api.data.source import io.novafoundation.nova.feature_currency_api.domain.model.Currency import io.novafoundation.nova.feature_wallet_api.domain.model.HistoricalCoinRate interface CoinPriceLocalDataSource { suspend fun getFloorCoinPriceAtTime(priceId: String, currency: Currency, timestamp: Long): HistoricalCoinRate? suspend fun hasCeilingCoinPriceAtTime(priceId: String, currency: Currency, timestamp: Long): Boolean suspend fun getCoinPriceRange(priceId: String, currency: Currency, fromTimestamp: Long, toTimestamp: Long): List<HistoricalCoinRate> suspend fun updateCoinPrice(priceId: String, currency: Currency, coinRate: List<HistoricalCoinRate>) }
13
Kotlin
6
9
66a5c0949aee03a5ebe870a1b0d5fa3ae929516f
723
nova-wallet-android
Apache License 2.0
src/main/kotlin/com/cpiassistant/nodes/CpiArtifact.kt
andrzejhalicki
842,165,993
false
{"Kotlin": 68771}
package com.cpiassistant.nodes import com.cpiassistant.services.CpiService import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager open class CpiArtifact(override val id: String, override val name: String, open val service: CpiService, override var isLoaded: Boolean = false ): BaseNode() { private val resources = mutableListOf<CpiResource>() open fun getResources(artifactId: String, callback: (List<CpiResource>) -> Unit) { this.service.getResources(artifactId) { r -> this.resources.addAll(r) callback(this.resources) } } open fun addResource(name: String, content: String, callback: (Boolean) -> Unit) { this.service.createResource(this.id, name,content) { res -> if(res) { Notifications.Bus.notify(Notification("Custom Notification Group", "Resource added", NotificationType.INFORMATION)) } else { Notifications.Bus.notify(Notification("Custom Notification Group", "Resource not added", NotificationType.ERROR)) } callback(res) } } open fun updateResource(name: String, content: String, callback: (Boolean) -> Unit) { this.service.updateResource(this.id, name,content) { success, message -> if(success) { Notifications.Bus.notify(Notification("Custom Notification Group", "Resource ${name} updated", NotificationType.INFORMATION)) } else { Notifications.Bus.notify(Notification("Custom Notification Group", "Resource ${name} not updated: $message", NotificationType.ERROR)) } callback(success) } } open fun deploy() { this.service.deployArtifact(this.id) { taskId -> val service = this.service ApplicationManager.getApplication().executeOnPooledThread(object: Runnable { override fun run() { var running = true while(running) { service.checkDeploymentStatus(taskId) { status, success -> if(success == true && status == "SUCCESS") { running = false Notifications.Bus.notify(Notification("Custom Notification Group", "Deployment of ${[email protected]} Succeeded", NotificationType.INFORMATION)) } else if(success == false) { running = false Notifications.Bus.notify(Notification("Custom Notification Group", "${<EMAIL>}: ${status}", NotificationType.ERROR)) } } Thread.sleep(3000) } } }) } } }
1
Kotlin
0
3
36a93fc109bca48a84260d2970769216b7d4b658
3,026
intellij-cpi-assistant
MIT License
app/src/main/java/com/betulnecanli/purplepage/adapter/GoalAdapter.kt
betulnecanli
522,035,167
false
{"Kotlin": 62419}
package com.betulnecanli.purplepage.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.betulnecanli.purplepage.data.model.Goals import com.betulnecanli.purplepage.databinding.GoalItemBinding class GoalAdapter( private val listener : OnItemClickListener ): RecyclerView.Adapter<GoalAdapter.GoalViewHolder>() { inner class GoalViewHolder(private val binding : GoalItemBinding): RecyclerView.ViewHolder(binding.root) { init { binding.apply { root.setOnClickListener { val position = adapterPosition if(position != RecyclerView.NO_POSITION){ val goal = differ.currentList[position] listener.OnItemClick(goal) } } gCheckButton.setOnClickListener { val position = adapterPosition if(position!= RecyclerView.NO_POSITION){ val goal = differ.currentList[position] listener.onCheckedBoxClick(goal,gCheckButton.isChecked) } } } } fun bind(g :Goals){ binding.apply { gTitle.text = g.goalTitle gCheckButton.isChecked = g.isCheckedG gTitle.paint.isStrikeThruText = g.isCheckedG } } } private val differCallback = object : DiffUtil.ItemCallback<Goals>(){ override fun areItemsTheSame(oldItem: Goals, newItem: Goals): Boolean { return oldItem.uidG == newItem.uidG } override fun areContentsTheSame(oldItem: Goals, newItem: Goals): Boolean { return oldItem == newItem } } private val differ = AsyncListDiffer(this, differCallback) var mGoals : List<Goals> get() = differ.currentList set(value){ differ.submitList(value) } interface OnItemClickListener{ fun OnItemClick(g : Goals) fun onCheckedBoxClick(g:Goals, isChecked: Boolean) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GoalViewHolder { return GoalViewHolder( GoalItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: GoalViewHolder, position: Int) { val goal = mGoals[position] holder.bind(goal) } override fun getItemCount(): Int = mGoals.size }
0
Kotlin
0
2
864b6385e6f79bf2f4e793a126d5a0ee3e74ad40
2,747
PurplePage
Apache License 2.0
app/src/main/java/com/skyyo/template/features/signIn/SignInViewModel.kt
Skyyo
325,519,535
false
{"Kotlin": 47273}
package com.skyyo.template.features.signIn import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.skyyo.template.R import com.skyyo.template.application.models.local.InputWrapper import com.skyyo.template.application.models.remote.SocialSignInRequest import com.skyyo.template.application.repositories.auth.AuthRepository import com.skyyo.template.application.repositories.auth.SocialSignInResult import com.skyyo.template.utils.InputValidator import com.skyyo.template.utils.eventDispatchers.NavigationDispatcher import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject const val EMAIL = "email" const val PASSWORD = "<PASSWORD>" const val IS_PASSWORD_VISIBLE = "isPasswordVisible" @HiltViewModel class SignInViewModel @Inject constructor( private val navigationDispatcher: NavigationDispatcher, private val handle: SavedStateHandle, private val authRepository: AuthRepository ) : ViewModel() { val email = handle.getStateFlow(EMAIL, InputWrapper()) val password = handle.getStateFlow(PASSWORD, InputWrapper()) val isPasswordVisible = handle.getStateFlow(IS_PASSWORD_VISIBLE, false) var stateRelatedVariable = false val areInputsValid = combine(email, password) { email, password -> email.errorId == null && email.value.isNotEmpty() && password.errorId == null && password.value.isNotEmpty() }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false) val events = Channel<SignInEvent>(Channel.UNLIMITED) fun onEmailEntered(input: String) { stateRelatedVariable = true val error = InputValidator.getEmailErrorIdOrNull(input) handle[EMAIL] = email.value.copy(value = input, errorId = error) } fun onPasswordEntered(input: String) { val error = InputValidator.getPasswordErrorIdOrNull(input) handle[PASSWORD] = password.value.copy(value = input, errorId = error) } fun onPasswordVisibilityClick() { handle[IS_PASSWORD_VISIBLE] = !isPasswordVisible.value } fun goHome() = navigationDispatcher.emit { it.navigate(R.id.goHome) } private fun authGoogle(googleToken: String) = viewModelScope.launch(Dispatchers.IO) { when (authRepository.authGoogle(SocialSignInRequest(idToken = googleToken))) { SocialSignInResult.SuccessFirstTime -> { } SocialSignInResult.Success -> { } // navigate somewhere etc SocialSignInResult.NetworkError -> { } // events.send(error) } } }
0
Kotlin
7
21
5840e6b1017d7925bcf8cd8adeb7a7fae13040d1
2,837
android-template
MIT License
definitions-ecs-ashley/src/test/kotlin/fledware/ecs/definitions/ashley/driver_ashley.kt
fledware
408,627,203
false
{"Kotlin": 545508}
@file:Suppress("UNCHECKED_CAST") package fledware.ecs.definitions.ashley import com.badlogic.ashley.core.Component import com.badlogic.ashley.core.Engine import com.badlogic.ashley.core.Entity import fledware.definitions.DefinitionsManager import fledware.definitions.reader.gatherJar import fledware.definitions.registry.DefaultDefinitionsBuilder import fledware.definitions.tests.testJarPath import fledware.ecs.definitions.instantiator.EntityInstantiator import fledware.ecs.definitions.instantiator.SceneInstantiator import fledware.ecs.definitions.test.ManagerDriver import kotlin.reflect.KClass fun createAshleyManager() = DefaultDefinitionsBuilder(listOf( ashleyComponentDefinitionLifecycle(), ashleyEntityDefinitionLifecycle(), ashleySceneDefinitionLifecycle(), ashleySystemDefinitionLifecycle(), ashleyWorldDefinitionLifecycle() )).also { it.gatherJar("ecs-loading".testJarPath) it.gatherJar("ecs-loading-ashley".testJarPath) }.build() fun createAshleyEngine() = createAshleyManager().also { manager -> Engine().withDefinitionsManager(manager) } fun createAshleyDriver() = AshleyManagerDriver(createAshleyEngine()) class AshleyManagerDriver(override val manager: DefinitionsManager) : ManagerDriver { val engine = manager.contexts[Engine::class] override val entities: List<Any> get() = engine.entities.toList() override val systems: List<Any> get() = engine.systems.toList() override fun entityInstantiator(type: String): EntityInstantiator<Any, Any> { return manager.entityInstantiator(type) as EntityInstantiator<Any, Any> } override fun entityComponent(entity: Any, type: KClass<out Any>): Any { return (entity as Entity).getComponent(type.java as Class<Component>)!! } override fun entityComponentOrNull(entity: Any, type: KClass<out Any>): Any? { return (entity as Entity).getComponent(type.java as Class<Component>) } override fun entityDefinitionType(entity: Any): String { return (entity as Entity).definitionType } override fun sceneInstantiator(type: String): SceneInstantiator<Any, Any, Any> { return manager.sceneInstantiator(type) as SceneInstantiator<Any, Any, Any> } override fun decorateWithScene(type: String) { manager.decorateWithScene(type) } override fun decorateWithWorld(type: String) { manager.decorateWithWorld(type) } override fun update(delta: Float) { engine.update(delta) } }
6
Kotlin
0
0
2422b5f3bce36d5e7ea5e0962e94f2f2bcd3997e
2,436
FledDefs
Apache License 2.0
window/window-demos/demo/src/main/java/androidx/window/demo/coresdk/WindowStateCallbackActivity.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2023 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.window.demo.coresdk import android.content.ComponentCallbacks import android.content.Context import android.content.res.Configuration import android.hardware.display.DisplayManager import android.hardware.display.DisplayManager.DisplayListener import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.Display.DEFAULT_DISPLAY import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.window.demo.R import androidx.window.demo.common.DemoTheme import androidx.window.layout.WindowInfoTracker import androidx.window.layout.WindowMetricsCalculator import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch /** Activity to show display configuration from different system callbacks. */ class WindowStateCallbackActivity : ComponentActivity() { private val viewModel: WindowStateViewModel by viewModels() /** * [DisplayManager]s from `Activity` and `Application` are updated from different resource * configurations, so we listen on them separately. */ private lateinit var applicationDisplayManager: DisplayManager private lateinit var activityDisplayManager: DisplayManager private lateinit var windowMetricsCalculator: WindowMetricsCalculator private lateinit var handler: Handler /** * Runnable to poll configuration every 500ms. To always provide an up-to-date configuration so * it can be used to verify the configurations from other callbacks. */ private val updateWindowStateIfChanged = object : Runnable { override fun run() { provideLatestWindowState() handler.postDelayed(this, 500) } } /** [DisplayListener] on `Application`. */ private val applicationDisplayListener = object : DisplayListener { override fun onDisplayAdded(displayId: Int) {} override fun onDisplayRemoved(displayId: Int) {} override fun onDisplayChanged(displayId: Int) { if (displayId != DEFAULT_DISPLAY) { return } onWindowStateCallbackInvoked(R.string.application_display_listener_title, displayId) } } /** [DisplayListener] on `Activity`. */ private val activityDisplayListener = object : DisplayListener { override fun onDisplayAdded(displayId: Int) {} override fun onDisplayRemoved(displayId: Int) {} override fun onDisplayChanged(displayId: Int) { if (displayId != DEFAULT_DISPLAY) { return } onWindowStateCallbackInvoked(R.string.activity_display_listener_title, displayId) } } /** [onConfigurationChanged] on `Application`. */ private val applicationComponentCallback = object : ComponentCallbacks { override fun onConfigurationChanged(configuration: Configuration) { onWindowStateCallbackInvoked( R.string.application_configuration_title, configuration ) } @Deprecated( "Since API level 34 this is never called. Apps targeting API level 34 " + "and above may provide an empty implementation." ) override fun onLowMemory() {} } override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) setContent { DemoTheme { WindowStateScreen() } } applicationDisplayManager = application.getSystemService(DisplayManager::class.java) activityDisplayManager = getSystemService(DisplayManager::class.java) windowMetricsCalculator = WindowMetricsCalculator.getOrCreate() handler = Handler(Looper.getMainLooper()) applicationDisplayManager.registerDisplayListener(applicationDisplayListener, handler) activityDisplayManager.registerDisplayListener(activityDisplayListener, handler) application.registerComponentCallbacks(applicationComponentCallback) // Collect windowInfo when STARTED and stop when STOPPED. lifecycleScope.launch(Dispatchers.Main) { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { WindowInfoTracker.getOrCreate(this@WindowStateCallbackActivity) .windowLayoutInfo(this@WindowStateCallbackActivity) .collect { info -> onWindowStateCallbackInvoked(R.string.display_feature_title, info) } } } } override fun onDestroy() { super.onDestroy() applicationDisplayManager.unregisterDisplayListener(applicationDisplayListener) activityDisplayManager.unregisterDisplayListener(activityDisplayListener) application.unregisterComponentCallbacks(applicationComponentCallback) } override fun onResume() { super.onResume() // Start polling the configuration every 500ms. updateWindowStateIfChanged.run() } override fun onPause() { super.onPause() handler.removeCallbacks(updateWindowStateIfChanged) } /** [onConfigurationChanged] on `Activity`. */ override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) onWindowStateCallbackInvoked(R.string.activity_configuration_title, newConfig) } /** Called when the corresponding system callback is invoked. */ private fun onWindowStateCallbackInvoked(resId: Int, details: Any?) { viewModel.onWindowStateCallback(queryWindowState(resId, details = "$details")) } private fun provideLatestWindowState() { viewModel.updateLatestWindowState( queryWindowState( R.string.latest_configuration_title, "poll configuration every 500ms", ) ) } private fun queryWindowState(resId: Int, details: String): WindowState { fun DisplayManager.defaultDisplayRotation() = getDisplay(DEFAULT_DISPLAY).rotation fun Context.displayBounds() = windowMetricsCalculator.computeMaximumWindowMetrics(this).bounds return WindowState( name = getString(resId), applicationDisplayRotation = applicationDisplayManager.defaultDisplayRotation(), activityDisplayRotation = activityDisplayManager.defaultDisplayRotation(), applicationDisplayBounds = applicationContext.displayBounds(), activityDisplayBounds = [email protected](), callbackDetails = details, ) } }
29
Kotlin
1011
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
7,608
androidx
Apache License 2.0
common/common-utils/src/main/java/com/duckduckgo/common/utils/CurrentTimeProvider.kt
duckduckgo
78,869,127
false
{"Kotlin": 12149229, "HTML": 63593, "Ruby": 14552, "C++": 10312, "JavaScript": 8619, "CMake": 1992, "C": 1076, "Shell": 784}
/* * Copyright (c) 2022 DuckDuckGo * * 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 com.duckduckgo.common.utils import android.os.SystemClock import com.duckduckgo.di.scopes.AppScope import com.squareup.anvil.annotations.ContributesBinding import javax.inject.Inject interface CurrentTimeProvider { fun getTimeInMillis(): Long } @ContributesBinding(AppScope::class) class RealCurrentTimeProvider @Inject constructor() : CurrentTimeProvider { override fun getTimeInMillis(): Long = SystemClock.elapsedRealtime() }
56
Kotlin
873
3,593
ed999f27210085e8b31bdbdd2d51d9e174551386
1,047
Android
Apache License 2.0
app/src/main/kotlin/com/nido/weatherlogger/data/source/local/room/utils/AppDatabase.kt
naveedahmad99
245,104,141
false
null
package com.nido.weatherlogger.data.source.local.room.utils import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.sqlite.db.SupportSQLiteDatabase import com.nido.weatherlogger.data.source.local.room.cities.CityDao import com.nido.weatherlogger.data.source.local.room.cities.CityEntity import com.nido.weatherlogger.data.source.local.room.city_forecast_data.CityForecastDataDao import com.nido.weatherlogger.data.source.local.room.forecast_data.ForecastDataDao import com.nido.weatherlogger.data.source.local.room.forecast_data.ForecastDataEntity import com.nido.weatherlogger.helpers.Constants import java.util.concurrent.Executors /** * This is the backend. The database. This used to be done by the OpenHelper. * The fact that this has very few comments emphasizes its coolness. */ @Database( entities = [CityEntity::class, ForecastDataEntity::class], version = 1, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun cityDao(): CityDao abstract fun cityForecastDataDao(): CityForecastDataDao abstract fun forecastDataDao(): ForecastDataDao /** * Define a companion object, this allows us to add functions on the SleepDatabase class. */ companion object { // DATABASE_INSTANCE will keep a reference to any database returned via getInstance. // // This will help us avoid repeatedly initializing the database, which is expensive. // // The value of a volatile variable will never be cached, and all writes and // reads will be done to and from the main memory. It means that changes made by one // thread to shared data are visible to other threads. @Volatile private var DATABASE_INSTANCE: AppDatabase? = null private val cities = listOf( CityEntity(Constants.LATVIA_CITY_ID, "LATVIA"), CityEntity(Constants.RIGA_CITY_ID, "RIGA"), CityEntity(Constants.DORBAY_CITY_ID, "DURBE"), CityEntity(Constants.SABILE_CITY_ID, "SABILE"), CityEntity(Constants.TALSI_CITY_ID, "TALSI") ) /** * Multiple threads can ask for the database at the same time, ensure we only initialize * it once by using synchronized. Only one thread may enter a synchronized block at a * time. * * @param context used to get access to the filesystem. */ fun getInstance(context: Context): AppDatabase = DATABASE_INSTANCE ?: synchronized(this) { DATABASE_INSTANCE ?: buildDatabase(context).also { DATABASE_INSTANCE = it } } /** * Helper function to get the database. * * If a database has already been retrieved, the previous database will be returned. * Otherwise, create a new database. * * This function is threadsafe, and callers should cache the result for multiple database * calls to avoid overhead. * * This is an example of a simple Singleton pattern that takes another Singleton as an * argument in Kotlin. * * To learn more about Singleton read the wikipedia article: * https://en.wikipedia.org/wiki/Singleton_pattern * * @param context used to get access to the filesystem. */ private fun buildDatabase(context: Context) = Room.databaseBuilder(context, AppDatabase::class.java, "weather_logger_db" ) // prepopulate the database after onCreate was called .addCallback(object : Callback() { override fun onCreate(db: SupportSQLiteDatabase) { super.onCreate(db) // insert the data on the IO Thread Executors.newSingleThreadExecutor().execute { getInstance(context).cityDao().saveData(cities) } } }) .build() } }
0
Kotlin
0
1
5b9e243a9549d147b994c71b1ef08bbf3f0cee5d
4,164
WeatherLogger
Apache License 2.0
src/main/kotlin/lv/gdg/kotlin/kata/Task3.kt
siga111
76,856,221
false
null
package lv.gdg.kotlin.kata /** * Two tortoises named A and B must run a race. A starts with an average speed of 720 feet per hour. * Young B knows she runs faster than A and furthermore has not finished her cabbage. * * When she starts, at last, she can see that A has a 70 feet lead but B speed is 850 feet per hour. * How long will it take B to catch A? * * More generally: given two speeds v1 (A speed, integer > 0) and v2 (B speed, integer > 0) * and a lead g (integer > 0) how long will it take B to catch A? * * The result will be an array [h, mn, s] where h, mn, s is the time needed in hours, minutes * and seconds (don't worry for fractions of second). If v1 >= v2 then return null. * * Examples: * * race(720, 850, 70) => [0, 32, 18] * race(80, 91, 37) => [3, 21, 49] */
0
Kotlin
0
0
3a853aab5f7b9e4d2f823737632adf93c93a00aa
798
gdg-riga-kotlin
Apache License 2.0
Compose-Ur-Pres/cup/src/commonMain/kotlin/net/kodein/cup/Slide.kt
KodeinKoders
786,962,808
false
{"Kotlin": 183157, "HTML": 1674}
package net.kodein.cup import androidx.compose.foundation.layout.ColumnScope import androidx.compose.runtime.Composable import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList import net.kodein.cup.utils.* public sealed interface SlideGroup { public val slideList: List<Slide> } public class Slides( content: List<SlideGroup>, private val user: ((Position) -> DataMap)? = null, private val specs: ((Position) -> SlideSpecs)? = null ): SlideGroup { public data class Position( val indexInGroup: Int, val lastGroupIndex: Int, ) public constructor( vararg content: SlideGroup, user: ((Position) -> DataMap)? = null, specs: ((Position) -> SlideSpecs)? = null ) : this(content.toList(), user, specs) override val slideList: ImmutableList<Slide> = run { val slides = content.flatMap { it.slideList } if (specs == null && user == null) slides.toImmutableList() else slides.mapIndexed { index, slide -> val position = Position(index, slides.lastIndex) val mergedSpecs = when { slide.specs != null && specs != null -> slide.specs.merge(specs.invoke(position)) slide.specs == null && specs != null -> specs.invoke(position) else -> slide.specs } val mergedUser = when { user != null -> slide.user + user.invoke(position) else -> slide.user } slide.copy(specs = mergedSpecs, user = mergedUser) }.toImmutableList() } } public val Slides.Position.isFirst: Boolean get() = indexInGroup == 0 public val Slides.Position.isLast: Boolean get() = indexInGroup == lastGroupIndex public typealias SlideContent = @Composable ColumnScope.(Int) -> Unit @ExposedCopyVisibility public data class Slide internal constructor( public val name: String, public val stepCount: Int = 1, public val specs: SlideSpecs? = null, public val user: DataMap = emptyDataMap(), public val contentBuilder: @Composable () -> SlideContent ) : SlideGroup { public val lastStep: Int get() = stepCount - 1 override val slideList: List<Slide> get() = listOf(this) } public fun Slide( stepCount: Int = 1, specs: SlideSpecs? = null, user: DataMap = emptyDataMap(), content: SlideContent ): EagerProperty<Slide> = eagerProperty { property -> Slide( name = property.name, stepCount = stepCount, specs = specs, user = user, contentBuilder = { content } ) } public fun Slide( name: String, stepCount: Int = 1, specs: SlideSpecs? = null, user: DataMap = emptyDataMap(), content: SlideContent ): Slide = Slide( name = name, stepCount = stepCount, specs = specs, user = user, contentBuilder = { content } ) public object PreparedSlideScope { public fun slideContent(content: SlideContent): SlideContent = content } @Suppress("FunctionName") public fun PreparedSlide( stepCount: Int = 1, specs: SlideSpecs? = null, user: DataMap = emptyDataMap(), prepare: @Composable PreparedSlideScope.() -> SlideContent ) : EagerProperty<Slide> = eagerProperty { property -> Slide( name = property.name, stepCount = stepCount, specs = specs, user = user, contentBuilder = { PreparedSlideScope.prepare() } ) }
1
Kotlin
1
124
751468499eb1d1c4fe5c3791801648760f637ad7
3,561
CuP
Apache License 2.0
app/src/main/java/marian/vasilca/videoplayer/utilities/Extensions.kt
MarianVasilca
144,833,118
false
null
package marian.vasilca.videoplayer.utilities import android.content.Context import android.content.pm.PackageManager import android.net.Uri import android.support.v4.content.ContextCompat fun String.hasPermission(context: Context): Boolean = ContextCompat.checkSelfPermission(context, this) == PackageManager.PERMISSION_GRANTED fun String.toUri(): Uri = Uri.parse(this)
0
Kotlin
0
0
a6f07046c67948d8aa139d952861667da57adc07
381
android-video-player
Apache License 2.0
app/src/main/java/com/lxy/responsivelayout/nav/RLNavGraph.kt
luckylxyang
785,319,118
false
{"Kotlin": 73334, "Java": 4903}
package com.lxy.responsivelayout.nav import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navDeepLink import com.lxy.responsivelayout.entity.Article import com.lxy.responsivelayout.main.ArticleDetail import com.lxy.responsivelayout.main.ArticleList const val POST_ID = "postId" @Composable fun RLNavGraph( isExpandedScreen: Boolean, modifier: Modifier = Modifier, navController: NavHostController = rememberNavController(), openDrawer: () -> Unit = {}, startDestination: String = RLDestinations.HOME_ROUTE, ) { NavHost( navController = navController, startDestination = startDestination, modifier = modifier ) { composable( route = RLDestinations.HOME_ROUTE, // deepLinks = listOf( // navDeepLink { // uriPattern = // "$JETNEWS_APP_URI/${RLDestinations.HOME_ROUTE}?$POST_ID={$POST_ID}" // } // ) ) { navBackStackEntry -> val list = arrayListOf<Article>( Article("我是一个标题", "https://developer.android.google.cn/guide/topics/large-screens/support-different-screen-sizes?hl=zh-cn", "test"), Article("我是二个标题", "https://developer.android.google.cn/develop/ui/compose/layouts/adaptive?hl=zh-cn", "test2"), ) // ArticleList(messages = list, navController = navController) } composable(RLDestinations.INTERESTS_ROUTE) { // it.arguments?.getString("url")?.let { it1 -> ArticleDetail(url = it1) } } } }
0
Kotlin
0
1
6ef437bf505c13bb56ceee01ce938e283b8b9c22
1,876
ResponsiveLayoutDemo
Apache License 2.0
map/src/main/kotlin/de/darkatra/bfme2/map/reader/AssetEntry.kt
DarkAtra
325,887,805
false
null
package de.darkatra.bfme2.map.reader data class AssetEntry( val assetType: String, val endPosition: Long )
1
Kotlin
0
1
4110f2f02777ce1dba31c14ef2c4befbbe1fdec1
110
bfme2-modding-utils
MIT License
map/src/main/kotlin/de/darkatra/bfme2/map/reader/AssetEntry.kt
DarkAtra
325,887,805
false
null
package de.darkatra.bfme2.map.reader data class AssetEntry( val assetType: String, val endPosition: Long )
1
Kotlin
0
1
4110f2f02777ce1dba31c14ef2c4befbbe1fdec1
110
bfme2-modding-utils
MIT License
kava/src/main/kotlin/dev/reifiedbeans/kava/Kava.kt
reifiedbeans
867,995,401
false
{"Kotlin": 8220}
package dev.reifiedbeans.kava /** * Creates a new Kava module using the Kava DSL. */ fun kava(init: KavaDsl.() -> Unit): KavaModule { val dsl = KavaDsl().apply(init) return KavaModule(dsl.bindings, dsl.modules) }
0
Kotlin
0
0
fc386e782dff8a8cedd17d34f2629dd0b5eddf72
224
kava
MIT License
modules/dagger/arrow-dagger/src/main/kotlin/arrow/dagger/instances/optiont.kt
mikezx6r
160,887,969
true
{"Kotlin": 1968065, "CSS": 187632, "JavaScript": 66836, "HTML": 11798, "Java": 4465, "Shell": 3043}
package arrow.dagger.instances import arrow.data.OptionTPartialOf import arrow.instances.* import arrow.typeclasses.* import dagger.Module import dagger.Provides import javax.inject.Inject @Module abstract class OptionTInstances<F> { @Provides fun optionTFunctor(ev: DaggerOptionTFunctorInstance<F>): Functor<OptionTPartialOf<F>> = ev @Provides fun optionTApplicative(ev: DaggerOptionTApplicativeInstance<F>): Applicative<OptionTPartialOf<F>> = ev @Provides fun optionTMonad(ev: DaggerOptionTMonadInstance<F>): Monad<OptionTPartialOf<F>> = ev @Provides fun optionTFoldable(ev: DaggerOptionTFoldableInstance<F>): Foldable<OptionTPartialOf<F>> = ev @Provides fun optionTTraverse(ev: DaggerOptionTTraverseInstance<F>): Traverse<OptionTPartialOf<F>> = ev @Provides fun optionTSemigroupK(ev: DaggerOptionTSemigroupKInstance<F>): SemigroupK<OptionTPartialOf<F>> = ev @Provides fun optionTMonoidK(ev: DaggerOptionTMonoidKInstance<F>): MonoidK<OptionTPartialOf<F>> = ev } class DaggerOptionTFunctorInstance<F> @Inject constructor(val FF: Functor<F>) : OptionTFunctorInstance<F> { override fun FF(): Functor<F> = FF } class DaggerOptionTApplicativeInstance<F> @Inject constructor(val AF: Applicative<F>) : OptionTApplicativeInstance<F> { override fun FF(): Functor<F> = AF override fun AF(): Applicative<F> = AF } class DaggerOptionTMonadInstance<F> @Inject constructor(val FF: Monad<F>) : OptionTMonadInstance<F> { override fun FF(): Monad<F> = FF override fun MF(): Monad<F> = FF } class DaggerOptionTFoldableInstance<F> @Inject constructor(val FFF: Foldable<F>) : OptionTFoldableInstance<F> { override fun FFF(): Foldable<F> = FFF } class DaggerOptionTTraverseInstance<F> @Inject constructor(val FFF: Traverse<F>) : OptionTTraverseInstance<F> { override fun FFF(): Traverse<F> = FFF override fun FFT(): Traverse<F> = FFF } class DaggerOptionTSemigroupKInstance<F> @Inject constructor(val FF: Monad<F>) : OptionTSemigroupKInstance<F> { override fun MF(): Monad<F> = FF } class DaggerOptionTMonoidKInstance<F> @Inject constructor(val FF: Monad<F>) : OptionTMonoidKInstance<F> { override fun MF(): Monad<F> = FF }
0
Kotlin
0
0
fb5b911523405a0f60e067dce34af309d1459abb
2,169
kategory
Apache License 2.0
src/main/kotlin/asmble/run/jvm/emscripten/Tty.kt
tbutter
89,142,117
true
{"Kotlin": 369347, "Java": 2305, "C": 182}
package asmble.run.jvm.emscripten sealed class Tty { class OutputStream(val os: java.io.OutputStream) : Tty() { } }
0
Kotlin
0
0
b367c59ba343e9ca2912703789c802e45c2b10d0
125
asmble
MIT License
documents_feature/src/main/java/com/flyview/documents_feature/ui/scan/mark_list/navbar/MarkListTab.kt
DmiMukh
676,402,705
false
{"Kotlin": 296304, "Java": 130379}
package com.flyview.documents_feature.ui.scan.mark_list.navbar enum class MarkListTab { PACK, BOX }
0
Kotlin
0
0
f2dcebe8643c068c7fd57bfddd85fd1f6d6fd8f9
108
PharmMobile
MIT License
shared/src/commonMain/kotlin/com/data/DatabaseDriverFactory.kt
dthomson117
817,026,731
false
{"Kotlin": 78887, "Swift": 342}
package com.data import app.cash.sqldelight.db.SqlDriver import com.workout.AppDatabase import com.workout.db.Day import com.workout.db.Split @Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING") expect class DatabaseDriverFactory { fun createDriver(): SqlDriver } fun createDatabase(databaseDriverFactory: DatabaseDriverFactory): AppDatabase { val driver = databaseDriverFactory.createDriver() val database = AppDatabase( driver = driver, DayAdapter = Day.Adapter(dateAdapter = localDateAdapter), SplitAdapter = Split.Adapter(colourAdapter = colorAdapter), ) // Do more work with the database (see below). return database }
1
Kotlin
0
0
615a329d4e8ded6150cb15a033925398ec2cb597
706
Workout
MIT License
keanu-project/src/test/java/io/improbable/keanu/research/test.kt
nickmalleson
138,507,611
false
{"HTML": 2259116, "Java": 1038320, "Kotlin": 24591, "R": 6683, "Python": 2901, "Makefile": 2795, "Shell": 349}
package io.improbable.keanu.research import io.improbable.keanu.vertices.dbl.probabilistic.GaussianVertex fun main(args : Array<String>) { // Gauss randDoubleSource = new GaussianVertex({10}, 0.0, 1.0) // println(randDoubleSource.shape[0]) }
0
HTML
0
2
a58debded6707ea17a24afb8a269de6603cd2c05
249
keanu-post-hackathon
MIT License
src/main/kotlin/eu/luminis/workshops/kdd/inventory/domain/writemodel/legostore/commands/StoreCommand.kt
nkrijnen
500,971,652
false
{"Kotlin": 69360}
package eu.luminis.workshops.kdd.inventory.domain.writemodel.legostore.commands sealed interface StoreCommand
0
Kotlin
0
7
05b896ac01651f05eacbf7880743321a97cc8d79
110
event-sourcing-in-code
MIT License
template/app/src/mobileAndDesktopMain/kotlin/kotli/app/di/platform/createRoomDatabaseBuilder.kt
kotlitecture
790,159,970
false
{"Kotlin": 482571, "Swift": 543, "JavaScript": 313, "HTML": 234}
package kotli.app.di.platform import androidx.room.RoomDatabase import androidx.room.RoomDatabaseConstructor import kotli.app.common.data.source.database.room.AppDatabase expect fun createRoomDatabaseBuilder(name: String): RoomDatabase.Builder<AppDatabase> expect object AppDatabaseConstructor : RoomDatabaseConstructor<AppDatabase>
0
Kotlin
3
55
b96c8867f393bedba65b2f6f8a40e806bf07bcd9
335
template-multiplatform-compose
MIT License
app/src/main/java/com/samuelokello/kazihub/landing/LandingScreenViewModel.kt
OkelloSam21
749,782,789
false
{"Kotlin": 278163}
package com.samuelokello.kazihub.landing import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.samuelokello.kazihub.domain.repositpry.AuthRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject data class LandingScreenState (val destination: Destination? = null) { enum class Destination{ SIGN_IN, ON_BOARDING, CREATE_PROFILE, SIGN_UP, USER_TYPE, HOME } } class LandingScreenViewModel @Inject constructor(val repository: AuthRepository): ViewModel() { private val _state = MutableStateFlow(LandingScreenState()) val state = _state.asStateFlow() init { checkNavigationDestination() } private fun checkNavigationDestination() { viewModelScope.launch { // val userHasOnBoarded = repository.userHasOnBoarded.first() // if (userHasOnBoarded.not()) { // _state.update { it.copy(destination = LandingScreenState.Destination.USER_TYPE) } // } // // val hasSignedIn = repository.userHasSignedIn.first() // if (hasSignedIn.not()) { // _state.update { it.copy(destination = LandingScreenState.Destination.SIGN_IN) } // return@launch // } // // val hasSignedUp = repository.userHasSignedUp.first() // if (hasSignedUp.not()) { // _state.update { it.copy(destination = LandingScreenState.Destination.SIGN_UP) } // return@launch // } _state.update { it.copy(destination = LandingScreenState.Destination.HOME) } } } }
0
Kotlin
0
0
510745d20b259d7930fa58481181080fd70a4a9f
1,798
KaziHub
MIT License
src/offer/ShellSort.kt
andrewloski
154,839,594
true
{"Kotlin": 79493, "Java": 31720}
package offer /* * 希尔排序Kotlin实现 */ fun main(args: Array<String>) { val array = intArrayOf(5, 7, 2, 9, 3, 1, 4, 0, 8, 6) array.shellSort() array.forEach { print("$it ") } } fun IntArray.shellSort() { var h = 1 val boundary = size / 3 while (h < boundary) h = 3 * h + 1 while (h >= 1) { for (i in h until size) { var j = i while (j >= h && this[j] < this[j-h]) { exchange(j, j-h) j -= h } } h /= 3 } }
0
Kotlin
0
0
878265e3fcc76c66b55f3f39bba11dee540b3691
435
Algorithm
Apache License 2.0
logger/android-logger/src/androidMain/kotlin/io/kached/logger/AndroidLogger.kt
faogustavo
304,986,591
false
null
package io.kached.logger import android.util.Log import io.kached.LogLevel import io.kached.Logger private const val DEFAULT_TAG = "KACHED" class AndroidLogger constructor( private val tag: String = DEFAULT_TAG, ) : Logger { override suspend fun log(message: String, level: LogLevel) { when (level) { LogLevel.Error -> Log.e(tag, message) LogLevel.Warning -> Log.w(tag, message) LogLevel.Info -> Log.i(tag, message) } } override suspend fun log(error: Throwable, level: LogLevel) { val errorMessage = error.message ?: error.cause?.message ?: return when (level) { LogLevel.Error -> Log.e(tag, errorMessage, error) LogLevel.Warning -> Log.w(tag, errorMessage, error) LogLevel.Info -> Log.i(tag, errorMessage, error) } } }
9
Kotlin
1
5
f5124a6e295e9328669cb2d8a744321fac57b5c2
883
kached
Apache License 2.0
src/main/kotlin/ac/github/oa/internal/core/attribute/equip/BreastPlate.kt
ShirosakiMio
707,539,187
false
{"Kotlin": 284577, "Java": 6919, "JavaScript": 1159}
package ac.github.oa.internal.core.attribute.equip import org.bukkit.entity.LivingEntity import org.bukkit.inventory.ItemStack import taboolib.type.BukkitEquipment class BreastPlate(itemStack: ItemStack?) : Slot(itemStack) { override val id: String get() = BukkitEquipment.CHEST.name override fun getItem(entity: LivingEntity): ItemStack? { return BukkitEquipment.CHEST.getItem(entity) } }
0
Kotlin
0
0
2ed0dddc083b4a844efcff4fb1cd236a06c0482d
424
OriginAttribute
Creative Commons Zero v1.0 Universal
Bi-tu/app/src/main/java/com/kotuz/mesajbulutu/HesapAyarlariİki.kt
EmreKotuz
360,215,125
false
null
package com.kotuz.mesajbulutu import android.os.Bundle import android.app.Fragment import android.content.Intent import android.support.v4.app.DialogFragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.UserProfileChangeRequest import kotlinx.android.synthetic.main.activity_hesap_ayarlari.* import kotlinx.android.synthetic.main.fragment_hesap_ayarlari_iki.* class HesapAyarlariİki : DialogFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) var kullanicii = FirebaseAuth.getInstance().currentUser!! }}
0
Kotlin
1
1
9f5b803c2c5e7e9e01b521a42ebded425cce433b
733
Bi-Tu
Apache License 2.0
gravifon/src/test/kotlin/org/gravidence/gravifon/playback/backend/gstreamer/TrackQueueTest.kt
gravidence
448,136,601
false
{"Kotlin": 469102}
package org.gravidence.gravifon.playback.backend.gstreamer import org.gravidence.gravifon.TestUtil import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.nullValue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test internal class TrackQueueTest { private lateinit var trackQueue: TrackQueue @BeforeEach internal fun setUp() { trackQueue = TrackQueue() } @Test fun `One Track - Peek`() { val track1 = TestUtil.randomFileVirtualTrack() trackQueue.pushNext(track1) assertThat(trackQueue.peekActive(), nullValue()) assertThat(trackQueue.peekNext(), equalTo(track1)) } @Test fun `One Track - Poll Active from Inactive Queue`() { val track1 = TestUtil.randomFileVirtualTrack() trackQueue.pushNext(track1) assertThat(trackQueue.pollActive(), equalTo(Pair(null, track1))) assertThat(trackQueue.peekActive(), equalTo(track1)) assertThat(trackQueue.peekNext(), nullValue()) } @Test fun `One Track - Poll Active from Activated Queue`() { val track1 = TestUtil.randomFileVirtualTrack() trackQueue.pushNext(track1) trackQueue.pollActive() assertThat(trackQueue.pollActive(), equalTo(Pair(track1, null))) assertThat(trackQueue.peekActive(), nullValue()) assertThat(trackQueue.peekNext(), nullValue()) } @Test fun `One Track - Poll Next from Inactive Queue`() { val track1 = TestUtil.randomFileVirtualTrack() trackQueue.pushNext(track1) assertThat(trackQueue.pollNext(), equalTo(track1)) assertThat(trackQueue.peekActive(), nullValue()) assertThat(trackQueue.peekNext(), nullValue()) } @Test fun `One Track - Poll Next from Activated Queue`() { val track1 = TestUtil.randomFileVirtualTrack() trackQueue.pushNext(track1) trackQueue.pollActive() assertThat(trackQueue.pollNext(), nullValue()) assertThat(trackQueue.peekActive(), equalTo(track1)) assertThat(trackQueue.peekNext(), nullValue()) } @Test fun `Two Tracks - Peek`() { val track1 = TestUtil.randomFileVirtualTrack() val track2 = TestUtil.randomFileVirtualTrack() trackQueue.pushNext(track1) trackQueue.pushNext(track2) trackQueue.pollActive() assertThat(trackQueue.peekActive(), equalTo(track1)) assertThat(trackQueue.peekNext(), equalTo(track2)) } @Test fun `Two Tracks - Poll Active`() { val track1 = TestUtil.randomFileVirtualTrack() val track2 = TestUtil.randomFileVirtualTrack() trackQueue.pushNext(track1) trackQueue.pushNext(track2) trackQueue.pollActive() assertThat(trackQueue.pollActive(), equalTo(Pair(track1, track2))) assertThat(trackQueue.peekActive(), equalTo(track2)) assertThat(trackQueue.peekNext(), nullValue()) } @Test fun `Two Tracks - Poll Next`() { val track1 = TestUtil.randomFileVirtualTrack() val track2 = TestUtil.randomFileVirtualTrack() trackQueue.pushNext(track1) trackQueue.pushNext(track2) trackQueue.pollActive() assertThat(trackQueue.pollNext(), equalTo(track2)) assertThat(trackQueue.peekActive(), equalTo(track1)) assertThat(trackQueue.peekNext(), nullValue()) } @Test fun `Three Tracks - Peek`() { val track1 = TestUtil.randomFileVirtualTrack() val track2 = TestUtil.randomFileVirtualTrack() val track3 = TestUtil.randomFileVirtualTrack() trackQueue.pushNext(track1) trackQueue.pushNext(track2) trackQueue.pushNext(track3) trackQueue.pollActive() assertThat(trackQueue.peekActive(), equalTo(track1)) assertThat(trackQueue.peekNext(), equalTo(track2)) } @Test fun `Three Tracks - Poll Active`() { val track1 = TestUtil.randomFileVirtualTrack() val track2 = TestUtil.randomFileVirtualTrack() val track3 = TestUtil.randomFileVirtualTrack() trackQueue.pushNext(track1) trackQueue.pushNext(track2) trackQueue.pushNext(track3) trackQueue.pollActive() assertThat(trackQueue.pollActive(), equalTo(Pair(track1, track2))) assertThat(trackQueue.peekActive(), equalTo(track2)) assertThat(trackQueue.peekNext(), equalTo(track3)) } @Test fun `Three Tracks - Poll Next`() { val track1 = TestUtil.randomFileVirtualTrack() val track2 = TestUtil.randomFileVirtualTrack() val track3 = TestUtil.randomFileVirtualTrack() trackQueue.pushNext(track1) trackQueue.pushNext(track2) trackQueue.pushNext(track3) trackQueue.pollActive() assertThat(trackQueue.pollNext(), equalTo(track2)) assertThat(trackQueue.peekActive(), equalTo(track1)) assertThat(trackQueue.peekNext(), nullValue()) } }
0
Kotlin
0
0
4092b8463956d382e03b7151016295bcd230a308
5,047
gravifon
MIT License
RxJava/src/main/kotlin/chapter05/examples/OpenWeatherMapV1.kt
Im-Tae
260,676,018
false
null
package chapter05.examples import common.CommonUtils import common.Log import common.OkHttpHelper import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import java.util.regex.Pattern class OpenWeatherMapV1 { private val URL = "http://api.openweathermap.org/data/2.5/weather?q=London&appid=" private val API_KEY = "ea9463cc69d79542047ba01dae512a5e" fun run() { val source = Observable.just(URL + API_KEY) .map(OkHttpHelper()::getWithLog) .subscribeOn(Schedulers.io()) val temperature = source.map(this::parseTemperature) val city = source.map(this::parseCityName) val country = source.map(this::parseCountry) CommonUtils.start() Observable.concat(temperature, city, country) .observeOn(Schedulers.newThread()) .subscribe { data -> Log.it(data) } CommonUtils.sleep(3000) } private fun parseTemperature(json: String): String = parse(json, "\"temp\":[0-9]*.[0-9]*") private fun parseCityName(json: String): String = parse(json, "\"name\":\"[a-zA-Z]*\"") private fun parseCountry(json: String): String = parse(json, "\"country\":\"[a-zA-Z]*\"") private fun parse(json: String, regex: String): String { val pattern = Pattern.compile(regex) val match = pattern.matcher(json) if (match.find()) return match.group() return "N/A" } } fun main() { val demo = OpenWeatherMapV1() demo.run() }
0
Kotlin
12
5
819e4234069f03a822f8defa15cc2d37cc58fb25
1,492
Blog_Example
MIT License
app/src/main/java/com/lookie/instadownloader/data/remote/model/ShortMediaModel.kt
nhphung216
233,366,868
false
null
package com.lookie.instadownloader.data.remote.model import android.os.Parcel import android.os.Parcelable import com.google.gson.Gson import com.google.gson.annotations.SerializedName class ShortMediaModel() : Parcelable { @SerializedName("id") var id: String? = "" @SerializedName("shortcode") var shortcode: String? = "" @SerializedName("display_url") var displayUrl: String? = "" @SerializedName("video_url") var videoUrl: String? = "" @SerializedName("is_video") var isVideo: Boolean = false @SerializedName("edge_sidecar_to_children") var children: ChildrenModel? = ChildrenModel() @SerializedName("edge_media_to_caption") var caption: ChildrenModel? = ChildrenModel() @SerializedName("owner") var owner: OwnerModel? = OwnerModel() @SerializedName("text") var text: String? = "" constructor(parcel: Parcel) : this() { id = parcel.readString() shortcode = parcel.readString() displayUrl = parcel.readString() videoUrl = parcel.readString() isVideo = parcel.readByte() != 0.toByte() children = parcel.readParcelable(ChildrenModel::class.java.classLoader) caption = parcel.readParcelable(ChildrenModel::class.java.classLoader) text = parcel.readString() } override fun toString(): String { return Gson().toJson(this) } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(id) parcel.writeString(shortcode) parcel.writeString(displayUrl) parcel.writeString(videoUrl) parcel.writeByte(if (isVideo) 1 else 0) parcel.writeParcelable(children, flags) parcel.writeParcelable(caption, flags) parcel.writeString(text) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<ShortMediaModel> { override fun createFromParcel(parcel: Parcel): ShortMediaModel { return ShortMediaModel(parcel) } override fun newArray(size: Int): Array<ShortMediaModel?> { return arrayOfNulls(size) } } fun isMultiMedia(): Boolean { return children!!.edges!!.isNotEmpty() } }
1
Kotlin
1
6
45e57fd03e90acf557ecd38f2d92e5035657e8e4
2,096
insta-downloader
Apache License 2.0
user-infrastructure/src/test/kotlin/com/xquare/v1userservice/EqualsTestUtils.kt
team-xquare
466,882,102
false
{"Kotlin": 119366, "Dockerfile": 440, "Shell": 417}
package com.xquare.v1userservice.user import kotlin.reflect.KProperty import kotlin.reflect.full.memberProperties import org.assertj.core.api.Assertions.assertThat object EqualsTestUtils { fun isEqualTo(baseObject: Any, targetObject: Any) { val baseObjectFieldMap = baseObject::class.memberProperties .associateBy { it.name } val targetObjectFields = targetObject::class.memberProperties targetObjectFields .forEach { assertThat(getValueOfProperty(baseObject, baseObjectFieldMap[it.name]!!)) .isEqualTo(getValueOfProperty(targetObject, it)) } } private fun getValueOfProperty(obj: Any, property: KProperty<*>) = property.getter.call(obj) }
2
Kotlin
2
8
c68ae11f10ca874d902ee6f7f770f7a7c4352e5f
761
v1-service-user
MIT License
enro-core/src/main/java/dev/enro/core/compose/ComposableNavigationResult.kt
splitwise
349,506,770
true
{"Kotlin": 554655}
package dev.enro.core.compose import androidx.compose.runtime.Composable import androidx.compose.runtime.DisallowComposableCalls import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import dev.enro.core.NavigationKey import dev.enro.core.result.EnroResultChannel import dev.enro.core.result.internal.ResultChannelImpl import java.util.* @Composable inline fun <reified T: Any> registerForNavigationResult( // Sometimes, particularly when interoperating between Compose and the legacy View system, // it may be required to provide an id explicitly. This should not be required when using // registerForNavigationResult from an entirely Compose-based screen. // Remember a random UUID that will be used to uniquely identify this result channel // within the composition. This is important to ensure that results are delivered if a Composable // is used multiple times within the same composition (such as within a list). // See ComposableListResultTests id: String = rememberSaveable { UUID.randomUUID().toString() }, noinline onResult: @DisallowComposableCalls (T) -> Unit ): EnroResultChannel<T, NavigationKey.WithResult<T>> { val navigationHandle = navigationHandle() val resultChannel = remember(onResult) { ResultChannelImpl( navigationHandle = navigationHandle, resultType = T::class.java, onResult = onResult, additionalResultId = id ) } DisposableEffect(true) { resultChannel.attach() onDispose { resultChannel.detach() } } return resultChannel }
10
Kotlin
0
0
bacab3d4858dc911d7abb179aa69c624e497a2f8
1,724
Enro
Apache License 2.0
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/LoadMoreListener.kt
waffle-iron
98,105,778
true
{"Kotlin": 44602}
package io.github.feelfreelinux.wykopmobilny.utils abstract class LoadMoreListener { var page = 1 var loading = false abstract fun loadMore () }
0
Kotlin
0
0
3b3a26b9a12c2a1b7fd8395ec8d76b574f759349
157
WykopMobilny
MIT License
materialdrawer/src/main/java/com/mikepenz/materialdrawer/util/MenuDrawerUtils.kt
mikepenz
30,120,110
false
{"Kotlin": 422696, "Ruby": 2019, "Shell": 470}
package com.mikepenz.materialdrawer.util import android.annotation.SuppressLint import android.view.Menu import androidx.annotation.MenuRes import androidx.appcompat.view.SupportMenuInflater import androidx.appcompat.view.menu.MenuBuilder import com.mikepenz.materialdrawer.R import com.mikepenz.materialdrawer.model.DividerDrawerItem import com.mikepenz.materialdrawer.model.PrimaryDrawerItem import com.mikepenz.materialdrawer.model.SecondaryDrawerItem import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem import com.mikepenz.materialdrawer.model.interfaces.iconDrawable import com.mikepenz.materialdrawer.model.interfaces.nameText import com.mikepenz.materialdrawer.widget.MaterialDrawerSliderView /** * Inflates the DrawerItems from a menu.xml */ @SuppressLint("RestrictedApi") fun MaterialDrawerSliderView.inflateMenu(@MenuRes menuRes: Int) { val menuInflater = SupportMenuInflater(context) val mMenu = MenuBuilder(context) menuInflater.inflate(menuRes, mMenu) addMenuItems(mMenu, false) } /** * helper method to init the drawerItems from a menu */ private fun MaterialDrawerSliderView.addMenuItems(mMenu: Menu, subMenu: Boolean) { var groupId = R.id.material_drawer_menu_default_group for (i in 0 until mMenu.size()) { val mMenuItem = mMenu.getItem(i) var iDrawerItem: IDrawerItem<*> if (!subMenu && mMenuItem.groupId != groupId && mMenuItem.groupId != 0) { groupId = mMenuItem.groupId iDrawerItem = DividerDrawerItem() itemAdapter.add(iDrawerItem) } if (mMenuItem.hasSubMenu()) { iDrawerItem = PrimaryDrawerItem().apply { nameText = mMenuItem.title iconDrawable = mMenuItem.icon identifier = mMenuItem.itemId.toLong() isEnabled = mMenuItem.isEnabled isSelectable = false } itemAdapter.add(iDrawerItem) addMenuItems(mMenuItem.subMenu, true) } else if (mMenuItem.groupId != 0 || subMenu) { iDrawerItem = SecondaryDrawerItem().apply { nameText = mMenuItem.title iconDrawable = mMenuItem.icon identifier = mMenuItem.itemId.toLong() isEnabled = mMenuItem.isEnabled } itemAdapter.add(iDrawerItem) } else { iDrawerItem = PrimaryDrawerItem().apply { nameText = mMenuItem.title iconDrawable = mMenuItem.icon identifier = mMenuItem.itemId.toLong() isEnabled = mMenuItem.isEnabled } itemAdapter.add(iDrawerItem) } } }
5
Kotlin
2080
11,670
b03f1d495ae65fd88bdd3ee7e496665ae9721c0f
2,689
MaterialDrawer
Apache License 2.0
core/test/src/main/java/dev/shushant/test/TestData.kt
dev-shushant
665,347,929
false
{"Kotlin": 99424, "Shell": 4127}
package dev.shushant.test import java.math.BigDecimal import kotlin.random.Random val currencies = mutableMapOf( "AED" to "United Arab Emirates Dirham", "AFN" to "Afghan Afghani", "ALL" to "Albanian Lek", "AMD" to "Armenian Dram", "ANG" to "Netherlands Antillean Guilder", "AOA" to "Angolan Kwanza", "ARS" to "Argentine Peso", "AUD" to "Australian Dollar", "AWG" to "Aruban Florin", "AZN" to "Azerbaijani Manat", "BAM" to "Bosnia-Herzegovina Convertible Mark", "BBD" to "Barbadian Dollar", "BDT" to "Bangladeshi Taka", "BGN" to "Bulgarian Lev", "BHD" to "Bahraini Dinar", "BIF" to "Burundian Franc", "BMD" to "Bermudan Dollar", "BND" to "Brunei Dollar", "BOB" to "Bolivian Boliviano", "BRL" to "Brazilian Real", "BSD" to "Bahamian Dollar", "BTC" to "Bitcoin", "BTN" to "Bhutanese Ngultrum", "BWP" to "Botswanan Pula", "BYN" to "Belarusian Ruble", "BZD" to "Belize Dollar", "CAD" to "Canadian Dollar", "CDF" to "Congolese Franc", "CHF" to "Swiss Franc", "CLF" to "Chilean Unit of Account (UF)", "CLP" to "Chilean Peso", "CNH" to "Chinese Yuan (Offshore)", "CNY" to "Chinese Yuan", "COP" to "Colombian Peso", "CRC" to "Costa Rican Colón", "CUC" to "Cuban Convertible Peso", "CUP" to "Cuban Peso", "CVE" to "Cape Verdean Escudo", "CZK" to "Czech Republic Koruna", "DJF" to "Djiboutian Franc", "DKK" to "Danish Krone", "DOP" to "Dominican Peso", "DZD" to "Algerian Dinar", "EGP" to "Egyptian Pound", "ERN" to "Eritrean Nakfa", "ETB" to "Ethiopian Birr", "EUR" to "Euro", "FJD" to "Fijian Dollar", "FKP" to "Falkland Islands Pound", "GBP" to "British Pound Sterling", "GEL" to "Georgian Lari", "GGP" to "Guernsey Pound", "GHS" to "Ghanaian Cedi", "GIP" to "Gibraltar Pound", "GMD" to "Gambian Dalasi", "GNF" to "Guinean Franc", "GTQ" to "Guatemalan Quetzal", "GYD" to "Guyanaese Dollar", "HKD" to "Hong Kong Dollar", "HNL" to "Honduran Lempira", "HRK" to "Croatian Kuna", "HTG" to "Haitian Gourde", "HUF" to "Hungarian Forint", "IDR" to "Indonesian Rupiah", "ILS" to "Israeli New Sheqel", "IMP" to "Manx pound", "INR" to "Indian Rupee", "IQD" to "Iraqi Dinar", "IRR" to "Iranian Rial", "ISK" to "Icelandic Króna", "JEP" to "Jersey Pound", "JMD" to "Jamaican Dollar", "JOD" to "Jordanian Dinar", "JPY" to "Japanese Yen", "KES" to "Kenyan Shilling", "KGS" to "Kyrgystani Som", "KHR" to "Cambodian Riel", "KMF" to "Comorian Franc", "KPW" to "North Korean Won", "KRW" to "South Korean Won", "KWD" to "Kuwaiti Dinar", "KYD" to "Cayman Islands Dollar", "KZT" to "Kazakhstani Tenge", "LAK" to "Laotian Kip", "LBP" to "Lebanese Pound", "LKR" to "Sri Lankan Rupee", "LRD" to "Liberian Dollar", "LSL" to "Lesotho Loti", "LYD" to "Libyan Dinar", "MAD" to "Mor<NAME>", "MDL" to "Moldovan Leu", "MGA" to "Malagasy Ariary", "MKD" to "Macedonian Denar", "MMK" to "Myanma Kyat", "MNT" to "Mongolian Tugrik", "MOP" to "Macanese Pataca", "MRU" to "Mauritanian Ouguiya", "MUR" to "Mauritian Rupee", "MVR" to "Maldivian Rufiyaa", "MWK" to "Malawian Kwacha", "MXN" to "Mexican Peso", "MYR" to "Malaysian Ringgit", "MZN" to "Mozambican Metical", "NAD" to "Namibian Dollar", "NGN" to "Nigerian Naira", "NIO" to "Nicaraguan Córdoba", "NOK" to "Norwegian Krone", "NPR" to "Nepalese Rupee", "NZD" to "New Zealand Dollar", "OMR" to "Omani Rial", "PAB" to "Panamanian Balboa", "PEN" to "Peruvian Nuevo Sol", "PGK" to "Papua New Guinean Kina", "PHP" to "Philippine Peso", "PKR" to "Pakistani Rupee", "PLN" to "Polish Zloty", "PYG" to "Paraguayan Guarani", "QAR" to "Qatari Rial", "RON" to "Romanian Leu", "RSD" to "Serbian Dinar", "RUB" to "Russian Ruble", "RWF" to "Rwandan Franc", "SAR" to "Saudi Riyal", "SBD" to "Solomon Islands Dollar", "SCR" to "Seychellois Rupee", "SDG" to "Sudanese Pound", "SEK" to "Swedish Krona", "SGD" to "Singapore Dollar", "SHP" to "Saint Helena Pound", "SLL" to "Sierra Leonean Leone", "SOS" to "Somali Shilling", "SRD" to "Surinamese Dollar", "SSP" to "South Sudanese Pound", "STD" to "São Tomé and Príncipe Dobra (pre-2018)", "STN" to "São Tomé and Príncipe Dobra", "SVC" to "Salvadoran Colón", "SYP" to "Syrian Pound", "SZL" to "Swazi Lilangeni", "THB" to "Thai Baht", "TJS" to "Tajikistani Somoni", "TMT" to "Turkmenistani Manat", "TND" to "Tunisian Dinar", "TOP" to "Tongan Pa'anga", "TRY" to "Turkish Lira", "TTD" to "Trinidad and Tobago Dollar", "TWD" to "New Taiwan Dollar", "TZS" to "Tanzanian Shilling", "UAH" to "Ukrainian Hryvnia", "UGX" to "Ugandan Shilling", "USD" to "United States Dollar", "UYU" to "Uruguayan Peso", "UZS" to "Uzbekistan Som", "VEF" to "V<NAME> (Old)", "VES" to "V<NAME>", "VND" to "Vietnamese Dong", "VUV" to "Vanuatu Vatu", "WST" to "Samoan Tala", "XAF" to "CFA Franc BEAC", "XAG" to "Silver Ounce", "XAU" to "Gold Ounce", "XCD" to "East Caribbean Dollar", "XDR" to "Special Drawing Rights", "XOF" to "CFA Franc BCEAO", "XPD" to "Palladium Ounce", "XPF" to "CFP Franc", "XPT" to "Platinum Ounce", "YER" to "Yemeni Rial", "ZAR" to "South African Rand", "ZMW" to "Zambian Kwacha", "ZWL" to "Zimbabwean Dollar" ) val exchangeRates = mutableMapOf( "AED" to 3.67304, "AFN" to 87.00, "ALL" to 95.2, "AMD" to 387.575856, "ANG" to 1.80256, "AOA" to 823.665, "ARS" to 262.726143, "AUD" to 1.498893, "AWG" to 1.8, "AZN" to 1.7, "BAM" to 1.784855, "BBD" to 2.00, "BDT" to 108.608071, "BGN" to 1.781554, "BHD" to 0.376988, "BIF" to 2835.00, "BMD" to 1.00, "BND" to 1.349182, "BOB" to 6.911027, "BRL" to 4.872, "BSD" to 1.00, "BTC" to 0.000032956715, "BTN" to 82.621975, "BWP" to 13.469919, "BYN" to 2.524515, "BZD" to 2.016016, "CAD" to 1.328656, "CDF" to 2432.00, "CHF" to 0.886539, "CLF" to 0.029438, "CLP" to 812.35, "CNH" to 7.231095, "CNY" to 7.2316, "COP" to 4165.88, "CRC" to 544.454337, "CUC" to 1.00, "CUP" to 25.75, "CVE" to 101.00, "CZK" to 21.703999, "DJF" to 178.074855, "DKK" to 6.780343, "DOP" to 55.76, "DZD" to 135.274227, "EGP" to 30.901456, "ERN" to 15.00, "ETB" to 54.61, "EUR" to 0.90998, "FJD" to 2.2193, "FKP" to 0.778452, "GBP" to 0.778452, "GEL" to 2.595, "GGP" to 0.778452, "GHS" to 11.375, "GIP" to 0.778452, "GMD" to 59.65, "GNF" to 8650.00, "GTQ" to 7.846501, "GYD" to 209.254851, "HKD" to 7.82815, "HNL" to 24.720001, "HRK" to 6.856016, "HTG" to 138.522993, "HUF" to 346.3, "IDR" to 15185.516003, "ILS" to 3.70005, "IMP" to 0.778452, "INR" to 82.5541, "IQD" to 1310.00, "IRR" to 42275.00, "ISK" to 134.01, "JEP" to 0.778452, "JMD" to 154.685021, "JOD" to 0.7094, "JPY" to 141.48066667, "KES" to 141.05, "KGS" to 87.7379, "KHR" to 4131.00, "KMF" to 449.050075, "KPW" to 900.00, "KRW" to 1301.051665, "KWD" to 0.307001, "KYD" to 0.833474, "KZT" to 443.175067, "LAK" to 19163.90312, "LBP" to 15242.5, "LKR" to 313.066156, "LRD" to 182.7, "LSL" to 18.85, "LYD" to 4.82, "MAD" to 9.7805, "MDL" to 18.251593, "MGA" to 4535.00, "MKD" to 56.049811, "MMK" to 2100.333069, "MNT" to 3519.00, "MOP" to 8.065837, "MRU" to 35.48, "MUR" to 45.5, "MVR" to 15.39, "MWK" to 1050.00, "MXN" to 17.06882, "MYR" to 4.6705, "MZN" to 63.850001, "NAD" to 18.85, "NGN" to 769.5, "NIO" to 36.55, "NOK" to 10.505623, "NPR" to 132.195051, "NZD" to 1.609979, "OMR" to 0.385013, "PAB" to 1.00, "PEN" to 3.6405, "PGK" to 3.52, "PHP" to 55.559001, "PKR" to 279.5, "PLN" to 4.046059, "PYG" to 7281.575124, "QAR" to 3.641, "RON" to 4.5031, "RSD" to 106.671991, "RUB" to 90.549996, "RWF" to 1165.00, "SAR" to 3.751377, "SBD" to 8.397638, "SCR" to 13.563567, "SDG" to 600.5, "SEK" to 10.78817, "SGD" to 1.345322, "SHP" to 0.778452, "SLL" to 17665.00, "SOS" to 568.5, "SRD" to 37.6, "SSP" to 130.26, "STD" to 22823.990504, "STN" to 22.7, "SVC" to 8.751797, "SYP" to 2512.53, "SZL" to 18.85, "THB" to 35.11, "TJS" to 10.941753, "TMT" to 3.51, "TND" to 3.0865, "TOP" to 2.3523, "TRY" to 26.086, "TTD" to 6.786065, "TWD" to 31.3675, "TZS" to 2445.00, "UAH" to 36.940159, "UGX" to 3690.550226, "USD" to 1.00, "UYU" to 38.138154, "UZS" to 11585.00, "VES" to 28.269451, "VND" to 23655.00, "VUV" to 118.979, "WST" to 2.72551, "XAF" to 596.907887, "XAG" to 0.04324886, "XAU" to 0.00051927, "XCD" to 2.70255, "XDR" to 0.749698, "XOF" to 596.907887, "XPD" to 0.00080921, "XPF" to 108.589524, "XPT" to 0.00107643, "YER" to 250.349961, "ZAR" to 18.805871, "ZWL" to 322.00 ) fun convertCurrency(baseCurrency: String, sourceAmount: BigDecimal): MutableMap<String, Double> { val mapOfExchangeRate = mutableMapOf<String, Double>() val usdEquivalent = sourceAmount.toDouble().div( exchangeRates.getOrDefault(baseCurrency, Random.nextDouble(0.0, 100.0)) ) for (currency in exchangeRates) { val convertedAmount = usdEquivalent * exchangeRates.getValue(currency.key) mapOfExchangeRate[currency.key] = convertedAmount } return mapOfExchangeRate }
0
Kotlin
0
0
5c8ac52e5f60353a1e7def649ee2bebd08f19ca9
9,955
CurrencyConverter
MIT License
app/src/main/java/com/example/recipeapp/utils/Constants.kt
kl3jvi
389,310,024
false
null
package com.example.recipeapp.utils object Constants { const val DISH_TYPE: String = "DishType" const val DISH_CATEGORY: String = "DishCategory" const val DISH_COOKING_TIME: String = "DishCookingTime" const val DISH_IMAGE_SOURCE_LOCAL: String = "Local" const val DISH_IMAGE_SOURCE_ONLINE: String = "Online" const val EXTRA_DISH_DETAILS: String = "DishDetails" const val ALL_ITEMS: String = "All" const val FILTER_SELECTION: String = "FilterSelection" const val API_ENDPOINT: String = "recipes/random" const val API_KEY: String = "apiKey" const val LIMIT_LICENSE: String = "limitLicense" const val TAGS: String = "tags" const val NUMBER: String = "number" const val BASE_URL: String = "https://api.spoonacular.com/" const val API_KEY_VALUE: String = "d6e3518068b347aba81e097cfc690697" const val LIMIT_LICENSE_VALUE: Boolean = true const val TAGS_VALUE: String = "vegetarian,desert" const val NUMBER_VALUE: Int = 1 fun dishTypes(): ArrayList<String> { val list = ArrayList<String>() list.add("Breakfast") list.add("Lunch") list.add("Snacks") list.add("Dinner") list.add("Salad") list.add("Side Dish") list.add("Dessert") list.add("Other") return list } fun dishCategories(): ArrayList<String> { val list = ArrayList<String>() list.add("Pizza") list.add("BBQ") list.add("Bakery") list.add("Burger") list.add("Cafe") list.add("Chicken") list.add("Dessert") list.add("Drinks") list.add("Hot Dogs") list.add("Juices") list.add("Sandwich") list.add("Tea & Coffee") list.add("Wraps") list.add("Other") return list } fun dishTime(): ArrayList<String> { val list = ArrayList<String>() list.add("5") list.add("10") list.add("15") list.add("20") list.add("25") list.add("30") list.add("45") list.add("60") list.add("70") list.add("80") list.add("90") list.add("100") list.add("110") list.add("120") return list } }
0
Kotlin
0
3
3eb3fb9f4c7113c5ad7ee6d9b4921befa3c1c6f0
2,241
recipe-app
Apache License 2.0
modules/presentation/src/main/kotlin/dev/theolm/wwc/presentation/ext/ActivityExt.kt
theolm
658,128,759
false
{"Kotlin": 75393}
package dev.theolm.wwc.presentation.ext import android.app.Activity import android.content.Intent import android.net.Uri private const val WhatsappUri = "https://api.whatsapp.com/send?phone=" fun Activity.startWhatsAppChat(phone: String, packageId: String) { // Only set the intent package if both WhatsApp and WhatsApp Business are installed val shouldSetPackage = this.checkIfWpIsInstalled() && this.checkIfWpBusinessIsInstalled() Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(WhatsappUri + phone) if (shouldSetPackage) { setPackage(packageId) } }.also { startActivity(it) finish() } }
4
Kotlin
5
73
48c80ee4ea33b0226ca8329b5b7ad862865f5a93
669
WhatsAppNoContact
MIT License
platform/runner/extension/std/log/src/main/kotlin/io/hamal/extension/std/log/Extension.kt
hamal-io
622,870,037
false
{"Kotlin": 3917028, "C": 1401512, "TypeScript": 339641, "Lua": 170806, "C++": 40651, "Makefile": 11728, "Java": 7564, "JavaScript": 3076, "CMake": 2838, "CSS": 1567, "HTML": 1248, "Shell": 977}
package io.hamal.extension.std.log import io.hamal.lib.kua.Sandbox import io.hamal.lib.kua.extend.extension.RunnerExtension import io.hamal.lib.kua.extend.extension.RunnerExtensionFactory import io.hamal.lib.kua.type.KuaString object ExtensionLogFactory : RunnerExtensionFactory { override fun create(sandbox: Sandbox): RunnerExtension { return RunnerExtension(name = KuaString("log")) } }
39
Kotlin
0
0
c263adf12584f9ed4be14d3884daa88ab08313d3
408
hamal
Creative Commons Zero v1.0 Universal
DSLs/kubernetes/dsl/src/main/kotlin-gen/dev/forkhandles/k8s/authorization/v1beta1/spec.kt
fork-handles
649,794,132
false
{"Kotlin": 575626, "Shell": 2264, "Just": 1042, "Nix": 740}
// GENERATED package dev.forkhandles.k8s.authorization.v1beta1 import io.fabric8.kubernetes.api.model.authorization.v1beta1.LocalSubjectAccessReview as v1beta1_LocalSubjectAccessReview import io.fabric8.kubernetes.api.model.authorization.v1beta1.SelfSubjectAccessReview as v1beta1_SelfSubjectAccessReview import io.fabric8.kubernetes.api.model.authorization.v1beta1.SelfSubjectAccessReviewSpec as v1beta1_SelfSubjectAccessReviewSpec import io.fabric8.kubernetes.api.model.authorization.v1beta1.SelfSubjectRulesReview as v1beta1_SelfSubjectRulesReview import io.fabric8.kubernetes.api.model.authorization.v1beta1.SelfSubjectRulesReviewSpec as v1beta1_SelfSubjectRulesReviewSpec import io.fabric8.kubernetes.api.model.authorization.v1beta1.SubjectAccessReview as v1beta1_SubjectAccessReview import io.fabric8.kubernetes.api.model.authorization.v1beta1.SubjectAccessReviewSpec as v1beta1_SubjectAccessReviewSpec fun v1beta1_LocalSubjectAccessReview.spec(block: v1beta1_SubjectAccessReviewSpec.() -> Unit = {}) { if (spec == null) { spec = v1beta1_SubjectAccessReviewSpec() } spec.block() } fun v1beta1_SelfSubjectAccessReview.spec(block: v1beta1_SelfSubjectAccessReviewSpec.() -> Unit = {}) { if (spec == null) { spec = v1beta1_SelfSubjectAccessReviewSpec() } spec.block() } fun v1beta1_SelfSubjectRulesReview.spec(block: v1beta1_SelfSubjectRulesReviewSpec.() -> Unit = {}) { if (spec == null) { spec = v1beta1_SelfSubjectRulesReviewSpec() } spec.block() } fun v1beta1_SubjectAccessReview.spec(block: v1beta1_SubjectAccessReviewSpec.() -> Unit = {}) { if (spec == null) { spec = v1beta1_SubjectAccessReviewSpec() } spec.block() }
0
Kotlin
0
9
68221cee577ea16dc498745606d07b0fb62f5cb7
1,716
k8s-dsl
MIT License
src/main/java/ru/hollowhorizon/hc/client/render/entity/GLTFEntityRenderer.kt
HollowHorizon
450,852,365
false
{"Kotlin": 355887, "Java": 211777, "GLSL": 26970, "HTML": 357}
package ru.hollowhorizon.hc.client.render.entity import com.mojang.blaze3d.vertex.DefaultVertexFormat import com.mojang.blaze3d.vertex.PoseStack import com.mojang.blaze3d.vertex.VertexFormat import com.mojang.math.Vector3f import net.minecraft.Util import net.minecraft.client.renderer.MultiBufferSource import net.minecraft.client.renderer.RenderStateShard import net.minecraft.client.renderer.RenderStateShard.TextureStateShard import net.minecraft.client.renderer.RenderType import net.minecraft.client.renderer.RenderType.CompositeState import net.minecraft.client.renderer.entity.EntityRenderer import net.minecraft.client.renderer.entity.EntityRendererProvider import net.minecraft.client.renderer.texture.OverlayTexture import net.minecraft.client.renderer.texture.TextureManager import net.minecraft.resources.ResourceLocation import net.minecraft.util.Mth import net.minecraft.world.entity.LivingEntity import net.minecraft.world.entity.animal.FlyingAnimal import ru.hollowhorizon.hc.client.models.gltf.ModelData import ru.hollowhorizon.hc.client.models.gltf.animations.AnimationType import ru.hollowhorizon.hc.client.models.gltf.animations.GLTFAnimationPlayer import ru.hollowhorizon.hc.client.models.gltf.manager.AnimatedEntityCapability import ru.hollowhorizon.hc.client.models.gltf.manager.GltfManager import ru.hollowhorizon.hc.client.models.gltf.manager.IAnimated import ru.hollowhorizon.hc.client.utils.get import ru.hollowhorizon.hc.client.utils.rl open class GLTFEntityRenderer<T>(manager: EntityRendererProvider.Context) : EntityRenderer<T>(manager) where T : LivingEntity, T : IAnimated { val itemInHandRenderer = manager.itemInHandRenderer val renderType = Util.memoize { texture: ResourceLocation, data: Boolean -> val state = CompositeState.builder().setShaderState(RenderStateShard.RENDERTYPE_ENTITY_TRANSLUCENT_SHADER) .setTextureState(TextureStateShard(texture, false, false)) .setTransparencyState(RenderStateShard.TRANSLUCENT_TRANSPARENCY).setCullState(RenderStateShard.NO_CULL) .setLightmapState(RenderStateShard.LIGHTMAP).setOverlayState(RenderStateShard.OVERLAY) .createCompositeState(data) RenderType.create( "hc:gltf_entity", DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.TRIANGLES, 256, true, true, state ) } override fun getTextureLocation(entity: T): ResourceLocation { //return "hc:textures/entity/vuzz.png".rl return TextureManager.INTENTIONAL_MISSING_TEXTURE } @Suppress("DEPRECATION") override fun render( entity: T, yaw: Float, partialTick: Float, stack: PoseStack, source: MultiBufferSource, packedLight: Int, ) { super.render(entity, yaw, partialTick, stack, source, packedLight) val capability = entity[AnimatedEntityCapability::class] val modelPath = capability.model if (modelPath == NO_MODEL) return val model = GltfManager.getOrCreate(modelPath.rl) stack.pushPose() preRender(entity, capability, model.animationPlayer, stack) val lerpBodyRot = Mth.rotLerp(partialTick, entity.yBodyRotO, entity.yBodyRot) stack.mulPose(Vector3f.YP.rotationDegrees(-lerpBodyRot)) model.update(capability, entity.tickCount, partialTick) model.entityUpdate(entity, capability, partialTick) model.render( stack, ModelData(entity.offhandItem, entity.mainHandItem, itemInHandRenderer, entity), { texture -> source.getBuffer(getRenderType(capability.textures[texture.path]?.rl ?: texture)) }, packedLight, OverlayTexture.pack(0, if (entity.hurtTime > 0 || !entity.isAlive) 3 else 10) ) stack.popPose() } protected fun getRenderType(texture: ResourceLocation): RenderType = renderType.apply(texture, true) private fun preRender( entity: T, capability: AnimatedEntityCapability, manager: GLTFAnimationPlayer, stack: PoseStack, ) { stack.mulPoseMatrix(capability.transform.matrix) stack.mulPose(Vector3f.YP.rotationDegrees(180f)) updateAnimations(entity, capability, manager) } private fun updateAnimations(entity: T, capability: AnimatedEntityCapability, manager: GLTFAnimationPlayer) { when { entity.hurtTime > 0 -> manager.playOnce(capability, AnimationType.HURT) entity.swinging -> manager.playOnce(capability, AnimationType.SWING) } manager.currentLoopAnimation = when { !entity.isAlive -> AnimationType.DEATH entity is FlyingAnimal && entity.isFlying -> AnimationType.FLY entity.isSleeping -> AnimationType.SLEEP entity.vehicle != null -> AnimationType.SIT entity.fallFlyingTicks > 4 -> AnimationType.FALL entity.animationSpeed > 0.01 -> { when { entity.isVisuallySwimming -> AnimationType.SWIM entity.isShiftKeyDown -> AnimationType.WALK_SNEAKED entity.animationSpeed > 1.5f -> AnimationType.RUN else -> AnimationType.WALK } } else -> AnimationType.IDLE } } companion object { const val NO_MODEL = "%NO_MODEL%" } }
1
Kotlin
1
4
8ae56f1f2f8997d42149ef82a2f3751b6e757472
5,460
HollowCore
MIT License
geotabdrivesdk/src/main/java/com/geotab/mobile/sdk/util/UriWrapper.kt
Geotab
333,267,573
false
{"Kotlin": 387965, "JavaScript": 23897}
package com.geotab.mobile.sdk.util import android.net.Uri class UriWrapper { fun parse(pathString: String): Uri { return Uri.parse(pathString) } }
1
Kotlin
2
2
9d2b6363c999fde1064f315479b69e450e637a30
165
mobile-sdk-android
MIT License
src/main/java/ru/hollowhorizon/hollowengine/cutscenes/replay/ReplayBlock.kt
HollowHorizon
586,593,959
false
null
package ru.hollowhorizon.hollowengine.cutscenes.replay import kotlinx.serialization.Serializable import net.minecraft.block.DoorBlock import net.minecraft.entity.LivingEntity import net.minecraft.item.BlockItem import net.minecraft.item.ItemStack import net.minecraft.item.ItemUseContext import net.minecraft.util.math.BlockPos import net.minecraft.util.math.BlockRayTraceResult import net.minecraft.world.World import net.minecraftforge.common.util.FakePlayer import net.minecraftforge.registries.ForgeRegistries import ru.hollowhorizon.hc.client.utils.nbt.ForBlockPos import ru.hollowhorizon.hc.client.utils.toRL @Serializable class ReplayBlock( val pos: @Serializable(ForBlockPos::class) BlockPos, val block: String, ) { fun place(level: World, target: LivingEntity, fakePlayer: FakePlayer) { val block = ForgeRegistries.BLOCKS.getValue(block.toRL()) ?: throw IllegalArgumentException("Block $block not found") val blockItem = block.asItem() if (blockItem is BlockItem) { blockItem.useOn(ItemUseContext(fakePlayer, target.usedItemHand, BlockRayTraceResult(target.lookAngle, target.direction, pos, false))) } else { level.setBlockAndUpdate(pos, block.defaultBlockState()) if (block is DoorBlock) { block.setPlacedBy(level, pos, block.defaultBlockState(), null, ItemStack.EMPTY) } } } fun placeWorld(level: World) { val block = ForgeRegistries.BLOCKS.getValue(block.toRL()) ?: throw IllegalArgumentException("Block $block not found") level.setBlockAndUpdate(pos, block.defaultBlockState()) } fun destroy(fakePlayer: FakePlayer) { val manager = fakePlayer.gameMode manager.destroyBlock(pos) } fun destroyWorld(level: World) { level.destroyBlock(pos, false) } fun use(level: World, target: LivingEntity, fakePlayer: FakePlayer) { val manager = fakePlayer.gameMode manager.useItemOn(fakePlayer, level, target.useItem, target.usedItemHand, BlockRayTraceResult(target.lookAngle, target.direction, pos, false)) } }
0
Kotlin
2
3
99f1ae108a54268500c2fbf228cb756380210c7a
2,152
HollowEngine
MIT License
src/test/kotlin/org/wfanet/measurement/common/crypto/SecurityProviderTest.kt
world-federation-of-advertisers
375,798,604
false
null
// Copyright 2021 The Cross-Media Measurement Authors // // 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 org.wfanet.measurement.common.crypto import com.google.common.truth.Truth.assertThat import com.google.protobuf.ByteString import java.security.cert.X509Certificate import java.security.spec.InvalidKeySpecException import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.common.byteStringOf import org.wfanet.measurement.common.crypto.testing.FIXED_CA_CERT_PEM_FILE import org.wfanet.measurement.common.crypto.testing.FIXED_CLIENT_CERT_PEM_FILE import org.wfanet.measurement.common.crypto.testing.FIXED_SERVER_CERT_PEM_FILE import org.wfanet.measurement.common.crypto.testing.FIXED_SERVER_KEY_FILE private const val KEY_ALGORITHM = "EC" private val SERVER_SKID = byteStringOf( 0xE7, 0xB3, 0xB5, 0x45, 0x77, 0x1B, 0xC2, 0xB9, 0xA1, 0x88, 0x02, 0x07, 0x90, 0x3F, 0x87, 0xA5, 0xC4, 0x2C, 0x63, 0xA8 ) private val CLIENT_SKID = byteStringOf( 0x48, 0x32, 0x98, 0xE2, 0x03, 0xFE, 0xA1, 0xAF, 0xA0, 0x8D, 0x10, 0x7C, 0x92, 0x37, 0xCE, 0x19, 0x11, 0x6A, 0xA7, 0x8F, ) private val CLIENT_AKID = byteStringOf( 0x57, 0xE8, 0x9A, 0x06, 0x76, 0xBE, 0xBA, 0x1E, 0xA0, 0x71, 0x50, 0x5C, 0x40, 0x87, 0x9B, 0x98, 0xF1, 0xF5, 0x0C, 0x9E, ) @RunWith(JUnit4::class) class SecurityProviderTest { @Test fun `readCertificate reads fixed cert from PEM file`() { val certificate: X509Certificate = readCertificate(FIXED_SERVER_CERT_PEM_FILE) assertThat(certificate.subjectDN.name).isEqualTo("CN=server.example.com,O=Server") } @Test fun `readPrivateKey reads key from PKCS#8 PEM file`() { val privateKey = readPrivateKey(FIXED_SERVER_KEY_FILE, KEY_ALGORITHM) assertThat(privateKey.format).isEqualTo("PKCS#8") } @Test fun `readPrivateKey reads key from PKCS#8 PEM ByteString`() { val privateKey = readPrivateKey(FIXED_SERVER_KEY_FILE, KEY_ALGORITHM) val data = ByteString.copyFrom(privateKey.getEncoded()) val privateKeyCopy = readPrivateKey(data, KEY_ALGORITHM) assertThat(privateKeyCopy.format).isEqualTo("PKCS#8") assertThat(privateKey).isEqualTo(privateKeyCopy) } @Test fun `readPrivateKey reads key from invalid encoded ByteString`() { val data = ByteString.copyFromUtf8("some-invalid-encoded-key") assertFailsWith(InvalidKeySpecException::class) { readPrivateKey(data, KEY_ALGORITHM) } } @Test fun `subjectKeyIdentifier returns SKID`() { val certificate: X509Certificate = readCertificate(FIXED_SERVER_CERT_PEM_FILE) assertThat(certificate.subjectKeyIdentifier).isEqualTo(SERVER_SKID) } @Test fun `authorityKeyIdentifier returns SKID of issuer`() { val issuerCertificate = readCertificate(FIXED_CA_CERT_PEM_FILE) val certificate: X509Certificate = readCertificate(FIXED_SERVER_CERT_PEM_FILE) assertThat(certificate.authorityKeyIdentifier).isEqualTo(issuerCertificate.subjectKeyIdentifier) } @Test fun `subjectKeyIdentifier returns SKID of certificate with another format`() { val certificate: X509Certificate = readCertificate(FIXED_CLIENT_CERT_PEM_FILE) assertThat(certificate.subjectKeyIdentifier).isEqualTo(CLIENT_SKID) } @Test fun `authorityKeyIdentifier returns AKID of certificate with another format`() { val certificate: X509Certificate = readCertificate(FIXED_CLIENT_CERT_PEM_FILE) assertThat(certificate.authorityKeyIdentifier).isEqualTo(CLIENT_AKID) } }
3
Kotlin
0
1
91b8802bb7f6a1db6cedcc3d623771c12dc136bf
4,258
common-jvm
Apache License 2.0
app/src/main/java/com/partokarwat/showcase/ui/compose/Dimensions.kt
partokarwat
869,065,220
false
{"Kotlin": 76418}
package com.partokarwat.showcase.ui.compose import androidx.compose.ui.unit.dp object Dimensions { val spacingSmall = 8.dp val spacingNormal = 16.dp val minimumTouchTarget = 48.dp val coinChartHeight = 200.dp }
0
Kotlin
0
0
6712471f5b9767b8dfa232bea9eea3c0c792a7ad
229
showcase-app
MIT License
komga/src/main/kotlin/org/gotson/komga/interfaces/rest/dto/SeriesDto.kt
himura95
245,517,968
true
{"Kotlin": 228714, "Vue": 150769, "TypeScript": 36658, "TSQL": 3392, "JavaScript": 2632, "PLSQL": 2130, "Shell": 1470, "HTML": 704, "Dockerfile": 391}
package org.gotson.komga.interfaces.rest.dto import com.fasterxml.jackson.annotation.JsonFormat import org.gotson.komga.domain.model.Series import org.gotson.komga.domain.model.SeriesMetadata import java.time.LocalDateTime data class SeriesDto( val id: Long, val libraryId: Long, val name: String, val url: String, @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") val created: LocalDateTime?, @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") val lastModified: LocalDateTime?, @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") val fileLastModified: LocalDateTime, val booksCount: Int, val metadata: SeriesMetadataDto ) data class SeriesMetadataDto( val status: String, val statusLock: Boolean, @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") val created: LocalDateTime?, @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") val lastModified: LocalDateTime?, val title: String, val titleLock: Boolean, val titleSort: String, val titleSortLock: Boolean ) fun Series.toDto(includeUrl: Boolean) = SeriesDto( id = id, libraryId = library.id, name = name, url = if (includeUrl) url.toURI().path else "", created = createdDate?.toUTC(), lastModified = lastModifiedDate?.toUTC(), fileLastModified = fileLastModified.toUTC(), booksCount = books.size, metadata = metadata.toDto() ) fun SeriesMetadata.toDto() = SeriesMetadataDto( status = status.name, statusLock = statusLock, created = createdDate?.toUTC(), lastModified = lastModifiedDate?.toUTC(), title = title, titleLock = titleLock, titleSort = titleSort, titleSortLock = titleSortLock )
0
Kotlin
0
0
2db410bcca942b296b3e06f3a4924b9f2328af03
1,602
komga
MIT License
solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseComplement.kt
tuProlog
230,784,338
false
{"Kotlin": 3797695, "Java": 18690, "ANTLR": 10366, "CSS": 1535, "JavaScript": 894, "Prolog": 818}
package it.unibo.tuprolog.solve.stdlib.function import it.unibo.tuprolog.core.Integer import it.unibo.tuprolog.core.Numeric import it.unibo.tuprolog.core.Real import it.unibo.tuprolog.solve.ExecutionContext import it.unibo.tuprolog.solve.function.UnaryMathFunction /** * Implementation of `'\'/1` arithmetic functor * * @author Enrico */ object BitwiseComplement : UnaryMathFunction("\\") { override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = Numeric.of(integer.value.not()) override fun mathFunction(real: Real, context: ExecutionContext): Numeric = throwTypeErrorBecauseOnlyIntegersAccepted(functor, real, context) }
76
Kotlin
13
76
f3beae8a90efd099341dfa29283790d02d39d48e
681
2p-kt
Apache License 2.0
app/src/main/java/com/wangyiheng/vcamsx/MainHook.kt
Xposed-Modules-Repo
730,140,026
false
{"Kotlin": 59248}
package com.wangyiheng.vcamsx import android.app.Application import android.content.Context import android.graphics.SurfaceTexture import android.hardware.Camera import android.hardware.camera2.CameraDevice import android.hardware.camera2.CaptureRequest import android.net.Uri import android.os.Handler import android.util.Log import android.view.Surface import android.widget.Toast import cn.dianbobo.dbb.util.HLog import com.wangyiheng.vcamsx.data.models.VideoStatues import com.wangyiheng.vcamsx.utils.InfoManager import com.wangyiheng.vcamsx.utils.VideoToFrames import de.robv.android.xposed.* import de.robv.android.xposed.callbacks.XC_LoadPackage import kotlinx.coroutines.* import tv.danmaku.ijk.media.player.IjkMediaPlayer import java.util.* class MainHook : IXposedHookLoadPackage { private var c2_builder: CaptureRequest.Builder? = null val TAG = "vcamsx" var cameraCallbackClass: Class<*>? = null var hw_decode_obj: VideoToFrames? = null private var ijkMediaPlayer: IjkMediaPlayer? = null private var TheOnlyPlayer: IjkMediaPlayer? = null private var origin_preview_camera: Camera? = null private var fake_SurfaceTexture: SurfaceTexture? = null private var isplaying: Boolean = false private var videoStatus: VideoStatues? = null private var infoManager : InfoManager?= null private var context: Context? = null private var original_preview_Surface: Surface? = null private var original_c1_preview_SurfaceTexture:SurfaceTexture? = null var cameraOnpreviewframe: Camera? = null private var c2_virtual_surface: Surface? = null private var c2_state_callback_class: Class<*>? = null private var c2_state_callback: CameraDevice.StateCallback? = null // Xposed模块中 override fun handleLoadPackage(lpparam: XC_LoadPackage.LoadPackageParam) { if(lpparam.packageName == "com.wangyiheng.vcamsx"){ return } //获取context XposedHelpers.findAndHookMethod( "android.app.Instrumentation", lpparam.classLoader, "callApplicationOnCreate", Application::class.java, object : XC_MethodHook() { override fun afterHookedMethod(param: MethodHookParam?) { if (param!!.args[0] is Application) { val application = param.args[0] as? Application ?: return val applicationContext = application.applicationContext if (context == applicationContext) return try { context = applicationContext initStatus() if(!lpparam.processName.contains(":")){ if(ijkMediaPlayer == null){ if(videoStatus?.isLiveStreamingEnabled == true){ initRTMPStream() }else if(videoStatus?.isVideoEnable == true){ initIjkPlayer() } } } } catch (ee: Exception) { HLog.d("VCAMSX", "$ee") } } } }) // 支持bilibili摄像头替换 XposedHelpers.findAndHookMethod("android.hardware.Camera", lpparam.classLoader, "setPreviewTexture", SurfaceTexture::class.java, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { if (param.args[0] == null) { return } if (param.args[0] == fake_SurfaceTexture) { return } if (origin_preview_camera != null && origin_preview_camera == param.thisObject) { param.args[0] = fake_SurfaceTexture return } origin_preview_camera = param.thisObject as Camera original_c1_preview_SurfaceTexture = param.args[0] as SurfaceTexture fake_SurfaceTexture = if (fake_SurfaceTexture == null) { SurfaceTexture(10) } else { fake_SurfaceTexture!!.release() SurfaceTexture(10) } param.args[0] = fake_SurfaceTexture } }) XposedHelpers.findAndHookMethod("android.hardware.Camera", lpparam.classLoader, "startPreview", object : XC_MethodHook() { override fun beforeHookedMethod(param: MethodHookParam?) { if(ijkMediaPlayer == null || !ijkMediaPlayer!!.isPlayable){ if(videoStatus?.isLiveStreamingEnabled == true){ initRTMPStream() }else if(videoStatus?.isVideoEnable == true){ initIjkPlayer() } } TheOnlyPlayer = ijkMediaPlayer c1_camera_play() } }) // XposedHelpers.findAndHookMethod( // "android.hardware.Camera", // lpparam.classLoader, // "setPreviewCallbackWithBuffer", // Camera.PreviewCallback::class.java, // object : XC_MethodHook() { // @Throws(Throwable::class) // override fun beforeHookedMethod(param: MethodHookParam) { // if (param.args[0] != null) { // process_callback(param) // } // } // } // ) XposedHelpers.findAndHookMethod( "android.hardware.camera2.CameraManager", lpparam.classLoader, "openCamera", String::class.java, CameraDevice.StateCallback::class.java, Handler::class.java, object : XC_MethodHook() { @Throws(Throwable::class) override fun afterHookedMethod(param: MethodHookParam) { try { if(param.args[1] == null){ return } if(param.args[1] == c2_state_callback){ return } c2_state_callback = param.args[1] as CameraDevice.StateCallback c2_state_callback_class = param.args[1]?.javaClass process_camera2_init(c2_state_callback_class as Class<Any>?,lpparam) }catch (e:Exception){ HLog.d("android.hardware.camera2.CameraManager报错了", "openCamera") } } }) } // private fun process_callback(param: XC_MethodHook.MethodHookParam) { // val previewCbClass = param.args[0].javaClass // // XposedHelpers.findAndHookMethod(previewCbClass, "onPreviewFrame", ByteArray::class.java, Camera::class.java, object : XC_MethodHook() { // @Throws(Throwable::class) // override fun beforeHookedMethod(paramd: MethodHookParam) { // // val localCam = paramd.args[1] as Camera // if (localCam == cameraOnpreviewframe) { // System.arraycopy(data_buffer, 0, paramd.args[0], 0, Math.min(data_buffer.size, (paramd.args[0] as ByteArray).size)) // } else { // cameraCallbackClass = previewCbClass // cameraOnpreviewframe = paramd.args[1] as Camera // // hw_decode_obj?.stopDecode() // hw_decode_obj = VideoToFrames() // hw_decode_obj!!.setSaveFrames(OutputImageFormat.NV21) // hw_decode_obj!!.decode("/storage/emulated/0/Android/data/com.smile.gifmaker/files/Camera1/virtual.mp4") // // System.arraycopy(data_buffer, 0, paramd.args[0], 0, Math.min(data_buffer.size, (paramd.args[0] as ByteArray).size)) // } // } // }) // } fun initStatus(){ infoManager = InfoManager(context!!) videoStatus = infoManager!!.getVideoStatus() } private fun process_camera2_init(c2StateCallbackClass: Class<Any>?, lpparam: XC_LoadPackage.LoadPackageParam) { XposedHelpers.findAndHookMethod(c2StateCallbackClass, "onOpened", CameraDevice::class.java, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { original_preview_Surface = null } }) XposedHelpers.findAndHookMethod("android.hardware.camera2.CaptureRequest.Builder", lpparam.classLoader, "addTarget", android.view.Surface::class.java, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { if (param.args[0] != null) { if(param.args[0] == c2_virtual_surface)return val surfaceInfo = param.args[0].toString() if (!surfaceInfo.contains("Surface(name=null)")) { if(original_preview_Surface != param.args[0] as Surface ){ original_preview_Surface = param.args[0] as Surface } } } } }) XposedHelpers.findAndHookMethod("android.hardware.camera2.CaptureRequest.Builder", lpparam.classLoader, "build",object :XC_MethodHook(){ @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { if(param.thisObject != null && param.thisObject != c2_builder){ c2_builder = param.thisObject as CaptureRequest.Builder if(ijkMediaPlayer == null || !ijkMediaPlayer!!.isPlayable){ if(videoStatus?.isLiveStreamingEnabled == true){ initRTMPStream() }else if(videoStatus?.isVideoEnable == true){ initIjkPlayer() } } TheOnlyPlayer = ijkMediaPlayer process_camera_play() } } }) XposedHelpers.findAndHookMethod(c2StateCallbackClass, "onDisconnected",CameraDevice::class.java, object : XC_MethodHook() { @Throws(Throwable::class) override fun beforeHookedMethod(param: MethodHookParam) { original_preview_Surface = null } }) } fun process_camera_play() { ijkplay_play() } fun initIjkPlayer(){ if(ijkMediaPlayer == null){ ijkMediaPlayer = IjkMediaPlayer() ijkMediaPlayer!!.setVolume(0F, 0F) // 设置音量为0 // 设置解码方式为软解码 if (videoStatus != null) { val codecType = videoStatus!!.codecType val mediaCodecOption = if (codecType) 1L else 0L // 将 Int 转换为 Long ijkMediaPlayer?.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", mediaCodecOption) } ijkMediaPlayer!!.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probsize", 4096) ijkMediaPlayer!!.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "max-buffer-size", 8192) ijkMediaPlayer!!.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1) ijkMediaPlayer!!.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0) ijkMediaPlayer!!.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", 2) ijkMediaPlayer!!.setOnPreparedListener { ijkMediaPlayer!!.isLooping= true if(original_preview_Surface != null){ ijkMediaPlayer!!.setSurface(original_preview_Surface) } ijkMediaPlayer!!.start() } ijkMediaPlayer!!.setOnCompletionListener { if(ijkMediaPlayer != TheOnlyPlayer){ ijkMediaPlayer!!.release() ijkMediaPlayer = null }else{ playNextVideo() } } ijkMediaPlayer!!.setOnErrorListener { mp, what, extra -> ijkMediaPlayer!!.stop() true // 返回true表示已处理错误,返回false表示未处理错误 } val videoUrl ="content://com.wangyiheng.vcamsx.videoprovider" ijkMediaPlayer!!.setDataSource(context, Uri.parse(videoUrl)) ijkMediaPlayer!!.prepareAsync() } } fun initRTMPStream() { ijkMediaPlayer = IjkMediaPlayer().apply { try { // 硬件解码设置,0为软解,1为硬解 setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 0) setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 1) setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 1) // 缓冲设置 setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_clear", 1) setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 0) setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec_mpeg4", 1) setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "analyzemaxduration", 100L) setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "probesize", 1024L) setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "flush_packets", 1L) setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 1L) setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1L) // 错误监听器 setOnErrorListener { _, what, extra -> Log.e("IjkMediaPlayer", "Error occurred. What: $what, Extra: $extra") Toast.makeText(context, "直播接收失败$what", Toast.LENGTH_SHORT).show() true } // 信息监听器 setOnInfoListener { _, what, extra -> Log.i("IjkMediaPlayer", "Info received. What: $what, Extra: $extra") true } // 设置 RTMP 流的 URL dataSource = videoStatus!!.liveURL // 异步准备播放器 prepareAsync() // 当播放器准备好后,开始播放 setOnPreparedListener { Log.d("vcamsx","onPrepared直播推流开始") if(original_preview_Surface != null){ ijkMediaPlayer!!.setSurface(original_preview_Surface) } Toast.makeText(context, "直播接收成功,可以进行投屏", Toast.LENGTH_SHORT).show() start() } } catch (e: Exception) { Log.d("vcamsx","$e") } } } private fun playNextVideo() { try { ijkMediaPlayer!!.reset() val videoUrl ="content://com.wangyiheng.vcamsx.videoprovider" ijkMediaPlayer!!.setDataSource(context, Uri.parse(videoUrl)) ijkMediaPlayer!!.setSurface(original_preview_Surface) ijkMediaPlayer!!.prepareAsync() } catch (e: Exception) { e.printStackTrace() } } private fun handleMediaPlayer(surface: Surface) { try { initStatus() videoStatus?.let { status -> val volume = if (status.isVideoEnable && status.volume) 1F else 0F ijkMediaPlayer?.setVolume(volume, volume) if (status.isVideoEnable || status.isLiveStreamingEnabled) { ijkMediaPlayer?.setSurface(surface) } } } catch (e: Exception) { e.printStackTrace() } } fun ijkplay_play() { original_preview_Surface?.let { surface -> handleMediaPlayer(surface) } } private fun c1_camera_play() { if (original_c1_preview_SurfaceTexture != null && videoStatus?.isVideoEnable == true) { original_preview_Surface = Surface(original_c1_preview_SurfaceTexture) if(original_preview_Surface!!.isValid == true){ handleMediaPlayer(original_preview_Surface!!) } } } companion object { @Volatile var data_buffer = byteArrayOf(0) } }
3
Kotlin
15
89
c41beb5e86a9faad902789dd50d97d5652ad71bd
16,704
com.wangyiheng.vcamsx
MIT License
app/src/main/java/org/oppia/app/home/recentlyplayed/RecentlyPlayedFragment.kt
PrarabdhGarg
234,525,485
true
{"Kotlin": 1593533}
package org.oppia.app.home.recentlyplayed import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import org.oppia.app.fragment.InjectableFragment import org.oppia.app.model.PromotedStory import javax.inject.Inject /** Fragment that contains all recently played stories. */ class RecentlyPlayedFragment : InjectableFragment(), OngoingStoryClickListener { @Inject lateinit var recentlyPlayedFragmentPresenter: RecentlyPlayedFragmentPresenter override fun onAttach(context: Context) { super.onAttach(context) fragmentComponent.inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return recentlyPlayedFragmentPresenter.handleCreateView(inflater, container) } override fun onOngoingStoryClicked(promotedStory: PromotedStory) { recentlyPlayedFragmentPresenter.onOngoingStoryClicked(promotedStory) } }
0
Kotlin
0
0
71077d462b6593ea7921e6e6558b44e29e5da851
997
oppia-android
Apache License 2.0
src/main/kotlin/org/vitrivr/cottontail/database/entity/EntityTransaction.kt
frankier
278,349,990
true
{"Kotlin": 1020644, "Dockerfile": 280}
package org.vitrivr.cottontail.database.entity import org.vitrivr.cottontail.database.general.Transaction import org.vitrivr.cottontail.database.index.Index import org.vitrivr.cottontail.database.index.IndexTransaction import org.vitrivr.cottontail.database.index.IndexType import org.vitrivr.cottontail.model.basics.* import org.vitrivr.cottontail.utilities.name.Name /** * A [Transaction] that operates on a single [Index]. [Transaction]s are a unit of isolation for data operations (read/write). * * @author <NAME> * @version 1.1 */ interface EntityTransaction : Transaction, Filterable, Scanable, Countable, Deletable { /** * Returns a collection of all the [IndexTransaction] available to this [EntityTransaction]. * * @return Collection of [IndexTransaction]s. May be empty. */ fun indexes(): Collection<IndexTransaction> /** * Returns a collection of all the [IndexTransaction] available to this [EntityTransaction], that match the given [ColumnDef] and [IndexType] constraint. * * @param columns The list of [ColumnDef] that should be handled by this [IndexTransaction]. * @param type The (optional) [IndexType]. If ommitted, [IndexTransaction]s of any type are returned. * * @return Collection of [IndexTransaction]s. May be empty. */ fun indexes(columns: Array<ColumnDef<*>>? = null, type: IndexType? = null): Collection<IndexTransaction> /** * Returns the [IndexTransaction] for the given [Name] or null, if such a [IndexTransaction] doesn't exist. * * @param name The [Name] of the [Index] the [IndexTransaction] belongs to. * @return Optional [IndexTransaction] */ fun index(name: Name): IndexTransaction? }
0
Kotlin
0
0
e4ec66eaf014bb8ea4399cc7ea54062f16cf0c60
1,733
cottontaildb
MIT License
day_07/src/main/kotlin/io/github/zebalu/advent2020/BagRuleReader.kt
zebalu
317,448,231
false
null
package io.github.zebalu.advent2020 typealias Rules = Map<String, Set<Pair<Int, String>>> object BagRuleReader { fun readRules(lines: List<String>): Rules { val result = mutableMapOf<String, MutableSet<Pair<Int, String>>>() lines.forEach { line -> val parts = line.split(" bags contain ") val type = parts[0] parts[1].split(", ").map { s -> s.split(" bag")[0] }.forEach { bag -> val split = bag.split(" ") if (split.size != 2 && split.size != 3) { throw IllegalStateException("split is not 2 or 3 long: " + split) } val count = if ("no".equals(split[0])) 0 else split[0].toInt() val bagName = if (count == 0) "no other" else split[1] + " " + split[2] result.computeIfAbsent(type, { _ -> mutableSetOf<Pair<Int, String>>() }).add(Pair(count, bagName)) } } return result } fun countWaysToShinyGold(rules: Map<String, Set<Pair<Int, String>>>) = rules.keys.count { name -> (!("shiny gold".equals(name))) && isThereWayToShinyGold( name, rules, setOf(name) ) } fun countContentInShinyGold(rules: Rules) = countContent("shiny gold", rules) private fun countContent(name: String, rules: Rules): Int { return rules.get(name)?.map { pair -> pair.first + pair.first * countContent(pair.second, rules) }?.sum() ?: 0 } private fun isThereWayToShinyGold(name: String, rules: Rules, visited: Set<String>): Boolean { if ("shiny gold".equals(name)) { return true } val col = rules.get(name)?.map { pair -> if (pair.first == 0) false else if ("shiny gold".equals(pair.second)) true else if (visited.contains(pair.second)) false else isThereWayToShinyGold( pair.second, rules, visited + pair.second ) } return if (col == null || col.isEmpty()) false else col.reduce { acc, next -> acc || next } } }
0
Kotlin
0
1
ca54c64a07755ba044440832ba4abaa7105cdd6e
1,813
advent2020
Apache License 2.0
meistercharts-history/meistercharts-history-core/src/commonMain/kotlin/com/meistercharts/history/impl/io/RelativeHistoryValues.kt
Neckar-IT
599,079,962
false
null
/** * Copyright 2023 Neckar IT GmbH, Mössingen, Germany * * 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 com.meistercharts.history.impl.io import com.meistercharts.history.impl.HistoryValues import it.neckar.open.collections.DoubleArray2 import it.neckar.open.collections.IntArray2 import it.neckar.open.kotlin.serializers.DoubleArray2Serializer import it.neckar.open.kotlin.serializers.IntArray2Serializer import kotlinx.serialization.Serializable /** * Contains *RELATIVE* history values. * * This is an optimized variant of [HistoryValues]. * Only the first value for each data series is absolute. All other values are relative to that one * * Should not be used directly. Instead, convert to absolute [#makeAbsolute]. * */ @Deprecated("Do not use anymore, does not make sense") @Serializable() class RelativeHistoryValues( val decimalValues: @Serializable(with = DoubleArray2Serializer::class) DoubleArray2, val enumValues: @Serializable(with = IntArray2Serializer::class) IntArray2, val referenceEntryHistoryValues: @Serializable(with = IntArray2Serializer::class) IntArray2, ) { init { //TODO improve require - also check referenceEntryHistoryValues require(enumValues.isEmpty || decimalValues.isEmpty || decimalValues.height == enumValues.height) { "Different timestampCounts. Significant: ${decimalValues.height} - enumValues: ${enumValues.height}" } } /** * The amount of data series */ val decimalsDataSeriesCount: Int get() { return decimalValues.width } val enumsDataSeriesCount: Int get() { return enumValues.width } val timeStampsCount: Int get() { //Same as enum values height return decimalValues.height } /** * Returns the absolute history values */ @Deprecated("no longer needed, serialize directly") fun makeAbsolute(): HistoryValues { val absoluteSignificantValues: DoubleArray2 = decimalValues.makeAbsolute() val absoluteEnumValues: IntArray2 = enumValues.makeAbsolute() val referenceEntryHistoryValues: IntArray2 = referenceEntryHistoryValues.makeAbsolute() TODO("not implemented yet!") //return HistoryValues(absoluteSignificantValues, absoluteEnumValues, referenceEntryHistoryValues, ) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as RelativeHistoryValues if (decimalValues != other.decimalValues) { return false } if (enumValues != other.enumValues) { return false } return referenceEntryHistoryValues == other.referenceEntryHistoryValues } override fun hashCode(): Int { var result = decimalValues.hashCode() result = 31 * result + enumValues.hashCode() result = 30 * result + referenceEntryHistoryValues.hashCode() return result } } /** * Converts the int array to an int array with relative values */ fun IntArray2.makeAbsolute(): IntArray2 { if (width == 0 || height == 0) { return IntArray2(width, height, 0) } val absolute = IntArray2(width, height, 0) //Iterate over cols first - we want to calculate relative values for each data series for (x in 0 until this.width) { //copy the first entry absolute[x, 0] = this[x, 0] for (y in 1 until this.height) { val previous = absolute[x, y - 1] //read the previous *absolute* value val current = this[x, y] val absoluteValue = current + previous absolute[x, y] = absoluteValue } } return absolute } fun DoubleArray2.makeAbsolute(): DoubleArray2 { if (width == 0 || height == 0) { return DoubleArray2(width, height, 0.0) } val absolute = DoubleArray2(width, height, 0.0) //Iterate over cols first - we want to calculate relative values for each data series for (x in 0 until this.width) { //copy the first entry absolute[x, 0] = this[x, 0] for (y in 1 until this.height) { val previous = absolute[x, y - 1] //read the previous *absolute* value val current = this[x, y] val absoluteValue = current + previous absolute[x, y] = absoluteValue } } return absolute } /** * Creates a relative history values object */ @Deprecated("No longer required") fun HistoryValues.makeRelative(): RelativeHistoryValues { return RelativeHistoryValues( decimalHistoryValues.values.makeRelative(), enumHistoryValues.values.makeRelative(), referenceEntryHistoryValues.values.makeRelative(), ) } /** * Returns a copy with relative values (relative to the previous value) */ fun IntArray2.makeRelative(): IntArray2 { if (width == 0 || height == 0) { return IntArray2(width, height, 0) } val relative = IntArray2(width, height, 0) //Iterate over cols first - we want to calculate relative values for each data series for (x in 0 until this.width) { //copy the first entry relative[x, 0] = this[x, 0] for (y in 1 until this.height) { val previous = this[x, y - 1] val current = this[x, y] val delta = current - previous relative[x, y] = delta } } return relative } fun DoubleArray2.makeRelative(): DoubleArray2 { if (width == 0 || height == 0) { return DoubleArray2(width, height, 0.0) } val relative = DoubleArray2(width, height, 0.0) //Iterate over cols first - we want to calculate relative values for each data series for (x in 0 until this.width) { //copy the first entry relative[x, 0] = this[x, 0] for (y in 1 until this.height) { val previous = this[x, y - 1] val current = this[x, y] val delta = current - previous relative[x, y] = delta } } return relative }
0
Kotlin
0
4
af73f0e09e3e7ac9437240e19974d0b1ebc2f93c
6,231
meistercharts
Apache License 2.0
amani-sdk-v1/src/main/kotlin/ai/amani/sdk/presentation/home_kyc/HomeKYCState.kt
AMANI-AI-ORG
644,307,729
false
{"Kotlin": 193827}
package ai.amani.sdk.presentation.home_kyc /** * @Author: zekiamani * @Date: 6.09.2022 */ sealed class HomeKYCState { object Loading : HomeKYCState() object Loaded: HomeKYCState() data class Error(var httpsErrorCode: Int = 0) : HomeKYCState() }
0
Kotlin
0
0
24e3af74423bcfdcd911a995d849168d9a11d5e6
267
Android.SDK.UI
MIT License
android/measure/src/main/java/sh/measure/android/events/Attachment.kt
measure-sh
676,897,841
false
{"Kotlin": 890104, "Go": 615450, "Swift": 379937, "TypeScript": 350495, "Shell": 26060, "Objective-C": 17998, "C": 9958, "Python": 7639, "Lua": 1206, "JavaScript": 1053, "CMake": 479, "CSS": 461, "C++": 445}
package sh.measure.android.events import kotlinx.serialization.Serializable import kotlinx.serialization.Transient @Serializable internal class Attachment( /** * The name of the attachment, e.g. "screenshot.png". */ val name: String, /** * The type of the attachment. See [AttachmentType] for the list of attachment types. */ val type: String, /** * An optional byte array representing the attachment. */ @Transient val bytes: ByteArray? = null, /** * An optional path to the attachment. */ @Transient val path: String? = null, ) { init { require(bytes != null || path != null) { "Failed to create Attachment. Either bytes or path must be provided" } require(bytes == null || path == null) { "Failed to create Attachment. Only one of bytes or path must be provided" } } }
75
Kotlin
25
484
86b1a2363fcb9abd876151dacc4f9fa15fc1f7ba
922
measure
Apache License 2.0
TeamCode/src/main/kotlin/Cart.kt
Eeshwar-Krishnan
527,795,954
false
{"Kotlin": 51032, "Java": 42525}
abstract class Cart(var p8 : Pico8) { abstract fun map_data(): String abstract fun flag_data(): String abstract fun init() abstract fun update() abstract fun draw() }
0
Kotlin
1
5
bcb9310464b252443890ea7c9e3466551150eff8
188
CelesteClassicFTC
BSD 3-Clause Clear License
app/src/main/java/bapspatil/captainchef/sync/RecipeWidgetRemoteViewsService.kt
bapspatil
105,727,452
false
null
package bapspatil.captainchef.sync import android.content.Context import android.content.Intent import android.widget.RemoteViews import android.widget.RemoteViewsService import bapspatil.captainchef.R import bapspatil.captainchef.model.Ingredient import java.util.* /** * Created by bapspatil */ class RecipeWidgetRemoteViewsService : RemoteViewsService() { internal var remoteIngredientsList: ArrayList<Ingredient>? = null override fun onGetViewFactory(intent: Intent): RemoteViewsService.RemoteViewsFactory { return RecipeWidgetRemoteViewsFactory(this.applicationContext, intent) } inner class RecipeWidgetRemoteViewsFactory(internal var mContext: Context, intent: Intent) : RemoteViewsService.RemoteViewsFactory { override fun onCreate() { } override fun onDataSetChanged() { remoteIngredientsList = RecipeWidgetProvider.Companion.ingredientArrayList } override fun onDestroy() { } override fun getCount(): Int { return if (remoteIngredientsList == null) 0 else remoteIngredientsList!!.size } override fun getViewAt(i: Int): RemoteViews { // Construct the RemoteViews for the individual ingredient list item val views = RemoteViews(mContext.packageName, R.layout.recipe_widget_list_item_view) // Set the TextView in the layout of those individual ingredient list items views.setTextViewText(R.id.widget_ingredients_text_view, remoteIngredientsList!![i].ingredientName + "\n\t\t\tQuantity: " + remoteIngredientsList!![i].quant + " " + remoteIngredientsList!![i].measuredWith) // Return the RemoteViews return views } override fun getLoadingView(): RemoteViews? { return null } override fun getViewTypeCount(): Int { return 1 } override fun getItemId(position: Int): Long { return position.toLong() } override fun hasStableIds(): Boolean { return true } } }
1
Kotlin
0
10
2ecdd8e3d13a9f434d1649d0cd55c91c1c2db78a
2,139
CaptainChef
Apache License 2.0
app/src/test/kotlin/com/jamjaws/adventofcode/xxiii/day/Day05Test.kt
JamJaws
725,792,497
false
{"Kotlin": 30656}
package com.jamjaws.adventofcode.xxiii.day import com.jamjaws.adventofcode.xxiii.readInput import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test class Day05Test { private val text = readInput("example/Day05") @Test fun part1() { Day05().part1(text) shouldBe 35 } @Test fun part2() { Day05().part2(text) shouldBe 46 } }
0
Kotlin
0
0
e2683305d762e3d96500d7268e617891fa397e9b
384
advent-of-code-2023
MIT License
felles/src/main/kotlin/no/nav/familie/kontrakter/felles/dokdistkanal/DokdistkanalRequest.kt
navikt
206,793,193
false
{"Kotlin": 268541}
package no.nav.familie.kontrakter.felles.dokdistkanal import no.nav.familie.kontrakter.felles.PersonIdent data class DokdistkanalRequest( val bruker: PersonIdent, val mottaker: PersonIdent, val dokumenttypeId: String? = null, val erArkivert: Boolean? = null, val forsendelseStørrelseIMegabytes: Int? = null, )
1
Kotlin
0
2
fd2cae7cc0d8617384440a78bab948e558fcc69b
332
familie-kontrakter
MIT License
rssparser/src/test/java/com/prof/rssparser/core/CoreXMLParserItemChannelImageTest.kt
prof18
61,429,036
false
null
/* * Copyright 2019 Marco Gomiero * * 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 com.prof.rssparser.core import com.prof.rssparser.Image import com.prof.rssparser.testutils.BaseCoreXMLParserTest class CoreXMLParserItemChannelImageTest : BaseCoreXMLParserTest( feedPath = "/feed-item-channel-image.xml", channelTitle = "www.espn.com - TOP", channelLink = "https://www.espn.com", channelDescription = "Latest TOP news from www.espn.com", channelImage = Image( title = "www.espn.com - TOP", url = "https://a.espncdn.com/i/espn/teamlogos/lrg/trans/espn_dotcom_black.gif", link = "https://www.espn.com", description = null, ), channelLastBuildDate = "Fri, 7 May 2021 18:43:18 GMT", articleGuid = "31393791", articleTitle = "Inside the mysterious world of missing sports memorabilia", articleLink = "https://www.espn.com/mlb/story/_/id/31393791/inside-mysterious-world-missing-sports-memorabilia", articlePubDate = "Fri, 7 May 2021 10:44:02 EST", articleDescription = "Some of the most treasured pieces of sports memorabilia are missing, can't be authenticated or... currently reside on the moon. A look at those mysterious historic items -- and what they'd be worth in a red-hot sports memorabilia market.", articleImage = "https://a.espncdn.com/photo/2021/0506/r850492_1296x1296_1-1.jpg", )
2
Kotlin
118
403
686eb4194dd5496bedca002a8194378b84e6115b
1,906
RSS-Parser
Apache License 2.0
ktaf/src/test/kotlin/com/github/benpollarduk/ktaf/command/game/ExamineTest.kt
benpollarduk
696,256,399
false
{"Kotlin": 531898, "JavaScript": 486, "HTML": 346, "CSS": 343}
package com.github.benpollarduk.ktaf.command.game import com.github.benpollarduk.ktaf.assets.Item import com.github.benpollarduk.ktaf.assets.interaction.ReactionResult import com.github.benpollarduk.ktaf.commands.game.Examine import com.github.benpollarduk.ktaf.logic.GameTestHelper import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class ExamineTest { @Test fun `given null item when invoke then return error`() { // Given val command = Examine(null) // When val result = command.invoke(GameTestHelper.getBlankGame()) // Then Assertions.assertEquals(ReactionResult.ERROR, result.result) } @Test fun `given valid game when invoke then return ok`() { // Given val command = Examine(Item("", "")) // When val result = command.invoke(GameTestHelper.getBlankGame()) // Then Assertions.assertEquals(ReactionResult.OK, result.result) } }
1
Kotlin
0
9
1b865af8f8d207c3c4505647e88cca0d281869b0
983
ktaf
MIT License