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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/csperandio/dependencies/files/FileFinder.kt
|
lolo101
| 366,496,744
| true
|
{"Kotlin": 20826}
|
package csperandio.dependencies.files
import java.io.File
class FileFinder(private val rootDir: File) {
fun all(fileName: String): List<File> {
return rootDir.walk().filter { it.isFile && it.name == fileName }.toList()
}
}
| 0
|
Kotlin
|
0
| 0
|
c20f9df48bbe5e37172704f05b6be0bace2914d0
| 240
|
check-dependencies
|
MIT License
|
app/src/main/java/com/spit/tph/nike_mvp/IPresenter.kt
|
edcedc
| 761,522,515
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "JSON": 3, "Proguard": 2, "XML": 113, "Java": 294, "Kotlin": 32}
|
package com.csl.ams.nike_mvp
/**
* User: Nike
* 2024/1/15 09:42
*/
interface IPresenter<in V: IBaseView> {
fun init(mRootView: V)
}
| 0
|
Java
|
0
| 0
|
2945055ad6e48f201c38348f574919ecc0e56d55
| 142
|
NEWTPH
|
MIT License
|
rd-core/rd-core-jvm/src/test/kotlin/com/jetbrains/rider/util/test/cases/BackgroundSchedulerTest.kt
|
kjellski
| 147,781,181
| true
|
{"Kotlin": 579409}
|
package com.jetbrains.rider.util.test.cases
import com.jetbrains.rider.util.Closeable
import com.jetbrains.rider.util.ILoggerFactory
import com.jetbrains.rider.util.Statics
import com.jetbrains.rider.util.log.ErrorAccumulatorLoggerFactory
import com.jetbrains.rider.util.threading.TestSingleThreadScheduler
import org.junit.After
import org.junit.Before
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class BackgroundSchedulerTest {
private lateinit var disposeLoggerFactory: Closeable
@Before
fun setup() {
val statics = Statics<ILoggerFactory>()
disposeLoggerFactory = statics.push(ErrorAccumulatorLoggerFactory)
}
@After
fun tearDown() {
disposeLoggerFactory.close()
}
@Test
fun test0() {
val s = TestSingleThreadScheduler("test")
assertFalse { s.isActive }
assertFails { s.assertThread() }
var tasksExecuted : Int = 0
s.queue {
Thread.sleep(100)
tasksExecuted++
}
s.queue {
tasksExecuted++
s.assertThread()
}
assertEquals(0, tasksExecuted)
s.assertNoExceptions()
assertEquals(2, tasksExecuted)
s.queue {
throw IllegalStateException()
}
s.queue {
tasksExecuted++
}
assertFails { s.assertNoExceptions() }
assertTrue("x == 3", { tasksExecuted == 3 })
}
}
| 0
|
Kotlin
|
0
| 0
|
0eaa82803db30efec5b832bf660f511f6e205ca0
| 1,541
|
rd
|
Apache License 2.0
|
adk/reduction_gatt_connection/Android/connectableDevice.kt
|
forrestan
| 399,789,055
| true
|
{"C": 1311640, "C++": 899092, "Objective-C": 36107, "Makefile": 15256, "Kotlin": 2598, "Swift": 2145, "Shell": 1488}
|
var bluetoothGatt: BluetoothGatt? = null
var refreshGattServicesCallback: RefreshGattServicesCallback? = null
lateinit var bluetoothGattCallback: BluetoothGattCallback
...
bluetoothGattCallback = object : BluetoothGattCallback() {
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
...
if (status == BluetoothGatt.GATT_SUCCESS) {
refreshGattServicesCallback?.onSuccess()
} else {
refreshGattServicesCallback?.onFail()
}
refreshGattServicesCallback = null
...
}
}
...
override fun refreshGattServices(refreshGattServicesCallback: RefreshGattServicesCallback) {
if (refreshDeviceCache()) {
this.refreshGattServicesCallback = refreshGattServicesCallback
bluetoothGatt!!.discoverServices(bluetoothGatt)
} else {
refreshGattServicesCallback.onFail()
}
}
...
fun refreshDeviceCache(): Boolean {
var result = false
try {
val refreshMethod: Method = bluetoothGatt!!.javaClass.getMethod("refresh")
result = refreshMethod.invoke(bluetoothGatt!!, *arrayOfNulls(0)) as? Boolean ?: false
} catch (exception: Exception) {
}
return result
}
| 0
| null |
0
| 1
|
1d26565e41d2d59fb1c3417f4ae4646541b77a6d
| 1,207
|
bluetooth_mesh_stack_features
|
zlib License
|
buildSrc/src/main/java/com/pp/ppcompose/buildsrc/Dependencies.kt
|
pauloaapereira
| 517,433,807
| false
|
{"Kotlin": 414514}
|
package com.pp.ppcompose.buildsrc
object Configs {
const val CompileSdkVersion = 32
const val MinSdkVersion = 26
const val TargetSdkVersion = 32
const val VersionCode = 1
const val VersionName = "1.0"
}
object ClassPaths {
const val gradlePlugin = "com.android.tools.build:gradle:7.2.1"
const val kotlinPlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.0"
}
object Compose {
const val composeVersion = "1.3.0-alpha01"
const val animation = "androidx.compose.animation:animation:$composeVersion"
const val iconsExtended = "androidx.compose.material:material-icons-extended:$composeVersion"
const val material = "androidx.compose.material:material:$composeVersion"
const val runtime = "androidx.compose.runtime:runtime:$composeVersion"
const val tooling = "androidx.compose.ui:ui-tooling:$composeVersion"
const val ui = "androidx.compose.ui:ui:$composeVersion"
const val uiUtil = "androidx.compose.ui:ui-util:$composeVersion"
const val uiTest = "androidx.compose.ui:ui-test-junit4:$composeVersion"
const val activityCompose = "androidx.activity:activity-compose:1.6.0-alpha05"
const val navigationCompose = "androidx.navigation:navigation-compose:2.5.0-alpha02"
const val hiltNavigation = "androidx.hilt:hilt-navigation-compose:1.0.0"
}
object Tests {
private const val junitVersion = "4.13.2"
private const val junitKtx = "1.1.4-alpha07"
const val junit = "junit:junit:$junitVersion"
const val junitKotlin = "androidx.test.ext:junit-ktx:$junitKtx"
}
object Core {
const val androidXCore = "androidx.core:core-ktx:1.9.0-alpha05"
const val appCompat = "androidx.appcompat:appcompat:1.6.0-alpha05"
const val material = "com.google.android.material:material:1.7.0-alpha03"
}
object Libs {
object Kotlin {
const val stdlib = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.0"
}
object Coroutines {
private const val version = "1.6.4"
const val core = "org.jetbrains.kotlinx:kotlinx-coroutines-core:$version"
const val android = "org.jetbrains.kotlinx:kotlinx-coroutines-android:$version"
const val test = "org.jetbrains.kotlinx:kotlinx-coroutines-test:$version"
}
object Lottie {
const val lottie = "com.airbnb.android:lottie-compose:5.2.0"
}
object Accompanist {
const val insets = "com.google.accompanist:accompanist-insets:0.24.13-rc"
}
object GoogleLocation {
const val location = "com.google.android.gms:play-services-location:20.0.0"
}
object Hilt {
private const val version = "2.43"
const val library = "com.google.dagger:hilt-android:$version"
const val googleAndroidCompiler = "com.google.dagger:hilt-android-compiler:$version"
const val googleCompiler = "com.google.dagger:hilt-compiler:$version"
const val testing = "com.google.dagger:hilt-android-testing:$version"
const val gradlePlugin = "com.google.dagger:hilt-android-gradle-plugin:$version"
}
object ImageProcessing {
private const val version = "2.1.0"
const val coil = "io.coil-kt:coil-compose:$version"
}
}
| 0
|
Kotlin
|
0
| 0
|
3acacdd970a20bb65a034a869dfaea8bf648a357
| 3,181
|
ViveAFesta
|
Apache License 2.0
|
src/test/kotlin/io/steinh/aoc/day01/TrebuchetTest.kt
|
daincredibleholg
| 726,426,347
| false
|
{"Kotlin": 14505}
|
package day01
import kotlin.test.Test
import kotlin.test.assertEquals
class TrebuchetTest {
val trebuchet = Trebuchet()
@Test
fun checkDemoInput() {
val input = {}.javaClass.classLoader?.getResource("day01/demo-input.txt")?.readText()?.lines()
val actual = trebuchet.calibrate(input!!)
assertEquals(actual, 142)
}
@Test
fun checkDemoInputPart2() {
val input = {}.javaClass.classLoader?.getResource("day01/demo-input-part2.txt")?.readText()?.lines()
val actual = trebuchet.calibrate(input!!)
assertEquals(actual, 281)
}
}
| 0
|
Kotlin
|
0
| 0
|
4aa7c684d0e337c257ae55a95b80f1cf388972a9
| 607
|
AdventOfCode2023
|
MIT License
|
app/src/main/java/cz/muni/fi/umimecesky/game/flappy/ConceptAdapter.kt
|
mareksabo
| 82,814,524
| false
| null |
/*
* Copyright (c) 2018 <NAME>
*
* 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 cz.muni.fi.umimecesky.game.flappy
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import cz.muni.fi.umimecesky.R
import cz.muni.fi.umimecesky.game.shared.model.RaceConcept
import cz.muni.fi.umimecesky.game.shared.util.GuiUtil.inflate
import cz.muni.fi.umimecesky.prefs
import kotlinx.android.synthetic.main.column_category_flappy.view.categoryName
import kotlinx.android.synthetic.main.column_category_flappy.view.highestScore
/**
* @author <NAME>
*/
class ConceptAdapter(concepts: List<RaceConcept>) :
RecyclerView.Adapter<ConceptAdapter.ConceptHolder>() {
private val concepts = concepts.toMutableList()
override fun getItemCount() = concepts.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConceptAdapter.ConceptHolder =
ConceptHolder(parent.inflate(R.layout.column_category_flappy, false))
override fun onBindViewHolder(holder: ConceptAdapter.ConceptHolder, position: Int) =
holder.bindConcept(concepts[position])
// workaround fixing not refreshing score bug
fun refreshAllItems() {
val list: List<RaceConcept> = concepts.toList()
concepts.clear()
concepts.addAll(list)
notifyDataSetChanged()
}
class ConceptHolder(private var v: View) : RecyclerView.ViewHolder(v), View.OnClickListener {
private var raceConcept: RaceConcept? = null
init {
v.setOnClickListener(this)
}
override fun onClick(v: View?) {
try {
FlappySettingsDialog(itemView.context, raceConcept)
} catch (ignored: IllegalArgumentException) {
}
}
fun bindConcept(raceConcept: RaceConcept) {
this.raceConcept = raceConcept
v.categoryName.text = raceConcept.name
v.highestScore.text = "${prefs.getBestScore(raceConcept)}"
}
}
}
| 1
|
Kotlin
|
0
| 4
|
488245ce33b0abace0d21a153ac44e348fd6d1f2
| 2,562
|
umimecesky
|
Apache License 2.0
|
app/src/main/java/com/kirillemets/flashcards/domain/model/DictionaryEntry.kt
|
KirillEmets
| 291,228,411
| false
| null |
package com.kirillemets.flashcards.domain.model
class DictionaryEntry(
val japanese: String,
val reading: String,
val englishMeanings: List<String>,
) {
val meaningsString: String
get() = englishMeanings.joinToString().take(50)
fun meaningString(id: Int) = (id + 1).toString() + ". " + englishMeanings[id]
}
| 3
|
Kotlin
|
0
| 1
|
271dadbb27b6adec52f3f5b57058027ca3325b0e
| 337
|
JpCards
|
MIT License
|
app/src/main/java/com/example/movieapp/ViewModel/MovieViewModel.kt
|
Danc-0
| 377,314,329
| false
| null |
package com.example.movieapp.ViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.movieapp.api.ApiService
import com.example.movieapp.data.datasource.ApiHelper
import com.example.movieapp.data.datasource.Resource
import com.example.movieapp.model.MoviesResponse
import com.example.movieapp.data.repository.MovieRepository
import com.example.movieapp.data.repository.MoviesRepository
import com.example.movieapp.model.MovieGenres
import com.example.movieapp.model.Result
import com.example.movieapp.paging.MoviePagingSource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MovieViewModel @Inject constructor(
private val repository: MovieRepository,
private val apiService: ApiService
) : ViewModel() {
val _myMovieResponse: MutableLiveData<Resource<MoviesResponse>> = MutableLiveData()
val _myMovieGenreResponse: MutableLiveData<Resource<MovieGenres>> = MutableLiveData()
val movieResponse: LiveData<Resource<MoviesResponse>>
get() = _myMovieResponse
val movieGenreResponse: LiveData<Resource<MovieGenres>>
get() = _myMovieGenreResponse
fun getMovie(apiKey: String): Flow<PagingData<Result>> {
return Pager(config = PagingConfig(
pageSize = 50,
enablePlaceholders = false,
prefetchDistance = 20
),
pagingSourceFactory = {
(MoviePagingSource(
apiService,
apiKey = apiKey
))
}).flow.cachedIn(viewModelScope)
}
fun getMoviesGenre() {
viewModelScope.launch {
_myMovieGenreResponse.value = Resource.Loading
_myMovieGenreResponse.value = repository.getMovieGenre("en-US")
}
}
fun getMovies() {
viewModelScope.launch {
_myMovieResponse.value = Resource.Loading
_myMovieResponse.value = repository.getMovies(1)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
45d4b4fe94ee22b2d71714cc28fb38a7f4ae2516
| 2,295
|
Movies
|
MIT License
|
composeApp/src/commonMain/kotlin/com/afapps/notificationSaver/presentation/features/splash/logo/NSaver.kt
|
alfayedoficial
| 869,041,201
| false
|
{"Kotlin": 126759, "Swift": 621}
|
/*
* Converted using https://composables.com/svgtocompose
*/
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.group
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
public val NSaver: ImageVector
get() {
if (_NSaver != null) {
return _NSaver!!
}
_NSaver = ImageVector.Builder(
name = "NSaver02",
defaultWidth = 366.5.dp,
defaultHeight = 306.6.dp,
viewportWidth = 366.5f,
viewportHeight = 306.6f
).apply {
group {
}
group {
group {
path(
fill = SolidColor(Color.Black),
fillAlpha = 1.0f,
stroke = null,
strokeAlpha = 1.0f,
strokeLineWidth = 1.0f,
strokeLineCap = StrokeCap.Butt,
strokeLineJoin = StrokeJoin.Miter,
strokeLineMiter = 1.0f,
pathFillType = PathFillType.NonZero
) {
moveTo(143.2f, 45.4f)
curveToRelative(00f, 1.80f, -0.80f, 4.20f, -2.20f, 70f)
curveToRelative(-1.80f, 3.70f, -2.90f, 5.90f, -3.20f, 6.80f)
curveToRelative(-4.80f, 15.20f, -7.20f, 27.60f, -7.20f, 37.30f)
lineToRelative(-0.8f, 71.9f)
curveToRelative(-0.20f, 7.30f, -1.80f, 14.90f, -50f, 22.50f)
curveToRelative(-4.20f, 9.70f, -9.30f, 14.50f, -15.50f, 14.50f)
curveToRelative(-9.20f, 00f, -18.20f, -7.70f, -27.20f, -230f)
curveToRelative(-6.50f, -11.30f, -13.10f, -270f, -19.70f, -470f)
curveToRelative(-3.80f, -130f, -7.80f, -260f, -11.80f, -390f)
curveToRelative(-3.50f, 28.30f, -5.20f, 47.30f, -5.20f, 570f)
curveToRelative(00f, 21.30f, 1.30f, 33.60f, 3.90f, 36.80f)
curveToRelative(2.60f, 3.20f, 3.90f, 5.50f, 3.90f, 70f)
curveToRelative(00f, 3.20f, -1.70f, 60f, -50f, 8.40f)
curveToRelative(-3.30f, 2.40f, -6.70f, 3.60f, -100f, 3.60f)
curveToRelative(-4.70f, 00f, -8.50f, -4.90f, -11.50f, -14.80f)
curveToRelative(-2.30f, -7.70f, -3.50f, -14.70f, -3.50f, -210f)
curveToRelative(00f, -2.80f, 0.10f, -70f, 0.20f, -12.60f)
curveToRelative(0.20f, -5.60f, 0.20f, -9.80f, 0.20f, -12.60f)
curveToRelative(00f, -6.80f, 0.80f, -170f, 2.50f, -30.50f)
curveToRelative(1.70f, -13.50f, 2.50f, -23.70f, 2.50f, -30.50f)
verticalLineTo(56.6f)
curveToRelative(00f, -0.30f, -0.10f, -0.80f, -0.40f, -1.50f)
curveToRelative(-0.20f, -0.70f, -0.40f, -1.20f, -0.40f, -1.50f)
curveToRelative(00f, -3.30f, 2.20f, -6.10f, 6.80f, -8.20f)
curveToRelative(3.70f, -1.80f, 7.30f, -2.80f, 110f, -2.80f)
curveToRelative(8.50f, 00f, 14.60f, 2.80f, 18.20f, 8.20f)
curveToRelative(10f, 1.80f, 1.90f, 5.70f, 2.70f, 11.50f)
curveToRelative(0.50f, 40f, 10f, 8.10f, 1.50f, 12.20f)
curveToRelative(20f, 11.80f, 7.20f, 30.80f, 15.80f, 570f)
curveToRelative(10.20f, 30.80f, 17.80f, 46.20f, 22.80f, 46.20f)
curveToRelative(1.80f, 00f, 2.80f, -2.30f, 2.80f, -70f)
curveToRelative(00f, -1.30f, -0.20f, -3.50f, -0.60f, -6.50f)
curveToRelative(-0.40f, -30f, -0.60f, -5.30f, -0.60f, -70f)
lineToRelative(2.5f, -67.9f)
curveToRelative(0.50f, -10.20f, 2.20f, -20.20f, 5.20f, -30.10f)
curveToRelative(4.30f, -13.90f, 10.20f, -20.80f, 17.50f, -20.80f)
curveToRelative(2.30f, 00f, 5.60f, 1.50f, 9.80f, 4.50f)
curveTo(143.10f, 440f, 143.20f, 44.70f, 143.20f, 45.40f)
close()
}
}
group(
scaleX = 2.81f,
scaleY = 2.81f,
translationX = 1.4065934065934016f,
translationY = 1.4065934065934016f,
pivotX = 0f,
pivotY = 0f,
) {
path(
fill = SolidColor(Color.Black),
fillAlpha = 1.0f,
stroke = null,
strokeAlpha = 1.0f,
strokeLineWidth = 1.0f,
strokeLineCap = StrokeCap.Butt,
strokeLineJoin = StrokeJoin.Miter,
strokeLineMiter = 1.0f,
pathFillType = PathFillType.NonZero
) {
moveTo(115.9f, 64.5f)
verticalLineTo(36.5f)
curveTo(115.90f, 180f, 100.90f, 30f, 82.40f, 30f)
lineToRelative(0f, 0f)
curveTo(63.90f, 30f, 48.90f, 180f, 48.90f, 36.50f)
verticalLineToRelative(28.1f)
curveToRelative(00f, 3.60f, -1.60f, 6.90f, -4.30f, 9.20f)
lineToRelative(0f, 0f)
curveToRelative(-2.70f, 2.30f, -4.30f, 5.70f, -4.30f, 9.20f)
lineToRelative(0f, 0f)
curveToRelative(00f, 2.10f, 1.70f, 3.90f, 3.90f, 3.90f)
horizontalLineToRelative(76.3f)
curveToRelative(2.10f, 00f, 3.90f, -1.70f, 3.90f, -3.90f)
lineToRelative(0f, 0f)
curveToRelative(00f, -3.60f, -1.60f, -6.90f, -4.30f, -9.20f)
lineToRelative(0f, 0f)
curveTo(117.40f, 71.40f, 115.90f, 68.10f, 115.90f, 64.50f)
close()
}
path(
fill = SolidColor(Color.Black),
fillAlpha = 1.0f,
stroke = null,
strokeAlpha = 1.0f,
strokeLineWidth = 1.0f,
strokeLineCap = StrokeCap.Butt,
strokeLineJoin = StrokeJoin.Miter,
strokeLineMiter = 1.0f,
pathFillType = PathFillType.NonZero
) {
moveTo(67.6f, 86.9f)
curveTo(67.60f, 86.90f, 67.60f, 86.90f, 67.60f, 86.90f)
curveToRelative(00f, 8.30f, 6.60f, 14.90f, 14.80f, 14.90f)
reflectiveCurveTo(97.2f, 95.1f, 97.2f, 87f)
curveToRelative(00f, 00f, 00f, -0.10f, 00f, -0.10f)
}
}
group {
path(
fill = SolidColor(Color.Black),
fillAlpha = 1.0f,
stroke = null,
strokeAlpha = 1.0f,
strokeLineWidth = 1.0f,
strokeLineCap = StrokeCap.Butt,
strokeLineJoin = StrokeJoin.Miter,
strokeLineMiter = 1.0f,
pathFillType = PathFillType.NonZero
) {
moveTo(264.1f, 93.1f)
lineTo(199.8f, 92.9f)
lineTo(198.3f, 93.2f)
lineTo(197.5f, 93.5f)
lineTo(196.6f, 94.3f)
lineTo(196.1f, 95.1f)
lineTo(196f, 95.8f)
lineTo(195.8f, 159.2f)
lineTo(196.2f, 160.7f)
lineTo(197f, 161.1f)
lineTo(197.8f, 161.5f)
lineTo(199.4f, 161.4f)
lineTo(200.9f, 161.2f)
lineTo(202.6f, 159.9f)
lineTo(229.3f, 137.5f)
lineTo(230.5f, 137.2f)
lineTo(231.3f, 137.6f)
lineTo(232.9f, 138.4f)
lineTo(261.3f, 161.3f)
lineTo(262.6f, 161.5f)
lineTo(263.5f, 161.7f)
lineTo(264.5f, 161.7f)
lineTo(265.2f, 161.2f)
lineTo(265.9f, 160.6f)
lineTo(266.3f, 158.9f)
lineTo(266.4f, 142.8f)
lineTo(266.6f, 125.8f)
lineTo(266.6f, 97.5f)
lineTo(266.2f, 95f)
lineTo(266f, 94.3f)
close()
}
path(
fill = SolidColor(Color.Black),
fillAlpha = 1.0f,
stroke = null,
strokeAlpha = 1.0f,
strokeLineWidth = 1.0f,
strokeLineCap = StrokeCap.Butt,
strokeLineJoin = StrokeJoin.Miter,
strokeLineMiter = 1.0f,
pathFillType = PathFillType.NonZero
) {
moveTo(263.1f, 92.3f)
curveToRelative(0.90f, 00f, 1.80f, 0.10f, 2.60f, 0.70f)
curveToRelative(10f, 0.80f, 1.50f, 1.90f, 1.50f, 3.10f)
curveToRelative(00f, 2.40f, 00f, 4.90f, 00f, 7.30f)
curveToRelative(00f, 12.80f, 00f, 25.60f, 0.10f, 38.50f)
curveToRelative(00f, 5.50f, 00f, 10.90f, 0.10f, 16.40f)
curveToRelative(00f, 1.10f, -0.10f, 2.20f, -0.80f, 3.10f)
curveToRelative(-10f, 1.20f, -2.70f, 1.90f, -4.50f, 1.30f)
curveToRelative(-0.90f, -0.30f, -1.50f, -10f, -2.20f, -1.50f)
curveToRelative(-20f, -1.60f, -4.10f, -3.30f, -6.10f, -4.90f)
curveToRelative(-2.60f, -2.10f, -5.30f, -4.30f, -80f, -6.40f)
curveToRelative(-2.60f, -2.10f, -5.20f, -4.20f, -7.80f, -6.30f)
curveToRelative(-20f, -1.60f, -40f, -3.20f, -5.90f, -4.80f)
curveToRelative(-0.90f, -0.70f, -20f, -0.70f, -2.90f, 00f)
curveToRelative(-2.90f, 2.40f, -5.80f, 4.80f, -8.70f, 7.20f)
curveToRelative(-4.30f, 3.60f, -8.60f, 7.20f, -130f, 10.80f)
curveToRelative(-2.10f, 1.70f, -4.10f, 3.40f, -6.20f, 5.10f)
curveToRelative(-1.10f, 0.90f, -2.30f, 1.10f, -3.60f, 0.80f)
curveToRelative(-1.80f, -0.50f, -2.90f, -20f, -2.90f, -40f)
curveToRelative(00f, -30f, 00f, -60f, 00f, -90f)
curveToRelative(00f, -6.30f, 00f, -12.50f, 0.10f, -18.80f)
curveToRelative(0.10f, -9.80f, 0.10f, -19.50f, 0.20f, -29.30f)
curveToRelative(00f, -1.90f, 00f, -3.70f, 0.10f, -5.60f)
curveToRelative(00f, -2.20f, 1.60f, -3.70f, 3.80f, -3.70f)
curveTo(209.80f, 92.40f, 252.50f, 92.30f, 263.10f, 92.30f)
close()
moveTo(198.9f, 93.8f)
curveToRelative(-1.60f, 00f, -2.20f, 10f, -2.20f, 2.40f)
curveToRelative(0.10f, 1.50f, -0.10f, 33.80f, 00f, 48.50f)
curveToRelative(00f, 4.70f, 00f, 9.30f, 0.10f, 140f)
curveToRelative(00f, 0.90f, 0.30f, 1.50f, 1.10f, 1.90f)
curveToRelative(0.80f, 0.40f, 1.60f, 0.20f, 2.20f, -0.30f)
curveToRelative(3.40f, -2.80f, 6.80f, -5.60f, 10.10f, -8.40f)
curveToRelative(4.50f, -3.70f, 8.90f, -7.40f, 13.40f, -11.20f)
curveToRelative(1.50f, -1.20f, 30f, -2.40f, 4.50f, -3.70f)
curveToRelative(1.40f, -1.20f, 3.60f, -1.10f, 50f, 00f)
curveToRelative(1.70f, 1.30f, 3.40f, 2.70f, 5.10f, 4.10f)
curveToRelative(1.30f, 1.10f, 2.70f, 2.20f, 40f, 3.30f)
curveToRelative(2.40f, 1.90f, 4.80f, 3.90f, 7.20f, 5.80f)
curveToRelative(4.20f, 3.40f, 8.30f, 6.70f, 12.50f, 10.10f)
curveToRelative(0.50f, 0.40f, 1.10f, 0.80f, 1.90f, 0.70f)
curveToRelative(1.10f, -0.20f, 1.70f, -10f, 1.70f, -2.20f)
curveToRelative(00f, -5.50f, 00f, -10.90f, 00f, -16.40f)
curveToRelative(00f, -6.80f, 00f, -13.50f, 0.10f, -20.30f)
curveToRelative(00f, -8.70f, 0.10f, -17.40f, 0.10f, -260f)
curveToRelative(00f, -1.20f, -0.90f, -2.20f, -2.10f, -2.20f)
curveToRelative(-0.50f, 00f, -10f, 00f, -1.50f, 00f)
curveTo(251.70f, 93.80f, 209.60f, 93.80f, 198.90f, 93.80f)
close()
}
}
}
}.build()
return _NSaver!!
}
private var _NSaver: ImageVector? = null
| 0
|
Kotlin
|
0
| 5
|
de331f0977e22a54f1b5d098f8c0d950922a4740
| 10,031
|
NotificationSaver_KMP
|
MIT License
|
module_home/src/main/java/com/phone/module_home/view/IHomePageView.kt
|
UrasakiNakajima
| 685,999,091
| false
|
{"Kotlin": 1376968, "Java": 250415, "CMake": 172579, "C++": 147334, "HTML": 45021, "C": 10920, "AIDL": 910}
|
package com.phone.module_home.view
import com.phone.library_base.base.IBaseView
import com.phone.library_common.bean.ResultData
import java.io.File
/**
* author : Urasaki
* e-mail : <EMAIL>
* date : 2020/3/7 15:44
* introduce :
*/
interface IHomePageView : IBaseView {
fun homePageDataSuccess(success: List<ResultData.JuheNewsBean>)
fun homePageDataError(error: String?)
}
| 0
|
Kotlin
|
0
| 3
|
c96e018ab96d1723e5684ef8f4e93a228ac110ab
| 401
|
RxJava2AndRetrofit2
|
Apache License 2.0
|
app/src/main/java/com/android/skip/node/NodeCount.kt
|
GuoXiCheng
| 506,451,823
| false
|
{"Kotlin": 38437, "JavaScript": 863}
|
package com.android.skip.node
import android.view.accessibility.AccessibilityNodeInfo
class NodeCount: NodeCallBack {
private var nodeCount = 0
override fun onCallback(accessibilityNodeInfo: AccessibilityNodeInfo) {
nodeCount ++
}
fun cleanCount() {
nodeCount = 0
}
fun getCount(): Int {
return nodeCount
}
}
| 8
|
Kotlin
|
51
| 716
|
b56999f3bcf85b965aa798ede45c26cc5f3c2c42
| 364
|
SKIP
|
MIT License
|
app/src/main/java/com/mbaguszulmi/githubuser/provider/UserProvider.kt
|
mbaguszulmi
| 287,586,839
| false
| null |
package com.mbaguszulmi.githubuser.provider
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import com.mbaguszulmi.githubuser.model.database.AppDb
import com.mbaguszulmi.githubuser.model.database.dao.GithubUserDao
import com.mbaguszulmi.githubuser.model.database.entities.GithubUser
class UserProvider : ContentProvider() {
companion object {
private const val USER = 1
private const val USER_ID = 2
private val sUriMatcher = UriMatcher(UriMatcher.NO_MATCH)
private lateinit var githubUserDao: GithubUserDao
}
init {
sUriMatcher.addURI(GithubUser.AUTHORITY, GithubUser.TABLE_NAME, USER)
sUriMatcher.addURI(GithubUser.AUTHORITY, "${GithubUser.TABLE_NAME}/#", USER_ID)
}
override fun onCreate(): Boolean {
githubUserDao = AppDb.getInstance(context as Context).githubUserDao()
return true
}
override fun query(
uri: Uri, projection: Array<String>?, selection: String?,
selectionArgs: Array<String>?, sortOrder: String?
): Cursor? {
return when (sUriMatcher.match(uri)) {
USER -> githubUserDao.findAll()
USER_ID -> githubUserDao.find(uri.lastPathSegment!!.toInt())
else -> null
}
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
val added = when (USER) {
sUriMatcher.match(uri) -> githubUserDao.insert(GithubUser.fromContentValues(values))
else -> 0
}
context?.contentResolver?.notifyChange(GithubUser.CONTENT_URI, null)
return Uri.parse("${GithubUser.CONTENT_URI}/$added")
}
override fun update(
uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<String>?
): Int {
val updated = when (USER_ID) {
sUriMatcher.match(uri) -> githubUserDao.update(GithubUser.fromContentValues(values))
else -> 0
}
context?.contentResolver?.notifyChange(GithubUser.CONTENT_URI, null)
return updated
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
val deleted = when (USER_ID) {
sUriMatcher.match(uri) -> {
val githubUser = githubUserDao.findGithubUser(uri.lastPathSegment!!.toInt())
githubUserDao.delete(githubUser)
}
else -> 0
}
context?.contentResolver?.notifyChange(GithubUser.CONTENT_URI, null)
return deleted
}
override fun getType(uri: Uri): String? {
return "GithubUser"
}
}
| 0
|
Kotlin
|
0
| 0
|
8cb3ebd7f416dfdb430e9d6a107cccc953c4caa1
| 2,743
|
android-github-user
|
Apache License 2.0
|
app/src/main/java/at/markushi/checkmate/ui/SettingsScreen.kt
|
markushi
| 543,017,728
| false
|
{"Kotlin": 73559}
|
package at.markushi.checkmate.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import at.markushi.checkmate.AppViewModel
import at.markushi.checkmate.R
@Composable
fun SettingsScreen(appViewModel: AppViewModel) {
Column {
Text(
modifier = Modifier.padding(
top = 48.dp,
start = 16.dp,
end = 16.dp,
bottom = 16.dp
),
text = stringResource(R.string.settings_title),
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.headlineLarge
)
Text(
modifier = Modifier.padding(16.dp),
text = stringResource(R.string.settings_goal_header)
)
for (goal in appViewModel.goals) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(64.dp)
.clickable {
appViewModel.onGoalSettingsClicked(goal)
}
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
modifier = Modifier
.size(24.dp)
.background(color = goal.color.asColor(), shape = CircleShape)
)
Spacer(modifier = Modifier.size(8.dp))
Text(text = goal.name)
}
}
Button(
modifier = Modifier.padding(16.dp),
onClick = {
appViewModel.onCreateGoalClicked()
}) {
Text(text = stringResource(R.string.settings_new_goal))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c84d794829b9df2898bc3a10e452ec5e891b11db
| 2,554
|
checkmate
|
Apache License 2.0
|
base/src/main/java/com/surrus/galwaybus/domain/interactor/GetBusStopsUseCase.kt
|
eduardb
| 147,106,837
| true
|
{"Kotlin": 105848, "Java": 73116, "GLSL": 9264, "Ruby": 3139}
|
package com.surrus.galwaybus.domain.interactor
import com.surrus.galwaybus.domain.executor.ExecutorThread
import com.surrus.galwaybus.domain.executor.PostExecutionThread
import com.surrus.galwaybus.domain.repository.GalwayBusRepository
import com.surrus.galwaybus.model.BusStop
import io.reactivex.Flowable
open class GetBusStopsUseCase constructor(val galwayRepository: GalwayBusRepository,
executorThread: ExecutorThread, postExecutionThread: PostExecutionThread):
FlowableUseCase<List<List<BusStop>>, String>(executorThread, postExecutionThread) {
override fun buildUseCaseObservable(params: String?): Flowable<List<List<BusStop>>> {
return galwayRepository.getBusStops(params!!)
}
}
| 0
|
Kotlin
|
0
| 0
|
2fc542f37e19de59f4ef0eea15a8046244680bfe
| 763
|
galway-bus-android
|
MIT License
|
base/src/main/java/com/surrus/galwaybus/domain/interactor/GetBusStopsUseCase.kt
|
eduardb
| 147,106,837
| true
|
{"Kotlin": 105848, "Java": 73116, "GLSL": 9264, "Ruby": 3139}
|
package com.surrus.galwaybus.domain.interactor
import com.surrus.galwaybus.domain.executor.ExecutorThread
import com.surrus.galwaybus.domain.executor.PostExecutionThread
import com.surrus.galwaybus.domain.repository.GalwayBusRepository
import com.surrus.galwaybus.model.BusStop
import io.reactivex.Flowable
open class GetBusStopsUseCase constructor(val galwayRepository: GalwayBusRepository,
executorThread: ExecutorThread, postExecutionThread: PostExecutionThread):
FlowableUseCase<List<List<BusStop>>, String>(executorThread, postExecutionThread) {
override fun buildUseCaseObservable(params: String?): Flowable<List<List<BusStop>>> {
return galwayRepository.getBusStops(params!!)
}
}
| 0
|
Kotlin
|
0
| 0
|
2fc542f37e19de59f4ef0eea15a8046244680bfe
| 763
|
galway-bus-android
|
MIT License
|
neuvi/src/main/kotlin/com/github/jnexil/neuvi/internal/MutNetwork.kt
|
JNexil
| 76,639,857
| false
| null |
package com.github.jnexil.neuvi.internal
import com.github.jnexil.neuvi.api.*
import com.github.jnexil.neuvi.api.layers.*
import com.github.jnexil.neuvi.api.linalg.*
import com.github.jnexil.neuvi.api.networks.*
import com.github.jnexil.neuvi.api.providers.*
internal class MutNetwork internal constructor(override val input: MutableLayer, override val output: MutableLayer, override val memory: MemoryProvider): Network {
val propagation = output.backPropagation()
override fun process(data: Vector): Vector {
input.enter(data)
output.absorbRecursive()
return memory.copyVector(output.values)
}
override fun train(expected: Vector) {
propagation.train(expected)
}
}
| 0
|
Kotlin
|
0
| 0
|
100081be16f921e39e8bfb7b6cccae0785d51f04
| 721
|
Neurio
|
Apache License 2.0
|
core/src/commonMain/kotlin/com/sjaindl/s11/core/firestore/config/model/Config.kt
|
sjaindl
| 833,289,183
| false
|
{"Kotlin": 196302, "Ruby": 7377, "Swift": 1695, "HTML": 1023, "CSS": 306}
|
package com.sjaindl.s11.core.firestore.config.model
import kotlinx.serialization.Serializable
@Serializable
data class Config(
val bets: Boolean,
val freeze: Boolean,
)
| 0
|
Kotlin
|
0
| 0
|
3cf276256f442ad905ce1a8b222379ffc45cbee6
| 179
|
StartingEleven
|
MIT License
|
adventure-serialization/src/main/kotlin/net/bladehunt/kotstom/serialization/adventure/AdventureCompoundDecoder.kt
|
bladehuntmc
| 822,386,546
| false
|
{"Kotlin": 117270}
|
package net.bladehunt.kotstom.serialization.adventure
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.InternalSerializationApi
import kotlinx.serialization.SerializationException
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.StructureKind
import kotlinx.serialization.encoding.CompositeDecoder
import kotlinx.serialization.internal.AbstractPolymorphicSerializer
import net.bladehunt.kotstom.serialization.adventure.internal.TaggedAdventureDecoder
import net.kyori.adventure.nbt.BinaryTag
import net.kyori.adventure.nbt.CompoundBinaryTag
@OptIn(InternalSerializationApi::class, ExperimentalSerializationApi::class)
internal class AdventureCompoundDecoder(
override val adventureNbt: AdventureNbt,
private val compound: CompoundBinaryTag
) : TaggedAdventureDecoder() {
private var index = 0
override fun decodeTaggedBinaryTag(tag: String): BinaryTag = compound[tag]!!
override fun decodeTaggedBoolean(tag: String): Boolean = compound.getBoolean(tag)
override fun decodeTaggedByte(tag: String): Byte = compound.getByte(tag)
override fun decodeTaggedShort(tag: String): Short = compound.getShort(tag)
override fun decodeTaggedInt(tag: String): Int = compound.getInt(tag)
override fun decodeTaggedLong(tag: String): Long = compound.getLong(tag)
override fun decodeTaggedFloat(tag: String): Float = compound.getFloat(tag)
override fun decodeTaggedDouble(tag: String): Double = compound.getDouble(tag)
override fun decodeTaggedChar(tag: String): Char = compound.getString(tag)[0]
override fun decodeTaggedString(tag: String): String = compound.getString(tag)
override fun decodeTaggedEnum(tag: String, enumDescriptor: SerialDescriptor): Int =
decodeTaggedInt(tag)
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
while (index < descriptor.elementsCount) {
val name = descriptor.getTag(index++)
val index = index - 1
val optional = descriptor.isElementOptional(index)
if (!optional) return index
else if (compound.keySet().contains(name)) return index
}
return CompositeDecoder.DECODE_DONE
}
override fun <T> decodeSerializableValue(deserializer: DeserializationStrategy<T>): T {
if (deserializer !is AbstractPolymorphicSerializer<*>)
return super.decodeSerializableValue(deserializer)
val compound = if (currentTagOrNull != null) {
compound.getCompound(popTag())
} else compound
val decoder = AdventureCompoundDecoder(adventureNbt, compound)
val type = decoder.decodeTaggedString(adventureNbt.discriminator)
val actualSerializer =
deserializer.findPolymorphicSerializerOrNull(decoder, type)
?: throw SerializationException("$type was not found!")
@Suppress("UNCHECKED_CAST")
return (actualSerializer as DeserializationStrategy<T>).deserialize(decoder)
}
override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder {
if (currentTagOrNull == null) return this
return when (descriptor.kind) {
is StructureKind.LIST -> {
AdventureListDecoder(adventureNbt, compound.getList(popTag()))
}
else -> {
AdventureCompoundDecoder(adventureNbt, compound.getCompound(popTag()))
}
}
}
}
| 0
|
Kotlin
|
0
| 9
|
f0bd4675be3ecd858b057d2d936aa93e5ed20cc2
| 3,558
|
KotStom
|
MIT License
|
app/src/main/kotlin/kkris/hatschen/sampling/VertexSampler.kt
|
kkris
| 461,260,394
| false
|
{"Kotlin": 27718, "JavaScript": 3634, "Shell": 287}
|
package kkris.hatschen.sampling
import kkris.hatschen.gtsp.GtspSet
import kkris.hatschen.parser.Area
enum class VertexSampleType(val value: String) {
CENTROID("centroid"),
CENTER_BIAS("center-bias"),
GRID("grid"),
BOUNDARY("boundary")
}
interface VertexSampler {
fun sample(area: Area, allAreas: List<Area>): GtspSet
companion object {
fun create(type: VertexSampleType): VertexSampler {
return when (type) {
VertexSampleType.CENTROID -> CentroidAreaSampler()
VertexSampleType.CENTER_BIAS -> CenterBiasAreaSampler()
VertexSampleType.GRID -> GridSampler()
VertexSampleType.BOUNDARY -> BoundarySampler()
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
d00f1df9012cf92f8e76af0eb6eb3954653c69fb
| 745
|
hatschen
|
MIT License
|
kool-core/src/commonMain/kotlin/de/fabmax/kool/scene/ui/UiShader.kt
|
fabmax
| 81,503,047
| false
| null |
package de.fabmax.kool.scene.ui
import de.fabmax.kool.KoolContext
import de.fabmax.kool.pipeline.*
import de.fabmax.kool.pipeline.shadermodel.ShaderModel
import de.fabmax.kool.pipeline.shadermodel.StageInterfaceNode
import de.fabmax.kool.pipeline.shadermodel.fragmentStage
import de.fabmax.kool.pipeline.shadermodel.vertexStage
import de.fabmax.kool.pipeline.shading.FloatInput
import de.fabmax.kool.pipeline.shading.ModeledShader
import de.fabmax.kool.pipeline.shading.Texture2dInput
import de.fabmax.kool.scene.Mesh
import de.fabmax.kool.util.Color
class UiShader(font: Texture2d? = SingleColorTexture(Color.WHITE)) : ModeledShader(uiShaderModel()) {
val alpha = FloatInput(U_ALPHA, 1f)
val font = Texture2dInput(U_FONT_TEX, font)
override fun onPipelineSetup(builder: Pipeline.Builder, mesh: Mesh, ctx: KoolContext) {
builder.blendMode = BlendMode.BLEND_PREMULTIPLIED_ALPHA
builder.cullMethod = CullMethod.NO_CULLING
builder.depthTest = DepthCompareOp.LESS_EQUAL
super.onPipelineSetup(builder, mesh, ctx)
}
override fun onPipelineCreated(pipeline: Pipeline, mesh: Mesh, ctx: KoolContext) {
alpha.connect(model)
font.connect(model)
super.onPipelineCreated(pipeline, mesh, ctx)
}
companion object {
val UI_MESH_ATTRIBS = listOf(Attribute.POSITIONS, Attribute.TEXTURE_COORDS, Attribute.COLORS)
private const val U_ALPHA = "uAlpha"
private const val U_FONT_TEX = "uFontTex"
private fun uiShaderModel() = ShaderModel("UI Shader").apply {
val ifTexCoords: StageInterfaceNode
val ifColors: StageInterfaceNode
vertexStage {
ifTexCoords = stageInterfaceNode("ifTexCoords", attrTexCoords().output)
ifColors = stageInterfaceNode("ifColors", attrColors().output)
positionOutput = simpleVertexPositionNode().outVec4
}
fragmentStage {
val alpha = pushConstantNode1f(U_ALPHA)
val fontSampler = texture2dSamplerNode(texture2dNode(U_FONT_TEX), ifTexCoords.output)
val mulAlpha = multiplyNode(fontSampler.outColor, alpha.output)
val alphaColor = colorAlphaNode(ifColors.output, mulAlpha.output)
colorOutput(unlitMaterialNode(alphaColor.outAlphaColor).outColor)
}
}
}
}
| 3
|
Kotlin
|
4
| 62
|
edef672ca0f491b5b612203be7a9e102d411993b
| 2,389
|
kool
|
Apache License 2.0
|
src/main/kotlin/xyz/chlamydomonos/hyphacraft/blocks/MycovastusHyphaHiddenBlock.kt
|
Chlamydomonos
| 832,406,228
| false
|
{"Kotlin": 139172, "Java": 3138}
|
package xyz.chlamydomonos.hyphacraft.blocks
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateDefinition
import xyz.chlamydomonos.hyphacraft.blocks.utils.ModProperties
class MycovastusHyphaHiddenBlock : Block(Properties.ofFullCopy(Blocks.GLASS)) {
override fun createBlockStateDefinition(builder: StateDefinition.Builder<Block, BlockState>) {
builder.add(ModProperties.PHASE)
}
}
| 0
|
Kotlin
|
0
| 0
|
ee09cd02a3a0d2e1dbf751849280e55ab9cd5dd1
| 544
|
HyphaCraft
|
MIT License
|
src/com/design/pattern/singleton/Singleton.kt
|
alphaguy4
| 441,482,895
| false
|
{"Kotlin": 6610, "Java": 1885}
|
package com.design.pattern.singleton
/*
* In kotlin we need to simply use `object` keyword to declare a singleton class
* For example: object Singleton
* The object classes can have functions, properties and the init method
* Constructor isn't allowed in object, so we can use `init{}` for some initialisation
* */
object Singleton {
init {
println("Hello, I am Singleton class from kotlin")
println("Unlike java, i don't need boiler plate code")
}
fun helperFunction(str: String = "") {
println("I am a single $str")
}
var singletonVariable: String = "Hello Singleton world";
}
fun main() {
Singleton.helperFunction()
Singleton.singletonVariable = "Changed"
Singleton.helperFunction("Kotlin")
}
| 0
|
Kotlin
|
0
| 1
|
5a31023c942d07c0e7158e42c092dc0f8cddd566
| 759
|
Design-Patterns
|
Apache License 2.0
|
src/main/kotlin/com/booleworks/prl/model/rules/GroupRule.kt
|
booleworks
| 721,827,131
| false
|
{"Kotlin": 995198, "ANTLR": 16772, "Shell": 261}
|
// SPDX-License-Identifier: MIT
// Copyright 2023 BooleWorks GmbH
package com.booleworks.prl.model.rules
import com.booleworks.prl.model.AnyProperty
import com.booleworks.prl.model.Module
import com.booleworks.prl.model.Visibility
import com.booleworks.prl.model.constraints.BooleanFeature
import com.booleworks.prl.model.constraints.ConstraintType
import com.booleworks.prl.model.constraints.EnumFeature
import com.booleworks.prl.model.constraints.Equivalence
import com.booleworks.prl.model.constraints.Exo
import com.booleworks.prl.model.constraints.FALSE
import com.booleworks.prl.model.constraints.IntFeature
import com.booleworks.prl.model.constraints.and
import com.booleworks.prl.model.constraints.not
import com.booleworks.prl.model.constraints.or
import com.booleworks.prl.model.datastructures.FeatureAssignment
import com.booleworks.prl.model.datastructures.FeatureRenaming
import com.booleworks.prl.parser.PragmaticRuleLanguage.KEYWORD_CONTAINS
import com.booleworks.prl.parser.PragmaticRuleLanguage.KEYWORD_GROUP
import com.booleworks.prl.parser.PragmaticRuleLanguage.SYMBOL_COMMA
import com.booleworks.prl.parser.PragmaticRuleLanguage.SYMBOL_LSQB
import com.booleworks.prl.parser.PragmaticRuleLanguage.SYMBOL_RSQB
import com.booleworks.prl.parser.PragmaticRuleLanguage.groupTypeString
import com.booleworks.prl.parser.PragmaticRuleLanguage.visibilityString
import java.util.Objects
enum class GroupType { OPTIONAL, MANDATORY }
class GroupRule(
val type: GroupType,
val group: BooleanFeature,
val content: Set<BooleanFeature>,
val visibility: Visibility = Visibility.PUBLIC,
override val module: Module,
override val id: String = "",
override val description: String = "",
override val properties: Map<String, AnyProperty> = mapOf(),
override val lineNumber: Int? = null
) : Rule<GroupRule>(module, id, description, properties, lineNumber) {
constructor(
type: GroupType,
group: BooleanFeature,
content: Collection<BooleanFeature>,
visibility: Visibility = Visibility.PUBLIC,
module: Module,
id: String = "",
description: String = "",
properties: Map<String, AnyProperty> = mapOf(),
lineNumber: Int? = null
) : this(type, group, content.toSet(), visibility, module, id, description, properties, lineNumber)
private constructor(
rule: AnyRule,
type: GroupType,
group: BooleanFeature,
content: Collection<BooleanFeature>,
visibility: Visibility = Visibility.PUBLIC
)
: this(
type,
group,
content.toSet(),
visibility,
rule.module,
rule.id,
rule.description,
rule.properties,
rule.lineNumber
)
override fun features() = setOf(group) + content
override fun booleanFeatures() = setOf(group) + content
override fun enumFeatures() = setOf<EnumFeature>()
override fun enumValues() = mapOf<EnumFeature, Set<String>>()
override fun intFeatures() = setOf<IntFeature>()
override fun containsBooleanFeatures() = true
override fun containsEnumFeatures() = false
override fun containsIntFeatures() = false
/**
* Evaluates if the rule is true with the given assignment.
*
* For mandatory rules the group is always true. An optional rule becomes a mandatory rule
* if the group is true. If the group is false, all features of the groupContent must be false.
* @param assignment the current assignment
* @return the evaluation of this rule
*/
override fun evaluate(assignment: FeatureAssignment) =
if (type == GroupType.MANDATORY || group.evaluate(assignment)) {
group.evaluate(assignment) && Exo(content).evaluate(assignment)
} else {
not(or(content)).evaluate(assignment)
}
override fun restrict(assignment: FeatureAssignment) =
if (type == GroupType.MANDATORY) restrictMandatory(assignment) else restrictOptional(assignment)
private fun restrictMandatory(assignment: FeatureAssignment): AnyRule {
group.restrict(assignment).let {
if (it.type === ConstraintType.TRUE) {
return ConstraintRule(this, Exo(content).restrict(assignment))
} else if (it.type === ConstraintType.FALSE) {
return ConstraintRule(this, FALSE)
}
}
return Exo(content).restrict(assignment).let {
when {
it.type === ConstraintType.TRUE -> ConstraintRule(this, group)
it.type === ConstraintType.FALSE -> ConstraintRule(this, FALSE)
it.type === ConstraintType.ATOM || it.type === ConstraintType.AND -> ConstraintRule(
this,
and(group, it)
)
else -> GroupRule(this, type, group, it.booleanFeatures(), visibility)
}
}
}
private fun restrictOptional(assignment: FeatureAssignment): AnyRule {
group.restrict(assignment).let {
if (it.type === ConstraintType.TRUE) {
return ConstraintRule(this, Exo(content).restrict(assignment))
} else if (it.type === ConstraintType.FALSE) {
return ConstraintRule(this, not(or(content).restrict(assignment)))
}
}
return Exo(content).restrict(assignment).let {
when {
it.type === ConstraintType.TRUE -> ConstraintRule(this, group)
it.type === ConstraintType.FALSE ->
if (or(content).restrict(assignment).type === ConstraintType.FALSE) {
ConstraintRule(this, not(group))
} else {
ConstraintRule(this, FALSE)
}
it.type === ConstraintType.ATOM -> ConstraintRule(this, Equivalence(group, it))
it.type === ConstraintType.AND -> ConstraintRule(this, and(group, it).syntacticSimplify())
else -> GroupRule(this, type, group, it.booleanFeatures(), visibility)
}
}
}
override fun syntacticSimplify() = when {
content.isEmpty() -> ConstraintRule(this, if (type == GroupType.OPTIONAL) not(group) else FALSE)
content.size == 1 -> ConstraintRule(
this,
if (type == GroupType.OPTIONAL) Equivalence(group, content.first()) else and(group, content.first())
)
else -> this
}
override fun rename(renaming: FeatureRenaming) =
GroupRule(this, type, renaming.rename(group), content.map { renaming.rename(it) }, visibility)
override fun stripProperties() =
GroupRule(type, group, content, visibility, module, id, description, mapOf(), lineNumber)
override fun stripMetaInfo() = GroupRule(type, group, content, visibility, module, "", "", properties, lineNumber)
override fun stripAll() = GroupRule(type, group, content, visibility, module, "", "", mapOf(), lineNumber)
override fun headerLine(currentModule: Module) =
"${groupTypeString(type)} ${visibilityString(visibility)}$KEYWORD_GROUP ${group.toString(currentModule)} " +
"$KEYWORD_CONTAINS $SYMBOL_LSQB" +
content.joinToString("$SYMBOL_COMMA ") { it.toString(currentModule) } + SYMBOL_RSQB
override fun hashCode() = Objects.hash(super.hashCode(), type, group, visibility, content)
override fun equals(other: Any?) = super.equals(other) && hasEqualConstraint(other as AnyRule)
private fun hasEqualConstraint(other: AnyRule) =
other is GroupRule && type == other.type && group == other.group && visibility == other.visibility &&
content == other.content
}
| 1
|
Kotlin
|
0
| 0
|
2f0fb469f74b133aba7006d30e37d5ba882a1191
| 7,731
|
prl-compiler
|
MIT License
|
game/src/main/kotlin/com/runt9/heroDynasty/character/item/armor/Mail.kt
|
runt9
| 130,910,358
| false
| null |
package com.runt9.heroDynasty.character.item.armor
class Mail : Armor() {
override val dodgeChanceRoll: Pair<Double, Double> = 0.95 to 0.99
override val physicalIncomingDamageRoll: Pair<Double, Double> = 0.92 to 0.97
override val insulatedIncomingDamageRoll: Pair<Double, Double> = 0.98 to 1.0
override fun getNameSuffixes(): List<String> {
val nameSuffixes = super.getNameSuffixes().toMutableList()
val positionSuffix = when (position) {
Armor.Position.HEAD -> "Helmet"
Armor.Position.BODY -> "Coat"
Armor.Position.LEGS -> "Pants"
Armor.Position.ARMS -> "Gloves"
Armor.Position.FEET -> "Boots"
}
nameSuffixes.add(positionSuffix)
return nameSuffixes.toList()
}
}
| 0
|
Kotlin
|
0
| 0
|
87be0aa7394a2980145768ee315797a3e1655ff0
| 786
|
hero-dynasty
|
MIT License
|
overlord-server/src/main/kotlin/tv/dotstart/overlord/server/entity/security/User.kt
|
dotStart
| 260,457,926
| false
|
{"Kotlin": 211624}
|
/*
* Copyright (C) 2020 <NAME> <<EMAIL>>
* and other copyright owners as documented in the project's IP log.
*
* 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 tv.dotstart.overlord.server.entity.security
import jetbrains.exodus.entitystore.Entity
import kotlinx.dnq.*
import org.springframework.security.crypto.bcrypt.BCrypt
import tv.dotstart.overlord.server.entity.audit.AbstractAuditedEntity
import tv.dotstart.overlord.server.entity.security.audit.UserAuditLogEntry
/**
* Represents a user which has been registered with the system and is able to access the
* application.
*
* @author [<NAME>](mailto:<EMAIL>)
* @date 28/06/2020
*/
class User(entity: Entity) : AbstractAuditedEntity<UserAuditLogEntry>(entity) {
companion object : XdNaturalEntityType<User>()
/**
* Provides a login name for this user which will be used as a primary identification factor when
* logging in.
*
* This value is expected to be unique within the application database.
*/
var name by xdRequiredStringProp(unique = true, trimmed = true)
/**
* Provides a display name for this user which is displayed as a replacement to [name] if
* specified.
*
* This field is primarily provided for organizational purposes in systems where many users are
* given access to game server instances.
*/
var displayName by xdStringProp(trimmed = true)
/**
* Provides a BCrypt password hash which encodes the user's actual password.
*/
private var passwordHash by xdRequiredStringProp()
/**
* Identifies whether this user has been locked (e.g. is not permitted to access the application
* even with their correct password).
*/
var locked by xdBooleanProp()
override val auditLog by xdLink0_N(UserAuditLogEntry)
/**
* Evaluates whether a given password matches the known hashed version of the user password.
*
* This method may take a while to complete as BCrypt is purposefully designed to be slow while
* generating hashes to prevent brute force attacks on user passwords.
*/
fun checkPassword(password: String): Boolean = BCrypt.checkpw(password, this.passwordHash)
/**
* Replaces the previously set user password with the given value.
*
* Note: This method generates a new salt and replaces the password hash accordingly. Similar
* to [checkPassword], this method may take some time to complete as BCrypt hashing is
* purposefully expensive.
*/
fun updatePassword(password: String) {
val salt = BCrypt.gensalt()
this.passwordHash = BCrypt.hashpw(password, salt)
}
}
| 6
|
Kotlin
|
1
| 0
|
c1050766a48c44a7464b0350eff2f70c906c1ba4
| 3,085
|
overlord
|
Apache License 2.0
|
search/search_data/src/main/java/com/erkindilekci/search_data/mapper/NewsMappers.kt
|
erkindilekci
| 666,722,648
| false
| null |
package com.erkindilekci.search_data.mapper
import com.erkindilekci.search_data.model.ArticleDto
import com.erkindilekci.search_domain.model.Article
fun ArticleDto.toArticle(): Article = Article(
author ?: "",
content ?: "",
description ?: "",
title ?: "",
urlToImage ?: ""
)
| 0
|
Kotlin
|
0
| 0
|
4774dffbfb9751390e53fa20baa56471e50dd68a
| 298
|
Multi-ModuleNewsApp
|
Apache License 2.0
|
app/src/main/java/com/cmt/view/fragment/OtpFragment.kt
|
ChanduSaketi
| 789,653,107
| false
|
{"Kotlin": 268298}
|
package com.cmt.view.fragment
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.cmt.R
import com.cmt.databinding.FragmentOtpBinding
import com.cmt.helper.IConstants
import com.cmt.helper.hideKeyboard
import com.cmt.my_doctors.app.AppController
import com.cmt.view.activity.MainActivity
import com.cmt.view.activity.PlainActivity
import com.cmt.viewModel.fragment.OtpVM
class OtpFragment(val mobile: String? = null) : Fragment() {
private lateinit var binding: FragmentOtpBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
binding = FragmentOtpBinding.inflate(layoutInflater, container, false).apply {
viewModel = ViewModelProvider(this@OtpFragment).get(OtpVM::class.java)
viewModel?.binding = this
lifecycleOwner = this@OtpFragment
}
return binding.root
}
@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.etOtp1.setInputType(InputType.TYPE_CLASS_NUMBER)
binding.etOtp2.setInputType(InputType.TYPE_CLASS_NUMBER)
binding.etOtp3.setInputType(InputType.TYPE_CLASS_NUMBER)
binding.etOtp4.setInputType(InputType.TYPE_CLASS_NUMBER)
if (AppController.passwordType == IConstants.Defaults.registration) {
binding.phoneNumber.text = "+91 $mobile"
} else if (IConstants.ValueHolder.loginType == "mobile") {
binding.phoneNumber.text = "+91 $mobile"
} else if (IConstants.ValueHolder.loginType == "email") {
binding.phoneNumber.text = "$mobile"
}
binding.viewModel?.setDataToView(mobile!!)
binding.verifyBtn.setOnClickListener {
if (binding.etOtp1.text.isNullOrEmpty() && binding.etOtp2.text.isNullOrEmpty() &&
binding.etOtp3.text.isNullOrEmpty() && binding.etOtp4.text.isNullOrEmpty()
) {
binding.viewModel?.errorMsg?.postValue("Please enter OTP")
} else if (binding.etOtp1.text.isNullOrEmpty() || binding.etOtp2.text.isNullOrEmpty() ||
binding.etOtp3.text.isNullOrEmpty() || binding.etOtp4.text.isNullOrEmpty()
) {
binding.viewModel?.errorMsg?.postValue("Please enter valid OTP")
} else {
binding.viewModel?.errorMsg?.postValue(null)
view.hideKeyboard()
binding.viewModel?.verifyOtp(requireActivity())
/* if (AppController.passwordType == IConstants.Defaults.forgot_password) {
val intent = Intent(requireActivity(), PlainActivity::class.java)
intent.putExtra(IConstants.IntentStrings.type, IConstants.FragmentType.chooseNewPassword)
requireActivity().startActivity(intent)
requireActivity().finishAffinity()
requireActivity().overridePendingTransition(R.anim.enter, R.anim.exit)
}
else if (AppController.passwordType == IConstants.Defaults.registration) {
val intent = Intent(requireActivity(), MainActivity::class.java)
intent.putExtra(
IConstants.IntentStrings.type,
IConstants.FragmentType.home
)
requireActivity().startActivity(intent)
requireActivity().overridePendingTransition(R.anim.enter, R.anim.exit)
requireActivity().finishAffinity()
}*/
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
facc36cb37801215c31585c8bc5655ea78489d15
| 3,943
|
satyam_acadamy
|
MIT License
|
lib/compiler/src/main/kotlin/dev/buijs/klutter/compiler/scanner/ControllerTypes.kt
|
buijs-dev
| 436,644,099
| false
|
{"Kotlin": 415674, "Groovy": 202700, "Shell": 4390, "Ruby": 3246}
|
/* Copyright (c) 2021 - 2023 Buijs Software
*
* 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 dev.buijs.klutter.compiler.scanner
import dev.buijs.klutter.kore.ast.*
import dev.buijs.klutter.kore.common.Either
import dev.buijs.klutter.kore.common.EitherNok
import dev.buijs.klutter.kore.common.EitherOk
/**
* Alias for [Either] with only right value of type [Controller].
*/
internal typealias ValidController = EitherOk<String, Controller>
/**
* Alias for [Either] with only left value of type [String] (error).
*/
internal typealias InvalidController = EitherNok<String, Controller>
/**
* Alias for [Either] with only right value of type [Method].
*/
internal typealias ValidEvent = EitherOk<String, Method>
/**
* Alias for [Either] with only left value of type [String] (error).
*/
internal typealias InvalidEvent = EitherNok<String, Method>
/**
* Alias for [Either] containing a valid [Controller] or a [String] error message.
*/
internal typealias ValidControllerOrError = Either<String,Controller>
| 3
|
Kotlin
|
5
| 220
|
93d360ce7e391c0b60d7a1c63f7ba949df09f44e
| 2,057
|
klutter
|
MIT License
|
library/kdenticon/src/main/java/kdenticon/SvgRenderer.kt
|
huskcasaca
| 464,732,039
| false
| null |
package kdenticon
class SvgRenderer(target: SvgWriter) : Renderer {
private var _pathsByColor = HashMap<String, SvgPath>()
private var _target = target
var size = target.size
private lateinit var _path: SvgPath
override fun setBackground(fillColor: String) {
val re = Regex("^(#......)(..)?")
var match = re.matchEntire(fillColor)?.groups?.get(1)?.value
val opacityMatch = re.matchEntire(fillColor)?.groups?.get(2)?.value
val opacity = opacityMatch?.let {
opacityMatch.toInt(16) / 255f
} ?: 1f
val colorMatch = re.matchEntire(fillColor)?.groups?.get(1)?.value
val color = colorMatch?.let {
colorMatch
} ?: "000000"
this._target.setBackground(color, opacity)
}
override fun beginShape(color: String) {
if (this._pathsByColor[color] == null) {
this._pathsByColor[color] = SvgPath()
}
this._path = this._pathsByColor[color]!!
}
override fun endShape() {
}
override fun addPolygon(points: List<Point>) {
this._path.addPolygon(points)
}
override fun addCircle(point: Point, diameter: Float, counterClockwise: Boolean) {
this._path.addCircle(point, diameter, counterClockwise)
}
override fun finish() {
for (color in this._pathsByColor.keys) {
this._target.append(color, this._pathsByColor[color]!!.dataString)
}
}
}
| 0
|
Kotlin
|
4
| 5
|
2522ec7169a5fd295225caf936bae2edf09b157e
| 1,459
|
bitshares-oases-android
|
MIT License
|
server/src/main/kotlin/org/kryptonmc/krypton/event/player/KryptonPlayerResourcePackStatusEvent.kt
|
KryptonMC
| 255,582,002
| false
| null |
/*
* This file is part of the Krypton project, licensed under the Apache License v2.0
*
* Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton 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 org.kryptonmc.krypton.event.player
import org.kryptonmc.api.entity.player.Player
import org.kryptonmc.api.event.player.PlayerResourcePackStatusEvent
import org.kryptonmc.api.resource.ResourcePack
class KryptonPlayerResourcePackStatusEvent(override val player: Player, override val status: ResourcePack.Status) : PlayerResourcePackStatusEvent
| 27
|
Kotlin
|
11
| 233
|
a9eff5463328f34072cdaf37aae3e77b14fcac93
| 1,085
|
Krypton
|
Apache License 2.0
|
sdk/src/androidMain/kotlin/com/simplyfi/sdk/view/WebView.android.kt
|
simplyfi-com
| 738,484,911
| false
|
{"Kotlin": 19414, "CSS": 134}
|
package com.simplyfi.sdk.view
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
@SuppressLint("SetJavaScriptEnabled")
@Composable
actual fun WebView(
config: ViewConfig,
modifier: Modifier,
onCreated: () -> Unit,
onDispose: () -> Unit,
) {
AndroidView(
factory = {
WebView(it).apply {
settings.apply {
javaScriptEnabled = true
allowFileAccess = true
domStorageEnabled = true
}
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
view?.evaluateJavascript(
"""localStorage.setItem('${config.tokenKey}', '"${config.token}"')""",
null
)
}
}
loadUrl(config.url)
}
},
modifier,
onRelease = {
onDispose()
},
)
}
| 0
|
Kotlin
|
0
| 0
|
15ca984e234cc11582d4f4f97d65eeea109d2791
| 1,554
|
kotlin-shared
|
MIT License
|
projects/android/koin-android-compat/src/main/java/org/koin/android/compat/GetViewModelCompat.kt
|
InsertKoinIO
| 93,515,203
| false
| null |
/*
* Copyright 2017-2023 the original author or 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.koin.android.compat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.viewmodel.CreationExtras
import org.koin.androidx.viewmodel.factory.KoinViewModelFactory
import org.koin.core.annotation.KoinInternalApi
import org.koin.core.parameter.ParametersDefinition
import org.koin.core.qualifier.Qualifier
import org.koin.core.scope.Scope
import kotlin.reflect.KClass
@OptIn(KoinInternalApi::class)
@Deprecated("scope is not used for ViewModel creation. This will fallback to root scope.")
@KoinInternalApi
fun <T : ViewModel> resolveViewModelCompat(
vmClass: Class<T>,
viewModelStore: ViewModelStore,
key: String? = null,
extras: CreationExtras,
qualifier: Qualifier? = null,
scope: Scope,
parameters: ParametersDefinition? = null,
): T = org.koin.androidx.viewmodel.resolveViewModel(vmClass.kotlin, viewModelStore, key, extras, qualifier, scope, parameters)
| 96
| null |
674
| 8,587
|
0dcf904e9da4948af292206704de34d885b78dce
| 1,613
|
koin
|
Apache License 2.0
|
app/src/test/java/com/openwallet/playerframe/bean/ScaleTypeTest.kt
|
hsbc
| 742,467,592
| false
|
{"Kotlin": 502702, "Java": 40426}
|
package com.openwallet.playerframe.bean
import junit.framework.TestCase
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class ScaleTypeTest : TestCase() {
@Before
public override fun setUp() {
super.setUp()
}
@Test
fun test_ScaleType() {
ScaleType.FIT_LONG_SIDE
ScaleType.FIT_SHORT_SIDE
ScaleType.CENTER
ScaleType.FULL_SCREEN
}
}
| 0
|
Kotlin
|
0
| 1
|
b72ac403ce1e38139ab42548967e08e6db347ddd
| 505
|
OpenWallet-aOS
|
Apache License 2.0
|
kProperties-core/src/commonMain/kotlin/de/kotlinBerlin/kProperties/property/KProperty.kt
|
KotlinBerlin
| 276,181,033
| false
| null |
package de.kotlinBerlin.kProperties.property
import de.kotlinBerlin.kProperties.value.KObservableValue
import de.kotlinBerlin.kProperties.value.KWritableValue
/**
* In addition to an [KReadOnlyProperty] a [KProperty] also implements the [KWritableValue] interface and
* so its value can be modified.
*
* Additionally it offers support to bind it to another [KProperty] instance either uni- or bidirectional with the
* [bind] and [bindBidirectional] methods. To remove a binding there are the [unbind] and the [unbindBidirectional]
* methods.
*
* The value of a [KProperty] that is bound unidirectional to another [KProperty] may not be changed manually.
*
* @see [KObservableValue]
* @see [KWritableValue]
*/
interface KProperty<T> : KWritableValue<T>, KReadOnlyProperty<T> {
/**
* The valid state represents whether or not the current value of the [KProperty] instance
* is valid or should be recomputed.
*/
val valid: Boolean
/**
* Binds this [KProperty] to the value of [anObservable]. The value of this [KProperty] may not be changed
* manually as long as it is bound to another [KProperty].
*
* If this [KProperty] is already bound the this binding will be removed first.
*/
fun bind(anObservable: KObservableValue<T>)
/**
* Removes the current binding to another [KProperty].
* If this [KProperty] is not bound then this method is a no-op.
*/
fun unbind()
/**
* Returns whether or not this [KProperty] is currently bound unidirectional to another [KProperty].
*/
fun isBound(): Boolean
/**
* Creates a bidirectional binding between this [KProperty] and [aProperty]. In contrast to the [bind] method
* the value of this [KProperty] may be changed manually even if it is bound bidirectionally to another [KProperty].
*
* One [KProperty] may be bound bidirectionally to more than one other [KProperty].
*/
fun bindBidirectional(aProperty: KProperty<T>)
/**
* Removes the bidirectional binding between this [KProperty] and [aProperty].
*/
fun unbindBidirectional(aProperty: KProperty<T>)
}
| 0
|
Kotlin
|
0
| 1
|
e4f37018e15bb291c68b677d9b1d8b559d80f6d5
| 2,160
|
kProperties
|
Apache License 2.0
|
frontend/silk-foundation/src/jsMain/kotlin/com/varabyte/kobweb/silk/defer/Deferred.kt
|
varabyte
| 389,223,226
| false
|
{"Kotlin": 1688738}
|
package com.varabyte.kobweb.silk.defer
import androidx.compose.runtime.*
import kotlinx.browser.window
private class DeferredComposablesState {
private var timeoutHandle = -1
private val batchedCommands = mutableListOf<() -> Unit>()
private val entries = mutableStateListOf<DeferredComposablesState.Entry>()
// By not running some commands immediately, instead delaying and batching them together, this prevents a bunch of
// intermediate recompositions.
private fun invokeLater(block: () -> Unit) {
batchedCommands.add(block)
if (timeoutHandle == -1) {
timeoutHandle = window.setTimeout({
batchedCommands.forEach { it.invoke() }
batchedCommands.clear()
timeoutHandle = -1
})
}
}
fun append(): Entry = Entry().also {
invokeLater {
entries.add(it)
}
}
@Composable
fun forEach(render: @Composable (Entry) -> Unit) {
entries.forEach { render(it) }
}
inner class Entry {
var content: (@Composable () -> Unit)? = null
fun dismiss() {
invokeLater {
entries.remove(this)
}
}
}
}
private val LocalDeferred = staticCompositionLocalOf<DeferredComposablesState> {
error("Attempting to defer rendering without calling `DeferringHost`, a required pre-requisite.")
}
@Deprecated("Renamed to `Deferred` to be consistent with official Compose naming conventions.",
ReplaceWith("Deferred(content)")
)
@Composable
fun deferRender(content: @Composable () -> Unit) {
Deferred(content)
}
/**
* Defer the target [content] from rendering until the main content is finished.
*
* This has the (often wanted) side effects of making sure the content always appears on top of the main content
* (without needing to use z-index tricks) while also de-parenting the target being rendered (thereby avoiding
* inheriting unexpected styles from element you want to appear beside, not within).
*
* Render deferral is particularly useful for overlays, like modals and tooltips.
*/
@Composable
fun Deferred(content: @Composable () -> Unit) {
val state = LocalDeferred.current
val deferredEntry = remember(state) { state.append() }
deferredEntry.content = content
DisposableEffect(deferredEntry) { onDispose { deferredEntry.dismiss() } }
}
@Deprecated("Renamed to `DeferringHost` to be consistent with official Compose naming conventions.",
ReplaceWith("DeferringHost(content)")
)
@Composable
fun renderWithDeferred(content: @Composable () -> Unit) {
DeferringHost(content)
}
/**
* Wraps a scope within which users can declare [Deferred] blocks.
*
* Any [Deferred] blocks will be deferred until the end of the scope.
*
* For example:
*
* ```
* DeferringHost {
* Box()
* Deferred { Row() }
* Column()
* }
* ```
*
* is equivalent to declaring `Box()`, `Column()`, then `Row()` in that order.
*/
@Composable
fun DeferringHost(content: @Composable () -> Unit) {
val state = DeferredComposablesState()
CompositionLocalProvider(LocalDeferred provides state) {
content()
state.forEach { entry ->
// Deferred content itself may defer more content! Like showing a tooltip within an overlay
// If we don't do this, we end up with the deferred list constantly getting modified and causing
// recompositions as a result.
entry.content?.let { DeferringHost(it) }
}
}
}
| 109
|
Kotlin
|
70
| 1,556
|
da9ea932d01d770cdd6cf2afce50edc9b615fde2
| 3,532
|
kobweb
|
Apache License 2.0
|
app/src/main/java/com/bossed/waej/eventbus/EBSelectPart.kt
|
Ltow
| 710,230,789
| false
|
{"Kotlin": 2304560, "Java": 395495, "HTML": 71364}
|
package com.bossed.waej.eventbus
import com.bossed.waej.javebean.PartListRow
data class EBSelectPart(val data: ArrayList<PartListRow>)
| 0
|
Kotlin
|
0
| 0
|
8c2e9928f6c47484bec7a5beca32ed4b10200f9c
| 136
|
wananexiu
|
Mulan Permissive Software License, Version 2
|
app/src/main/java/com/bossed/waej/eventbus/EBSelectPart.kt
|
Ltow
| 710,230,789
| false
|
{"Kotlin": 2304560, "Java": 395495, "HTML": 71364}
|
package com.bossed.waej.eventbus
import com.bossed.waej.javebean.PartListRow
data class EBSelectPart(val data: ArrayList<PartListRow>)
| 0
|
Kotlin
|
0
| 0
|
8c2e9928f6c47484bec7a5beca32ed4b10200f9c
| 136
|
wananexiu
|
Mulan Permissive Software License, Version 2
|
shepherd-java-api/src/main/kotlin/ShepherdClient.kt
|
mvysny
| 644,365,109
| false
| null |
package com.github.mvysny.shepherd.api
import java.io.Closeable
import java.time.Duration
import java.time.Instant
import java.time.ZoneId
import java.time.ZonedDateTime
public interface ShepherdClient : Closeable {
/**
* Lists all registered projects.
*/
public fun getAllProjectIDs(): List<ProjectId>
/**
* Gets all projects, including metadata.
* @param ownerEmail if not null, return only projects owned by given owner (e-mail address, refers to [ProjectOwner.email].
*/
public fun getAllProjects(ownerEmail: String? = null): List<ProjectView>
/**
* Retrieves info about given project. Fails with an exception if there is no such project.
*/
public fun getProjectInfo(id: ProjectId): Project
/**
* Creates new [project]:
*
* * creates a config file for it on the filesystem (`/etc/shepherd/projects`);
* * creates a Kubernetes config file for the project
* * registers the project to Jenkins and starts first Jenkins build. The build is configured to call the `shepherd-build` script.
*
* Fails if the project json config file already exists. Blocks until the project is created.
*/
public fun createProject(project: Project)
/**
* Updates the project:
* * updates the project config file on the filesystem (`/etc/shepherd/projects`);
* * update a Kubernetes config file for the project, dropping all Kubernetes objects that are no longer necessary.
* * updates the project registration in Jenkins.
* Fails if the project json config file doesn't exist yet.
*
* Restarts the project automatically:
* * either starts a new build in Jenkins if there were any changes in [BuildSpec.buildArgs] or [BuildSpec.dockerFile].
* * otherwise only re-applies the Kubernetes yaml file (if it has been changed).
*
* Note that some properties can not be changed (an exception is thrown by this function if such a change is detected):
* * [Project.id]
* * [Project.gitRepo]
*
* Blocks until the update is fully completed.
*/
public fun updateProject(project: Project)
/**
* Deletes given project: stops and removes all builds, stops and removes all Kubernetes rules,
* and removes the project json config (from `/etc/shepherd/projects`).
*
* This function will still try to unregister the project from Jenkins and Kubernetes
* even if the project json config is already nonexistent.
*
* Blocks until the project is fully deleted. This may take up to 1 minute since
* cleanup of Kubernetes objects is a lengthy operation.
*/
public fun deleteProject(id: ProjectId)
/**
* Retrieves the run logs of the main app pod (=the app itself). There may be additional pods (e.g. PostgreSQL)
* but their logs are not returned.
*/
public fun getRunLogs(id: ProjectId): String
/**
* Returns the current CPU/memory usage of the main app pod.
*/
public fun getRunMetrics(id: ProjectId): ResourcesUsage
/**
* Retrieve the last 30 builds for given project [id].
* @return the list of builds, sorted by [Build.number] ascending.
*/
public fun getLastBuilds(id: ProjectId): List<Build>
/**
* Retrieves the full build log (stdout).
* @param buildNumber pass in [Build.number].
*/
public fun getBuildLog(id: ProjectId, buildNumber: Int): String
}
/**
* @property lastBuild project last build. May be null if there is no build for the project yet.
*/
public data class ProjectView(
val project: Project,
val lastBuild: Build?
) {
val lastBuildOngoing: Boolean get() = lastBuild != null && !lastBuild.isCompleted
/**
* Returns URLs on which this project runs (can be browsed to). E.g. for `vaadin-boot-example-gradle`
* on the `v-herd.eu` [host], this returns `https://v-herd.eu/vaadin-boot-example-gradle`.
*/
public fun getPublishedURLs(host: String): List<String> = project.getPublishedURLs(host)
}
public enum class BuildResult {
FAILURE,
UNSTABLE,
REBUILDING,
BUILDING,
/**
* This means a job was already running and has been aborted.
*/
ABORTED,
/**
*
*/
SUCCESS,
/**
* ?
*/
UNKNOWN,
/**
* This is returned if a job has never been built.
*/
NOT_BUILT,
/**
* This will be the result of a job in cases where it has been cancelled
* during the time in the queue.
*/
CANCELLED
}
/**
* Resources the app uses.
* @property memoryMb current memory usage, in megabytes.
* @property cpu CPU usage, relative to one core. 1 means 1 CPU core is fully used; 0.5 means that
* half of one CPU core is used; 2 means that two CPU cores are fully utilized.
*/
public data class ResourcesUsage(
val memoryMb: Int,
val cpu: Float
) {
init {
require(memoryMb >= 0) { "memoryMb: must be 0 or higher but got $memoryMb" }
require(cpu >= 0) { "cpu: must be 0 or higher but was $cpu" }
}
public companion object {
@JvmStatic
public val zero: ResourcesUsage = ResourcesUsage(0, 0f)
}
}
/**
* Contains information about a particular build of an app.
* @property number the build number, starts with 1, second build has the number of 2 etc.
* @property duration how long the build took. 0 if the build is not yet complete.
* @property estimatedDuration estimated duration based on previous builds
* @property buildStarted when the build started
* @property outcome the outcome or [BuildResult.BUILDING] if not yet completed.
*/
public data class Build(
val number: Int,
val duration: Duration,
val estimatedDuration: Duration,
val buildStarted: Instant,
val outcome: BuildResult
) {
val isCompleted: Boolean get() = outcome != BuildResult.BUILDING
/**
* When the build ended; null if the build is not yet completed.
*/
val buildEnded: Instant? get() = if (!isCompleted) {
null
} else {
buildStarted + duration
}
}
| 2
|
Kotlin
|
0
| 0
|
511497749cbdba3133a57c1b4d75ee18c5b5b406
| 6,092
|
shepherd-java-client
|
Apache License 2.0
|
app/src/main/java/com/zaenur/androidbasickotlindiceroller/Dice.kt
|
rochman25
| 471,257,517
| false
|
{"Kotlin": 2407}
|
package com.zaenur.androidbasickotlindiceroller
class Dice(private val numSides: Int) {
fun roll(): Int {
return (1..numSides).random()
}
}
| 0
|
Kotlin
|
0
| 0
|
4db477a5998341db13acbeb099682988f1f93841
| 158
|
android-basic-kotlin-dice-roller
|
The Unlicense
|
design/src/main/java/dev/kadirkid/pagingtest/design/core/color/BackgroundColors.kt
|
kadirkid
| 732,869,570
| false
|
{"Kotlin": 63479}
|
/**
* Copyright (c) 2023 <NAME>
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package dev.kadirkid.pagingtest.design.core.color
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.ProvidableCompositionLocal
import androidx.compose.runtime.staticCompositionLocalOf
import dev.kadirkid.pagingtest.design.core.BackgroundColor
import dev.kadirkid.pagingtest.design.md_theme_dark_errorContainer
import dev.kadirkid.pagingtest.design.md_theme_dark_onPrimaryContainer
import dev.kadirkid.pagingtest.design.md_theme_dark_onSecondaryContainer
import dev.kadirkid.pagingtest.design.md_theme_dark_onTertiaryContainer
import dev.kadirkid.pagingtest.design.md_theme_dark_primaryContainer
import dev.kadirkid.pagingtest.design.md_theme_dark_secondaryContainer
import dev.kadirkid.pagingtest.design.md_theme_dark_surface
import dev.kadirkid.pagingtest.design.md_theme_dark_tertiaryContainer
import dev.kadirkid.pagingtest.design.md_theme_light_errorContainer
import dev.kadirkid.pagingtest.design.md_theme_light_onPrimaryContainer
import dev.kadirkid.pagingtest.design.md_theme_light_onSecondaryContainer
import dev.kadirkid.pagingtest.design.md_theme_light_onTertiaryContainer
import dev.kadirkid.pagingtest.design.md_theme_light_primaryContainer
import dev.kadirkid.pagingtest.design.md_theme_light_secondaryContainer
import dev.kadirkid.pagingtest.design.md_theme_light_surface
import dev.kadirkid.pagingtest.design.md_theme_light_tertiaryContainer
@Immutable
public class BackgroundColors internal constructor(
public val primary: BackgroundColor,
public val secondary: BackgroundColor,
public val tertiary: BackgroundColor,
public val onPrimary: BackgroundColor,
public val onSecondary: BackgroundColor,
public val onTertiary: BackgroundColor,
public val surface: BackgroundColor,
public val error: BackgroundColor,
)
public val LocalBackgroundColors: ProvidableCompositionLocal<BackgroundColors> =
staticCompositionLocalOf { error("No BackgroundColors provided") }
internal fun lightBackgroundColors(): BackgroundColors = BackgroundColors(
primary = BackgroundColor(md_theme_light_primaryContainer),
secondary = BackgroundColor(md_theme_light_secondaryContainer),
tertiary = BackgroundColor(md_theme_light_tertiaryContainer),
onPrimary = BackgroundColor(md_theme_light_onPrimaryContainer),
onSecondary = BackgroundColor(md_theme_light_onSecondaryContainer),
onTertiary = BackgroundColor(md_theme_light_onTertiaryContainer),
surface = BackgroundColor(md_theme_light_surface),
error = BackgroundColor(md_theme_light_errorContainer),
)
internal fun darkBackgroundColors(): BackgroundColors = BackgroundColors(
primary = BackgroundColor(md_theme_dark_primaryContainer),
secondary = BackgroundColor(md_theme_dark_secondaryContainer),
tertiary = BackgroundColor(md_theme_dark_tertiaryContainer),
onPrimary = BackgroundColor(md_theme_dark_onPrimaryContainer),
onSecondary = BackgroundColor(md_theme_dark_onSecondaryContainer),
onTertiary = BackgroundColor(md_theme_dark_onTertiaryContainer),
surface = BackgroundColor(md_theme_dark_surface),
error = BackgroundColor(md_theme_dark_errorContainer),
)
internal fun BackgroundColors.withNames() = buildList {
add("primary" to primary)
add("secondary" to secondary)
add("tertiary" to tertiary)
add("error" to error)
}
| 0
|
Kotlin
|
0
| 0
|
6f19cc1b117905e29203926b9e95c9e21828d413
| 3,479
|
Pagingtest
|
MIT License
|
src/main/kotlin/com/vk/modulite/actions/usages/yaml/FindSymbolUsagesInSelectedModuleAction.kt
|
VKCOM
| 568,834,307
| false
|
{"Kotlin": 422298, "HTML": 610, "PHP": 478}
|
package com.vk.modulite.actions.usages.yaml
import com.intellij.openapi.actionSystem.AnActionEvent
import com.vk.modulite.actions.YamlPsiElementAction
import com.vk.modulite.actions.dialogs.SelectFindUsagesModuliteDialog
import com.vk.modulite.psi.extensions.files.containingModulite
import org.jetbrains.yaml.psi.YAMLQuotedText
class FindSymbolUsagesInSelectedModuleAction : YamlPsiElementAction<YAMLQuotedText>(YAMLQuotedText::class.java) {
override fun actionPerformed(element: YAMLQuotedText) {
val modulite = SelectFindUsagesModuliteDialog.request(element.project, element.containingModulite()) ?: return
YamlUsagesFinder(modulite).find(element)
}
override fun update(e: AnActionEvent, element: YAMLQuotedText?) {
if (element == null) {
e.presentation.isEnabledAndVisible = false
return
}
val value = element.text
val isModuliteName = value.contains("@")
val isComposerPackageName = value.contains("#")
if (isModuliteName || isComposerPackageName) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.text = "Find Usages in Modulite..."
}
override val errorHint: String = "Error"
}
| 16
|
Kotlin
|
4
| 65
|
1710a34883000389383020524ac77e8bcae45bfc
| 1,257
|
modulite
|
MIT License
|
src/main/kotlin/team/msg/hiv2/global/error/GlobalExceptionHandler.kt
|
GSM-MSG
| 634,687,373
| false
| null |
package team.msg.hiv2.global.error
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import team.msg.hiv2.global.error.exception.HiException
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(HiException::class)
fun handleHiException(e: HiException): ResponseEntity<ErrorResponse> =
ResponseEntity(
ErrorResponse(e.errorCode.message, e.errorCode.status),
HttpStatus.valueOf(e.errorCode.status)
)
}
| 0
|
Kotlin
|
0
| 9
|
a5010400e231335fa0ccb7cd77b5562fd90aca2d
| 640
|
Hi-v2-BackEnd
|
MIT License
|
intellij-plugin/educational-core/testSrc/com/jetbrains/edu/coursecreator/actions/create/CCCreateFrameworkTaskTest.kt
|
JetBrains
| 43,696,115
| false
|
{"Kotlin": 5014435, "Java": 42267, "Python": 19649, "HTML": 14893, "CSS": 10327, "JavaScript": 302, "Shell": 71}
|
package com.jetbrains.edu.coursecreator.actions.create
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.LightPlatformTestCase
import com.jetbrains.edu.coursecreator.actions.studyItem.CCCreateTask
import com.jetbrains.edu.coursecreator.ui.withMockCreateStudyItemUi
import com.jetbrains.edu.learning.EduActionTestCase
import com.jetbrains.edu.learning.courseFormat.CourseMode
import com.jetbrains.edu.learning.fileTree
import com.jetbrains.edu.learning.testAction
import org.junit.Assert.assertArrayEquals
import org.junit.Test
class CCCreateFrameworkTaskTest : EduActionTestCase() {
private val root: VirtualFile get() = LightPlatformTestCase.getSourceRoot()
override fun getTestDataPath(): String = super.getTestDataPath() + "/actions/frameworkLessons"
@Test
fun `test first task in framework lesson`() {
val lessonName = "FrameworkLesson"
val taskName = "Task"
val course = courseWithFiles(courseMode = CourseMode.EDUCATOR) {
frameworkLesson(lessonName)
}
val lessonFile = findFile(lessonName)
withMockCreateStudyItemUi(MockNewStudyItemUi(taskName)) {
withVirtualFileListener(course) {
testAction(CCCreateTask.ACTION_ID, dataContext(lessonFile))
}
}
fileTree {
dir(lessonName) {
dir(taskName) {
file("Task.txt")
dir("tests") {
file("Tests.txt")
}
file("task.md")
}
}
}.assertEquals(root)
assertEquals(1, course.lessons[0].taskList.size)
}
@Test
fun `test new task in framework lesson`() {
val lessonName = "FrameworkLesson"
val course = courseWithFiles(courseMode = CourseMode.EDUCATOR) {
frameworkLesson(lessonName) {
eduTask("task1") {
taskFile("Task.kt", "fun foo(): String = <p>TODO()</p>") {
placeholder(0, "\"Foo\"")
}
taskFile("build.gradle")
}
}
}
val newTaskName = "task2"
val lessonFile = findFile(lessonName)
withMockCreateStudyItemUi(MockNewStudyItemUi(newTaskName)) {
withVirtualFileListener(course) {
testAction(CCCreateTask.ACTION_ID, dataContext(lessonFile))
}
}
fileTree {
dir(lessonName) {
dir("task1") {
file("Task.kt", "fun foo(): String = \"Foo\"")
file("build.gradle")
file("task.md")
}
dir(newTaskName) {
file("Task.kt", "fun foo(): String = \"Foo\"")
file("build.gradle")
file("task.md")
dir("tests") {
file("Tests.txt")
}
}
}
}.assertEquals(root, myFixture)
assertEquals(2, course.lessons[0].taskList.size)
val createdTask = course.lessons[0].taskList[1]
assertEquals(3, createdTask.taskFiles.size)
val prevTaskFile = course.lessons[0].taskList[0].taskFiles["Task.kt"] ?: error("Can't find `Task.kt` file")
val taskFile = createdTask.taskFiles["Task.kt"] ?: error("Can't find `Task.kt` file")
assertEquals(prevTaskFile.name, taskFile.name)
assertEquals(1, taskFile.answerPlaceholders.size)
val placeholder = taskFile.answerPlaceholders[0]
val targetPlaceholder = placeholder.placeholderDependency?.resolve(course) ?: error("Can't resolve placeholder dependency")
assertEquals(prevTaskFile.answerPlaceholders[0], targetPlaceholder)
}
@Test
fun `test new task in the middle of lesson`() {
val course = courseWithFiles(courseMode = CourseMode.EDUCATOR) {
frameworkLesson {
eduTask {
taskFile("Task.kt", """
fun foo(): String = <p>TODO()</p>
fun bar(): String = <p>TODO()</p>
""") {
placeholder(0, "\"Foo\"")
placeholder(1, "\"Bar\"")
}
}
eduTask {
taskFile("Foo.kt", """
fun foo(): String = <p>TODO()</p>
""") {
placeholder(0, "\"Foo\"", dependency = "lesson1#task1#Task.kt#1")
}
taskFile("Bar.kt", """
fun bar(): String = <p>TODO()</p>
""") {
placeholder(0, "\"Bar\"", dependency = "lesson1#task1#Task.kt#2")
}
}
}
}
val task1 = course.lessons[0].getTask("task1") ?: error("Can't find `task1`")
val task2 = course.lessons[0].getTask("task2") ?: error("Can't find `task2`")
val firstTaskFile = findFile("lesson1/task1")
withMockCreateStudyItemUi(MockNewStudyItemUi("task1.5", 2)) {
testAction(CCCreateTask.ACTION_ID, dataContext(firstTaskFile))
}
val insertedTask = course.lessons[0].getTask("task1.5") ?: error("Can't find `task1.5`")
val taskFile = insertedTask.getTaskFile("Task.kt") ?: error("Can't find `Task.kt` in `task1.5`")
// Check that all placeholders of new task refer to prev task
assertEquals(task1.getTaskFile("Task.kt")!!.answerPlaceholders[0],
taskFile.answerPlaceholders[0].placeholderDependency?.resolve(course))
assertEquals(task1.getTaskFile("Task.kt")!!.answerPlaceholders[1],
taskFile.answerPlaceholders[1].placeholderDependency?.resolve(course))
// Check that all placeholders of next task refer to new task
assertEquals(taskFile.answerPlaceholders[0],
task2.getTaskFile("Foo.kt")?.answerPlaceholders?.get(0)?.placeholderDependency?.resolve(course))
assertEquals(taskFile.answerPlaceholders[1],
task2.getTaskFile("Bar.kt")?.answerPlaceholders?.get(0)?.placeholderDependency?.resolve(course))
}
@Test
fun `test copy images`() {
val lessonName = "lesson1"
val imageName = "image.png"
val course = courseWithFiles(courseMode = CourseMode.EDUCATOR) {
frameworkLesson(lessonName) {
eduTask {
taskFile("Task.kt")
taskFileFromResources(testRootDisposable, imageName, "$testDataPath/$imageName")
}
}
}
val newTaskName = "task2"
val lessonFile = findFile(lessonName)
withVirtualFileListener(course) {
withMockCreateStudyItemUi(MockNewStudyItemUi(newTaskName)) {
testAction(CCCreateTask.ACTION_ID, dataContext(lessonFile))
}
}
fileTree {
dir(lessonName) {
dir("task1") {
file("Task.kt")
file(imageName)
file("task.md")
}
dir(newTaskName) {
file("Task.kt")
file(imageName)
file("task.md")
dir("tests") {
file("Tests.txt")
}
}
}
}.assertEquals(root)
val originalImage = findFile("$lessonName/task1/$imageName")
val imageCopy = findFile("$lessonName/$newTaskName/$imageName")
assertArrayEquals("Contents of `$originalImage` and `$imageCopy` differ",
VfsUtil.loadBytes(originalImage),
VfsUtil.loadBytes(imageCopy))
}
@Test
fun `test copy actual text of files`() {
val lessonName = "lesson1"
val course = courseWithFiles(courseMode = CourseMode.EDUCATOR) {
frameworkLesson(lessonName) {
eduTask("task1") {
taskFile("Task.kt", "fun foo(): String = TODO()")
taskFile("build.gradle", "apply plugin: \"kotlin\"")
}
}
}
typeAtTheEndOfFile("lesson1/task1/Task.kt", "\nfun bar(): String = TODO()")
typeAtTheEndOfFile("lesson1/task1/build.gradle", "\napply plugin: \"java\"")
val newTaskName = "task2"
val lessonFile = findFile(lessonName)
withVirtualFileListener(course) {
withMockCreateStudyItemUi(MockNewStudyItemUi(newTaskName)) {
testAction(CCCreateTask.ACTION_ID, dataContext(lessonFile))
}
}
fileTree {
dir(lessonName) {
dir("task1") {
file("Task.kt", """
fun foo(): String = TODO()
fun bar(): String = TODO()
""")
file("build.gradle", """
apply plugin: "kotlin"
apply plugin: "java"
""")
file("task.md")
}
dir(newTaskName) {
file("Task.kt", """
fun foo(): String = TODO()
fun bar(): String = TODO()
""")
file("build.gradle", """
apply plugin: "kotlin"
apply plugin: "java"
""")
file("task.md")
dir("tests") {
file("Tests.txt")
}
}
}
}.assertEquals(root, myFixture)
}
@Test
fun `test copy propagatable property of files`() {
val lessonName = "lesson"
val course = courseWithFiles(courseMode = CourseMode.EDUCATOR) {
frameworkLesson(lessonName) {
eduTask("task1") {
taskFile("src/Task.kt", "fun foo() {}", propagatable = true)
taskFile("src/Baz.kt", "fun baz() {}", propagatable = false)
taskFile("test/Tests1.kt", "fun tests1() {}", propagatable = false)
taskFile("test/Tests2.kt", "fun tests2() {}", propagatable = true)
}
}
}
val lesson = course.lessons.first()
val newTaskName = "task2"
val lessonFile = findFile(lessonName)
withVirtualFileListener(course) {
withMockCreateStudyItemUi(MockNewStudyItemUi(newTaskName)) {
testAction(CCCreateTask.ACTION_ID, dataContext(lessonFile))
}
}
val task2 = lesson.getTask(newTaskName)!!
assertEquals(true, task2.taskFiles["src/Task.kt"]?.isPropagatable)
assertEquals(false, task2.taskFiles["src/Baz.kt"]?.isPropagatable)
assertEquals(false, task2.taskFiles["test/Tests1.kt"]?.isPropagatable)
assertEquals(true, task2.taskFiles["test/Tests2.kt"]?.isPropagatable)
}
@Test
fun `test tests files in edu task are non-propagatable by default`() {
val lessonName = "lesson"
val course = courseWithFiles(courseMode = CourseMode.EDUCATOR) {
frameworkLesson(lessonName)
}
val lesson = course.lessons.first()
val taskName = "task1"
val lessonFile = findFile(lessonName)
withVirtualFileListener(course) {
withMockCreateStudyItemUi(MockNewStudyItemUi(taskName)) {
testAction(CCCreateTask.ACTION_ID, dataContext(lessonFile))
}
}
val task = lesson.getTask(taskName)!!
assertEquals(true, task.taskFiles["Task.txt"]?.isPropagatable)
assertEquals(false, task.taskFiles["tests/Tests.txt"]?.isPropagatable)
}
@Test
fun `test input and output files in output task are non-propagatable by default`() {
val lessonName = "lesson"
val course = courseWithFiles(courseMode = CourseMode.EDUCATOR) {
frameworkLesson(lessonName)
}
val lesson = course.lessons.first()
val taskName = "task1"
val lessonFile = findFile(lessonName)
withVirtualFileListener(course) {
withMockCreateStudyItemUi(MockNewStudyItemUi(taskName, itemType = "Output")) {
testAction(CCCreateTask.ACTION_ID, dataContext(lessonFile))
}
}
val task = lesson.getTask(taskName)!!
assertEquals(false, task.taskFiles["tests/input.txt"]?.isPropagatable)
assertEquals(false, task.taskFiles["tests/output.txt"]?.isPropagatable)
assertEquals(true, task.taskFiles["Main.txt"]?.isPropagatable)
}
private fun typeAtTheEndOfFile(path: String, text: String) {
val psiFile = myFixture.configureFromTempProjectFile(path)
myFixture.editor.caretModel.moveToOffset(psiFile.textLength)
myFixture.type(text)
}
}
| 7
|
Kotlin
|
49
| 150
|
9cec6c97d896f4485e76cf9a2a95f8a8dd21c982
| 11,369
|
educational-plugin
|
Apache License 2.0
|
src/commonTest/kotlin/serialize/search/TestExactOnSingleWordQuery.kt
|
pallavirawat
| 205,637,107
| true
|
{"Kotlin": 941656, "Ruby": 4462}
|
package serialize.search
import com.algolia.search.model.search.ExactOnSingleWordQuery
import com.algolia.search.model.search.ExactOnSingleWordQuery.*
import kotlinx.serialization.json.JsonLiteral
import serialize.TestSerializer
import unknown
internal class TestExactOnSingleWordQuery : TestSerializer<ExactOnSingleWordQuery>(
ExactOnSingleWordQuery
) {
override val items = listOf(
Attribute to JsonLiteral(Attribute.raw),
None to JsonLiteral(None.raw),
Word to JsonLiteral(Word.raw),
Other(unknown) to JsonLiteral(unknown)
)
}
| 0
|
Kotlin
|
0
| 0
|
a7127793476d4453873266222ea71b1fce5c8c32
| 577
|
algoliasearch-client-kotlin
|
MIT License
|
db-objekts-core/src/test/kotlin/com/dbobjekts/metadata/joins/ManualJoinBuilderTest.kt
|
jaspersprengers
| 576,889,038
| false
| null |
package com.dbobjekts.metadata.joins
import com.dbobjekts.testdb.acme.CatalogDefinition
import com.dbobjekts.testdb.acme.core.Address
import com.dbobjekts.testdb.acme.core.Country
import com.dbobjekts.testdb.acme.core.Employee
import com.dbobjekts.testdb.acme.core.EmployeeAddress
import com.dbobjekts.testdb.acme.library.Composite
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class ManualJoinBuilderTest {
val e = Employee
val a = Address
val ea = EmployeeAddress
val c = Country
val co = Composite
@BeforeEach
fun setup() {
val c = CatalogDefinition
}
@Test
fun `join Employee and Country`() {
assertThat(Employee
.leftJoin(EmployeeAddress).on(e.id.eq(ea.employeeId))
.leftJoin(Address).on(a.id.eq(ea.addressId))
.leftJoin(Country).on(c.id.eq(a.countryId)).toSQL())
.isEqualTo("CORE.EMPLOYEE em LEFT JOIN CORE.EMPLOYEE_ADDRESS ea on em.ID = ea.EMPLOYEE_ID LEFT JOIN CORE.ADDRESS ad on ad.ID = ea.ADDRESS_ID LEFT JOIN CORE.COUNTRY co on co.ID = ad.COUNTRY_ID")
}
}
| 0
|
Kotlin
|
2
| 4
|
51b40a89c2ae648cb720073538ca7a3ee712b49e
| 1,160
|
db-objekts
|
Apache License 2.0
|
apps/mvpapp/src/main/java/dev/eduayuso/cleansamples/mvpapp/features/posts/OnPostClickListener.kt
|
eduayuso
| 340,966,656
| false
| null |
package dev.eduayuso.cleansamples.mvpapp.features.posts
interface OnPostClickListener {
fun onPostClick(id: String)
}
| 1
|
Kotlin
|
0
| 0
|
d42fe931d229636596b7e969405e5c9d04e3a290
| 123
|
clean_samples
|
Apache License 2.0
|
app/src/androidTest/java/ir/amirsobhan/sticknote/utils/RecyclerViewTestUtils.kt
|
a1383n
| 342,316,747
| false
| null |
package ir.amirsobhan.sticknote.utils
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.NoMatchingViewException
import androidx.test.espresso.ViewAssertion
import com.google.common.truth.Truth.assertThat
import ir.amirsobhan.sticknote.R
import ir.amirsobhan.sticknote.database.Note
class RecyclerViewItemCountAssertion(private val expectedCount: Int) : ViewAssertion {
override fun check(view: View, noViewFoundException: NoMatchingViewException?) {
if (noViewFoundException != null) {
throw noViewFoundException
}
val recyclerView = view as RecyclerView
val adapter = recyclerView.adapter
assertThat(adapter?.itemCount).isEqualTo(expectedCount)
}
}
class RecyclerViewSimpleItemCheckAssertion(private val list: List<Note>) : ViewAssertion{
override fun check(view: View?, noViewFoundException: NoMatchingViewException?) {
if (noViewFoundException != null) {
throw noViewFoundException
}
val recyclerView = view as RecyclerView
var i = 0
while (recyclerView.childCount > i){
val note = list[i]
val view = recyclerView.getChildAt(i)
assertThat(view.findViewById<TextView>(R.id.title).text).isEqualTo(note.title)
i++
}
}
}
| 11
|
Kotlin
|
0
| 1
|
f34e4f45e63cd5965fbd883502d15bb0e0e99daf
| 1,387
|
sticknote
|
MIT License
|
server/src/main/kotlin/nl/ordina/robotics/server/transport/cli/Script.kt
|
Ordina-Group
| 632,941,364
| false
|
{"Kotlin": 102174, "Svelte": 35570, "TypeScript": 14959, "JavaScript": 2253, "HTML": 1407, "Dockerfile": 264, "CSS": 114}
|
package nl.ordina.robotics.server.transport.cli
import kotlinx.serialization.Serializable
import nl.ordina.robotics.server.robot.RobotSettings
import nl.ordina.robotics.server.socket.Message
typealias InstructionExecutor = suspend (Instruction) -> InstructionResult
fun interface Script {
suspend fun run(execute: InstructionExecutor): Message
}
@Serializable
data class Instruction(
val value: List<String>,
val withSudo: Boolean = false,
val inWorkDir: Boolean = false,
val separator: String = Cmd.Unix.And,
) {
constructor(
vararg value: String,
withSudo: Boolean = false,
inWorkDir: Boolean = false,
separator: String = Cmd.Unix.And,
) : this(value.toList(), withSudo, inWorkDir, separator)
fun toInstructionString(robotSettings: RobotSettings): String {
val prefixes = listOf(
if (inWorkDir) "${Cmd.Unix.cd(robotSettings.workDir)} && " else "",
if (withSudo) sudoPrefix(robotSettings.password) else "",
).joinToString(" ")
return value.joinToString(
separator,
prefix = prefixes,
)
}
}
@Serializable
data class InstructionResult(
val result: String?,
val error: String? = null,
) {
init {
require(result != null || error != null) {
"Either result or error must be set."
}
}
val resultOrError: String
get() = result ?: error!!
val success: Boolean
get() = error == null
}
| 0
|
Kotlin
|
0
| 0
|
eab777ebd1b8b0a3810184ad1211d5e1f2b4e437
| 1,501
|
robotics-chief
|
MIT License
|
app/src/main/java/com/jamesnyakush/carhub/ui/auth/Register.kt
|
danny-o
| 252,690,988
| true
|
{"Kotlin": 48808}
|
package com.jamesnyakush.carhub.ui.auth
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.jamesnyakush.carhub.R
import com.jamesnyakush.carhub.data.db.entity.User
import com.jamesnyakush.carhub.data.listeners.AuthListener
import com.jamesnyakush.carhub.databinding.ActivityRegisterBinding
import com.jamesnyakush.carhub.ui.home.main.MainActivity
import com.jamesnyakush.carhub.util.snackbar
import com.jamesnyakush.carhub.util.toast
import kotlinx.android.synthetic.main.activity_register.*
import org.kodein.di.KodeinAware
import org.kodein.di.android.kodein
import org.kodein.di.generic.instance
class Register : AppCompatActivity(), AuthListener,KodeinAware {
override val kodein by kodein()
private val factory: AuthViewModelFactory by instance()
lateinit var viewModel: AuthViewModel
lateinit var binding: ActivityRegisterBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar!!.hide()
binding = DataBindingUtil.setContentView(this, R.layout.activity_register)
viewModel = ViewModelProviders.of(this,factory).get(AuthViewModel::class.java)
binding.viewmodel = viewModel
viewModel.authListener = this
viewModel.getLoggedInUser().observe(this, Observer { user ->
if (user != null) {
Intent(this, MainActivity::class.java).also {
it.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(it)
}
}
})
}
override fun onStarted() {
}
override fun onSuccess(user: User) {
toast("Registered Successfully")
}
override fun onFailiure(msg: String) {
register_layout.snackbar(msg)
}
}
| 0
| null |
0
| 0
|
6e370ae7cbe3e88bfa028786300e5623f8d88bd6
| 1,991
|
truck-hub
|
Apache License 2.0
|
core/src/main/java/com/summit/core/status/Status.kt
|
cesarwillymc
| 326,488,032
| false
| null |
package com.summit.core.status
enum class Status {
SUCCESS,
LOADING,
ERROR
}
| 0
|
Kotlin
|
0
| 2
|
9583792cfc3832bdc5b76584ff90a741f4b87458
| 93
|
AddFast
|
Apache License 2.0
|
src/test/kotlin/g0401_0500/s0401_binary_watch/SolutionTest.kt
|
javadev
| 190,711,550
| false
|
{"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994}
|
package g0401_0500.s0401_binary_watch
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun readBinaryWatch() {
assertThat(
Solution().readBinaryWatch(1),
equalTo(
listOf(
"0:01", "0:02", "0:04", "0:08", "0:16", "0:32", "1:00", "2:00",
"4:00", "8:00"
)
)
)
}
@Test
fun readBinaryWatch2() {
assertThat(
Solution().readBinaryWatch(9),
equalTo(
listOf()
)
)
}
}
| 0
|
Kotlin
|
20
| 43
|
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
| 684
|
LeetCode-in-Kotlin
|
MIT License
|
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Tshirt.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.Tshirt: ImageVector
get() {
if (_tshirt != null) {
return _tshirt!!
}
_tshirt = Builder(name = "Tshirt", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(24.0f, 6.636f)
curveToRelative(0.0f, -2.301f, -1.221f, -4.386f, -3.185f, -5.44f)
curveToRelative(-1.477f, -0.793f, -3.032f, -1.195f, -4.625f, -1.195f)
lineTo(7.81f, 0.001f)
curveToRelative(-1.592f, 0.0f, -3.148f, 0.402f, -4.625f, 1.195f)
curveTo(1.221f, 2.25f, 0.0f, 4.335f, 0.0f, 6.636f)
verticalLineToRelative(5.388f)
horizontalLineToRelative(4.0f)
verticalLineToRelative(11.976f)
horizontalLineToRelative(16.0f)
verticalLineToRelative(-12.0f)
horizontalLineToRelative(4.0f)
verticalLineToRelative(-5.364f)
close()
moveTo(14.901f, 2.0f)
curveToRelative(-0.455f, 1.196f, -1.593f, 2.0f, -2.901f, 2.0f)
reflectiveCurveToRelative(-2.446f, -0.804f, -2.901f, -2.0f)
horizontalLineToRelative(5.802f)
close()
moveTo(22.0f, 10.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-3.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(15.0f)
lineTo(6.0f, 22.0f)
lineTo(6.0f, 7.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(3.024f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-3.388f)
curveToRelative(0.0f, -1.563f, 0.817f, -2.973f, 2.131f, -3.679f)
curveToRelative(0.939f, -0.504f, 1.913f, -0.81f, 2.905f, -0.915f)
lineToRelative(-0.01f, 0.002f)
curveToRelative(0.542f, 2.329f, 2.587f, 3.956f, 4.974f, 3.956f)
reflectiveCurveToRelative(4.432f, -1.627f, 4.974f, -3.956f)
lineToRelative(-0.01f, -0.002f)
curveToRelative(0.991f, 0.105f, 1.965f, 0.411f, 2.905f, 0.915f)
curveToRelative(1.314f, 0.706f, 2.131f, 2.116f, 2.131f, 3.679f)
verticalLineToRelative(3.364f)
close()
}
}
.build()
return _tshirt!!
}
private var _tshirt: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,350
|
icons
|
MIT License
|
yandex-mapkit-kmp/src/androidMain/kotlin/ru/sulgik/mapkit/map/ClusterListener.android.kt
|
SuLG-ik
| 813,953,018
| false
|
{"Kotlin": 321441}
|
package ru.sulgik.mapkit.map
import ru.sulgik.mapkit.geometry.Cluster
import ru.sulgik.mapkit.geometry.toCommon
import com.yandex.mapkit.map.ClusterListener as NativeClusterListener
public actual abstract class ClusterListener actual constructor() {
private val nativeListener = NativeClusterListener { onClusterAdded(it.toCommon()) }
public fun toNative(): NativeClusterListener {
return nativeListener
}
public actual abstract fun onClusterAdded(cluster: Cluster)
}
| 0
|
Kotlin
|
1
| 17
|
2d292b701adb2c538f8cd3ddf614250f9d6a444d
| 497
|
yandex-mapkit-kmp
|
Apache License 2.0
|
src/test/kotlin/jamilservices/ComponentIdGeneratorTest.kt
|
jamilservices
| 836,473,913
| false
|
{"Kotlin": 5947}
|
/*-
* #%L
* component-id-generator
* %%
* Copyright (C) 2024 Jamil Services
* %%
* 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.
* #L%
*/
import com.jamilservices.JComponentIdGenerator
import org.junit.Test
import kotlin.test.assertEquals
import com.google.gson.JsonObject
import java.io.File
import java.util.UUID
import com.google.gson.Gson
class JComponentIdGeneratorTest {
@Test
fun `tthis generation of IDs for components`() {
val inputFile = File("input.json")
inputFile.writeText("[\"component1\", \"component2\", \"component3\"]")
val outputFile = File("output.json")
JComponentIdGenerator.main(arrayOf("input.json", "output.json"))
val outputJson = outputFile.readText()
val gson = Gson()
val outputObject: JsonObject = gson.fromJson(outputJson, JsonObject::class.java)
assertEquals(3, outputObject.size())
assertEquals(true, outputObject.has("component1"))
assertEquals(true, outputObject.has("component2"))
assertEquals(true, outputObject.has("component3"))
val component1Id = outputObject.get("component1").asString
val component2Id = outputObject.get("component2").asString
val component3Id = outputObject.get("component3").asString
assertEquals(true, UUID.fromString(component1Id)!= null)
assertEquals(true, UUID.fromString(component2Id)!= null)
assertEquals(true, UUID.fromString(component3Id)!= null)
inputFile.delete()
outputFile.delete()
}
}
| 0
|
Kotlin
|
0
| 0
|
901c27f33c448990efb4b784d80cc073b6ba7e47
| 2,569
|
component-id-generator
|
MIT License
|
src/all/comicznetv2/src/eu/kanade/tachiyomi/extension/all/comicznetv2/ComiczNetV2.kt
|
komikku-app
| 720,497,299
| false
|
{"Kotlin": 6775539, "JavaScript": 2160}
|
package eu.kanade.tachiyomi.extension.all.comicznetv2
import eu.kanade.tachiyomi.multisrc.madara.Madara
class ComiczNetV2 : Madara("Comicz.net v2", "https://v2.comiz.net", "all") {
override val useNewChapterEndpoint = false
}
| 22
|
Kotlin
|
8
| 97
|
7fc1d11ee314376fe0daa87755a7590a03bc11c0
| 232
|
komikku-extensions
|
Apache License 2.0
|
MirrorTrips-main/app/src/main/java/com/ipca/budget/travelmobile/entities/Destiny.kt
|
ademar1k82
| 676,015,143
| false
|
{"Kotlin": 32495}
|
package com.ipca.budget.travelmobile.entities
import org.json.JSONObject
class Destiny {
var name: String? = null
var country: String? = null
var image: String? = null
var apiTime: String? = null
var description: String? = null
var tourismLink: String? = null
var youtubeLink: String? = null
var airport: String? = null
var cityHotel: String? = null
fun toJSON() : JSONObject{
val jsonObject = JSONObject()
jsonObject.put("name", name)
jsonObject.put("country", country)
jsonObject.put("image", image)
jsonObject.put("apiTime" , apiTime)
jsonObject.put("description" , description)
jsonObject.put("tourismLink" , tourismLink)
jsonObject.put("youtubeLink" , youtubeLink)
jsonObject.put("airport" , airport)
return jsonObject
}
companion object {
fun fromJSON(jsonObject: JSONObject) : Destiny {
return Destiny().apply {
name = jsonObject.getString("name")
country = jsonObject.getString("country")
image = jsonObject.getString("image")
apiTime = jsonObject.getString("apiTime")
description = jsonObject.getString("description")
tourismLink = jsonObject.getString("tourismLink")
youtubeLink = jsonObject.getString("youtubeLink")
airport = jsonObject.getString("airport")
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
444215982a8fa0bb32e32e5722e4ad73cb4cd6e2
| 1,484
|
mirrortrips
|
FSF All Permissive License
|
MirrorTrips-main/app/src/main/java/com/ipca/budget/travelmobile/entities/Destiny.kt
|
ademar1k82
| 676,015,143
| false
|
{"Kotlin": 32495}
|
package com.ipca.budget.travelmobile.entities
import org.json.JSONObject
class Destiny {
var name: String? = null
var country: String? = null
var image: String? = null
var apiTime: String? = null
var description: String? = null
var tourismLink: String? = null
var youtubeLink: String? = null
var airport: String? = null
var cityHotel: String? = null
fun toJSON() : JSONObject{
val jsonObject = JSONObject()
jsonObject.put("name", name)
jsonObject.put("country", country)
jsonObject.put("image", image)
jsonObject.put("apiTime" , apiTime)
jsonObject.put("description" , description)
jsonObject.put("tourismLink" , tourismLink)
jsonObject.put("youtubeLink" , youtubeLink)
jsonObject.put("airport" , airport)
return jsonObject
}
companion object {
fun fromJSON(jsonObject: JSONObject) : Destiny {
return Destiny().apply {
name = jsonObject.getString("name")
country = jsonObject.getString("country")
image = jsonObject.getString("image")
apiTime = jsonObject.getString("apiTime")
description = jsonObject.getString("description")
tourismLink = jsonObject.getString("tourismLink")
youtubeLink = jsonObject.getString("youtubeLink")
airport = jsonObject.getString("airport")
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
444215982a8fa0bb32e32e5722e4ad73cb4cd6e2
| 1,484
|
mirrortrips
|
FSF All Permissive License
|
app/src/main/java/com/andor/watchit/screens/movielist/view/MovieListItemViewMvc.kt
|
andor201995
| 233,206,385
| false
| null |
package com.andor.watchit.screens.movielist.view
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.andor.watchit.R
import com.andor.watchit.screens.common.helper.ImageLoader
import com.andor.watchit.screens.common.mvc.BaseObservableViewMvc
import com.andor.watchit.screens.common.mvc.ObservableViewMvc
import com.andor.watchit.screens.movielist.model.MovieListEvent
import com.andor.watchit.usecase.common.model.MovieUiModel
import com.jakewharton.rxbinding3.view.clicks
interface TopRatedMovieListItemViewMvc : ObservableViewMvc<MovieListEvent> {
fun updateView(movieUiModel: MovieUiModel)
fun cleanUp()
}
class TopRatedMovieListItemViewMvcImpl(
parent: ViewGroup?,
inflater: LayoutInflater,
private val imageLoader: ImageLoader
) :
TopRatedMovieListItemViewMvc,
BaseObservableViewMvc<MovieListEvent>() {
private var moviePosterContainer: View
private var moviePosterImageView: ImageView
init {
setRootView(inflater.inflate(R.layout.list_item, parent, false))
moviePosterImageView = findViewById(R.id.posterImageView)
moviePosterContainer = findViewById(R.id.posterContainer)
}
override fun updateView(movieUiModel: MovieUiModel) {
moviePosterContainer.clicks().map {
MovieListEvent.LoadMovie(movieUiModel)
}.subscribe(getEventStream())
moviePosterImageView.also {
imageLoader.loadImageInto(it, movieUiModel.posterPath)
}
}
override fun cleanUp() {
imageLoader.cleanUp(moviePosterImageView)
}
}
| 10
|
Kotlin
|
0
| 0
|
873829cd486d7756bd2a94b1bd1b06a89bfc94be
| 1,634
|
WatchIt
|
Apache License 2.0
|
ui/features/tasks/src/main/java/com/example/tasks/model/NoteAndTask.kt
|
City-Zouitel
| 576,223,915
| false
| null |
package com.example.tasks.model
data class NoteAndTask(
val noteUid:String,
val todoId:Long
)
| 25
|
Kotlin
|
6
| 43
|
113dab3fe752335fec2b394dc0097dc54ff4643d
| 102
|
JetNote
|
Apache License 2.0
|
app/src/main/java/com/example/project5/MainActivity.kt
|
howardjh
| 701,034,816
| false
|
{"Kotlin": 10036}
|
package com.example.project5
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.renderscript.ScriptGroup.Input
import androidx.lifecycle.ViewModelProvider
import com.example.project5.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: TranslateViewModel
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
viewModel = ViewModelProvider(this).get(TranslateViewModel::class.java)
val fragmentTransaction = supportFragmentManager.beginTransaction()
val inputFragment = InputFragment()
fragmentTransaction.replace(R.id.input_layout, inputFragment)
fragmentTransaction.commit()
binding.inputEnglish.setOnClickListener {
viewModel.setExpectedLangTag("English")
}
binding.inputSpanish.setOnClickListener {
viewModel.setExpectedLangTag("Spanish")
}
binding.inputGerman.setOnClickListener {
viewModel.setExpectedLangTag("German")
}
binding.translateEnglish.setOnClickListener {
viewModel.setTranslateToTag("English")
}
binding.translateGerman.setOnClickListener {
viewModel.setTranslateToTag("German")
}
binding.translateSpanish.setOnClickListener {
viewModel.setTranslateToTag("Spanish")
}
viewModel.translatedText.observe(this) { translatedText ->
binding.tvTranslated.text = translatedText
}
}
}
| 0
|
Kotlin
|
0
| 0
|
0bef6a9df3fd41ab3c83e92343d0d2469e0f23d1
| 1,765
|
Project5Real
|
Apache License 2.0
|
shoppifront/android/app/src/main/kotlin/com/example/shoppifront/MainActivity.kt
|
VB10
| 251,075,703
| false
| null |
package com.example.shoppifront
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 12
|
Dart
|
12
| 63
|
ba7a7c7f861d9408fb40e3c7c24c7865ed2caf47
| 128
|
shoppii
|
Apache License 2.0
|
app/common/src/commonJvmMain/kotlin/com/denchic45/studiversity/ui/auth/WelcomeComponent.kt
|
denchic45
| 435,895,363
| false
| null |
package com.denchic45.studiversity.ui.auth
import com.arkivanov.decompose.ComponentContext
import com.denchic45.studiversity.PlatformMain
import com.denchic45.studiversity.data.domain.Cause
import com.denchic45.studiversity.data.domain.ClientError
import com.denchic45.studiversity.data.domain.Forbidden
import com.denchic45.studiversity.data.domain.NoConnection
import com.denchic45.studiversity.data.domain.NotFound
import com.denchic45.studiversity.data.domain.ServerError
import com.denchic45.studiversity.data.pref.AppPreferences
import com.denchic45.studiversity.domain.onFailure
import com.denchic45.studiversity.domain.onSuccess
import com.denchic45.studiversity.domain.usecase.CheckDomainUseCase
import com.denchic45.studiversity.util.componentScope
import com.denchic45.stuiversity.api.OrganizationResponse
import io.ktor.client.call.NoTransformationFoundException
import io.ktor.client.network.sockets.ConnectTimeoutException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.tatarka.inject.annotations.Assisted
import me.tatarka.inject.annotations.Inject
import java.net.ConnectException
@Inject
class WelcomeComponent(
private val appPreferences: AppPreferences,
private val checkDomainUseCase: CheckDomainUseCase,
@Assisted
private val onSuccess: () -> Unit,
@Assisted
componentContext: ComponentContext,
) : ComponentContext by componentContext {
private val componentScope = componentScope()
val url = MutableStateFlow("")
val state = MutableStateFlow<State>(State.Idle)
fun onDomainType(text:String) {
url.value = text
}
fun onCheckDomainClick() {
componentScope.launch {
state.value = State.Loading
checkDomainUseCase(url.value).onSuccess {
state.value = State.Success(it.organization)
appPreferences.url = url.value
withContext(Dispatchers.PlatformMain) {
onSuccess()
}
}.onFailure {
when (val failure = it) {
is Cause -> {
state.value = when (failure.throwable) {
is NoTransformationFoundException -> State.WrongDomain
is ConnectTimeoutException -> State.Timeout
is ConnectException -> State.FailedConnect
else -> State.UnknownError
}
}
NoConnection -> state.value = State.NoConnection
Forbidden,
is ClientError,
NotFound,
ServerError,
-> state.value = State.UnknownError
}
}
}
}
sealed class State(val isError: Boolean = false) {
object Idle : State()
object Loading : State()
data class Success(private val organization: OrganizationResponse) : State()
object NoConnection : State(true)
object FailedConnect : State(true)
object WrongDomain : State(true)
object Timeout : State(true)
object UnknownError : State(true)
}
}
| 0
|
Kotlin
|
0
| 5
|
02d19321d16604a052f6dd29aa54be29343991e6
| 3,302
|
Studiversity
|
Apache License 2.0
|
amazon/kms/client/src/main/kotlin/org/http4k/connect/amazon/kms/action/GetPublicKey.kt
|
http4k
| 295,641,058
| false
|
{"Kotlin": 1624429, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675}
|
package org.http4k.connect.amazon.kms.action
import org.http4k.connect.Http4kConnectAction
import org.http4k.connect.amazon.core.model.KMSKeyId
import org.http4k.connect.amazon.kms.KMSAction
import org.http4k.connect.amazon.kms.model.CustomerMasterKeySpec
import org.http4k.connect.amazon.kms.model.EncryptionAlgorithm
import org.http4k.connect.amazon.kms.model.KeyUsage
import org.http4k.connect.amazon.kms.model.SigningAlgorithm
import org.http4k.connect.model.Base64Blob
import se.ansman.kotshi.JsonSerializable
@Http4kConnectAction
@JsonSerializable
data class GetPublicKey(
val KeyId: KMSKeyId,
val GrantTokens: List<String>? = null
) : KMSAction<PublicKey>(PublicKey::class)
@JsonSerializable
data class PublicKey(
val KeyId: KMSKeyId,
@Deprecated("Use KeySpec")
val CustomerMasterKeySpec: CustomerMasterKeySpec,
val KeySpec: CustomerMasterKeySpec,
val KeyUsage: KeyUsage,
val PublicKey: Base64Blob,
val EncryptionAlgorithms: List<EncryptionAlgorithm>? = null,
val SigningAlgorithms: List<SigningAlgorithm>? = null
)
| 7
|
Kotlin
|
17
| 37
|
94e71e6bba87d9c79ac29f7ba23bdacd0fdf354c
| 1,066
|
http4k-connect
|
Apache License 2.0
|
app/src/main/java/com/leonbec/easychat/service/UserDataService.kt
|
wenfangdu
| 115,662,878
| false
|
{"Kotlin": 26898}
|
package com.leonbec.easychat.service
import android.graphics.Color
import com.leonbec.easychat.controller.App
import java.util.*
/**
* Created by leonbec on 2017/12/30.
*/
object UserDataService {
var id = ""
var avatarColor = ""
var avatarName = ""
var email = ""
var name = ""
fun logout() {
id = ""
avatarColor = ""
avatarName = ""
email = ""
name = ""
MessageService.channels.clear()
App.preference.authToken = ""
App.preference.userEmail = ""
App.preference.isLoggedIn = false
}
fun returnAvatarColor(components: String): Int {
val strippedColor = components
.replace("[", "")
.replace("]", "")
.replace(",", "")
var r = 0
var g = 0
var b = 0
val scanner = Scanner(strippedColor)
if (scanner.hasNext()) {
r = (scanner.nextDouble() * 255).toInt()
g = (scanner.nextDouble() * 255).toInt()
b = (scanner.nextDouble() * 255).toInt()
}
return Color.rgb(r, g, b)
}
}
| 0
|
Kotlin
|
0
| 1
|
547eeab859af9f92b0b105cd16498b2d25a4bc2e
| 1,127
|
EasyChat
|
MIT License
|
app/src/main/java/ch/admin/foitt/pilotwallet/platform/deeplink/domain/repository/DeepLinkIntentRepository.kt
|
e-id-admin
| 775,912,525
| false
|
{"Kotlin": 1521284}
|
package ch.admin.foitt.pilotwallet.platform.deeplink.domain.repository
interface DeepLinkIntentRepository {
fun set(deepLink: String)
fun get(): String?
fun reset()
}
| 1
|
Kotlin
|
1
| 4
|
6572b418ec5abc5d94b18510ffa87a1e433a5c82
| 182
|
eidch-pilot-android-wallet
|
MIT License
|
lib/src/main/kotlin/com/lemonappdev/konsist/api/provider/KoIsWildcardProvider.kt
|
LemonAppDev
| 621,181,534
| false
|
{"Kotlin": 5054558, "Python": 46133}
|
package com.lemonappdev.konsist.api.provider
/**
* An interface representing a Kotlin declaration that provides information about whether it is a wildcard.
*/
interface KoIsWildcardProvider : KoBaseProvider {
/**
* Determines whatever this declaration is a wildcard.
*/
val isWildcard: Boolean
}
| 6
|
Kotlin
|
27
| 1,141
|
696b67799655e2154447ab45f748e983d8bcc1b5
| 317
|
konsist
|
Apache License 2.0
|
bitgouel-domain/src/main/kotlin/team/msg/domain/club/repository/custom/impl/CustomClubRepositoryImpl.kt
|
School-of-Company
| 700,741,727
| false
|
{"Kotlin": 622843, "Shell": 764, "Dockerfile": 206}
|
package team.msg.domain.club.repository.custom.impl
import com.querydsl.core.types.dsl.BooleanExpression
import com.querydsl.jpa.impl.JPAQueryFactory
import team.msg.domain.club.model.QClub.club
import team.msg.domain.club.repository.custom.CustomClubRepository
import team.msg.domain.school.model.QSchool.school
class CustomClubRepositoryImpl(
private val queryFactory: JPAQueryFactory
) : CustomClubRepository {
override fun existsOne(id: Long): Boolean {
val fetchOne = queryFactory.selectOne()
.from(club)
.where(club.id.eq(id))
.fetchFirst() // limit 1
return fetchOne != null
}
override fun deleteAllBySchoolId(schoolId: Long) {
queryFactory.delete(school)
.where(club.school.id.eq(schoolId))
.execute()
}
override fun findAllBySchoolName(schoolName: String?): List<String> =
queryFactory
.select(club.name)
.from(club)
.where(schoolNameEq(schoolName))
.orderBy(club.school.name.asc(), club.name.asc())
.fetch()
private fun schoolNameEq(schoolName: String?): BooleanExpression? =
if (schoolName.isNullOrBlank()) null else club.school.name.eq(schoolName)
}
| 0
|
Kotlin
|
0
| 17
|
49b3337e147d4e7325d5145a2bb86e2dfedcbce3
| 1,257
|
Bitgouel-Server
|
MIT License
|
src/main/kotlin/com/ffaero/openrocketassembler/view/ConfigurationTabLabelBase.kt
|
wildcat-rocketry
| 313,389,669
| false
|
{"Kotlin": 162168}
|
package com.ffaero.openrocketassembler.view
import java.awt.Component
import javax.swing.JLabel
open class ConfigurationTabLabelBase(val view: Component) : JLabel() {
private val unsafeMouseListener = MouseHierarchyTrampoline()
private var _enableUnsafeUI = false
var enableUnsafeUI: Boolean
get() = _enableUnsafeUI
set(value) {
if (_enableUnsafeUI != value) {
_enableUnsafeUI = value
if (value) {
unsafeMouseListener.enable()
addMouseListener(unsafeMouseListener)
} else {
removeMouseListener(unsafeMouseListener)
}
}
}
fun insert(tabs: ConfigurationTabView, idx: Int) {
tabs.insertTab("", null, view, "", idx)
tabs.setTabComponentAt(idx, this)
}
}
| 5
|
Kotlin
|
0
| 0
|
4c12948ed3b2fd5656a88ceb0cb2fcaa72d738ef
| 718
|
openrocket-assembler
|
MIT License
|
app/src/main/java/com/convidadoskotlin/view/viewholder/GuestViewHolder.kt
|
gabrielvieira1
| 770,099,780
| false
|
{"Kotlin": 32406}
|
package com.convidadoskotlin.view.viewholder
import android.app.AlertDialog
import androidx.recyclerview.widget.RecyclerView
import com.convidadoskotlin.R
import com.convidadoskotlin.databinding.RowGuestBinding
import com.convidadoskotlin.service.model.GuestModel
import com.convidadoskotlin.view.listener.GuestListener
class GuestViewHolder(private val item: RowGuestBinding, private val listener: GuestListener) :
RecyclerView.ViewHolder(item.root) {
fun bind(guest: GuestModel) {
// Atribui valores
item.textName.text = guest.name
// Atribui eventos
item.textName.setOnClickListener {
listener.onClick(guest.id)
}
// Atribui eventos
item.textName.setOnLongClickListener {
AlertDialog.Builder(itemView.context)
.setTitle(R.string.remocao_convidado)
.setMessage(R.string.deseja_remover)
.setPositiveButton(R.string.remover) { dialog, which ->
listener.onDelete(guest.id)
}
.setNeutralButton(R.string.cancelar, null)
.show()
true
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5b0eb029d82e6022e3ab76edec48b505287f0db8
| 1,170
|
ConvidadosKotlin
|
MIT License
|
app/src/main/java/com/unichamba1/MainActivity2.kt
|
bryanmiranda138
| 854,299,220
| false
|
{"Kotlin": 149451}
|
package com.unichamba1
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.unichamba1.Fragmentos.FragmentCuenta
import com.unichamba1.Fragmentos.FragmentInicio
import com.unichamba1.Fragmentos.FragmentMisOfertas
import com.unichamba1.Fragmentos.FragmentNuevaOferta
import com.unichamba1.databinding.ActivityMainBinding
import com.google.firebase.auth.FirebaseAuth
import android.app.Dialog
import android.net.Uri
import android.view.ViewGroup
import android.widget.Button
import com.unichamba1.Fragmentos.FragmentJovenes
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView
import android.widget.ImageButton
import androidx.core.view.GravityCompat
class MainActivity2 : AppCompatActivity(),FragmentInicio.OnVerOfertasClickListener , FragmentInicio.OnVerJovenesClickListener{
private lateinit var binding: ActivityMainBinding
private lateinit var firebaseAuth: FirebaseAuth
private lateinit var drawerLayout: DrawerLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
drawerLayout = findViewById(R.id.drawer_layout)
val navView = findViewById<NavigationView>(R.id.mi_menu0)
val hamburgerButton = findViewById<ImageButton>(R.id.btnBack)
hamburgerButton.setOnClickListener {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
drawerLayout.openDrawer(GravityCompat.START)
}
}
verFragmentInicio()
binding.BottonNV!!.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.Item_Inicio -> {
verFragmentInicio()
true
}
R.id.Item_Filtrar -> {
verFragmentFiltrar()
true
}
R.id.Item_Mis_Ofertas -> {
verFragmentMisOfertas()
true
}
else -> {
false
}
}
}
navView.setNavigationItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.Item_sitio -> {
abrirSitioWeb("https://www.unichamba.com/")
true
}
R.id.Item_Terminos -> {
abrirSitioWeb("https://website-unichamba.netlify.app/policy")
drawerLayout.closeDrawer(GravityCompat.START)
true
}
R.id.Item_Quienes_Somos -> {
abrirSitioWeb("https://website-unichamba.netlify.app/details")
drawerLayout.closeDrawer(GravityCompat.START)
true
}
else -> false
}
}
}
override fun onVerJovenesClicked() {
binding.BottonNV?.selectedItemId = R.id.Item_Filtrar
verFragmentFiltrar()
}
override fun onVerOfertasClicked() {
binding.BottonNV?.selectedItemId = R.id.Item_Mis_Ofertas
verFragmentMisOfertas()
}
private fun abrirSitioWeb(url: String = "") {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
startActivity(intent)
}
private fun verFragmentInicio() {
binding.TituloRL!!.text = "Inicio"
val fragment = FragmentInicio()
val fragmentTransition = supportFragmentManager.beginTransaction()
fragmentTransition.replace(binding.FragmentL1!!.id, fragment, "FragmentInicio")
fragmentTransition.commit()
}
private fun verFragmentFiltrar() {
binding.TituloRL!!.text = "Jovenes"
val fragment = FragmentJovenes()
val fragmentTransition = supportFragmentManager.beginTransaction()
fragmentTransition.replace(binding.FragmentL1!!.id, fragment, "FragmentFiltral")
fragmentTransition.commit()
}
private fun verFragmentMisOfertas() {
binding.TituloRL!!.text = "Ofertas"
val fragment = FragmentMisOfertas()
val fragmentTransition = supportFragmentManager.beginTransaction()
fragmentTransition.replace(binding.FragmentL1!!.id, fragment, "FragmentMisOfertas")
fragmentTransition.commit()
}
}
private fun Any.replace(id: Int, fragment: FragmentInicio, tag: String) {
}
private fun Any.replace(id: Int, fragment: FragmentJovenes, tag: String) {
}
private fun Any.replace(id: Int, fragment: FragmentMisOfertas, tag: String) {
}
| 0
|
Kotlin
|
0
| 0
|
2a56db1ea30d1087f047ed2d9f82c7f58e8e3790
| 4,903
|
LaAppV2
|
Apache License 2.0
|
src/main/kotlin/csense/idea/base/bll/kotlin/KtClass.kt
|
csense-oss
| 226,373,994
| false
|
{"Kotlin": 150126}
|
@file:Suppress("unused")
package csense.idea.base.bll.kotlin
import com.intellij.psi.PsiClass
import com.intellij.psi.search.searches.ClassInheritorsSearch
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.core.isOverridable
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.isAbstract
fun KtClass.isAbstractOrOpen(): Boolean {
return isAbstract() || isOverridable()
}
fun KtClass.getEnumValues(): List<KtEnumEntry> {
return collectDescendantsOfType()
}
fun KtClass.findSealedClassInheritors(): List<PsiClass> {
return ClassInheritorsSearch.search(toLightClass() as PsiClass).toList()
}
| 0
|
Kotlin
|
0
| 0
|
1543bcadb124ca29c5f09e6762384648e19fa6e0
| 723
|
idea-kotlin-shared-base
|
MIT License
|
app/src/main/java/com/permissionx/app/MainActivity.kt
|
long948
| 401,197,763
| false
| null |
package com.permissionx.app
import android.Manifest
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.permissionx.hxldev.PermissionX
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
makeCallBtn.setOnClickListener {
PermissionX.request(this,
Manifest.permission.CALL_PHONE){allGranted,deniedList->
if (allGranted){
call()
}else{
Toast.makeText(this, "你否认了 $deniedList",
Toast.LENGTH_SHORT).show()
}
}
}
}
private fun call() {
try {
val intent=Intent(Intent.ACTION_CALL)
intent.data= Uri.parse("tel:10086")
startActivity(intent)
}catch (e :SecurityException){
e.printStackTrace()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
12d61e3c7da5f401caaac31f0a9cff9f72092e63
| 1,180
|
PermissionX
|
Apache License 2.0
|
ok-marketplace-be-repository-cassandra/src/main/kotlin/ru/otus/otuskotlin/marketplace/backend/repository/cassandra/common/dto/UnitTypeCassandraDto.kt
|
otuskotlin
| 323,966,359
| false
| null |
package ru.otus.otuskotlin.marketplace.backend.repository.cassandra.common.dto
import com.datastax.oss.driver.api.mapper.annotations.CqlName
import com.datastax.oss.driver.api.mapper.annotations.Entity
import ru.otus.otuskotlin.marketplace.common.backend.models.MpUnitTypeIdModel
import ru.otus.otuskotlin.marketplace.common.backend.models.MpUnitTypeModel
@Entity
data class UnitTypeCassandraDto(
@CqlName(ID)
val id: String? = null,
@CqlName(NAME)
val name: String? = null,
@CqlName(DESCRIPTION)
val description: String? = null,
@CqlName(SYNONYMS)
val synonyms: Set<String>? = null,
@CqlName(SYMBOL)
val symbol: String? = null,
@CqlName(SYMBOLS)
val symbols: Set<String>? = null,
@CqlName(IS_BASE)
val isBase: Boolean? = null,
) {
fun toModel() = MpUnitTypeModel(
id = id?.let { MpUnitTypeIdModel(it) }?: MpUnitTypeIdModel.NONE,
name = name?: MpUnitTypeModel.NONE.name,
description = description?: MpUnitTypeModel.NONE.description,
synonyms = synonyms?.toMutableSet()?: MpUnitTypeModel.NONE.synonyms,
symbol = symbol?: MpUnitTypeModel.NONE.symbol,
symbols = symbols?.toMutableSet()?: MpUnitTypeModel.NONE.symbols,
isBase = isBase?: MpUnitTypeModel.NONE.isBase,
)
companion object {
const val TYPE_NAME = "unit_type"
const val ID = "id"
const val NAME = "name"
const val DESCRIPTION = "description"
const val SYNONYMS = "synonyms"
const val SYMBOL = "symbol"
const val SYMBOLS = "symbols"
const val IS_BASE = "is_base"
fun of(model: MpUnitTypeModel) = UnitTypeCassandraDto(
id = model.id.takeIf { it != MpUnitTypeModel.NONE.id }?.id,
name = model.name.takeIf { it != MpUnitTypeModel.NONE.name },
description = model.description.takeIf { it != MpUnitTypeModel.NONE.description },
synonyms = model.synonyms.takeIf { it != MpUnitTypeModel.NONE.synonyms },
symbol = model.symbol.takeIf { it != MpUnitTypeModel.NONE.symbol },
symbols = model.symbols.takeIf { it != MpUnitTypeModel.NONE.symbols },
isBase = model.isBase.takeIf { it != MpUnitTypeModel.NONE.isBase },
)
}
}
| 0
|
Kotlin
|
0
| 1
|
5f05fe658504dfa5d7300e3f0f523d250ff6ce31
| 2,262
|
202012-otuskotlin-marketplace
|
MIT License
|
ethers-crypto/src/main/kotlin/io/ethers/crypto/bip32/HDPath.kt
|
Kr1ptal
| 712,963,462
| false
|
{"Kotlin": 1017930, "Solidity": 28233}
|
package io.ethers.crypto.bip32
/**
* Implementation of [BIP-0032](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) derivation paths.
* */
class HDPath(private val indices: Array<Int>) {
/**
* Returns depth of current derivation path.
* */
val depth: Int
get() = indices.size
/**
* Create a copy of this path, adding a new depth with optionally hardened [index].
* */
@JvmOverloads
fun extend(index: Int, hardened: Boolean = false): HDPath {
return HDPath(indices + if (hardened) index or BIP32_HARDENED_OFFSET else index)
}
/**
* Get index at provided [depth].
* */
fun indexAtDepth(depth: Int): Int = indices[depth]
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as HDPath
return indices.contentEquals(other.indices)
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + indices.contentHashCode()
return result
}
/**
* Returns a string representation of this derivation path.
* */
override fun toString(): String {
return indices.joinToString(prefix = "m/", separator = "/") {
if (isHardened(it)) {
"${it and (BIP32_HARDENED_OFFSET.inv())}'"
} else {
it.toString()
}
}
}
companion object {
/**
* BIP32 hardened key offset.
* */
private const val BIP32_HARDENED_OFFSET = 0x8000_0000.toInt()
/**
* Default derivation path for Ethereum: m/44'/60'/0'/0.
*
* Based on [BIP-0044](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) format.
* */
val ETHEREUM = parse("m/44'/60'/0'/0")
/**
* Parse derivation path from string.
* */
fun parse(path: String): HDPath {
if (path.isEmpty() || path[0] != 'm') {
throw IllegalArgumentException("Invalid derivation path: $path")
}
if (path == "m") {
return HDPath(emptyArray())
}
val indices = path.removePrefix("m").removePrefix("/").split("/").map {
if (it.endsWith("'")) {
it.dropLast(1).toInt() or BIP32_HARDENED_OFFSET
} else {
it.toInt()
}
}
return HDPath(indices.toTypedArray())
}
fun isHardened(index: Int): Boolean {
return index and BIP32_HARDENED_OFFSET != 0
}
}
}
| 10
|
Kotlin
|
1
| 9
|
85f3824fde9caaeeee91986ca177d005f7a225bb
| 2,741
|
ethers-kt
|
Apache License 2.0
|
libs/firebase/src/main/kotlin/br/com/mob1st/libs/firebase/firestore/Collections.kt
|
mob1st
| 526,655,668
| false
|
{"Kotlin": 589975, "Shell": 1558}
|
package br.com.mob1st.libs.firebase.firestore
import com.google.firebase.firestore.FirebaseFirestore
fun FirebaseFirestore.groups() = collection("groups")
fun FirebaseFirestore.users() = collection("users")
fun FirebaseFirestore.members(groupId: String) = groups().document(groupId).collection("members")
fun FirebaseFirestore.memberships(userId: String) = users().document(userId).collection("memberships")
fun FirebaseFirestore.competitions() = collection("competitions")
| 11
|
Kotlin
|
0
| 3
|
ea57a781dd1c7e336213ed9ca76146afbb445e9d
| 480
|
bet-app-android
|
Apache License 2.0
|
docs/src/main/kotlin/me/hana/docs/endpoint/EndPointGroup.kt
|
utsmannn
| 459,662,831
| false
|
{"Kotlin": 777}
|
package me.hana.docs.endpoint
data class EndPointGroup(
val name: String = "",
val endPoint: EndPoint = EndPoint(),
val child: List<EndPoint> = emptyList(),
val priority: Int = 100
)
| 0
|
Kotlin
|
0
| 5
|
ee901a6a2943fa0b6b1d52b2984742c13d419507
| 199
|
hana
|
Apache License 2.0
|
app/src/main/java/com/digitaldream/linkskool/fragments/StaffELearningCourseWorkFragment.kt
|
Toochidennis
| 706,639,845
| false
|
{"Gradle": 3, "Java Properties": 5, "Shell": 1, "Text": 2, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Java": 225, "XML": 1015, "Kotlin": 246, "JavaScript": 1, "HTML": 2, "INI": 2}
|
package com.digitaldream.linkskool.fragments
import android.content.Context.MODE_PRIVATE
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.digitaldream.linkskool.R
import com.digitaldream.linkskool.adapters.StaffELearningCourseWorkAdapter
import com.digitaldream.linkskool.dialog.StaffELearningCreateContentDialogFragment
import com.digitaldream.linkskool.models.ContentModel
import com.digitaldream.linkskool.utils.ItemTouchHelperCallback
import com.google.android.material.floatingactionbutton.FloatingActionButton
import org.json.JSONArray
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
class StaffELearningCourseWorkFragment : Fragment() {
private lateinit var contentRecyclerView: RecyclerView
private lateinit var addContentButton: FloatingActionButton
private lateinit var swipeRefreshLayout: SwipeRefreshLayout
private lateinit var contentAdapter: StaffELearningCourseWorkAdapter
private var contentList = mutableListOf<ContentModel>()
private var mLevelId: String? = null
private var mCourseId: String? = null
private var mCourseName: String? = null
private var responseFromServer: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
responseFromServer = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_staff_e_learning_course_work, container, false)
}
companion object {
@JvmStatic
fun newInstance(param1: String, param2: String) =
StaffELearningCourseWorkFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpViews(view)
parseResponse()
addContent()
refresh()
}
private fun setUpViews(view: View) {
view.apply {
contentRecyclerView = findViewById(R.id.contentRecyclerView)
addContentButton = findViewById(R.id.add_btn)
swipeRefreshLayout = findViewById(R.id.swipeRefresh)
}
val sharedPreferences = requireActivity().getSharedPreferences("loginDetail", MODE_PRIVATE)
with(sharedPreferences) {
mLevelId = getString("level", "")
mCourseId = getString("courseId", "")
mCourseName = getString("course_name", "")
}
}
private fun addContent() {
addContentButton.setOnClickListener {
StaffELearningCreateContentDialogFragment()
.show(parentFragmentManager, "Create Content")
}
}
private fun parseResponse() {
contentList.clear()
responseFromServer?.let { response ->
with(JSONArray(response)) {
for (i in 0 until length()) {
val contentObject = getJSONObject(i)
contentObject.let {
val id = it.getString("id")
val title = it.getString("title")
val description = it.getString("body")
val courseId = it.getString("course_id")
val levelId = it.getString("level")
val authorId = it.getString("author_id")
val authorName = it.getString("author_name")
val term = it.getString("term")
val date = it.getString("upload_date")
val type = it.getString("type")
val category = it.getString("category")
when (it.getString("content_type")) {
"Topic" -> {
val content = ContentModel(
id, title,
description,
courseId,
levelId,
authorId, authorName, date, term, type,
"topic",
title
)
contentList.add(content)
}
"Assignment" -> {
val content = ContentModel(
id, title,
description,
courseId,
levelId,
authorId, authorName, date, term, type,
"assignment",
category
)
contentList.add(content)
}
"Material" -> {
val content = ContentModel(
id, title,
description, courseId,
levelId, authorId,
authorName, date,
term, type,
"material",
category
)
contentList.add(content)
}
"Quiz" -> {
val content = ContentModel(
id, title,
description, courseId,
levelId, authorId,
authorName, date,
term, type,
"question",
category
)
contentList.add(content)
}
else -> null
}
}
}
}
setUpRecyclerView()
}
}
private fun setUpRecyclerView() {
sortDataList()
contentAdapter = StaffELearningCourseWorkAdapter(contentList)
contentRecyclerView.apply {
hasFixedSize()
layoutManager = LinearLayoutManager(requireContext())
adapter = contentAdapter
}
onTouchHelper()
}
private fun onTouchHelper() {
val touchCallback = ItemTouchHelperCallback(contentAdapter)
val touchHelper = ItemTouchHelper(touchCallback)
touchHelper.attachToRecyclerView(contentRecyclerView)
}
private fun sortDataList() {
contentList.sortBy { it.category }
}
private fun refresh() {
swipeRefreshLayout.apply {
setColorSchemeResources(R.color.test_color_1)
setOnRefreshListener {
parseResponse()
isRefreshing = false
}
}
}
}
| 1
|
Java
|
0
| 1
|
551e25524b77efaba17cb9bd89a07b8ccc01b13e
| 7,875
|
linkskool
|
MIT License
|
sample/app/src/main/java/com/google/android/jacquard/sample/home/HomeTilesListAdapter.kt
|
gildardoperez
| 624,963,235
| true
|
{"Text": 2, "Markdown": 16, "Gradle": 8, "Ignore List": 5, "Java Properties": 2, "XML": 138, "Shell": 2, "Proguard": 2, "Java": 251, "JSON": 4, "YAML": 1, "SVG": 2, "SCSS": 1, "JavaScript": 1, "INI": 1, "Kotlin": 100}
|
/*
* Copyright 2021 Google LLC
*
* 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 com.google.android.jacquard.sample.home
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.android.jacquard.sample.R
/** Adapter for recyclerview in [HomeFragment]. */
class HomeTilesListAdapter(
private val context: Context,
private val itemClick: ItemClickListener<HomeTileModel>
) : ListAdapter<HomeTileModel, HomeTilesListAdapter.AbstractViewHolder>(
DIFF_CALLBACK
) {
/** Creating ViewHolder for recyclerview in [HomeFragment]. */
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AbstractViewHolder {
when (HomeTileModel.Type.values()[viewType]) {
HomeTileModel.Type.TILE_API -> return TileTypeApiViewHolder(
context,
LayoutInflater.from(context)
.inflate(
R.layout.item_product_tile_api, /* root= */null, /* attachToRoot= */false
),
itemClick,
R.drawable.shape_tile_disabled,
R.drawable.shape_tile_enabled,
R.color.home_tile_semi_transparent_black,
R.color.black
)
HomeTileModel.Type.TILE_SAMPLE_USE_CASE -> return TileTypeSampleUseCaseViewHolder(
context,
LayoutInflater.from(context)
.inflate(
R.layout.item_product_tile_sample_use_case, /* root= */
null, /* attachToRoot= */
false
),
itemClick,
R.drawable.shape_tile_disabled,
R.drawable.shape_tile_enabled,
R.color.home_tile_semi_transparent_black,
R.color.black
)
}
return SectionViewHolder(
context,
LayoutInflater.from(context)
.inflate(
R.layout.item_product_section, /* root= */
null, /* attachToRoot= */
false
),
itemClick
)
}
/** Binding ViewHolder for recyclerview in [HomeFragment]. */
override fun onBindViewHolder(holder: AbstractViewHolder, position: Int) {
holder.populate(currentList[position]!!)
}
/** Returns the number of items. */
override fun getItemCount(): Int {
return currentList.size
}
/** Returns the type of View. */
override fun getItemViewType(position: Int): Int {
return currentList[position]!!.type!!.ordinal
}
abstract class AbstractViewHolder(
protected var context: Context,
itemView: View,
protected var itemClick: ItemClickListener<HomeTileModel>,
protected var drawableDisabled: Int,
protected var drawableEnabled: Int,
protected var textColorDisabled: Int,
protected var textColorEnabled: Int
) : RecyclerView.ViewHolder(itemView) {
abstract fun populate(model: HomeTileModel)
}
private class TileTypeApiViewHolder(
context: Context,
itemView: View,
itemClick: ItemClickListener<HomeTileModel>,
drawableDisabled: Int,
drawableEnabled: Int,
textColorDisabled: Int,
textColorEnabled: Int
) : AbstractViewHolder(
context,
itemView,
itemClick,
drawableDisabled,
drawableEnabled,
textColorDisabled,
textColorEnabled
) {
private val textTitle: TextView = itemView.findViewById(R.id.tileTitle)
private val textSubTitle: TextView = itemView.findViewById(R.id.tileSubTitle)
override fun populate(model: HomeTileModel) {
textTitle.text = context.getString(model.title)
textSubTitle.text = context.getString(model.subTitle)
if (!model.enabled) {
itemView.setBackgroundResource(drawableDisabled)
textTitle.setTextColor(context.getColor(textColorDisabled))
textSubTitle.setTextColor(context.getColor(textColorDisabled))
return
}
textTitle.setTextColor(context.getColor(textColorEnabled))
textSubTitle.setTextColor(context.getColor(textColorEnabled))
itemView.setBackgroundResource(drawableEnabled)
itemView.setOnClickListener { itemClick.itemClick(model) }
}
}
private class TileTypeSampleUseCaseViewHolder(
context: Context,
itemView: View,
itemClick: ItemClickListener<HomeTileModel>,
drawableDisabled: Int,
drawableEnabled: Int,
textColorDisabled: Int,
textColorEnabled: Int
) : AbstractViewHolder(
context,
itemView,
itemClick,
drawableDisabled,
drawableEnabled,
textColorDisabled,
textColorEnabled
) {
private val textTitle: TextView = itemView.findViewById(R.id.tileTitle)
override fun populate(model: HomeTileModel) {
textTitle.text = context.getString(model.title)
if (!model.enabled) {
itemView.setBackgroundResource(drawableDisabled)
textTitle.setTextColor(context.getColor(textColorDisabled))
return
}
textTitle.setTextColor(context.getColor(textColorEnabled))
itemView.setBackgroundResource(drawableEnabled)
itemView.setOnClickListener { itemClick.itemClick(model) }
}
}
private class SectionViewHolder(
context: Context,
itemView: View,
itemClick: ItemClickListener<HomeTileModel>
) : AbstractViewHolder(
context,
itemView,
itemClick, /* drawableDisabled= */
0, /* drawableEnabled= */
0, /* textColorDisabled= */
0, /* textColorEnabled= */
0
) {
private val textTitle: TextView = itemView.findViewById(R.id.tileTitle)
override fun populate(model: HomeTileModel) {
textTitle.text = context.getString(model.title)
if (!model.enabled) {
return
}
itemView.setOnClickListener { itemClick.itemClick(model) }
}
}
companion object {
private val DIFF_CALLBACK: DiffUtil.ItemCallback<HomeTileModel> =
object : DiffUtil.ItemCallback<HomeTileModel>() {
override fun areItemsTheSame(
oldItem: HomeTileModel, newItem: HomeTileModel
): Boolean {
return oldItem.title == newItem.title
}
override fun areContentsTheSame(
oldItem: HomeTileModel, newItem: HomeTileModel
): Boolean {
return oldItem.title == newItem.title && oldItem.type == newItem.type && oldItem.enabled == newItem.enabled
}
}
}
}
| 0
| null |
0
| 0
|
f88ec2dea9813203a4ed5d70646915c4d5651d6e
| 7,749
|
JacquardSDKAndroid
|
Apache License 2.0
|
services/analytics/impl/src/main/kotlin/io/element/android/services/analytics/impl/DefaultScreenTracker.kt
|
vector-im
| 546,522,002
| false
|
{"Gradle Kotlin DSL": 179, "Markdown": 28, "CODEOWNERS": 1, "Java Properties": 2, "Shell": 19, "Text": 34, "Ignore List": 20, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "TOML": 2, "Ruby": 1, "Kotlin": 2498, "XML": 821, "HTML": 1, "JavaScript": 5, "CSS": 1, "INI": 9, "Java": 1, "YAML": 45, "JSON": 3, "Proguard": 5, "Gherkin": 1, "Python": 13}
|
/*
* Copyright (c) 2024 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.services.analytics.impl
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.Lifecycle
import com.squareup.anvil.annotations.ContributesBinding
import im.vector.app.features.analytics.plan.MobileScreen
import io.element.android.libraries.designsystem.utils.OnLifecycleEvent
import io.element.android.libraries.di.AppScope
import io.element.android.services.analytics.api.AnalyticsService
import io.element.android.services.analytics.api.ScreenTracker
import io.element.android.services.toolbox.api.systemclock.SystemClock
import javax.inject.Inject
@ContributesBinding(AppScope::class)
class DefaultScreenTracker @Inject constructor(
private val analyticsService: AnalyticsService,
private val systemClock: SystemClock
) : ScreenTracker {
@Composable
override fun TrackScreen(
screen: MobileScreen.ScreenName,
) {
var startTime by remember { mutableLongStateOf(0L) }
OnLifecycleEvent { _, event ->
when (event) {
Lifecycle.Event.ON_RESUME -> {
startTime = systemClock.epochMillis()
}
Lifecycle.Event.ON_PAUSE -> analyticsService.screen(
screen = MobileScreen(
durationMs = (systemClock.epochMillis() - startTime).toInt(),
screenName = screen
)
)
else -> Unit
}
}
}
}
| 1
| null |
1
| 1
|
c7672ab25022f58e3a9fec567b7d455f6085f7fc
| 2,257
|
element-x-android
|
Apache License 2.0
|
src/main/kotlin/io/github/nikpivkin/lifetime/event/PluginReloadEvent.kt
|
nikpivkin
| 618,118,736
| false
|
{"Java": 24475, "Kotlin": 21796}
|
package io.github.nikpivkin.lifetime.event
import org.bukkit.event.Event
import org.bukkit.event.HandlerList
class PluginReloadEvent : Event() {
override fun getHandlers() = HANDLERS
companion object {
private val HANDLERS = HandlerList()
@JvmStatic
fun getHandlerList() = HANDLERS
}
}
| 1
| null |
1
| 1
|
14568b818dc90e318c9816353a52855e8fab5d14
| 327
|
lifetime-min-plg
|
MIT License
|
core/kotlin-stub/source/jetbrains/mps/kotlin/stubs/metadata/metadataReader.kt
|
JetBrains
| 2,209,077
| false
|
{"Text": 29, "XML": 11142, "Ignore List": 8, "Markdown": 22, "Git Attributes": 1, "Java": 29329, "JetBrains MPS": 4297, "C++": 789, "Java Properties": 29, "INI": 12, "Kotlin": 69, "SVG": 756, "Ant Build System": 15, "Shell": 8, "Batchfile": 8, "NSIS": 1, "Diff": 10, "Groovy": 2, "HTML": 78, "JSON": 2, "CSS": 3, "Python": 2, "Perl": 4, "XSLT": 15}
|
package jetbrains.mps.kotlin.stubs.metadata
import jetbrains.mps.kotlin.stubs.platform.isKlibMetadataFileName
import jetbrains.mps.kotlin.stubs.platform.isKotlinJsFileName
import jetbrains.mps.kotlin.stubs.platform.isKotlinMetadataFileName
import kotlinx.metadata.internal.accept
import kotlinx.metadata.internal.common.KmModuleFragment
import kotlinx.metadata.internal.common.KotlinCommonMetadata
import kotlinx.metadata.internal.metadata.ProtoBuf
import kotlinx.metadata.internal.metadata.builtins.BuiltInsBinaryVersion
import kotlinx.metadata.internal.metadata.builtins.BuiltInsProtoBuf
import kotlinx.metadata.internal.metadata.deserialization.NameResolverImpl
import kotlinx.metadata.internal.protobuf.CodedInputStream
import kotlinx.metadata.internal.protobuf.ExtensionRegistryLite
import java.io.InputStream
/**
* Component agnostic way to read metadata from a file.
*
* Usually, knowledge on how to load a file is known from the Component, but this data is lost when moving to
* FolderSourceSet.
*
* This is based on a file extension to load known formats, but should ideally be done by components themselves.
*/
fun InputStream.readKtMetadata(fileName: String): KmModuleFragment? {
return when {
fileName.isKotlinJsFileName -> {
// This format contains: version descriptor, delimited header, package
// JS version format is the same as builtins one, we reuse it to read
if (BuiltInsBinaryVersion.readFrom(this).isSupportedJsMetadataVersion()) {
// Skip the header (encoded with delimited protobuf message)
// TODO data from the header might be of some use, ask to have utilities bundled somewhere or generate the proto ourself
skipNBytes(CodedInputStream.readRawVarint32(read(), this).toLong())
// Remaining is package data
parseModuleFragment()
} else null
}
fileName.isKlibMetadataFileName -> {
parseModuleFragment()
}
fileName.isKotlinMetadataFileName ->
KotlinCommonMetadata.read(readAllBytes())?.toKmModuleFragment()
else -> {
// TODO load version from klib descriptor and check it
parseModuleFragment()
}
}
}
fun InputStream.parseModuleFragment(): KmModuleFragment {
val proto = ProtoBuf.PackageFragment.parseFrom(
this,
ExtensionRegistryLite.newInstance().apply(BuiltInsProtoBuf::registerAllExtensions)
)
val fragment = KmModuleFragment()
val strings = NameResolverImpl(proto.strings, proto.qualifiedNames)
if (proto.hasPackage()) {
fragment.visitPackage()?.let { proto.`package`.accept(it, strings) }
}
proto.class_List.forEach { klass ->
fragment.visitClass()?.let {
klass.accept(it, strings)
}
}
fragment.visitEnd()
return fragment
}
| 1
| null |
1
| 1
|
5bb20b8a104c08206490e0f3fad70304fa0e0151
| 2,899
|
MPS
|
Apache License 2.0
|
app/src/main/java/com/jpb/android/appget/sysinfoToolsActivity.kt
|
jpbandroid
| 615,646,483
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "XML": 55, "Kotlin": 20, "Java": 6, "AIDL": 3}
|
package com.jpb.android.appget
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class sysinfoToolsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sysinfo_tools)
}
}
| 0
|
Java
|
0
| 1
|
947024cbbf123a863a2ccfe8006eb91f83e98107
| 320
|
AppGet
|
Apache License 2.0
|
app/src/main/java/cz/inventi/inventiskeleton/presentation/post/list/PostListComponent.kt
|
InventiDevelopment
| 89,702,956
| false
| null |
package cz.inventi.inventiskeleton.presentation.post.list
import cz.inventi.inventiskeleton.di.ScreenModule
import cz.inventi.inventiskeleton.di.ScreenScope
import dagger.Subcomponent
import dagger.android.AndroidInjector
/**
* Created by tomas.valenta on 5/11/2017.
*/
@ScreenScope @Subcomponent(modules = arrayOf(ScreenModule::class))
interface PostListComponent : AndroidInjector<PostListController> {
@Subcomponent.Builder abstract class Builder : AndroidInjector.Builder<PostListController>() {
abstract fun screenModule(screenModule: ScreenModule): Builder
override fun seedInstance(postListController: PostListController) {
screenModule(ScreenModule(postListController.javaClass.simpleName))
}
}
}
| 5
|
Kotlin
|
3
| 4
|
faee881565eeffe5a25b0501909692acba83ed52
| 756
|
AndroidSkeleton
|
Apache License 2.0
|
core/data/src/main/java/com/halilozcan/animearch/core/data/di/IoDispatcher.kt
|
halilozcan
| 572,966,235
| false
| null |
package com.halilozcan.animearch.core.data.di
import javax.inject.Qualifier
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class IoDispatcher
| 1
|
Kotlin
|
8
| 97
|
5903644dbabf505702d488d8ec7bb19b78174467
| 158
|
AnimeArch
|
Apache License 2.0
|
app/src/main/java/com/example/DiarioApplication/data/Note/Note.kt
|
AdrianZa1
| 860,056,200
| false
|
{"Kotlin": 135595}
|
package com.example.DiarioApplication.data.Note
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "notes")
data class Note(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val title: String,
val content: String,
val timestamp: Long,
val isPinned: Boolean = false,
val isFavorite: Boolean = false
)
| 0
|
Kotlin
|
0
| 0
|
b4879190d9581510d2f1fd7dfe11217f4a1f67cc
| 356
|
diario_personal
|
Apache License 2.0
|
Week3/W3S2_11321051/src/main/kotlin/Player3.kt
|
marloxxx
| 563,639,368
| false
|
{"Kotlin": 171819, "PHP": 91686, "C++": 39436, "CMake": 34938, "Blade": 18425, "Dart": 7911, "C": 2850, "Swift": 2316, "HTML": 1830, "Shell": 1069, "JavaScript": 285, "Objective-C": 76}
|
class Player3(_name: String, var _healthPoints: Int, val _isBlessed: Boolean, private val _isImmortal: Boolean) {
var name = _name
get() = field.capitalize()
private set(value) {
field = value.trim()
}
constructor(name: String) : this(
name,
_healthPoints = 100,
_isBlessed = true,
_isImmortal = false
)
init {
require(_healthPoints > 0, { "healthPoints must be greater than zero." })
require(name.isNotBlank(), {"Player must have a name"})
}
fun castFireball(numFireballs: Int = 2) = println("A glass of Fireball springs into existence. (x$numFireballs)")
fun auraColor(): String {
val auraVisible = _isBlessed && _healthPoints > 50 || _isImmortal
val auraColor = if (auraVisible) "GREEN" else "NONE"
return auraColor
}
}
// deklarasi class player 3 dengan parameter _name, _healtPoints, _isBlessed, _isImmortal
// class ini memiliki constructor default yang memiliki parameter _name, _healtPoints, _isBlessed, _isImmortal
// class ini juga memiliki constructor secondary yang memiliki parameter name dan memiliki nilai default _healthPoints = 100, _isBlessed = true, _isImmortal = false
// class ini memiliki rule bahwa _healthPoints harus lebih besar dari 0 dan name tidak boleh kosong
fun main() {
val player = Player3("Madrigal")
player.castFireball()
// Player status
val healtStatus = formatHealtStatus(player._healthPoints, player._isBlessed)
printPlayerStatus(player)
// castFireball()
}
fun printPlayerStatus(player: Player3){
println("(Aura: ${player.auraColor()}) (Blessed: ${if (player._isBlessed) "YES" else "NO"})")
println("${player.name} ${player._healthPoints}")
}
| 0
|
Kotlin
|
0
| 0
|
6c32297cef729b18561591555d5bdbe630562bd0
| 1,762
|
PAM
|
MIT License
|
build-logic/convention/src/main/kotlin/io/github/john/tuesday/nutrition/ConfigurePublishing.kt
|
John-Tuesday
| 700,786,727
| false
|
{"Kotlin": 50100}
|
package io.github.john.tuesday.nutrition
const val MavenGroupId = "io.github.john-tuesday"
const val MavenVersion = "0.2.0-alpha02"
data class RepositoryInfo(
val name: String,
val description: String,
val repoUrl: String,
val homeUrl: String = repoUrl,
val documentationBaseUrl: String = "",
)
val NutritionRepo: RepositoryInfo = RepositoryInfo(
name = "Nutrition",
description = "Kotlin library which models human nutritional data",
repoUrl = "https://github.com/John-Tuesday/nutrition",
documentationBaseUrl = "https://john-tuesday.github.io/nutrition/documentation/nutrition/nutrition",
)
val NutritionTestRepo: RepositoryInfo = RepositoryInfo(
name = "Nutrition Test",
description = "Kotlin test helper library for Nutrition library",
repoUrl = "https://github.com/John-Tuesday/nutrition",
documentationBaseUrl = "https://john-tuesday.github.io/nutrition/documentation/nutrition/nutrition-test",
)
| 0
|
Kotlin
|
0
| 0
|
edae76d81270b8de1949556035d32773622b4b4a
| 960
|
nutrition
|
MIT License
|
app/src/main/java/com/liorhass/android/chargecap/UserAlerter.kt
|
liorhass
| 293,218,053
| false
| null |
package com.liorhass.android.chargecap
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.PowerManager
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import timber.log.Timber
const val USER_ALERT_NOTIFICATION_ID = 292
const val ACTION_SHOULD_ALERT_THE_USER = "com.liorhass.android.chargecap.should_alert_user"
// https://stackoverflow.com/a/41418325/1071117
fun alertUser(context: Context) {
Timber.d("alertUser()")
val intent = Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
intent.putExtra(ACTION_SHOULD_ALERT_THE_USER, true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// On Android 8 (Oreo) and up, the alert is done with a notification
Timber.d("alertUser(): Notifying user")
val notificationDismissPendingIntent = NotificationDismissActivity.createDismissIntent(USER_ALERT_NOTIFICATION_ID, context)
val mainActivityPendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val notification = NotificationCompat.Builder(context, MainActivity.NOTIFICATIONS_CHANNEL_ID)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setSmallIcon(R.drawable.ic_baseline_battery_alert_24)
.setContentTitle(context.getString(R.string.battery_charge_reached_limit))
.setContentText(context.getString(R.string.disconnect_device_from_charger))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setLocalOnly(true)
.setAutoCancel(true)
.setOngoing(true)
// When the screen is off, Android will run this activity (our MainActivity)
// instead of a notification. MainActivity will alert the user and let them
// turn off the alert. This is same behaviour as an alarm clock.
.setFullScreenIntent(mainActivityPendingIntent, true)
// If the user clicks the notification - dismiss it. This is done by a special
// activity that we set here.
.setContentIntent(notificationDismissPendingIntent) // todo: Is this needed when we have setAutoCancel(true)?
// Some users may not know to click the notification in order to silence it.
// For these users we provide an explicit "Dismiss" button that does the same
// as clicking the notification body.
.addAction(R.drawable.ic_baseline_cancel_24, "Dismiss", notificationDismissPendingIntent) // todo string
.build()
notification.flags.or(Notification.FLAG_INSISTENT)
NotificationManagerCompat.from(context).notify(USER_ALERT_NOTIFICATION_ID, notification)
} else {
// Before Android 8 (Oreo), the alert is done by starting MainActivity
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
val wakeLock = powerManager.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.ON_AFTER_RELEASE,
"ChargeCap:BatteryMonitoringService"
)
wakeLock.acquire(5000L)
context.startActivity(intent)
}
}
| 0
|
Kotlin
|
0
| 0
|
0d87a28c4a0a0f8cad25e19a63c51a48defb5993
| 3,449
|
ChargeCap
|
MIT License
|
src/main/kotlin/de/gmuth/log/Slf4jAdapter.kt
|
gmuth
| 247,626,449
| false
| null |
package de.gmuth.log
/**
* Copyright (c) 2022 <NAME>
*/
import de.gmuth.log.Logging.LogLevel
import de.gmuth.log.Logging.LogLevel.*
// slf4j, http://www.slf4j.org
class Slf4jAdapter(name: String) : Logger(name, supportLevelConfiguration = false) {
private val slf4jLogger = org.slf4j.LoggerFactory.getLogger(name)
override var logLevel: LogLevel
get() = throw UnsupportedOperationException("get logLevel not supported")
set(value) {
throw UnsupportedOperationException("set logLevel not supported")
}
override fun isEnabled(level: LogLevel) = with(slf4jLogger) {
when (level) {
OFF -> false
TRACE -> isTraceEnabled
DEBUG -> isDebugEnabled
INFO -> isInfoEnabled
WARN -> isWarnEnabled
ERROR -> isErrorEnabled
}
}
@SuppressWarnings("kotlin:S108")
override fun publish(messageLogLevel: LogLevel, throwable: Throwable?, messageString: String?) = with(slf4jLogger) {
when (messageLogLevel) {
OFF -> {} // don't publish anything
TRACE -> trace(messageString, throwable)
DEBUG -> debug(messageString, throwable)
INFO -> info(messageString, throwable)
WARN -> warn(messageString, throwable)
ERROR -> error(messageString, throwable)
}
}
companion object {
fun configure() {
Logging.factory = Logging.Factory { Slf4jAdapter(it) }
}
}
}
| 0
|
Kotlin
|
8
| 49
|
c18ebf4ffdb3fe69d5517717305f1e1d9baa5c10
| 1,510
|
ipp-client-kotlin
|
MIT License
|
app/src/main/java/com/app/whakaara/data/preferences/PreferencesDatabase.kt
|
ahudson20
| 531,856,934
| false
|
{"Kotlin": 170057, "Shell": 761}
|
package com.app.whakaara.data.preferences
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [Preferences::class], version = 1, exportSchema = false)
abstract class PreferencesDatabase : RoomDatabase() {
abstract fun preferencesDao(): PreferencesDao
}
| 1
|
Kotlin
|
1
| 3
|
a5c93145e580b065342dd9833bb2b496bd6a9e00
| 292
|
whakaara
|
MIT License
|
app/src/main/java/com/example/cstv/entities/Live.kt
|
GusttavoOliveira
| 474,155,926
| false
| null |
package com.example.cstv.entities
data class Live(
val opens_at: Any,
val supported: Boolean,
val url: Any
)
| 0
|
Kotlin
|
0
| 2
|
7a9a270bb99d50c4b3c58e77b2ee348479eaeb14
| 121
|
CSTV
|
MIT License
|
src/main/kotlin/playground/common/exception/MoxRestClientException.kt
|
dtkmn
| 596,118,171
| false
|
{"Kotlin": 334372, "Dockerfile": 763}
|
package playground.common.exception
import org.springframework.http.HttpStatus
class MoxRestClientException(
override val statusCode: HttpStatus,
override val errorCode: String,
val debugMessage: String,
val validationErrors: Map<String, Any>? = null
) : DragonException(debugMessage, errorCode, statusCode, null)
| 0
|
Kotlin
|
0
| 0
|
06b6e996d3d319a7ad390dab9b3f33132f5f0378
| 332
|
kotlin-playground
|
MIT License
|
modules/wasm-binary/src/commonMain/kotlin/ParserException.kt
|
wasmium
| 761,480,110
| false
|
{"Kotlin": 584714, "JavaScript": 203}
|
package org.wasmium.wasm.binary
public class ParserException(
override val message: String,
) : WasmBinaryException()
| 0
|
Kotlin
|
0
| 3
|
4c474db29b638e2ad09f19ad9d90dd648fc7c776
| 123
|
wasmium-wasm-binary
|
Apache License 2.0
|
app/src/main/java/com/rpfcoding/borutocharacterviewer/di/DatabaseModule.kt
|
riley0521
| 461,738,945
| false
| null |
package com.rpfcoding.borutocharacterviewer.di
import android.content.Context
import androidx.room.Room
import com.rpfcoding.borutocharacterviewer.data.local.BorutoDatabase
import com.rpfcoding.borutocharacterviewer.data.local.dao.HeroEntityDao
import com.rpfcoding.borutocharacterviewer.data.local.dao.HeroRemoteKeyDao
import com.rpfcoding.borutocharacterviewer.data.repository.LocalHeroRemoteKeyRepositoryImpl
import com.rpfcoding.borutocharacterviewer.data.repository.LocalHeroRepositoryImpl
import com.rpfcoding.borutocharacterviewer.domain.repository.LocalHeroRemoteKeyRepository
import com.rpfcoding.borutocharacterviewer.domain.repository.LocalHeroRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Provides
@Singleton
fun provideDatabase(
@ApplicationContext context: Context
): BorutoDatabase = Room.databaseBuilder(
context,
BorutoDatabase::class.java,
"boruto_database"
).build()
@Provides
@Singleton
fun provideHeroDao(
db: BorutoDatabase
) = db.heroEntityDao()
@Provides
@Singleton
fun provideHeroRemoteKeyDao(
db: BorutoDatabase
) = db.heroRemoteKeyDao()
@Provides
@Singleton
fun provideHeroRepository(
heroEntityDao: HeroEntityDao
): LocalHeroRepository = LocalHeroRepositoryImpl(heroEntityDao)
@Provides
@Singleton
fun provideHeroRemoteKeyRepository(
heroRemoteKeyDao: HeroRemoteKeyDao
): LocalHeroRemoteKeyRepository = LocalHeroRemoteKeyRepositoryImpl(heroRemoteKeyDao)
}
| 0
|
Kotlin
|
0
| 0
|
86baf29435338ac9294224174a2fcc52d37f7945
| 1,784
|
BorutoCharacterViewer
|
Apache License 2.0
|
src/main/kotlin/me/fzzyhmstrs/amethyst_imbuement/entity/ManaPotionEntity.kt
|
fzzyhmstrs
| 461,338,617
| false
|
{"Kotlin": 1732617, "Java": 107324}
|
package me.fzzyhmstrs.amethyst_imbuement.entity
import me.fzzyhmstrs.amethyst_imbuement.registry.RegisterEntity
import me.fzzyhmstrs.amethyst_imbuement.registry.RegisterItem
import net.minecraft.entity.EntityType
import net.minecraft.entity.ExperienceOrbEntity
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.projectile.thrown.ThrownItemEntity
import net.minecraft.item.Item
import net.minecraft.potion.PotionUtil
import net.minecraft.potion.Potions
import net.minecraft.server.world.ServerWorld
import net.minecraft.util.hit.HitResult
import net.minecraft.world.World
import net.minecraft.world.WorldEvents
class ManaPotionEntity: ThrownItemEntity {
constructor(entityType: EntityType<out ManaPotionEntity>, world: World): super(entityType, world)
constructor(world: World, owner: LivingEntity): super(RegisterEntity.MANA_POTION, owner, world)
constructor(world: World, x: Double, y: Double, z: Double): super(RegisterEntity.MANA_POTION, x, y, z, world)
override fun getDefaultItem(): Item {
return RegisterItem.MANA_POTION
}
override fun getGravity(): Float {
return 0.07f
}
override fun onCollision(hitResult: HitResult?) {
super.onCollision(hitResult)
if (this.world is ServerWorld) {
this.world.syncWorldEvent(
WorldEvents.SPLASH_POTION_SPLASHED,
this.blockPos,
PotionUtil.getColor(Potions.WATER)
)
val i: Int = (3 + this.world.random.nextInt(5) + this.world.random.nextInt(5)) * 2
ExperienceOrbEntity.spawn(this.world as ServerWorld?, this.pos, i)
this.discard()
}
}
}
| 9
|
Kotlin
|
8
| 4
|
e5c456771de86c614858fa24587bf03a22590f3f
| 1,688
|
ai
|
MIT License
|
app/src/main/java/me/qcuncle/nowinnews/domain/usecases/userentry/SaveNewsShowNumber.kt
|
QCuncle
| 768,718,477
| false
|
{"Kotlin": 313407}
|
package me.qcuncle.nowinnews.domain.usecases.userentry
import me.qcuncle.nowinnews.domain.manager.SubscriptionManager
import javax.inject.Inject
class SaveNewsShowNumber @Inject constructor(
private val subscriptionManager: SubscriptionManager
) {
suspend operator fun invoke(num: Int) {
subscriptionManager.setShowNumberOfHotArticle(num)
}
}
| 0
|
Kotlin
|
0
| 7
|
2105632328876c3c23349470c05a0b7cde226931
| 364
|
nowinnews
|
Apache License 2.0
|
app/src/main/java/me/qcuncle/nowinnews/domain/usecases/userentry/SaveNewsShowNumber.kt
|
QCuncle
| 768,718,477
| false
|
{"Kotlin": 313407}
|
package me.qcuncle.nowinnews.domain.usecases.userentry
import me.qcuncle.nowinnews.domain.manager.SubscriptionManager
import javax.inject.Inject
class SaveNewsShowNumber @Inject constructor(
private val subscriptionManager: SubscriptionManager
) {
suspend operator fun invoke(num: Int) {
subscriptionManager.setShowNumberOfHotArticle(num)
}
}
| 0
|
Kotlin
|
0
| 7
|
2105632328876c3c23349470c05a0b7cde226931
| 364
|
nowinnews
|
Apache License 2.0
|
kgl-glfw/src/nativeMain/kotlin/com/kgl/glfw/Window.kt
|
Dominaezzz
| 164,507,082
| false
| null |
/**
* Copyright [2019] [<NAME>]
*
* 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.kgl.glfw
import cglfw.*
import cnames.structs.GLFWwindow
import com.kgl.core.*
import io.ktor.utils.io.core.*
import kotlinx.cinterop.*
import kotlin.native.concurrent.*
actual class Window private constructor(val ptr: CPointer<GLFWwindow>) : Closeable {
actual constructor(
width: Int,
height: Int,
title: String,
monitor: Monitor?,
share: Window?
) : this(
glfwCreateWindow(width, height, title, monitor?.ptr, share?.ptr)
?: throw Exception("Could not create window.")
)
init {
ensureNeverFrozen()
check(glfwGetWindowUserPointer(ptr) == null) {
"Must not already have a userPointer"
}
glfwSetWindowUserPointer(ptr, StableRef.create(this).asCPointer())
}
actual var position: Pair<Int, Int>
get() {
VirtualStack.push()
return try {
val width = VirtualStack.alloc<IntVar>()
val height = VirtualStack.alloc<IntVar>()
glfwGetWindowPos(ptr, width.ptr, height.ptr)
width.value to height.value
} finally {
VirtualStack.pop()
}
}
set(value) {
glfwSetWindowPos(ptr, value.first, value.second)
}
actual var size: Pair<Int, Int>
get() {
VirtualStack.push()
return try {
val width = VirtualStack.alloc<IntVar>()
val height = VirtualStack.alloc<IntVar>()
glfwGetWindowSize(ptr, width.ptr, height.ptr)
width.value to height.value
} finally {
VirtualStack.pop()
}
}
set(value) {
glfwSetWindowSize(ptr, value.first, value.second)
}
actual val frameBufferSize: Pair<Int, Int>
get() {
VirtualStack.push()
return try {
val width = VirtualStack.alloc<IntVar>()
val height = VirtualStack.alloc<IntVar>()
glfwGetFramebufferSize(ptr, width.ptr, height.ptr)
width.value to height.value
} finally {
VirtualStack.pop()
}
}
actual val contentScale: Pair<Float, Float>
get() {
VirtualStack.push()
return try {
val width = VirtualStack.alloc<FloatVar>()
val height = VirtualStack.alloc<FloatVar>()
glfwGetWindowContentScale(ptr, width.ptr, height.ptr)
width.value to height.value
} finally {
VirtualStack.pop()
}
}
actual val frameSize: FrameSize
get() {
VirtualStack.push()
return try {
val left = VirtualStack.alloc<IntVar>()
val top = VirtualStack.alloc<IntVar>()
val right = VirtualStack.alloc<IntVar>()
val bottom = VirtualStack.alloc<IntVar>()
glfwGetWindowFrameSize(ptr, left.ptr, top.ptr, right.ptr, bottom.ptr)
FrameSize(left.value, top.value, right.value, bottom.value)
} finally {
VirtualStack.pop()
}
}
actual var clipboardString: String?
get() = glfwGetClipboardString(ptr)?.toKString()
set(value) {
glfwSetClipboardString(ptr, value)
}
actual var shouldClose: Boolean
get() = glfwWindowShouldClose(ptr) == GLFW_TRUE
set(value) {
glfwSetWindowShouldClose(ptr, if (value) GLFW_TRUE else GLFW_FALSE)
}
actual var isIconified: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_ICONIFIED) == GLFW_TRUE
set(value) {
if (value) {
glfwIconifyWindow(ptr)
} else {
glfwRestoreWindow(ptr)
}
}
actual var isVisible: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_VISIBLE) == GLFW_TRUE
set(value) {
if (value) {
glfwShowWindow(ptr)
} else {
glfwHideWindow(ptr)
}
}
actual var isDecorated: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_DECORATED) == GLFW_TRUE
set(value) {
glfwSetWindowAttrib(ptr, GLFW_DECORATED, if (value) GLFW_TRUE else GLFW_FALSE)
}
actual var isResizable: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_RESIZABLE) == GLFW_TRUE
set(value) {
glfwSetWindowAttrib(ptr, GLFW_RESIZABLE, if (value) GLFW_TRUE else GLFW_FALSE)
}
actual var isFloating: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_FLOATING) == GLFW_TRUE
set(value) {
glfwSetWindowAttrib(ptr, GLFW_FLOATING, if (value) GLFW_TRUE else GLFW_FALSE)
}
actual var isAutoIconify: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_AUTO_ICONIFY) == GLFW_TRUE
set(value) {
glfwSetWindowAttrib(ptr, GLFW_AUTO_ICONIFY, if (value) GLFW_TRUE else GLFW_FALSE)
}
actual var isFocusOnShow: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_FOCUS_ON_SHOW) == GLFW_TRUE
set(value) {
glfwSetWindowAttrib(ptr, GLFW_FOCUS_ON_SHOW, if (value) GLFW_TRUE else GLFW_FALSE)
}
actual val isFocused: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_FOCUSED) == GLFW_TRUE
actual val isMaximized: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_MAXIMIZED) == GLFW_TRUE
actual val isHovered: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_HOVERED) == GLFW_TRUE
actual val hasTransparentFramebuffer: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_TRANSPARENT_FRAMEBUFFER) == GLFW_TRUE
actual val clientApi: ClientApi
get() = ClientApi.from(glfwGetWindowAttrib(ptr, GLFW_CLIENT_API))
actual val contextCreationApi: CreationApi
get() = CreationApi.from(glfwGetWindowAttrib(ptr, GLFW_CONTEXT_CREATION_API))
actual val contextVersionMajor: Int
get() = glfwGetWindowAttrib(ptr, GLFW_CONTEXT_VERSION_MAJOR)
actual val contextVersionMinor: Int
get() = glfwGetWindowAttrib(ptr, GLFW_CONTEXT_VERSION_MINOR)
actual val contextRevision: Int
get() = glfwGetWindowAttrib(ptr, GLFW_CONTEXT_REVISION)
actual val openGLForwardCompat: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_OPENGL_FORWARD_COMPAT) == GLFW_TRUE
actual val openGLDebugContext: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_OPENGL_DEBUG_CONTEXT) == GLFW_TRUE
actual val openGLProfile: OpenGLProfile
get() = OpenGLProfile.from(glfwGetWindowAttrib(ptr, GLFW_OPENGL_PROFILE))
actual val contextReleaseBehaviour: ReleaseBehaviour
get() = ReleaseBehaviour.from(glfwGetWindowAttrib(ptr, GLFW_CONTEXT_RELEASE_BEHAVIOR))
actual val contextNoError: Boolean
get() = glfwGetWindowAttrib(ptr, GLFW_CONTEXT_NO_ERROR) == GLFW_TRUE
actual val contextRobustness: Robustness
get() = Robustness.from(glfwGetWindowAttrib(ptr, GLFW_CONTEXT_ROBUSTNESS))
actual val monitor: Monitor? get() = glfwGetWindowMonitor(ptr)?.let { Monitor(it) }
actual var cursorPosition: Pair<Double, Double>
get() {
VirtualStack.push()
return try {
val width = VirtualStack.alloc<DoubleVar>()
val height = VirtualStack.alloc<DoubleVar>()
glfwGetCursorPos(ptr, width.ptr, height.ptr)
width.value to height.value
} finally {
VirtualStack.pop()
}
}
set(value) {
glfwSetCursorPos(ptr, value.first, value.second)
}
actual var opacity: Float
get() = glfwGetWindowOpacity(ptr)
set(value) {
glfwSetWindowOpacity(ptr, value)
}
actual var cursorMode: CursorMode
get() = CursorMode.from(glfwGetInputMode(ptr, GLFW_CURSOR))
set(value) {
glfwSetInputMode(ptr, GLFW_CURSOR, value.value)
}
actual var stickyKeysEnabled: Boolean
get() = glfwGetInputMode(ptr, GLFW_STICKY_KEYS) == GLFW_TRUE
set(value) {
glfwSetInputMode(ptr, GLFW_STICKY_KEYS, if (value) GLFW_TRUE else GLFW_FALSE)
}
actual var stickyMouseButtonsEnabled: Boolean
get() = glfwGetInputMode(ptr, GLFW_STICKY_MOUSE_BUTTONS) == GLFW_TRUE
set(value) {
glfwSetInputMode(ptr, GLFW_STICKY_MOUSE_BUTTONS, if (value) GLFW_TRUE else GLFW_FALSE)
}
actual var lockKeyModsEnabled: Boolean
get() = glfwGetInputMode(ptr, GLFW_LOCK_KEY_MODS) == GLFW_TRUE
set(value) {
glfwSetInputMode(ptr, GLFW_LOCK_KEY_MODS, if (value) GLFW_TRUE else GLFW_FALSE)
}
actual var rawMouseButtonEnabled: Boolean
get() = glfwGetInputMode(ptr, GLFW_RAW_MOUSE_MOTION) == GLFW_TRUE
set(value) {
glfwSetInputMode(ptr, GLFW_RAW_MOUSE_MOTION, if (value) GLFW_TRUE else GLFW_FALSE)
}
actual fun setMonitor(monitor: Monitor?, xpos: Int, ypos: Int, width: Int, height: Int, refreshRate: Int) {
glfwSetWindowMonitor(ptr, monitor?.ptr, xpos, ypos, width, height, refreshRate)
}
actual fun setTitle(title: String) {
glfwSetWindowTitle(ptr, title)
}
actual fun setSizeLimits(minWidth: Int, minHeight: Int, maxWidth: Int, maxHeight: Int) {
glfwSetWindowSizeLimits(ptr, minWidth, minHeight, maxWidth, maxHeight)
}
actual fun setAspectRatio(number: Int, denom: Int) {
glfwSetWindowAspectRatio(ptr, number, denom)
}
actual fun setIcon(images: Array<Image>) {
glfwSetWindowIcon(ptr, images.size, createValues(images.size) { index ->
val image = images[index]
pixels = image.pixels.pointer.reinterpret()
width = image.width
height = image.height
})
}
actual fun maximize() {
glfwMaximizeWindow(ptr)
}
actual fun focus() {
glfwFocusWindow(ptr)
}
actual fun requestAttention() {
glfwRequestWindowAttention(ptr)
}
actual fun setCursor(cursor: Cursor?) {
glfwSetCursor(ptr, cursor?.ptr)
}
actual fun getKey(key: KeyboardKey): Action = Action.from(glfwGetKey(ptr, key.value))
actual fun getMouseButton(button: MouseButton): Action = Action.from(glfwGetMouseButton(ptr, button.value))
actual fun swapBuffers() {
glfwSwapBuffers(ptr)
}
private var windowPosCallback: WindowPosCallback? = null
private var windowSizeCallback: WindowSizeCallback? = null
private var frameBufferCallback: FrameBufferCallback? = null
private var windowCloseCallback: WindowCloseCallback? = null
private var windowRefreshCallback: WindowRefreshCallback? = null
private var windowFocusCallback: WindowFocusCallback? = null
private var windowMaximizeCallback: WindowMaximizeCallback? = null
private var windowIconifyCallback: WindowIconifyCallback? = null
private var cursorEnterCallback: CursorEnterCallback? = null
private var windowContentScaleCallback: WindowContentScaleCallback? = null
private var cursorPosCallback: CursorPosCallback? = null
private var scrollCallback: ScrollCallback? = null
private var dropCallback: DropCallback? = null
private var keyCallback: KeyCallback? = null
private var mouseButtonCallback: MouseButtonCallback? = null
private var charCallback: CharCallback? = null
private var charModsCallback: CharModsCallback? = null
private inline fun <TCallback, TNativeCallback> setCallback(
callback: TCallback?,
propGetter: () -> TCallback?,
propSetter: (TCallback?) -> Unit,
realSetter: (CValuesRef<GLFWwindow>?, TNativeCallback?) -> TNativeCallback?,
getCFunction: () -> TNativeCallback?
): TCallback? {
val previous = propGetter()
propSetter(callback)
if (callback != null) {
// only set the native callback if there was no callback set,
// since the native callback has a reference to the property
if (previous == null) {
realSetter(ptr, getCFunction())
}
} else {
realSetter(ptr, null)
}
return previous
}
actual fun setPosCallback(callback: WindowPosCallback?): WindowPosCallback? {
return setCallback(callback, { windowPosCallback }, { windowPosCallback = it }, ::glfwSetWindowPosCallback) {
staticCFunction { window, x, y ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.windowPosCallback?.invoke(context, x, y)
}
}
}
actual fun setSizeCallback(callback: WindowSizeCallback?): WindowSizeCallback? {
return setCallback(callback, { windowSizeCallback }, { windowSizeCallback = it }, ::glfwSetWindowSizeCallback) {
staticCFunction { window, width, height ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.windowSizeCallback?.invoke(context, width, height)
}
}
}
actual fun setCloseCallback(callback: WindowCloseCallback?): WindowCloseCallback? {
return setCallback(
callback,
{ windowCloseCallback },
{ windowCloseCallback = it },
::glfwSetWindowCloseCallback
) {
staticCFunction { window ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.windowCloseCallback?.invoke(context)
}
}
}
actual fun setRefreshCallback(callback: WindowRefreshCallback?): WindowRefreshCallback? {
return setCallback(
callback,
{ windowRefreshCallback },
{ windowRefreshCallback = it },
::glfwSetWindowRefreshCallback
) {
staticCFunction { window ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.windowRefreshCallback?.invoke(context)
}
}
}
actual fun setFocusCallback(callback: WindowFocusCallback?): WindowFocusCallback? {
return setCallback(
callback,
{ windowFocusCallback },
{ windowFocusCallback = it },
::glfwSetWindowFocusCallback
) {
staticCFunction { window, focused ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.windowFocusCallback?.invoke(context, focused == GLFW_TRUE)
}
}
}
actual fun setIconifyCallback(callback: WindowIconifyCallback?): WindowIconifyCallback? {
return setCallback(
callback,
{ windowIconifyCallback },
{ windowIconifyCallback = it },
::glfwSetWindowIconifyCallback
) {
staticCFunction { window, iconified ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.windowIconifyCallback?.invoke(context, iconified == GLFW_TRUE)
}
}
}
actual fun setMaximizeCallback(callback: WindowMaximizeCallback?): WindowMaximizeCallback? {
return setCallback(
callback,
{ windowMaximizeCallback },
{ windowMaximizeCallback = it },
::glfwSetWindowMaximizeCallback
) {
staticCFunction { window, maximized ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.windowMaximizeCallback?.invoke(context, maximized == GLFW_TRUE)
}
}
}
actual fun setContentScaleCallback(callback: WindowContentScaleCallback?): WindowContentScaleCallback? {
return setCallback(
callback,
{ windowContentScaleCallback },
{ windowContentScaleCallback = it },
::glfwSetWindowContentScaleCallback
) {
staticCFunction { window, x, y ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.windowContentScaleCallback?.invoke(context, x, y)
}
}
}
actual fun setCursorEnterCallback(callback: CursorEnterCallback?): CursorEnterCallback? {
return setCallback(
callback,
{ cursorEnterCallback },
{ cursorEnterCallback = it },
::glfwSetCursorEnterCallback
) {
staticCFunction { window, entered ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.cursorEnterCallback?.invoke(context, entered == GLFW_TRUE)
}
}
}
actual fun setScrollCallback(callback: ScrollCallback?): ScrollCallback? {
return setCallback(callback, { scrollCallback }, { scrollCallback = it }, ::glfwSetScrollCallback) {
staticCFunction { window, x, y ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.scrollCallback?.invoke(context, x, y)
}
}
}
actual fun setCursorPosCallback(callback: CursorPosCallback?): CursorPosCallback? {
return setCallback(callback, { cursorPosCallback }, { cursorPosCallback = it }, ::glfwSetCursorPosCallback) {
staticCFunction { window, width, height ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.cursorPosCallback?.invoke(context, width, height)
}
}
}
actual fun setFrameBufferCallback(callback: FrameBufferCallback?): FrameBufferCallback? {
return setCallback(
callback,
{ frameBufferCallback },
{ frameBufferCallback = it },
::glfwSetFramebufferSizeCallback
) {
staticCFunction { window, width, height ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.frameBufferCallback?.invoke(context, width, height)
}
}
}
actual fun setDropCallback(callback: DropCallback?): DropCallback? {
return setCallback(callback, { dropCallback }, { dropCallback = it }, ::glfwSetDropCallback) {
staticCFunction { window, count, names ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
checkNotNull(names)
context.dropCallback?.invoke(context, Array(count) { names[it]!!.toKString() })
}
}
}
actual fun setKeyCallback(callback: KeyCallback?): KeyCallback? {
return setCallback(callback, { keyCallback }, { keyCallback = it }, ::glfwSetKeyCallback) {
staticCFunction { window, key, scancode, action, mods ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.keyCallback?.invoke(
context, KeyboardKey.from(key), scancode, Action.from(action), Flag(mods)
)
}
}
}
actual fun setMouseButtonCallback(callback: MouseButtonCallback?): MouseButtonCallback? {
return setCallback(
callback,
{ mouseButtonCallback },
{ mouseButtonCallback = it },
::glfwSetMouseButtonCallback
) {
staticCFunction { window, button, action, mods ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.mouseButtonCallback?.invoke(
context, MouseButton.from(button), Action.from(action), Flag(mods)
)
}
}
}
actual fun setCharCallback(callback: CharCallback?): CharCallback? {
return setCallback(callback, { charCallback }, { charCallback = it }, ::glfwSetCharCallback) {
staticCFunction { window, codepoint ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.charCallback?.invoke(context, codepoint)
}
}
}
actual fun setCharModsCallback(callback: CharModsCallback?): CharModsCallback? {
return setCallback(callback, { charModsCallback }, { charModsCallback = it }, ::glfwSetCharModsCallback) {
staticCFunction { window, codepoint, mods ->
val context = glfwGetWindowUserPointer(window)!!.asStableRef<Window>().get()
context.charModsCallback?.invoke(context, codepoint, Flag(mods))
}
}
}
override fun close() {
glfwGetWindowUserPointer(ptr)!!.asStableRef<Window>().dispose()
glfwDestroyWindow(ptr)
}
}
| 13
|
Kotlin
|
11
| 96
|
41155a8200602535697b872232e41cfe6f5eb20e
| 18,276
|
kgl
|
Apache License 2.0
|
app/src/main/java/com/example/classvista_admin/Main/Teacher/EnrollTeacherInSubjects.kt
|
abdulqaderpatel
| 732,734,663
| false
|
{"Kotlin": 146089}
|
package com.example.classvista_admin.Main.Teacher
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.NavController
import com.example.classvista_admin.Components.Main.AdminButton
import com.example.classvista_admin.Components.Main.PrimaryAppBar
import com.example.classvista_admin.Components.Teacher.SelectSubjectsCard
import com.example.classvista_admin.Data.TeacherInterface
import com.example.classvista_admin.Models.Subject.Subject
import com.example.classvista_admin.Navigation.Screen
import com.example.classvista_admin.Utils.RetrofitInstance
import com.example.classvista_admin.ViewModels.TeacherViewModel
import com.example.classvista_admin.ViewModels.UserViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
@Composable
fun EnrollTeacherInSubjects(
navController: NavController,
userViewModel: UserViewModel,
teacherViewModel: TeacherViewModel, teacherId: String
) {
var buttonLoading by remember {
mutableStateOf(false)
}
var context = LocalContext.current
LaunchedEffect(Dispatchers.IO) {
teacherViewModel.subjects.clear()
teacherViewModel.subjects.addAll(
RetrofitInstance.subjectInterface.getSubjectsUnassignedToTeachers("Bearer ${userViewModel.userId.value.token}")
.body()!!.data
)
teacherViewModel.subjects.map {
teacherViewModel.isSubjectSelected.add(mutableStateOf(false))
}
}
Scaffold(
topBar = { PrimaryAppBar(title = "Assign Subjects") },
bottomBar = {
AdminButton(label = "Assign Subjects", buttonLoading = buttonLoading) {
CoroutineScope(Dispatchers.Main).launch {
buttonLoading = true;
RetrofitInstance.teacherInterface.assignMultipleSubjectsToTeacher(
"Bearer ${userViewModel.userId.value.token}",
TeacherInterface.SubjectsTeacher(
subjectIds = teacherViewModel.selectedSubjectIds,
teacherId = teacherId
)
)
navController.popBackStack()
teacherViewModel.isTeacherDataLoaded.value = false
buttonLoading = false;
android.os.Handler(Looper.getMainLooper()).post {
Toast.makeText(context, "Subjects Assigned To Teacher", Toast.LENGTH_LONG)
.show()
}
}
}
}) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(it)
)
{
LazyColumn {
itemsIndexed(teacherViewModel.subjects)
{ index, subject ->
SelectSubjectsCard(
isSelected = teacherViewModel.isSubjectSelected[index].value,
onCheckedChange = {
if (!teacherViewModel.isSubjectSelected[index].value) {
teacherViewModel.selectedSubjectIds.add(subject.id)
teacherViewModel.isSubjectSelected[index].value = true;
Log.d("Subjects", teacherViewModel.selectedSubjectIds.toString())
} else {
teacherViewModel.selectedSubjectIds.remove(subject.id)
teacherViewModel.isSubjectSelected[index].value = false;
Log.d("Subjects", teacherViewModel.selectedSubjectIds.toString())
}
},
subject = subject
)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4d4ef065e82ea55b6d42b63f954d50998a7d511c
| 4,674
|
ClassVista_admin
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.