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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
timeselectview/src/main/java/com/ndhzs/timeselectview/layout/ChildLayout.kt
|
985892345
| 349,440,488
| false
| null |
package com.ndhzs.timeselectview.layout
import android.annotation.SuppressLint
import android.content.Context
import android.widget.FrameLayout
import com.ndhzs.timeselectview.utils.TSViewAttrs
import com.ndhzs.timeselectview.viewinterface.IChildLayout
/**
* @author 985892345
* @date 2021/3/20
* @description [ParentLayout]之下,[com.ndhzs.timeselectview.layout.view.RectView]之上
*/
@SuppressLint("ViewConstructor")
internal class ChildLayout(
context: Context,
iChildLayout: IChildLayout,
private val attrs: TSViewAttrs,
position: Int
) : FrameLayout(context) {
init {
val lp = LayoutParams(attrs.mRectViewWidth, LayoutParams.MATCH_PARENT)
lp.leftMargin = attrs.mIntervalLeft
attachViewToParent(iChildLayout.getRectView(position), -1, lp)
val lp2 = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
attachViewToParent(iChildLayout.getSeparatorLineView(position), -1, lp2)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val newHeightMS = MeasureSpec.makeMeasureSpec(attrs.mInsideTotalHeight, MeasureSpec.EXACTLY)
super.onMeasure(widthMeasureSpec, newHeightMS)
}
}
| 0
|
Kotlin
|
0
| 5
|
74e9502cc553c8c8ddc9de765931e6547b6a5283
| 1,216
|
TimeSelectView_Library
|
Apache License 2.0
|
src/conventions/7_Invoke.kt
|
stakenschneider
| 224,120,914
| false
| null |
package conventions
class Pp {
var numberOfInvocations: Int = 0
private set
operator fun invoke(): Pp {
numberOfInvocations++
return this
}
}
fun invokeTwice(invokable: Pp) = invokable()()
fun main() {
print(invokeTwice(Pp()).numberOfInvocations)
Pp()()()()()()
}
| 0
|
Kotlin
|
0
| 1
|
91b752e1e83b22075e9ac48d8638677c105ac763
| 311
|
Kotlin-stepik
|
Apache License 2.0
|
validator-android/src/main/kotlin/by/shostko/validator/android/CollectionValidator.kt
|
shostko
| 212,552,006
| false
| null |
@file:Suppress("unused")
package by.shostko.validator.android
class NotEmptyCollectionValidator<T>(
private val tag: String? = null,
private val reason: ((Collection<T>) -> Int?)? = null,
) : BaseValidator<Collection<T>>(tag) {
override fun validate(value: Collection<T>) {
if (value.isEmpty()) {
throw ValidationException(tag, reason?.invoke(value) ?: R.string.by_shostko_validator_not_empty_collection)
}
}
}
class EmptyCollectionValidator<T>(
private val tag: String? = null,
private val reason: ((Collection<T>) -> Int?)? = null,
) : BaseValidator<Collection<T>>(tag) {
override fun validate(value: Collection<T>) {
if (value.isNotEmpty()) {
throw ValidationException(tag, reason?.invoke(value) ?: R.string.by_shostko_validator_empty_collection)
}
}
}
class SizeValidator<T>(
private val expectedSize: Int,
private val tag: String? = null,
private val reason: ((Collection<T>) -> Int?)? = null,
) : BaseValidator<Collection<T>>(tag) {
override fun validate(value: Collection<T>) {
if (value.size != expectedSize) {
throw ValidationException(tag, reason?.invoke(value) ?: R.string.by_shostko_validator_size)
}
}
}
class SizeLessValidator<T>(
private val limit: Int,
private val tag: String? = null,
private val reason: ((Collection<T>) -> Int?)? = null,
) : BaseValidator<Collection<T>>(tag) {
override fun validate(value: Collection<T>) {
if (value.size >= limit) {
throw ValidationException(tag, reason?.invoke(value) ?: R.string.by_shostko_validator_size_less)
}
}
}
class SizeLessOrEqualValidator<T>(
private val limit: Int,
private val tag: String? = null,
private val reason: ((Collection<T>) -> Int?)? = null,
) : BaseValidator<Collection<T>>(tag) {
override fun validate(value: Collection<T>) {
if (value.size > limit) {
throw ValidationException(tag, reason?.invoke(value) ?: R.string.by_shostko_validator_size_less)
}
}
}
class SizeOverValidator<T>(
private val limit: Int,
private val tag: String? = null,
private val reason: ((Collection<T>) -> Int?)? = null,
) : BaseValidator<Collection<T>>(tag) {
override fun validate(value: Collection<T>) {
if (value.size <= limit) {
throw ValidationException(tag, reason?.invoke(value) ?: R.string.by_shostko_validator_size_over)
}
}
}
class SizeOverOrEqualValidator<T>(
private val limit: Int,
private val tag: String? = null,
private val reason: ((Collection<T>) -> Int?)? = null,
) : BaseValidator<Collection<T>>(tag) {
override fun validate(value: Collection<T>) {
if (value.size < limit) {
throw ValidationException(tag, reason?.invoke(value) ?: R.string.by_shostko_validator_size_over)
}
}
}
class SingleItemValidator<T>(
private val tag: String? = null,
private val reason: ((Collection<T>) -> Int?)? = null,
) : BaseValidator<Collection<T>>(tag) {
override fun validate(value: Collection<T>) {
if (value.size != 1) {
throw ValidationException(tag, reason?.invoke(value) ?: R.string.by_shostko_validator_single_item)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
87e7fc495375507a45ddcde37955f4847f1b2e3c
| 3,265
|
validator
|
Apache License 2.0
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/GrinTongueWink.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.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.rounded.Icons
public val Icons.Outline.GrinTongueWink: ImageVector
get() {
if (_grinTongueWink != null) {
return _grinTongueWink!!
}
_grinTongueWink = Builder(name = "GrinTongueWink", defaultWidth = 512.0.dp, defaultHeight =
512.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) {
moveTo(16.0f, 14.0f)
lineTo(8.0f, 14.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f)
lineTo(9.0f, 16.0f)
verticalLineToRelative(0.6f)
curveToRelative(0.133f, 4.495f, 5.87f, 4.49f, 6.0f, 0.0f)
lineTo(15.0f, 16.0f)
horizontalLineToRelative(1.0f)
arcTo(1.0f, 1.0f, 0.0f, false, false, 16.0f, 14.0f)
close()
moveTo(13.0f, 16.6f)
curveToRelative(-0.062f, 1.839f, -1.939f, 1.837f, -2.0f, 0.0f)
lineTo(11.0f, 16.0f)
horizontalLineToRelative(2.0f)
close()
moveTo(12.0f, 0.0f)
arcTo(12.013f, 12.013f, 0.0f, false, false, 0.0f, 12.0f)
curveToRelative(0.6f, 15.9f, 23.4f, 15.893f, 24.0f, 0.0f)
arcTo(12.013f, 12.013f, 0.0f, false, false, 12.0f, 0.0f)
close()
moveTo(12.0f, 22.0f)
arcTo(10.011f, 10.011f, 0.0f, false, true, 2.0f, 12.0f)
curveTo(2.5f, -1.248f, 21.5f, -1.245f, 22.0f, 12.0f)
arcTo(10.011f, 10.011f, 0.0f, false, true, 12.0f, 22.0f)
close()
moveTo(18.0f, 10.0f)
curveToRelative(0.0f, 1.0f, -0.895f, 1.0f, -2.0f, 1.0f)
reflectiveCurveToRelative(-2.0f, 0.0f, -2.0f, -1.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 4.0f, 0.0f)
close()
moveTo(7.0f, 11.0f)
arcTo(1.0f, 1.0f, 0.0f, false, true, 7.0f, 9.0f)
horizontalLineToRelative(3.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, 2.0f)
close()
}
}
.build()
return _grinTongueWink!!
}
private var _grinTongueWink: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,029
|
icons
|
MIT License
|
src/main/kotlin/io/arct/arctlib/extensions/EntityTypeExtensions.kt
|
aeuu-archive
| 275,284,611
| false
| null |
@file:Suppress("unused")
package io.arct.arctlib.extensions
import org.bukkit.entity.EntityType
/**
* Check if a [EntityType] is a skeleton.
*
* @return Whether the [EntityType] is of type skeleton.
*/
val EntityType.isSkeleton: Boolean
get() = when (this) {
EntityType.SKELETON,
EntityType.WITHER_SKULL -> true
else -> false
}
/**
* Check if a [EntityType] is a spider.
*
* @return Whether the [EntityType] is of type spider.
*/
val EntityType.isSpider: Boolean
get() = when (this) {
EntityType.SPIDER,
EntityType.CAVE_SPIDER -> true
else -> false
}
/**
* Check if a [EntityType] is a cube.
*
* @return Whether the [EntityType] is of type cube.
*/
val EntityType.isCube: Boolean
get() = when (this) {
EntityType.SLIME,
EntityType.MAGMA_CUBE -> true
else -> false
}
/**
* Check if a [EntityType] is a zombie.
*
* @return Whether the [EntityType] is of type zombie.
*/
val EntityType.isZombie: Boolean
get() = when (this) {
EntityType.ZOMBIE,
EntityType.PIG_ZOMBIE -> true
else -> false
}
/**
* Check if a [EntityType] is a hostile.
*
* @return Whether the [EntityType] is of type hostile.
*/
val EntityType.isHostile: Boolean
get() = when (this) {
EntityType.CREEPER,
EntityType.SKELETON,
EntityType.WITHER_SKULL,
EntityType.SPIDER,
EntityType.GIANT,
EntityType.ZOMBIE,
EntityType.SLIME,
EntityType.GHAST,
EntityType.PIG_ZOMBIE,
EntityType.ENDERMAN,
EntityType.CAVE_SPIDER,
EntityType.SILVERFISH,
EntityType.BLAZE,
EntityType.MAGMA_CUBE,
EntityType.ENDER_DRAGON,
EntityType.WITHER,
EntityType.WITCH,
EntityType.ENDERMITE,
EntityType.GUARDIAN -> true
else -> false
}
/**
* Check if a [EntityType] is a passive.
*
* @return Whether the [EntityType] is of type passive.
*/
val EntityType.isPassive: Boolean
get() = when (this) {
EntityType.BAT,
EntityType.PIG,
EntityType.SHEEP,
EntityType.COW,
EntityType.CHICKEN,
EntityType.SQUID,
EntityType.WOLF,
EntityType.MUSHROOM_COW,
EntityType.SNOWMAN,
EntityType.OCELOT,
EntityType.IRON_GOLEM,
EntityType.HORSE,
EntityType.RABBIT,
EntityType.VILLAGER -> true
else -> false
}
/**
* Check if a [EntityType] is a projectile.
*
* @return Whether the [EntityType] is of type projectile.
*/
val EntityType.isProjectile: Boolean
get() = when (this) {
EntityType.ARROW,
EntityType.SNOWBALL,
EntityType.FIREBALL,
EntityType.SMALL_FIREBALL,
EntityType.ENDER_PEARL,
EntityType.SPLASH_POTION,
EntityType.EGG -> true
else -> false
}
| 2
|
Kotlin
|
1
| 2
|
29100cc3dbe81962904a1fc99fc47de4585ac9c1
| 2,892
|
arctlib
|
MIT License
|
ktx/src/main/java/com/kotlin/android/ktx/ext/TextViewExt.kt
|
R-Gang-H
| 538,443,254
| false
| null |
package com.kotlin.android.ktx.ext
import android.text.Html
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.StringRes
import com.kotlin.android.ktx.ext.core.getString
import java.util.regex.Pattern
/**
* @author ZhouSuQiang
* @email <EMAIL>
* @date 2020/7/24
*/
fun TextView.setTextWithFormat(@StringRes resId: Int, vararg params: Any) {
text = getString(resId, *params)
}
/**
* 从字符串里取出数字,并设置颜色
*/
fun TextView.textHighLight(str: String, @ColorInt color: Int) {
val p = Pattern.compile("\\d+")
val m = p.matcher(str)
val spannableString = SpannableString(str)
while (m.find()) {
val span = ForegroundColorSpan(color)
spannableString.setSpan(span, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
text = spannableString
}
/**
* 匹配关键词的内容设置高亮颜色
*/
fun TextView.convertToHtml(title: String, color: String, keyword: String) {
val htmlKey = "<font color=\"${color}\">${keyword}</font>"
text = Html.fromHtml(title.replace(keyword, htmlKey, false), Html.FROM_HTML_MODE_LEGACY)
}
| 0
|
Kotlin
|
0
| 1
|
e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28
| 1,203
|
Mtime
|
Apache License 2.0
|
app/src/androidTest/java/com/oscarliang/gitfinder/ui/search/SearchFragmentTest.kt
|
iamoscarliang
| 771,415,562
| false
|
{"Kotlin": 85207}
|
package com.oscarliang.gitfinder.ui.search
import android.content.Context
import android.view.KeyEvent
import androidx.annotation.StringRes
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.lifecycle.MutableLiveData
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.pressKey
import androidx.test.espresso.action.ViewActions.swipeDown
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.doesNotExist
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.hasDescendant
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.oscarliang.gitfinder.R
import com.oscarliang.gitfinder.model.Repo
import com.oscarliang.gitfinder.util.DataBindingIdlingResourceRule
import com.oscarliang.gitfinder.util.EspressoTestUtil.nestedScrollTo
import com.oscarliang.gitfinder.util.LoadMoreState
import com.oscarliang.gitfinder.util.RecyclerViewMatcher
import com.oscarliang.gitfinder.util.Resource
import com.oscarliang.gitfinder.util.TestUtil
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.hamcrest.CoreMatchers.not
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.loadKoinModules
import org.koin.dsl.module
@RunWith(AndroidJUnit4::class)
class SearchFragmentTest {
@Rule
@JvmField
val dataBindingIdlingResourceRule = DataBindingIdlingResourceRule<SearchFragment>()
private lateinit var navController: NavController
private lateinit var viewModel: SearchViewModel
private val searchResults = MutableLiveData<Resource<List<Repo>>>()
private val loadMoreState = MutableLiveData<LoadMoreState>()
@Before
fun init() {
navController = mockk<NavController>(relaxed = true)
viewModel = mockk<SearchViewModel>(relaxed = true)
every { viewModel.searchResults } returns searchResults
every { viewModel.loadMoreState } returns loadMoreState
val scenario = launchFragmentInContainer(themeResId = R.style.Theme_GitFinder) {
// Use a TestRunner to load a empty module and inject
// a mock ViewModel into fragment to verify interaction
loadKoinModules(module {
viewModel {
viewModel
}
})
SearchFragment()
}
dataBindingIdlingResourceRule.monitorFragment(scenario)
scenario.onFragment { fragment ->
Navigation.setViewNavController(fragment.requireView(), navController)
}
}
@Test
fun testSearchLoading() {
onView(withId(R.id.shimmer_layout)).check(matches(not(isDisplayed())))
onView(withId(R.id.edit_search)).perform(
typeText("foo"),
pressKey(KeyEvent.KEYCODE_ENTER)
)
verify { viewModel.setQuery("foo", any()) }
searchResults.postValue(Resource.loading(null))
onView(withId(R.id.shimmer_layout)).check(matches(isDisplayed()))
}
@Test
fun testSearchLoadingWithData() {
val repo = TestUtil.createRepo("foo", "bar", "owner")
searchResults.postValue(Resource.loading(listOf(repo)))
onView(withId(R.id.shimmer_layout)).check(matches(not(isDisplayed())))
onView(listMatcher().atPosition(0)).check(matches(hasDescendant(withText("foo"))))
}
@Test
fun testSearchSuccess() {
val repo = TestUtil.createRepo("foo", "bar", "owner")
searchResults.postValue(Resource.success(listOf(repo)))
onView(withId(R.id.shimmer_layout)).check(matches(not(isDisplayed())))
onView(listMatcher().atPosition(0)).check(matches(hasDescendant(withText("foo"))))
}
@Test
fun testSearchError() {
searchResults.postValue(Resource.error("idk", null))
onView(withId(R.id.text_error)).check(matches(isDisplayed()))
onView(withId(R.id.text_error)).check(matches(withText("idk")))
}
@Test
fun testSearchNull() {
val repo = TestUtil.createRepo("foo", "bar", "owner")
searchResults.postValue(Resource.success(listOf(repo)))
onView(listMatcher().atPosition(0)).check(matches(hasDescendant(withText("foo"))))
searchResults.postValue(null)
onView(listMatcher().atPosition(0)).check(doesNotExist())
}
@Test
fun testRefresh() {
searchResults.postValue(Resource.error("idk", null))
onView(withId(R.id.shimmer_layout)).check(matches(not(isDisplayed())))
onView(withId(R.id.swipe_refresh_layout)).perform(swipeDown())
verify { viewModel.retry() }
searchResults.postValue(Resource.loading(null))
onView(withId(R.id.shimmer_layout)).check(matches(isDisplayed()))
val repo = TestUtil.createRepo("foo", "bar", "owner")
searchResults.postValue(Resource.success(listOf(repo)))
onView(withId(R.id.shimmer_layout)).check(matches(not(isDisplayed())))
onView(listMatcher().atPosition(0)).check(matches(hasDescendant(withText("foo"))))
}
@Test
fun testSearchNextPage() {
val repos = TestUtil.createRepos(10, "foo", "bar", "owner")
searchResults.postValue(Resource.success(repos))
onView(listMatcher().atPosition(9)).perform(nestedScrollTo())
onView(listMatcher().atPosition(9)).check(matches(isDisplayed()))
verify { viewModel.loadNextPage() }
}
@Test
fun testLoadMoreState() {
loadMoreState.postValue(LoadMoreState(isRunning = true, hasMore = true, null))
onView(withId(R.id.progressbar)).check(matches(isDisplayed()))
loadMoreState.postValue(LoadMoreState(isRunning = false, hasMore = true, null))
onView(withId(R.id.progressbar)).check(matches(not(isDisplayed())))
}
@Test
fun testLoadMoreStateError() {
loadMoreState.postValue(LoadMoreState(isRunning = false, hasMore = false, "idk"))
onView(withId(R.id.text_message)).check(matches(hasDescendant(withText("idk"))))
}
@Test
fun testLoadMoreStateNoMore() {
loadMoreState.postValue(LoadMoreState(isRunning = false, hasMore = false, null))
onView(withText(getString(R.string.no_more_result)))
.check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)))
}
@Test
fun testNavigateToDetail() {
val repo = TestUtil.createRepo("foo", "bar", "owner").copy(url = "abc")
searchResults.postValue(Resource.success(listOf(repo)))
onView(withText("foo")).perform(click())
verify { navController.navigate(SearchFragmentDirections.actionToDetailFragment("abc")) }
}
@Test
fun testBookmark() {
val repo = TestUtil.createRepo("foo", "bar", "owner")
searchResults.postValue(Resource.success(listOf(repo)))
onView(withId(R.id.btn_bookmark)).perform(click())
verify { viewModel.toggleBookmark(repo) }
}
private fun listMatcher(): RecyclerViewMatcher {
return RecyclerViewMatcher(R.id.repo_list)
}
private fun getString(@StringRes id: Int, vararg args: Any): String {
return ApplicationProvider.getApplicationContext<Context>().getString(id, *args)
}
}
| 0
|
Kotlin
|
0
| 0
|
4f662f9dc36d349fa147fcda44c55426dfb20bf2
| 7,851
|
git-finder
|
MIT License
|
app/src/main/java/app/evolute/compose/ui/theme/Theme.kt
|
hello-there-kenobi
| 521,856,064
| false
| null |
package app.evolute.compose.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.ViewCompat
//region Composable
@Composable
fun ComposeAppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = true,
content: @Composable () -> Unit,
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme)
dynamicDarkColorScheme(context)
else
dynamicLightColorScheme(context)
}
darkTheme -> DarkColorPalette
else -> LightColorPalette
}
val typography =
if (darkTheme)
DarkTypography
else
LightTypography
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
(view.context as Activity).window.statusBarColor = colorScheme.primary.toArgb()
ViewCompat.getWindowInsetsController(view)?.isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = typography,
content = content
)
}
//endregion Composable
| 0
|
Kotlin
|
0
| 0
|
c805116388f6d14a217c76fae451ee9691bb7214
| 1,677
|
compose
|
Apache License 2.0
|
web/src/main/kotlin/world/phantasmal/web/core/rendering/conversion/MeshBuilder.kt
|
DaanVandenBosch
| 189,066,992
| false
| null |
package world.phantasmal.web.core.rendering.conversion
import org.khronos.webgl.Float32Array
import org.khronos.webgl.Uint16Array
import org.khronos.webgl.set
import world.phantasmal.core.asArray
import world.phantasmal.core.jsArrayOf
import world.phantasmal.core.unsafe.UnsafeMap
import world.phantasmal.psolib.fileFormats.ninja.XvrTexture
import world.phantasmal.web.externals.three.*
import world.phantasmal.webui.obj
class MeshBuilder(
private val textures: List<XvrTexture?> = emptyList(),
private val textureCache: UnsafeMap<Int, Texture?> = UnsafeMap(),
) {
private val positions = mutableListOf<Vector3>()
private val normals = mutableListOf<Vector3>()
private val uvs = mutableListOf<Vector2>()
private val boneIndices = mutableListOf<Short>()
private val boneWeights = mutableListOf<Float>()
private val bones = mutableListOf<Bone>()
/**
* One group per material.
*/
private val groups = mutableListOf<Group>()
private var indexCount = 0
private var defaultMaterial: Material? = null
fun getGroupIndex(
textureIndex: Int?,
alpha: Boolean,
additiveBlending: Boolean,
): Int {
val groupIndex = groups.indexOfFirst {
it.textureIndex == textureIndex &&
it.alpha == alpha &&
it.additiveBlending == additiveBlending
}
return if (groupIndex != -1) {
groupIndex
} else {
groups.add(Group(textureIndex, alpha, additiveBlending))
groups.lastIndex
}
}
val vertexCount: Int
get() = positions.size
fun getPosition(index: Int): Vector3 =
positions[index]
fun getNormal(index: Int): Vector3 =
normals[index]
fun vertex(
position: Vector3,
normal: Vector3,
uv: Vector2? = null,
boneIndices: IntArray? = null,
boneWeights: FloatArray? = null,
) {
positions.add(position)
normals.add(normal)
uv?.let { uvs.add(uv) }
if (boneIndices != null && boneWeights != null) {
require(boneIndices.size == 4)
require(boneWeights.size == 4)
for (index in boneIndices) {
this.boneIndices.add(index.toShort())
}
for (weight in boneWeights) {
this.boneWeights.add(weight)
}
}
}
fun index(groupIdx: Int, index: Int) {
groups[groupIdx].indices.push(index.toShort())
indexCount++
}
fun bone(bone: Bone) {
bones.add(bone)
}
fun defaultMaterial(material: Material) {
defaultMaterial = material
}
fun buildMesh(boundingVolumes: Boolean = false): Mesh =
build(skinning = false, boundingVolumes) { geom, materials, _ ->
Mesh(geom, materials)
}
/**
* Creates an [InstancedMesh] with 0 instances.
*/
fun buildInstancedMesh(maxInstances: Int, boundingVolumes: Boolean = false): InstancedMesh =
build(skinning = false, boundingVolumes) { geom, materials, _ ->
InstancedMesh(geom, materials, maxInstances).apply {
// Start with 0 instances.
count = 0
}
}
/**
* Creates a [SkinnedMesh] with bones and a skeleton for animation.
*/
fun buildSkinnedMesh(boundingVolumes: Boolean = false): SkinnedMesh =
build(skinning = true, boundingVolumes) { geom, materials, bones ->
SkinnedMesh(geom, materials).apply {
add(bones[0])
bind(Skeleton(bones))
}
}
private fun <M : Mesh> build(
skinning: Boolean,
boundingVolumes: Boolean,
createMesh: (BufferGeometry, Array<Material>, Array<Bone>) -> M,
): M {
check(positions.size == normals.size)
check(uvs.isEmpty() || positions.size == uvs.size)
val positions = Float32Array(3 * positions.size)
val normals = Float32Array(3 * normals.size)
val uvs = if (uvs.isEmpty()) null else Float32Array(2 * uvs.size)
for (i in this.positions.indices) {
val pos = this.positions[i]
positions[3 * i] = pos.x.toFloat()
positions[3 * i + 1] = pos.y.toFloat()
positions[3 * i + 2] = pos.z.toFloat()
val normal = this.normals[i]
normals[3 * i] = normal.x.toFloat()
normals[3 * i + 1] = normal.y.toFloat()
normals[3 * i + 2] = normal.z.toFloat()
uvs?.let {
val uv = this.uvs[i]
uvs[2 * i] = uv.x.toFloat()
uvs[2 * i + 1] = uv.y.toFloat()
}
}
val geom = BufferGeometry()
geom.setAttribute("position", Float32BufferAttribute(positions, 3))
geom.setAttribute("normal", Float32BufferAttribute(normals, 3))
uvs?.let { geom.setAttribute("uv", Float32BufferAttribute(uvs, 2)) }
if (skinning) {
check(this.positions.size == boneIndices.size / 4)
check(this.positions.size == boneWeights.size / 4)
boneIndices.maxOrNull()?.let {
check(it < bones.size)
}
geom.setAttribute(
"skinIndex",
Uint16BufferAttribute(Uint16Array(boneIndices.toTypedArray()), 4)
)
geom.setAttribute(
"skinWeight",
Float32BufferAttribute(Float32Array(boneWeights.toTypedArray()), 4)
)
}
val indices = Uint16Array(indexCount)
var offset = 0
val materials = mutableListOf<Material>()
val defaultMaterial = defaultMaterial ?: MeshLambertMaterial(obj {
this.skinning = skinning
side = DoubleSide
})
for (group in groups) {
indices.set(group.indices.asArray(), offset)
geom.addGroup(offset, group.indices.length, materials.size)
var tex: Texture? = null
if (group.textureIndex != null) {
textureCache.get(group.textureIndex)
if (tex == null) {
tex = textures.getOrNull(group.textureIndex)?.let { xvm ->
xvrTextureToThree(xvm)
}
textureCache.set(group.textureIndex, tex)
}
}
val mat = if (tex == null) {
defaultMaterial
} else {
MeshBasicMaterial(obj {
this.skinning = skinning
map = tex
side = DoubleSide
if (group.alpha) {
transparent = true
alphaTest = 0.01
}
if (group.additiveBlending) {
transparent = true
alphaTest = 0.01
blending = AdditiveBlending
}
})
}
materials.add(mat)
offset += group.indices.length
}
geom.setIndex(Uint16BufferAttribute(indices, 1))
if (boundingVolumes) {
geom.computeBoundingBox()
geom.computeBoundingSphere()
}
return createMesh(geom, materials.toTypedArray(), bones.toTypedArray())
}
private class Group(
val textureIndex: Int?,
val alpha: Boolean,
val additiveBlending: Boolean,
) {
val indices = jsArrayOf<Short>()
}
}
| 2
|
Kotlin
|
5
| 20
|
62a49b067c50a4862198e18f96159826c2ed66af
| 7,582
|
phantasmal-world
|
MIT License
|
core/src/main/java/io/android/todarch/core/dagger/ScopeFragment.kt
|
todarch
| 152,471,665
| false
| null |
/*
* Copyright 2018 Todarch
*
* 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.android.todarch.core.dagger
import javax.inject.Scope
import kotlin.annotation.AnnotationRetention.RUNTIME
/**
* @author <NAME> <<EMAIL>>
* @since 21.10.2018.
*/
@Scope
@Retention(RUNTIME)
annotation class ScopeFragment
| 0
|
Kotlin
|
0
| 3
|
34e25e9cf457379e5cb0c8e6e7793d249767b2a1
| 826
|
todarch-android
|
Apache License 2.0
|
app/src/main/kotlin/io/github/tonyguyot/flagorama/ui/home/HomeAdapter.kt
|
TonyGuyot
| 272,160,703
| false
| null |
/*
* Copyright (C) 2020 <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 io.github.tonyguyot.flagorama.ui.home
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import io.github.tonyguyot.flagorama.databinding.ListItemHomeBinding
import io.github.tonyguyot.flagorama.model.Region
import timber.log.Timber
/**
* Adapter for the [RecyclerView] in [HomeFragment].
*/
class HomeAdapter : ListAdapter<Region, HomeAdapter.ViewHolder>(DiffCallback()) {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val region = getItem(position)
holder.apply {
bind(createOnClickListener(region.code, region.name), region)
itemView.tag = region
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
ListItemHomeBinding.inflate(
LayoutInflater.from(parent.context), parent, false))
}
private fun createOnClickListener(id: String, name: String): View.OnClickListener {
return View.OnClickListener {
Timber.d("click on item %s", name)
val direction = HomeFragmentDirections.actionHomeFragmentToRegionFragment(id, name)
it.findNavController().navigate(direction)
}
}
class ViewHolder(private val binding: ListItemHomeBinding)
: RecyclerView.ViewHolder(binding.root) {
fun bind(listener: View.OnClickListener, item: Region) {
binding.apply {
clickListener = listener
region = item
executePendingBindings()
}
}
}
}
private class DiffCallback : DiffUtil.ItemCallback<Region>() {
override fun areItemsTheSame(oldItem: Region, newItem: Region): Boolean {
return oldItem.code == newItem.code
}
override fun areContentsTheSame(oldItem: Region, newItem: Region): Boolean {
return oldItem == newItem
}
}
| 0
|
Kotlin
|
1
| 0
|
8b5adf2039fd9dcbd73ff558974e61a6dd357a75
| 2,699
|
flagorama-app
|
Apache License 2.0
|
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/TengeSolid.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36756847}
|
package compose.icons.lineawesomeicons
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 compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.TengeSolid: ImageVector
get() {
if (_tengeSolid != null) {
return _tengeSolid!!
}
_tengeSolid = Builder(name = "TengeSolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp,
viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(6.6328f, 5.0f)
curveTo(6.2848f, 5.0f, 6.0f, 5.2741f, 6.0f, 5.6211f)
lineTo(6.0f, 8.3672f)
curveTo(6.0f, 8.7152f, 6.2848f, 9.0f, 6.6328f, 9.0f)
lineTo(25.3789f, 9.0f)
curveTo(25.7259f, 9.0f, 26.0f, 8.7152f, 26.0f, 8.3672f)
lineTo(26.0f, 5.6211f)
curveTo(26.0f, 5.2741f, 25.7259f, 5.0f, 25.3789f, 5.0f)
lineTo(6.6328f, 5.0f)
close()
moveTo(6.6328f, 12.0f)
curveTo(6.2848f, 12.0f, 6.0f, 12.2841f, 6.0f, 12.6211f)
lineTo(6.0f, 15.3672f)
curveTo(6.0f, 15.7152f, 6.2848f, 16.0f, 6.6328f, 16.0f)
lineTo(14.0f, 16.0f)
lineTo(14.0f, 27.3789f)
curveTo(14.0f, 27.7259f, 14.2741f, 28.0f, 14.6211f, 28.0f)
lineTo(17.3789f, 28.0f)
curveTo(17.7259f, 28.0f, 18.0f, 27.7259f, 18.0f, 27.3789f)
lineTo(18.0f, 16.0f)
lineTo(25.3789f, 16.0f)
curveTo(25.7259f, 16.0f, 26.0f, 15.7152f, 26.0f, 15.3672f)
lineTo(26.0f, 12.6211f)
curveTo(26.0f, 12.2841f, 25.7259f, 12.0f, 25.3789f, 12.0f)
lineTo(6.6328f, 12.0f)
close()
}
}
.build()
return _tengeSolid!!
}
private var _tengeSolid: ImageVector? = null
| 15
|
Kotlin
|
20
| 460
|
651badc4ace0137c5541f859f61ffa91e5242b83
| 2,542
|
compose-icons
|
MIT License
|
geojson/src/commonMain/kotlin/io/github/elcolto/geokjson/geojson/serialization/FeatureSerializer.kt
|
elcolto
| 807,275,879
| false
|
{"Kotlin": 174678}
|
package io.github.elcolto.geokjson.geojson.serialization
import io.github.elcolto.geokjson.geojson.Feature
import io.github.elcolto.geokjson.geojson.Geometry
import io.github.elcolto.geokjson.geojson.serialization.BoundingBoxSerializer.toJsonArray
import io.github.elcolto.geokjson.geojson.serialization.GeometrySerializer.toJsonObject
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonEncoder
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.put
internal class FeatureSerializer<T : Geometry> : JsonSerializer<Feature<T>> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Feature")
override fun deserialize(input: JsonDecoder): Feature<T> = Feature.fromJson(input.decodeJsonElement().jsonObject)
override fun serialize(output: JsonEncoder, value: Feature<T>) {
output.encodeJsonElement(value.toJsonObject())
}
}
internal fun <T : Geometry> Feature<T>.toJsonObject(): JsonObject = buildJsonObject {
put("type", "Feature")
bbox?.let { put("bbox", it.toJsonArray()) }
geometry?.let { put("geometry", it.toJsonObject()) }
id?.let { put("id", it) }
put("properties", JsonObject(properties))
}
| 60
|
Kotlin
|
0
| 1
|
441bcf7fadea923706ecb426f2a4c29aacd0dbb7
| 1,448
|
GeoKJSON
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/assessments/api/answers/CheckboxGroupDto.kt
|
ministryofjustice
| 289,880,556
| false
|
{"Kotlin": 467156, "Dockerfile": 1341, "Shell": 181}
|
package uk.gov.justice.digital.assessments.api.answers
import io.swagger.v3.oas.annotations.media.Schema
import uk.gov.justice.digital.assessments.api.groups.GroupContentDto
import uk.gov.justice.digital.assessments.jpa.entities.refdata.GroupEntity
import java.util.UUID
data class CheckboxGroupDto(
@Schema(description = "Checkbox Group Identifier", example = "<uuid>")
val checkboxGroupId: UUID,
@Schema(description = "Checkbox Code", example = "Checkbox-code-name")
val checkboxGroupCode: String,
@Schema(description = "Checkbox Title", example = "Checkbox of children")
val title: String? = null,
@Schema(description = "Checkbox Subheading", example = "Some group subheading")
val subheading: String? = null,
@Schema(description = "Checkbox Help-text", example = "Some group help text")
val helpText: String? = null,
@Schema(description = "Questions and Groups")
val contents: List<GroupContentDto>
) : GroupContentDto {
companion object {
fun from(group: GroupEntity, contents: List<GroupContentDto>): CheckboxGroupDto {
return CheckboxGroupDto(
checkboxGroupId = group.groupUuid,
checkboxGroupCode = group.groupCode,
title = group.heading,
subheading = group.subheading,
helpText = group.helpText,
contents = contents
)
}
}
}
| 5
|
Kotlin
|
1
| 2
|
4a4460e335d1b893e1b80c8ce5afd85b89d0b7c4
| 1,335
|
hmpps-assessments-api
|
MIT License
|
client/src/main/java/ru/memebattle/feature/SemesterFragment.kt
|
Onotole1
| 242,397,687
| false
| null |
package ru.memebattle.feature
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_semester.*
import ru.memebattle.ARGS_SEMESTER
import ru.memebattle.R
import ru.memebattle.common.dto.user.SemesterDto
import ru.memebattle.common.dto.user.SemesterSubjectDto
class SemesterFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_semester, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val semester = arguments?.get(ARGS_SEMESTER) as SemesterDto
semesterName.text = semester.name
val mockSubjects = listOf(
SemesterSubjectDto(0, 70.0f, 0),
SemesterSubjectDto(1, 90.0f, 0),
SemesterSubjectDto(2, 70.0f, 0),
SemesterSubjectDto(3, 90.0f, 0),
SemesterSubjectDto(4, 70.0f, 0),
SemesterSubjectDto(5, 80.0f, 0),
SemesterSubjectDto(6, 80.0f, 0),
SemesterSubjectDto(7, 70.0f, 0),
SemesterSubjectDto(8, 90.0f, 0),
SemesterSubjectDto(9, 80.0f, 0)
)
recyclerViewSubjects?.adapter = SubjectsAdapter(mockSubjects)
}
}
| 0
|
Kotlin
|
0
| 3
|
fd2b1e526af65649b734810ef3bcdb9d4ea7539a
| 1,490
|
memebattle-template
|
Apache License 2.0
|
references/src/main/java/com/iniongungroup/mobile/android/references/fragments/BooksFragment.kt
|
IniongunIsaac
| 222,639,477
| false
| null |
package com.iniongungroup.mobile.android.references.fragments
import android.graphics.Typeface
import android.os.Bundle
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.Observer
import com.iniongun.tivbible.common.base.BaseFragment
import com.iniongun.tivbible.common.utils.liveDataEvent.LiveDataEventObserver
import com.iniongungroup.mobile.android.references.BR
import com.iniongungroup.mobile.android.references.R
import com.iniongungroup.mobile.android.references.ReferencesActivity
import com.iniongungroup.mobile.android.references.ReferencesViewModel
import com.iniongungroup.mobile.android.references.adapters.BooksAdapter
import com.iniongungroup.mobile.android.references.databinding.FragmentBooksBinding
import kotlinx.android.synthetic.main.fragment_books.*
class BooksFragment : BaseFragment<FragmentBooksBinding, ReferencesViewModel>() {
private val referencesViewModel by lazy { (requireActivity() as ReferencesActivity).referencesViewModel }
private lateinit var booksAdapter: BooksAdapter
private lateinit var fragmentBooksBinding: FragmentBooksBinding
override fun getViewModel() = referencesViewModel
override fun getLayoutId() = R.layout.fragment_books
override fun getBindingVariable() = BR.viewModel
override fun getLayoutBinding(binding: FragmentBooksBinding) {
fragmentBooksBinding = binding
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
booksAdapter = BooksAdapter(referencesViewModel)
setupBooksRecyclerView()
setOnClickListeners()
}
override fun setViewModelObservers() {
super.setViewModelObservers()
observeBooks()
observeShowChaptersFragment()
observeSettings()
}
private fun observeShowChaptersFragment() {
referencesViewModel.showChaptersFragment.observe(this, LiveDataEventObserver {
if (it) (requireActivity() as ReferencesActivity).setViewPagerItem(1)
})
}
private fun setOnClickListeners() {
fragmentBooksBinding.doneButton.setOnClickListener {
}
searchEditText.addTextChangedListener {
it?.toString()?.let { newText ->
referencesViewModel.filterBooks(newText)
}
}
}
private fun setupBooksRecyclerView() {
fragmentBooksBinding.booksRecyclerView.adapter = booksAdapter
}
private fun observeBooks() {
referencesViewModel.books.observe(this, Observer {
booksAdapter.submitList(it)
})
}
private fun observeSettings() {
referencesViewModel.settings.observe(this, Observer { setting ->
val typeface = Typeface.createFromAsset(activity!!.assets, "font/${setting.fontStyle.name}")
searchEditText.typeface = typeface
})
}
}
| 0
|
Kotlin
|
2
| 7
|
63da6ec716325a23b24d7071e53d5845ba56fa3c
| 2,897
|
Tiv-Bible
|
MIT License
|
src/main/kotlin/icu/windea/pls/script/structureView/ParadoxScriptFileTreeElement.kt
|
DragonKnightOfBreeze
| 328,104,626
| false
| null |
package icu.windea.pls.script.structureView
import com.intellij.ide.structureView.*
import com.intellij.ide.structureView.impl.common.*
import com.intellij.util.*
import icu.windea.pls.*
import icu.windea.pls.script.psi.*
import icu.windea.pls.util.*
class ParadoxScriptFileTreeElement(
element: ParadoxScriptFile
) : PsiTreeElementBase<ParadoxScriptFile>(element) {
override fun getChildrenBase(): Collection<StructureViewTreeElement> {
val element = element ?: return emptyList()
val rootBlock = element.block ?: return emptyList()
val result = SmartList<StructureViewTreeElement>()
rootBlock.forEachChild {
when {
it is ParadoxScriptVariable -> result.add(ParadoxScriptVariableTreeElement(it))
it is ParadoxScriptProperty -> result.add(ParadoxScriptPropertyTreeElement(it))
it is ParadoxScriptValue -> result.add(ParadoxScriptValueTreeElement(it))
}
}
return result
}
override fun getPresentableText(): String? {
val element = element ?: return null
return element.name
}
override fun getLocationString(): String? {
val element = element ?: return null
//如果文件名是descriptor.mod(不区分大小写),不显示定义信息
if(element.name.equals(descriptorFileName, true)) return null
val definitionInfo = element.definitionInfo ?: return null
val name = definitionInfo.name
val typesText = definitionInfo.typeText
//如果definitionName和rootKey相同,则省略definitionName
val builder = StringBuilder()
if(!name.equals(definitionInfo.rootKey, true)) {
builder.append(name)
}
builder.append(": ").append(typesText)
//如果存在,显示定义的本地化名字(最相关的本地化文本)
val primaryLocalisation = definitionInfo.resolvePrimaryLocalisation(element)
if(primaryLocalisation != null) {
val localizedName = ParadoxLocalisationTextRenderer.render(primaryLocalisation)
builder.append(" ").append(localizedName)
}
return builder.toString()
}
}
| 1
|
Kotlin
|
1
| 7
|
037b9b4ba467ed49ea221b99efb0a26cd630bb67
| 1,857
|
Paradox-Language-Support
|
MIT License
|
client/android/api-generator-test/src/test/java/com/yandex/generator/EntityWithOptionalStringEnumPropertyTest.kt
|
divkit
| 523,491,444
| false
|
{"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38}
|
package com.yandex.generator
import com.yandex.div.json.expressions.ExpressionResolver
import com.yandex.testing.EntityWithOptionalStringEnumProperty
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class EntityWithOptionalStringEnumPropertyTest {
private val case = EntityTestCase(
ctor = EntityWithOptionalStringEnumProperty.Companion::invoke
)
@Test
fun `property value is set`() {
val json = """{ "property": "second" }"""
val entity = case.parse(ASSERT_ENVIRONMENT, json)
assertEquals(EntityWithOptionalStringEnumProperty.Property.SECOND,
entity.property?.evaluate(ExpressionResolver.EMPTY))
}
@Test
fun `null property value`() {
val json = """{ }"""
val entity = case.parse(ASSERT_ENVIRONMENT, json)
assertNull(entity.property)
}
}
| 5
|
Kotlin
|
128
| 2,240
|
dd102394ed7b240ace9eaef9228567f98e54d9cf
| 1,008
|
divkit
|
Apache License 2.0
|
app/src/main/java/com/techlads/composetv/utils/extensions.kt
|
UmairKhalid786
| 586,631,597
| false
|
{"Kotlin": 158319}
|
package com.techlads.composetv.utils
import android.view.KeyEvent
import android.view.KeyEvent.KEYCODE_DPAD_CENTER
import android.view.KeyEvent.KEYCODE_DPAD_LEFT
import android.view.KeyEvent.KEYCODE_DPAD_RIGHT
import android.view.KeyEvent.KEYCODE_ENTER
import android.view.KeyEvent.KEYCODE_NUMPAD_ENTER
import android.view.KeyEvent.KEYCODE_SYSTEM_NAVIGATION_LEFT
import android.view.KeyEvent.KEYCODE_SYSTEM_NAVIGATION_RIGHT
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.onPreviewKeyEvent
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
fun <T> StateFlow<T>.toMutable() = this as MutableStateFlow
private val DPadEventsKeyCodes = listOf(
KEYCODE_DPAD_LEFT,
KEYCODE_SYSTEM_NAVIGATION_LEFT,
KEYCODE_DPAD_RIGHT,
KEYCODE_SYSTEM_NAVIGATION_RIGHT,
KEYCODE_DPAD_CENTER,
KEYCODE_ENTER,
KEYCODE_NUMPAD_ENTER
)
fun Modifier.handleDPadKeyEvents(
onLeft: (() -> Unit)? = null,
onRight: (() -> Unit)? = null,
onEnter: (() -> Unit)? = null
) = onPreviewKeyEvent {
fun onActionUp(block: () -> Unit) {
if (it.nativeKeyEvent.action == KeyEvent.ACTION_UP) block()
}
if (!DPadEventsKeyCodes.contains(it.nativeKeyEvent.keyCode)) return@onPreviewKeyEvent false
when (it.nativeKeyEvent.keyCode) {
KEYCODE_ENTER,
KEYCODE_DPAD_CENTER,
KEYCODE_NUMPAD_ENTER, -> {
onEnter?.apply {
onActionUp(::invoke)
return@onPreviewKeyEvent true
}
}
KEYCODE_DPAD_LEFT,
KEYCODE_SYSTEM_NAVIGATION_LEFT -> {
onLeft?.apply {
onActionUp(::invoke)
return@onPreviewKeyEvent true
}
}
KEYCODE_DPAD_RIGHT,
KEYCODE_SYSTEM_NAVIGATION_RIGHT -> {
onRight?.apply {
onActionUp(::invoke)
return@onPreviewKeyEvent true
}
}
}
false
}
| 7
|
Kotlin
|
17
| 95
|
d6d710c2ac9276a3a15c895a176afc78145d976b
| 1,970
|
ComposeTv
|
Apache License 2.0
|
app/src/main/java/com/berger/baseapp/data/di/EpisodesModule.kt
|
Shaikot35
| 612,941,885
| false
| null |
package com.berger.baseapp.data.di
import androidx.compose.runtime.Stable
import com.berger.baseapp.data.remote.api.EpisodesService
import com.berger.baseapp.data.remote.source.EpisodesRemoteDataSource
import com.berger.baseapp.data.remote.source.impl.EpisodesRemoteDataSourceImpl
import com.berger.baseapp.data.repository.EpisodesRepositoryImpl
import com.berger.baseapp.domain.repository.EpisodesRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import retrofit2.Retrofit
/**
* Created by merttoptas on 19.03.2022
*/
@Stable
@Module
@InstallIn(ViewModelComponent::class)
class EpisodesModule {
@Provides
fun provideEpisodesService(retrofit: Retrofit): EpisodesService =
retrofit.create(EpisodesService::class.java)
@Provides
fun provideEpisodesRemoteDataSource(episodesService: EpisodesService): EpisodesRemoteDataSource =
EpisodesRemoteDataSourceImpl(episodesService)
@Provides
fun provideEpisodesRepository(
episodesRemoteDataSource: EpisodesRemoteDataSource
): EpisodesRepository =
EpisodesRepositoryImpl(episodesRemoteDataSource)
}
| 0
|
Kotlin
|
0
| 0
|
448d02d0ca8334ac7dd72fccb751f5c44517aab4
| 1,194
|
BaseApp
|
Apache License 2.0
|
common/src/commonMain/kotlin/com.chrynan.chat/model/contact/PhoneNumber.kt
|
chRyNaN
| 206,982,352
| false
| null |
package com.chrynan.chat.model.contact
import com.chrynan.chat.model.core.ID
import com.chrynan.chat.model.core.Node
import com.chrynan.chat.model.core.TimeMoment
data class PhoneNumber(
override val id: ID,
val number: String,
val formattedNumber: String,
val name: String,
val type: String? = null,
val description: String? = null,
val lastUpdated: TimeMoment,
val range: InfoTimeRange? = null,
val note: String? = null
) : Node
| 0
|
Kotlin
|
0
| 3
|
8269e4bcecad6ba4ef10e211ca4cb52e1cdff4b8
| 468
|
Chat
|
Apache License 2.0
|
database/src/main/java/ru/merkulyevsasha/database/dao/ArticleCommentsDao.kt
|
sashamerkulev
| 72,357,607
| false
|
{"Gradle": 13, "HTML": 2, "Java Properties": 3, "YAML": 1, "Shell": 2, "Ignore List": 8, "Batchfile": 1, "Text": 1, "Markdown": 1, "Proguard": 7, "Java": 13, "XML": 46, "Kotlin": 113}
|
package ru.merkulyevsasha.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import io.reactivex.Single
import ru.merkulyevsasha.database.entities.ArticleCommentEntity
@Dao
interface ArticleCommentsDao {
@Query("select * from comments where articleId = :articleId order by pubDate desc")
fun getArticleComments(articleId: Int): Single<List<ArticleCommentEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertOrUpdate(items: List<ArticleCommentEntity>)
@Update
fun update(item: ArticleCommentEntity)
@Query("update articles set usersCommentCount = usersCommentCount + :commentsCount, isUserCommented = 1 where articleId = :articleId")
fun updateArticle(articleId: Int, commentsCount: Int)
@Transaction
fun updateArticleComment(comment: ArticleCommentEntity, commentsCount: Int) {
update(comment)
updateArticle(comment.articleId, commentsCount)
}
}
| 1
| null |
1
| 1
|
fc8ab8149c34bbda3cce9a7002d203ff62f52bd6
| 1,071
|
news
|
Apache License 2.0
|
metrics/core/src/main/kotlin/io/wavebeans/metrics/Metrics.kt
|
WaveBeans
| 174,378,458
| false
|
{"Kotlin": 1263856, "Shell": 6924, "Dockerfile": 408}
|
package io.wavebeans.metrics
const val tableTag = "table"
const val bitDepthTag = "bitDepth"
const val formatTag = "format"
const val limitTag = "limit"
const val offsetTag = "offset"
const val clazzTag = "class"
const val typeTag = "type"
val audioStreamRequestMetric = MetricObject.counter(
"io.wavebeans.http.audioService.stream",
"requestCount",
"Counts the number of requests for streaming on Audio Service.",
tableTag, bitDepthTag, formatTag, limitTag, offsetTag
)
val audioStreamRequestTimeMetric = MetricObject.time(
"io.wavebeans.http.audioService.stream",
"requestTime",
"Measures the time taken to handle the incoming request and start streaming on Audio Service.",
tableTag, bitDepthTag, formatTag, limitTag, offsetTag
)
val audioStreamBytesSentMetric = MetricObject.counter(
"io.wavebeans.http.audioService.stream",
"bytesSent",
"Counts the number of bytes sent during stream on Audio Service",
tableTag, bitDepthTag, formatTag, limitTag, offsetTag
)
val samplesProcessedOnOutputMetric = MetricObject.counter(
"io.wavebeans.lib.output",
"samplesProcessed",
"Counts the number of samples processed by the output",
clazzTag
)
val samplesSkippedOnOutputMetric = MetricObject.counter(
"io.wavebeans.lib.output",
"samplesSkipped",
"Counts the number of samples skipped by the output, i.e. due to the gate closed and so on",
clazzTag
)
val samplesProcessedOnInputMetric = MetricObject.counter(
"io.wavebeans.lib.input",
"samplesProcessed",
"Counts the number of samples processed by the input",
clazzTag, typeTag
)
val flushedOnOutputMetric = MetricObject.counter(
"io.wavebeans.lib.output",
"flushed",
"Counts the number of times the output was flushed if applicable",
clazzTag
)
val gateStateOnOutputMetric = MetricObject.gauge(
"io.wavebeans.lib.output",
"gate.state",
"Reflects the state of the gate of the specific output, 0 is closed, 1 is opened",
clazzTag
)
val bytesProcessedOnOutputMetric = MetricObject.counter(
"io.wavebeans.lib.output",
"bytesProcessed",
"Counts the number of bytes processed by the output",
clazzTag
)
val outputStateMetric = MetricObject.gauge(
"io.wavebeans.lib.output",
"state",
"Reflects the state of the specific output, 0 is closed, 1 is opened",
clazzTag
)
| 26
|
Kotlin
|
0
| 21
|
2a0eb6b481f0f848a7e66f7cb4c395ddb47952d1
| 2,532
|
wavebeans
|
Apache License 2.0
|
app/src/main/java/com/skt/nugu/sampleapp/player/SamplePlayerFactory.kt
|
nugu-developers
| 214,067,023
| false
| null |
/**
* Copyright (c) 2020 SK Telecom Co., Ltd. All rights reserved.
*
* 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.skt.nugu.sampleapp.player
import android.content.Context
import android.media.AudioManager
import android.media.MediaPlayer
import com.skt.nugu.sampleapp.player.exo.ExoMediaPlayer
import com.skt.nugu.sdk.agent.mediaplayer.PlayerFactory
import com.skt.nugu.sdk.agent.mediaplayer.UriSourcePlayablePlayer
import com.skt.nugu.sdk.external.silvertray.NuguOpusPlayer
import com.skt.nugu.sdk.platform.android.mediaplayer.AndroidMediaPlayer
import com.skt.nugu.sdk.platform.android.mediaplayer.IntegratedMediaPlayer
class SamplePlayerFactory constructor(
private val context: Context,
private val useExoPlayer: Boolean
) : PlayerFactory {
override fun createAlertsPlayer() = IntegratedMediaPlayer(
createPlayer(),
NuguOpusPlayer(AudioManager.STREAM_MUSIC)
)
override fun createAudioPlayer() = IntegratedMediaPlayer(
createPlayer(),
NuguOpusPlayer(AudioManager.STREAM_MUSIC)
)
override fun createSpeakPlayer() = IntegratedMediaPlayer(
createPlayer(),
NuguOpusPlayer(AudioManager.STREAM_MUSIC)
)
override fun createBeepPlayer() = createPlayer()
private fun createPlayer(): UriSourcePlayablePlayer {
return if (useExoPlayer) {
ExoMediaPlayer(context)
} else {
AndroidMediaPlayer(context, MediaPlayer())
}
}
}
| 3
| null |
18
| 27
|
53ebf6b8b17afeff6fdb3a8741f345f2fbe0d649
| 1,984
|
nugu-android
|
Apache License 2.0
|
src/jvmMain/kotlin/baaahs/geom/Matrix4FJvm.kt
|
baaahs
| 174,897,412
| false
|
{"Kotlin": 4817815, "C": 1529197, "C++": 661363, "GLSL": 412779, "JavaScript": 61944, "HTML": 56277, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450}
|
package baaahs.geom
import kotlinx.serialization.Serializable
import org.joml.Matrix4f as NativeMatrix4F
import org.joml.Matrix4fc as NativeMatrix4FC
import org.joml.Quaternionf as NativeQuaternionF
import org.joml.Vector3f as NativeVector3F
@Serializable(Matrix4FSerializer::class)
actual class Matrix4F(private val nativeMatrix: NativeMatrix4FC) {
actual constructor(elements: FloatArray?) : this(
NativeMatrix4F().also { if (elements != null) it.set(elements) }
)
actual val elements: FloatArray
get() = nativeMatrix.get(FloatArray(16))
actual val position: Vector3F
get() = nativeMatrix.getTranslation(NativeVector3F()).toVector3F()
actual val translation: Vector3F
get() = position
actual val rotation: EulerAngle
get() = NativeQuaternionF().setFromUnnormalized(nativeMatrix)
.getEulerAnglesXYZ(NativeVector3F())
.toEulerAngle()
actual val scale: Vector3F
get() = nativeMatrix.getScale(NativeVector3F()).toVector3F()
actual operator fun times(matrix: Matrix4F): Matrix4F {
val dest = NativeMatrix4F()
nativeMatrix.mul(matrix.nativeMatrix, dest)
return Matrix4F(dest)
}
actual fun transform(vector: Vector3F): Vector3F {
return vector.toNativeVector3F().mulProject(nativeMatrix).toVector3F()
}
actual fun withTranslation(translation: Vector3F): Matrix4F {
return Matrix4F(
NativeMatrix4F(nativeMatrix).translation(translation.x, translation.y, translation.z)
)
}
actual fun withRotation(rotation: EulerAngle): Matrix4F {
return Matrix4F(
NativeMatrix4F(nativeMatrix).rotationXYZ(
rotation.xRad.toFloat(), rotation.yRad.toFloat(), rotation.zRad.toFloat()
)
)
}
actual fun withScale(scale: Vector3F): Matrix4F {
return Matrix4F(
NativeMatrix4F(nativeMatrix).scaling(translation.x, translation.y, translation.z)
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Matrix4F) return false
return nativeMatrix == other.nativeMatrix
}
override fun hashCode(): Int {
return nativeMatrix.hashCode()
}
actual fun inverse(): Matrix4F {
// Ensure the matrix is invertible (determinant != 0)
val det = determinant()
require(det != 0.0f) { "Matrix is not invertible (determinant is zero)" }
val invElements = FloatArray(16)
val m = elements
// Inverse calculation logic here...
// This code snippet assumes a row-major order for the matrix elements.
// For a 4x4 matrix, you'll have to compute the cofactor matrix,
// and then divide by the determinant.
// Compute the cofactors and fill in invElements accordingly
invElements[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] +
m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10]
invElements[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] -
m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10]
invElements[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] +
m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6]
invElements[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] -
m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6]
invElements[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] -
m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10]
invElements[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] +
m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10]
invElements[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] -
m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6]
invElements[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] +
m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6]
invElements[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] +
m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9]
invElements[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] -
m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9]
invElements[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] +
m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5]
invElements[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] -
m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5]
invElements[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] -
m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9]
invElements[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] +
m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9]
invElements[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] -
m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5]
invElements[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] +
m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5]
// Continue filling in invElements with the correct cofactors...
// Finally, divide each element by the determinant
for (i in invElements.indices) {
invElements[i] /= det
}
return Matrix4F(invElements)
}
actual fun determinant(): Float {
// Calculate the determinant of the 4x4 matrix
// For a 4x4 matrix in elements[], the determinant calculation will be extensive.
// Example:
return elements[0] * (
elements[5] * (elements[10] * elements[15] - elements[11] * elements[14]) -
elements[9] * (elements[6] * elements[15] - elements[7] * elements[14]) +
elements[13] * (elements[6] * elements[11] - elements[7] * elements[10])
) -
elements[4] * (
elements[1] * (elements[10] * elements[15] - elements[11] * elements[14]) -
elements[9] * (elements[2] * elements[15] - elements[3] * elements[14]) +
elements[13] * (elements[2] * elements[11] - elements[3] * elements[10])
) +
elements[8] * (
elements[1] * (elements[6] * elements[15] - elements[7] * elements[14]) -
elements[5] * (elements[2] * elements[15] - elements[3] * elements[14]) +
elements[13] * (elements[2] * elements[7] - elements[3] * elements[6])
) -
elements[12] * (
elements[1] * (elements[6] * elements[11] - elements[7] * elements[10]) -
elements[5] * (elements[2] * elements[11] - elements[3] * elements[10]) +
elements[9] * (elements[2] * elements[7] - elements[3] * elements[6])
)
}
}
actual fun matrix4F_compose(position: Vector3F, rotation: EulerAngle, scale: Vector3F): Matrix4F =
Matrix4F(
NativeMatrix4F().apply {
translationRotateScale(
position.toNativeVector3F(),
//NativeQuaternionF().rotateXYZ(
// rotation.xRad.toFloat(), rotation.yRad.toFloat(), rotation.zRad.toFloat()
//),
NativeQuaternionF().rotateZYX(
rotation.zRad.toFloat(), rotation.yRad.toFloat(), rotation.xRad.toFloat()
),
scale.toNativeVector3F()
)
}
)
private fun Vector3F.toNativeVector3F() =
NativeVector3F(x, y, z)
private fun org.joml.Vector3f.toVector3F() =
Vector3F(x, y, z)
private fun org.joml.Vector3f.toEulerAngle() =
EulerAngle(this[0].toDouble(), this[1].toDouble(), this[2].toDouble())
| 111
|
Kotlin
|
13
| 40
|
77ad22b042fc0ac440410619dd27b468c3b3a600
| 8,326
|
sparklemotion
|
MIT License
|
src/main/kotlin/org/rust/ide/actions/ToggleExternalLinterOnTheFlyAction.kt
|
intellij-rust
| 42,619,487
| false
|
{"Gradle Kotlin DSL": 2, "Java Properties": 5, "Markdown": 11, "TOML": 19, "Shell": 2, "Text": 124, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "XML": 140, "Kotlin": 2284, "INI": 3, "ANTLR": 1, "Rust": 362, "YAML": 131, "RenderScript": 1, "JSON": 6, "HTML": 198, "SVG": 136, "JFlex": 1, "Java": 1, "Python": 37}
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import org.rust.cargo.project.settings.rustSettings
class ToggleExternalLinterOnTheFlyAction : ToggleAction() {
override fun isSelected(e: AnActionEvent): Boolean {
val project = e.project ?: return false
return project.rustSettings.runExternalLinterOnTheFly
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
val project = e.project ?: return
project.rustSettings.modify { it.runExternalLinterOnTheFly = state }
}
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
super.update(e)
val externalLinterName = e.project?.rustSettings?.externalLinter?.title ?: "External Linter"
e.presentation.text = "Run $externalLinterName on the Fly"
}
}
| 1,841
|
Kotlin
|
380
| 4,528
|
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
| 1,117
|
intellij-rust
|
MIT License
|
app/src/main/java/com/arturostrowski/quiz/app/ui/chat/interactor/ChatMVPInteractor.kt
|
Mesti193
| 215,134,193
| false
| null |
package com.arturostrowski.quiz.app.ui.chat.interactor
import com.arturostrowski.quiz.app.data.database.repository.user.User
import com.arturostrowski.quiz.app.data.network.request.GetChatRequest
import com.arturostrowski.quiz.app.data.network.response.GetChatResponse
import com.arturostrowski.quiz.app.ui.base.interactor.MVPInteractor
import io.reactivex.Observable
interface ChatMVPInteractor : MVPInteractor {
fun getChats(request: GetChatRequest): Observable<GetChatResponse>
fun loadUser(): Observable<List<User>>
}
| 0
|
Kotlin
|
0
| 0
|
1c0cef0108b0b90a4074f18b4690e5533214b41c
| 533
|
QuizApp
|
Apache License 2.0
|
kondor-examples/src/main/kotlin/Http4kHelpers.kt
|
uberto
| 343,412,601
| false
|
{"Kotlin": 342010, "Java": 46239, "Shell": 922}
|
import com.ubertob.kondor.json.JConverter
import org.http4k.asString
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.ContentType.Companion.APPLICATION_JSON
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.lens.BiDiBodyLens
import org.http4k.lens.ContentNegotiation
import org.http4k.lens.Meta
import org.http4k.lens.httpBodyRoot
private val contentTypeHeaderName = "Content-Type"
fun Request.contentType(contentType: ContentType) =
header(contentTypeHeaderName, contentType.toHeaderValue())
// for http clients
fun <T : Any> Request.bodyAsJson(converter: JConverter<T>, value: T) =
body(converter.toJson(value)).contentType(APPLICATION_JSON)
fun <T : Any> Response.parseJsonBody(converter: JConverter<T>): T =
converter.fromJson(bodyString()).orThrow()
//for http servers
fun <T : Any> Request.parseJsonBody(converter: JConverter<T>): T =
converter.fromJson(bodyString()).orThrow()
fun <T : Any> Response.bodyAsJson(converter: JConverter<T>, value: T) =
body(converter.toJson(value)).header(contentTypeHeaderName, APPLICATION_JSON.toHeaderValue())
fun <T : Any> JConverter<T>.toBodyLens(vararg metas: Meta): BiDiBodyLens<T> =
httpBodyRoot(metas.toList(), APPLICATION_JSON, ContentNegotiation.None)
.map({ fromJson(it.payload.asString()).orThrow() }, { Body(toJson(it)) })
.toLens()
| 1
|
Kotlin
|
14
| 81
|
b186b1693d422c9ac9a4c70beb30403d7ede80c3
| 1,404
|
kondor-json
|
Apache License 2.0
|
src/main/kotlin/io/fdeitylink/util/fx/FileEditTab.kt
|
fdeitylink
| 96,371,360
| false
| null |
/*
* Copyright 2017 <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.
*/
/*
* TODO:
* protected fun rename(p: Path)?
* Store undo pointer to call markUnchanged() on undo()/redo() if the same state as when save() was called is met
* Create abstract class representing a savable object and use that rather than Path and delegating save() to subclasses?
* Handle tabs that have a '*' in their name not as a marker of changes (is this already handled?)
*/
package io.fdeitylink.util.fx
import java.util.ArrayDeque
import java.nio.file.Path
import java.nio.file.Files
import javafx.scene.Node
import javafx.event.Event
import javafx.event.EventHandler
import javafx.scene.control.ButtonType
import javafx.scene.control.Tab
import javafx.scene.control.Tooltip
abstract class FileEditTab
@JvmOverloads protected constructor(path: Path, text: String? = null, content: Node? = null) : Tab(text, content) {
//https://xkcd.com/853/
private val undoQueue = ArrayDeque<UndoableEdit>()
private val redoQueue = ArrayDeque<UndoableEdit>()
val path: Path = path.toAbsolutePath()
/*
* Modifying isChanged is done via markChanged() and markUnchanged().
* This is so that subclasses can increase the visibility of the
* setter methods as needed, independently of one another. If the
* visibility of only one method needs to be changed, that can be
* done so other classes cannot arbitrarily change the boolean.
*/
var isChanged = false
private set
init {
require(Files.isRegularFile(path)) { "${this.path} is not a file" }
id = this.path.toString()
tooltip = Tooltip(this.path.toString())
onCloseRequest = EventHandler<Event> { event ->
if (isChanged) {
val alert = createAlert(title = this.text?.substring(0, this.text.lastIndexOf('*')),
message = "This tab has unsaved changes. Save before closing?")
alert.buttonTypes.addAll(ButtonType.YES, ButtonType.NO, ButtonType.CANCEL)
alert.showAndWait().ifPresent {
if (ButtonType.YES == it) {
save()
}
else if (ButtonType.CANCEL == it) {
event!!.consume()
}
}
}
}
}
open fun undo() {
if (!undoQueue.isEmpty()) {
markChanged()
val edit = undoQueue.removeFirst()
redoQueue.addFirst(edit)
edit.undo()
}
}
open fun redo() {
if (!redoQueue.isEmpty()) {
markChanged()
val edit = redoQueue.removeFirst()
undoQueue.addFirst(edit)
edit.redo()
}
}
abstract fun save()
protected open fun markChanged() {
if (!isChanged) {
isChanged = true
if (!text.endsWith("*")) {
text += '*'
}
}
}
protected open fun markUnchanged() {
if (isChanged) {
isChanged = false
if (text.endsWith("*")) {
text = text.substring(0, text.lastIndexOf("*"))
}
}
}
protected fun addUndo(edit: UndoableEdit) {
markChanged()
redoQueue.clear()
undoQueue.addFirst(edit)
}
}
| 0
|
Kotlin
|
1
| 2
|
a33c53f89d1a4e6c8c0f91fedb8445c09f761b70
| 3,896
|
kotlin-utils
|
Apache License 2.0
|
bitgouel-domain/src/main/kotlin/team/msg/domain/lecture/repository/custom/impl/CustomLectureRepositoryImpl.kt
|
School-of-Company
| 700,741,727
| false
| null |
package team.msg.domain.lecture.repository.custom.impl
import com.querydsl.core.types.dsl.BooleanExpression
import com.querydsl.jpa.impl.JPAQueryFactory
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Component
import team.msg.domain.lecture.model.QLecture.lecture
import team.msg.domain.lecture.model.QRegisteredLecture.registeredLecture
import team.msg.domain.lecture.repository.custom.CustomLectureRepository
import team.msg.domain.lecture.repository.custom.projection.LectureListProjection
import team.msg.domain.lecture.repository.custom.projection.QLectureListProjection
import java.util.*
import java.util.Objects.isNull
@Component
class CustomLectureRepositoryImpl(
private val queryFactory: JPAQueryFactory
) : CustomLectureRepository {
override fun findAllByLectureType(pageable: Pageable, lectureType: String?): Page<LectureListProjection> {
val content = queryFactory.select(
QLectureListProjection(
lecture,
registeredLecture.count()
)
).from(lecture)
.leftJoin(registeredLecture).on(lecture.eq(registeredLecture.lecture))
.where(
eqLectureType(lectureType)
)
.groupBy(lecture)
.offset(pageable.offset)
.limit(pageable.pageSize.toLong())
.fetch()
val count = queryFactory
.select(lecture.count())
.from(lecture)
.where(
eqLectureType(lectureType)
).fetchOne()!!
return PageImpl(content, pageable, count)
}
override fun deleteAllByUserId(userId: UUID) {
queryFactory.delete(lecture)
.where(lecture.user.id.eq(userId))
.execute()
}
override fun findAllLineByDivision(division: String, keyword: String?): List<String> =
queryFactory
.select(lecture.line)
.from(lecture)
.where(
lecture.division.contains(division),
eqLine(keyword)
)
.fetch()
.distinct()
override fun findAllDepartment(keyword: String?): List<String> =
queryFactory
.select(lecture.department)
.from(lecture)
.where(eqDepartment(keyword))
.fetch()
.distinct()
override fun findAllDivisions(keyword: String?): List<String> =
queryFactory
.select(lecture.division)
.from(lecture)
.where(eqDivision(keyword))
.fetch()
.distinct()
private fun eqLectureType(lectureType: String?): BooleanExpression? =
if(isNull(lectureType)) null else lecture.lectureType.contains(lectureType)
private fun eqLine(keyword: String?): BooleanExpression? =
if(keyword.isNullOrBlank()) null else lecture.line.contains(keyword)
private fun eqDepartment(keyword: String?): BooleanExpression? =
if(keyword.isNullOrBlank()) null else lecture.department.contains(keyword)
private fun eqDivision(keyword: String?): BooleanExpression? =
if(keyword.isNullOrBlank()) null else lecture.division.contains(keyword)
}
| 4
| null |
0
| 17
|
90d788c3e7393290e0f09860af78aebc084ef571
| 3,306
|
Bitgouel-Server
|
MIT License
|
bootstrap/src/main/kotlin/net/dontdrinkandroot/wicket/bootstrap/css/Breakpoint.kt
|
dontdrinkandroot
| 7,002,436
| false
| null |
package net.dontdrinkandroot.wicket.bootstrap.css
import net.dontdrinkandroot.wicket.css.CssClass
enum class Breakpoint(override val classString: String) : CssClass {
SMALL("sm"),
MEDIUM("md"),
LARGE("lg"),
EXTRA_LARGE("xl"),
EXTRA_EXTRA_LARGE("xxl");
}
| 34
|
Kotlin
|
1
| 3
|
eaf007cfe70a136a334bd9cb22b5cc0e2fa50ff3
| 275
|
wicket.java
|
Apache License 2.0
|
src/ko/navercomic/src/eu/kanade/tachiyomi/extension/ko/navercomic/NaverComic.kt
|
mangacat
| 190,679,694
| true
|
{"Kotlin": 1307203, "Java": 4615, "Shell": 1729}
|
package eu.kanade.tachiyomi.extension.ko.navercomic
import android.annotation.SuppressLint
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import okhttp3.Request
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
class NaverWebtoon : NaverComicBase("webtoon") {
override val name = "Naver Webtoon"
override fun popularMangaRequest(page: Int) = GET("$baseUrl/$mType/weekday.nhn")
override fun popularMangaSelector() = ".list_area.daily_all .col ul > li"
override fun popularMangaNextPageSelector() = null
override fun popularMangaFromElement(element: Element): SManga {
val thumb = element.select("div.thumb img").first().attr("src")
val title = element.select("a.title").first()
val manga = SManga.create()
manga.url = title.attr("href").substringBefore("&week")
manga.title = title.text().trim()
manga.thumbnail_url = thumb
return manga
}
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/$mType/weekday.nhn?order=Update")
override fun latestUpdatesSelector() = ".list_area.daily_all .col.col_selected ul > li"
override fun latestUpdatesNextPageSelector() = null
override fun latestUpdatesFromElement(element: Element) = popularMangaFromElement(element)
}
class NaverBestChallenge : NaverComicChallengeBase("bestChallenge") {
override val name = "Naver Webtoon Best Challenge"
override fun popularMangaRequest(page: Int) = GET("$baseUrl/genre/$mType.nhn")
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/genre/$mType.nhn?m=main&order=Update")
}
class NaverChallenge : NaverComicChallengeBase("challenge") {
override val name = "Naver Webtoon Challenge"
override fun popularMangaRequest(page: Int) = GET("$baseUrl/genre/$mType.nhn")
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/genre/$mType.nhn?m=list&order=Update")
// Need to override again because there's no mobile page.
override fun chapterPagedListRequest(manga: SManga, page: Int): Request {
return GET("$baseUrl${manga.url}&page=$page")
}
override fun chapterListSelector() = ".viewList > tbody > tr:not([class])"
override fun chapterFromElement(element: Element): SChapter {
val nameElement = element.select("td.title > a").first()
val rawName = nameElement.text().trim()
val chapter = SChapter.create()
chapter.url = nameElement.attr("src")
chapter.chapter_number = parseChapterNumber(rawName)
chapter.name = rawName
chapter.date_upload = parseChapterDate(element.select("td.num").last().text().trim())
return chapter
}
@SuppressLint("SimpleDateFormat")
private fun parseChapterDate(date: String): Long {
return try {
SimpleDateFormat("yyyy.MM.dd").parse(date).time
} catch (e: Exception) {
e.printStackTrace()
0
}
}
}
| 0
|
Kotlin
|
0
| 2
|
1d538bb2fec19417c69c0799526469fb7799e33e
| 3,020
|
tachiyomi-extensions
|
Apache License 2.0
|
app/src/main/java/com/apps/nabungemas/ui/theme/Theme.kt
|
artfath
| 482,567,125
| false
|
{"Kotlin": 113363}
|
package com.kj_bagwatgeeta.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Yellow200,
primaryVariant = Yellow700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Yellow500,
primaryVariant = Yellow700,
secondary = Teal200
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun Jetpack_compose_practiceTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
| 0
|
Kotlin
|
0
| 2
|
a7a4f9644ccdfd06e9548e83187dc01ea25293f1
| 1,129
|
Nabung-Emas-App
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonersearch/resource/RestrictedPatientSearchResource.kt
|
ministryofjustice
| 256,501,813
| false
| null |
package uk.gov.justice.digital.hmpps.prisonersearch.search.resource
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.tags.Tag
import org.springdoc.core.annotations.ParameterObject
import org.springframework.data.domain.Pageable
import org.springframework.data.web.PageableDefault
import org.springframework.http.MediaType
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import uk.gov.justice.digital.hmpps.prisonersearch.search.services.RestrictedPatientSearchCriteria
import uk.gov.justice.digital.hmpps.prisonersearch.search.services.RestrictedPatientSearchService
@RestController
@Validated
@PreAuthorize("hasAnyRole('ROLE_GLOBAL_SEARCH', 'ROLE_PRISONER_SEARCH')")
@RequestMapping(
"/restricted-patient-search",
produces = [MediaType.APPLICATION_JSON_VALUE],
consumes = [MediaType.APPLICATION_JSON_VALUE],
)
class RestrictedPatientSearchResource(private val restrictedPatientSearchService: RestrictedPatientSearchService) {
@PostMapping("/match-restricted-patients")
@Operation(summary = "Match prisoners by criteria", description = "Requires ROLE_GLOBAL_SEARCH or ROLE_PRISONER_SEARCH role")
@Tag(name = "Specific use case")
fun findByCriteria(
@Parameter(required = true) @RequestBody searchCriteria: RestrictedPatientSearchCriteria,
@ParameterObject @PageableDefault
pageable: Pageable,
) =
restrictedPatientSearchService.findBySearchCriteria(searchCriteria, pageable)
}
| 3
|
Kotlin
|
3
| 5
|
46816e4d23e9c201740d05df2c6d21fd21ee3bad
| 1,811
|
prisoner-offender-search
|
MIT License
|
app/src/main/java/com/near/android/charg2earn/ui/home/compose/NFTCollection.kt
|
ebatteSZ
| 567,559,700
| false
|
{"Kotlin": 276355, "Rust": 10522}
|
package com.near.android.charg2earn.ui.home.compose
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import com.near.android.charg2earn.base.composeui.*
import com.near.android.charg2earn.ui.compose.theme.Black_item_subtitle
import com.near.android.charg2earn.ui.compose.theme.Black_item_title
import com.near.android.charg2earn.ui.compose.theme.GreenColor
import com.near.android.charg2earn.ui.compose.theme.RaffleColor
import com.near.android.charg2earn.R
@Composable
fun NFTCollection(
modifier: Modifier = Modifier,
onClickRaffle: () -> Unit,
onClickMint: () -> Unit
) {
ConstraintLayout(modifier = modifier.fillMaxWidth()) {
val (name, priceTitle, price, bottom) = createRefs()
Text(
text = stringResource(R.string.nft_collection),
fontSize = nameFontSize,
style = textStyleBold,
color = Black_item_title,
modifier = Modifier.constrainAs(name) {
start.linkTo(parent.start)
top.linkTo(parent.top)
}
)
Text(
text = stringResource(R.string.nft_price),
fontSize = NftPriceSize,
style = textStyleMedium,
color = Black_item_subtitle,
modifier = Modifier.constrainAs(priceTitle) {
end.linkTo(parent.end)
top.linkTo(name.top)
}
)
Text(
text = "=$0.001",
fontSize = NftPriceSize,
style = textStyleMedium,
color = Black_item_subtitle,
modifier = Modifier.constrainAs(price) {
end.linkTo(parent.end)
top.linkTo(priceTitle.bottom)
}
)
Row(
Modifier
.padding(top = BtnVertical)
.fillMaxWidth()
.constrainAs(bottom) {
top.linkTo(name.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
},
verticalAlignment = Alignment.CenterVertically
) {
NFTBottom(
onClick = { onClickRaffle() },
modifier = Modifier
.height(BtnHeight)
.width(BtnWidth),
colors = ButtonDefaults.buttonColors(GreenColor)
) {
Text(
text = stringResource(R.string.title_home_raffle),
fontSize = BtnRaffleSize,
style = textStyleBold,
color = Black_item_title,
)
}
Box(modifier = Modifier.width(DividerWidth))
NFTBottom(
onClick = { onClickMint() },
modifier = Modifier
.height(BtnHeight)
.width(BtnWidth),
colors = ButtonDefaults.buttonColors(RaffleColor)
) {
Text(
text = stringResource(R.string.testing_mint),
fontSize = BtnRaffleSize,
style = textStyleBold,
color = Color.White,
)
}
}
}
}
@Composable
fun NFTBottom(
onClick: () -> Unit,
modifier: Modifier = Modifier,
colors: ButtonColors = ButtonDefaults.buttonColors(),
content: @Composable RowScope.() -> Unit
) {
Button(
onClick = { onClick() },
modifier = modifier,
shape = MRoundedShape,
elevation = ButtonDefaults.buttonElevation(1.dp),
contentPadding = PaddingValues(0.dp),
colors = colors
) {
content()
}
}
private val nameFontSize = 18.sp
private val NftPriceSize = 10.sp
private val BtnRaffleSize = 16.sp
private val BtnHeight = 58.dp
private val BtnWidth = 158.dp
private val BtnVertical = 18.dp
private val DividerWidth = 19.dp
| 0
|
Kotlin
|
0
| 0
|
79bebc1672acde9519d4bf1fcbb93cfb2963dd33
| 4,391
|
near_charge2earn_demo
|
MIT License
|
app/src/main/java/com/myscript/iink/app/mathpad/MainActivity.kt
|
jingkecn
| 181,008,191
| false
| null |
/*
* Copyright (c) MyScript. All rights reserved.
*/
package com.myscript.iink.app.mathpad
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.myscript.iink.*
import com.myscript.iink.extensions.convert
import com.myscript.iink.extensions.copyToClipboard
import com.myscript.iink.uireferenceimplementation.EditorView
import com.myscript.iink.uireferenceimplementation.FontUtils
import com.myscript.iink.uireferenceimplementation.InputController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity(), IEditorListener {
private lateinit var contentPart: ContentPart
private lateinit var editorView: EditorView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
(application as? MyApplication)?.contentPackage?.let { initWith(it) }
editorView = findViewById<EditorView>(R.id.editor_view).also { initWith(it) }
}
private fun initWith(contentPackage: ContentPackage) = with(contentPackage) {
createPart("Math").let { contentPart = it }
}
private fun initWith(view: EditorView) = with(view) {
(application as? IInteractiveInkApplication)?.engine?.let {
setEngine(it)
editor?.addListener(this@MainActivity)
inputMode = InputController.INPUT_MODE_FORCE_PEN
setTypefaces(FontUtils.loadFontsFromAssets(applicationContext.assets))
post {
editor?.part = contentPart
visibility = View.VISIBLE
}
}
}
override fun onDestroy() {
editorView.close()
contentPart.close()
super.onDestroy()
}
// region Implementations (options menu)
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.activity_main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
menu?.let {
editorView.editor?.run {
it.findItem(R.id.menu_clear)?.isEnabled = part?.isClosed == false
it.findItem(R.id.menu_redo)?.isEnabled = canRedo()
it.findItem(R.id.menu_undo)?.isEnabled = canUndo()
}
}
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
editorView.editor?.let {
// wait for the editor to be idle.
if (!it.isIdle) it.waitForIdle()
when (item?.itemId) {
R.id.menu_clear -> it.clear()
R.id.menu_convert -> it.convert()
R.id.menu_redo -> it.redo()
R.id.menu_undo -> it.undo()
R.id.menu_export_latex -> it.copyToClipboard(this, MimeType.LATEX)
R.id.menu_export_math_ml -> it.copyToClipboard(this, MimeType.MATHML)
else -> return@let
}
}
return super.onOptionsItemSelected(item)
}
// endregion
// region Implementations (IEditorListener)
override fun contentChanged(editor: Editor?, blockIds: Array<out String>?) {
invalidateOptionsMenu()
}
override fun partChanging(editor: Editor?, old: ContentPart?, new: ContentPart?) {
invalidateOptionsMenu()
}
override fun partChanged(editor: Editor?) {
invalidateOptionsMenu()
}
override fun onError(editor: Editor?, blockId: String?, message: String?) {
GlobalScope.launch(Dispatchers.Main) {
Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show()
}
}
// endregion
}
| 1
| null |
3
| 16
|
1897040d46ef84df77d265dba5dc8437babfb486
| 3,888
|
interactive-math-pad-android
|
MIT License
|
app/src/main/java/com/thezayin/chatbottesting/domain/model/Message.kt
|
thezayin
| 770,338,666
| false
|
{"Kotlin": 21702}
|
package com.thezayin.chatbottesting.domain.model
data class Message(
val sender:String?,
val cnt: String
)
| 0
|
Kotlin
|
0
| 1
|
ff1b19a7cc8bd640116f2d857a0cd538430886b1
| 115
|
Brainshop-chatbot-app
|
MIT License
|
src/main/kotlin/net/illuc/kontraption/container/IonThrusterEnergyContainer.kt
|
illucc
| 692,191,268
| false
|
{"Kotlin": 106933, "Java": 31921}
|
package net.illuc.kontraption.container
import mekanism.api.AutomationType
import mekanism.api.IContentsListener
import mekanism.api.NBTConstants
import mekanism.api.math.FloatingLong
import mekanism.common.capabilities.energy.MachineEnergyContainer
import mekanism.common.util.NBTUtils
import net.illuc.kontraption.blockEntities.TileEntityIonThruster
import net.minecraft.nbt.CompoundTag
import java.util.function.Predicate
class IonThrusterEnergyContainer private constructor(maxEnergy: FloatingLong, energyPerTick: FloatingLong, canExtract: Predicate<AutomationType>,
canInsert: Predicate<AutomationType>, tile: TileEntityIonThruster, listener: IContentsListener?) : MachineEnergyContainer<TileEntityIonThruster?>(maxEnergy, energyPerTick, canExtract, canInsert, tile, listener) {
override fun adjustableRates(): Boolean {
return true
}
fun updateEnergyUsage(energyUsage: FloatingLong) {
currentEnergyPerTick = energyUsage
maxEnergy = energyUsage.multiply(400)
}
override fun serializeNBT(): CompoundTag {
val nbt = super.serializeNBT()
nbt.putString(NBTConstants.ENERGY_USAGE, energyPerTick.toString())
return nbt
}
override fun deserializeNBT(nbt: CompoundTag) {
super.deserializeNBT(nbt)
NBTUtils.setFloatingLongIfPresent(nbt, NBTConstants.ENERGY_USAGE) { energyUsage: FloatingLong -> updateEnergyUsage(energyUsage) }
}
companion object {
fun input(tile: TileEntityIonThruster, listener: IContentsListener?): IonThrusterEnergyContainer {
val electricBlock = validateBlock(tile)
return IonThrusterEnergyContainer(electricBlock.storage, electricBlock.usage, notExternal, alwaysTrue, tile, listener)
}
}
}
| 5
|
Kotlin
|
9
| 8
|
55bbf9a1630ee55ddc9310c72b0fe9eb67252869
| 1,812
|
Kontraption
|
Apache License 2.0
|
src/test/kotlin/dev/shtanko/di/stopwatch/StopwatchTest.kt
|
ashtanko
| 203,993,092
| false
|
{"Kotlin": 5328917, "Shell": 1158, "Makefile": 469}
|
/*
* Copyright 2021 <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 dev.shtanko.di.stopwatch
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
// TODO tmp solution
class StopwatchTest {
@Test
fun `start test`() {
val s = Stopwatch(MockTimeSource())
assertThat(s.start()).isEqualTo("Measure: 5")
}
private class MockTimeSource : TimeSource {
override fun measure(): Int = 5
}
}
| 4
|
Kotlin
|
0
| 18
|
7dfef253726f8fafab960e5c6e298c4e243c38a0
| 990
|
kotlab
|
Apache License 2.0
|
datasource/datasource-remote/src/main/java/com/example/data_remote/di/ApiModule.kt
|
arunkarshan
| 540,678,357
| false
|
{"Kotlin": 127353, "Java": 310}
|
package com.example.data_remote.di
import com.example.data_remote.network.LoginApi
import com.example.data_remote.network.OrderApi
import org.koin.core.annotation.Factory
import org.koin.core.annotation.Module
import org.koin.core.annotation.Single
import retrofit2.Retrofit
/*********************************************************
* Class : ApiModule
* Author : <NAME>
* Created : 16/09/2022
*******************************************************
* Purpose :
*******************************************************
* Rework Details:
* 1) {Author} : {Date} : {Details}
*********************************************************/
@Module
class ApiModule {
@Factory
fun provideLoginApi(retrofit: Retrofit): LoginApi = retrofit.create(LoginApi::class.java)
@Factory
fun provideOrderApi(retrofit: Retrofit): OrderApi = retrofit.create(OrderApi::class.java)
}
| 0
|
Kotlin
|
0
| 2
|
2a32ca5357099792321f7c811521011f277edf5a
| 894
|
SampleCleanArchitecture
|
Apache License 2.0
|
src/main/kotlin/io/pcast/helpers/Helpers.kt
|
pcast-player
| 859,558,028
| false
|
{"Kotlin": 15061}
|
package io.pcast.helpers
import com.fasterxml.uuid.Generators
import java.util.UUID
fun generateUuidV7(): UUID = Generators.timeBasedEpochGenerator().generate()
| 0
|
Kotlin
|
0
| 0
|
4f43b6ac548010b215e2308b976ecd6bbc830393
| 162
|
pcast-api-kt
|
MIT License
|
feature/account/server/certificate/src/main/kotlin/app/k9mail/feature/account/server/certificate/ServerCertificateModule.kt
|
thunderbird
| 1,326,671
| false
|
{"Kotlin": 4414732, "Java": 2272898, "Shell": 6333, "AIDL": 1946}
|
package app.k9mail.feature.account.server.certificate
import app.k9mail.feature.account.server.certificate.data.InMemoryServerCertificateErrorRepository
import app.k9mail.feature.account.server.certificate.domain.ServerCertificateDomainContract
import app.k9mail.feature.account.server.certificate.domain.usecase.AddServerCertificateException
import app.k9mail.feature.account.server.certificate.ui.ServerCertificateErrorViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.module.Module
import org.koin.dsl.module
val featureAccountServerCertificateModule: Module = module {
single<ServerCertificateDomainContract.ServerCertificateErrorRepository> {
InMemoryServerCertificateErrorRepository()
}
factory<ServerCertificateDomainContract.UseCase.AddServerCertificateException> {
AddServerCertificateException(
localKeyStore = get(),
)
}
viewModel {
ServerCertificateErrorViewModel(
certificateErrorRepository = get(),
addServerCertificateException = get(),
)
}
}
| 732
|
Kotlin
|
2441
| 8,913
|
d02c7c0a45638357e1ce933dff3421c8fb6aa12a
| 1,093
|
thunderbird-android
|
Apache License 2.0
|
src/main/kotlin/com/github/kerubistan/kerub/data/ispn/VirtualStorageDeviceDaoImpl.kt
|
kerubistan
| 19,528,622
| false
| null |
package com.github.kerubistan.kerub.data.ispn
import com.github.kerubistan.kerub.audit.AuditManager
import com.github.kerubistan.kerub.data.EventListener
import com.github.kerubistan.kerub.data.VirtualStorageDeviceDao
import com.github.kerubistan.kerub.model.VirtualStorageDevice
import org.infinispan.Cache
import java.util.UUID
class VirtualStorageDeviceDaoImpl(
cache: Cache<UUID, VirtualStorageDevice>,
eventListener: EventListener,
auditManager: AuditManager)
: VirtualStorageDeviceDao, AbstractAssetDao<VirtualStorageDevice>(cache, eventListener, auditManager) {
override fun getEntityClass(): Class<VirtualStorageDevice> =
VirtualStorageDevice::class.java
}
| 109
|
Kotlin
|
4
| 14
|
99cb43c962da46df7a0beb75f2e0c839c6c50bda
| 677
|
kerub
|
Apache License 2.0
|
typescript-kotlin/src/main/kotlin/typescript/getTrailingCommentRanges.fun.kt
|
turansky
| 393,199,102
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("typescript")
@file:JsNonModule
package typescript
/*
external fun getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined
*/
| 0
|
Kotlin
|
1
| 10
|
bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0
| 212
|
react-types-kotlin
|
Apache License 2.0
|
app/src/main/java/io/heckel/ntfy/service/JsonConnection.kt
|
binwiederhier
| 421,237,780
| false
| null |
package io.heckel.ntfy.service
import android.util.Log
import io.heckel.ntfy.data.ConnectionState
import io.heckel.ntfy.data.Notification
import io.heckel.ntfy.data.Repository
import io.heckel.ntfy.data.Subscription
import io.heckel.ntfy.msg.ApiService
import io.heckel.ntfy.util.topicUrl
import kotlinx.coroutines.*
import okhttp3.Call
import java.util.concurrent.atomic.AtomicBoolean
class SubscriberConnection(
private val repository: Repository,
private val api: ApiService,
private val baseUrl: String,
private val sinceTime: Long,
private val topicsToSubscriptionIds: Map<String, Long>, // Topic -> Subscription ID
private val stateChangeListener: (Collection<Long>, ConnectionState) -> Unit,
private val notificationListener: (Subscription, Notification) -> Unit,
private val serviceActive: () -> Boolean
) {
private val subscriptionIds = topicsToSubscriptionIds.values
private val topicsStr = topicsToSubscriptionIds.keys.joinToString(separator = ",")
private val url = topicUrl(baseUrl, topicsStr)
private var since: Long = sinceTime
private lateinit var call: Call
private lateinit var job: Job
fun start(scope: CoroutineScope) {
job = scope.launch(Dispatchers.IO) {
Log.d(TAG, "[$url] Starting connection for subscriptions: $topicsToSubscriptionIds")
// Retry-loop: if the connection fails, we retry unless the job or service is cancelled/stopped
var retryMillis = 0L
while (isActive && serviceActive()) {
Log.d(TAG, "[$url] (Re-)starting connection for subscriptions: $topicsToSubscriptionIds")
val startTime = System.currentTimeMillis()
val notify = notify@ { topic: String, notification: Notification ->
since = notification.timestamp
val subscriptionId = topicsToSubscriptionIds[topic] ?: return@notify
val subscription = repository.getSubscription(subscriptionId) ?: return@notify
val notificationWithSubscriptionId = notification.copy(subscriptionId = subscription.id)
notificationListener(subscription, notificationWithSubscriptionId)
}
val failed = AtomicBoolean(false)
val fail = { e: Exception ->
failed.set(true)
if (isActive && serviceActive()) { // Avoid UI update races if we're restarting a connection
stateChangeListener(subscriptionIds, ConnectionState.CONNECTING)
}
}
// Call /json subscribe endpoint and loop until the call fails, is canceled,
// or the job or service are cancelled/stopped
try {
call = api.subscribe(baseUrl, topicsStr, since, notify, fail)
while (!failed.get() && !call.isCanceled() && isActive && serviceActive()) {
stateChangeListener(subscriptionIds, ConnectionState.CONNECTED)
Log.d(TAG,"[$url] Connection is active (failed=$failed, callCanceled=${call.isCanceled()}, jobActive=$isActive, serviceStarted=${serviceActive()}")
delay(CONNECTION_LOOP_DELAY_MILLIS) // Resumes immediately if job is cancelled
}
} catch (e: Exception) {
Log.e(TAG, "[$url] Connection failed: ${e.message}", e)
if (isActive && serviceActive()) { // Avoid UI update races if we're restarting a connection
stateChangeListener(subscriptionIds, ConnectionState.CONNECTING)
}
}
// If we're not cancelled yet, wait little before retrying (incremental back-off)
if (isActive && serviceActive()) {
retryMillis = nextRetryMillis(retryMillis, startTime)
Log.d(TAG, "[$url] Connection failed, retrying connection in ${retryMillis / 1000}s ...")
delay(retryMillis)
}
}
Log.d(TAG, "[$url] Connection job SHUT DOWN")
// FIXME: Do NOT update state here as this can lead to races; this leaks the subscription state map
}
}
fun since(): Long {
return since
}
fun cancel() {
Log.d(TAG, "[$url] Cancelling connection")
if (this::job.isInitialized) job?.cancel()
if (this::call.isInitialized) call?.cancel()
}
fun matches(otherSubscriptionIds: Collection<Long>): Boolean {
return subscriptionIds.toSet() == otherSubscriptionIds.toSet()
}
private fun nextRetryMillis(retryMillis: Long, startTime: Long): Long {
val connectionDurationMillis = System.currentTimeMillis() - startTime
if (connectionDurationMillis > RETRY_RESET_AFTER_MILLIS) {
return RETRY_STEP_MILLIS
} else if (retryMillis + RETRY_STEP_MILLIS >= RETRY_MAX_MILLIS) {
return RETRY_MAX_MILLIS
}
return retryMillis + RETRY_STEP_MILLIS
}
companion object {
private const val TAG = "NtfySubscriberConn"
private const val CONNECTION_LOOP_DELAY_MILLIS = 30_000L
private const val RETRY_STEP_MILLIS = 5_000L
private const val RETRY_MAX_MILLIS = 60_000L
private const val RETRY_RESET_AFTER_MILLIS = 60_000L // Must be larger than CONNECTION_LOOP_DELAY_MILLIS
}
}
| 5
| null |
97
| 92
|
66c4eece013518a9147f235627c22a5bcee7df30
| 5,486
|
ntfy-android
|
Apache License 2.0
|
backend/src/main/kotlin/de/mcella/spring/learntool/security/oauth2/user/OAuth2UserInfoFactory.kt
|
sitMCella
| 251,022,990
| false
| null |
package de.mcella.spring.learntool.security.oauth2.user
import de.mcella.spring.learntool.security.oauth2.user.exceptions.OAuth2AuthenticationProcessingException
import de.mcella.spring.learntool.user.AuthProvider
import org.springframework.stereotype.Service
@Service
class OAuth2UserInfoFactory {
fun getOAuth2UserInfo(registrationId: String, attributes: Map<String, Any>): OAuth2UserInfo {
if (registrationId.equals(AuthProvider.google.toString(), ignoreCase = true)) {
return GoogleOAuth2UserInfo(attributes)
}
throw OAuth2AuthenticationProcessingException("Sorry, the login with $registrationId is not supported yet.")
}
}
| 1
|
Kotlin
|
0
| 0
|
01c434e43eb302365f58ea665285a91600a083cd
| 674
|
learn-tool
|
MIT License
|
app/src/main/java/com/mrostami/geckoincompose/data/local/dao/PreferencesDao.kt
|
MosRos
| 639,811,989
| false
| null |
package com.mrostami.geckoincompose.data.local.dao
import kotlinx.coroutines.flow.Flow
interface PreferencesDao {
suspend fun changeTheme(mode: Int)
suspend fun getThemeMode() : Flow<Int>
fun setAuthToken(token: String)
fun getAuthToken() : String?
fun setLastSyncDate(time: Long)
fun getLastSyncDate() : Long
}
| 0
|
Kotlin
|
5
| 17
|
8e396051f6acc17fa2eba8745285fdf800832c60
| 340
|
Geckoin-Compose
|
Apache License 2.0
|
plugins/kapt3/kapt3-compiler/testData/converter/invalidFieldName.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 73968610, "Java": 6672141, "Swift": 4257498, "C": 2622360, "C++": 1898765, "Objective-C": 641056, "Objective-C++": 167134, "JavaScript": 135706, "Python": 48402, "Shell": 31423, "TypeScript": 22754, "Lex": 18369, "Groovy": 17265, "Batchfile": 11693, "CSS": 11368, "Ruby": 6922, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
|
// FIR_BLOCKED: LC don't support illegal java identifiers
enum class Color {
BLACK, `WHI-TE`
}
@Anno(Color.`WHI-TE`)
annotation class Anno(val color: Color)
// EXPECTED_ERROR: (kotlin:6:1) an enum annotation value must be an enum constant
// EXPECTED_ERROR: (other:-1:-1) 'WHI-TE' is an invalid Java enum value name
| 162
|
Kotlin
|
5729
| 46,436
|
c902e5f56504e8572f9bc13f424de8bfb7f86d39
| 322
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/moviedatabase/toggleFavourite/data/ToggleFavouriteRepositoryImpl.kt
|
ali-gevari
| 838,166,478
| false
|
{"Kotlin": 192241}
|
package com.example.moviedatabase.toggleFavourite.data
import com.example.moviedatabase.toggleFavourite.data.network.ToggleFavouriteApi
import com.example.moviedatabase.toggleFavourite.domain.ToggleFavouriteRepository
import com.example.moviedatabase.toggleFavourite.data.entity.ToggleFavouriteBody
import com.example.moviedatabase.toggleFavourite.data.entity.ToggleFavouriteMapper
import com.example.moviedatabase.toggleFavourite.domain.entity.ToggleFavourite
import com.example.moviedatabase.util.ProgramType
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class ToggleFavouriteRepositoryImpl @Inject constructor(
private val toggleFavouriteApi: ToggleFavouriteApi,
private val toggleFavouriteMapper: ToggleFavouriteMapper
) : ToggleFavouriteRepository {
override fun toggleFavourite(
programId: String,
programType: ProgramType,
isFavourite: Boolean
): Flow<ToggleFavourite> = flow {
val toggleFavouriteBody = ToggleFavouriteBody(
id = programId,
type = programType.type.lowercase(),
favorite = isFavourite
)
val request = toggleFavouriteApi.toggleFavourite(toggleFavouriteBody)
val response = toggleFavouriteMapper.mapToggleFavourite(request)
emit(response)
}
}
| 1
|
Kotlin
|
0
| 0
|
764509e150c28857d2992f2d2e1b427faaa0c5f7
| 1,339
|
MovieDatabase
|
Apache License 2.0
|
api/src/main/kotlin/org/web3j/corda/api/VaultQueryResource.kt
|
iantstaley
| 733,498,695
| false
| null |
/*
* Copyright 2019 Web3 Labs 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 org.web3j.corda.api
import org.web3j.corda.model.core.node.services.Vault_Page_net_corda_core_contracts_ContractState
import javax.ws.rs.GET
import javax.ws.rs.QueryParam
interface VaultQueryResource {
@GET
fun contractStateType(
@QueryParam("contract-state-type")
contractStateType: String
): Vault_Page_net_corda_core_contracts_ContractState
}
| 1
| null |
1
| 3
|
c5786f5e822cf95d3e5e17e167217f75db2eba3d
| 970
|
web3j-corda
|
Apache License 2.0
|
library/src/main/kotlin/com/connectrpc/ServerOnlyStreamInterface.kt
|
connectrpc
| 604,763,682
| false
| null |
// Copyright 2022-2023 The Connect 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 com.connectrpc
import kotlinx.coroutines.channels.ReceiveChannel
/**
* Represents a server-only stream (a stream where the server streams data to the client after
* receiving an initial request) that can send request messages.
*/
interface ServerOnlyStreamInterface<Input, Output> {
/**
* The Channel for received StreamResults.
*
* @return ReceiveChannel for iterating over the received results.
*/
fun resultChannel(): ReceiveChannel<StreamResult<Output>>
/**
* Send a request to the server over the stream and closes the request.
*
* Can only be called exactly one time when starting the stream.
*
* @param input The request message to send.
* @return [Result.success] on send success, [Result.failure] on
* any sends which are not successful.
*/
suspend fun sendAndClose(input: Input): Result<Unit>
/**
* Close the receive stream.
*/
fun receiveClose()
/**
* Determine if the underlying client receive stream is closed.
*
* @return true if the underlying client receive stream is closed. If the stream is still open,
* this will return false.
*/
fun isReceiveClosed(): Boolean
/**
* Determine if the underlying stream is closed.
*
* @return true if the underlying stream is closed. If the stream is still open,
* this will return false.
*/
fun isClosed(): Boolean
}
| 6
| null |
6
| 56
|
d54b0c9a052a7fc22b40c90b67b1e4eca43bffa4
| 2,073
|
connect-kotlin
|
Apache License 2.0
|
skirmish/src/main/kotlin/com/seanshubin/game_4x/skirmish/Intent.kt
|
SeanShubin
| 204,213,077
| false
|
{"XML": 1, "Maven POM": 13, "Ignore List": 1, "Shell": 1, "Text": 9, "HTML": 12, "Kotlin": 245, "Java": 12}
|
package com.seanshubin.game_4x.skirmish
interface Intent {
companion object {
data class AttackCommanderNamed(val defenderName: String) : Intent
}
}
| 0
|
Kotlin
|
0
| 0
|
a05479651479b5ab1470b925c015c7fa74cd59cb
| 166
|
game-4x
|
The Unlicense
|
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/ui/settings/notification/NotificationSettingsFragmentViewModelTest.kt
|
si-covid-19
| 286,833,811
| false
| null |
package de.rki.coronawarnapp.ui.settings.notification
import android.content.Context
import de.rki.coronawarnapp.ui.settings.notifications.NotificationSettings
import de.rki.coronawarnapp.ui.settings.notifications.NotificationSettingsFragmentViewModel
import de.rki.coronawarnapp.ui.settings.notifications.NotificationSettingsState
import io.kotest.matchers.shouldBe
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import kotlinx.coroutines.flow.flow
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import testhelpers.BaseTest
import testhelpers.TestDispatcherProvider
import testhelpers.extensions.CoroutinesTestExtension
import testhelpers.extensions.InstantExecutorExtension
import testhelpers.extensions.observeForTesting
@ExtendWith(InstantExecutorExtension::class, CoroutinesTestExtension::class)
class NotificationSettingsFragmentViewModelTest : BaseTest() {
@MockK lateinit var context: Context
@MockK(relaxUnitFun = true) lateinit var notificationSettings: NotificationSettings
@BeforeEach
fun setup() {
MockKAnnotations.init(this)
every { notificationSettings.isNotificationsEnabled } returns flow { emit(true) }
every { notificationSettings.isNotificationsRiskEnabled } returns flow { emit(false) }
every { notificationSettings.isNotificationsTestEnabled } returns flow { emit(true) }
}
private fun createInstance(): NotificationSettingsFragmentViewModel =
NotificationSettingsFragmentViewModel(
dispatcherProvider = TestDispatcherProvider(),
notificationSettings = notificationSettings
)
@Test
fun `notification state`() {
createInstance().apply {
notificationSettingsState.observeForTesting { }
notificationSettingsState.value shouldBe NotificationSettingsState(
isNotificationsEnabled = true,
isNotificationsRiskEnabled = false,
isNotificationsTestEnabled = true
)
}
every { notificationSettings.isNotificationsEnabled } returns flow { emit(false) }
every { notificationSettings.isNotificationsRiskEnabled } returns flow { emit(true) }
every { notificationSettings.isNotificationsTestEnabled } returns flow { emit(false) }
createInstance().apply {
notificationSettingsState.observeForTesting { }
notificationSettingsState.value shouldBe NotificationSettingsState(
isNotificationsEnabled = false,
isNotificationsRiskEnabled = true,
isNotificationsTestEnabled = false
)
}
}
@Test
fun `toggle risk notifications`() {
createInstance().toggleNotificationsRiskEnabled()
verify { notificationSettings.toggleNotificationsRiskEnabled() }
}
@Test
fun `toggle test notifications`() {
createInstance().toggleNotificationsTestEnabled()
verify { notificationSettings.toggleNotificationsTestEnabled() }
}
}
| 6
|
Kotlin
|
8
| 15
|
5a3b4be63b5b030da49216a0132a3979cad89af1
| 3,149
|
ostanizdrav-android
|
Apache License 2.0
|
app/src/main/java/de/eso/weather/ui/shared/livedatacommand/LiveDataCommandObserver.kt
|
e-solutions-GmbH
| 506,562,385
| false
| null |
package de.eso.weather.ui.shared.livedatacommand
import androidx.lifecycle.Observer
class LiveDataCommandObserver(private val action: () -> Unit) : Observer<LiveDataCommand> {
override fun onChanged(command: LiveDataCommand) {
if (!command.hasBeenHandled) {
command.hasBeenHandled = true
action()
}
}
}
| 0
|
Kotlin
|
1
| 1
|
d054b0a902cd1b6392ff0d31a2e7f8751f5fdf0c
| 353
|
sample-weather-compose
|
MIT License
|
app/src/main/java/com/oky2abbas/sms2html/about/AboutView.kt
|
oky2abbas
| 165,665,044
| false
| null |
package com.oky2abbas.sms2html.about
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.oky2abbas.sms2html.R
class AboutView : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.about_view, container, false)
}
}
| 0
|
Kotlin
|
0
| 2
|
61b8e151d1fa09a9744405842b693618d90184b2
| 474
|
smsExtraction
|
MIT License
|
app/src/main/java/com/breezefsmhmhcorporation/features/dashboard/presentation/api/submithomeloc/SubmitHomeLocationRepo.kt
|
DebashisINT
| 654,125,604
| false
| null |
package com.breezefsmhmhcorporation.features.dashboard.presentation.api.submithomeloc
import com.breezefsmhmhcorporation.base.BaseResponse
import com.breezefsmhmhcorporation.features.dashboard.presentation.model.SubmitHomeLocationInputModel
import io.reactivex.Observable
/**
* Created by Saikat on 13-03-2019.
*/
class SubmitHomeLocationRepo(val apiService: SubmitHomeLocationApi) {
fun submitAttendance(addAttendenceModel: SubmitHomeLocationInputModel): Observable<BaseResponse> {
return apiService.submitHomeLocation(addAttendenceModel)
}
}
| 0
|
Kotlin
|
0
| 0
|
855a26194f21b9b24780e0c3d26914bc1725bb60
| 563
|
HMHCorporation
|
Apache License 2.0
|
mediation_adapter_mopub/src/main/java/com/hmscl/huawei/ads/mediation_adapter_mopub/utils/HuaweiAdsMediaLayout.kt
|
Explore-In-HMS
| 402,729,985
| false
|
{"Kotlin": 99921}
|
package com.test.huawei.ads.mopub_mediation_library.utils
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.view.TextureView
import android.view.TextureView.SurfaceTextureListener
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.RelativeLayout
import com.mopub.common.Preconditions
import com.mopub.common.logging.MoPubLog
import com.mopub.common.logging.MoPubLog.SdkLogEvent
import com.mopub.common.util.Dips
import com.mopub.common.util.Drawables
import com.mopub.mobileads.VastVideoProgressBarWidget
import com.mopub.mobileads.resource.DrawableConstants.GradientStrip
class HuaweiAdsMediaLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) :
RelativeLayout(context, attrs, defStyleAttr) {
enum class Mode {
IMAGE, PLAYING, LOADING, BUFFERING, PAUSED, FINISHED
}
enum class MuteState {
MUTED, UNMUTED
}
@Volatile
private var mMode = Mode.IMAGE
private var mMuteState: MuteState
private val mMainImageView: ImageView
// These views are video-only, ordered by their z index. Don't create them if they aren't needed.
var textureView: TextureView? = null
private set
private var mLoadingSpinner: ProgressBar? = null
private var mPlayButton: ImageView? = null
private var mBottomGradient: ImageView? = null
private var mTopGradient: ImageView? = null
private var mVideoProgress: VastVideoProgressBarWidget? = null
private var mMuteControl: ImageView? = null
private var mOverlay: View? = null
private var mMutedDrawable: Drawable? = null
private var mUnmutedDrawable: Drawable? = null
private var mIsInitialized = false
// Measurements
private val mControlSizePx: Int
private val mGradientStripHeightPx: Int
private val mMuteSizePx: Int
private val mPaddingPx: Int
fun setSurfaceTextureListener(stl: SurfaceTextureListener?) {
if (textureView != null) {
textureView!!.surfaceTextureListener = stl
val st = textureView!!.surfaceTexture
if (st != null && stl != null) {
stl.onSurfaceTextureAvailable(st, textureView!!.width, textureView!!.height)
}
}
}
/**
* Users should call this method when the view will be used for video. Video views are not
* instantiated in the image-only case in order to save time and memory.
*/
fun initForVideo() {
if (mIsInitialized) {
return
}
// Init and set up all the video view items.
val videoTextureLayoutParams =
LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
videoTextureLayoutParams.addRule(CENTER_IN_PARENT)
textureView = TextureView(context)
textureView!!.layoutParams = videoTextureLayoutParams
textureView!!.id = generateViewId()
addView(textureView)
// Place texture beneath image.
mMainImageView.bringToFront()
val loadingSpinnerParams = LayoutParams(mControlSizePx, mControlSizePx)
loadingSpinnerParams.addRule(ALIGN_PARENT_TOP)
loadingSpinnerParams.addRule(ALIGN_PARENT_RIGHT)
mLoadingSpinner = ProgressBar(context)
mLoadingSpinner!!.layoutParams = loadingSpinnerParams
mLoadingSpinner!!.setPadding(0, mPaddingPx, mPaddingPx, 0)
mLoadingSpinner!!.isIndeterminate = true
addView(mLoadingSpinner)
val bottomGradientParams = LayoutParams(LayoutParams.MATCH_PARENT, mGradientStripHeightPx)
bottomGradientParams.addRule(ALIGN_BOTTOM, textureView!!.id)
mBottomGradient = ImageView(context)
mBottomGradient!!.layoutParams = bottomGradientParams
val bottomGradientDrawable = GradientDrawable(
GradientDrawable.Orientation.BOTTOM_TOP,
intArrayOf(GradientStrip.START_COLOR, GradientStrip.END_COLOR)
)
mBottomGradient!!.setImageDrawable(bottomGradientDrawable)
addView(mBottomGradient)
val topGradientParams = LayoutParams(LayoutParams.MATCH_PARENT, mGradientStripHeightPx)
topGradientParams.addRule(ALIGN_TOP, textureView!!.id)
mTopGradient = ImageView(context)
mTopGradient!!.layoutParams = topGradientParams
val topGradientDrawable = GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
intArrayOf(GradientStrip.START_COLOR, GradientStrip.END_COLOR)
)
mTopGradient!!.setImageDrawable(topGradientDrawable)
addView(mTopGradient)
mVideoProgress = VastVideoProgressBarWidget(context)
mVideoProgress!!.setAnchorId(textureView!!.id)
mVideoProgress!!.calibrateAndMakeVisible(1000, 0)
addView(mVideoProgress)
mMutedDrawable = Drawables.NATIVE_MUTED.createDrawable(context)
mUnmutedDrawable = Drawables.NATIVE_UNMUTED.createDrawable(context)
val muteControlParams = LayoutParams(mMuteSizePx, mMuteSizePx)
muteControlParams.addRule(ALIGN_PARENT_LEFT)
muteControlParams.addRule(ABOVE, mVideoProgress!!.id)
mMuteControl = ImageView(context)
mMuteControl!!.layoutParams = muteControlParams
mMuteControl!!.scaleType = ImageView.ScaleType.CENTER_INSIDE
mMuteControl!!.setPadding(mPaddingPx, mPaddingPx, mPaddingPx, mPaddingPx)
mMuteControl!!.setImageDrawable(mMutedDrawable)
addView(mMuteControl)
val overlayParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
overlayParams.addRule(CENTER_IN_PARENT)
mOverlay = View(context)
mOverlay!!.layoutParams = overlayParams
mOverlay!!.setBackgroundColor(Color.TRANSPARENT)
addView(mOverlay)
val playButtonParams = LayoutParams(mControlSizePx, mControlSizePx)
playButtonParams.addRule(CENTER_IN_PARENT)
mPlayButton = ImageView(context)
mPlayButton!!.layoutParams = playButtonParams
mPlayButton!!.setImageDrawable(Drawables.NATIVE_PLAY.createDrawable(context))
addView(mPlayButton)
mIsInitialized = true
updateViewState()
}
/**
* Resets the view, removing all the OnClickListeners and setting the view to hide
*/
fun reset() {
setMode(Mode.IMAGE)
setPlayButtonClickListener(null)
setMuteControlClickListener(null)
setVideoClickListener(null)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
val measWidth = MeasureSpec.getSize(widthMeasureSpec)
val measHeight = MeasureSpec.getSize(heightMeasureSpec)
val curWidth = measuredWidth
val curHeight = measuredHeight
var finalWidth: Int
finalWidth = if (widthMode == MeasureSpec.EXACTLY) {
measWidth
} else if (widthMode == MeasureSpec.AT_MOST) {
// Cap width at max width.
Math.min(measWidth, curWidth)
} else {
// MeasWidth is meaningless. Stay with current width.
curWidth
}
// Set height based on width + height constraints.
var finalHeight = (ASPECT_MULTIPLIER_WIDTH_TO_HEIGHT * finalWidth).toInt()
// Check if the layout is giving us bounds smaller than we want, conform to those if needed.
if (heightMode == MeasureSpec.EXACTLY && measHeight < finalHeight) {
finalHeight = measHeight
finalWidth = (ASPECT_MULTIPLIER_HEIGHT_TO_WIDTH * finalHeight).toInt()
}
if (Math.abs(finalHeight - curHeight) >= 2
|| Math.abs(finalWidth - curWidth) >= 2
) {
MoPubLog.log(
SdkLogEvent.CUSTOM,
String.format("Resetting mediaLayout size to w: %d h: %d", finalWidth, finalHeight)
)
layoutParams.width = finalWidth
layoutParams.height = finalHeight
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
fun setMainImageDrawable(drawable: Drawable) {
Preconditions.checkNotNull(drawable)
mMainImageView.setImageDrawable(drawable)
}
fun resetProgress() {
if (mVideoProgress != null) {
mVideoProgress!!.reset()
}
}
fun updateProgress(progressTenthPercentage: Int) {
if (mVideoProgress != null) {
mVideoProgress!!.updateProgress(progressTenthPercentage)
}
}
fun setMode(mode: Mode) {
Preconditions.checkNotNull(mode)
mMode = mode
post { updateViewState() }
}
val mainImageView: ImageView?
get() = mMainImageView
fun setMuteControlClickListener(muteControlListener: OnClickListener?) {
if (mMuteControl != null) {
mMuteControl!!.setOnClickListener(muteControlListener)
}
}
fun setPlayButtonClickListener(playButtonListener: OnClickListener?) {
if (mPlayButton != null && mOverlay != null) {
mOverlay!!.setOnClickListener(playButtonListener)
mPlayButton!!.setOnClickListener(playButtonListener)
}
}
fun setVideoClickListener(videoClickListener: OnClickListener?) {
if (textureView != null) {
textureView!!.setOnClickListener(videoClickListener)
}
}
fun setMuteState(muteState: MuteState) {
Preconditions.checkNotNull(muteState)
if (muteState == mMuteState) {
return
}
mMuteState = muteState
if (mMuteControl != null) {
when (mMuteState) {
MuteState.MUTED -> mMuteControl!!.setImageDrawable(mMutedDrawable)
MuteState.UNMUTED -> mMuteControl!!.setImageDrawable(mUnmutedDrawable)
else -> mMuteControl!!.setImageDrawable(mUnmutedDrawable)
}
}
}
private fun updateViewState() {
when (mMode) {
Mode.IMAGE -> {
setMainImageVisibility(VISIBLE)
setLoadingSpinnerVisibility(INVISIBLE)
setVideoControlVisibility(INVISIBLE)
setPlayButtonVisibility(INVISIBLE)
}
Mode.LOADING -> {
setMainImageVisibility(VISIBLE)
setLoadingSpinnerVisibility(VISIBLE)
setVideoControlVisibility(INVISIBLE)
setPlayButtonVisibility(INVISIBLE)
}
Mode.BUFFERING -> {
setMainImageVisibility(INVISIBLE)
setLoadingSpinnerVisibility(VISIBLE)
setVideoControlVisibility(VISIBLE)
setPlayButtonVisibility(INVISIBLE)
setMainImageVisibility(INVISIBLE)
setLoadingSpinnerVisibility(INVISIBLE)
setVideoControlVisibility(VISIBLE)
setPlayButtonVisibility(INVISIBLE)
}
Mode.PLAYING -> {
setMainImageVisibility(INVISIBLE)
setLoadingSpinnerVisibility(INVISIBLE)
setVideoControlVisibility(VISIBLE)
setPlayButtonVisibility(INVISIBLE)
}
Mode.PAUSED -> {
setMainImageVisibility(INVISIBLE)
setLoadingSpinnerVisibility(INVISIBLE)
setVideoControlVisibility(VISIBLE)
setPlayButtonVisibility(VISIBLE)
}
Mode.FINISHED -> {
setMainImageVisibility(VISIBLE)
setLoadingSpinnerVisibility(INVISIBLE)
setVideoControlVisibility(INVISIBLE)
setPlayButtonVisibility(VISIBLE)
}
else -> {
}
}
}
private fun setMainImageVisibility(visibility: Int) {
mMainImageView.visibility = visibility
}
private fun setLoadingSpinnerVisibility(visibility: Int) {
if (mLoadingSpinner != null) {
mLoadingSpinner!!.visibility = visibility
}
if (mTopGradient != null) {
mTopGradient!!.visibility = visibility
}
}
private fun setVideoControlVisibility(visibility: Int) {
if (mBottomGradient != null) {
mBottomGradient!!.visibility = visibility
}
if (mVideoProgress != null) {
mVideoProgress!!.visibility = visibility
}
if (mMuteControl != null) {
mMuteControl!!.visibility = visibility
}
}
private fun setPlayButtonVisibility(visibility: Int) {
if (mPlayButton != null && mOverlay != null) {
mPlayButton!!.visibility = visibility
mOverlay!!.visibility = visibility
}
}
companion object {
private const val GRADIENT_STRIP_HEIGHT_DIPS = 35
private const val MUTE_SIZE_DIPS = 36
private const val CONTROL_SIZE_DIPS = 40
private const val PINNER_PADDING_DIPS = 10
private const val ASPECT_MULTIPLIER_WIDTH_TO_HEIGHT = 9f / 16
private const val ASPECT_MULTIPLIER_HEIGHT_TO_WIDTH = 16f / 9
}
// Constructors
init {
Preconditions.checkNotNull(context)
mMuteState = MuteState.MUTED
// Create and layout the main imageView and set its modes.
val params = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
params.addRule(CENTER_IN_PARENT)
mMainImageView = ImageView(context)
mMainImageView.layoutParams = params
mMainImageView.scaleType = ImageView.ScaleType.CENTER_CROP
addView(mMainImageView)
mControlSizePx = Dips.asIntPixels(CONTROL_SIZE_DIPS.toFloat(), context)
mGradientStripHeightPx = Dips.asIntPixels(GRADIENT_STRIP_HEIGHT_DIPS.toFloat(), context)
mMuteSizePx = Dips.asIntPixels(MUTE_SIZE_DIPS.toFloat(), context)
mPaddingPx = Dips.asIntPixels(PINNER_PADDING_DIPS.toFloat(), context)
}
}
| 1
|
Kotlin
|
1
| 6
|
1ddf7ec0f462e8111a49d44386cf88181ba7be40
| 14,140
|
huawei.ads.mopub_mediation
|
Apache License 2.0
|
android/poker/src/main/java/nl/entreco/scrumpoker/poker/ui/poker/PokerCardModel.kt
|
Entreco
| 155,434,723
| false
| null |
package nl.entreco.scrumpoker.poker.ui.poker
import androidx.databinding.ObservableField
import nl.entreco.scrumpoker.poker.model.PokerCard
data class PokerCardModel(private val pokerCard: PokerCard){
val value = ObservableField<String>(pokerCard.value)
}
| 0
|
Kotlin
|
0
| 0
|
8395ca6b6292be3db8e57262c3bd598b55c5f7fb
| 261
|
Scrum-Poker
|
Apache License 2.0
|
observer/src/main/java/com/xingray/observer/field/BooleanField.kt
|
XingRay
| 207,265,131
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 18, "Java": 2, "Kotlin": 45}
|
package com.xingray.observer.field
/**
* 可观察的`Boolean`字段
*
* @author : leixing
* @date : 2019/11/22 14:29
* @version : 1.0.0
* mail : <EMAIL>
*
*/
class BooleanField(private var value: Boolean) {
constructor() : this(false)
fun get(): Boolean {
return value
}
fun set(value: Boolean): Pair<Boolean, Boolean>? {
if (value == this.value) {
return null
}
val last = this.value
this.value = value
return Pair(true, last)
}
override fun toString(): String {
return value.toString()
}
}
| 0
|
Kotlin
|
0
| 1
|
8326f6b7c50bb73c0372350beb97ecf7bb13abb9
| 589
|
Observer
|
Apache License 2.0
|
actions/java/com/squareup/tools/sqldelight/cli/Utils.kt
|
square
| 360,699,920
| false
|
{"Starlark": 32578, "Kotlin": 8248, "Shell": 1841}
|
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package com.squareup.tools.sqldelight.cli
import java.lang.IllegalStateException
// General types
internal class SqlDelightException(message: String) : IllegalStateException(message)
| 3
|
Starlark
|
5
| 6
|
f63e79a3a105079b55d9c4d27943c33faa7f6e80
| 779
|
sqldelight_bazel_rules
|
Apache License 2.0
|
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsresettlementpassportapi/integration/SubjectAccessRequestIntegrationTest.kt
|
ministryofjustice
| 665,659,688
| false
|
{"Kotlin": 1542825, "Dockerfile": 1995}
|
package uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.integration
import net.javacrumbs.jsonunit.assertj.assertThatJson
import net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER
import org.junit.jupiter.api.Test
import org.springframework.test.context.jdbc.Sql
import java.time.LocalDate
class SubjectAccessRequestIntegrationTest : IntegrationTestBase() {
@Test
@Sql("classpath:testdata/sql/seed-sar-data-1.sql")
fun `SAR without Dates`() {
val nomsId = "G1458GV"
val response = webTestClient.get()
.uri("/subject-access-request?prn=$nomsId")
.headers(setAuthorisation(roles = listOf("ROLE_SAR_DATA_ACCESS")))
.exchange()
.expectStatus().isOk
.expectHeader().contentType("application/json")
.expectBody(String::class.java)
.returnResult().responseBody!!
assertThatJson(response)
.`when`(IGNORING_ARRAY_ORDER)
.isEqualTo(readFile("testdata/expectation/sar-without-dates.json"))
}
@Test
@Sql("classpath:testdata/sql/seed-sar-data-1.sql")
fun `SAR with Dates`() {
val nomsId = "G1458GV"
val fromYesterday = LocalDate.parse("2023-08-17")
val fromLastYear = LocalDate.parse("2022-08-17")
val responseContentYesterday = getSarData(nomsId, fromYesterday)
assertThatJson(responseContentYesterday)
.`when`(IGNORING_ARRAY_ORDER)
.isEqualTo(readFile("testdata/expectation/sar-with-dates-1.json"))
val responseContent = getSarData(nomsId, fromLastYear)
assertThatJson(responseContent)
.`when`(IGNORING_ARRAY_ORDER)
.isEqualTo(readFile("testdata/expectation/sar-with-dates-2.json"))
}
private fun getSarData(nomsId: String, fromYesterday: LocalDate?): String = webTestClient.get()
.uri("/subject-access-request?prn=$nomsId&fromDate=$fromYesterday")
.headers(setAuthorisation(roles = listOf("ROLE_SAR_DATA_ACCESS")))
.exchange()
.expectStatus().isOk
.expectHeader().contentType("application/json")
.expectBody(String::class.java)
.returnResult().responseBody!!
@Test
fun `SAR request when nomsId not found`() {
val nomsId = "abc"
webTestClient.get()
.uri("/subject-access-request?prn=$nomsId")
.headers(setAuthorisation(roles = listOf("ROLE_SAR_DATA_ACCESS")))
.exchange()
.expectStatus().isEqualTo(204)
}
}
| 2
|
Kotlin
|
2
| 1
|
cc205590e7bce4b8790e20dab9d89c77bedab85d
| 2,326
|
hmpps-resettlement-passport-api
|
MIT License
|
designtokens/src/main/java/com/seljabali/designtokens/spacings/spacingselector/SpacingsLandingPageViewHolder.kt
|
whether-jacket
| 183,982,379
| false
| null |
package com.seljabali.designtokens.spacings.spacingselector
import android.view.View
import android.widget.ImageView
import com.google.android.material.textview.MaterialTextView
import androidx.recyclerview.widget.RecyclerView
import com.seljabali.designtokens.R
import com.seljabali.designtokens.LandingItem
class SpacingsLandingPageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val pageItemNameTextView: MaterialTextView = itemView.findViewById(R.id.pageItemNameTextView)
private val pageItemIconImageView: ImageView = itemView.findViewById(R.id.pageItemIconImageView)
fun bind(currentPageItem: LandingItem) {
pageItemNameTextView.text = itemView.context.getString(currentPageItem.titleStringId)
pageItemIconImageView.background = itemView.context.getDrawable(currentPageItem.iconId)
}
}
| 22
|
Kotlin
|
1
| 16
|
ec0d1390c86f11a49ee8023285d6842649d4b85b
| 852
|
weather-app-2020-android
|
Creative Commons Zero v1.0 Universal
|
subprojects/common/report-viewer/src/testFixtures/kotlin/com/avito/report/StubReportsApi.kt
|
StanlyT
| 344,157,673
| true
|
{"Kotlin": 2773538, "HTML": 121161, "Shell": 17522, "Python": 14168, "Makefile": 7187, "Dockerfile": 7134}
|
package com.avito.report
import com.avito.android.Result
import com.avito.report.model.AndroidTest
import com.avito.report.model.CreateResult
import com.avito.report.model.CrossDeviceSuite
import com.avito.report.model.GetReportResult
import com.avito.report.model.Report
import com.avito.report.model.ReportCoordinates
import com.avito.report.model.SimpleRunTest
import com.google.gson.JsonElement
import java.util.ArrayDeque
import java.util.Queue
import java.util.concurrent.ConcurrentLinkedQueue
class StubReportsApi(
reportListResults: List<Result<List<Report>>> = emptyList()
) : ReportsApi {
private val reportListResultsQueue: Queue<Result<List<Report>>> = ArrayDeque(reportListResults)
private val testsForReportId = mutableMapOf<String, Result<List<SimpleRunTest>>>()
private val markAsSuccessfulRequests = mutableListOf<MarkAsRequest>()
private val testsForRunId = mutableMapOf<ReportCoordinates, Result<List<SimpleRunTest>>>()
lateinit var createResult: CreateResult
lateinit var getReportResult: GetReportResult
lateinit var finished: Result<Unit>
lateinit var crossDeviceTestData: Result<CrossDeviceSuite>
val addTestsRequests: Queue<AddTestsRequest> = ConcurrentLinkedQueue()
@Synchronized
override fun create(
reportCoordinates: ReportCoordinates,
buildId: String,
testHost: String,
gitBranch: String,
gitCommit: String,
tmsBranch: String
): CreateResult = createResult
override fun addTest(reportCoordinates: ReportCoordinates, buildId: String?, test: AndroidTest): Result<String> {
TODO("not implemented")
}
fun enqueueTestsForReportId(reportId: String, value: Result<List<SimpleRunTest>>) {
testsForReportId[reportId] = value
}
override fun getTestsForReportId(reportId: String): Result<List<SimpleRunTest>> {
return testsForReportId[reportId] ?: error("you need to enqueue result by reportId: $reportId")
}
override fun addTests(
reportCoordinates: ReportCoordinates,
buildId: String?,
tests: Collection<AndroidTest>
): Result<List<String>> {
addTestsRequests.add(AddTestsRequest(reportCoordinates, buildId, tests))
return Result.Success(emptyList())
}
@Synchronized
override fun getReportsList(planSlug: String, jobSlug: String, pageNumber: Int): Result<List<Report>> {
if (reportListResultsQueue.isEmpty()) {
throw IllegalArgumentException(
"getReportsList results queue is empty in StubReportsApi"
)
}
return reportListResultsQueue.poll()
}
@Synchronized
override fun getCrossDeviceTestData(reportCoordinates: ReportCoordinates): Result<CrossDeviceSuite> =
crossDeviceTestData
@Synchronized
override fun getReport(reportCoordinates: ReportCoordinates): GetReportResult = getReportResult
fun enqueueTestsForRunId(reportCoordinates: ReportCoordinates, value: Result<List<SimpleRunTest>>) {
testsForRunId[reportCoordinates] = value
}
@Synchronized
override fun getTestsForRunId(reportCoordinates: ReportCoordinates): Result<List<SimpleRunTest>> {
return testsForRunId[reportCoordinates] ?: error("no stub ready for $reportCoordinates")
}
@Synchronized
override fun setFinished(reportCoordinates: ReportCoordinates): Result<Unit> = finished
fun getLastMarkAsSuccessfulRequest(): MarkAsRequest? = markAsSuccessfulRequests.lastOrNull()
@Synchronized
override fun markAsSuccessful(testRunId: String, author: String, comment: String): Result<Unit> {
markAsSuccessfulRequests.add(
MarkAsRequest(
testRunId,
author,
comment
)
)
return Result.Success(Unit)
}
@Synchronized
override fun markAsFailed(testRunId: String, author: String, comment: String): Result<Unit> {
TODO("not implemented")
}
override fun pushPreparedData(reportId: String, analyzerKey: String, preparedData: JsonElement): Result<Unit> {
TODO("not implemented")
}
data class MarkAsRequest(
val testRunId: String,
val author: String,
val comment: String
)
data class AddTestsRequest(
val reportCoordinates: ReportCoordinates,
val buildId: String?,
val tests: Collection<AndroidTest>
)
}
| 0
|
Kotlin
|
0
| 0
|
96463f7714c0550e331d2a37fb32ad98fac9d62d
| 4,449
|
avito-android
|
MIT License
|
octicons/src/commonMain/kotlin/compose/icons/octicons/Grabber16.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36719092}
|
package compose.icons.octicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
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 compose.icons.Octicons
public val Octicons.Grabber16: ImageVector
get() {
if (_grabber16 != null) {
return _grabber16!!
}
_grabber16 = Builder(name = "Grabber16", defaultWidth = 16.0.dp, defaultHeight = 16.0.dp,
viewportWidth = 16.0f, viewportHeight = 16.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(10.0f, 13.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, 0.0f, -2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f)
close()
moveTo(6.0f, 13.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, 0.0f, -2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f)
close()
moveTo(7.0f, 8.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, -2.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 2.0f, 0.0f)
close()
moveTo(10.0f, 9.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, 0.0f, -2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f)
close()
moveTo(11.0f, 4.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, -2.0f, 0.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 2.0f, 0.0f)
close()
moveTo(6.0f, 5.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, 0.0f, -2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f)
close()
}
}
.build()
return _grabber16!!
}
private var _grabber16: ImageVector? = null
| 17
|
Kotlin
|
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 2,437
|
compose-icons
|
MIT License
|
src/main/kotlin/com/github/santosleijon/frugalfennecbackend/users/domain/User.kt
|
santosleijon
| 490,805,467
| false
| null |
package com.github.santosleijon.frugalfennecbackend.users.domain
import com.github.santosleijon.frugalfennecbackend.common.AggregateRoot
import com.github.santosleijon.frugalfennecbackend.common.DomainEvent
import com.github.santosleijon.frugalfennecbackend.users.domain.events.UserCreatedEvent
import java.util.*
class User(
id: UUID,
version: Int,
) : AggregateRoot(id, version) {
var email: String? = null
private set
companion object {
const val aggregateName: String = "User"
fun loadFrom(events: List<DomainEvent>, id: UUID, version: Int): User {
val newUser = User(id, version)
for (event in events) {
newUser.mutate(event)
}
return newUser
}
}
constructor(
id: UUID,
email: String
) : this(id = id, version = 0) {
this.apply(
UserCreatedEvent(
id,
version,
email,
)
)
}
override fun mutate(event: DomainEvent) {
when (event) {
is UserCreatedEvent -> {
email = event.email
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ab566b6ea6438238751e51a64a537d710de181bb
| 1,193
|
frugal-fennec-expense-manager
|
MIT License
|
example-speech-recognition/src/main/java/com/dailystudio/tflite/example/speech/recognition/AudioInferenceInfo.kt
|
dailystudio
| 267,263,865
| false
| null |
package com.dailystudio.tflite.example.speech.recognition
import android.content.Context
import com.dailystudio.tflite.example.common.InferenceInfo
import com.dailystudio.tflite.example.common.InferenceInfoItem
class AudioInferenceInfo(var sampleRate: Int = 0,
var bufferSize: Int = 0,
analysisTime: Long = 0,
inferenceTime: Long = 0) : InferenceInfo(analysisTime, inferenceTime) {
override fun toInfoItems(context: Context): MutableList<InferenceInfoItem> {
val items = super.toInfoItems(context)
val idStart = items.size
val resources = context.resources
val itemSampleRate = InferenceInfoItem(idStart+ 1, R.drawable.ic_info_sample_rate,
resources.getString(R.string.label_info_sample_rate), "%d Hz".format(sampleRate))
items.add(itemSampleRate)
val itemBufferSize = InferenceInfoItem(idStart + 2, R.drawable.ic_info_buffer_size,
resources.getString(R.string.label_info_buffer_size), "%dB".format(bufferSize))
items.add(itemBufferSize)
return items
}
override fun toString(): String {
return buildString {
append("sample rate: $sampleRate,")
append(super.toString())
}
}
}
| 1
|
Kotlin
|
6
| 47
|
1ce173bdc6dd2ac2a0c83197ff27ded3ed381df2
| 1,303
|
tensorflow-lite-examples-android
|
Apache License 2.0
|
transport-eta-android/presentation/src/main/java/com/joaquimley/transporteta/presentation/home/favorite/FavoritesViewModelFactory.kt
|
JoaquimLey
| 93,657,822
| false
| null |
package com.joaquimley.transporteta.presentation.home.favorite
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.joaquimley.transporteta.domain.interactor.transport.favorites.ClearAllTransportsAsFavoriteUseCase
import com.joaquimley.transporteta.domain.interactor.transport.favorites.GetFavoritesUseCase
import com.joaquimley.transporteta.domain.interactor.transport.favorites.MarkTransportAsFavoriteUseCase
import com.joaquimley.transporteta.domain.interactor.transport.favorites.MarkTransportAsNoFavoriteUseCase
import com.joaquimley.transporteta.domain.interactor.transport.CancelEtaRequestUseCase
import com.joaquimley.transporteta.domain.interactor.transport.RequestEtaUseCase
import com.joaquimley.transporteta.presentation.mapper.PresentationTransportMapper
abstract class FavoritesViewModelFactory(private val getFavoritesUseCase: GetFavoritesUseCase,
private val markTransportAsFavoriteUseCase: MarkTransportAsFavoriteUseCase,
private val markTransportAsNoFavoriteUseCase: MarkTransportAsNoFavoriteUseCase,
private val clearAllTransportsAsFavoriteUseCase: ClearAllTransportsAsFavoriteUseCase,
private val requestEtaUseCase: RequestEtaUseCase,
private val cancelEtaRequestUseCase: CancelEtaRequestUseCase,
private val mapper: PresentationTransportMapper) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return create() as T
}
fun create(): FavoritesViewModel {
return create(getFavoritesUseCase,
markTransportAsFavoriteUseCase,
markTransportAsNoFavoriteUseCase,
clearAllTransportsAsFavoriteUseCase,
requestEtaUseCase,
cancelEtaRequestUseCase,
mapper)
}
abstract fun create(getFavoritesUseCase: GetFavoritesUseCase,
markTransportAsFavoriteUseCase: MarkTransportAsFavoriteUseCase,
markTransportAsNotNoFavoriteUseCase: MarkTransportAsNoFavoriteUseCase,
clearAllTransportsAsFavoriteUseCase: ClearAllTransportsAsFavoriteUseCase,
requestEtaUseCase: RequestEtaUseCase,
cancelEtaRequestUseCase: CancelEtaRequestUseCase,
presentationTransportMapper: PresentationTransportMapper): FavoritesViewModel
}
| 34
|
Kotlin
|
45
| 224
|
7c841a3b4e7f296e5b5e53eab6c7a9e84c2b3c61
| 2,645
|
transport-eta
|
Apache License 2.0
|
app/src/main/java/com/sleepysoft/gaminglife/activities/GLIDGenerationActivity.kt
|
SleepySoft
| 537,375,480
| false
|
{"Kotlin": 363016, "Python": 3483}
|
package com.sleepysoft.gaminglife.activities
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.method.ScrollingMovementMethod
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.sleepysoft.gaminglife.R
import com.sleepysoft.gaminglife.finishWithResult
import glcore.GlEncryption
import glcore.GlRoot
const val THRESHOLD_POW = 8
class GeneratePairActivity : AppCompatActivity() {
// var mPrevPoW = 0
var mExpectPoW = 0
val mQuitFlag = mutableListOf(false)
val mGlEncryption = GlEncryption()
var mCalculateGlIdThread = CalculateGlIdThread(8, mGlEncryption, mQuitFlag)
private var mHandler = Handler(Looper.getMainLooper())
private val mRunnable = Runnable { updateKeyGenInfo() }
lateinit var mSeekBarPoW: SeekBar
lateinit var mTextOutput: TextView
lateinit var mTextSeekPow: TextView
lateinit var mButtonGenerate: Button
lateinit var mButtonAcceptGlId: Button
lateinit var mButtonCancelGenerate: Button
class CalculateGlIdThread(
var pow: Int,
val mGlEncryption: GlEncryption,
val quitFlag: List< Boolean >) : Thread("CalculateGlIdThread") {
@RequiresApi(Build.VERSION_CODES.O)
override fun run() = mGlEncryption.createKeyPair(pow, quitFlag).let { }
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_generate_key_pair)
mTextSeekPow = findViewById(R.id.id_text_current_pow)
mSeekBarPoW = findViewById(R.id.id_seek_pow)
mSeekBarPoW.run {
min = 8
max = 32
setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (progress < 10) {
mTextSeekPow.text = " %d".format(progress)
} else {
mTextSeekPow.text = "%d".format(progress)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
}
})
}
mTextOutput = findViewById(R.id.id_text_output)
// https://www.geeksforgeeks.org/how-to-make-textview-scrollable-in-android/
mTextOutput.movementMethod = ScrollingMovementMethod()
mButtonGenerate = findViewById(R.id.id_button_generate_glid)
mButtonGenerate.setOnClickListener {
if (!mCalculateGlIdThread.isAlive) {
mQuitFlag[0] = false
// mPrevPoW = 0
mExpectPoW = mSeekBarPoW.progress
mCalculateGlIdThread = CalculateGlIdThread(
mExpectPoW, mGlEncryption, mQuitFlag).apply { start() }
mTextOutput.text = ""
mButtonGenerate.isEnabled = false
mButtonCancelGenerate.isEnabled = true
mHandler.postDelayed(mRunnable, 100)
}
}
mButtonCancelGenerate = findViewById(R.id.id_button_cancel_generate)
mButtonCancelGenerate.setOnClickListener {
if (mCalculateGlIdThread.isAlive) {
mQuitFlag[0] = true
}
}
mButtonAcceptGlId = findViewById(R.id.id_button_accept)
mButtonAcceptGlId.setOnClickListener {
GlRoot.systemConfig.GLID = glId()
GlRoot.systemConfig.mainKeyPair = mGlEncryption.powKeyPair
GlRoot.systemConfig.saveSystemConfig()
finishWithResult(mapOf(), true)
}
}
override fun onDestroy() {
super.onDestroy()
if (mCalculateGlIdThread.isAlive) {
mQuitFlag[0] = true
}
}
fun updateKeyGenInfo() {
val text = resources.getString(R.string.FORMAT_GLID_GEN_LOG)
mTextOutput.text = text.format(mGlEncryption.calcLoop, mGlEncryption.keyPairPow)
/* if (mPrevPoW != mGlEncryption.keyPairPow) {
mPrevPoW = mGlEncryption.keyPairPow
}*/
if (mCalculateGlIdThread.isAlive) {
mHandler.postDelayed(mRunnable, 100)
} else {
mButtonGenerate.isEnabled = true
mButtonCancelGenerate.isEnabled = false
if (mGlEncryption.keyPairPow >= THRESHOLD_POW) {
// Got the expect PoW
val glId = glId()
val text = resources.getString(R.string.FORMAT_GLID_GEN_SUCCESS)
mTextOutput.append("---------------------------------------------\n")
mTextOutput.append(text.format(glId, mGlEncryption.keyPairPow))
mTextOutput.append("---------------------------------------------\n")
mButtonAcceptGlId.isEnabled = true
} else {
val text = resources.getString(R.string.FORMAT_GLID_GEN_FAIL)
mTextOutput.append(text)
mButtonAcceptGlId.isEnabled = false
}
}
}
// ---------------------------------------------------------------------------------------------
private fun glId() : String =
mGlEncryption.powKeyPair.publicKey?.let {
val pubKeySha = GlEncryption.dataSha256(it.encoded)
val glId = GlEncryption.glidFromPublicKeyHash(pubKeySha)
glId
} ?: ""
}
| 0
|
Kotlin
|
1
| 1
|
ec89ed131c8363329d664ab25eb4e7654ac0083f
| 5,663
|
GamingLife
|
Apache License 2.0
|
compiler/ir/serialization.common/src/org/jetbrains/kotlin/backend/common/linkage/partial/MissingDeclarationStubGenerator.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.common.linkage.partial
import org.jetbrains.kotlin.backend.common.linkage.partial.PartialLinkageUtils.guessName
import org.jetbrains.kotlin.backend.common.overrides.FakeOverrideBuilder
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.ir.IrBuiltIns
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrExternalPackageFragmentImpl
import org.jetbrains.kotlin.ir.linkage.IrProvider
import org.jetbrains.kotlin.ir.linkage.partial.PartiallyLinkedDeclarationOrigin
import org.jetbrains.kotlin.ir.symbols.*
import org.jetbrains.kotlin.ir.util.createImplicitParameterDeclarationWithWrappedDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.types.error.ErrorUtils
/**
* Generates the simplest possible stubs for missing declarations.
*
* Note: This is a special type of [IrProvider]. It should not be used in row with other IR providers, because it may bring to
* undesired situation when stubs for unbound fake override symbols are generated even before the corresponding call of
* [FakeOverrideBuilder.provideFakeOverrides] is made leaving no chance for proper linkage of fake overrides. This IR provider
* should be applied only after the fake overrides generation.
*/
internal class MissingDeclarationStubGenerator(private val builtIns: IrBuiltIns) : IrProvider {
private val commonParent by lazy {
IrExternalPackageFragmentImpl.createEmptyExternalPackageFragment(ErrorUtils.errorModule, FqName.ROOT)
}
private var declarationsToPatch = arrayListOf<IrDeclaration>()
private val stubbedSymbols = hashSetOf<IrSymbol>()
val allStubbedSymbols: Set<IrSymbol> get() = stubbedSymbols
fun grabDeclarationsToPatch(): Collection<IrDeclaration> {
val result = declarationsToPatch
declarationsToPatch = arrayListOf()
return result
}
override fun getDeclaration(symbol: IrSymbol): IrDeclaration {
require(!symbol.isBound)
stubbedSymbols.add(symbol)
return when (symbol) {
is IrClassSymbol -> generateClass(symbol)
is IrSimpleFunctionSymbol -> generateSimpleFunction(symbol)
is IrConstructorSymbol -> generateConstructor(symbol)
is IrPropertySymbol -> generateProperty(symbol)
is IrEnumEntrySymbol -> generateEnumEntry(symbol)
is IrTypeAliasSymbol -> generateTypeAlias(symbol)
else -> throw NotImplementedError("Generation of stubs for ${symbol::class.java} is not supported yet")
}
}
private fun generateClass(symbol: IrClassSymbol): IrClass {
return builtIns.irFactory.createClass(
startOffset = UNDEFINED_OFFSET,
endOffset = UNDEFINED_OFFSET,
origin = PartiallyLinkedDeclarationOrigin.MISSING_DECLARATION,
symbol = symbol,
name = symbol.guessName(),
kind = ClassKind.CLASS,
visibility = DescriptorVisibilities.DEFAULT_VISIBILITY,
modality = Modality.OPEN
).apply {
setCommonParent()
createImplicitParameterDeclarationWithWrappedDescriptor()
}
}
private fun generateSimpleFunction(symbol: IrSimpleFunctionSymbol): IrSimpleFunction {
return builtIns.irFactory.createFunction(
startOffset = UNDEFINED_OFFSET,
endOffset = UNDEFINED_OFFSET,
origin = PartiallyLinkedDeclarationOrigin.MISSING_DECLARATION,
symbol = symbol,
name = symbol.guessName(),
visibility = DescriptorVisibilities.DEFAULT_VISIBILITY,
modality = Modality.FINAL,
returnType = builtIns.nothingType,
isInline = false,
isExternal = false,
isTailrec = false,
isSuspend = false,
isOperator = false,
isInfix = false,
isExpect = false
).setCommonParent()
}
private fun generateConstructor(symbol: IrConstructorSymbol): IrConstructor {
return builtIns.irFactory.createConstructor(
startOffset = UNDEFINED_OFFSET,
endOffset = UNDEFINED_OFFSET,
origin = PartiallyLinkedDeclarationOrigin.MISSING_DECLARATION,
symbol = symbol,
name = SpecialNames.INIT,
visibility = DescriptorVisibilities.DEFAULT_VISIBILITY,
returnType = builtIns.nothingType,
isInline = false,
isExternal = false,
isPrimary = false,
isExpect = false,
).setCommonParent()
}
private fun generateProperty(symbol: IrPropertySymbol): IrProperty {
return builtIns.irFactory.createProperty(
startOffset = UNDEFINED_OFFSET,
endOffset = UNDEFINED_OFFSET,
origin = PartiallyLinkedDeclarationOrigin.MISSING_DECLARATION,
symbol = symbol,
name = symbol.guessName(),
visibility = DescriptorVisibilities.DEFAULT_VISIBILITY,
modality = Modality.FINAL,
isVar = false,
isConst = false,
isLateinit = false,
isDelegated = false,
isExternal = false,
isExpect = false
).setCommonParent()
}
private fun generateEnumEntry(symbol: IrEnumEntrySymbol): IrEnumEntry {
return builtIns.irFactory.createEnumEntry(
startOffset = UNDEFINED_OFFSET,
endOffset = UNDEFINED_OFFSET,
origin = PartiallyLinkedDeclarationOrigin.MISSING_DECLARATION,
symbol = symbol,
name = symbol.guessName()
).setCommonParent()
}
private fun generateTypeAlias(symbol: IrTypeAliasSymbol): IrTypeAlias {
return builtIns.irFactory.createTypeAlias(
startOffset = UNDEFINED_OFFSET,
endOffset = UNDEFINED_OFFSET,
symbol = symbol,
name = symbol.guessName(),
visibility = DescriptorVisibilities.DEFAULT_VISIBILITY,
expandedType = builtIns.nothingType,
isActual = true,
origin = PartiallyLinkedDeclarationOrigin.MISSING_DECLARATION,
).setCommonParent()
}
private fun <T : IrDeclaration> T.setCommonParent(): T {
parent = commonParent
declarationsToPatch += this
return this
}
private fun IrSymbol.guessName(): Name =
signature?.guessName(nameSegmentsToPickUp = 1)?.let(Name::guessByFirstCharacter) ?: PartialLinkageUtils.UNKNOWN_NAME
}
| 182
| null |
5771
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 7,013
|
kotlin
|
Apache License 2.0
|
app/src/main/java/be/digitalia/fosdem/activities/ExternalBookmarksActivity.kt
|
cbeyls
| 15,915,146
| false
| null |
package be.digitalia.fosdem.activities
import android.os.Bundle
import androidx.fragment.app.add
import androidx.fragment.app.commit
import be.digitalia.fosdem.R
import be.digitalia.fosdem.fragments.ExternalBookmarksListFragment
import be.digitalia.fosdem.utils.extractNfcAppData
import be.digitalia.fosdem.utils.hasNfcAppData
import be.digitalia.fosdem.utils.toBookmarks
class ExternalBookmarksActivity : SimpleToolbarActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
if (savedInstanceState == null) {
val intent = intent
val bookmarkIds = if (intent.hasNfcAppData()) {
intent.extractNfcAppData().toBookmarks()
} else null
if (bookmarkIds == null) {
// Invalid data format, exit
finish()
return
}
supportFragmentManager.commit {
add<ExternalBookmarksListFragment>(R.id.content,
args = ExternalBookmarksListFragment.createArguments(bookmarkIds))
}
}
}
}
| 21
|
Kotlin
|
91
| 131
|
5095210e4e2530d4e6be773f499749ffdbf520bb
| 1,188
|
fosdem-companion-android
|
Apache License 2.0
|
tests/unit/src/test/kotlin/test/java/failure/core/method/style/named/QueryTest.kt
|
zcdsg
| 462,998,363
| true
|
{"Kotlin": 206989, "Java": 106166, "ANTLR": 1321, "Shell": 111}
|
package test.java.failure.core.method.style.named
import org.junit.Test
import test.BaseTest
import test.Person
import test.java.failure.core.method.style.named.prefix.QueryNotReturnCollectionBadDao
import test.java.failure.core.method.style.named.prefix.QueryNotReturnEntityCollectionBadDao
import test.java.failure.core.method.style.named.prefix.QueryOneNotReturnEntityBadDao
/**
*
* @author afezeria
*/
class QueryTest : BaseTest() {
@Test
fun `return type of the query method is not collection`() {
compileFailure<QueryNotReturnCollectionBadDao> {
assertErrorMessageEquals("The return type of method must be a collection")
}
}
@Test
fun `return type of method query is not collection of crudEntity`() {
compileFailure<QueryNotReturnEntityCollectionBadDao> {
assertErrorMessageEquals("The element type of the return type must be a ${Person::class.qualifiedName}")
}
}
@Test
fun `return type of method queryOne is not crudEntity`() {
compileFailure<QueryOneNotReturnEntityBadDao> {
assertErrorMessageEquals("The return type of method must be ${Person::class.qualifiedName}")
}
}
}
| 0
| null |
0
| 1
|
162536681775ccc02d8fa707bdc68287fd92abbe
| 1,209
|
freedao
|
Apache License 2.0
|
kotlin-node/src/jsMain/generated/node/crypto/CipherCCMSetAADOptions.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 12635434, "JavaScript": 423801}
|
// Generated by Karakum - do not modify it manually!
package node.crypto
sealed external interface CipherCCMSetAADOptions {
var plaintextLength: Double
}
| 38
|
Kotlin
|
162
| 1,347
|
997ed3902482883db4a9657585426f6ca167d556
| 160
|
kotlin-wrappers
|
Apache License 2.0
|
Corona-Warn-App/src/deviceForTesters/java/de/rki/coronawarnapp/test/submission/ui/SubmissionTestFragmentViewModel.kt
|
corona-warn-app
| 268,027,139
| false
| null |
package de.rki.coronawarnapp.test.submission.ui
import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.liveData
import com.google.android.gms.nearby.exposurenotification.TemporaryExposureKey
import com.google.gson.Gson
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import de.rki.coronawarnapp.appconfig.AppConfigProvider
import de.rki.coronawarnapp.appconfig.ConfigData
import de.rki.coronawarnapp.main.CWASettings
import de.rki.coronawarnapp.srs.core.AndroidIdProvider
import de.rki.coronawarnapp.srs.core.model.SrsSubmissionResponse
import de.rki.coronawarnapp.srs.core.model.SrsSubmissionType
import de.rki.coronawarnapp.srs.core.repository.SrsSubmissionRepository
import de.rki.coronawarnapp.srs.core.storage.SrsDevSettings
import de.rki.coronawarnapp.srs.core.storage.SrsSubmissionSettings
import de.rki.coronawarnapp.submission.data.tekhistory.TEKHistoryUpdater
import de.rki.coronawarnapp.util.TimeStamper
import de.rki.coronawarnapp.util.coroutine.DispatcherProvider
import de.rki.coronawarnapp.util.serialization.BaseGson
import de.rki.coronawarnapp.util.ui.SingleLiveEvent
import de.rki.coronawarnapp.util.viewmodel.CWAViewModel
import de.rki.coronawarnapp.util.viewmodel.SimpleCWAViewModelFactory
import timber.log.Timber
import java.time.Instant
class SubmissionTestFragmentViewModel @AssistedInject constructor(
@BaseGson baseGson: Gson,
timeStamper: TimeStamper,
androidIdProvider: AndroidIdProvider,
dispatcherProvider: DispatcherProvider,
tekHistoryUpdaterFactory: TEKHistoryUpdater.Factory,
private val srsDevSettings: SrsDevSettings,
private val appConfigProvider: AppConfigProvider,
private val srsSubmissionSettings: SrsSubmissionSettings,
private val srsSubmissionRepository: SrsSubmissionRepository,
private val cwaSettings: CWASettings,
) : CWAViewModel(dispatcherProvider = dispatcherProvider) {
val srsSubmissionResult = SingleLiveEvent<SrsSubmissionResult>()
val otpData = srsSubmissionSettings.otp.asLiveData2()
val mostRecentSubmissionDate = srsSubmissionSettings.mostRecentSubmissionTime.asLiveData2()
val androidId = liveData { emit(androidIdProvider.getAndroidId()) }
val deviceTimeState = srsDevSettings.deviceTimeState.asLiveData2()
val checkLocalPrerequisites = srsDevSettings.checkLocalPrerequisites.asLiveData2()
val forceAndroidIdAcceptance = srsDevSettings.forceAndroidIdAcceptance.asLiveData2()
val firstReliableTime = cwaSettings.firstReliableDeviceTime.asLiveData2()
private val exportJson = baseGson.newBuilder().apply { setPrettyPrinting() }.create()
private val tekHistoryUpdater = tekHistoryUpdaterFactory.create(
object : TEKHistoryUpdater.Callback {
override fun onTEKAvailable(teks: List<TemporaryExposureKey>) {
Timber.d("TEKs are available: %s", teks)
val now = timeStamper.nowUTC
val tekList = teks.map { key ->
TEKHistoryItem(
obtainedAt = now,
key = key
)
}.sortedBy { it.obtainedAt }
tekHistory.postValue(tekList)
}
override fun onTEKPermissionDeclined() {
Timber.d("Permission were declined.")
}
override fun onTracingConsentRequired(onConsentResult: (given: Boolean) -> Unit) {
showTracingConsentDialog.postValue(onConsentResult)
}
override fun onPermissionRequired(permissionRequest: (Activity) -> Unit) {
permissionRequestEvent.postValue(permissionRequest)
}
override fun onError(error: Throwable) {
errorEvents.postValue(error)
}
}
)
val errorEvents = SingleLiveEvent<Throwable>()
val shareTEKsEvent = SingleLiveEvent<TEKExport>()
val permissionRequestEvent = SingleLiveEvent<(Activity) -> Unit>()
val showTracingConsentDialog = SingleLiveEvent<(Boolean) -> Unit>()
val tekHistory = MutableLiveData<List<TEKHistoryItem>>()
fun submit() = launch {
try {
val result = srsSubmissionRepository.submit(
type = SrsSubmissionType.SRS_SELF_TEST,
keys = tekHistory.value.orEmpty().map { it.key }
)
val event = when (result) {
SrsSubmissionResponse.Success -> Success
is SrsSubmissionResponse.TruncatedKeys -> TruncatedSubmission(result.days)
}
srsSubmissionResult.postValue(event)
} catch (e: Exception) {
Timber.e(e, "submit()")
srsSubmissionResult.postValue(Error(e))
}
}
fun resetMostRecentSubmission() = launch {
srsSubmissionSettings.resetMostRecentSubmission()
}
fun resetOtp() = launch {
srsSubmissionSettings.resetOtp()
}
fun checkLocalPrerequisites(check: Boolean) = launch {
srsDevSettings.checkLocalPrerequisites(check)
}
fun forceAndroidIdAcceptance(force: Boolean) = launch {
srsDevSettings.forceAndroidIdAcceptance(force)
}
fun deviceTimeState(state: ConfigData.DeviceTimeState?) = launch {
srsDevSettings.deviceTimeState(state)
appConfigProvider.apply {
reset()
getAppConfig()
}
}
fun updateStorage() {
tekHistoryUpdater.getTeksForTesting()
}
fun emailTEKs() {
tekHistory.value?.toExportedKeys()?.let {
launch {
val tekExport = TEKExport(
exportText = exportJson.toJson(it)
)
shareTEKsEvent.postValue(tekExport)
}
}
}
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
return tekHistoryUpdater.handleActivityResult(requestCode, resultCode, data).also {
Timber.d("tekHistoryUpdater.handleActivityResult(): %s", it)
}
}
fun clearTekCache() = launch {
tekHistoryUpdater.clearTekCache()
}
fun updateFirstReliableTime(time: Long) = launch {
cwaSettings.updateFirstReliableDeviceTime(Instant.ofEpochMilli(time))
}
@AssistedFactory
interface Factory : SimpleCWAViewModelFactory<SubmissionTestFragmentViewModel>
}
sealed interface SrsSubmissionResult
data class TruncatedSubmission(val numberOfDays: String?) : SrsSubmissionResult
data class Error(val cause: Exception) : SrsSubmissionResult
object Success : SrsSubmissionResult
| 6
|
Kotlin
|
504
| 2,486
|
7b0eee8d53a090ee0ca585c6a90c4cec570e51d6
| 6,626
|
cwa-app-android
|
Apache License 2.0
|
Patterns/CreationMode/singleton_mode/src/com/fausto/singleton/SingletonType.kt
|
FaustoFan-FB
| 417,426,537
| false
|
{"Kotlin": 37636, "Java": 7800}
|
package com.fausto.singleton
import java.lang.reflect.Method
import kotlin.concurrent.thread
/**
* @author: fausto
* @date: 2021/10/16 14:50
* @description: 饿汉式与懒汉式单例模式
*/
/**
* 饿汉式线程安全
*/
object Singleton0
/**
* 懒汉式线程不安全(违背单例模式,不推荐使用)
*/
class Singleton1 private constructor(){
companion object{
private var mInstance: Singleton1? = null
get(){
if (field == null) field = Singleton1()
return field
}
fun getInstance(): Singleton1 {
return mInstance!!
}
}
}
/**
* 懒汉式线程安全 (效率降低,不推荐)
*/
class Singleton2 private constructor(){
companion object{
private var mInstance: Singleton2? = null
@Synchronized
fun getInstance(): Singleton2 {
return mInstance ?: Singleton2().apply {
mInstance = this
}
}
}
}
/**
* 双重校验锁(推荐)
*/
class Singleton3 private constructor(){
companion object{
val instance: Singleton3 by lazy(mode = LazyThreadSafetyMode.PUBLICATION) {
Singleton3()
}
}
}
/**
* 静态内部类
*/
class Singleton4 private constructor(){
private object SingletonHolder{
val holder = Singleton4()
}
companion object{
val instance = SingletonHolder.holder
}
}
/**
* 枚举方式
*/
enum class Singleton{
INSTANCE
}
fun main() {
//饿汉式
//println(Singleton0)
//println(Singleton0)
println(Singleton.INSTANCE.hashCode())
//懒汉式
//println(Singleton1.getInstance())
//println(Singleton1.getInstance())
//threadTest(1000 , Singleton2)
}
fun<T> threadTest(num: Int , type: T){
var getInstance: Method = type!!::class.java.getMethod("getInstance")
thread {
run {
for (i in 0..num){
println("${Thread.currentThread().name}==>${getInstance.invoke(type)}---$i")
}
}
}
thread {
run {
for (i in 0..num){
println("${Thread.currentThread().name}==>${getInstance.invoke(type)}---$i")
}
}
}
thread {
run {
for (i in 0..num){
println("${Thread.currentThread().name}==>${getInstance.invoke(type)}---$i")
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5a91cfbdfd981914e88c64679439754af76bc8c0
| 2,311
|
DesignPattern
|
Apache License 2.0
|
app/src/main/java/com/vaibhav/nextlife/ui/homeScreen/feedScreen/FeedFragment.kt
|
Vaibhav2002
| 351,128,652
| false
| null |
package com.vaibhav.nextlife.ui.homeScreen.feedScreen
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.vaibhav.nextlife.R
import com.vaibhav.nextlife.databinding.FragmentFeedBinding
import com.vaibhav.nextlife.ui.auth.AuthorizationActivity
import com.vaibhav.nextlife.ui.homeScreen.HomeViewModel
import com.vaibhav.nextlife.utils.Constants
import com.vaibhav.nextlife.utils.Resource
import com.vaibhav.nextlife.utils.adapters.BloodGroupAdapter
import com.vaibhav.nextlife.utils.adapters.RequirementsAdapter
import com.vaibhav.nextlife.utils.showErrorToastLight
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber
@AndroidEntryPoint
class FeedFragment : Fragment(R.layout.fragment_feed) {
private lateinit var binding: FragmentFeedBinding
private val sharedViewModel: HomeViewModel by activityViewModels()
private lateinit var bloodGroupAdapter: BloodGroupAdapter
private lateinit var requirementsAdapter: RequirementsAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentFeedBinding.bind(view)
bloodGroupAdapter = BloodGroupAdapter(requireContext(), onCLickListener = {
if (it.isChecked) {
sharedViewModel.setBloodType(it.text.replace(" ", ""))
sharedViewModel.fetchAllRequirements(it.text.replace(" ", ""))
} else {
sharedViewModel.setBloodType("")
sharedViewModel.fetchAllRequirements("")
}
Timber.d(it.isChecked.toString())
})
setHasOptionsMenu(true)
requirementsAdapter = RequirementsAdapter {
val action = FeedFragmentDirections.actionFeedFragmentToRequirementDetailFragment(it)
findNavController().navigate(action)
}
binding.addFab.setOnClickListener {
findNavController().navigate(R.id.action_feedFragment_to_postFragment)
}
binding.refresh.setOnRefreshListener {
binding.refresh.isRefreshing = true
val type = bloodGroupAdapter.getPressedBloodGroup()
type?.let {
sharedViewModel.fetchAllRequirements(it.text.replace(" ", ""))
} ?: sharedViewModel.fetchAllRequirements("")
binding.refresh.isRefreshing = false
}
sharedViewModel.allRequests.observe(viewLifecycleOwner, {
when (it) {
is Resource.Loading -> binding.loadingAnim.isVisible = true
is Resource.Success -> {
binding.loadingAnim.isVisible = false
requirementsAdapter.submitList(it.data)
if (it.data.isNullOrEmpty())
Toast.makeText(
requireContext(),
"No requirements found in your state",
Toast.LENGTH_SHORT
).show()
}
is Resource.Error -> {
binding.loadingAnim.isVisible = false
requireActivity().showErrorToastLight(
"Error loading requirements",
it.message ?: "Oops something went wrong"
)
}
}
})
binding.bloodGroupRecycle.apply {
adapter = bloodGroupAdapter
setHasFixedSize(true)
}
binding.requirementsRecycle.apply {
adapter = requirementsAdapter
setHasFixedSize(false)
}
bloodGroupAdapter.submitList(Constants.bloodGroups)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.app_bar_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.logout -> {
sharedViewModel.logout()
requireActivity().startActivity(
Intent(
requireContext(),
AuthorizationActivity::class.java
)
)
requireActivity().finish()
return true
}
R.id.profile -> {
findNavController().navigate(R.id.action_feedFragment_to_profileFragment)
return true
}
else -> return false
}
}
}
| 0
|
Kotlin
|
0
| 3
|
5a8a68e365f9ae9d703a884ab610d6c48f2e8c39
| 4,848
|
NextLife
|
Apache License 2.0
|
fileboxlib/src/main/java/com/lyrebirdstudio/fileboxlib/security/ConcealInitializer.kt
|
lyrebirdstudio
| 238,207,373
| false
| null |
package com.lyrebirdstudio.fileboxlib.security
import android.content.Context
import com.facebook.android.crypto.keychain.AndroidConceal
import com.facebook.android.crypto.keychain.SharedPrefsBackedKeyChain
import com.facebook.crypto.Crypto
import com.facebook.crypto.CryptoConfig
import com.facebook.soloader.SoLoader
import java.lang.Exception
object ConcealInitializer {
private var isNativeLoaderInitialized = false
private var crypto: Crypto? = null
@Synchronized
fun initialize(context: Context): Crypto {
if (isNativeLoaderInitialized.not()) {
isNativeLoaderInitialized = try {
SoLoader.init(context, false)
true
} catch (e: Exception) {
false
}
}
if (crypto == null) {
val keyChain = SharedPrefsBackedKeyChain(context, CryptoConfig.KEY_256)
crypto = AndroidConceal.get().createDefaultCrypto(keyChain)
}
return crypto!!
}
fun isInitialized(): Boolean {
return isNativeLoaderInitialized && crypto != null
}
}
| 3
|
Kotlin
|
24
| 312
|
0cfaa0d0b05ed5d25d87eed88de224f630ba91e6
| 1,106
|
filebox
|
Apache License 2.0
|
src/main/kotlin/com/github/ivan_osipov/clabo/api/model/CallbackGame.kt
|
ivan-osipov
| 92,181,671
| false
| null |
package com.github.ivan_osipov.clabo.api.model
class CallbackGame
| 31
|
Kotlin
|
3
| 6
|
943583bce73aad8479c1be8d7e6f6fe74807058e
| 66
|
Clabo
|
Apache License 2.0
|
kafka-reference-impl/judge/src/main/kotlin/validateMove.kt
|
Terkwood
| 191,042,808
| false
| null |
fun MoveCommandGameState.isValid(): Boolean {
val move = this.moveCmd
val game = this.gameState
val correctPlayer = move.player == game.playerUp
val coord = move.coord
val passing = coord == null
val coordExists: Boolean by lazy {
if (coord != null) {
val size = game.board.size
val (x, y) = coord
size > x && size > y && x >= 0 && y >= 0
} else false
}
val validCoord: Boolean by lazy {
coordExists && game.board.pieces[move.coord] == null
}
return correctPlayer && (passing || validCoord)
}
| 83
|
Rust
|
7
| 66
|
ec01dc3dae54e1e248d540d442caa1731f2822e4
| 594
|
BUGOUT
|
MIT License
|
zircon.jvm.libgdx/src/main/kotlin/org/hexworks/zircon/api/LibgdxApplications.kt
|
Xanik
| 282,687,897
| false
| null |
package org.hexworks.zircon.api
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration
import org.hexworks.zircon.api.application.AppConfig
import org.hexworks.zircon.api.application.Application
import org.hexworks.zircon.api.grid.TileGrid
import org.hexworks.zircon.internal.application.LibgdxApplication
import org.hexworks.zircon.internal.application.LibgdxGame
object LibgdxApplications {
/**
* Builds a new [Application] using the given `appConfig`.
*/
@JvmStatic
@JvmOverloads
fun buildApplication(
appConfig: AppConfig = AppConfig.defaultConfiguration(),
libgdxConfig: LwjglApplicationConfiguration = LwjglApplicationConfiguration()
): LibgdxApplication {
return makeLibgdxGame(appConfig, libgdxConfig).libgdxApplication
}
/**
* Builds and starts a new [Application] from the given `appConfig`.
*/
@JvmStatic
@JvmOverloads
fun startApplication(
appConfig: AppConfig = AppConfig.defaultConfiguration(),
libgdxConfig: LwjglApplicationConfiguration = LwjglApplicationConfiguration()
): LibgdxApplication {
with(makeLibgdxGame(appConfig, libgdxConfig)) {
start()
return this.libgdxApplication
}
}
/**
* Builds JUST a new [Application], not a libgdx game
*/
@JvmStatic
@JvmOverloads
fun buildRawApplication(appConfig: AppConfig = AppConfig.defaultConfiguration()): LibgdxApplication {
return LibgdxApplication(appConfig)
}
/**
* Starts JUST a new [Application], not a libgdx game
*/
@JvmStatic
@JvmOverloads
fun startRawApplication(appConfig: AppConfig = AppConfig.defaultConfiguration()): LibgdxApplication {
return LibgdxApplication(appConfig).also {
it.start()
}
}
/**
* Builds and starts a new [Application] and returns its [TileGrid].
*/
@JvmStatic
@JvmOverloads
fun startTileGrid(
appConfig: AppConfig = AppConfig.defaultConfiguration(),
libgdxConfig: LwjglApplicationConfiguration = LwjglApplicationConfiguration()
): TileGrid {
val maxTries = 10
var currentTryCount = 0
val game = makeLibgdxGame(appConfig, libgdxConfig)
game.start()
var notInitialized = true
while (notInitialized) {
try {
game.libgdxApplication
notInitialized = false
} catch (e: Exception) {
if (currentTryCount >= maxTries) {
throw e
} else {
currentTryCount++
Thread.sleep(1000)
}
}
}
return game.libgdxApplication.tileGrid
}
/**
* Creates a [LibgdxGame] that contains a built and started [Application]
*
* Note that the Zircon `appConfig` fields title, size, and fpsLimit
* will override the Libgdx `LwjglApplicationConfiguration` fields
* title, width and height, and foregroundFPS respectively.
*/
@JvmStatic
private fun makeLibgdxGame(
appConfig: AppConfig = AppConfig.defaultConfiguration(),
libgdxConfig: LwjglApplicationConfiguration = LwjglApplicationConfiguration()
): LibgdxGame {
libgdxConfig.title = appConfig.title
libgdxConfig.width = appConfig.size.width * appConfig.defaultTileset.width
libgdxConfig.height = appConfig.size.height * appConfig.defaultTileset.height
libgdxConfig.foregroundFPS = appConfig.fpsLimit
libgdxConfig.useGL30 = false
return LibgdxGame.build(appConfig, libgdxConfig)
}
}
| 1
| null |
1
| 2
|
bf435cddeb55f7c3a9da5dd5c29be13af8354d0f
| 3,663
|
zircon
|
Apache License 2.0
|
app/src/main/java/com/example/pockedex/ui/MainActivity.kt
|
gilsonMartins
| 535,386,240
| false
| null |
package com.example.pockedex.ui
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.pockedex.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}
| 0
|
Kotlin
|
0
| 2
|
20ddf324db4f8e4c22e3512abf99e6a28d327fc1
| 472
|
pokedex-e
|
Apache License 2.0
|
app/src/main/java/com/hdev/qrcode/barcode/reader/ui/screens/create/ListCreateItem.kt
|
Hendriyawan
| 538,512,765
| false
| null |
package com.hdev.qrcode.barcode.reader.ui.screens.create
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
data class ItemCreate(val icon: ImageVector, val title: String)
@Composable
fun ItemCreateQR(item: ItemCreate) {
Card(modifier = Modifier
.padding(5.dp)
.clickable { },
shape = RoundedCornerShape(6.dp),
backgroundColor = MaterialTheme.colors.surface) {
Column(modifier = Modifier
.padding(5.dp)
.padding(5.dp), horizontalAlignment = Alignment.CenterHorizontally) {
Icon(imageVector = item.icon, contentDescription = item.title)
Text(text = item.title, textAlign = TextAlign.Center)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9784769016de40a5d673194000c82cfa6789c660
| 1,270
|
ComposeQRReader
|
Apache License 2.0
|
app/src/main/java/com/breezelinktelecom/features/viewAllOrder/interf/NewOrderSizeQtyDelOnClick.kt
|
DebashisINT
| 851,532,207
| false
|
{"Kotlin": 15739075, "Java": 1026627}
|
package com.breezelinktelecom.features.viewAllOrder.interf
import com.breezelinktelecom.app.domain.NewOrderGenderEntity
import com.breezelinktelecom.features.viewAllOrder.model.ProductOrder
import java.text.FieldPosition
interface NewOrderSizeQtyDelOnClick {
fun sizeQtySelListOnClick(product_size_qty: ArrayList<ProductOrder>)
fun sizeQtyListOnClick(product_size_qty: ProductOrder,position: Int)
}
| 0
|
Kotlin
|
0
| 0
|
6b0e10f53cfab02f3790b9064bd705ee3dc87fef
| 408
|
LinkTelecom
|
Apache License 2.0
|
tracing/tracing-ktx/src/main/java/androidx/tracing/Trace.kt
|
RikkaW
| 389,105,112
| true
|
{"Java": 49060640, "Kotlin": 36832495, "Python": 336507, "AIDL": 179831, "Shell": 150493, "C++": 38342, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343}
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.tracing
/**
* Wrap the specified [block] in calls to [Trace.beginSection] (with the supplied [label])
* and [Trace.endSection].
*
* @param label A name of the code section to appear in the trace.
* @param block A block of code which is being traced.
*/
inline fun <T> trace(label: String, crossinline block: () -> T): T {
try {
Trace.beginSection(label)
return block()
} finally {
Trace.endSection()
}
}
/**
* Wrap the specified [block] in calls to [Trace.beginAsyncSection] (with the supplied [methodName]
* and [cookie]) and [Trace.endAsyncSection].
*
* @param methodName The method name to appear in the trace.
* @param cookie Unique identifier for distinguishing simultaneous events
*/
suspend inline fun <T> traceAsync(
methodName: String,
cookie: Int,
crossinline block: suspend () -> T
): T {
try {
Trace.beginAsyncSection(methodName, cookie)
return block()
} finally {
Trace.endAsyncSection(methodName, cookie)
}
}
| 0
|
Java
|
0
| 7
|
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
| 1,655
|
androidx
|
Apache License 2.0
|
kotlin/android/app/src/main/java/dev/firezone/android/tunnel/data/TunnelRepositoryImpl.kt
|
firezone
| 257,787,813
| false
|
{"Elixir": 2035829, "Rust": 551474, "HCL": 192926, "TypeScript": 183237, "Swift": 165447, "Kotlin": 98421, "HTML": 34599, "JavaScript": 18522, "Dockerfile": 14089, "Shell": 11136, "CSS": 2434, "Makefile": 1525, "C": 334}
|
/* Licensed under Apache 2.0 (C) 2023 Firezone, Inc. */
package dev.firezone.android.tunnel.data
import android.content.SharedPreferences
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapter
import dev.firezone.android.tunnel.data.TunnelRepository.Companion.CONFIG_KEY
import dev.firezone.android.tunnel.data.TunnelRepository.Companion.RESOURCES_KEY
import dev.firezone.android.tunnel.data.TunnelRepository.Companion.ROUTES_KEY
import dev.firezone.android.tunnel.data.TunnelRepository.Companion.STATE_KEY
import dev.firezone.android.tunnel.model.Cidr
import dev.firezone.android.tunnel.model.Resource
import dev.firezone.android.tunnel.model.Tunnel
import dev.firezone.android.tunnel.model.TunnelConfig
import java.lang.Exception
import javax.inject.Inject
@OptIn(ExperimentalStdlibApi::class)
class TunnelRepositoryImpl
@Inject
constructor(
private val sharedPreferences: SharedPreferences,
private val moshi: Moshi,
) : TunnelRepository {
private val lock = Any()
override fun addListener(callback: SharedPreferences.OnSharedPreferenceChangeListener) {
sharedPreferences.registerOnSharedPreferenceChangeListener(callback)
}
override fun removeListener(callback: SharedPreferences.OnSharedPreferenceChangeListener) {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(callback)
}
override fun get(): Tunnel? =
synchronized(lock) {
return try {
Tunnel(
config = requireNotNull(getConfig()),
state = getState(),
routes = getRoutes(),
resources = getResources(),
)
} catch (e: Exception) {
null
}
}
override fun setConfig(config: TunnelConfig) {
synchronized(lock) {
val json = moshi.adapter<TunnelConfig>().toJson(config)
sharedPreferences.edit().putString(CONFIG_KEY, json).apply()
}
}
override fun getConfig(): TunnelConfig? =
synchronized(lock) {
val json = sharedPreferences.getString(CONFIG_KEY, "{}") ?: "{}"
return moshi.adapter<TunnelConfig>().fromJson(json)
}
override fun setState(state: Tunnel.State) {
synchronized(lock) {
sharedPreferences.edit().putString(STATE_KEY, state.name).apply()
}
}
override fun getState(): Tunnel.State {
val json = sharedPreferences.getString(STATE_KEY, null)
return json?.let { Tunnel.State.valueOf(it) } ?: Tunnel.State.Closed
}
override fun setResources(resources: List<Resource>) {
synchronized(lock) {
val json = moshi.adapter<List<Resource>>().toJson(resources)
sharedPreferences.edit().putString(RESOURCES_KEY, json).apply()
}
}
override fun getResources(): List<Resource> {
synchronized(lock) {
val json = sharedPreferences.getString(RESOURCES_KEY, "[]") ?: "[]"
return moshi.adapter<List<Resource>>().fromJson(json) ?: emptyList()
}
}
override fun addRoute(route: Cidr) {
synchronized(lock) {
getRoutes().toMutableList().run {
add(route)
val json = moshi.adapter<List<Cidr>>().toJson(this)
sharedPreferences.edit().putString(ROUTES_KEY, json).apply()
}
}
}
override fun removeRoute(route: Cidr) {
synchronized(lock) {
getRoutes().toMutableList().run {
remove(route)
val json = moshi.adapter<List<Cidr>>().toJson(this)
sharedPreferences.edit().putString(ROUTES_KEY, json).apply()
}
}
}
override fun getRoutes(): List<Cidr> =
synchronized(lock) {
val json = sharedPreferences.getString(ROUTES_KEY, "[]") ?: "[]"
return moshi.adapter<List<Cidr>>().fromJson(json) ?: emptyList()
}
override fun clearAll() {
synchronized(lock) {
sharedPreferences.edit().clear().apply()
}
}
}
| 170
|
Elixir
|
243
| 5,756
|
6113effb5e12011435e21c2be50e7d23fb28e802
| 4,450
|
firezone
|
Apache License 2.0
|
app/src/main/java/io/aethibo/rollback/framework/mvibase/IModel.kt
|
primepixel
| 383,722,476
| false
| null |
package io.aethibo.rollback.framework.mvibase
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.StateFlow
interface IModel<S : IState, I : IIntent> {
val intents: Channel<I>
val state: StateFlow<S>
}
| 0
|
Kotlin
|
1
| 1
|
f65162bb7ebb53828eb48b42c7a913e10ca66b9e
| 233
|
Rollback
|
Apache License 2.0
|
ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/spec/extension/stash/BitbucketServerProjectConfigurationPropertyExtensions.kt
|
nemerosa
| 19,351,480
| false
|
{"Git Config": 1, "Gradle Kotlin DSL": 67, "Markdown": 46, "Ignore List": 22, "Java Properties": 3, "Shell": 9, "Text": 3, "Batchfile": 2, "Groovy": 145, "JSON": 31, "JavaScript": 792, "JSON with Comments": 4, "GraphQL": 79, "Kotlin": 3960, "Java": 649, "HTML": 269, "PlantUML": 25, "AsciiDoc": 288, "XML": 9, "YAML": 33, "INI": 4, "Dockerfile": 7, "Less": 31, "CSS": 13, "SQL": 43, "Dotenv": 1, "Maven POM": 1, "SVG": 4}
|
package net.nemerosa.ontrack.kdsl.spec.extension.stash
import net.nemerosa.ontrack.json.parse
import net.nemerosa.ontrack.kdsl.spec.Project
import net.nemerosa.ontrack.kdsl.spec.deleteProperty
import net.nemerosa.ontrack.kdsl.spec.getProperty
import net.nemerosa.ontrack.kdsl.spec.setProperty
/**
* Sets a Bitbucket Server property on a project.
*/
var Project.bitbucketServerConfigurationProperty: BitbucketServerProjectConfigurationProperty?
get() = getProperty(BITBUCKET_SERVER_PROJECT_CONFIGURATION_PROPERTY)?.parse()
set(value) {
if (value != null) {
setProperty(BITBUCKET_SERVER_PROJECT_CONFIGURATION_PROPERTY, value)
} else {
deleteProperty(BITBUCKET_SERVER_PROJECT_CONFIGURATION_PROPERTY)
}
}
class BitbucketServerProjectConfigurationProperty(
val configuration: String,
val project: String,
val repository: String,
val indexationInterval: Int = 0,
val issueServiceConfigurationIdentifier: String? = null,
)
const val BITBUCKET_SERVER_PROJECT_CONFIGURATION_PROPERTY =
"net.nemerosa.ontrack.extension.stash.property.StashProjectConfigurationPropertyType"
| 44
|
Kotlin
|
25
| 96
|
759f17484c9b507204e5a89524e07df871697e74
| 1,176
|
ontrack
|
MIT License
|
krate-moshi-reflect/src/test/java/hu/autsoft/krate/moshi/TestModel.kt
|
AutSoft
| 143,710,217
| false
| null |
package hu.autsoft.krate.moshi
internal data class TestModel(val x: Int, val y: Double, val z: String)
| 1
|
Kotlin
|
12
| 278
|
7d9149463ca95d18778d03cdaeedb92c33e5fbfc
| 104
|
Krate
|
Apache License 2.0
|
core/src/ru/serdjuk/zxsna/app/windows/CancelDialog.kt
|
vito-Z80
| 302,118,445
| false
|
{"Gradle": 4, "INI": 2, "Shell": 1, "Text": 5, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "JAR Manifest": 1, "Java": 2, "Kotlin": 70, "Assembly": 1, "XML": 1}
|
package ru.serdjuk.zxsna.app.windows
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.scenes.scene2d.ui.Dialog
import ru.serdjuk.zxsna.app.system.module
@ExperimentalUnsignedTypes
class CancelDialog(text: String) : Dialog("", module.skin) {
init {
isModal = true
text(" \n$text")
row()
pad(40f)
button("Cancel")
pack()
setPosition(
Gdx.graphics.width / 2f - prefWidth / 2f,
Gdx.graphics.height / 2f - prefHeight / 2f
)
toFront()
module.stage.addActor(this)
}
}
| 1
| null |
1
| 1
|
8e19849cb1d6f71fc6a155940a2c3180db98e89d
| 588
|
ZXSNAv2
|
Apache License 2.0
|
library/src/main/kotlin/com/freakyaxel/emvparser/tlv/TLVParser.kt
|
alexpopa95
| 507,649,584
| false
|
{"Kotlin": 29848, "Shell": 707}
|
package com.freakyaxel.emvparser.tlv
internal object TLVParser {
fun getData(recv: ByteArray): ByteArray {
val recvSize = recv.size
return if (recvSize >= 2) {
recv.copyOfRange(0, recvSize - 2)
} else ByteArray(0)
}
}
| 0
|
Kotlin
|
2
| 0
|
fb6cb7ec51acba42890240151b1c9740c600c77e
| 262
|
emv-card-reader
|
MIT License
|
app/src/main/java/com/brins/lightmusic/api/service/MusicVideoService.kt
|
BrinsLee
| 193,304,333
| false
| null |
package com.brins.lightmusic.api.service
import com.brins.lightmusic.common.AppConfig
import com.brins.lightmusic.model.musicvideo.LastestMvDataBean
import com.brins.lightmusic.model.musicvideo.MvCommentsResult
import com.brins.lightmusic.model.musicvideo.MvMetaResult
import com.brins.lightmusic.model.musicvideo.MvResult
import io.reactivex.Observable
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface MusicVideoService {
@GET(AppConfig.LASTESTMUSICVIDEO)
fun getLatestMusicVideo(@Query("limit") limit: Int): Observable<MvResult>
@GET(AppConfig.MVURL)
fun getMvMetaData(@Query("id") id: String): Call<MvMetaResult>
@GET(AppConfig.MVDETAIL)
fun getMvDetail(@Query("id") id: String): Observable<LastestMvDataBean>
@GET(AppConfig.MVALL)
fun getMvAll(@Query("area") area: String, @Query("limit") limit: Int): Call<MvResult>
@GET(AppConfig.MVCOMMENTS)
fun getMvComments(@Query("id") id : String): Call<MvCommentsResult>
}
| 1
|
Kotlin
|
3
| 20
|
f0be073b901efdee40d38824bc3c0cc4d6aa426d
| 1,002
|
LightMusic
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com.github.nagatsukaakiya.osuapi/models/GameMode.kt
|
dmitry-stakhov
| 626,238,572
| false
| null |
package com.github.nagatsukaakiya.osuapi.models
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.encodeToJsonElement
@Serializable
enum class GameMode {
@SerialName("osu")
Standard,
@SerialName("mania")
Mania,
@SerialName("fruits")
Catch,
@SerialName("taiko")
Taiko;
internal fun getValue(): String = Json.decodeFromJsonElement(Json.encodeToJsonElement(this))
}
| 1
|
Kotlin
|
0
| 0
|
9ee37d56093fd9092bad0225ba2a8163a7488969
| 562
|
osu-API-wrapper
|
Apache License 2.0
|
src/main/kotlin/no/nav/nada/SchemaApp.kt
|
navikt
| 275,420,244
| false
| null |
package no.nav.nada
import io.ktor.application.Application
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.config.ApplicationConfig
import io.ktor.features.CallLogging
import io.ktor.features.ContentNegotiation
import io.ktor.features.DefaultHeaders
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.metrics.micrometer.MicrometerMetrics
import io.ktor.request.path
import io.ktor.response.respond
import io.ktor.routing.get
import io.ktor.routing.routing
import io.ktor.serialization.json
import io.micrometer.core.instrument.Clock
import io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics
import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics
import io.micrometer.core.instrument.binder.system.ProcessorMetrics
import io.micrometer.prometheus.PrometheusConfig
import io.micrometer.prometheus.PrometheusMeterRegistry
import io.prometheus.client.CollectorRegistry
import kotlinx.serialization.json.Json
import org.flywaydb.core.Flyway
import org.slf4j.event.Level
import javax.sql.DataSource
fun Application.schemaApi(
appConfig: ApplicationConfig = this.environment.config,
dataSource: DataSource = dataSourceFrom(databaseConfigFrom(appConfig)),
schemaRepository: SchemaRepository = SchemaRepository(dataSource)
) {
val jsonConfig = Json { isLenient = true }
val flywayDs = dataSourceFrom(databaseConfigFrom(appConfig), "admin")
val flyway = Flyway.configure().dataSource(flywayDs).load()
flyway.migrate()
SchemaReader.apply {
create(kafkaConfigFrom(appConfig, serviceUser(appConfig)), schemaRepository)
run()
}
install(CallLogging) {
level = Level.INFO
filter { call ->
!call.request.path().startsWith("/internal")
}
}
install(DefaultHeaders)
install(ContentNegotiation) {
json(
json = jsonConfig,
contentType = ContentType.Application.Json
)
}
install(MicrometerMetrics) {
registry = PrometheusMeterRegistry(
PrometheusConfig.DEFAULT,
CollectorRegistry.defaultRegistry,
Clock.SYSTEM
)
meterBinders = listOf(
ClassLoaderMetrics(),
JvmMemoryMetrics(),
JvmGcMetrics(),
ProcessorMetrics(),
JvmThreadMetrics()
)
}
routing {
nais()
get("/") {
val topics = schemaRepository.findTopics()
call.respond(mapOf("topics" to topics))
}
get("/topic/{topic}") {
call.parameters["topic"]?.let { topic ->
val topicInfo = schemaRepository.topicInfo(topic)
call.respond(mapOf("schemas" to topicInfo))
} ?: call.respond(HttpStatusCode.BadRequest)
}
schemaRegistry(schemaRepository)
}
}
fun serviceUser(appConfig: ApplicationConfig): ServiceUser {
return ServiceUser(
username = appConfig.property("serviceuser.username").getString(),
password = appConfig.property("serviceuser.password").getString()
)
}
| 11
| null |
1
| 1
|
23badf652733f33a57a14da8eea99de11f9f250e
| 3,244
|
kafka-schema-backup
|
MIT License
|
app/src/main/java/com/example/worldcapitalsquiz/CountriesData.kt
|
cosmin-oros
| 509,459,475
| false
| null |
package com.example.worldcapitalsquiz
data class CountriesData(
val country: String,
val capital: String,
val flagId: Int,
val hint: String,
val order: Int
)
| 0
|
Kotlin
|
0
| 2
|
87732f32a9f51446484de90f111cf1d4085e0d64
| 179
|
World-Capitals-Quiz-App
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/viewmodel/TimerViewModel.kt
|
gszesiek
| 346,160,442
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.androiddevchallenge.viewmodel
import android.os.CountDownTimer
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.androiddevchallenge.model.Time
class TimerViewModel : ViewModel() {
var timer: CountDownTimer? = null
private val _timeLeft = MutableLiveData<Time>(Time(0, 0))
val timeLeft: LiveData<Time> = _timeLeft
private val _action = MutableLiveData<String>("work")
val action: LiveData<String> = _action
private val _startButton = MutableLiveData<String>("Start")
val startButton: LiveData<String> = _startButton
private val _pauseButton = MutableLiveData<String>("Pause")
val pauseButton: LiveData<String> = _pauseButton
fun onClicked(button: String) {
when (button) {
"work" -> {
onStart(Time(1, 10))
_action.value = "work"
}
"done" -> {
println(action)
if (action.value == "work") {
onRest(Time(0, 30))
} else {
onStart(Time(1, 30))
}
}
"pause" -> {
onPause()
}
"go" -> {
onStart(timeLeft.value!!)
}
}
}
fun fromMilliseconds(milliseconds: Long): Time {
val minutes = ((milliseconds / 60000) % 60).toInt()
val seconds = ((milliseconds / 1000) % 60).toInt()
return Time(minutes, seconds)
}
fun timeInMillisec(timeLeft: Time) = timeLeft.minutes * 60 * 1000L + timeLeft.seconds * 1000L
fun onStart(setTime: Time) {
timer?.cancel()
_timeLeft.value = setTime
_action.value = "work"
_startButton.value = "Reset"
_pauseButton.value = "Pause"
timer = object : CountDownTimer(timeInMillisec(timeLeft.value!!), 1000) {
override fun onTick(millisUntilFinished: Long) {
_timeLeft.value = fromMilliseconds(millisUntilFinished)
}
override fun onFinish() {
onRest(Time(0, 30))
}
}
timer?.start()
}
fun onRest(setTime: Time) {
timer?.cancel()
_timeLeft.value = setTime
_action.value = "rest"
timer = object : CountDownTimer(timeInMillisec(timeLeft.value!!), 1000) {
override fun onTick(millisUntilFinished: Long) {
_timeLeft.value = fromMilliseconds(millisUntilFinished)
}
override fun onFinish() {
onStart(Time(1, 30))
}
}
timer?.start()
}
fun onPause() {
timer?.cancel()
_pauseButton.value = "Go"
}
}
| 0
|
Kotlin
|
0
| 0
|
ae239a0bda3ad4a03aad494d4bdaf5e2eee2d46a
| 3,398
|
Week-2-Countdown-timer
|
Apache License 2.0
|
net.akehurst.language/bug-test/src/commonTest/kotlin/test_BuggyClass.kt
|
dhakehurst
| 197,245,665
| false
|
{"Kotlin": 3541898, "ANTLR": 64742, "Rascal": 17698, "Java": 14313, "PEG.js": 6866, "JavaScript": 5287, "BASIC": 22}
|
/*
* Copyright (C) 2023 Dr. <NAME> (http://dr.david.h.akehurst.net)
*
* 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 bugs
import kotlin.test.Test
class test_BuggyClass {
@Test
fun testBug() {
val bc = BuggyClass()
}
}
| 3
|
Kotlin
|
7
| 45
|
177abcb60c51efcfc2432174f5d6620a7db89928
| 775
|
net.akehurst.language
|
Apache License 2.0
|
src/test/kotlin/days/Day18Test.kt
|
hughjdavey
| 725,972,063
| false
|
{"Kotlin": 76988}
|
package days
import days.Day14.Direction
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.hasSize
import org.hamcrest.Matchers.`in`
import org.hamcrest.Matchers.`is`
import org.junit.jupiter.api.Test
class Day18Test {
private val day18 = Day18()
@Test
fun testPartOne() {
assertThat(day18.partOne(), `is`(62L))
}
@Test
fun testPartTwo() {
assertThat(day18.partTwo(), `is`(952408144115L))
}
@Test
fun testParseInstructions() {
val instructions = day18.parseInstructions()
assertThat(instructions, hasSize(14))
assertThat(instructions[0], `is`(Day18.DigInstruction(Direction.EAST, 6, "#70c710")))
assertThat(instructions[1], `is`(Day18.DigInstruction(Direction.SOUTH, 5, "#0dc571")))
assertThat(instructions[2], `is`(Day18.DigInstruction(Direction.WEST, 2, "#5713f0")))
assertThat(instructions[11], `is`(Day18.DigInstruction(Direction.NORTH, 3, "#a77fa3")))
assertThat(instructions[12], `is`(Day18.DigInstruction(Direction.WEST, 2, "#015232")))
assertThat(instructions[13], `is`(Day18.DigInstruction(Direction.NORTH, 2, "#7a21e3")))
}
@Test
fun testParseInstructionsFromColours() {
val instructions = day18.parseInstructionsFromColours()
assertThat(instructions, hasSize(14))
assertThat(instructions[0], `is`(Day18.DigInstruction(Direction.EAST, 461937, "#70c710")))
assertThat(instructions[1], `is`(Day18.DigInstruction(Direction.SOUTH, 56407, "#0dc571")))
assertThat(instructions[2], `is`(Day18.DigInstruction(Direction.EAST, 356671, "#5713f0")))
assertThat(instructions[11], `is`(Day18.DigInstruction(Direction.NORTH, 686074, "#a77fa3")))
assertThat(instructions[12], `is`(Day18.DigInstruction(Direction.WEST, 5411, "#015232")))
assertThat(instructions[13], `is`(Day18.DigInstruction(Direction.NORTH, 500254, "#7a21e3")))
}
}
| 0
|
Kotlin
|
0
| 0
|
330f13d57ef8108f5c605f54b23d04621ed2b3de
| 1,955
|
aoc-2023
|
Creative Commons Zero v1.0 Universal
|
domain/src/test/kotlin/no/nav/su/se/bakover/domain/grunnlag/BosituasjonTest.kt
|
navikt
| 227,366,088
| false
| null |
package no.nav.su.se.bakover.domain.grunnlag
import io.kotest.matchers.shouldBe
import no.nav.su.se.bakover.common.desember
import no.nav.su.se.bakover.common.februar
import no.nav.su.se.bakover.common.januar
import no.nav.su.se.bakover.common.juni
import no.nav.su.se.bakover.common.mars
import no.nav.su.se.bakover.common.periode.Periode
import no.nav.su.se.bakover.domain.Fnr
import no.nav.su.se.bakover.domain.grunnlag.Grunnlag.Bosituasjon.Companion.slåSammenPeriodeOgBosituasjon
import no.nav.su.se.bakover.test.fixedTidspunkt
import no.nav.su.se.bakover.test.generer
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.util.UUID
internal class BosituasjonTest {
@Test
fun `viser om søker har ektefelle eller ikke`() {
Grunnlag.Bosituasjon.Fullstendig.EktefellePartnerSamboer.Under67.UførFlyktning(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(fraOgMed = 1.januar(2021), tilOgMed = 30.juni(2021)),
fnr = Fnr.generer(),
begrunnelse = null,
).harEktefelle() shouldBe true
Grunnlag.Bosituasjon.Fullstendig.EktefellePartnerSamboer.Under67.IkkeUførFlyktning(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(fraOgMed = 1.januar(2021), tilOgMed = 30.juni(2021)),
fnr = Fnr.generer(),
begrunnelse = null,
).harEktefelle() shouldBe true
Grunnlag.Bosituasjon.Fullstendig.EktefellePartnerSamboer.SektiSyvEllerEldre(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(fraOgMed = 1.januar(2021), tilOgMed = 30.juni(2021)),
fnr = Fnr.generer(),
begrunnelse = null,
).harEktefelle() shouldBe true
Grunnlag.Bosituasjon.Fullstendig.Enslig(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(fraOgMed = 1.januar(2021), tilOgMed = 30.juni(2021)),
begrunnelse = null,
).harEktefelle() shouldBe false
Grunnlag.Bosituasjon.Fullstendig.DelerBoligMedVoksneBarnEllerAnnenVoksen(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(fraOgMed = 1.januar(2021), tilOgMed = 30.juni(2021)),
begrunnelse = null,
).harEktefelle() shouldBe false
Grunnlag.Bosituasjon.Ufullstendig.HarIkkeEps(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(fraOgMed = 1.januar(2021), tilOgMed = 30.juni(2021)),
).harEktefelle() shouldBe false
Grunnlag.Bosituasjon.Ufullstendig.HarEps(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
fnr = Fnr.generer(),
periode = Periode.create(fraOgMed = 1.januar(2021), tilOgMed = 30.juni(2021)),
).harEktefelle() shouldBe true
}
@Test
fun `returnerer false hvis 2 grunnlag har samme informasjon om ektefelle`() {
val gjeldendeBosituasjon = Grunnlag.Bosituasjon.Ufullstendig.HarEps(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(fraOgMed = 1.januar(2021), tilOgMed = 30.juni(2021)),
fnr = Fnr.generer(),
)
gjeldendeBosituasjon.harEndretEllerFjernetEktefelle(gjeldendeBosituasjon) shouldBe false
}
@Test
fun `returnerer true hvis grunnlag om ektefelle har endret sig`() {
val gjeldendeBosituasjon = Grunnlag.Bosituasjon.Ufullstendig.HarEps(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(fraOgMed = 1.januar(2021), tilOgMed = 30.juni(2021)),
fnr = Fnr.generer(),
)
Grunnlag.Bosituasjon.Ufullstendig.HarIkkeEps(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(fraOgMed = 1.januar(2021), tilOgMed = 30.juni(2021)),
).harEndretEllerFjernetEktefelle(gjeldendeBosituasjon) shouldBe true
}
@Test
fun `oppdaterer periode i bosituasjon`() {
val oppdatertPeriode = Periode.create(1.februar(2021), 31.januar(2022))
val gjeldendeBosituasjon = Grunnlag.Bosituasjon.Ufullstendig.HarIkkeEps(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(1.januar(2021), 31.desember(2021)),
)
gjeldendeBosituasjon.oppdaterBosituasjonsperiode(oppdatertPeriode) shouldBe gjeldendeBosituasjon.copy(
periode = oppdatertPeriode,
)
}
@Test
fun `slår sammen like og tilstøtende bosituasjoner`() {
val b1 = Grunnlag.Bosituasjon.Fullstendig.Enslig(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(1.januar(2021), 31.januar(2021)),
begrunnelse = null,
)
val b2 = b1.copy(
periode = Periode.create(1.februar(2021), 28.februar(2021)),
)
val b3 = Grunnlag.Bosituasjon.Fullstendig.EktefellePartnerSamboer.Under67.IkkeUførFlyktning(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(1.mars(2021), 31.mars(2021)),
fnr = Fnr.generer(),
begrunnelse = null,
)
val actual = listOf(b1, b2, b3).slåSammenPeriodeOgBosituasjon()
actual.size shouldBe 2
actual.first() shouldBe Grunnlag.Bosituasjon.Fullstendig.Enslig(
id = b1.id,
opprettet = fixedTidspunkt,
periode = Periode.create(1.januar(2021), 28.februar(2021)),
begrunnelse = null,
)
actual.last() shouldBe Grunnlag.Bosituasjon.Fullstendig.EktefellePartnerSamboer.Under67.IkkeUførFlyktning(
id = b3.id,
opprettet = fixedTidspunkt,
periode = Periode.create(1.mars(2021), 31.mars(2021)),
fnr = b3.fnr,
begrunnelse = null,
)
}
@Test
fun `kaster exception dersom det finnes ufullstendig bostiuasjon når den skal slå sammen`() {
val b1 = Grunnlag.Bosituasjon.Fullstendig.Enslig(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(1.januar(2021), 31.januar(2021)),
begrunnelse = null,
)
val b2 = Grunnlag.Bosituasjon.Ufullstendig.HarIkkeEps(
id = UUID.randomUUID(),
opprettet = fixedTidspunkt,
periode = Periode.create(1.februar(2021), 28.februar(2021)),
)
assertThrows<IllegalStateException> {
listOf(b1, b2).slåSammenPeriodeOgBosituasjon()
}
}
}
| 3
|
Kotlin
|
0
| 0
|
b0864f973c8986f58af07c4bc7f601caa602dbfc
| 6,848
|
su-se-bakover
|
MIT License
|
src/main/kotlin/com/kryptonkoins/repository/KryptonRepository.kt
|
laguiar
| 106,131,582
| false
| null |
package com.kryptonkoins.repository
import com.kryptonkoins.domain.Krypton
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import java.util.*
interface KryptonRepository : ReactiveMongoRepository<Krypton, UUID>
| 0
|
Kotlin
|
0
| 2
|
3fdda6a9dab55c128cc182087e67bd2cf6ca8458
| 239
|
kryptonkoins
|
MIT License
|
app/src/main/java/com/tasomaniac/devwidget/main/MainNavigation.kt
|
fkorotkov
| 119,068,308
| false
|
{"Gradle": 3, "YAML": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 76, "XML": 45, "Java": 10, "HTML": 1, "SVG": 3}
|
package com.tasomaniac.devwidget.main
import android.content.Context
import android.os.Build.VERSION_CODES.O
import android.support.annotation.RequiresApi
import com.tasomaniac.devwidget.configure.ConfigureActivity
import javax.inject.Inject
class MainNavigation @Inject constructor() {
@RequiresApi(O)
fun navigateForPinning(context: Context) {
val intent = ConfigureActivity.createIntentForPinning(context)
context.startActivity(intent)
}
}
| 1
| null |
1
| 1
|
738a7678d37db5abece32421072b3b8b7627cf73
| 474
|
DevWidget
|
Apache License 2.0
|
app/src/main/java/com/techlads/composetv/features/home/HomeViewModel.kt
|
UmairKhalid786
| 586,631,597
| false
|
{"Kotlin": 192563}
|
package com.techlads.composetv.features.home
import androidx.lifecycle.ViewModel
import com.techlads.composetv.features.home.leftmenu.data.MenuData
import com.techlads.composetv.features.home.leftmenu.model.MenuItem
import com.techlads.composetv.utils.toMutable
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor() : ViewModel() {
val menuItems: StateFlow<List<MenuItem>> = MutableStateFlow(emptyList())
val menuState: StateFlow<Boolean> = MutableStateFlow(false)
private val _usedTopBar: MutableStateFlow<Boolean> = MutableStateFlow(false)
val usedTopBar: StateFlow<Boolean> = _usedTopBar
init {
menuItems.toMutable().value = MenuData.menuItems
}
fun menuClosed() {
menuState.toMutable().value = false
}
fun menuOpen() {
menuState.toMutable().value = true
}
fun toggleTopBar(){
_usedTopBar.value = !_usedTopBar.value
}
}
| 4
|
Kotlin
|
30
| 190
|
194476db43143b3a74ff8baae089b1e5ec60142c
| 1,079
|
ComposeTv
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.