path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/afdhal_fa/treasure/LoginActivity.kt
|
Fuadafdhal
| 307,046,917
| false
| null |
package com.afdhal_fa.treasure
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.facebook.FacebookSdk
class LoginActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
FacebookSdk.sdkInitialize(applicationContext)
}
}
| 0
|
Kotlin
|
0
| 1
|
5b45872b51c34dc908a8f082a46a308162fa8315
| 392
|
Treasure
|
Apache License 2.0
|
test/ApplicationTest.kt
|
Slenkis
| 276,249,045
| false
| null |
package com.slenkis
import io.ktor.util.KtorExperimentalAPI
import kotlin.test.Test
class ApplicationTest {
@KtorExperimentalAPI
@Test
fun testRoot() {
// Empty
}
}
| 0
|
Kotlin
|
0
| 0
|
c43ca4352c3cfd0d86dbf89361e7fda57a3d9c1d
| 191
|
scythe
|
MIT License
|
src/kotlinPratice/Sample4.kt
|
ajayvamsee
| 628,901,868
| false
| null |
fun main(){
val list = listOf (1,1,2,2,3,3,4,5,6,7,1,2,3,4,5,6,7)
println(list)
// val setList = setOf(1,1,2,2,3,3,4,5,6,7,1,2,3,4,5,6,7)
// println(setList)
/* println("Convert list to set")
println(list.toSet())*/
println("Avoid Duplicate from the list")
println(list.distinct())
println(list.contains(2))
println(2 in list)
println(9 in list)
}
| 0
|
Kotlin
|
0
| 0
|
b97b345526baecf509b186259bdce52f95728aa8
| 393
|
PracticeJavaandkoltin
|
MIT License
|
src/main/kotlin/com/andrejusti/example/kotlin/springboot/rest/service/PaginationService.kt
|
justiandre
| 150,188,928
| false
| null |
package com.andrejusti.example.kotlin.springboot.rest.service
import org.apache.commons.lang3.math.NumberUtils
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import com.andrejusti.example.kotlin.springboot.rest.dto.ResultPage
@Service
class PaginationService(
@Value("\${app.search.pagination.numberRecords.default}") val paginationNumberRecordsDefault: Int,
@Value("\${app.search.pagination.numberRecords.max}") val paginationNumberRecordsMax: Int
) {
fun parsePagination(page: Int?, maxRecords: Int?): Pageable {
val pageNormalized = page ?: NumberUtils.INTEGER_ZERO
val maxRecordsNormalized: Int = (maxRecords ?: paginationNumberRecordsDefault)
.takeIf { paginationNumberRecordsMax > it }
?: paginationNumberRecordsMax
return PageRequest.of(pageNormalized, maxRecordsNormalized)
}
fun <T> parseResult(page: Int?, maxRecords: Int?, find: (Pageable) -> Page<T>): ResultPage<T> {
val pageable = parsePagination(page, maxRecords)
val page = find(pageable)
return ResultPage(page.totalElements, page.content)
}
}
| 0
|
Kotlin
|
13
| 27
|
873ddf8c8a9d7649b0ed790ea2c00dbf9d160bbe
| 1,329
|
example-kotlin-springboot-rest
|
MIT License
|
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/Community.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36756847}
|
package compose.icons.cssggicons
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.CssGgIcons
public val CssGgIcons.Community: ImageVector
get() {
if (_community != null) {
return _community!!
}
_community = Builder(name = "Community", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(12.0f, 17.456f)
curveTo(11.2389f, 17.8053f, 10.3922f, 18.0f, 9.5f, 18.0f)
curveTo(6.1863f, 18.0f, 3.5f, 15.3137f, 3.5f, 12.0f)
curveTo(3.5f, 8.6863f, 6.1863f, 6.0f, 9.5f, 6.0f)
curveTo(10.3922f, 6.0f, 11.2389f, 6.1947f, 12.0f, 6.544f)
curveTo(12.7611f, 6.1947f, 13.6078f, 6.0f, 14.5f, 6.0f)
curveTo(17.8137f, 6.0f, 20.5f, 8.6863f, 20.5f, 12.0f)
curveTo(20.5f, 15.3137f, 17.8137f, 18.0f, 14.5f, 18.0f)
curveTo(13.6078f, 18.0f, 12.7611f, 17.8053f, 12.0f, 17.456f)
close()
moveTo(10.0003f, 15.969f)
curveTo(9.8364f, 15.9895f, 9.6694f, 16.0f, 9.5f, 16.0f)
curveTo(7.2909f, 16.0f, 5.5f, 14.2091f, 5.5f, 12.0f)
curveTo(5.5f, 9.7909f, 7.2909f, 8.0f, 9.5f, 8.0f)
curveTo(9.6694f, 8.0f, 9.8364f, 8.0105f, 10.0003f, 8.031f)
curveTo(9.0666f, 9.0887f, 8.5f, 10.4782f, 8.5f, 12.0f)
curveTo(8.5f, 13.5218f, 9.0666f, 14.9113f, 10.0003f, 15.969f)
close()
moveTo(13.9998f, 8.031f)
curveTo(14.1636f, 8.0105f, 14.3306f, 8.0f, 14.5f, 8.0f)
curveTo(16.7091f, 8.0f, 18.5f, 9.7909f, 18.5f, 12.0f)
curveTo(18.5f, 14.2091f, 16.7091f, 16.0f, 14.5f, 16.0f)
curveTo(14.3306f, 16.0f, 14.1636f, 15.9895f, 13.9998f, 15.969f)
curveTo(14.9334f, 14.9113f, 15.5f, 13.5218f, 15.5f, 12.0f)
curveTo(15.5f, 10.4782f, 14.9334f, 9.0887f, 13.9998f, 8.031f)
close()
moveTo(12.0f, 8.8773f)
curveTo(12.9145f, 9.6104f, 13.5f, 10.7368f, 13.5f, 12.0f)
curveTo(13.5f, 13.2632f, 12.9145f, 14.3896f, 12.0f, 15.1227f)
curveTo(11.0855f, 14.3896f, 10.5f, 13.2632f, 10.5f, 12.0f)
curveTo(10.5f, 10.7368f, 11.0855f, 9.6104f, 12.0f, 8.8773f)
close()
}
}
.build()
return _community!!
}
private var _community: ImageVector? = null
| 15
|
Kotlin
|
20
| 460
|
651badc4ace0137c5541f859f61ffa91e5242b83
| 3,212
|
compose-icons
|
MIT License
|
nugu-core/src/main/java/com/skt/nugu/sdk/core/attachment/AttachmentManager.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.sdk.core.attachment
import com.skt.nugu.sdk.core.interfaces.attachment.Attachment
import com.skt.nugu.sdk.core.interfaces.attachment.AttachmentManagerInterface
import com.skt.nugu.sdk.core.interfaces.message.AttachmentMessage
import com.skt.nugu.sdk.core.utils.Logger
import java.util.concurrent.Future
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
class AttachmentManager(private val timeoutInSeconds: Long = 10) : AttachmentManagerInterface {
companion object {
private const val TAG = "AttachmentManager"
private const val ATTACHMENT_PRESERVE_DURATION = 1000L * 60 * 60L
}
private data class AttachmentStatus(
var readerCreated: Boolean = false,
var writerCreated: Boolean = false,
var writerClosed: Boolean = false,
var receiveEndAttachment: Boolean = false,
val createdAt: Long = System.currentTimeMillis()
)
private val lock: Lock = ReentrantLock()
private val attachments = HashMap<String, Attachment>()
private val attachmentsStatus = HashMap<String, AttachmentStatus>()
private val attachmentTimeoutFutureMap = HashMap<String, Future<*>>()
private val scheduleExecutor = ScheduledThreadPoolExecutor(1)
override fun createReader(attachmentId: String): Attachment.Reader? {
lock.withLock {
val status = attachmentsStatus[attachmentId]
return if (status != null) {
val reader = attachments[attachmentId]?.createReader()
if (reader != null) {
status.readerCreated = true
// if(status.writerClosed) {
// // remove attachment if writer closed.
// attachments.remove(attachmentId)
// }
}
Logger.d(
TAG,
"[createReader] Attachment Created Before - attachmentId: $attachmentId, status: $status, created reader: $reader"
)
reader
} else {
val attachment = StreamAttachment(attachmentId)
val reader = attachment.createReader()
attachments[attachmentId] = attachment
val newStatus = AttachmentStatus(readerCreated = true)
attachmentsStatus[attachmentId] = newStatus
val timeoutFuture = attachmentTimeoutFutureMap[attachmentId]
if(timeoutFuture == null) {
attachmentTimeoutFutureMap[attachmentId] = scheduleExecutor.schedule({
// no attachment received
Logger.d(TAG, "[createReader] attachment timeout: $attachmentId")
lock.withLock {
attachment.createWriter().close(true)
newStatus.writerCreated = true
newStatus.writerClosed = true
removeAttachment(attachmentId)
}
}, timeoutInSeconds, TimeUnit.SECONDS)
}
Logger.d(
TAG,
"[createReader] New Attachment Created - attachmentId: $attachmentId, status: $status, created reader: $reader"
)
reader
}
}
}
override fun removeAttachment(attachmentId: String) {
lock.withLock {
val attachmentRemoved = attachments.remove(attachmentId)
Logger.d(
TAG,
"[removeAttachment] attachmentId: $attachmentId, attachmentRemoved: $attachmentRemoved"
)
val removedStatus = removeStatusIfNoMoreNeedLocked(attachmentId)
trimTimeoutAttachmentLocked()
if (attachmentRemoved != null || removedStatus != null) {
Logger.d(
TAG,
"[removeAttachment] attachment size: ${attachments.size}, status size: ${attachmentsStatus.size}"
)
}
}
}
private fun removeStatusIfNoMoreNeedLocked(attachmentId: String): AttachmentStatus? {
val status = attachmentsStatus[attachmentId]
val removed = if (status != null) {
if (status.readerCreated && status.receiveEndAttachment) {
attachmentsStatus.remove(attachmentId)
} else {
null
}
} else {
null
}
if(removed != null) {
Logger.d(
TAG,
"[removeStatusIfNoMoreNeedLocked] removed - id: $attachmentId, status: $status"
)
} else {
Logger.d(
TAG,
"[removeStatusIfNoMoreNeedLocked] not removed - id: $attachmentId, status: $status"
)
}
return removed
}
override fun onAttachment(attachment: AttachmentMessage) {
val attachmentId = attachment.parentMessageId
lock.withLock {
attachmentTimeoutFutureMap.remove(attachmentId)?.cancel(true)
var status = attachmentsStatus[attachmentId]
val writer = if (status != null) {
val attachmentStream = attachments[attachmentId]
if (attachmentStream != null && !status.writerClosed) {
attachmentStream.createWriter()
} else {
null
}
} else {
val attachmentStream = StreamAttachment(attachmentId)
attachments[attachmentId] = attachmentStream
status = AttachmentStatus(writerCreated = true)
attachmentsStatus[attachmentId] = status
Logger.d(TAG, "[onAttachment] New Attachment Created- attachmentId: $attachmentId")
attachmentStream.createWriter()
}
if (writer != null) {
writer.write(attachment.content)
if (attachment.isEnd) {
writer.close()
} else {
attachmentTimeoutFutureMap[attachmentId] = scheduleExecutor.schedule({
Logger.d(TAG, "[onAttachment] attachment timeout: $attachmentId")
lock.withLock {
writer.close(true)
status.writerClosed = true
removeAttachment(attachmentId)
}
}, timeoutInSeconds, TimeUnit.SECONDS)
}
}
if (attachment.isEnd) {
Logger.d(TAG, "[onAttachment] receive end attachment: $attachmentId")
status.writerClosed = true
status.receiveEndAttachment = true
tryRemoveAttachmentAndStatusLocked(attachmentId)
}
}
}
private fun tryRemoveAttachmentAndStatusLocked(attachmentId: String) {
val removedStatus = removeStatusIfNoMoreNeedLocked(attachmentId)
val removedAttachment = if (removedStatus != null) {
attachments.remove(attachmentId)
} else {
null
}
trimTimeoutAttachmentLocked()
Logger.d(
TAG,
"[tryRemoveAttachmentAndStatusLocked] attachmentId: $attachmentId, removedAttachment: $removedAttachment, removedStatus: $removedStatus"
)
if (removedStatus != null || removedAttachment != null) {
Logger.d(
TAG,
"[tryRemoveAttachmentAndStatusLocked] attachment size: ${attachments.size}, status size: ${attachmentsStatus.size}"
)
}
}
private fun trimTimeoutAttachmentLocked() {
val current = System.currentTimeMillis()
val removeTargets = attachmentsStatus.filter {
current - it.value.createdAt > ATTACHMENT_PRESERVE_DURATION
}
removeTargets.forEach {
attachmentsStatus.remove(it.key)
attachments.remove(it.key)
}
Logger.d(TAG, "[trimTimeoutStatusLocked] removeTargets: $removeTargets")
}
}
| 5
| null |
18
| 27
|
9d90dcbb8463f7b8f98713126a93de7e291da86c
| 8,935
|
nugu-android
|
Apache License 2.0
|
backend/src/main/java/com/paligot/confily/backend/third/parties/conferencehall/ConferenceHallApi.kt
|
GerardPaligot
| 444,230,272
| false
| null |
package com.paligot.confily.backend.third.parties.conferencehall
import com.paligot.confily.backend.internals.SystemEnv
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.java.Java
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.logging.DEFAULT
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger
import io.ktor.client.plugins.logging.Logging
import io.ktor.client.request.get
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
class ConferenceHallApi(
private val client: HttpClient,
private val baseUrl: String = "https://${SystemEnv.conferenceHallUrl}/api"
) {
suspend fun fetchEventConfirmed(eventId: String, apiKey: String) =
client.get("$baseUrl/v1/event/$eventId?key=$apiKey&state=confirmed").body<Event>()
object Factory {
fun create(enableNetworkLogs: Boolean): ConferenceHallApi =
ConferenceHallApi(
client = HttpClient(Java.create()) {
install(ContentNegotiation) {
json(
Json {
isLenient = true
ignoreUnknownKeys = true
}
)
}
if (enableNetworkLogs) {
install(
Logging
) {
logger = Logger.DEFAULT
level = LogLevel.INFO
}
}
}
)
}
}
| 9
| null |
6
| 143
|
8c0985b73422d6b388012d79c7ab33c054dc55c1
| 1,709
|
Confily
|
Apache License 2.0
|
domain/src/main/java/com/demont/ldap/domain/services/LDAPScreeningService.kt
|
MaxMichel2
| 517,036,014
| false
| null |
package com.demont.ldap.domain.services
import android.os.Build
import android.telecom.Call
import android.telecom.CallScreeningService
import androidx.annotation.RequiresApi
import com.demont.ldap.domain.model.PreferenceKey
import com.demont.ldap.domain.preferences.PreferenceRepository
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import timber.log.Timber
@RequiresApi(Build.VERSION_CODES.N)
@AndroidEntryPoint
class LDAPScreeningService : CallScreeningService() {
private val scope = CoroutineScope(SupervisorJob())
@Inject
lateinit var repository: PreferenceRepository
override fun onScreenCall(callDetails: Call.Details) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
callDetails.callDirection == Call.Details.DIRECTION_INCOMING
) {
val phoneNumber = callDetails.handle.schemeSpecificPart
Timber.i("Number: $phoneNumber")
scope.launch {
repository.updatePreference(PreferenceKey.CALLING_PHONE_NUMBER, phoneNumber)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
dbc94589d6f51f3fcca8625e9942b4a2676b01eb
| 1,202
|
LDAP
|
Apache License 2.0
|
android/src/main/java/com/reactnativekeyboardcontroller/KeyboardAnimationController.kt
|
kirillzyusko
| 482,596,054
| false
| null |
package com.reactnativekeyboardcontroller.interactive
import android.os.CancellationSignal
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsAnimationControlListenerCompat
import androidx.core.view.WindowInsetsAnimationControllerCompat
import androidx.core.view.WindowInsetsCompat
import androidx.dynamicanimation.animation.SpringAnimation
import androidx.dynamicanimation.animation.SpringForce
import androidx.dynamicanimation.animation.springAnimationOf
import androidx.dynamicanimation.animation.withSpringForceProperties
import kotlin.math.roundToInt
@Suppress("detekt:TooManyFunctions")
internal class KeyboardAnimationController {
private var insetsAnimationController: WindowInsetsAnimationControllerCompat? = null
private var pendingRequestCancellationSignal: CancellationSignal? = null
private var pendingRequestOnReady: ((WindowInsetsAnimationControllerCompat) -> Unit)? = null
/* To take control of the an WindowInsetsAnimation, we need to pass in a listener to
controlWindowInsetsAnimation() in startControlRequest(). The listener created here
keeps track of the current WindowInsetsAnimationController and resets our state. */
private val animationControlListener by lazy {
object : WindowInsetsAnimationControlListenerCompat {
/**
* Once the request is ready, call our [onRequestReady] function
*/
override fun onReady(
controller: WindowInsetsAnimationControllerCompat,
types: Int,
) = onRequestReady(controller)
/**
* If the request is finished, we should reset our internal state
*/
override fun onFinished(controller: WindowInsetsAnimationControllerCompat) {
reset()
}
/**
* If the request is cancelled, we should reset our internal state
*/
override fun onCancelled(controller: WindowInsetsAnimationControllerCompat?) {
reset()
}
}
}
/**
* True if the IME was shown at the start of the current animation.
*/
private var isImeShownAtStart = false
private var currentSpringAnimation: SpringAnimation? = null
/**
* Start a control request to the [view]s [android.view.WindowInsetsController]. This should
* be called once the view is in a position to take control over the position of the IME.
*
* @param view The view which is triggering this request
* @param onRequestReady optional listener which will be called when the request is ready and
* the animation can proceed
*/
fun startControlRequest(
view: View,
onRequestReady: ((WindowInsetsAnimationControllerCompat) -> Unit)? = null,
) {
check(!isInsetAnimationInProgress()) {
"Animation in progress. Can not start a new request to controlWindowInsetsAnimation()"
}
// Keep track of the IME insets, and the IME visibility, at the start of the request
isImeShownAtStart = ViewCompat
.getRootWindowInsets(view)
?.isVisible(WindowInsetsCompat.Type.ime()) == true
// Create a cancellation signal, which we pass to controlWindowInsetsAnimation() below
pendingRequestCancellationSignal = CancellationSignal()
// Keep reference to the onReady callback
pendingRequestOnReady = onRequestReady
// update our state manager
InteractiveKeyboardProvider.isInteractive = true
// Finally we make a controlWindowInsetsAnimation() request:
ViewCompat.getWindowInsetsController(view)?.controlWindowInsetsAnimation(
// We're only catering for IME animations in this listener
WindowInsetsCompat.Type.ime(),
// Animation duration. This is not used by the system, and is only passed to any
// WindowInsetsAnimation.Callback set on views. We pass in -1 to indicate that we're
// not starting a finite animation, and that this is completely controlled by
// the user's touch.
-1,
// The time interpolator used in calculating the animation progress. The fraction value
// we passed into setInsetsAndAlpha() which be passed into this interpolator before
// being used by the system to inset the IME. LinearInterpolator is a good type
// to use for scrolling gestures.
linearInterpolator,
// A cancellation signal, which allows us to cancel the request to control
pendingRequestCancellationSignal,
// The WindowInsetsAnimationControlListener
animationControlListener,
)
}
/**
* Start a control request to the [view]s [android.view.WindowInsetsController], similar to
* [startControlRequest], but immediately fling to a finish using [velocityY] once ready.
*
* This function is useful for fire-and-forget operations to animate the IME.
*
* @param view The view which is triggering this request
* @param velocityY the velocity of the touch gesture which caused this call
*/
fun startAndFling(
view: View,
velocityY: Float,
) = startControlRequest(view) {
animateToFinish(velocityY)
}
/**
* Update the inset position of the IME by the given [dy] value. This value will be coerced
* into the hidden and shown inset values.
*
* This function should only be called if [isInsetAnimationInProgress] returns true.
*
* @return the amount of [dy] consumed by the inset animation, in pixels
*/
fun insetBy(dy: Int): Int {
val controller =
insetsAnimationController
?: throw IllegalStateException(
"Current WindowInsetsAnimationController is null." +
"This should only be called if isAnimationInProgress() returns true",
)
InteractiveKeyboardProvider.isInteractive = true
// Call updateInsetTo() with the new inset value
return insetTo(controller.currentInsets.bottom - dy)
}
/**
* Update the inset position of the IME to be the given [inset] value. This value will be
* coerced into the hidden and shown inset values.
*
* This function should only be called if [isInsetAnimationInProgress] returns true.
*
* @return the distance moved by the inset animation, in pixels
*/
fun insetTo(inset: Int): Int {
val controller =
insetsAnimationController
?: throw IllegalStateException(
"Current WindowInsetsAnimationController is null." +
"This should only be called if isAnimationInProgress() returns true",
)
val hiddenBottom = controller.hiddenStateInsets.bottom
val shownBottom = controller.shownStateInsets.bottom
val startBottom = if (isImeShownAtStart) shownBottom else hiddenBottom
val endBottom = if (isImeShownAtStart) hiddenBottom else shownBottom
// We coerce the given inset within the limits of the hidden and shown insets
val coercedBottom = inset.coerceIn(hiddenBottom, shownBottom)
val consumedDy = controller.currentInsets.bottom - coercedBottom
// Finally update the insets in the WindowInsetsAnimationController using
// setInsetsAndAlpha().
controller.setInsetsAndAlpha(
// Here we update the animating insets. This is what controls where the IME is displayed.
// It is also passed through to views via their WindowInsetsAnimation.Callback.
Insets.of(0, 0, 0, coercedBottom),
// This controls the alpha value. We don't want to alter the alpha so use 1f
1f,
// Finally we calculate the animation progress fraction. This value is passed through
// to any WindowInsetsAnimation.Callbacks, but it is not used by the system.
(coercedBottom - startBottom) / (endBottom - startBottom).toFloat(),
)
return consumedDy
}
/**
* Return `true` if an inset animation is in progress.
*/
fun isInsetAnimationInProgress(): Boolean = insetsAnimationController != null
/**
* Return `true` if an inset animation is currently finishing.
*/
fun isInsetAnimationFinishing(): Boolean = currentSpringAnimation != null
/**
* Return `true` if a request to control an inset animation is in progress.
*/
fun isInsetAnimationRequestPending(): Boolean = pendingRequestCancellationSignal != null
/**
* Cancel the current [WindowInsetsAnimationControllerCompat]. We immediately finish
* the animation, reverting back to the state at the start of the gesture.
*/
fun cancel() {
insetsAnimationController?.finish(isImeShownAtStart)
pendingRequestCancellationSignal?.cancel()
// Cancel the current spring animation
currentSpringAnimation?.cancel()
reset()
}
/**
* Finish the current [WindowInsetsAnimationControllerCompat] immediately.
*/
fun finish() {
val controller = insetsAnimationController
if (controller == null) {
// If we don't currently have a controller, cancel any pending request and return
pendingRequestCancellationSignal?.cancel()
return
}
val current = controller.currentInsets.bottom
val shown = controller.shownStateInsets.bottom
val hidden = controller.hiddenStateInsets.bottom
when (current) {
// The current inset matches either the shown/hidden inset, finish() immediately
shown -> {
InteractiveKeyboardProvider.shown = true
controller.finish(true)
}
hidden -> {
InteractiveKeyboardProvider.shown = false
controller.finish(false)
}
else -> {
// Otherwise, we'll look at the current position...
if (controller.currentFraction >= SCROLL_THRESHOLD) {
// If the IME is past the 'threshold' we snap to the toggled state
InteractiveKeyboardProvider.shown = !isImeShownAtStart
controller.finish(!isImeShownAtStart)
} else {
// ...otherwise, we snap back to the original visibility
InteractiveKeyboardProvider.shown = isImeShownAtStart
controller.finish(isImeShownAtStart)
}
}
}
}
/**
* Finish the current [WindowInsetsAnimationControllerCompat]. We finish the animation,
* animating to the end state if necessary.
*
* @param velocityY the velocity of the touch gesture which caused this call to [animateToFinish].
* Can be `null` if velocity is not available.
*/
fun animateToFinish(velocityY: Float? = null) {
val controller = insetsAnimationController
if (controller == null) {
// If we don't currently have a controller, cancel any pending request and return
pendingRequestCancellationSignal?.cancel()
return
}
InteractiveKeyboardProvider.isInteractive = false
val current = controller.currentInsets.bottom
val shown = controller.shownStateInsets.bottom
val hidden = controller.hiddenStateInsets.bottom
when {
// If we have a velocity, we can use it's direction to determine
// the visibility. Upwards == visible
velocityY != null ->
animateImeToVisibility(
visible = velocityY < 0,
velocityY = velocityY,
)
// The current inset matches either the shown/hidden inset, finish() immediately
current == shown -> {
InteractiveKeyboardProvider.shown = true
controller.finish(true)
}
current == hidden -> {
InteractiveKeyboardProvider.shown = false
controller.finish(false)
}
else -> {
// Otherwise, we'll look at the current position...
if (controller.currentFraction >= SCROLL_THRESHOLD) {
// If the IME is past the 'threshold' we animate it to the toggled state
animateImeToVisibility(!isImeShownAtStart)
} else {
// ...otherwise, we animate it back to the original visibility
animateImeToVisibility(isImeShownAtStart)
}
}
}
}
fun getCurrentKeyboardHeight(): Int {
val controller =
insetsAnimationController
?: throw IllegalStateException(
"Current WindowInsetsAnimationController is null." +
"This should only be called if isAnimationInProgress() returns true",
)
return controller.currentInsets.bottom
}
private fun onRequestReady(controller: WindowInsetsAnimationControllerCompat) {
// The request is ready, so clear out the pending cancellation signal
pendingRequestCancellationSignal = null
// Store the current WindowInsetsAnimationController
insetsAnimationController = controller
// Call any pending callback
pendingRequestOnReady?.invoke(controller)
pendingRequestOnReady = null
}
/**
* Resets all of our internal state.
*/
private fun reset() {
// Clear all of our internal state
insetsAnimationController = null
pendingRequestCancellationSignal = null
isImeShownAtStart = false
currentSpringAnimation?.cancel()
currentSpringAnimation = null
pendingRequestOnReady = null
}
/**
* Animate the IME to a given visibility.
*
* @param visible `true` to animate the IME to it's fully shown state, `false` to it's
* fully hidden state.
* @param velocityY the velocity of the touch gesture which caused this call. Can be `null`
* if velocity is not available.
*/
private fun animateImeToVisibility(
visible: Boolean,
velocityY: Float? = null,
) {
@Suppress("detekt:UseCheckOrError")
val controller =
insetsAnimationController
?: throw IllegalStateException("Controller should not be null")
currentSpringAnimation =
springAnimationOf(
setter = {
insetTo(it.roundToInt())
},
getter = { controller.currentInsets.bottom.toFloat() },
finalPosition =
when {
visible -> controller.shownStateInsets.bottom.toFloat()
else -> controller.hiddenStateInsets.bottom.toFloat()
},
).withSpringForceProperties {
// Tweak the damping value, to remove any bounciness.
dampingRatio = SpringForce.DAMPING_RATIO_NO_BOUNCY
// The stiffness value controls the strength of the spring animation, which
// controls the speed. Medium (the default) is a good value, but feel free to
// play around with this value.
stiffness = SpringForce.STIFFNESS_MEDIUM
}.apply {
if (velocityY != null) {
setStartVelocity(velocityY)
}
addEndListener { anim, _, _, _ ->
if (anim == currentSpringAnimation) {
currentSpringAnimation = null
}
// Once the animation has ended, finish the controller
finish()
}
}.also { it.start() }
}
}
/**
* Scroll threshold for determining whether to animating to the end state, or to the start state.
* Currently 15% of the total swipe distance distance
*/
private const val SCROLL_THRESHOLD = 0.15f
/**
* A LinearInterpolator instance we can re-use across listeners.
*/
private val linearInterpolator = LinearInterpolator()
| 8
| null |
71
| 996
|
4e659427e1037a2136d3691a534884c8341bbe44
| 14,916
|
react-native-keyboard-controller
|
MIT License
|
acrarium/src/main/kotlin/com/faendir/acra/ui/view/app/tabs/StatisticsAppTab.kt
|
F43nd1r
| 91,593,043
| false
| null |
/*
* (C) Copyright 2018 <NAME> (https://github.com/F43nd1r)
*
* 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.faendir.acra.ui.view.app.tabs
import com.faendir.acra.navigation.RouteParams
import com.faendir.acra.navigation.View
import com.faendir.acra.persistence.report.ReportRepository
import com.faendir.acra.persistence.version.VersionRepository
import com.faendir.acra.ui.component.statistics.Statistics
import com.faendir.acra.ui.view.app.AppView
import com.vaadin.flow.router.Route
/**
* @author lukas
* @since 11.10.18
*/
@View
@Route(value = "statistics", layout = AppView::class)
class StatisticsTab(
reportRepository: ReportRepository,
versionRepository: VersionRepository,
routeParams: RouteParams,
) : Statistics(routeParams.appId(), null, reportRepository, versionRepository)
| 7
| null |
51
| 200
|
31576a37d2c1eb61bb1d2641d7b214c87ce23fe1
| 1,330
|
Acrarium
|
Apache License 2.0
|
compose-jetsnack/common/src/commonMain/kotlin/com/example/jetsnack/model/SnackbarManager.kt
|
Kotlin
| 598,690,962
| false
|
{"Kotlin": 417771, "HTML": 11979, "JavaScript": 3324, "Swift": 1755, "Ruby": 101}
|
/*
* 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.jetsnack.model
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
data class Message(val id: Long, val message: Int /*@StringRes*/)
/**
* Class responsible for managing Snackbar messages to show on the screen
*/
object SnackbarManager {
private val _messages: MutableStateFlow<List<Message>> = MutableStateFlow(emptyList())
val messages: StateFlow<List<Message>> get() = _messages.asStateFlow()
fun showMessage(message: Int /*@StringRes*/) {
_messages.update { currentMessages ->
currentMessages + Message(
id = createRandomUUID(),
message = message
)
}
}
fun setMessageShown(messageId: Long) {
_messages.update { currentMessages ->
currentMessages.filterNot { it.id == messageId }
}
}
}
expect fun createRandomUUID(): Long
| 24
|
Kotlin
|
64
| 499
|
1b007347bf9f8a1ec3d420d30de1815768d5df02
| 1,613
|
kotlin-wasm-examples
|
Apache License 2.0
|
src/main/kotlin/com/brydonleonard/gatekey/persistence/spring/SpringConfig.kt
|
BrydonLeonard
| 692,129,514
| false
|
{"Kotlin": 74173, "Dockerfile": 292}
|
package com.brydonleonard.gatekey.persistence.spring
import com.brydonleonard.gatekey.Config
import com.brydonleonard.gatekey.persistence.model.ConversationStepModel
import com.brydonleonard.gatekey.persistence.model.DbMigrationModel
import com.brydonleonard.gatekey.persistence.model.FeedbackModel
import com.brydonleonard.gatekey.persistence.model.HouseholdModel
import com.brydonleonard.gatekey.persistence.model.KeyModel
import com.brydonleonard.gatekey.persistence.model.MetricModel
import com.brydonleonard.gatekey.persistence.model.UserModel
import com.brydonleonard.gatekey.persistence.model.UserRegistrationTokenModel
import com.j256.ormlite.dao.Dao
import com.j256.ormlite.dao.DaoManager
import com.j256.ormlite.jdbc.JdbcPooledConnectionSource
import com.j256.ormlite.support.ConnectionSource
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class SpringConfig {
@Bean(destroyMethod = "close")
fun connectionSource(config: Config): JdbcPooledConnectionSource =
JdbcPooledConnectionSource("jdbc:sqlite:${config.dbPath}")
@Bean
fun migrationDao(connectionSource: ConnectionSource): Dao<DbMigrationModel, Int> =
DaoManager.createDao(connectionSource, DbMigrationModel::class.java)
@Bean
fun conversationDao(connectionSource: ConnectionSource): Dao<ConversationStepModel, Long> =
DaoManager.createDao(connectionSource, ConversationStepModel::class.java)
@Bean
fun keyDao(connectionSource: ConnectionSource): Dao<KeyModel, String> =
DaoManager.createDao(connectionSource, KeyModel::class.java)
@Bean
fun userDao(connectionSource: ConnectionSource): Dao<UserModel, String> =
DaoManager.createDao(connectionSource, UserModel::class.java)
@Bean
fun userRegistrationTokenDao(connectionSource: ConnectionSource): Dao<UserRegistrationTokenModel, String> =
DaoManager.createDao(connectionSource, UserRegistrationTokenModel::class.java)
@Bean
fun metricDao(connectionSource: ConnectionSource): Dao<MetricModel, Long> =
DaoManager.createDao(connectionSource, MetricModel::class.java)
@Bean
fun feedbackDao(connectionSource: ConnectionSource): Dao<FeedbackModel, Int> =
DaoManager.createDao(connectionSource, FeedbackModel::class.java)
@Bean
fun householdDao(connectionSource: ConnectionSource): Dao<HouseholdModel, String> =
DaoManager.createDao(connectionSource, HouseholdModel::class.java)
}
| 0
|
Kotlin
|
0
| 0
|
c206ad07da679b7ed35a45c9ad539482e76f6b7f
| 2,556
|
GateKey
|
MIT License
|
extension/core/src/main/kotlin/io/holunda/camunda/bpm/data/CamundaBpmDataKotlin.kt
|
holunda-io
| 213,882,987
| false
| null |
package io.holunda.camunda.bpm.data
import io.holunda.camunda.bpm.data.factory.*
import java.util.*
/**
* Provides reified methods for variable factory construction.
*/
object CamundaBpmDataKotlin {
/**
* Creates a string variable factory.
*
* @param variableName name of the variable.
*
* @return variable factory for string.
*/
fun stringVariable(variableName: String): VariableFactory<String?> = BasicVariableFactory.forType<String?>(variableName)
/**
* Creates a date variable factory.
*
* @param variableName name of the variable.
*
* @return variable factory for date.
*/
fun dateVariable(variableName: String): VariableFactory<Date?> = BasicVariableFactory.forType(variableName)
/**
* Creates an integer variable factory.
*
* @param variableName name of the variable.
*
* @return variable factory for integer.
*/
fun intVariable(variableName: String): VariableFactory<Int?> = BasicVariableFactory.forType(variableName)
/**
* Creates a long variable factory.
*
* @param variableName name of the variable.
*
* @return variable factory for long.
*/
fun longVariable(variableName: String): VariableFactory<Long?> = BasicVariableFactory.forType(variableName)
/**
* Creates a short variable factory.
*
* @param variableName name of the variable.
*
* @return variable factory for short.
*/
fun shortVariable(variableName: String): VariableFactory<Short?> = BasicVariableFactory.forType(variableName)
/**
* Creates a double variable factory.
*
* @param variableName name of the variable.
*
* @return variable factory for double.
*/
fun doubleVariable(variableName: String): VariableFactory<Double?> = BasicVariableFactory.forType(variableName)
/**
* Creates a boolean variable factory.
*
* @param variableName name of the variable.
*
* @return variable factory for boolean.
*/
fun booleanVariable(variableName: String): VariableFactory<Boolean?> = BasicVariableFactory.forType(variableName)
/**
* Creates an uuid variable factory.
*
* @param variableName name of the variable.
* @return variable factory for uuid.
*/
fun uuidVariable(variableName: String): VariableFactory<UUID?> = BasicVariableFactory.forType(variableName)
/**
* Reified version of the basic variable factory.
* @param name The name of the variable.
* @param T The type of the variable.
* @return instance of [VariableFactory]
*/
inline fun <reified T : Any?> customVariable(name: String): VariableFactory<T> = BasicVariableFactory.forType(name)
/**
* Reified version of list variable factory.
* @param name The name of the variable.
* @param T The type of the variable.
* @return instance of [VariableFactory]
*/
inline fun <reified T : Any?> listVariable(name: String): VariableFactory<List<T>> = ListVariableFactory.forType(name)
/**
* Reified version of list variable factory.
* @param name The name of the variable.
* @param T The type of the variable.
* @return instance of [VariableFactory]
*/
inline fun <reified T : Any> listVariableNotNull(name: String): VariableFactory<List<T>> = ListVariableFactory.forType(name)
/**
* Reified version of list of maps variable factory.
* @param name The name of the variable.
* @param K The type of the variable key.
* @param V The type of the variable value.
* @return instance of [VariableFactory]
*/
inline fun <reified K : Any, reified V : Any?> listOfMapsVariable(name: String): VariableFactory<List<Map<K, V>>> = ListOfMapsVariableFactory.forType(name)
/**
* Reified version of list of maps variable factory.
* @param name The name of the variable.
* @param K The type of the variable key.
* @param V The type of the variable value.
* @return instance of [VariableFactory]
*/
inline fun <reified K : Any, reified V : Any?> listOfMapsVariableNotNull(name: String): VariableFactory<List<Map<K, V>>> = ListOfMapsVariableFactory.forType(name)
/**
* Reified version of set variable factory.
* @param name The name of the variable.
* @param T The type of the variable.
* @return instance of [VariableFactory]
*/
inline fun <reified T : Any?> setVariable(name: String): VariableFactory<Set<T>> = SetVariableFactory.forType(name)
/**
* Reified version of set variable factory.
* @param name The name of the variable.
* @param T The type of the variable.
* @return instance of [VariableFactory]
*/
inline fun <reified T : Any> setVariableNotNull(name: String): VariableFactory<Set<T>> = SetVariableFactory.forType(name)
/**
* Reified version of map variable factory.
* @param name The name of the variable.
* @param K The type of the variable key.
* @param V The type of the variable value.
* @return instance of [VariableFactory]
*/
inline fun <reified K : Any, reified V : Any?> mapVariable(name: String): VariableFactory<Map<K, V>> = MapVariableFactory.forType(name)
/**
* Reified version of map variable factory.
* @param name The name of the variable.
* @param K The type of the variable key.
* @param V The type of the variable value.
* @return instance of [VariableFactory]
*/
inline fun <reified K : Any, reified V : Any> mapVariableNotNullable(name: String): VariableFactory<Map<K, V>> = MapVariableFactory.forType(name)
}
| 17
| null |
6
| 31
|
9c3657be2ab4b5c92047aa145557ea66e4d690c5
| 5,421
|
camunda-bpm-data
|
Apache License 2.0
|
src/main/kotlin/com/liftric/dtcp/tasks/GetSuppressedVulnTask.kt
|
Liftric
| 639,795,618
| false
|
{"Kotlin": 53856}
|
package com.liftric.dtcp.tasks
import com.liftric.dtcp.model.Finding
import com.liftric.dtcp.service.DependencyTrack
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.provider.Property
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
abstract class GetSuppressedVulnTask : DefaultTask() {
@get:Input
abstract val apiKey: Property<String>
@get:Input
abstract val url: Property<String>
@get:Input
@get:Optional
abstract val projectUUID: Property<String>
@get:Input
@get:Optional
abstract val projectName: Property<String>
@get:Input
@get:Optional
abstract val projectVersion: Property<String>
@TaskAction
fun getSuppressedVulnTask() {
val apiKeyValue = apiKey.get()
val urlValue = url.get()
val projectUUIDValue = projectUUID.orNull
val projectNameValue = projectName.orNull
val projectVersionValue = projectVersion.orNull
val dt = DependencyTrack(apiKeyValue, urlValue)
val findings = when {
projectUUIDValue != null -> dt.getProjectFindingsById(projectUUIDValue)
projectNameValue != null && projectVersionValue != null -> {
val project = dt.getProject(projectNameValue, projectVersionValue)
dt.getProjectFindingsById(project.uuid)
}
else -> throw GradleException("Either projectUUID or projectName and projectVersion must be set")
}
printSuppressedVuln(findings)
}
private fun printSuppressedVuln(findings: List<Finding>) {
findings.forEach { finding ->
if (finding.analysis.isSuppressed) {
println(
"""
|vexComponent {
| purl = "${finding.component.purl}"
| vulnerability {
| id = "${finding.vulnerability.vulnId}"
| source = "${finding.vulnerability.source}"
| analysis = Vulnerability.Analysis.State.${finding.analysis.state}
| }
|}
""".trimMargin()
)
}
}
}
}
| 2
|
Kotlin
|
1
| 7
|
78a49818633c380bf0e41124e5b93ec0604586f4
| 2,306
|
dependency-track-companion-plugin
|
MIT License
|
core/src/test/kotlin/com/karumi/kotlinsnapshot/core/CameraTest.kt
|
Karumi
| 138,171,590
| false
| null |
package com.karumi.kotlinsnapshot.core
import com.karumi.kotlinsnapshot.matchWithSnapshot
import junit.framework.TestCase.fail
import org.junit.Test
class CameraTest {
companion object {
private const val WILL_NOT_MATCH = "will not match"
}
data class User(val id: Int, val name: String)
@Test
fun should_take_snapshots_of_data_classes() {
val u1 = User(1, "gabriel")
u1.matchWithSnapshot("should take snapshot of a data class")
}
@Test
fun should_take_snapshots_of_collections() {
val list = listOf(
User(1, "gabriel"),
User(2, "andres"),
User(3, "miguel"))
list.matchWithSnapshot("should take snapshot of a list")
}
@Test
fun should_take_snapshots_of_maps() {
val map = mapOf(
Pair(1, User(1, "gabriel")),
Pair(2, User(2, "andres")),
Pair(3, User(3, "miguel")))
map.matchWithSnapshot("should take snapshot of a map")
}
@Test
fun should_take_snapshots_of_json_strings() {
val json = """{"name":"gabriel","id":5}"""
json.matchWithSnapshot("should take snapshot of a json string")
}
@Test
fun should_take_snapshots_of_null_values() {
val nullString: String? = null
nullString.matchWithSnapshot("should take snapshots of null values")
}
@Test(expected = SnapshotException::class)
fun should_throw_snapshot_exception_when_not_match() {
WILL_NOT_MATCH.matchWithSnapshot("should throw snapshot exception when not match")
}
@Test
fun `should_throw_snapshot_exception_with_junit_diff_message`() {
try {
WILL_NOT_MATCH.matchWithSnapshot("should throw snapshot exception when not match")
fail("should throw snapshot exception to match actual value")
} catch (snapshotException: SnapshotException) {
snapshotException.message!!.matchWithSnapshot()
}
}
@Test
fun should_not_throw_snapshot_exception_because_of_Windows_line_endings() {
val stringWithWindowsLineEndings = "Line 1\nLine 2\n"
stringWithWindowsLineEndings.matchWithSnapshot(
"should not throw snapshot exception because of Windows line endings"
)
}
}
| 9
| null |
14
| 147
|
69fba61ca93080866a7ee90713595e1ead0bf1ba
| 2,286
|
KotlinSnapshot
|
MIT License
|
domain/src/main/kotlin/com/seanshubin/code/structure/domain/CreateFileCommand.kt
|
SeanShubin
| 678,139,745
| false
| null |
package com.seanshubin.code.structure.domain
import java.nio.charset.StandardCharsets
import java.nio.file.Path
data class CreateFileCommand(val path: Path, val lines: List<String>) : Command {
override fun execute(environment: Environment) {
environment.files.createDirectories(path.parent)
environment.files.write(path, lines, StandardCharsets.UTF_8)
}
}
| 0
|
Kotlin
|
0
| 0
|
2625bb5033029187730efc1ea6650e2034c7fc88
| 383
|
code-structure-2
|
The Unlicense
|
app/src/main/java/com/orange/ods/app/ui/AppBarState.kt
|
Orange-OpenSource
| 440,548,737
| false
| null |
/*
* Software Name: Orange Design System
* SPDX-FileCopyrightText: Copyright (c) Orange SA
* SPDX-License-Identifier: MIT
*
* This software is distributed under the MIT licence,
* the text of which is available at https://opensource.org/license/MIT/
* or see the "LICENSE" file for more details.
*
* Software description: Android library of reusable graphical components
*/
package com.orange.ods.app.ui
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.TextFieldValue
import com.orange.ods.app.R
import com.orange.ods.app.domain.recipes.LocalRecipes
import com.orange.ods.app.ui.AppBarAction.Companion.defaultActions
import com.orange.ods.app.ui.components.appbars.top.TopAppBarCustomizationState
import com.orange.ods.app.ui.components.utilities.clickOnElement
import com.orange.ods.app.ui.utilities.NavigationItem
import com.orange.ods.compose.component.appbar.top.OdsTopAppBar
import com.orange.ods.compose.component.menu.OdsDropdownMenu
import com.orange.ods.extension.orElse
import kotlin.math.max
val LocalAppBarManager = staticCompositionLocalOf<AppBarManager> { error("CompositionLocal AppBarManager not present") }
interface AppBarManager {
var searchedText: TextFieldValue
fun setCustomAppBar(customAppBarConfiguration: CustomAppBarConfiguration)
fun updateAppBarTabs(tabsConfiguration: TabsConfiguration)
fun clearAppBarTabs()
}
/**
* AppBar state source of truth.
*
* The app bar is managed according to the [Screen] displayed except if it has a custom app bar or if the screen cannot be found in the app [Screen]s (for
* example an about module screen). In this case, the app bar is displayed according to the provided [CustomAppBarConfiguration].
*/
class AppBarState(
private val navigationState: AppNavigationState,
searchedText: MutableState<TextFieldValue>,
private val customAppBarConfiguration: MutableState<CustomAppBarConfiguration>,
val tabsState: AppBarTabsState
) : AppBarManager {
private val isCustom: Boolean
@Composable get() = navigationState.currentScreen?.hasCustomAppBar != false
private val showNavigationIcon: Boolean
@Composable get() = (isCustom && customAppBarConfiguration.value.isNavigationIconEnabled)
|| (!isCustom && navigationState.currentScreen?.isHome(navigationState.previousRoute) == false)
val type: Screen.TopAppBarType
@Composable get() = navigationState.currentScreen?.topAppBarType.orElse { Screen.TopAppBarType.Default }
val title: String
@Composable get() = if (isCustom) {
customAppBarConfiguration.value.title
} else {
navigationState.currentScreen?.title?.asString().orEmpty()
}
val actions: List<OdsTopAppBar.ActionButton>
@Composable get() {
val screenAppBarActions = navigationState.currentScreen?.getAppBarActions(navigationState.previousRoute).orEmpty()
return if (isCustom) {
val context = LocalContext.current
val customActionCount = max(0, customAppBarConfiguration.value.actionCount - AppBarAction.defaultActions.size)
val customActions = NavigationItem.entries
.take(customActionCount)
.map {
val contentDescription = stringResource(id = it.textResId)
OdsTopAppBar.ActionButton(painter = painterResource(id = it.iconResId), contentDescription = contentDescription) {
clickOnElement(context, contentDescription)
}
}
screenAppBarActions.take(customAppBarConfiguration.value.actionCount) + customActions
} else {
screenAppBarActions
}
}
val overflowMenuItems: List<OdsDropdownMenu.Item>
@Composable get() = if (isCustom && customAppBarConfiguration.value.isOverflowMenuEnabled) {
val context = LocalContext.current
LocalRecipes.current.map { recipe ->
OdsDropdownMenu.Item(
text = recipe.title,
onClick = { clickOnElement(context, recipe.title) }
)
}
} else {
emptyList()
}
val hasScrollBehavior: Boolean
get() = customAppBarConfiguration.value.scrollBehavior != TopAppBarCustomizationState.ScrollBehavior.None
@Composable
fun getNavigationIcon(upPress: () -> Unit) = if (showNavigationIcon) {
OdsTopAppBar.NavigationIcon(Icons.Filled.ArrowBack, stringResource(id = R.string.top_app_bar_back_icon_desc), upPress)
} else {
null
}
// ----------------------------------------------------------
// AppBarManager implementation
// ----------------------------------------------------------
override var searchedText by searchedText
override fun setCustomAppBar(customAppBarConfiguration: CustomAppBarConfiguration) {
this.customAppBarConfiguration.value = customAppBarConfiguration
}
override fun updateAppBarTabs(tabsConfiguration: TabsConfiguration) {
tabsState.updateAppBarTabs(tabsConfiguration)
}
override fun clearAppBarTabs() {
tabsState.clearAppBarTabs()
}
}
@Composable
fun rememberAppBarState(
navigationState: AppNavigationState,
searchedText: MutableState<TextFieldValue> = remember { mutableStateOf(TextFieldValue("")) },
customAppBarConfiguration: MutableState<CustomAppBarConfiguration> = remember { mutableStateOf(CustomAppBarConfiguration.Default) },
tabsState: AppBarTabsState = rememberAppBarTabsState()
) = remember(navigationState, searchedText, customAppBarConfiguration, tabsState) {
AppBarState(navigationState, searchedText, customAppBarConfiguration, tabsState)
}
data class CustomAppBarConfiguration constructor(
val title: String,
val actionCount: Int,
val isNavigationIconEnabled: Boolean = true,
val isLarge: Boolean = false,
val scrollBehavior: TopAppBarCustomizationState.ScrollBehavior = TopAppBarCustomizationState.ScrollBehavior.Collapsible,
val isOverflowMenuEnabled: Boolean = false
) {
companion object {
val Default = CustomAppBarConfiguration(
title = "",
actionCount = defaultActions.size,
)
}
}
| 83
| null |
9
| 17
|
f3b84c4cb002c760ec3d7458b427d7b011104d14
| 6,873
|
ods-android
|
MIT License
|
tony-boot-demo/tony-dto/src/main/kotlin/com/tony/dto/req/UserLoginReq.kt
|
beingEggache
| 312,472,927
| false
|
{"Java": 1825396, "HTML": 354682, "Kotlin": 287327, "Dockerfile": 2745, "Shell": 2105, "CSS": 1466}
|
package com.tony.dto.req
import io.swagger.annotations.ApiModel
import io.swagger.annotations.ApiModelProperty
import javax.validation.constraints.NotBlank
/**
*
* @author tangli
* @since 2020-11-03 14:40
*/
@ApiModel("登录请求")
data class UserLoginReq(
@ApiModelProperty("用户名", required = true)
@get:NotBlank(message = "请输入用户名")
val userName: String?,
@ApiModelProperty("密码", required = true)
@get:NotBlank(message = "请输入密码")
val pwd: String?,
)
| 1
| null |
1
| 1
|
1c2991364067f3c28e7f99cd46df3e8f4000b18c
| 477
|
tony-boot
|
MIT License
|
src/main/kotlin/jp/nephy/penicillin/endpoints/stream/Sample.kt
|
colt005
| 186,767,944
| true
|
{"Kotlin": 1199305}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType")
package jp.nephy.penicillin.endpoints.stream
import jp.nephy.penicillin.core.request.EndpointHost
import jp.nephy.penicillin.core.request.action.StreamApiAction
import jp.nephy.penicillin.core.session.get
import jp.nephy.penicillin.core.streaming.handler.SampleStreamHandler
import jp.nephy.penicillin.core.streaming.listener.SampleStreamListener
import jp.nephy.penicillin.endpoints.Option
import jp.nephy.penicillin.endpoints.Stream
/**
* Returns a small random sample of all public statuses via a stream. The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/tweets/sample-realtime/api-reference/get-statuses-sample)
*
* @param delimited Specifies whether messages should be length-delimited. See [delimited](https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/connecting) or more information.
* @param stallWarnings Specifies whether stall warnings should be delivered. See [stall_warnings](https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/connecting#stalls) for more information.
* @param language Not documented yet.
* @param options Optional. Custom parameters of this request.
* @receiver [Stream] endpoint instance.
* @return [StreamApiAction] for [SampleStreamHandler] handler with [SampleStreamListener] listener.
*/
fun Stream.sample(
delimited: StreamDelimitedBy = StreamDelimitedBy.Default,
stallWarnings: Boolean? = null,
language: String? = null,
vararg options: Option
) = client.session.get("/1.1/statuses/sample.json", EndpointHost.Stream) {
parameter(
"delimited" to delimited.value,
"stall_warning" to stallWarnings,
"language" to language,
*options
)
}.stream<SampleStreamListener, SampleStreamHandler>()
/**
* Shorthand property to [Stream.sample].
* @see Stream.sample
*/
val Stream.sample
get() = sample()
| 0
|
Kotlin
|
0
| 0
|
d5860e3d9c7c95c7d7ec1879c080b114ca77e127
| 3,217
|
Penicillin
|
MIT License
|
spanly/src/main/kotlin/io/jmdg/spanly/Spanly.kt
|
joshuadeguzman
| 170,096,158
| false
| null |
package io.jmdg.spanly
import android.text.SpannableStringBuilder
import io.jmdg.spanly.internal.helpers.span
/**
* Created by <NAME> on 2/11/19.
*/
class Spanly : SpannableStringBuilder() {
companion object {
val TAG = Spanly::class.java.simpleName
}
override fun append(text: CharSequence): Spanly {
super.append(text)
return this
}
fun append(text: CharSequence, vararg spans: Any): Spanly {
var _text = text
spans.forEach { span ->
_text = span(_text, span)
}
super.append(_text)
return this
}
fun space() : Spanly {
super.append(" ")
return this
}
fun next() : Spanly {
super.append("\n")
return this
}
}
| 0
| null |
6
| 5
|
65dac1490e07859e7a1221acc79a4cd04d4c4ac4
| 767
|
Spanly
|
MIT License
|
ui/src/main/java/dev/sunnyday/core/ui/fragment/CoreFragment.kt
|
SunnyDayDev
| 178,215,276
| false
| null |
package dev.sunnyday.core.ui.fragment
import android.content.Intent
import androidx.fragment.app.Fragment
import dev.sunnyday.core.ui.listener.*
/**
* Created by <NAME> (SunnyDay.Dev) on 2019-03-28.
* mail: <EMAIL>
*/
open class CoreFragment: Fragment(),
OnBackPressedListener.Registry.Owner,
OnActivityResultListener.Registry.Owner,
OnRequestPermissionResultListener.Registry.Owner,
OnBackPressedListener {
private val activityOnBackPressedListenerDelegate: OnBackPressedListener = object : OnBackPressedListener {
override fun onBackPressed(): Boolean {
if (isHidden) return false
return this@CoreFragment.onBackPressed()
}
}
override val onBackPressedRegistry: OnBackPressedListener.Registry =
DefaultOnBackPressedRegistry()
override val onActivityResultRegistry: OnActivityResultListener.Registry =
DefaultOnActivityResultRegistry()
override val onRequestPermissionResultRegistry: OnRequestPermissionResultListener.Registry =
DefaultOnRequestPermissionResultRegistry()
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (!onActivityResultRegistry.onActivityResult(requestCode, resultCode, data)) {
onUnhandledActivityResult(requestCode, resultCode, data)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (!onRequestPermissionResultRegistry.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
onUnhandledRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
override fun onStart() {
super.onStart()
(activity as? OnBackPressedListener.Registry.Owner)
?.onBackPressedRegistry
?.add(activityOnBackPressedListenerDelegate)
}
override fun onStop() {
super.onStop()
(activity as? OnBackPressedListener.Registry.Owner)
?.onBackPressedRegistry
?.remove(activityOnBackPressedListenerDelegate)
}
override fun onBackPressed(): Boolean =
onBackPressedRegistry.onBackPressed() || onUnhandledBackPressed()
protected open fun onUnhandledBackPressed(): Boolean = false
protected open fun onUnhandledRequestPermissionsResult(requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
protected open fun onUnhandledActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
}
}
| 0
|
Kotlin
|
0
| 0
|
ec79bad3cc61ecb2e0b2fa651caa6f73ccf39b33
| 2,818
|
core
|
MIT License
|
ui/src/main/java/dev/sunnyday/core/ui/fragment/CoreFragment.kt
|
SunnyDayDev
| 178,215,276
| false
| null |
package dev.sunnyday.core.ui.fragment
import android.content.Intent
import androidx.fragment.app.Fragment
import dev.sunnyday.core.ui.listener.*
/**
* Created by <NAME> (SunnyDay.Dev) on 2019-03-28.
* mail: <EMAIL>
*/
open class CoreFragment: Fragment(),
OnBackPressedListener.Registry.Owner,
OnActivityResultListener.Registry.Owner,
OnRequestPermissionResultListener.Registry.Owner,
OnBackPressedListener {
private val activityOnBackPressedListenerDelegate: OnBackPressedListener = object : OnBackPressedListener {
override fun onBackPressed(): Boolean {
if (isHidden) return false
return this@CoreFragment.onBackPressed()
}
}
override val onBackPressedRegistry: OnBackPressedListener.Registry =
DefaultOnBackPressedRegistry()
override val onActivityResultRegistry: OnActivityResultListener.Registry =
DefaultOnActivityResultRegistry()
override val onRequestPermissionResultRegistry: OnRequestPermissionResultListener.Registry =
DefaultOnRequestPermissionResultRegistry()
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (!onActivityResultRegistry.onActivityResult(requestCode, resultCode, data)) {
onUnhandledActivityResult(requestCode, resultCode, data)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (!onRequestPermissionResultRegistry.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
onUnhandledRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
override fun onStart() {
super.onStart()
(activity as? OnBackPressedListener.Registry.Owner)
?.onBackPressedRegistry
?.add(activityOnBackPressedListenerDelegate)
}
override fun onStop() {
super.onStop()
(activity as? OnBackPressedListener.Registry.Owner)
?.onBackPressedRegistry
?.remove(activityOnBackPressedListenerDelegate)
}
override fun onBackPressed(): Boolean =
onBackPressedRegistry.onBackPressed() || onUnhandledBackPressed()
protected open fun onUnhandledBackPressed(): Boolean = false
protected open fun onUnhandledRequestPermissionsResult(requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
protected open fun onUnhandledActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
}
}
| 0
|
Kotlin
|
0
| 0
|
ec79bad3cc61ecb2e0b2fa651caa6f73ccf39b33
| 2,818
|
core
|
MIT License
|
app/src/main/java/com/telenav/osv/data/collector/phonedata/collector/HardwareInfoCollector.kt
|
kartaview
| 63,806,526
| false
| null |
package com.telenav.osv.data.collector.phonedata.collector
import android.os.Build
import android.os.Handler
import com.telenav.osv.data.collector.datatype.datatypes.HardwareInfoObject
import com.telenav.osv.data.collector.datatype.util.LibraryUtil
import com.telenav.osv.data.collector.phonedata.manager.PhoneDataListener
class HardwareInfoCollector(phoneDataListener: PhoneDataListener?, notifyHandler: Handler?) : PhoneCollector(phoneDataListener, notifyHandler) {
/**
* Retrieve the producer and the model of the device and send the information to the client
* The method is called once when the service is started
*/
fun sendHardwareInformation() {
onNewSensorEvent(HardwareInfoObject(Build.MODEL, LibraryUtil.PHONE_SENSOR_READ_SUCCESS))
}
}
| 76
|
Java
|
30
| 130
|
66eb0ee1ab093562e2867087084b26803fe58174
| 783
|
android
|
MIT License
|
GameLib/src/main/kotlin/fr/o80/gamelib/service/condition/Operation.kt
|
olivierperez
| 307,115,498
| false
| null |
package fr.o80.gamelib.service.condition
enum class Operation {
EQUAL,
DIFFERENT,
GTE,
LTE
}
| 1
| null |
1
| 4
|
913367faa0ffa72002e8b6ab88f6592f2e4b6028
| 110
|
SoulGame
|
Apache License 2.0
|
boxicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/boxicons/boxicons/solid/BxsMedal.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 34345428}
|
package com.woowla.compose.icon.collections.boxicons.boxicons.solid
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 com.woowla.compose.icon.collections.boxicons.boxicons.SolidGroup
public val SolidGroup.BxsMedal: ImageVector
get() {
if (_bxsMedal != null) {
return _bxsMedal!!
}
_bxsMedal = Builder(name = "BxsMedal", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(17.0f, 2.0f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(4.059f)
arcToRelative(8.946f, 8.946f, 0.0f, false, true, 4.0f, 1.459f)
lineTo(17.0f, 2.0f)
close()
moveTo(11.0f, 2.0f)
lineTo(7.0f, 2.0f)
verticalLineToRelative(5.518f)
arcToRelative(8.946f, 8.946f, 0.0f, false, true, 4.0f, -1.459f)
lineTo(11.0f, 2.0f)
close()
moveTo(12.0f, 22.0f)
arcToRelative(7.0f, 7.0f, 0.0f, true, false, 0.0f, -14.0f)
arcToRelative(7.0f, 7.0f, 0.0f, false, false, 0.0f, 14.0f)
close()
moveTo(10.775f, 13.481f)
lineTo(12.0f, 11.0f)
lineToRelative(1.225f, 2.481f)
lineToRelative(2.738f, 0.397f)
lineToRelative(-1.981f, 1.932f)
lineToRelative(0.468f, 2.727f)
lineTo(12.0f, 17.25f)
lineToRelative(-2.449f, 1.287f)
lineToRelative(0.468f, -2.727f)
lineToRelative(-1.981f, -1.932f)
lineToRelative(2.737f, -0.397f)
close()
}
}
.build()
return _bxsMedal!!
}
private var _bxsMedal: ImageVector? = null
| 0
|
Kotlin
|
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 2,529
|
compose-icon-collections
|
MIT License
|
app/src/main/java/com/linhtetko/efficientweatherapp/di/RepositoryModule.kt
|
lin-htet-ko
| 726,358,254
| false
|
{"Kotlin": 95925, "CMake": 1249, "C++": 502}
|
package com.linhtetko.efficientweatherapp.di
import com.linhtetko.domain.di.DataModule
import com.linhtetko.domain.repositories.WeatherRepoImpl
import com.linhtetko.domain.repositories.WeatherRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class RepositoryModule {
@Provides
@Singleton
fun bindWeatherRepo(dataModule: DataModule): WeatherRepository {
return WeatherRepoImpl(dataModule)
}
}
| 0
|
Kotlin
|
0
| 0
|
dea33ddf60850d8e3ec8fc6d121cb161ea65bd1a
| 577
|
efficient_weather_app
|
Apache License 2.0
|
app/src/main/java/com/example/studysmart/presentation/dashboard/DashboardScreen.kt
|
CodeInKotLang
| 702,698,514
| false
|
{"Kotlin": 145710}
|
package com.example.studysmart.presentation.dashboard
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.studysmart.R
import com.example.studysmart.domain.model.Session
import com.example.studysmart.domain.model.Subject
import com.example.studysmart.domain.model.Task
import com.example.studysmart.presentation.components.AddSubjectDialog
import com.example.studysmart.presentation.components.CountCard
import com.example.studysmart.presentation.components.DeleteDialog
import com.example.studysmart.presentation.components.SubjectCard
import com.example.studysmart.presentation.components.studySessionsList
import com.example.studysmart.presentation.components.tasksList
import com.example.studysmart.presentation.destinations.SessionScreenRouteDestination
import com.example.studysmart.presentation.destinations.SubjectScreenRouteDestination
import com.example.studysmart.presentation.destinations.TaskScreenRouteDestination
import com.example.studysmart.presentation.subject.SubjectScreenNavArgs
import com.example.studysmart.presentation.task.TaskScreenNavArgs
import com.example.studysmart.util.SnackbarEvent
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.annotation.RootNavGraph
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.collectLatest
@RootNavGraph(start = true)
@Destination
@Composable
fun DashboardScreenRoute(
navigator: DestinationsNavigator
) {
val viewModel: DashboardViewModel = hiltViewModel()
val state by viewModel.state.collectAsStateWithLifecycle()
val tasks by viewModel.tasks.collectAsStateWithLifecycle()
val recentSessions by viewModel.recentSessions.collectAsStateWithLifecycle()
DashboardScreen(
state = state,
tasks = tasks,
recentSessions = recentSessions,
onEvent = viewModel::onEvent,
snackbarEvent = viewModel.snackbarEventFlow,
onSubjectCardClick = { subjectId ->
subjectId?.let {
val navArg = SubjectScreenNavArgs(subjectId = subjectId)
navigator.navigate(SubjectScreenRouteDestination(navArgs = navArg))
}
},
onTaskCardClick = { taskId ->
val navArg = TaskScreenNavArgs(taskId = taskId, subjectId = null)
navigator.navigate(TaskScreenRouteDestination(navArgs = navArg))
},
onStartSessionButtonClick = {
navigator.navigate(SessionScreenRouteDestination())
}
)
}
@Composable
private fun DashboardScreen(
state: DashboardState,
tasks: List<Task>,
recentSessions: List<Session>,
onEvent: (DashboardEvent) -> Unit,
snackbarEvent: SharedFlow<SnackbarEvent>,
onSubjectCardClick: (Int?) -> Unit,
onTaskCardClick: (Int?) -> Unit,
onStartSessionButtonClick: () -> Unit
) {
var isAddSubjectDialogOpen by rememberSaveable { mutableStateOf(false) }
var isDeleteSessionDialogOpen by rememberSaveable { mutableStateOf(false) }
val snackbarHostState = remember { SnackbarHostState() }
LaunchedEffect(key1 = true) {
snackbarEvent.collectLatest { event ->
when(event) {
is SnackbarEvent.ShowSnackbar -> {
snackbarHostState.showSnackbar(
message = event.message,
duration = event.duration
)
}
SnackbarEvent.NavigateUp -> {}
}
}
}
AddSubjectDialog(
isOpen = isAddSubjectDialogOpen,
subjectName = state.subjectName,
goalHours = state.goalStudyHours,
selectedColors = state.subjectCardColors,
onSubjectNameChange = { onEvent(DashboardEvent.OnSubjectNameChange(it)) },
onGoalHoursChange = { onEvent(DashboardEvent.OnGoalStudyHoursChange(it)) },
onColorChange = { onEvent(DashboardEvent.OnSubjectCardColorChange(it)) },
onDismissRequest = { isAddSubjectDialogOpen = false },
onConfirmButtonClick = {
onEvent(DashboardEvent.SaveSubject)
isAddSubjectDialogOpen = false
}
)
DeleteDialog(
isOpen = isDeleteSessionDialogOpen,
title = "Delete Session?",
bodyText = "Are you sure, you want to delete this session? Your studied hours will be reduced " +
"by this session time. This action can not be undone.",
onDismissRequest = { isDeleteSessionDialogOpen = false },
onConfirmButtonClick = {
onEvent(DashboardEvent.DeleteSession)
isDeleteSessionDialogOpen = false
}
)
Scaffold(
snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
topBar = { DashboardScreenTopBar() }
) { paddingValues ->
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
) {
item {
CountCardsSection(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
subjectCount = state.totalSubjectCount,
studiedHours = state.totalStudiedHours.toString(),
goalHours = state.totalGoalStudyHours.toString()
)
}
item {
SubjectCardsSection(
modifier = Modifier.fillMaxWidth(),
subjectList = state.subjects,
onAddIconClicked = { isAddSubjectDialogOpen = true },
onSubjectCardClick = onSubjectCardClick
)
}
item {
Button(
onClick = onStartSessionButtonClick,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 48.dp, vertical = 20.dp)
) {
Text(text = "Start Study Session")
}
}
tasksList(
sectionTitle = "UPCOMING TASKS",
emptyListText = "You don't have any upcoming tasks.\n " +
"Click the + button in subject screen to add new task.",
tasks = tasks,
onCheckBoxClick = { onEvent(DashboardEvent.OnTaskIsCompleteChange(it)) },
onTaskCardClick = onTaskCardClick
)
item {
Spacer(modifier = Modifier.height(20.dp))
}
studySessionsList(
sectionTitle = "RECENT STUDY SESSIONS",
emptyListText = "You don't have any recent study sessions.\n " +
"Start a study session to begin recording your progress.",
sessions = recentSessions,
onDeleteIconClick = {
onEvent(DashboardEvent.OnDeleteSessionButtonClick(it))
isDeleteSessionDialogOpen = true
}
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun DashboardScreenTopBar() {
CenterAlignedTopAppBar(
title = {
Text(
text = "StudySmart",
style = MaterialTheme.typography.headlineMedium
)
}
)
}
@Composable
private fun CountCardsSection(
modifier: Modifier,
subjectCount: Int,
studiedHours: String,
goalHours: String
) {
Row(modifier = modifier) {
CountCard(
modifier = Modifier.weight(1f),
headingText = "Subject Count",
count = "$subjectCount"
)
Spacer(modifier = Modifier.width(10.dp))
CountCard(
modifier = Modifier.weight(1f),
headingText = "Studied Hours",
count = studiedHours
)
Spacer(modifier = Modifier.width(10.dp))
CountCard(
modifier = Modifier.weight(1f),
headingText = "Goal Study Hours",
count = goalHours
)
}
}
@Composable
private fun SubjectCardsSection(
modifier: Modifier,
subjectList: List<Subject>,
emptyListText: String = "You don't have any subjects.\n Click the + button to add new subject.",
onAddIconClicked: () -> Unit,
onSubjectCardClick: (Int?) -> Unit
) {
Column(modifier = modifier) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = "SUBJECTS",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(start = 12.dp)
)
IconButton(onClick = onAddIconClicked) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Add Subject"
)
}
}
if (subjectList.isEmpty()) {
Image(
modifier = Modifier
.size(120.dp)
.align(Alignment.CenterHorizontally),
painter = painterResource(R.drawable.img_books),
contentDescription = emptyListText
)
Text(
modifier = Modifier.fillMaxWidth(),
text = emptyListText,
style = MaterialTheme.typography.bodySmall,
color = Color.Gray,
textAlign = TextAlign.Center
)
}
LazyRow(
horizontalArrangement = Arrangement.spacedBy(12.dp),
contentPadding = PaddingValues(start = 12.dp, end = 12.dp)
) {
items(subjectList) { subject ->
SubjectCard(
subjectName = subject.name,
gradientColors = subject.colors.map { Color(it) },
onClick = { onSubjectCardClick(subject.subjectId) }
)
}
}
}
}
| 1
|
Kotlin
|
1
| 13
|
def9cbb2f47187fce7a3eb743b046928dfda7e74
| 12,041
|
StudySmart
|
MIT License
|
example/android/app/src/main/kotlin/com/example/sms_export_import/sms_export_import_example/MainActivity.kt
|
kesmitopiwala
| 441,432,557
| false
|
{"Kotlin": 24640, "Dart": 8795}
|
package com.example.sms_export_import.sms_export_import_example
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
}
| 0
|
Kotlin
|
0
| 0
|
ab5f95a323b99b110e4868ad9014acfabba2213b
| 293
|
sms_export_import
|
MIT License
|
app/src/main/java/com/example/nextgen/nearby/UpdateMapListener.kt
|
Vishwajith-Shettigar
| 800,866,827
| false
|
{"Kotlin": 203666}
|
package com.example.nextgen.nearby
import com.example.model.Profile
interface UpdateMapListener {
fun updateMap(profile: Profile,outOfBound:Boolean)
}
| 30
|
Kotlin
|
49
| 17
|
553fd3b1fc6a8c3c26a944097326b051fbd8277f
| 155
|
NextGen
|
MIT License
|
src/main/kotlin/com/firsttimeinforever/intellij/pdf/viewer/ui/editor/ResourceLoader.kt
|
NikolaiSviridov
| 368,194,223
| true
|
{"Kotlin": 99005, "TypeScript": 29859, "Less": 1350, "HTML": 301}
|
package com.firsttimeinforever.intellij.pdf.viewer.ui.editor
import java.io.File
import java.io.FileNotFoundException
object ResourceLoader {
private val shouldFixPaths =
System.getProperty("os.name").toLowerCase().contains("windows")
fun load(file: File): ByteArray {
val targetPath = ensureCorrectFormedPath(file)
return this::class.java.getResourceAsStream(targetPath).use {
if (it == null) {
throw FileNotFoundException("Could not load resource file: $targetPath")
}
it.readBytes()
}
}
// Fix incorrect pathing on windows, duh
private fun ensureCorrectFormedPath(file: File): String {
if (shouldFixPaths) {
return file.toString().replace('\\', '/')
}
return file.toString()
}
}
| 0
|
Kotlin
|
0
| 0
|
7b0959e038a781fc5e98db60e6ccb6373f740709
| 834
|
intellij-pdf-viewer
|
MIT License
|
telegram-bot/src/main/kotlin/eu/vendeli/tgbot/types/internal/options/VideoOptions.kt
|
vendelieu
| 496,567,172
| false
| null |
package eu.vendeli.tgbot.types.internal.options
import eu.vendeli.tgbot.types.ParseMode
import eu.vendeli.tgbot.types.internal.ImplicitFile
data class VideoOptions(
var duration: Int? = null,
var height: Int? = null,
var width: Int? = null,
var supportsStreaming: Boolean? = null,
var thumb: ImplicitFile<*>? = null,
override var fileName: String? = null,
override var parseMode: ParseMode? = null,
override var disableNotification: Boolean? = null,
override var replyToMessageId: Long? = null,
override var allowSendingWithoutReply: Boolean? = null,
override var protectContent: Boolean? = null,
override var messageThreadId: Long? = null,
override var hasSpoiler: Boolean? = null,
) : OptionsInterface<VideoOptions>, OptionsCommon, OptionsParseMode, FileOptions, MediaSpoiler
| 2
|
Kotlin
|
3
| 92
|
637844da81647abd3f04401dd1961f8331dc69ad
| 832
|
telegram-bot
|
Apache License 2.0
|
telegram-bot/src/main/kotlin/eu/vendeli/tgbot/types/internal/options/VideoOptions.kt
|
vendelieu
| 496,567,172
| false
| null |
package eu.vendeli.tgbot.types.internal.options
import eu.vendeli.tgbot.types.ParseMode
import eu.vendeli.tgbot.types.internal.ImplicitFile
data class VideoOptions(
var duration: Int? = null,
var height: Int? = null,
var width: Int? = null,
var supportsStreaming: Boolean? = null,
var thumb: ImplicitFile<*>? = null,
override var fileName: String? = null,
override var parseMode: ParseMode? = null,
override var disableNotification: Boolean? = null,
override var replyToMessageId: Long? = null,
override var allowSendingWithoutReply: Boolean? = null,
override var protectContent: Boolean? = null,
override var messageThreadId: Long? = null,
override var hasSpoiler: Boolean? = null,
) : OptionsInterface<VideoOptions>, OptionsCommon, OptionsParseMode, FileOptions, MediaSpoiler
| 2
|
Kotlin
|
3
| 92
|
637844da81647abd3f04401dd1961f8331dc69ad
| 832
|
telegram-bot
|
Apache License 2.0
|
app/src/main/java/com/beone/kevin/ui/user/mainuser/MainUserFragment.kt
|
JamesSuryaSeputro
| 292,648,188
| false
|
{"Kotlin": 161424}
|
package com.beone.kevin.ui.user.mainuser
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.beone.kevin.R
import kotlinx.android.synthetic.main.main_user_fragment.*
import org.koin.androidx.viewmodel.ext.android.viewModel
class MainUserFragment : Fragment() {
companion object {
fun newInstance() = MainUserFragment()
}
private val viewModel: MainUserViewModel by viewModel<MainUserViewModel>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.main_user_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
btn_profile.setOnClickListener {
val action = MainUserFragmentDirections.actionMainUserFragmentToProfilTki(true)
this.findNavController().navigate(action)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ee14de1ea6d5b0a5f7399c4df7010f38e33bf2f4
| 1,135
|
KevinAndroid
|
Apache License 2.0
|
bot/connector-messenger/src/main/kotlin/model/send/MediaType.kt
|
theopenconversationkit
| 84,538,053
| false
| null |
/*
* Copyright (C) 2017 VSCT
*
* 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 fr.vsct.tock.bot.connector.messenger.model.send
import fr.vsct.tock.bot.engine.action.SendAttachment
/**
*
*/
enum class MediaType {
image, video;
fun toAttachmentType(): SendAttachment.AttachmentType =
when (this) {
image -> SendAttachment.AttachmentType.image
video -> SendAttachment.AttachmentType.video
}
}
| 163
| null |
127
| 475
|
890f69960997ae9146747d082d808d92ee407fcb
| 963
|
tock
|
Apache License 2.0
|
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/GithubPullRequestDetailsPanel.kt
|
soyzhc
| 161,265,572
| false
| null |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.details
import com.intellij.openapi.Disposable
import com.intellij.openapi.roots.ui.componentsList.components.ScrollablePanel
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.util.Disposer
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SideBorder
import com.intellij.util.ui.ComponentWithEmptyText
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBValue
import com.intellij.util.ui.StatusText
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser
import org.jetbrains.plugins.github.api.data.GithubPullRequestDetailedWithHtml
import org.jetbrains.plugins.github.api.data.GithubRepoDetailed
import org.jetbrains.plugins.github.pullrequest.avatars.CachingGithubAvatarIconsProvider
import org.jetbrains.plugins.github.pullrequest.data.service.GithubPullRequestsStateService
import org.jetbrains.plugins.github.util.GithubSharedProjectSettings
import java.awt.Graphics
import java.awt.event.AdjustmentListener
import javax.swing.BorderFactory
import javax.swing.JPanel
import kotlin.properties.Delegates
internal class GithubPullRequestDetailsPanel(private val sharedProjectSettings: GithubSharedProjectSettings,
private val stateService: GithubPullRequestsStateService,
iconProviderFactory: CachingGithubAvatarIconsProvider.Factory,
private val accountDetails: GithubAuthenticatedUser,
private val repoDetails: GithubRepoDetailed)
: JPanel(), ComponentWithEmptyText, Disposable {
private val emptyText = object : StatusText(this) {
override fun isStatusVisible() = details == null
}
private val iconsProvider = iconProviderFactory.create(JBValue.UIInteger("Profile.Icon.Size", 20), this)
private val metaPanel = GithubPullRequestMetadataPanel(iconsProvider).apply {
border = JBUI.Borders.empty(4, 8, 4, 8)
}
private val descriptionPanel = GithubPullRequestDescriptionPanel().apply {
border = JBUI.Borders.empty(4, 8, 8, 8)
}
private val statePanel = GithubPullRequestStatePanel(stateService).apply {
border = BorderFactory.createCompoundBorder(IdeBorderFactory.createBorder(SideBorder.TOP),
JBUI.Borders.empty(8))
}
var details: GithubPullRequestDetailedWithHtml?
by Delegates.observable<GithubPullRequestDetailedWithHtml?>(null) { _, _, newValue ->
descriptionPanel.description = newValue?.bodyHtml
metaPanel.direction = newValue?.let { it.head to it.base }
metaPanel.reviewers = newValue?.requestedReviewers
metaPanel.assignees = newValue?.assignees
metaPanel.labels = newValue?.labels
statePanel.state = newValue?.let {
GithubPullRequestStatePanel.State.create(accountDetails, repoDetails, it, stateService.isBusy(it.number),
sharedProjectSettings.pullRequestMergeForbidden)
}
}
init {
layout = MigLayout(LC().flowY().fill()
.gridGap("0", "0")
.insets("0", "0", "0", "0"))
isOpaque = false
val scrollPane = ScrollPaneFactory.createScrollPane(ScrollablePanel(VerticalFlowLayout(0, 0)).apply {
add(metaPanel)
add(descriptionPanel)
isOpaque = false
}, true).apply {
viewport.isOpaque = false
isOpaque = false
}
add(scrollPane, CC().minWidth("0").minHeight("0").growX().growY().growPrioY(0).shrinkPrioY(0))
add(statePanel, CC().growX().growY().growPrioY(1).shrinkPrioY(1).pushY())
val verticalScrollBar = scrollPane.verticalScrollBar
verticalScrollBar.addAdjustmentListener(AdjustmentListener {
if (verticalScrollBar.maximum - verticalScrollBar.visibleAmount >= 1) {
statePanel.border = BorderFactory.createCompoundBorder(IdeBorderFactory.createBorder(SideBorder.TOP),
JBUI.Borders.empty(8))
}
else {
statePanel.border = JBUI.Borders.empty(8)
}
})
stateService.addPullRequestBusyStateListener(this) {
if (it == statePanel.state?.number)
statePanel.state = statePanel.state?.copy(busy = stateService.isBusy(it))
}
details = null
Disposer.register(this, iconsProvider)
}
override fun getEmptyText() = emptyText
override fun paintComponent(g: Graphics?) {
super.paintComponent(g)
emptyText.paint(this, g)
}
override fun dispose() {}
}
| 4
| null |
1
| 1
|
e45818aa6b54215ed0c69d1ad81abc7cac3240f8
| 4,899
|
intellij-community
|
Apache License 2.0
|
plugin-bsp/src/main/kotlin/org/jetbrains/plugins/bsp/magicmetamodel/impl/workspacemodel/impl/updaters/ModuleEntityUpdater.kt
|
JetBrains
| 826,262,028
| false
| null |
package org.jetbrains.plugins.bsp.impl.magicmetamodel.impl.workspacemodel.impl.updaters
import com.intellij.openapi.module.impl.ModuleManagerEx
import com.intellij.openapi.project.Project
import com.intellij.platform.workspace.jps.entities.DependencyScope
import com.intellij.platform.workspace.jps.entities.LibraryDependency
import com.intellij.platform.workspace.jps.entities.LibraryId
import com.intellij.platform.workspace.jps.entities.LibraryTableId
import com.intellij.platform.workspace.jps.entities.ModuleCustomImlDataEntity
import com.intellij.platform.workspace.jps.entities.ModuleDependency
import com.intellij.platform.workspace.jps.entities.ModuleDependencyItem
import com.intellij.platform.workspace.jps.entities.ModuleEntity
import com.intellij.platform.workspace.jps.entities.ModuleId
import com.intellij.platform.workspace.jps.entities.customImlData
import com.intellij.platform.workspace.jps.entities.modifyModuleEntity
import com.intellij.platform.workspace.storage.EntitySource
import com.intellij.platform.workspace.storage.MutableEntityStorage
import com.intellij.platform.workspace.storage.impl.url.toVirtualFileUrl
import com.intellij.workspaceModel.ide.impl.LegacyBridgeJpsEntitySourceFactory
import org.jetbrains.bsp.protocol.jpsCompilation.utils.JpsConstants
import org.jetbrains.bsp.protocol.jpsCompilation.utils.JpsFeatureFlags
import org.jetbrains.bsp.protocol.jpsCompilation.utils.JpsPaths
import org.jetbrains.plugins.bsp.impl.projectAware.BspWorkspace
import org.jetbrains.plugins.bsp.impl.target.temporaryTargetUtils
import org.jetbrains.plugins.bsp.workspacemodel.entities.BspDummyEntitySource
import org.jetbrains.plugins.bsp.workspacemodel.entities.BspModuleEntitySource
import org.jetbrains.plugins.bsp.workspacemodel.entities.GenericModuleInfo
import org.jetbrains.plugins.bsp.workspacemodel.entities.IntermediateLibraryDependency
import org.jetbrains.plugins.bsp.workspacemodel.entities.IntermediateModuleDependency
internal class ModuleEntityUpdater(
private val workspaceModelEntityUpdaterConfig: WorkspaceModelEntityUpdaterConfig,
private val defaultDependencies: List<ModuleDependencyItem> = ArrayList(),
) : WorkspaceModelEntityWithoutParentModuleUpdater<GenericModuleInfo, ModuleEntity> {
override fun addEntity(entityToAdd: GenericModuleInfo): ModuleEntity =
addModuleEntity(workspaceModelEntityUpdaterConfig.workspaceEntityStorageBuilder, entityToAdd)
private fun addModuleEntity(builder: MutableEntityStorage, entityToAdd: GenericModuleInfo): ModuleEntity {
val associatesDependencies = entityToAdd.associates.map { toModuleDependencyItemModuleDependency(it) }
val (libraryModulesDependencies, librariesDependencies) =
entityToAdd.librariesDependencies.partition {
!entityToAdd.isLibraryModule &&
workspaceModelEntityUpdaterConfig.project.temporaryTargetUtils.isLibraryModule(it.libraryName)
}
val modulesDependencies =
(entityToAdd.modulesDependencies + libraryModulesDependencies.toLibraryModuleDependencies()).map {
toModuleDependencyItemModuleDependency(it)
}
val dependencies =
defaultDependencies +
modulesDependencies +
librariesDependencies.map { toLibraryDependency(it, workspaceModelEntityUpdaterConfig.project) } +
associatesDependencies
val moduleEntityBuilder =
ModuleEntity(
name = entityToAdd.name,
dependencies = dependencies,
entitySource = toEntitySource(entityToAdd),
) {
this.type = entityToAdd.type
}
val moduleEntity = builder.addEntity(moduleEntityBuilder)
val imlData =
ModuleCustomImlDataEntity(
customModuleOptions = entityToAdd.capabilities.asMap() + entityToAdd.languageIdsAsSingleEntryMap,
entitySource = moduleEntity.entitySource,
) {
this.rootManagerTagCustomData = null
this.module = moduleEntityBuilder
}
// TODO: use a separate entity instead of imlData
return builder.modifyModuleEntity(moduleEntity) {
this.customImlData = imlData
}
}
private fun List<IntermediateLibraryDependency>.toLibraryModuleDependencies() = this.map { IntermediateModuleDependency(it.libraryName) }
private fun toEntitySource(entityToAdd: GenericModuleInfo): EntitySource =
when {
entityToAdd.isDummy -> BspDummyEntitySource
!JpsFeatureFlags.isJpsCompilationEnabled ||
entityToAdd.languageIds.any { it !in JpsConstants.SUPPORTED_LANGUAGES } -> BspModuleEntitySource(entityToAdd.name)
else ->
LegacyBridgeJpsEntitySourceFactory.createEntitySourceForModule(
project = workspaceModelEntityUpdaterConfig.project,
baseModuleDir =
JpsPaths
.getJpsImlModulesPath(workspaceModelEntityUpdaterConfig.projectBasePath)
.toVirtualFileUrl(workspaceModelEntityUpdaterConfig.virtualFileUrlManager),
externalSource = null,
moduleFileName = entityToAdd.name + ModuleManagerEx.IML_EXTENSION,
)
}
private fun toModuleDependencyItemModuleDependency(
intermediateModuleDependency: IntermediateModuleDependency,
project: Project = workspaceModelEntityUpdaterConfig.project,
): ModuleDependency =
BspWorkspace.getInstance(project).interner.getOrPut(
ModuleDependency(
module = BspWorkspace.getInstance(project).interner.getOrPut(ModuleId(intermediateModuleDependency.moduleName)),
exported = true,
scope = DependencyScope.COMPILE,
productionOnTest = true,
),
)
}
internal fun toLibraryDependency(intermediateLibraryDependency: IntermediateLibraryDependency, project: Project): LibraryDependency =
BspWorkspace.getInstance(project).interner.getOrPut(
LibraryDependency(
library =
BspWorkspace.getInstance(project).interner.getOrPut(
LibraryId(
name = intermediateLibraryDependency.libraryName,
tableId = LibraryTableId.ProjectLibraryTableId, // treat all libraries as project-level libraries
),
),
exported = true, // TODO https://youtrack.jetbrains.com/issue/BAZEL-632
scope = DependencyScope.COMPILE,
),
)
| 8
| null |
8
| 45
|
1d79484cfdf8fc31d3a4b214655e857214071723
| 6,182
|
hirschgarten
|
Apache License 2.0
|
basick/src/main/java/com/mozhimen/basick/utilk/android/content/UtilKApplicationInfo.kt
|
mozhimen
| 353,952,154
| false
| null |
package com.mozhimen.basick.utilk.android.content
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import java.lang.IllegalArgumentException
/**
* @ClassName UtilKApplicationInfo
* @Description TODO
* @Author Mozhimen & Kolin
* @Date 2023/4/18 11:24
* @Version 1.0
*/
object UtilKApplicationInfo {
@JvmStatic
fun get(context: Context): ApplicationInfo? =
UtilKPackageInfo.getApplicationInfo(context)
@JvmStatic
fun get(packageInfo: PackageInfo): ApplicationInfo =
packageInfo.applicationInfo
////////////////////////////////////////////////////////////////////
@JvmStatic
fun getFlags(context: Context): Int? =
get(context)?.flags
/**
* 和这个方法一样[UtilKPackageManager.getApplicationIcon]
*/
@JvmStatic
fun loadIcon(context: Context, packageManager: PackageManager): Drawable? =
get(context)?.loadIcon(packageManager)
@JvmStatic
fun loadIcon(applicationInfo: ApplicationInfo, packageManager: PackageManager): Drawable =
applicationInfo.loadIcon(packageManager)
/**
* 得到包名
*/
@JvmStatic
fun getPackageName(context: Context): String? =
get(context)?.packageName
@JvmStatic
fun getPackageName(applicationInfo: ApplicationInfo): String =
applicationInfo.packageName
/**
* app的目标版本
* @param context Context
* @return Int
*/
@JvmStatic
fun getTargetSdkVersion(context: Context): Int? =
get(context)?.targetSdkVersion
////////////////////////////////////////////////////////////////////
@JvmStatic
@Throws(IllegalArgumentException::class)
fun isSystemApp(context: Context): Boolean {
val flags = getFlags(context)
requireNotNull(flags)
return (flags and ApplicationInfo.FLAG_SYSTEM) != 0
}
@JvmStatic
@Throws(IllegalArgumentException::class)
fun isSystemUpdateApp(context: Context): Boolean {
val flags = getFlags(context)
requireNotNull(flags)
return (flags and ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0
}
@JvmStatic
@Throws(IllegalArgumentException::class)
fun isUserApp(context: Context): Boolean =
!isSystemApp(context) && !isSystemUpdateApp(context)
}
| 0
| null |
6
| 112
|
efbc55d940b169511106a9b813513fc3f86df1fb
| 2,403
|
SwiftKit
|
Apache License 2.0
|
aws-storage-s3/src/main/java/com/amplifyframework/storage/s3/transfer/UploadOptions.kt
|
aws-amplify
| 177,009,933
| false
| null |
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amplifyframework.storage.s3.transfer
import aws.sdk.kotlin.services.s3.model.ObjectCannedAcl
import com.amplifyframework.storage.ObjectMetadata
/**
* Options used to configure the upload of an object using {@link TransferManager}.
*/
internal data class UploadOptions @JvmOverloads constructor(
val bucket: String,
val objectMetadata: ObjectMetadata = ObjectMetadata(),
val cannedAcl: ObjectCannedAcl? = null,
val transferListener: TransferListener? = null
)
| 103
| null |
115
| 245
|
c1030d45909bb6e2ace4dc195047f9c2a8630fe2
| 1,073
|
amplify-android
|
Apache License 2.0
|
app/src/main/java/org/queiroz/themoviedb/movies/repository/MoviesRepositoryImpl.kt
|
queiroz
| 237,280,338
| false
|
{"Kotlin": 67194}
|
package org.queiroz.themoviedb.movies.repository
import org.queiroz.themoviedb.api.ApiService
import org.queiroz.themoviedb.api.networkRequest
import org.queiroz.themoviedb.model.TmdbMovies
import org.queiroz.themoviedb.util.Resource
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MoviesRepositoryImpl @Inject constructor(
private val service: ApiService
): MoviesRepository {
override suspend fun getPopularMovies(page: Int): Resource<TmdbMovies> =
networkRequest { service.getPopularMovies(page) }
}
| 0
|
Kotlin
|
0
| 0
|
9e00020ee260523afe52f5721655caead2ec5b66
| 547
|
themoviedb
|
Apache License 2.0
|
app/src/main/java/com/alirezaafkar/phuzei/presentation/muzei/PhotosArtSource.kt
|
QuinnDamerell
| 264,998,941
| true
|
{"Kotlin": 54912, "IDL": 1746, "Prolog": 988}
|
package com.alirezaafkar.phuzei.presentation.muzei
import android.annotation.SuppressLint
import android.content.Intent
import androidx.core.net.toUri
import com.alirezaafkar.phuzei.App
import com.alirezaafkar.phuzei.data.model.Media
import com.alirezaafkar.phuzei.data.model.isImage
import com.alirezaafkar.phuzei.data.model.largeUrl
import com.alirezaafkar.phuzei.data.pref.AppPreferences
import com.alirezaafkar.phuzei.data.repository.PhotosRepository
import com.google.android.apps.muzei.api.Artwork
import com.google.android.apps.muzei.api.RemoteMuzeiArtSource
import timber.log.Timber
import java.util.*
import javax.inject.Inject
/**
* Created by <NAME> on 16/9/2018AD.
*/
class PhotosArtSource : RemoteMuzeiArtSource(SOURCE_NAME) {
@Inject lateinit var repository: PhotosRepository
@Inject lateinit var prefs: AppPreferences
override fun onCreate() {
super.onCreate()
App.get(this).component?.inject(this)
}
@SuppressLint("CheckResult")
override fun onTryUpdate(reason: Int) {
repository.getAlbumPhotos(prefs.album ?: return)
.subscribe(
{
prefs.pageToken = it.nextPageToken
onPhotosResult(it.mediaItems.filter(Media::isImage))
},
{
prefs.pageToken = null
Timber.e(it)
}
)
}
private fun onPhotosResult(medias: List<Media>) {
if (medias.isEmpty()) {
Timber.w("No photos returned from API")
scheduleUpdate()
return
}
val currentToken = currentArtwork?.token
val random = Random()
var token: String
var media: Media
while (true) {
media = medias[random.nextInt(medias.size)]
token = media.id
if (medias.size <= 1 || token != currentToken) {
break
}
}
publish(media)
scheduleUpdate()
}
private fun publish(photo: Media) {
publishArtwork(
Artwork.Builder()
.token(photo.id)
.title(photo.filename)
.byline(photo.description)
.viewIntent(Intent(Intent.ACTION_VIEW, photo.productUrl.toUri()))
.imageUri(photo.largeUrl().toUri())
.build()
)
}
private fun scheduleUpdate() {
scheduleUpdate(System.currentTimeMillis() + ROTATE_TIME_MILLIS)
}
companion object {
private const val SOURCE_NAME = "PhotosArtSource"
private const val ROTATE_TIME_MILLIS = 3 * 60 * 60 * 1000 // rotate every 3 hours
}
}
| 0
| null |
0
| 0
|
f85236c2e7f2a94f27bdd7a0dd7e03dc28b5ce84
| 2,688
|
phuzei
|
Apache License 2.0
|
app/src/main/java/h/lillie/reborntube/settings/SponsorBlockSettings.kt
|
LillieH1000
| 517,439,028
| false
|
{"Kotlin": 174939}
|
package h.lillie.reborntube.settings
import android.app.AlertDialog
import android.os.Bundle
import android.content.res.ColorStateList
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.button.MaterialButton
import h.lillie.reborntube.R
class SponsorBlockSettings : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.sponsorblocksettings)
val settingsPreferences = getSharedPreferences("RTSettings", 0)
// Source
val sourceMainButton: MaterialButton = findViewById(R.id.sourceMainButton)
val sourceMirrorButton: MaterialButton = findViewById(R.id.sourceMirrorButton)
val sponsorBlockSource: Int = settingsPreferences.getInt("RTSponsorBlockSource", 0)
if (sponsorBlockSource == 0) {
sourceMainButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
sourceMirrorButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (sponsorBlockSource == 1) {
sourceMainButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
sourceMirrorButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
}
sourceMainButton.setOnClickListener {
sourceMainButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
sourceMirrorButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockSource", 0).apply()
}
sourceMirrorButton.setOnClickListener {
sourceMainButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
sourceMirrorButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
settingsPreferences.edit().putInt("RTSponsorBlockSource", 1).apply()
}
// Sponsor
val sponsorDisableButton: MaterialButton = findViewById(R.id.sponsorDisableButton)
val sponsorAutoSkipButton: MaterialButton = findViewById(R.id.sponsorAutoSkipButton)
val sponsorManualSkipButton: MaterialButton = findViewById(R.id.sponsorManualSkipButton)
val sponsorBlockSponsor: Int = settingsPreferences.getInt("RTSponsorBlockSponsor", 0)
if (sponsorBlockSponsor == 0) {
sponsorDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
sponsorAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
sponsorManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (sponsorBlockSponsor == 1) {
sponsorDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
sponsorAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
sponsorManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (sponsorBlockSponsor == 2) {
sponsorDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
sponsorAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
sponsorManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
}
sponsorDisableButton.setOnClickListener {
sponsorDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
sponsorAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
sponsorManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockSponsor", 0).apply()
}
sponsorAutoSkipButton.setOnClickListener {
sponsorDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
sponsorAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
sponsorManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockSponsor", 1).apply()
}
sponsorManualSkipButton.setOnClickListener {
sponsorDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
sponsorAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
sponsorManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
settingsPreferences.edit().putInt("RTSponsorBlockSponsor", 2).apply()
}
// Selfpromo
val selfpromoDisableButton: MaterialButton = findViewById(R.id.selfpromoDisableButton)
val selfpromoAutoSkipButton: MaterialButton = findViewById(R.id.selfpromoAutoSkipButton)
val selfpromoManualSkipButton: MaterialButton = findViewById(R.id.selfpromoManualSkipButton)
val selfpromoBlockSelfpromo: Int = settingsPreferences.getInt("RTSponsorBlockSelfpromo", 0)
if (selfpromoBlockSelfpromo == 0) {
selfpromoDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
selfpromoAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
selfpromoManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (selfpromoBlockSelfpromo == 1) {
selfpromoDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
selfpromoAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
selfpromoManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (selfpromoBlockSelfpromo == 2) {
selfpromoDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
selfpromoAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
selfpromoManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
}
selfpromoDisableButton.setOnClickListener {
selfpromoDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
selfpromoAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
selfpromoManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockSelfpromo", 0).apply()
}
selfpromoAutoSkipButton.setOnClickListener {
selfpromoDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
selfpromoAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
selfpromoManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockSelfpromo", 1).apply()
}
selfpromoManualSkipButton.setOnClickListener {
selfpromoDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
selfpromoAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
selfpromoManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
settingsPreferences.edit().putInt("RTSponsorBlockSelfpromo", 2).apply()
}
// Interaction
val interactionDisableButton: MaterialButton = findViewById(R.id.interactionDisableButton)
val interactionAutoSkipButton: MaterialButton = findViewById(R.id.interactionAutoSkipButton)
val interactionManualSkipButton: MaterialButton = findViewById(R.id.interactionManualSkipButton)
val interactionBlockInteraction: Int = settingsPreferences.getInt("RTSponsorBlockInteraction", 0)
if (interactionBlockInteraction == 0) {
interactionDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
interactionAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
interactionManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (interactionBlockInteraction == 1) {
interactionDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
interactionAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
interactionManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (interactionBlockInteraction == 2) {
interactionDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
interactionAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
interactionManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
}
interactionDisableButton.setOnClickListener {
interactionDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
interactionAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
interactionManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockInteraction", 0).apply()
}
interactionAutoSkipButton.setOnClickListener {
interactionDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
interactionAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
interactionManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockInteraction", 1).apply()
}
interactionManualSkipButton.setOnClickListener {
interactionDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
interactionAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
interactionManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
settingsPreferences.edit().putInt("RTSponsorBlockInteraction", 2).apply()
}
// Intro
val introDisableButton: MaterialButton = findViewById(R.id.introDisableButton)
val introAutoSkipButton: MaterialButton = findViewById(R.id.introAutoSkipButton)
val introManualSkipButton: MaterialButton = findViewById(R.id.introManualSkipButton)
val introBlockIntro: Int = settingsPreferences.getInt("RTSponsorBlockIntro", 0)
if (introBlockIntro == 0) {
introDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
introAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
introManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (introBlockIntro == 1) {
introDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
introAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
introManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (introBlockIntro == 2) {
introDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
introAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
introManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
}
introDisableButton.setOnClickListener {
introDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
introAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
introManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockIntro", 0).apply()
}
introAutoSkipButton.setOnClickListener {
introDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
introAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
introManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockIntro", 1).apply()
}
introManualSkipButton.setOnClickListener {
introDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
introAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
introManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
settingsPreferences.edit().putInt("RTSponsorBlockIntro", 2).apply()
}
// Outro
val outroDisableButton: MaterialButton = findViewById(R.id.outroDisableButton)
val outroAutoSkipButton: MaterialButton = findViewById(R.id.outroAutoSkipButton)
val outroManualSkipButton: MaterialButton = findViewById(R.id.outroManualSkipButton)
val outroBlockOutro: Int = settingsPreferences.getInt("RTSponsorBlockOutro", 0)
if (outroBlockOutro == 0) {
outroDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
outroAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
outroManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (outroBlockOutro == 1) {
outroDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
outroAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
outroManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (outroBlockOutro == 2) {
outroDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
outroAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
outroManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
}
outroDisableButton.setOnClickListener {
outroDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
outroAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
outroManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockOutro", 0).apply()
}
outroAutoSkipButton.setOnClickListener {
outroDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
outroAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
outroManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockOutro", 1).apply()
}
outroManualSkipButton.setOnClickListener {
outroDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
outroAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
outroManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
settingsPreferences.edit().putInt("RTSponsorBlockOutro", 2).apply()
}
// Preview
val previewDisableButton: MaterialButton = findViewById(R.id.previewDisableButton)
val previewAutoSkipButton: MaterialButton = findViewById(R.id.previewAutoSkipButton)
val previewManualSkipButton: MaterialButton = findViewById(R.id.previewManualSkipButton)
val previewBlockPreview: Int = settingsPreferences.getInt("RTSponsorBlockPreview", 0)
if (previewBlockPreview == 0) {
previewDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
previewAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
previewManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (previewBlockPreview == 1) {
previewDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
previewAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
previewManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (previewBlockPreview == 2) {
previewDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
previewAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
previewManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
}
previewDisableButton.setOnClickListener {
previewDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
previewAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
previewManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockPreview", 0).apply()
}
previewAutoSkipButton.setOnClickListener {
previewDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
previewAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
previewManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockPreview", 1).apply()
}
previewManualSkipButton.setOnClickListener {
previewDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
previewAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
previewManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
settingsPreferences.edit().putInt("RTSponsorBlockPreview", 2).apply()
}
// Filler
val fillerDisableButton: MaterialButton = findViewById(R.id.fillerDisableButton)
val fillerAutoSkipButton: MaterialButton = findViewById(R.id.fillerAutoSkipButton)
val fillerManualSkipButton: MaterialButton = findViewById(R.id.fillerManualSkipButton)
val fillerBlockFiller: Int = settingsPreferences.getInt("RTSponsorBlockFiller", 0)
if (fillerBlockFiller == 0) {
fillerDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
fillerAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
fillerManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (fillerBlockFiller == 1) {
fillerDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
fillerAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
fillerManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (fillerBlockFiller == 2) {
fillerDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
fillerAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
fillerManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
}
fillerDisableButton.setOnClickListener {
fillerDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
fillerAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
fillerManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockFiller", 0).apply()
}
fillerAutoSkipButton.setOnClickListener {
fillerDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
fillerAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
fillerManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockFiller", 1).apply()
}
fillerManualSkipButton.setOnClickListener {
fillerDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
fillerAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
fillerManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
settingsPreferences.edit().putInt("RTSponsorBlockFiller", 2).apply()
}
// Music_offtopic
val musicofftopicDisableButton: MaterialButton = findViewById(R.id.musicofftopicDisableButton)
val musicofftopicAutoSkipButton: MaterialButton = findViewById(R.id.musicofftopicAutoSkipButton)
val musicofftopicManualSkipButton: MaterialButton = findViewById(R.id.musicofftopicManualSkipButton)
val musicofftopicBlockMusicofftopic: Int = settingsPreferences.getInt("RTSponsorBlockMusicofftopic", 0)
if (musicofftopicBlockMusicofftopic == 0) {
musicofftopicDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
musicofftopicAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
musicofftopicManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (musicofftopicBlockMusicofftopic == 1) {
musicofftopicDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
musicofftopicAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
musicofftopicManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
} else if (musicofftopicBlockMusicofftopic == 2) {
musicofftopicDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
musicofftopicAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
musicofftopicManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
}
musicofftopicDisableButton.setOnClickListener {
musicofftopicDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
musicofftopicAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
musicofftopicManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockMusicofftopic", 0).apply()
}
musicofftopicAutoSkipButton.setOnClickListener {
musicofftopicDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
musicofftopicAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
musicofftopicManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
settingsPreferences.edit().putInt("RTSponsorBlockMusicofftopic", 1).apply()
}
musicofftopicManualSkipButton.setOnClickListener {
musicofftopicDisableButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
musicofftopicAutoSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.transparent))
)
musicofftopicManualSkipButton.backgroundTintList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_enabled)),
intArrayOf(applicationContext.getColor(R.color.lightgrey))
)
settingsPreferences.edit().putInt("RTSponsorBlockMusicofftopic", 2).apply()
}
val manualSkipPopup = AlertDialog.Builder(this@SponsorBlockSettings).create()
manualSkipPopup.setTitle("Notice")
manualSkipPopup.setMessage("Manual Skip is in beta and may not work correctly")
manualSkipPopup.setButton(AlertDialog.BUTTON_POSITIVE, "Okay") { _, _ -> }
manualSkipPopup.setCancelable(false)
manualSkipPopup.show()
}
}
| 1
|
Kotlin
|
1
| 9
|
57412084391c244657d51df0010ea41323103900
| 44,339
|
RebornTube
|
MIT License
|
subprojects/xcfa/xcfa-analysis/src/main/java/hu/bme/mit/theta/xcfa/analysis/XcfaSingeExprTraceRefiner.kt
|
ftsrg
| 39,392,321
| false
|
{"Java": 5132879, "Kotlin": 1301970, "C": 278090, "ANTLR": 121913, "C++": 110696, "SWIG": 65732, "SMT": 24985, "Shell": 5456, "Dockerfile": 2404, "PowerShell": 865}
|
/*
* Copyright 2024 Budapest University of Technology and Economics
*
* 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 hu.bme.mit.theta.xcfa.analysis
import com.google.common.base.Preconditions
import hu.bme.mit.theta.analysis.Prec
import hu.bme.mit.theta.analysis.Trace
import hu.bme.mit.theta.analysis.algorithm.arg.ARG
import hu.bme.mit.theta.analysis.algorithm.cegar.RefinerResult
import hu.bme.mit.theta.analysis.expr.ExprAction
import hu.bme.mit.theta.analysis.expr.ExprState
import hu.bme.mit.theta.analysis.expr.refinement.*
import hu.bme.mit.theta.analysis.ptr.PtrState
import hu.bme.mit.theta.analysis.ptr.WriteTriples
import hu.bme.mit.theta.analysis.ptr.patch
import hu.bme.mit.theta.common.logging.Logger
import java.util.*
class XcfaSingleExprTraceRefiner<S : ExprState, A : ExprAction, P : Prec, R : Refutation> :
SingleExprTraceRefiner<S, A, P, R> {
private constructor(
exprTraceChecker: ExprTraceChecker<R>,
precRefiner: PrecRefiner<S, A, P, R>,
pruneStrategy: PruneStrategy,
logger: Logger,
) : super(exprTraceChecker, precRefiner, pruneStrategy, logger)
private constructor(
exprTraceChecker: ExprTraceChecker<R>,
precRefiner: PrecRefiner<S, A, P, R>,
pruneStrategy: PruneStrategy,
logger: Logger,
nodePruner: NodePruner<S, A>,
) : super(exprTraceChecker, precRefiner, pruneStrategy, logger, nodePruner)
private fun findPoppedState(trace: Trace<S, A>): Pair<Int, XcfaState<S>>? {
trace.states.forEachIndexed { i, s ->
val state = s as XcfaState<S>
state.processes.entries
.find { (_, processState) -> processState.popped != null }
?.let { (pid, processState) ->
val stackBeforePop = LinkedList(processState.locs)
stackBeforePop.push(processState.popped)
val processesBeforePop = state.processes.toMutableMap()
processesBeforePop[pid] = processState.copy(locs = stackBeforePop)
val stateBeforePop = state.copy(processes = processesBeforePop)
return Pair(i, stateBeforePop)
}
}
return null
}
fun refineTemp(arg: ARG<S, A>, prec: P?): RefinerResult<P?, Trace<S, A>> {
Preconditions.checkNotNull(arg)
Preconditions.checkNotNull(prec)
assert(!arg.isSafe) { "ARG must be unsafe" }
val optionalNewCex = arg.cexs.findFirst()
val cexToConcretize = optionalNewCex.get()
val rawTrace = cexToConcretize.toTrace()
val (_, states, actions) =
rawTrace.actions.foldIndexed(
Triple(Pair(emptyMap(), 0), listOf(rawTrace.getState(0)), listOf())
) {
i: Int,
(wTripleCnt: Pair<WriteTriples, Int>, states: List<S>, actions: List<A>): Triple<
Pair<WriteTriples, Int>,
List<S>,
List<A>,
>,
a: A ->
val (wTriple, cnt) = wTripleCnt
val newA = (a as XcfaAction).withLastWrites(wTriple, cnt)
val newState =
(rawTrace.getState(i + 1) as XcfaState<PtrState<*>>).let {
it.withState(PtrState(it.sGlobal.innerState.patch(newA.nextWriteTriples())))
}
Triple(
Pair(newA.nextWriteTriples(), newA.cnts.values.maxOrNull() ?: newA.inCnt),
states + (newState as S),
actions + (newA as A),
)
}
val traceToConcretize = Trace.of(states, actions)
logger.write(Logger.Level.INFO, "| | Trace length: %d%n", traceToConcretize.length())
logger.write(Logger.Level.DETAIL, "| | Trace: %s%n", traceToConcretize)
logger.write(Logger.Level.SUBSTEP, "| | Checking trace...")
val cexStatus = exprTraceChecker.check(traceToConcretize)
logger.write(Logger.Level.SUBSTEP, "done, result: %s%n", cexStatus)
assert(cexStatus.isFeasible() || cexStatus.isInfeasible()) { "Unknown CEX status" }
return if (cexStatus.isFeasible()) {
RefinerResult.unsafe(traceToConcretize)
} else {
val refutation = cexStatus.asInfeasible().refutation
logger.write(Logger.Level.DETAIL, "| | | Refutation: %s%n", refutation)
val refinedPrec = precRefiner.refine(prec, traceToConcretize, refutation)
val pruneIndex = refutation.getPruneIndex()
assert(0 <= pruneIndex) { "Pruning index must be non-negative" }
assert(pruneIndex <= cexToConcretize.length()) { "Pruning index larger than cex length" }
when (pruneStrategy) {
PruneStrategy.LAZY -> {
logger.write(Logger.Level.SUBSTEP, "| | Pruning from index %d...", pruneIndex)
val nodeToPrune = cexToConcretize.node(pruneIndex)
nodePruner.prune(arg, nodeToPrune)
}
PruneStrategy.FULL -> {
logger.write(Logger.Level.SUBSTEP, "| | Pruning whole ARG", pruneIndex)
arg.pruneAll()
}
else -> throw java.lang.UnsupportedOperationException("Unsupported pruning strategy")
}
logger.write(Logger.Level.SUBSTEP, "done%n")
RefinerResult.spurious(refinedPrec)
}
}
override fun refine(arg: ARG<S, A>, prec: P?): RefinerResult<P?, Trace<S, A>> {
Preconditions.checkNotNull(arg)
Preconditions.checkNotNull<P>(prec)
assert(!arg.isSafe) { "ARG must be unsafe" }
val optionalNewCex = arg.cexs.findFirst()
val cexToConcretize = optionalNewCex.get()
val traceToConcretize = cexToConcretize.toTrace()
val refinerResult = refineTemp(arg, prec) // super.refine(arg, prec)
val checkForPop = !(traceToConcretize.states.first() as XcfaState<*>).xcfa!!.isInlined
return if (checkForPop && refinerResult.isUnsafe)
findPoppedState(traceToConcretize)?.let { (i, state) ->
when (pruneStrategy) {
PruneStrategy.LAZY -> {
logger.write(Logger.Level.SUBSTEP, "| | Pruning from index %d...", i)
val nodeToPrune = cexToConcretize.node(i)
nodePruner.prune(arg, nodeToPrune)
}
PruneStrategy.FULL -> {
logger.write(Logger.Level.SUBSTEP, "| | Pruning whole ARG", i)
arg.pruneAll()
}
else -> throw UnsupportedOperationException("Unsupported pruning strategy")
}
val refinedPrec = (prec as XcfaPrec<P>).copy()
refinedPrec.noPop.add(state)
RefinerResult.spurious(refinedPrec as P?)
} ?: refinerResult
else refinerResult
}
companion object {
fun <S : ExprState, A : ExprAction, P : Prec, R : Refutation> create(
exprTraceChecker: ExprTraceChecker<R>,
precRefiner: PrecRefiner<S, A, P, R>,
pruneStrategy: PruneStrategy,
logger: Logger,
): XcfaSingleExprTraceRefiner<S, A, P, R> {
return XcfaSingleExprTraceRefiner(exprTraceChecker, precRefiner, pruneStrategy, logger)
}
fun <S : ExprState, A : ExprAction, P : Prec, R : Refutation> create(
exprTraceChecker: ExprTraceChecker<R>,
precRefiner: PrecRefiner<S, A, P, R>,
pruneStrategy: PruneStrategy,
logger: Logger,
nodePruner: NodePruner<S, A>,
): XcfaSingleExprTraceRefiner<S, A, P, R> {
return XcfaSingleExprTraceRefiner(
exprTraceChecker,
precRefiner,
pruneStrategy,
logger,
nodePruner,
)
}
}
}
| 53
|
Java
|
43
| 49
|
cb77d7e6bb0e51ea00d2a1dc483fdf510dd8e8b4
| 7,671
|
theta
|
Apache License 2.0
|
data/paging/src/main/java/be/appwise/paging/base/pager/BaseRemotePager.kt
|
wisemen-digital
| 349,150,482
| false
|
{"Kotlin": 255860}
|
package be.appwise.paging.base.pager
import androidx.paging.ExperimentalPagingApi
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import kotlinx.coroutines.flow.Flow
interface BaseRemotePager<T : Any> : CoreRemotePager {
/**
* This functions expects to returns an [androidx.paging.Pager] object.
*
* From the [androidx.paging.Pager] you can get a LiveData or Flow object.
* Because the LiveData is extracted from the Flow, we will expect a Flow
*/
@ExperimentalPagingApi
fun pagingDataAsFlow(pagingConfig: PagingConfig = getDefaultPageConfig()): Flow<PagingData<T>>
}
| 7
|
Kotlin
|
5
| 5
|
a6998e4298e44c1a5a8d01b47e7bca9cf69e8f8f
| 630
|
AndroidCore
|
MIT License
|
di/di/src/main/java/vn/tiki/android/di/internal/Linker.kt
|
talenguyen
| 140,232,102
| false
|
{"Gradle": 41, "Text": 1, "Ignore List": 27, "EditorConfig": 7, "Markdown": 17, "Java Properties": 11, "Shell": 7, "Batchfile": 6, "XML": 92, "Kotlin": 92, "INI": 9, "Proguard": 6, "Java": 1, "Python": 1}
|
package vn.tiki.android.di.internal
class Linker internal constructor(internal val factories: MutableMap<Class<*>, Factory<*>> = mutableMapOf()) {
fun <T> install(key: Class<T>, factory: Factory<T>) {
factories[key] = factory
}
@Suppress("UNCHECKED_CAST")
fun <T> factoryFor(key: Class<T>): Factory<T> {
return if (factories.containsKey(key)) {
factories[key] as Factory<T>
} else {
throw IllegalArgumentException("no factory for ${key.name}")
}
}
operator fun plus(other: Linker): Linker {
val mergedFactories = this.factories + other.factories
return when (mergedFactories) {
is MutableMap -> Linker(mergedFactories)
else -> Linker(mergedFactories.toMutableMap())
}
}
internal fun dump() {
for (key in factories.keys) {
println("Found: factory for $key")
}
}
}
| 1
| null |
1
| 1
|
0c95b618da5c00fc9428eba166527f0767e4fd4b
| 853
|
AndroidDevelopment
|
Apache License 2.0
|
src/jvmMain/kotlin/software/momento/kotlin/sdk/internal/InternalControlClient.jvm.kt
|
momentohq
| 724,323,089
| false
|
{"Kotlin": 265819}
|
package software.momento.kotlin.sdk.internal
import grpc.control_client._CreateCacheRequest
import grpc.control_client._DeleteCacheRequest
import grpc.control_client._ListCachesRequest
import io.grpc.Metadata
import software.momento.kotlin.sdk.auth.CredentialProvider
import software.momento.kotlin.sdk.config.Configuration
import software.momento.kotlin.sdk.exceptions.CacheServiceExceptionMapper
import software.momento.kotlin.sdk.exceptions.MomentoErrorCode
import software.momento.kotlin.sdk.responses.cache.control.CacheCreateResponse
import software.momento.kotlin.sdk.responses.cache.control.CacheDeleteResponse
import software.momento.kotlin.sdk.internal.utils.ValidationUtils
import software.momento.kotlin.sdk.responses.cache.control.CacheInfo
import software.momento.kotlin.sdk.responses.cache.control.CacheListResponse
internal actual class InternalControlClient actual constructor(
credentialProvider: CredentialProvider,
configuration: Configuration
): InternalClient() {
private val stubsManager: ControlGrpcStubsManager
init {
stubsManager = ControlGrpcStubsManager(credentialProvider)
}
internal actual suspend fun createCache(cacheName: String): CacheCreateResponse {
return runCatching {
ValidationUtils.requireValidCacheName(cacheName)
}.fold(onSuccess = {
sendCreateCache(cacheName)
}, onFailure = { e ->
CacheCreateResponse.Error(CacheServiceExceptionMapper.convert(e))
})
}
private suspend fun sendCreateCache(cacheName: String): CacheCreateResponse {
val metadata = metadataWithCache(cacheName)
val request = _CreateCacheRequest.newBuilder().setCacheName(cacheName).build()
return runCatching {
this.stubsManager.stub.createCache(request, metadata)
}.fold(onSuccess = {
CacheCreateResponse.Success
}, onFailure = { e ->
val sdkException = CacheServiceExceptionMapper.convert(e, metadata)
when (sdkException.errorCode) {
MomentoErrorCode.ALREADY_EXISTS_ERROR -> CacheCreateResponse.AlreadyExists
else -> CacheCreateResponse.Error(sdkException)
}
})
}
internal actual suspend fun deleteCache(cacheName: String): CacheDeleteResponse {
return runCatching {
ValidationUtils.requireValidCacheName(cacheName)
}.fold(onSuccess = {
sendDeleteCache(cacheName)
}, onFailure = { e ->
CacheDeleteResponse.Error(CacheServiceExceptionMapper.convert(e))
})
}
private suspend fun sendDeleteCache(
cacheName: String
): CacheDeleteResponse {
val metadata = metadataWithCache(cacheName)
val request = _DeleteCacheRequest.newBuilder().setCacheName(cacheName).build()
return runCatching {
this.stubsManager.stub.deleteCache(request, metadata)
}.fold(onSuccess = {
CacheDeleteResponse.Success
}, onFailure = { e ->
CacheDeleteResponse.Error(CacheServiceExceptionMapper.convert(e, metadata))
})
}
internal actual suspend fun listCaches(): CacheListResponse {
return runCatching {}.fold(onSuccess = {
sendListCaches()
}, onFailure = { e ->
CacheListResponse.Error(CacheServiceExceptionMapper.convert(e))
})
}
private suspend fun sendListCaches(): CacheListResponse {
val request = _ListCachesRequest.newBuilder().setNextToken("").build()
val metadata = Metadata()
return runCatching {
this.stubsManager.stub.listCaches(request, metadata)
}.fold(onSuccess = { listCacheResponse ->
CacheListResponse.Success(
listCacheResponse.cacheList.map { CacheInfo(it.cacheName) }
)
}, onFailure = { e ->
CacheListResponse.Error(CacheServiceExceptionMapper.convert(e, metadata))
})
}
override fun close() {
stubsManager.close()
}
}
| 8
|
Kotlin
|
1
| 0
|
8dcf38374acd0e1b34c10a3af62dcbe3332d0885
| 4,054
|
client-sdk-kotlin
|
Apache License 2.0
|
.teamcity/patches/templates/EnforcedTemplate.kts
|
nuke-build
| 93,804,681
| false
|
{"C#": 17217584, "HTML": 1116292, "PowerShell": 6610, "Shell": 5202, "Kotlin": 822, "Batchfile": 414, "Dockerfile": 184}
|
package patches.templates
import jetbrains.buildServer.configs.kotlin.v2018_1.*
import jetbrains.buildServer.configs.kotlin.v2018_1.Template
import jetbrains.buildServer.configs.kotlin.v2018_1.buildFeatures.PullRequests
import jetbrains.buildServer.configs.kotlin.v2018_1.buildFeatures.commitStatusPublisher
import jetbrains.buildServer.configs.kotlin.v2018_1.buildFeatures.pullRequests
import jetbrains.buildServer.configs.kotlin.v2018_1.ui.*
/*
This patch script was generated by TeamCity on settings change in UI.
To apply the patch, create a template with id = 'EnforcedTemplate'
in the root project, and delete the patch script.
*/
create(DslContext.projectId, Template({
id("EnforcedTemplate")
name = "Enforced Template"
features {
pullRequests {
id = "BUILD_EXT_3"
provider = github {
authType = token {
token = "credentialsJSON:af125343-b8b3-47e9-8cc4-a978d3f1c953"
}
filterAuthorRole = PullRequests.GitHubRoleFilter.MEMBER
}
}
commitStatusPublisher {
id = "BUILD_EXT_4"
publisher = github {
githubUrl = "https://api.github.com"
authType = personalToken {
token = "credentialsJSON:30bca7f7-b76a-4431-9f84-b4bc1459b918"
}
}
}
}
}))
| 76
|
C#
|
359
| 2,980
|
c8d9236a19446f15c1b6b2e22a6f4b4f474d20ca
| 1,399
|
nuke
|
MIT License
|
core/src/main/java/de/schwerin/stoppCoronaDE/skeleton/core/model/helpers/AppDispatchers.kt
|
Mandarin-Medien
| 269,321,452
| false
| null |
package de.schwerin.stoppCoronaDE.skeleton.core.model.helpers
import kotlinx.coroutines.Dispatchers
import kotlin.coroutines.CoroutineContext
/**
* Collection of coroutine dispatchers that can be overridden in Unit tests.
*/
interface AppDispatchers {
@Suppress("PropertyName")
val Default: CoroutineContext
@Suppress("PropertyName")
val Main: CoroutineContext
@Suppress("PropertyName")
val IO: CoroutineContext
}
class AppDispatchersImpl : AppDispatchers {
override val Default: CoroutineContext
get() = Dispatchers.Default
override val Main: CoroutineContext
get() = Dispatchers.Main
override val IO: CoroutineContext
get() = Dispatchers.IO
}
| 0
|
Kotlin
|
0
| 1
|
a8a489c25b55cce8b14d60b9afa3fb44cfecab43
| 710
|
stopp-corona-de-android
|
Apache License 2.0
|
app/src/main/java/com/ps/movie/util/DispatchersProvider.kt
|
satyamgarg
| 709,651,406
| false
|
{"Kotlin": 79571, "Java": 47915}
|
package com.ps.movie.util
import kotlinx.coroutines.CoroutineDispatcher
interface DispatchersProvider {
val main: CoroutineDispatcher
val io: CoroutineDispatcher
val default: CoroutineDispatcher
}
| 0
|
Kotlin
|
0
| 0
|
a1277958a4c554ed5902f34f0d1b5f449579b437
| 211
|
ps-movie-app
|
MIT License
|
server/src/main/kotlin/cn/yjl/resp/RespCode.kt
|
Yin-Jinlong
| 689,947,942
| false
|
{"Kotlin": 85775, "Vue": 45426, "TypeScript": 10700, "SCSS": 7673, "HTML": 271}
|
package cn.yjl.resp
/**
* 预定义的返回代码和消息
*
* @author YJL
*/
enum class RespCode(val code: Int, val msg: String) {
/**
* OK
*/
OK(0, "OK"),
/**
* 没有附加消息
*/
NOTHING(0, "Nothing"),
/**
* 参数校验失败,格式等不正确
*/
VALIDATE_FAILED(10, "参数校验失败"),
/**
* 用户登录成功
*/
USER_LOGIN_SUCCESS(0, "用户登录成功"),
/**
* 用户登录失败(一般原因)
*/
USER_FAILED_LOGIN(100, "用户名或密码错误"),
/**
* 用户不存在
*/
USER_NOT_FOUND(110, "用户不存在"),
/**
* 用户名格式错误
*/
USER_NAME_ERROR(120, "用户名错误"),
/**
* 密码格式错误
*/
USER_PWD_ERROR(121, "密码格式错误"),
/**
* 提交消息成功
*/
USER_MSG_SEND_OK(0, "提交成功"),
/**
* 用户未登录
*/
USER_NOT_LOGIN(130, "用户未登录"),
/**
* 注册成功
*/
USER_LOGON_OK(0, "注册成功"),
/**
* 用户名已存在
*/
USER_LOGON_UNAME_EXISTS(130, "用户名已存在"),
TOKEN_ERROR(200, "token已过期或无效"),
/**
* 服务器错误
*/
SERVER_ERROR(1000, "服务器错误"),
}
| 0
|
Kotlin
|
0
| 0
|
af45158e38c60e4bb0c555c09750d62d8f5807ef
| 996
|
ssm-web
|
Apache License 2.0
|
exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/NestedTransactionsTest.kt
|
JetBrains
| 11,765,017
| false
| null |
package org.jetbrains.exposed.sql.tests.shared
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.tests.DatabaseTestsBase
import org.jetbrains.exposed.sql.tests.shared.dml.DMLTestsData
import org.jetbrains.exposed.sql.transactions.TransactionManager
import org.jetbrains.exposed.sql.transactions.inTopLevelTransaction
import org.jetbrains.exposed.sql.transactions.transaction
import org.junit.Test
import kotlin.test.assertNotNull
class NestedTransactionsTest : DatabaseTestsBase() {
@Test
fun testNestedTransactions() {
withTables(DMLTestsData.Cities) {
try {
db.useNestedTransactions = true
assertTrue(DMLTestsData.Cities.selectAll().empty())
DMLTestsData.Cities.insert {
it[DMLTestsData.Cities.name] = "city1"
}
assertEquals(1L, DMLTestsData.Cities.selectAll().count())
assertEqualLists(listOf("city1"), DMLTestsData.Cities.selectAll().map { it[DMLTestsData.Cities.name] })
transaction {
DMLTestsData.Cities.insert {
it[DMLTestsData.Cities.name] = "city2"
}
assertEqualLists(listOf("city1", "city2"), DMLTestsData.Cities.selectAll().map { it[DMLTestsData.Cities.name] })
transaction {
DMLTestsData.Cities.insert {
it[DMLTestsData.Cities.name] = "city3"
}
assertEqualLists(listOf("city1", "city2", "city3"), DMLTestsData.Cities.selectAll().map { it[DMLTestsData.Cities.name] })
}
assertEqualLists(listOf("city1", "city2", "city3"), DMLTestsData.Cities.selectAll().map { it[DMLTestsData.Cities.name] })
rollback()
}
assertEqualLists(listOf("city1"), DMLTestsData.Cities.selectAll().map { it[DMLTestsData.Cities.name] })
} finally {
db.useNestedTransactions = false
}
}
}
@Test
fun `test outer transaction restored after nested transaction failed`() {
withTables(DMLTestsData.Cities) {
assertNotNull(TransactionManager.currentOrNull())
try {
inTopLevelTransaction(this.transactionIsolation) {
repetitionAttempts = 1
throw IllegalStateException("Should be rethrow")
}
} catch (e: Exception) {
assertTrue(e is IllegalStateException)
}
assertNotNull(TransactionManager.currentOrNull())
}
}
}
| 5
| null |
679
| 8,137
|
b766aa7b29dbe82ed37e114a73fa97b1d32d24f5
| 2,752
|
Exposed
|
Apache License 2.0
|
src/commonMain/kotlin/fr/acinq/lightning/channel/WaitForChannelReady.kt
|
ACINQ
| 243,326,972
| false
| null |
package fr.acinq.lightning.channel
import fr.acinq.lightning.ChannelEvents
import fr.acinq.lightning.ShortChannelId
import fr.acinq.lightning.blockchain.BITCOIN_FUNDING_DEEPLYBURIED
import fr.acinq.lightning.blockchain.WatchConfirmed
import fr.acinq.lightning.blockchain.WatchEventConfirmed
import fr.acinq.lightning.blockchain.WatchEventSpent
import fr.acinq.lightning.channel.Channel.ANNOUNCEMENTS_MINCONF
import fr.acinq.lightning.router.Announcements
import fr.acinq.lightning.utils.Either
import fr.acinq.lightning.utils.toMilliSatoshi
import fr.acinq.lightning.wire.*
/** The channel funding transaction was confirmed, we exchange funding_locked messages. */
data class WaitForChannelReady(
override val commitments: Commitments,
val shortChannelId: ShortChannelId,
val lastSent: ChannelReady
) : ChannelStateWithCommitments() {
override fun updateCommitments(input: Commitments): ChannelStateWithCommitments = this.copy(commitments = input)
override fun ChannelContext.processInternal(cmd: ChannelCommand): Pair<ChannelState, List<ChannelAction>> {
return when {
cmd is ChannelCommand.MessageReceived && cmd.message is TxSignatures -> when (commitments.latest.localFundingStatus) {
is LocalFundingStatus.UnconfirmedFundingTx -> when (commitments.latest.localFundingStatus.sharedTx) {
is PartiallySignedSharedTransaction -> when (val fullySignedTx = commitments.latest.localFundingStatus.sharedTx.addRemoteSigs(commitments.latest.localFundingStatus.fundingParams, cmd.message)) {
null -> {
logger.warning { "received invalid remote funding signatures for txId=${cmd.message.txId}" }
// The funding transaction may still confirm (since our peer should be able to generate valid signatures), so we cannot close the channel yet.
Pair(this@WaitForChannelReady, listOf(ChannelAction.Message.Send(Warning(channelId, InvalidFundingSignature(channelId, cmd.message.txId).message))))
}
else -> {
when (val res = commitments.updateLocalFundingStatus(fullySignedTx.signedTx.txid, commitments.latest.localFundingStatus.copy(sharedTx = fullySignedTx), logger)) {
is Either.Left -> Pair(this@WaitForChannelReady, listOf())
is Either.Right -> {
logger.info { "received remote funding signatures, publishing txId=${fullySignedTx.signedTx.txid}" }
val nextState = this@WaitForChannelReady.copy(commitments = res.value.first)
val actions = buildList {
add(ChannelAction.Blockchain.PublishTx(fullySignedTx.signedTx))
add(ChannelAction.Storage.StoreState(nextState))
}
Pair(nextState, actions)
}
}
}
}
is FullySignedSharedTransaction -> {
logger.info { "ignoring duplicate remote funding signatures" }
Pair(this@WaitForChannelReady, listOf())
}
}
is LocalFundingStatus.ConfirmedFundingTx -> {
logger.info { "ignoring funding signatures for txId=${cmd.message.txId}, transaction is already confirmed" }
Pair(this@WaitForChannelReady, listOf())
}
}
cmd is ChannelCommand.MessageReceived && cmd.message is TxInitRbf -> {
logger.info { "rejecting tx_init_rbf, we have already accepted the channel" }
Pair(this@WaitForChannelReady, listOf(ChannelAction.Message.Send(TxAbort(channelId, InvalidRbfTxConfirmed(channelId, commitments.latest.fundingTxId).message))))
}
cmd is ChannelCommand.MessageReceived && cmd.message is ChannelReady -> {
// used to get the final shortChannelId, used in announcements (if minDepth >= ANNOUNCEMENTS_MINCONF this event will fire instantly)
val watchConfirmed = WatchConfirmed(
this@WaitForChannelReady.channelId,
commitments.latest.commitInput.outPoint.txid,
commitments.latest.commitInput.txOut.publicKeyScript,
ANNOUNCEMENTS_MINCONF.toLong(),
BITCOIN_FUNDING_DEEPLYBURIED
)
// we create a channel_update early so that we can use it to send payments through this channel, but it won't be propagated to other nodes since the channel is not yet announced
val initialChannelUpdate = Announcements.makeChannelUpdate(
staticParams.nodeParams.chainHash,
staticParams.nodeParams.nodePrivateKey,
staticParams.remoteNodeId,
shortChannelId,
staticParams.nodeParams.expiryDeltaBlocks,
commitments.params.remoteParams.htlcMinimum,
staticParams.nodeParams.feeBase,
staticParams.nodeParams.feeProportionalMillionth.toLong(),
commitments.latest.fundingAmount.toMilliSatoshi(),
enable = Helpers.aboveReserve(commitments)
)
val nextState = Normal(
commitments,
shortChannelId,
buried = false,
null,
initialChannelUpdate,
null,
null,
null,
null
)
val actions = listOf(
ChannelAction.Blockchain.SendWatch(watchConfirmed),
ChannelAction.Storage.StoreState(nextState),
ChannelAction.EmitEvent(ChannelEvents.Confirmed(nextState)),
)
Pair(nextState, actions)
}
cmd is ChannelCommand.MessageReceived && cmd.message is Error -> handleRemoteError(cmd.message)
cmd is ChannelCommand.WatchReceived -> when (cmd.watch) {
is WatchEventConfirmed -> updateFundingTxStatus(cmd.watch)
is WatchEventSpent -> handlePotentialForceClose(cmd.watch)
}
cmd is ChannelCommand.ExecuteCommand -> when (cmd.command) {
is CMD_CLOSE -> Pair(this@WaitForChannelReady, listOf(ChannelAction.ProcessCmdRes.NotExecuted(cmd.command, CommandUnavailableInThisState(channelId, this::class.toString()))))
is CMD_FORCECLOSE -> handleLocalError(cmd, ForcedLocalCommit(channelId))
else -> unhandled(cmd)
}
cmd is ChannelCommand.CheckHtlcTimeout -> Pair(this@WaitForChannelReady, listOf())
cmd is ChannelCommand.Disconnected -> Pair(Offline(this@WaitForChannelReady), listOf())
else -> unhandled(cmd)
}
}
override fun ChannelContext.handleLocalError(cmd: ChannelCommand, t: Throwable): Pair<ChannelState, List<ChannelAction>> {
logger.error(t) { "error on command ${cmd::class.simpleName} in state ${this@WaitForChannelReady::class.simpleName}" }
val error = Error(channelId, t.message)
return when {
commitments.nothingAtStake() -> Pair(Aborted, listOf(ChannelAction.Message.Send(error)))
else -> spendLocalCurrent().run { copy(second = second + ChannelAction.Message.Send(error)) }
}
}
}
| 21
|
Kotlin
|
13
| 48
|
d36d723fe9644f8ff0ca31703e23903367943d1e
| 7,770
|
lightning-kmp
|
Apache License 2.0
|
Kernl.Common/src/main/kotlin/org/mattshoe/shoebox/kernl/KernlEvent.kt
|
mattshoe
| 825,957,770
| false
|
{"Kotlin": 344588, "Shell": 1045}
|
package org.mattshoe.shoebox.kernl
/**
* Represents events that affect the state of the cache, such as invalidation and refresh events.
* This sealed interface defines different types of events that can be emitted to manage the cache's lifecycle.
*/
sealed interface KernlEvent {
/**
* Indicates that the cache should be invalidated for specific parameters.
* Invalidation events can be used to mark cache entries as stale, requiring a refresh before they are used again.
*
* This event is only useful for scenarios where data changes outside the normal cache TTL, such as user-initiated updates
* or external system notifications.
*
* @property params Optional parameters that specify which cache entries should be invalidated.
* If null, all cache entries will be invalidated.
*/
data class Invalidate(val params: Any? = null): KernlEvent
/**
* Indicates that the cache should be refreshed for specific parameters.
* Refresh events can be used to proactively update cache entries before they become stale, ensuring data freshness.
*
* This event is only useful for scenarios where data needs to be periodically updated, such as scheduled background refreshes
* or pre-fetching data for future use.
*
* @property params Optional parameters that specify which cache entries should be refreshed.
* If null, all cache entries will be refreshed.
*/
data class Refresh(val params: Any? = null): KernlEvent
}
| 19
|
Kotlin
|
1
| 9
|
72110575d93274e990ebf92bb90ed49e35a96d9a
| 1,549
|
kernl
|
Apache License 2.0
|
src/main/kotlin/org/example/inflearnspringsecurityjwt/member/repository/MemberRepositories.kt
|
KangminNa
| 759,698,862
| false
|
{"Kotlin": 23049, "Assembly": 20}
|
package org.example.inflearnspringsecurityjwt.member.repository
import org.example.inflearnspringsecurityjwt.member.entitiy.Member
import org.example.inflearnspringsecurityjwt.member.entitiy.MemberRole
import org.springframework.data.jpa.repository.JpaRepository
interface MemberRepository : JpaRepository<Member, Long> {
fun findByLoginId(loginId: String): Member?
}
interface MemberRoleRepository : JpaRepository<MemberRole, Long>
| 1
|
Kotlin
|
0
| 0
|
a1799e283ba881066a774291e9575b71a92721b9
| 444
|
inflearn-spring-security-jwt
|
MIT License
|
app/src/main/java/com/example/instagram/CommentsActivity.kt
|
Raghavarya2002
| 331,052,361
| false
| null |
package com.example.instagram
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.instagram.Adapter.CommentAdapter
import com.example.instagram.Model.Commnet
import com.example.instagram.Model.User
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_comments.*
class CommentsActivity : AppCompatActivity() {
private var postId = ""
private var publisherId = ""
private var firebaseUser: FirebaseUser? = null
private var commentAdapter: CommentAdapter? = null
private var commentList: MutableList<Commnet>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_comments)
val intent = intent
postId = intent.getStringExtra("postId")!!
publisherId = intent.getStringExtra("publisherId")!!
firebaseUser = FirebaseAuth.getInstance().currentUser
var recyclerView: RecyclerView
recyclerView = findViewById(R.id.recycler_view_comments)
val linearLayoutManager = LinearLayoutManager(this)
linearLayoutManager.reverseLayout = true
recyclerView.layoutManager = linearLayoutManager
commentList = ArrayList()
commentAdapter = CommentAdapter(this, commentList)
recyclerView.adapter = commentAdapter
userinfo()
readComments()
getPostImage()
post_comment.setOnClickListener(View.OnClickListener {
if (add_comment!!.text.toString() == "") {
Toast.makeText(
this@CommentsActivity,
"Please write comments first",
Toast.LENGTH_LONG
)
} else {
addComment()
}
})
}
private fun addComment() {
val commentsRef = FirebaseDatabase.getInstance().reference
.child("Comments")
.child(postId!!)
val commentsMap = HashMap<String, Any>()
commentsMap["comment"] = add_comment!!.text.toString()
commentsMap["publisher"] = firebaseUser!!.uid
commentsRef.push().setValue(commentsMap)
addNotification()
add_comment!!.text.clear()
}
private fun userinfo() {
val userRef =
FirebaseDatabase.getInstance().reference.child("Users").child(firebaseUser!!.uid)
userRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
// if (context!= null) return
if (snapshot.exists()) {
val user = snapshot.getValue(User::class.java)
Picasso.get().load(user!!.getimage()).placeholder(R.drawable.profile)
.into(profile_image_comment)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun getPostImage() {
val postRef = FirebaseDatabase.getInstance().reference.child("Posts").child(postId!!)
.child("postimage")
postRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
// if (context!= null) return
if (snapshot.exists()) {
val image = snapshot.value.toString()
Picasso.get().load(image).placeholder(R.drawable.profile)
.into(post_image_comment)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun readComments() {
val commentsRef = FirebaseDatabase.getInstance().reference
.child("Comments")
.child(postId)
commentsRef.addValueEventListener(object : ValueEventListener {
override fun onCancelled(error: DatabaseError) {
}
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
commentList!!.clear()
for (snapshot in snapshot.children) {
val comment = snapshot.getValue(Commnet::class.java)
commentList!!.add(comment!!)
}
commentAdapter!!.notifyDataSetChanged()
}
}
})
}
private fun addNotification() {
val notiRef = FirebaseDatabase.getInstance().reference
.child("Notifications")
.child(publisherId!!)
val notiMap = HashMap<String, Any>()
notiMap["userid"] = firebaseUser!!.uid
notiMap["text"] = "commented:" + add_comment!!.text.toString()
notiMap["postid"] = postId
notiMap["isPost"] = true
notiRef.push().setValue(notiMap)
}
}
| 2
|
Kotlin
|
1
| 1
|
1a0dbcbf95b91fe0514d02e43fef371c5338b141
| 5,363
|
Instagram-Clone
|
MIT License
|
app/src/main/java/com/webaddicted/kotlinproject/view/deviceinfo/DeviceDetailsFrm.kt
|
morristech
| 332,046,416
| true
|
{"Kotlin": 942645, "Java": 311227}
|
package com.webaddicted.kotlinproject.view.deviceinfo
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.Html
import android.util.DisplayMetrics
import android.view.View
import android.view.WindowManager
import androidx.databinding.ViewDataBinding
import com.webaddicted.kotlinproject.R
import com.webaddicted.kotlinproject.databinding.FrmDevBasicBinding
import com.webaddicted.kotlinproject.view.base.BaseFragment
class DeviceDetailsFrm : BaseFragment() {
private lateinit var mBinding: FrmDevBasicBinding
companion object {
val TAG = DeviceDetailsFrm::class.java.simpleName
fun getInstance(bundle: Bundle): DeviceDetailsFrm {
val fragment = DeviceDetailsFrm()
fragment.arguments = bundle
return fragment
}
}
override fun getLayout(): Int {
return R.layout.frm_dev_basic
}
override fun initUI(binding: ViewDataBinding?, view: View) {
mBinding = binding as FrmDevBasicBinding
getDeviceInfo()
}
private fun getDeviceInfo() {
var txtColor = "#FFFFFF"
if ((resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) ==
Configuration.UI_MODE_NIGHT_NO
) txtColor = "#000000"
else txtColor = "#FFFFFF"
mBinding.txtDeviceName.text = Build.BRAND
mBinding.txtDeviceId.text = Build.MODEL
@SuppressLint("HardwareIds") val androidID =
Settings.Secure.getString(
context!!.contentResolver,
Settings.Secure.ANDROID_ID
)
val wm =
activity?.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val metrics = DisplayMetrics()
display.getMetrics(metrics)
val width = metrics.widthPixels
val height = metrics.heightPixels
val deviceInfo = "<font color=\"$txtColor\">Manufacturer : </font>${Build.MANUFACTURER}<br>" +
"<font color=\"$txtColor\">Hardware : </font>${Build.HARDWARE}<br>" +
"<font color=\"$txtColor\">Board : </font>${Build.BOARD}<br>" +
"<font color=\"$txtColor\">Serial : </font>${Build.SERIAL}<br>" +
"<font color=\"$txtColor\">Android Id : </font>${androidID}<br>" +
"<font color=\"$txtColor\">ScreenResolution : </font>$width * $height Pixels<br>" +
"<font color=\"$txtColor\">BootLoader : </font>${Build.BOOTLOADER}<br>" +
"<font color=\"$txtColor\">Host : </font>${Build.HOST}<br>" +
"<font color=\"$txtColor\">User : </font>${Build.USER}<br>"
mBinding.txtDeviceInfo.text = Html.fromHtml(deviceInfo, Html.FROM_HTML_MODE_LEGACY)
}
}
| 0
| null |
0
| 0
|
5bd58ffe6c9608757f81d523ac2c107708346319
| 2,897
|
KotlinProject
|
Apache License 2.0
|
core/network/src/main/java/com/reddity/app/network/model/NetworkSubredditDetail.kt
|
fatih-ozturk
| 501,051,682
| false
| null |
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reddity.app.network.model.response.posts.postdetail
import android.os.Parcelable
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import kotlinx.parcelize.Parcelize
@JsonClass(generateAdapter = true)
@Parcelize
data class NetworkSubredditDetail(
@Json(name = "icon_img") val iconImage: String?,
@Json(name = "community_icon") val communityIcon: String?
) : Parcelable {
val subredditIconUrl: String?
get() {
return when {
!iconImage.isNullOrEmpty() -> iconImage
else -> communityIcon
}
}
}
| 2
|
Kotlin
|
1
| 9
|
173317f3185aad4414e826ea2a34e62c2c210965
| 1,196
|
Reddity
|
Apache License 2.0
|
src/main/kotlin/net/kunmc/lab/netherblockconverter/game/GameManager.kt
|
TeamKun
| 387,051,822
| false
| null |
package net.kunmc.lab.netherblockconverter.game
import java.util.*
class GameManager {
companion object {
var converterPlayers = mutableListOf<UUID>()
}
}
| 0
|
Kotlin
|
0
| 0
|
87475eb7367edda27f820a1e88052fdea9cf40e6
| 172
|
NetherBlockConverter
|
MIT License
|
app/src/main/java/com/nsk/app/bussiness/card/OneClickCardActivity.kt
|
StephenGiant
| 230,359,216
| false
| null |
package com.nsk.app.bussiness.card
import android.graphics.Color
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.CustomListener
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bigkoo.pickerview.view.TimePickerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.nsk.app.Nothings
import com.nsk.app.base.BaseTitleActivity
import com.nsk.app.caikangyu.R
import com.nsk.app.config.ApiConfig
import com.nsk.app.config.Routers
import com.nsk.app.utils.RxjavaUtils
import com.nsk.cky.ckylibrary.RightListener
import com.nsk.cky.ckylibrary.UserConstants
import com.nsk.cky.ckylibrary.bean.BankCardBean
import com.nsk.cky.ckylibrary.utils.BaiduLocation
import com.nsk.cky.ckylibrary.utils.DbManger
import com.nsk.cky.ckylibrary.utils.PermissionHelper
import com.zaaach.citypicker.CityPicker
import com.zaaach.citypicker.adapter.OnPickListener
import com.zaaach.citypicker.model.City
import com.zaaach.citypicker.model.HotCity
import com.zaaach.citypicker.model.LocateState
import com.zaaach.citypicker.model.LocatedCity
import kotlinx.android.synthetic.main.activity_one_key_card.*
import java.text.SimpleDateFormat
import java.util.*
/**
* Description: 办卡
* Company :
* Author : gene
* Date : 2018/7/29
*/
@Route(path = Routers.one_key_cards)
class OneClickCardActivity : BaseTitleActivity() ,RightListener{
override fun onClick() {
//城市选择
val hotCities = ArrayList<HotCity>()
hotCities.add(HotCity("北京", "北京", "101010100"))
hotCities.add(HotCity("上海", "上海", "101020100"))
hotCities.add(HotCity("广州", "广东", "101280101"))
hotCities.add(HotCity("深圳", "广东", "101280601"))
CityPicker.getInstance()
.setFragmentManager(supportFragmentManager) //此方法必须调用
.enableAnimation(true) //启用动画效果
.setLocatedCity( LocatedCity(DbManger.getInstance().get(UserConstants.loca_city), "", "")) //APP自身已定位的城市,默认为null(定位失败)
.setHotCities(hotCities) //指定热门城市
.setOnPickListener(object : OnPickListener {
override fun onPick(position: Int, data: City?) {
//上传选择城市数据
if(data==null){
return
}
DbManger.getInstance().put(UserConstants.city,data.name)
setRight(DbManger.getInstance().get(UserConstants.city),true,this@OneClickCardActivity)
for (a in com.nsk.app.Nothings.temp) {
if(TextUtils.equals(a.n_area_city,DbManger.getInstance().get(UserConstants.city))||a.n_area_city.contains(DbManger.getInstance().get(UserConstants.city))){
DbManger.getInstance().put(UserConstants.areaId,a.n_area_id.toString())
LogUtils.e(a.n_area_city+a.n_area_id)
}
}
}
override fun onLocate() {
PermissionHelper.requestLocation(object : PermissionHelper.OnPermissionGrantedListener{
override fun onPermissionGranted() {
BaiduLocation.getLocation(object : BaiduLocation.MyLocationListener{
override fun myLocatin(isSuccess: Boolean, pro: String?, city: String?, code: String?) {
if(isSuccess){
CityPicker.getInstance()
.locateComplete( LocatedCity(city, pro, code), LocateState.SUCCESS)
}
}
})
}
})
}
})
.show()
}
lateinit var bankCardBean: BankCardBean
var income=""
override fun setTitle(): Int {
return R.string.one_key_card
}
override fun getContentLayoutId(): Int {
return R.layout.activity_one_key_card
}
override fun initData() {
}
lateinit var pvCustomLunar0: OptionsPickerView<String>
lateinit var pvCustomLunar: TimePickerView
lateinit var dateString: String
override fun initView() {
initMale()
initCard()
setRight(DbManger.getInstance().get(UserConstants.city),true,this)
val selectedDate = Calendar.getInstance()//系统当前时间
val startDate = Calendar.getInstance()
startDate.set(1949, 1, 1)
val endDate = Calendar.getInstance()
endDate.set(2040, 1, 1)
pvCustomLunar0 = OptionsPickerBuilder(this, OnOptionsSelectListener { options1, options2, options3, v ->
income=Nothings.n_typeid[options1]
tv_income.text = Nothings.n_code_typename[options1]
})
.setContentTextSize(20)//设置滚轮文字大小
.setDividerColor(Color.LTGRAY)//设置分割线的颜色
.setSelectOptions(0, 1)//默认选中项
.setSubCalSize(18)
.setTitleSize(16)//标题文字大小
.setSubmitColor(Color.BLACK)
.setCancelColor(Color.BLACK)//取消按钮文字颜色
.isRestoreItem(true)//切换时是否还原,设置默认选中第一项。
.setBackgroundId(0x00000000) //设置外部遮罩颜色
.build<String>()
pvCustomLunar0.setPicker(Nothings.n_code_typename as List<String>)
pvCustomLunar = TimePickerBuilder(this@OneClickCardActivity,
OnTimeSelectListener { date, _ ->
val cal = getTime(date)
val simpleDateFormat = SimpleDateFormat("yyyy/MM/dd")
dateString = simpleDateFormat.format(cal.time)
val year = cal.get(Calendar.YEAR)
val month = cal.get(Calendar.MONTH)+1
val day = cal.get(Calendar.DAY_OF_MONTH)
tv_age.text = year.toString()+"."+month+"."+day
}).setDate(selectedDate)
.setRangDate(startDate, endDate)
.setTitleBgColor(R.color.background)
.setSubCalSize(20)
.setTitleSize(16)//标题文字大小
.setSubmitColor(Color.BLACK)
.setCancelColor(Color.BLACK)//取消按钮文字颜色
.setLayoutRes(R.layout.pickerview_custom, object : CustomListener {
override fun customLayout(v: View) {
val tvSubmit = v.findViewById(R.id.tv_finish) as TextView
val ivCancel = v.findViewById(R.id.tv_cancel) as TextView
tvSubmit.setOnClickListener {
pvCustomLunar.returnData()
pvCustomLunar.dismiss()
}
ivCancel.setOnClickListener { pvCustomLunar.dismiss() }
}
}).setType(booleanArrayOf(true, true, true, false, false, false))
.isCenterLabel(false) //是否只显示中间选中项的label文字,false则每项item全部都带有label。
.setDividerColor(Color.LTGRAY).build()
tv_age.setOnClickListener {
pvCustomLunar.show()
}
tv_sex.setOnClickListener {
pvOptions.show()
}
tv_cred_card.setOnClickListener {
pv1Options.show()
}
tv_select.setOnClickListener {
LogUtils.e("",tv_age.text.toString(),male.isNotBlank(),hasCard.isNotBlank(),income.isNotBlank())
if(tv_age.text.toString().isNotBlank()&&male.isNotBlank()&&hasCard.isNotBlank()&&income.isNotBlank()){
val map = mapOf(Pair(UserConstants.n_age_segment,tv_age.text.toString()),
Pair(UserConstants.n_sex,male),
Pair(UserConstants.n_income_segment,income),
Pair(UserConstants.n_have_creditcard,hasCard),
Pair("areaid", DbManger.getInstance().get(UserConstants.areaId)) )
serviceApi.getForString(ApiConfig.oneKeyCard,map).compose(RxjavaUtils.transformer()).compose(RxjavaUtils.handleResult())
.subscribe({ response ->
val gson = Gson()
//接口获取数据
LogUtils.e(response)
var datas= ArrayList<BankCardBean.NskHotCreditListBean>()
datas = gson.fromJson<java.util.ArrayList<BankCardBean.NskHotCreditListBean>>(response,object : TypeToken<ArrayList<BankCardBean.NskHotCreditListBean>>(){
}.type)
ARouter.getInstance().build(Routers.recommendCard).withSerializable("recommend",true).withSerializable("data",datas).navigation()
finish()
// ToastUtils.showLong("办卡成功")
}, {
ToastUtils.showLong("未知错误")
})
}else{
ToastUtils.showLong(getString(R.string.input_right_format))
}
}
tv_income.setOnClickListener{
pvCustomLunar0.show()
}
}
private fun getTime(date: Date): Calendar {//可根据需要自行截取数据显示
val cal = Calendar.getInstance()
cal.time = date
return cal
}
lateinit var pvOptions: OptionsPickerView<String>
lateinit var pv1Options: OptionsPickerView<String>
var male="1"
var hasCard=String()
private fun initMale() {
val males: List<String> = listOf("男","女")
pvOptions = OptionsPickerBuilder(this, OnOptionsSelectListener { options1, options2, options3, v ->
val str = males.get(options1)
tv_sex.text = str
if(TextUtils.equals(str,"男")){
male="2"
}else{
male="1"
}
})
.setTitleSize(16)//标题文字大小
.setSubmitColor(Color.BLACK)
.setCancelColor(Color.BLACK)//取消按钮文字颜色
.setCancelText("取消").setSubmitText("确定").build()
pvOptions.run {
setPicker(males)
setSelectOptions(0)
}
}
private fun initCard() {
val males: List<String> = listOf("有","没")
pv1Options = OptionsPickerBuilder(this, OnOptionsSelectListener { options1, options2, options3, v ->
val str = males.get(options1)
tv_cred_card.text = str
if(TextUtils.equals(str,"有")){
hasCard="1"
}else{
hasCard="2"
}
})
.setSubCalSize(18)
.setTitleSize(16)//标题文字大小
.setSubmitColor(Color.BLACK)
.setCancelColor(Color.BLACK)//取消按钮文字颜色
.setCancelText("取消").setSubmitText("确定").build()
pv1Options.run {
setPicker(males)
setSelectOptions(0)
}
}
}
| 1
| null |
1
| 1
|
d4bd736b90989a2a8b774dafcc57ab8aa42aabae
| 11,527
|
fuckcky
|
Apache License 2.0
|
app/src/main/java/com/ramadan/freindstdd/SignupState.kt
|
mrabelwahed
| 558,716,704
| false
| null |
package com.ramadan.freindstdd
sealed class SignupState {
object BadEmail : SignupState()
object BadPassword : SignupState()
}
| 0
|
Kotlin
|
0
| 0
|
05d1fa4a1aa4931b44024a807c444afe321dc927
| 130
|
FriendsTDD
|
Apache License 2.0
|
src/main/kotlin/leetcode/kotlin/49. Group Anagrams.kt
|
sandeep549
| 262,513,267
| false
| null |
package leetcode.kotlin
import java.util.Arrays
private fun groupAnagrams2(strs: Array<String>): List<List<String>> {
fun isanagram(s1: String, s2: String): Boolean {
if (s1.length != s2.length) return false
val map = mutableMapOf<Char, Int>()
for (i in s1.indices) {
var ch = s1[i]
map.put(ch, map.getOrDefault(ch, 0) + 1)
ch = s2[i]
map.put(ch, map.getOrDefault(ch, 0) - 1)
}
for (value in map.values) {
if (value != 0) return false
}
return true
}
val result = mutableListOf<MutableList<String>>()
val arr = IntArray(strs.size)
for (i in strs.indices) {
val s1 = strs[i]
val group = mutableListOf<String>()
for (j in i..strs.lastIndex) {
val s2 = strs[j]
if (arr[j] == 1) continue
if (i == j && arr[j] == 0) {
group.add(s1)
arr[j] = 1
continue
}
if (isanagram(s1, s2)) {
group.add(s2)
arr[j] = 1
}
}
if (group.isNotEmpty()) result.add(group)
}
return result
}
private fun groupAnagrams(strs: Array<String>): List<List<String>> {
val result = mutableMapOf<String, MutableList<String>>()
if (strs.isEmpty()) return emptyList()
for (s in strs) {
val ca = s.toCharArray()
Arrays.sort(ca)
val key = String(ca)
if (!result.containsKey(key)) result[key] = mutableListOf()
result[key]!!.add(s)
}
return result.values.toList()
}
fun groupAnagrams3(strs: Array<String>): List<List<String?>?>? {
val result = mutableMapOf<String, MutableList<String>>()
if (strs.isEmpty()) return emptyList()
val count = IntArray(26)
for (s in strs) {
count.fill(0)
for (c in s.toCharArray()) count[c - 'a']++
val sb = StringBuilder("")
for (i in 0..25) {
sb.append('#')
sb.append(count[i])
}
val key = sb.toString()
if (!result.containsKey(key)) result[key] = mutableListOf()
result[key]!!.add(s)
}
return result.values.toList()
}
| 1
|
Kotlin
|
0
| 0
|
166e24331a24a73051995ccd31db2cf56523c432
| 2,219
|
leetcode-kotlin
|
Apache License 2.0
|
core/usecases/src/test/kotlin/character/BuildNewCharacterTest.kt
|
Soyle-Productions
| 239,407,827
| false
| null |
package com.soyle.stories.usecase.character
import arrow.core.Either
import arrow.core.left
import arrow.core.right
import com.soyle.stories.domain.character.Character
import com.soyle.stories.domain.character.characterName
import com.soyle.stories.domain.mustEqual
import com.soyle.stories.domain.nonBlankStr
import com.soyle.stories.domain.project.Project
import com.soyle.stories.domain.shouldBe
import com.soyle.stories.domain.theme.CharacterIsNotMajorCharacterInTheme
import com.soyle.stories.domain.theme.CharacterNotInTheme
import com.soyle.stories.domain.theme.Theme
import com.soyle.stories.domain.theme.characterInTheme.StoryFunction
import com.soyle.stories.domain.theme.makeTheme
import com.soyle.stories.domain.validation.NonBlankString
import com.soyle.stories.usecase.character.buildNewCharacter.BuildNewCharacter
import com.soyle.stories.usecase.character.buildNewCharacter.BuildNewCharacterUseCase
import com.soyle.stories.usecase.character.arc.listAllCharacterArcs.CharacterItem
import com.soyle.stories.usecase.repositories.CharacterRepositoryDouble
import com.soyle.stories.usecase.repositories.ThemeRepositoryDouble
import com.soyle.stories.usecase.theme.ThemeDoesNotExist
import com.soyle.stories.usecase.theme.includeCharacterInComparison.CharacterIncludedInTheme
import com.soyle.stories.usecase.theme.useCharacterAsOpponent.CharacterUsedAsOpponent
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.api.assertThrows
class BuildNewCharacterTest {
private val projectId = Project.Id()
val providedName = nonBlankStr("Character Name")
private var createdCharacter: Character? = null
fun given(addNewCharacter: (Character) -> Unit = {}): (NonBlankString) -> Either<*, CharacterItem> {
val repo = CharacterRepositoryDouble(
onAddNewCharacter = {
createdCharacter = it
addNewCharacter.invoke(it)
}
)
val useCase = BuildNewCharacterUseCase(repo, ThemeRepositoryDouble())
val output = object : BuildNewCharacter.OutputPort {
var result: Either<*, CharacterItem>? = null
override fun receiveBuildNewCharacterFailure(failure: Exception) {
result = failure.left()
}
override suspend fun receiveBuildNewCharacterResponse(response: CharacterItem) {
result = response.right()
}
override suspend fun characterIncludedInTheme(response: CharacterIncludedInTheme) {
error("Should not include character in theme when simply creating a new character")
}
override suspend fun characterIsOpponent(response: CharacterUsedAsOpponent) {
error("Should not include character in theme when simply creating a new character")
}
}
return {
runBlocking {
useCase(projectId.uuid, it, output)
}
output.result!!
}
}
val useCase = given()
@Test
fun `character should have provided name`() {
val character: CharacterItem = (useCase(providedName) as Either.Right).b
assertEquals(projectId, createdCharacter!!.projectId)
assertEquals(providedName.value, character.characterName)
}
@Test
fun `new character should be persisted`() {
val useCase = given()
useCase(providedName)
assertEquals(providedName, createdCharacter!!.name)
assertNull(createdCharacter!!.media)
}
@Test
fun `output character should have id from created character`() {
val useCase = given()
val (result) = useCase(providedName) as Either.Right
assertEquals(createdCharacter!!.id.uuid, result.characterId)
assertEquals(providedName.value, result.characterName)
assertEquals(createdCharacter!!.media?.uuid, result.mediaId)
}
@Nested
inner class `Include in Theme` {
private val themeId = Theme.Id()
private var updatedTheme: Theme? = null
private var opponentCharacter: CharacterUsedAsOpponent? = null
private var includedCharacterResult: CharacterIncludedInTheme? = null
private var characterItemResult: CharacterItem? = null
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
inner class `Theme doesn't exist` {
init {
val error = assertThrows<ThemeDoesNotExist> {
buildCharacterToIncludeInTheme(providedName)
}
error.themeId.mustEqual(themeId.uuid)
}
@Test
fun `check character is not created`() {
assertNull(createdCharacter)
}
}
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
inner class `Theme exists` {
init {
givenTheme()
buildCharacterToIncludeInTheme(providedName)
}
@Test
fun `check character created with proper name`() {
val createdCharacter = createdCharacter!!
assertEquals(projectId, createdCharacter.projectId)
assertEquals(providedName, createdCharacter.name)
}
@Test
fun `check theme updated to include new character`() {
val createdCharacter = createdCharacter!!
val updatedTheme = updatedTheme!!
assertTrue(updatedTheme.containsCharacter(createdCharacter.id))
val minorCharacter = updatedTheme.getMinorCharacterById(createdCharacter.id)!!
assertEquals(providedName.value, minorCharacter.name)
}
@Test
fun `check character included event is output`() {
val includedCharacterResult = includedCharacterResult!!
assertEquals(themeId.uuid, includedCharacterResult.themeId)
assertEquals(createdCharacter!!.id.uuid, includedCharacterResult.characterId)
assertEquals(providedName.value, includedCharacterResult.characterName)
}
}
@Nested
inner class `And Use as Opponent to Character` {
private val perspectiveCharacterId = Character.Id()
@Test
fun `perspective character not in theme`() {
givenTheme()
val error = assertThrows<CharacterNotInTheme> {
buildCharacterToUseAsOpponent(providedName)
}
error.themeId.mustEqual(themeId.uuid)
error.characterId.mustEqual(perspectiveCharacterId.uuid)
}
@Test
fun `perspective character is not major character`() {
givenTheme()
givenThemeHasCharacter(perspectiveCharacterId)
val error = assertThrows<CharacterIsNotMajorCharacterInTheme> {
buildCharacterToUseAsOpponent(providedName)
}
error.themeId.mustEqual(themeId.uuid)
error.characterId.mustEqual(perspectiveCharacterId.uuid)
}
@Test
fun `perspective character is major character`() {
givenTheme()
givenThemeHasCharacter(perspectiveCharacterId, asMajorCharacter = true)
buildCharacterToUseAsOpponent(providedName)
createdCharacter!!
updatedTheme!! shouldBe {
assertEquals(
StoryFunction.Antagonist,
it.getMajorCharacterById(perspectiveCharacterId)!!
.getStoryFunctionsForCharacter(createdCharacter!!.id)
)
}
characterItemResult!!
includedCharacterResult!!
opponentCharacter!!.let {
it.characterId.mustEqual(createdCharacter!!.id.uuid)
it.characterName.mustEqual(providedName.value)
it.opponentOfCharacterId.mustEqual(perspectiveCharacterId.uuid)
it.themeId.mustEqual(themeId.uuid)
}
}
private fun buildCharacterToUseAsOpponent(name: NonBlankString) {
val useCase: BuildNewCharacter =
BuildNewCharacterUseCase(
CharacterRepositoryDouble(
onAddNewCharacter = {
createdCharacter = it
}), themeRepository)
val output = object : BuildNewCharacter.OutputPort {
override suspend fun receiveBuildNewCharacterResponse(response: CharacterItem) {
characterItemResult = response
}
override fun receiveBuildNewCharacterFailure(failure: Exception) {
throw failure
}
override suspend fun characterIncludedInTheme(response: CharacterIncludedInTheme) {
includedCharacterResult = response
}
override suspend fun characterIsOpponent(response: CharacterUsedAsOpponent) {
opponentCharacter = response
}
}
runBlocking {
useCase.createAndUseAsOpponent(name, themeId.uuid, perspectiveCharacterId.uuid, output)
}
}
}
private val themeRepository = ThemeRepositoryDouble(onUpdateTheme = {
updatedTheme = it
})
private fun givenTheme() {
themeRepository.themes[themeId] = makeTheme(themeId, projectId = projectId)
}
private fun givenThemeHasCharacter(characterId: Character.Id, asMajorCharacter: Boolean = false) {
themeRepository.themes[themeId] = themeRepository.themes.getValue(themeId)
.withCharacterIncluded(characterId, characterName().value, null).let {
if (asMajorCharacter) it.withCharacterPromoted(characterId)
else it
}
}
private fun buildCharacterToIncludeInTheme(name: NonBlankString) {
val useCase: BuildNewCharacter = BuildNewCharacterUseCase(
CharacterRepositoryDouble(
onAddNewCharacter = {
createdCharacter = it
}), themeRepository)
val output = object : BuildNewCharacter.OutputPort {
override suspend fun receiveBuildNewCharacterResponse(response: CharacterItem) {
characterItemResult = response
}
override fun receiveBuildNewCharacterFailure(failure: Exception) {
throw failure
}
override suspend fun characterIncludedInTheme(response: CharacterIncludedInTheme) {
includedCharacterResult = response
}
override suspend fun characterIsOpponent(response: CharacterUsedAsOpponent) {
opponentCharacter = response
}
}
runBlocking {
useCase.createAndIncludeInTheme(name, themeId.uuid, output)
}
}
}
}
| 45
|
Kotlin
|
0
| 9
|
1a110536865250dcd8d29270d003315062f2b032
| 11,541
|
soyle-stories
|
Apache License 2.0
|
app/src/main/java/com/consistence/pinyin/app/PinyinModel.kt
|
nemanjanedic
| 139,743,535
| true
|
{"Kotlin": 96949}
|
package com.consistence.pinyin.app
import android.app.Application
import com.consistence.pinyin.Model
import com.consistence.pinyin.R
import io.reactivex.Observable
import javax.inject.Inject
class PinyinModel @Inject internal constructor(application: Application) : Model<PinyinIntent, PinyinState>(application) {
override fun reducer(intent: PinyinIntent): Observable<PinyinState> = when(intent) {
is PinyinIntent.TabSelected -> {
observable(
when (intent.page) {
Page.PHONETIC -> PinyinState.SearchHint(
context().getString(R.string.pinyin_activity_search_phonetic_hint))
Page.ENGLISH -> PinyinState.SearchHint(
context().getString(R.string.pinyin_activity_search_english_hint))
Page.CHARACTER -> PinyinState.SearchHint(
context().getString(R.string.pinyin_activity_search_character_hint))
}
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
45062d9ef1f69ca838c8f157a9f6ec6c0f4a5c5e
| 1,061
|
android-mvi
|
Apache License 2.0
|
app/src/main/java/nick/mirosh/newsapp/ui/animations/AnimationContent.kt
|
nsmirosh
| 644,001,365
| false
|
{"Kotlin": 68913}
|
package nick.mirosh.newsapp.ui.animations
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
const val ANIMATION_DURATION = 800
enum class AnimationState {
FIRST_IN_PROGRESS, SECOND_IN_PROGRESS, INITIAL
}
@Composable
fun SmileyProgressAnimation(
modifier: Modifier = Modifier
) {
var animationState by remember {
mutableStateOf(AnimationState.INITIAL)
}
LaunchedEffect(Unit) {
while (true) {
animationState = AnimationState.FIRST_IN_PROGRESS
delay(ANIMATION_DURATION.toLong())
animationState = AnimationState.SECOND_IN_PROGRESS
delay(ANIMATION_DURATION.toLong())
}
}
SmileyAnimationDrawer(animationState)
}
@Composable
fun SmileyAnimationDrawer(animationState: AnimationState) {
val widthAndHeight = 200.dp
val density = LocalDensity.current
val widthInPixels = with(density) { widthAndHeight.toPx() }
val oneThird = widthInPixels / 3
val twoThirds = widthInPixels / 3 * 2
val circleRadius = 30f
val animationColor = Color.Blue
val animatedX: Float by animateFloatAsState(
targetValue = if (animationState == AnimationState.SECOND_IN_PROGRESS) twoThirds else oneThird,
animationSpec = tween(durationMillis = ANIMATION_DURATION), label = ""
)
val animatedX2: Float by animateFloatAsState(
targetValue = if (animationState == AnimationState.SECOND_IN_PROGRESS) widthInPixels else twoThirds,
animationSpec = tween(durationMillis = ANIMATION_DURATION), label = ""
)
val animatedX3: Float by animateFloatAsState(
targetValue = if (animationState == AnimationState.SECOND_IN_PROGRESS) oneThird else 0f,
animationSpec = tween(durationMillis = ANIMATION_DURATION), label = ""
)
val sweepAngle by animateFloatAsState(
targetValue = if (animationState == AnimationState.FIRST_IN_PROGRESS) 180f else 0f,
animationSpec = tween(durationMillis = ANIMATION_DURATION),
label = "",
)
val sweepAngle2 by animateFloatAsState(
targetValue = if (animationState == AnimationState.SECOND_IN_PROGRESS) 0f else -180f,
animationSpec = tween(durationMillis = ANIMATION_DURATION),
label = "",
)
Box(
modifier = Modifier
.fillMaxSize()
) {
Canvas(
modifier = Modifier
.height(widthAndHeight)
.width(widthAndHeight)
.align(Alignment.Center)
) {
val circleY = size.height / 2
if (animationState == AnimationState.FIRST_IN_PROGRESS) {
drawCircle(
radius = circleRadius,
color = animationColor,
center = Offset(widthInPixels, circleY)
)
drawCircle(
radius = circleRadius,
color = animationColor,
center = Offset(oneThird, circleY)
)
drawCircle(
radius = circleRadius,
color = animationColor,
center = Offset(twoThirds, circleY)
)
drawArc(
color = animationColor,
topLeft = Offset(0f, 0f),
startAngle = 0f,
sweepAngle = sweepAngle,
useCenter = false,
style = Stroke(
width = circleRadius * 2,
cap = StrokeCap.Round
)
)
} else {
val arcCenter =
Offset(animatedX3, 0f)
drawCircle(
radius = circleRadius,
color = animationColor,
center = Offset(animatedX, circleY)
)
drawCircle(
radius = circleRadius,
color = animationColor,
center = Offset(animatedX2, circleY)
)
drawArc(
color = animationColor,
topLeft = arcCenter,
startAngle = 180f,
sweepAngle = sweepAngle2,
useCenter = false,
style = Stroke(
width = circleRadius * 2,
cap = StrokeCap.Round
)
)
}
}
}
}
| 0
|
Kotlin
|
1
| 2
|
83ea959a7b5f7c06e6a85784591573596d13ebdd
| 5,418
|
NewsApp
|
MIT License
|
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/ChartColumn.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 20416825}
|
package com.woowla.compose.icon.collections.tabler.tabler.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.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.ChartColumn: ImageVector
get() {
if (_chartColumn != null) {
return _chartColumn!!
}
_chartColumn = Builder(name = "ChartColumn", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 20.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(17.0f, 20.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(10.5f, 20.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 16.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(17.0f, 16.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(10.5f, 16.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 12.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(17.0f, 12.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(10.5f, 12.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 8.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(17.0f, 8.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 4.0f)
horizontalLineToRelative(3.0f)
}
}
.build()
return _chartColumn!!
}
private var _chartColumn: ImageVector? = null
| 0
|
Kotlin
|
0
| 1
|
b037895588c2f62d069c724abe624b67c0889bf9
| 5,549
|
compose-icon-collections
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/data/api/entities/Forecast.kt
|
fgoncalves
| 349,052,322
| false
| null |
package com.example.androiddevchallenge.data.api.entities
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Forecast(
@Json(name = "dt")
val dt: Long,
@Json(name = "sunrise")
val sunrise: Long? = null,
@Json(name = "sunset")
val sunset: Long? = null,
@Json(name = "temp")
val temp: Float,
@Json(name = "feels_like")
val feelsLike: Float,
@Json(name = "pressure")
val pressure: Float,
@Json(name = "humidity")
val humidity: Float,
@Json(name = "dew_point")
val dewPoint: Float,
@Json(name = "uvi")
val uvIndex: Float,
@Json(name = "clouds")
val clouds: Float,
@Json(name = "visibility")
val visibility: Float,
@Json(name = "wind_speed")
val windSpeed: Float,
@Json(name = "wind_deg")
val windDeg: Int,
@Json(name = "wind_gust")
val windGust: Float? = null,
@Json(name = "weather")
val weather: List<WeatherBit> = emptyList(),
)
| 0
|
Kotlin
|
0
| 0
|
af35d750b061cf3ad896cb46583fa60256e2d86e
| 1,011
|
compose-weather
|
Apache License 2.0
|
core/src/main/java/com/larryhsiao/nyx/core/jots/PostedJot.kt
|
LarryHsiao
| 192,473,048
| false
| null |
package com.larryhsiao.nyx.core.jots
import com.larryhsiao.clotho.Source
import java.sql.Connection
import java.util.*
/**
* Source to build a Jot that just updated or created.
*/
class PostedJot constructor(
private val db: Source<Connection>,
private val jot: Jot,
private val updateVer: Boolean = true
) : Source<Jot> {
override fun value(): Jot {
return if (jot.id() == -1L) {
val calendar = Calendar.getInstance()
calendar.time = Date(jot.createdTime())
NewJot(
db,
jot.title(),
jot.content(),
jot.location(),
calendar,
jot.mood(),
jot.privateLock()
).value()
} else {
UpdateJot(jot, db, updateVer).fire()
jot
}
}
}
| 15
|
Kotlin
|
1
| 1
|
518f547f913a48394f7301eff89ec7a43d7be80e
| 852
|
Nyx
|
MIT License
|
app/src/main/java/tech/takenoko/cleanarchitecturex/entities/room/UserDao.kt
|
TakenokoTech
| 224,243,588
| false
| null |
package tech.takenoko.cleanarchitecturex.entities.room
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import tech.takenoko.cleanarchitecturex.repository.local.UserLocalDataSource
@Dao
interface UserDao {
@Insert
suspend fun insertAll(vararg users: UserLocalDataSource.User)
// @Delete
// suspend fun delete(user: UserLocalDataSource.User)
@Query(QUERY_GET_ALL)
suspend fun getAll(): List<UserLocalDataSource.User>
// @Query(QUERY_FIND_BY_NAME)
// suspend fun findByName(name: String): UserLocalDataSource.User
@Query(QUERY_DELETE_ALL)
suspend fun deleteAll()
@Query(QUERY_GET_ALL)
fun getAllToLive(): LiveData<List<UserLocalDataSource.User>>
}
/** ユーザー全件取得 */
const val QUERY_GET_ALL = """
SELECT *
FROM user
"""
/** ユーザー名から検索 */
const val QUERY_FIND_BY_NAME = """
SELECT *
FROM user
WHERE name LIKE :name
LIMIT 1
"""
/** ユーザー全件削除 */
const val QUERY_DELETE_ALL = """
DELETE FROM user
"""
| 1
|
Kotlin
|
0
| 3
|
3fe34a5d239c7baece4de3a8416c9fd80fe129a2
| 1,043
|
CleanArchitectureX
|
MIT License
|
kotlinx-coroutines-core/jvm/test/lincheck/MutexLincheckTest.kt
|
hltj
| 151,721,407
| false
| null |
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("unused")
package kotlinx.coroutines.lincheck
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.*
import org.jetbrains.kotlinx.lincheck.*
import org.jetbrains.kotlinx.lincheck.annotations.Operation
import org.jetbrains.kotlinx.lincheck.strategy.managed.modelchecking.*
import org.junit.*
class MutexLincheckTest : AbstractLincheckTest() {
private val mutex = Mutex()
override fun modelCheckingTest() {
// Ignored via empty body as the only way
}
@Operation
fun tryLock() = mutex.tryLock()
@Operation(promptCancellation = true)
suspend fun lock() = mutex.lock()
@Operation(handleExceptionsAsResult = [IllegalStateException::class])
fun unlock() = mutex.unlock()
override fun <O : Options<O, *>> O.customize(isStressTest: Boolean): O =
actorsBefore(0)
override fun ModelCheckingOptions.customize(isStressTest: Boolean) =
checkObstructionFreedom()
override fun extractState() = mutex.isLocked
}
| 1
| null |
106
| 255
|
9565dc2d1bc33056dd4321f9f74da085e6c0f39e
| 1,107
|
kotlinx.coroutines-cn
|
Apache License 2.0
|
server-testing/src/test/kotlin/InMemoryDatabaseTests.kt
|
lightningkite
| 512,032,499
| false
| null |
package com.lightningkite.lightningdb.test
import com.lightningkite.lightningdb.*
import com.lightningkite.lightningserver.auth.*
import com.lightningkite.lightningserver.cache.Cache
import com.lightningkite.lightningserver.cache.CacheSettings
import com.lightningkite.lightningserver.cache.CacheTest
import com.lightningkite.lightningserver.cache.LocalCache
import com.lightningkite.lightningserver.core.ContentType
import com.lightningkite.lightningserver.core.ServerPath
import com.lightningkite.lightningserver.db.DatabaseSettings
import com.lightningkite.lightningserver.db.InMemoryDatabase
import com.lightningkite.lightningserver.db.ModelInfo
import com.lightningkite.lightningserver.email.EmailSettings
import com.lightningkite.lightningserver.engine.LocalEngine
import com.lightningkite.lightningserver.engine.engine
import com.lightningkite.lightningserver.files.FileSystemTests
import com.lightningkite.lightningserver.files.FilesSettings
import com.lightningkite.lightningserver.files.LocalFileSystem
import com.lightningkite.lightningserver.http.HttpContent
import com.lightningkite.lightningserver.http.HttpStatus
import com.lightningkite.lightningserver.http.test
import com.lightningkite.lightningserver.settings.Settings
import com.lightningkite.lightningserver.settings.setting
import com.lightningkite.lightningserver.sms.SMSSettings
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import org.junit.Test
import java.io.File
import java.time.Duration
import java.util.*
import kotlin.test.assertEquals
class RamAggregationsTest: AggregationsTest() {
override val database: Database = InMemoryDatabase()
}
class RamConditionTests: ConditionTests() {
override val database: Database = InMemoryDatabase()
}
class RamModificationTests: ModificationTests() {
override val database: Database = InMemoryDatabase()
}
class RamOperationsTests: OperationsTests() {
override val database: Database = InMemoryDatabase()
}
class RamSortTest: SortTest() {
override val database: Database = InMemoryDatabase()
}
class RamMetaTest: MetaTest() {
override val database: Database = InMemoryDatabase()
}
class DelayRamAggregationsTest: AggregationsTest() {
override val database: Database = InMemoryDatabase().delayed(5L)
}
class DelayRamConditionTests: ConditionTests() {
override val database: Database = InMemoryDatabase().delayed(5L)
}
class DelayRamModificationTests: ModificationTests() {
override val database: Database = InMemoryDatabase().delayed(5L)
}
class DelayRamOperationsTests: OperationsTests() {
override val database: Database = InMemoryDatabase().delayed(5L)
}
class DelayRamSortTest: SortTest() {
override val database: Database = InMemoryDatabase().delayed(5L)
}
class DelayRamMetaTest: MetaTest() {
override val database: Database = InMemoryDatabase().delayed(5L)
}
class LocalCacheTest: CacheTest() {
override val cache: Cache = LocalCache
}
class LocalFilesTest: FileSystemTests() {
init {
TestSettings
}
override val system: LocalFileSystem = LocalFileSystem(File("build/local-files-test"), "hosted-files", null, JwtSigner())
override fun testSignedUrlAccess() {
runBlocking {
val testFile = system.root.resolve("test.txt")
val message = "Hello world!"
testFile.put(HttpContent.Text(message, ContentType.Text.Plain))
val signed = testFile.signedUrl
assert(signed.startsWith(testFile.url))
println("testFile.signedUrl: ${signed}")
val response = system.fetch.test(
wildcard = signed.substringAfterLast("hosted-files").substringBefore('?'),
queryParameters = signed.substringAfter('?').split('&')
.map { it.substringBefore('=') to it.substringAfter('=') }
)
println(response)
assertEquals(HttpStatus.OK, response.status)
assertEquals(message, response.body?.text())
}
}
override fun testSignedUpload() {
runBlocking {
val testFile = system.root.resolve("test.txt")
val message = "Hello world!"
val signed = testFile.uploadUrl(Duration.ofHours(1))
val response = system.upload.test(
wildcard = signed.substringAfterLast("hosted-files").substringBefore('?'),
queryParameters = signed.substringAfter('?').split('&').map { it.substringBefore('=') to it.substringAfter('=') },
body = HttpContent.Text(message, ContentType.Text.Plain)
)
println(response)
assertEquals(HttpStatus.NoContent, response.status)
}
}
}
class SecurityTest() {
init { TestSettings }
@Test
fun test() {
prepareModels()
runBlocking {
val unsecured = TestSettings.database().collection<LargeTestModel>("SecurityTest_test")
val secured = unsecured.withPermissions(ModelPermissions(
create = Condition.Always(),
read = Condition.Always(),
readMask = mask {
always(it.intNullable.maskedTo(null))
},
update = Condition.Always(),
delete = Condition.Always(),
))
unsecured.insert(listOf(
LargeTestModel(intNullable = 1),
LargeTestModel(intNullable = 2),
LargeTestModel(intNullable = 3),
LargeTestModel(intNullable = 4),
))
val results = secured.find(Condition.Always()).toList()
assertEquals(4, results.size)
for(r in results) assertEquals(null, r.intNullable)
}
}
}
object TestSettings {
val database = setting("database", DatabaseSettings("ram"))
val email = setting("email", EmailSettings("test"))
val sms = setting("sms", SMSSettings("test"))
val jwtSigner = setting("jwt", JwtSigner())
val cache = setting("cache", CacheSettings())
val files = setting("files", FilesSettings())
val oauthGoogle = setting<OauthProviderCredentials?>("oauth_google", null)
val oauthApple = setting<OauthAppleEndpoints.OauthAppleSettings?>("oauth_apple", null)
val oauthGithub = setting<OauthProviderCredentials?>("oauth_github", null)
val oauthMicrosoft = setting<OauthProviderCredentials?>("oauth_microsoft", null)
val info = ModelInfo<User, User, UUID>(
getCollection = { database().collection() },
forUser = { this }
)
val emailAccess: UserEmailAccess<User, UUID> = info.userEmailAccess { User(email = it, phoneNumber = it) }
val path = ServerPath("auth")
val baseAuth = BaseAuthEndpoints(path, emailAccess, jwtSigner)
val emailAuth = EmailAuthEndpoints(baseAuth, emailAccess, cache, email)
init {
Settings.populateDefaults()
engine = LocalEngine
}
}
| 1
|
Kotlin
|
1
| 3
|
d9a8407cad1091aa6ae4e5e3e598b91e9c23bd2a
| 6,913
|
lightning-server
|
MIT License
|
BestTrip/app/src/main/java/com/example/minhquan/besttrip/login/view/ListTaxi.kt
|
leanhthien
| 141,224,809
| true
|
{"Kotlin": 76443, "Java": 1119}
|
package com.example.minhquan.besttrip.login.view
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.example.minhquan.besttrip.R
import com.example.minhquan.besttrip.adapter.TaxiAdapter
import com.example.minhquan.besttrip.getsetdata.presenter.GetDataTaxi
import com.example.minhquan.besttrip.getsetdata.view.GetDataViewTaxiItf
import com.example.minhquan.besttrip.model.mapdata.ResultRoute
import com.example.minhquan.besttrip.model.firebasedata.Company
import com.example.minhquan.besttrip.model.firebasedata.Taxi
import com.example.minhquan.besttrip.model.firebasedata.User
import com.google.firebase.database.FirebaseDatabase
import kotlinx.android.synthetic.main.activity_route.*
import kotlinx.android.synthetic.main.list_taxi.*
class ListTaxi : AppCompatActivity(), GetDataViewTaxiItf {
private lateinit var rv4Seater: RecyclerView
private lateinit var rv7Seater: RecyclerView
private lateinit var rvPremium: RecyclerView
private lateinit var taxiAdapter4: TaxiAdapter
private lateinit var taxiAdapter7: TaxiAdapter
private lateinit var taxiAdapterVip: TaxiAdapter
private lateinit var route: ResultRoute
private lateinit var user: User
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.list_taxi)
rv4Seater = findViewById(R.id.rec4Seater)
rv7Seater = findViewById(R.id.rec7Seater)
rvPremium = findViewById(R.id.recPremium)
setSupportActionBar(toolBar)
supportActionBar?.title = "Choose your taxi"
//Getdata Taxi from FireBase
val database = FirebaseDatabase.getInstance().reference
GetDataTaxi(this).getDataTaxi(database.child("Taxi"))
setUpListView()
imgButtonDown.setOnClickListener {
finish()
overridePendingTransition( R.anim.slide_in_down, R.anim.slide_out_down )
}
}
private fun setUpListView() {
val bundle = intent.getBundleExtra("routeBundle")
route = bundle.getParcelable("selected_route") as ResultRoute
user = intent.getSerializableExtra("DataUser") as User
taxiAdapter4 = TaxiAdapter(this@ListTaxi, route, user)
taxiAdapter7 = TaxiAdapter(this@ListTaxi, route, user)
taxiAdapterVip = TaxiAdapter(this@ListTaxi, route, user)
rv4Seater.setHasFixedSize(true)
rv7Seater.setHasFixedSize(true)
rvPremium.setHasFixedSize(true)
val layoutManager1 = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
rv4Seater.layoutManager = layoutManager1
val layoutManager2 = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
rv7Seater.layoutManager = layoutManager2
val layoutManager3 = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
rvPremium.layoutManager = layoutManager3
rv4Seater.adapter = taxiAdapter4
rv7Seater.adapter = taxiAdapter7
rvPremium.adapter = taxiAdapterVip
}
override fun showDataTaxi(ob: Taxi) {
val listTaxi4 : List<Company> = ob.seater4.listCompany
val listTaxi7 : List<Company> = ob.seater7.listCompany
val listTaxiVip : List<Company> = ob.vip.listCompany
taxiAdapter4.setData(listTaxi4)
taxiAdapter7.setData(listTaxi7)
taxiAdapterVip.setData(listTaxiVip)
}
}
| 0
|
Kotlin
|
0
| 0
|
37fd3b11e385155e96c8984898cee2e80a54e4c8
| 3,521
|
BestTrip
|
Apache License 2.0
|
app/src/main/java/me/shreyasr/chatse/chat/ChatActivity.kt
|
ninadmg
| 96,411,626
| false
|
{"Gradle": 3, "INI": 1, "Markdown": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Java Properties": 1, "JSON": 1, "Proguard": 1, "Java": 5, "XML": 17, "Kotlin": 24}
|
package me.shreyasr.chatse.chat
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.support.design.widget.TabLayout
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import com.squareup.okhttp.Request
import me.shreyasr.chatse.R
import me.shreyasr.chatse.chat.service.IncomingEventService
import me.shreyasr.chatse.chat.service.IncomingEventServiceBinder
import me.shreyasr.chatse.network.Client
import me.shreyasr.chatse.network.ClientManager
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.intentFor
import org.json.JSONException
import org.jsoup.Jsoup
import timber.log.Timber
import java.io.IOException
class ChatActivity : AppCompatActivity(), ServiceConnection {
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_chat, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item != null) {
when (item.itemId) {
R.id.search_rooms -> startActivity(intentFor<RoomSearchActivity>())
}
}
return super.onOptionsItemSelected(item)
}
private lateinit var pagerAdapter: ChatFragmentPagerAdapter
private lateinit var viewPager: ViewPager
private lateinit var serviceBinder: IncomingEventServiceBinder
private var networkHandler: Handler? = null
private val uiThreadHandler = Handler(Looper.getMainLooper())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.setContentView(R.layout.activity_chat)
// Setup toolbar
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val serviceIntent = Intent(this, IncomingEventService::class.java)
this.bindService(serviceIntent, this, Context.BIND_AUTO_CREATE)
val handlerThread = HandlerThread("ChatActivityNetworkHandlerThread")
handlerThread.start()
networkHandler = Handler(handlerThread.looper)
viewPager = this.findViewById(R.id.pager) as ViewPager
pagerAdapter = ChatFragmentPagerAdapter(supportFragmentManager)
viewPager.adapter = pagerAdapter
}
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
Timber.d("Service connect")
serviceBinder = binder as IncomingEventServiceBinder
joinRooms()
}
private fun joinRooms() {
val client = ClientManager.client
doAsync {
val chatPageRequest = Request.Builder()
.url("https://chat.stackoverflow.com/rooms?tab=mine&sort=active")
.build()
val chatPageResponse = client.newCall(chatPageRequest).execute()
val chatPage = Jsoup.parse(chatPageResponse.body().string())
val rooms = chatPage.getElementsByClass("room-name").filter { it.children()[0].hasAttr("href") }
rooms.forEach {
val roomNum = it.child(0).attr("href").split("/")[2].toInt()
loadChatFragment(ChatRoom(Client.SITE_STACK_OVERFLOW, roomNum))
}
}
}
override fun onServiceDisconnected(name: ComponentName) {
Timber.d("Service disconnect")
}
private fun loadChatFragment(room: ChatRoom) {
networkHandler?.post {
try {
addChatFragment(createChatFragment(room))
} catch (e: IOException) {
Timber.e("Failed to create chat fragment", e)
} catch (e: JSONException) {
Timber.e("Failed to create chat fragment", e)
}
}
}
private fun addChatFragment(fragment: ChatFragment) {
uiThreadHandler.post {
pagerAdapter.addFragment(fragment)
setupTabLayout()
}
}
@Throws(IOException::class, JSONException::class)
private fun createChatFragment(room: ChatRoom): ChatFragment {
val roomInfo = serviceBinder.loadRoom(room)
serviceBinder.joinRoom(room, roomInfo.fkey)
val chatFragment = ChatFragment.createInstance(room, roomInfo.name, roomInfo.fkey)
serviceBinder.registerListener(room, chatFragment)
return chatFragment
}
private fun setupTabLayout() {
// Get and set up tablayout
val tabLayout = findViewById(R.id.room_tabs) as TabLayout
tabLayout.tabGravity = TabLayout.GRAVITY_FILL
tabLayout.post { tabLayout.setupWithViewPager(viewPager) }
}
}
| 1
| null |
1
| 1
|
37fbe3046ad93db603c89bb62a93d9fb90e3b66a
| 4,731
|
ChatSE
|
Apache License 2.0
|
src/main/kotlin/sparta/nbcamp/wachu/domain/review/repository/v1/ReviewRepository.kt
|
spartaKotlinTeamSober
| 828,133,738
| false
|
{"Kotlin": 172694, "Dockerfile": 666}
|
package sparta.nbcamp.wachu.domain.review.repository.v1
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import sparta.nbcamp.wachu.domain.review.model.v1.Review
interface ReviewRepository {
fun findById(id: Long): Review?
fun findAll(pageable: Pageable): Page<Review>
fun save(review: Review): Review
fun delete(review: Review)
}
| 6
|
Kotlin
|
1
| 0
|
aca4ad613b9b775ec26b95f12408f0fcac5d0ed5
| 391
|
wachu_server
|
MIT License
|
goProControllerAndroid/src/test/java/com/bortxapps/goprocontrollerandroid/feature/connection/GoProConnectorImplTest.kt
|
neoBortx
| 692,337,190
| false
|
{"Kotlin": 361746, "Java": 572}
|
package com.bortxapps.goprocontrollerandroid.feature.connection
import android.bluetooth.BluetoothDevice
import android.content.Context
import app.cash.turbine.test
import com.bortxapps.goprocontrollerandroid.domain.data.GoProBleConnectionStatus
import com.bortxapps.goprocontrollerandroid.domain.data.GoProError
import com.bortxapps.goprocontrollerandroid.domain.data.GoProException
import com.bortxapps.goprocontrollerandroid.feature.commands.data.GOPRO_NAME_PREFIX
import com.bortxapps.goprocontrollerandroid.feature.commands.data.GoProUUID
import com.bortxapps.goprocontrollerandroid.feature.connection.api.ConnectionApi
import com.bortxapps.goprocontrollerandroid.feature.connection.mapper.toMapCamera
import com.bortxapps.simplebleclient.api.data.BleConnectionStatus
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class GoProConnectorImplTest {
private lateinit var api: ConnectionApi
private lateinit var connector: GoProConnectorImpl
private val context = mockk<Context>(relaxed = true)
@Before
fun setUp() {
api = mockk(relaxed = true)
connector = GoProConnectorImpl(context, api)
}
@Test
fun `stopSearch returns success when API call is successful`() = runTest {
coEvery { api.stopSearch() } just runs // Mocking the stopSearch method
val result = connector.stopSearch()
assertEquals(Result.success(true), result)
coVerify(exactly = 1) { api.stopSearch() }
}
@Test
fun `getCamerasPaired returns list of paired cameras`() = runTest {
val mockBluetoothDevice = mockk<BluetoothDevice>(relaxed = true)
val expectedCameraList = listOf(mockBluetoothDevice.toMapCamera())
coEvery { api.getPairedCameras(context, any()) } returns listOf(mockBluetoothDevice)
val result = connector.getCamerasPaired().getOrThrow().toList()
assertEquals(expectedCameraList, result)
coVerify(exactly = 1) { api.getPairedCameras(context, GOPRO_NAME_PREFIX) }
}
@Test
fun `getNearByCameras returns list of nearby cameras`() = runTest {
val mockBluetoothDevice = mockk<BluetoothDevice>(relaxed = true)
val expectedCameraList = listOf(mockBluetoothDevice.toMapCamera())
coEvery { api.getNearByCameras(GoProUUID.SERVICE_UUID.uuid) } returns flowOf(mockBluetoothDevice)
val result = connector.getNearByCameras().getOrThrow().toList()
assertEquals(expectedCameraList, result)
coVerify(exactly = 1) { api.getNearByCameras(GoProUUID.SERVICE_UUID.uuid) }
}
@Test
fun `disconnectBle calls api disconnectBle and returns success`() = runTest {
coEvery { api.disconnectBle() } just runs
val result = connector.disconnectBle()
assertEquals(Result.success(true), result)
coVerify(exactly = 1) { api.disconnectBle() }
}
@Test
fun `subscribeToBleConnectionStatusChanges transforms and emits correct values`() = runTest {
val mockStatusFlow = MutableStateFlow(BleConnectionStatus.DISCONNECTED)
every { api.subscribeToConnectionStatusChanges() } returns mockStatusFlow
connector.subscribeToBleConnectionStatusChanges().test {
assertEquals(GoProBleConnectionStatus.STATE_DISCONNECTED, awaitItem())
mockStatusFlow.value = BleConnectionStatus.CONNECTING
assertEquals(GoProBleConnectionStatus.STATE_CONNECTING, awaitItem())
mockStatusFlow.value = BleConnectionStatus.CONNECTED
assertEquals(GoProBleConnectionStatus.STATE_CONNECTED, awaitItem())
mockStatusFlow.value = BleConnectionStatus.DISCONNECTING
assertEquals(GoProBleConnectionStatus.STATE_DISCONNECTING, awaitItem())
}
}
@Test
fun `connectToDevice should return failure for general Exception`() = runTest {
val address = "TestAddress"
coEvery { api.connectToDevice(context, address) } throws Exception("Test Exception")
val result = connector.connectToDevice(address)
assertTrue(result.isFailure)
assertTrue(result.exceptionOrNull() is GoProException)
}
@Test
fun `connectToDevice should return failure for GoProException`() = runTest {
val address = "TestAddress"
val goProException = GoProException(GoProError.OTHER)
coEvery { api.connectToDevice(context, address) } throws goProException
val result = connector.connectToDevice(address)
assertTrue(result.isFailure)
assertEquals(goProException, result.exceptionOrNull())
}
@Test
fun `connectToDevice should return success when api returns true`() = runTest {
val address = "TestAddress"
coEvery { api.connectToDevice(context, address) } returns true
val result = connector.connectToDevice(address)
assertTrue(result.isSuccess)
assertEquals(true, result.getOrNull())
}
@Test
fun `connectToDevice should return failure when api returns false`() = runTest {
val address = "TestAddress"
coEvery { api.connectToDevice(context, address) } returns false
val result = connector.connectToDevice(address)
assertTrue(result.isFailure)
assertTrue(result.exceptionOrNull() is GoProException)
}
}
| 0
|
Kotlin
|
0
| 1
|
d1b7ec3c40a8f0438dcd5f568af0752b4e9092c1
| 5,648
|
goProController
|
Apache License 2.0
|
app/src/main/java/dev/sertan/android/paper/ui/addnote/AddNoteFragment.kt
|
scnplt
| 385,908,880
| false
| null |
package dev.sertan.android.paper.ui.addnote
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
import dev.sertan.android.paper.databinding.FragmentAddNoteBinding
import dev.sertan.android.paper.ui.main.MainActivity
@AndroidEntryPoint
internal class AddNoteFragment : Fragment() {
private var _binding: FragmentAddNoteBinding? = null
private val binding get() = _binding!!
private val viewModel by viewModels<AddNoteViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentAddNoteBinding.inflate(inflater, container, false)
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.viewModel = viewModel
(requireActivity() as? MainActivity)?.onFabClicked { viewModel.save(view) }
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
c6a973d14a4d473ecae5e22f6076a4e0be19013a
| 1,298
|
paper
|
MIT License
|
presentation/src/main/java/com/aliasadi/clean/ui/moviedetails/MovieDetailsFragment.kt
|
AliAsadi
| 264,456,753
| false
| null |
package com.aliasadi.clean.ui.moviedetails
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.navArgs
import com.aliasadi.clean.R
import com.aliasadi.clean.databinding.FragmentMovieDetailsBinding
import com.aliasadi.clean.ui.base.BaseFragment
import com.aliasadi.clean.util.launchAndRepeatWithViewLifecycle
import com.bumptech.glide.Glide
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/**
* @author by <NAME> on 13/05/2020
*/
@AndroidEntryPoint
class MovieDetailsFragment : BaseFragment<FragmentMovieDetailsBinding>() {
private val args: MovieDetailsFragmentArgs by navArgs()
@Inject
lateinit var factory: MovieDetailsViewModel.Factory
private val viewModel: MovieDetailsViewModel by viewModels {
MovieDetailsViewModel.provideFactory(factory, args.movieId)
}
override fun inflateViewBinding(inflater: LayoutInflater): FragmentMovieDetailsBinding =
FragmentMovieDetailsBinding.inflate(inflater)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
setupListeners()
observeViewModel()
}
private fun setupListeners() = with(binding) {
favorite.setOnClickListener {
viewModel.onFavoriteClicked()
}
}
private fun observeViewModel() = with(viewModel) {
launchAndRepeatWithViewLifecycle {
uiState.collect { handleMovieDetailsUiState(it) }
}
}
private fun handleMovieDetailsUiState(movieState: MovieDetailsViewModel.MovieDetailsUiState) {
binding.movieTitle.text = movieState.title
binding.description.text = movieState.description
loadImage(movieState.imageUrl)
updateFavoriteDrawable(getFavoriteDrawable(movieState.isFavorite))
}
private fun getFavoriteDrawable(favorite: Boolean): Drawable? = if (favorite) {
ContextCompat.getDrawable(requireContext(), R.drawable.ic_favorite_fill_white_48)
} else {
ContextCompat.getDrawable(requireContext(), R.drawable.ic_favorite_border_white_48)
}
private fun updateFavoriteDrawable(drawable: Drawable?) = with(binding.favorite) {
setImageDrawable(drawable)
}
private fun loadImage(url: String) =
Glide.with(this).load(url).placeholder(R.color.light_gray).error(R.drawable.bg_image).into(binding.image)
}
| 1
| null |
17
| 89
|
bcc165e6fd628cb4bcf11fca9eedabb33ed25d28
| 2,523
|
Android-Clean-Architecture
|
Apache License 2.0
|
imgui-core/src/main/kotlin/imgui/internal/api/inputText.kt
|
Wicpar
| 232,814,537
| true
|
{"Kotlin": 1778437, "Java": 136969}
|
package imgui.internal.api
import gli_.has
import glm_.compareTo
import glm_.func.common.min
import glm_.glm
import glm_.i
import glm_.vec2.Vec2
import glm_.vec4.Vec4
import imgui.*
import imgui.ImGui.beginChildFrame
import imgui.ImGui.beginGroup
import imgui.ImGui.calcItemSize
import imgui.ImGui.calcItemWidth
import imgui.ImGui.calcTextSize
import imgui.ImGui.clearActiveId
import imgui.ImGui.clipboardText
import imgui.ImGui.currentWindow
import imgui.ImGui.dataTypeApplyOpFromText
import imgui.ImGui.dummy
import imgui.ImGui.endChildFrame
import imgui.ImGui.endGroup
import imgui.ImGui.focusWindow
import imgui.ImGui.focusableItemRegister
import imgui.ImGui.format
import imgui.ImGui.getColorU32
import imgui.ImGui.io
import imgui.ImGui.itemAdd
import imgui.ImGui.itemHoverable
import imgui.ImGui.itemSize
import imgui.ImGui.logRenderedText
import imgui.ImGui.markItemEdited
import imgui.ImGui.parseFormatTrimDecorations
import imgui.ImGui.popFont
import imgui.ImGui.pushFont
import imgui.ImGui.renderFrame
import imgui.ImGui.renderNavHighlight
import imgui.ImGui.renderText
import imgui.ImGui.scrollMaxY
import imgui.ImGui.setActiveId
import imgui.ImGui.setFocusId
import imgui.ImGui.style
import imgui.ImGui.textLineHeight
import imgui.api.g
import imgui.classes.InputTextCallbackData
import imgui.internal.classes.Rect
import imgui.internal.*
import imgui.internal.classes.TextEditState
import uno.kotlin.getValue
import uno.kotlin.isPrintable
import uno.kotlin.setValue
import java.util.*
import kotlin.math.max
import kotlin.math.min
import kotlin.reflect.KMutableProperty0
/** InputText */
internal interface inputText {
/** InputTextEx
* - bufSize account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!".
* This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match
* Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator.
* - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect.
* - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stl.h
* (FIXME: Rather confusing and messy function, among the worse part of our codebase, expecting to rewrite a V2 at some point.. Partly because we are
* doing UTF8 > U16 > UTF8 conversions on the go to easily internal interface with stb_textedit. Ideally should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188)
*/
fun inputTextEx(label: String, hint: String?, buf: CharArray, sizeArg: Vec2, flags: InputTextFlags,
callback: InputTextCallback? = null, callbackUserData: Any? = null): Boolean {
val window = currentWindow
if (window.skipItems) return false
// Can't use both together (they both use up/down keys)
assert(!(flags has InputTextFlag.CallbackHistory && flags has InputTextFlag._Multiline))
// Can't use both together (they both use tab key)
assert(!(flags has InputTextFlag.CallbackCompletion && flags has InputTextFlag.AllowTabInput))
val RENDER_SELECTION_WHEN_INACTIVE = false
val isMultiline = flags has InputTextFlag._Multiline
val isReadOnly = flags has InputTextFlag.ReadOnly
val isPassword = flags has InputTextFlag.Password
val isUndoable = flags hasnt InputTextFlag.NoUndoRedo
val isResizable = flags has InputTextFlag.CallbackResize
if (isResizable)
assert(callback != null) { "Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag!" }
if (flags has InputTextFlag.CallbackCharFilter)
assert(callback != null) { "Must provide a callback if you want a char filter!" }
if (isMultiline) // Open group before calling GetID() because groups tracks id created within their scope
beginGroup()
val id = window.getId(label)
val labelSize = calcTextSize(label, -1, true)
val h = if (isMultiline) textLineHeight * 8f else labelSize.y
val frameSize = calcItemSize(sizeArg, calcItemWidth(), (if (isMultiline) g.fontSize * 8f else labelSize.y) + style.framePadding.y * 2f) // Arbitrary default of 8 lines high for multi-line
val totalSize = Vec2(frameSize.x + if (labelSize.x > 0f) style.itemInnerSpacing.x + labelSize.x else 0f, frameSize.y)
val frameBb = Rect(window.dc.cursorPos, window.dc.cursorPos + frameSize)
val totalBb = Rect(frameBb.min, frameBb.min + totalSize)
var drawWindow = window
val innerSize = Vec2(frameSize)
if (isMultiline) {
if (!itemAdd(totalBb, id, frameBb)) {
itemSize(totalBb, style.framePadding.y)
endGroup()
return false
}
if (!beginChildFrame(id, frameBb.size)) {
endChildFrame()
endGroup()
return false
}
drawWindow = g.currentWindow!! // Child window
// This is to ensure that EndChild() will display a navigation highlight
drawWindow.dc.navLayerActiveMaskNext = drawWindow.dc.navLayerActiveMaskNext or drawWindow.dc.navLayerCurrentMask
innerSize.x -= drawWindow.scrollbarSizes.x
} else {
itemSize(totalBb, style.framePadding.y)
if (!itemAdd(totalBb, id, frameBb)) return false
}
val hovered = itemHoverable(frameBb, id)
if (hovered) g.mouseCursor = MouseCursor.TextInput
// NB: we are only allowed to access 'editState' if we are the active widget.
var state_: TextEditState? = g.inputTextState.takeIf { it.id == id }
val focusRequested = focusableItemRegister(window, id)
val focusRequestedByCode = focusRequested && g.focusRequestCurrWindow === window && g.focusRequestCurrCounterAll == window.dc.focusCounterAll
val focusRequestedByTab = focusRequested && !focusRequestedByCode
val userClicked = hovered && io.mouseClicked[0]
val userNavInputStart = g.activeId != id && (g.navInputId == id || (g.navActivateId == id && g.navInputSource == InputSource.NavKeyboard))
val userScrollFinish = isMultiline && state_ != null && g.activeId == 0 && g.activeIdPreviousFrame == drawWindow getScrollbarID Axis.Y
val userScrollActive = isMultiline && state_ != null && g.activeId == drawWindow getScrollbarID Axis.Y
var clearActiveId = false
var selectAll = g.activeId != id && (flags has InputTextFlag.AutoSelectAll || userNavInputStart) && !isMultiline
// println(g.imeLastKey)
val initMakeActive = focusRequested || userClicked || userScrollFinish || userNavInputStart
val initState = initMakeActive || userScrollActive
if (initState && g.activeId != id) {
// Access state even if we don't own it yet.
state_ = g.inputTextState
state_.cursorAnimReset()
// Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar)
// From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode)
val bufLen = buf.strlen
state_.initialTextA = CharArray(bufLen) // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.
System.arraycopy(buf, 0, state_.initialTextA, 0, bufLen)
// Start edition
state_.textW = CharArray(buf.size) // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string.
state_.textA = CharArray(0)
state_.textAIsValid = false // TextA is not valid yet (we will display buf until then)
state_.curLenW = state_.textW.textStr(buf) // TODO check if ImTextStrFromUtf8 needed
/* We can't get the result from ImStrncpy() above because it is not UTF-8 aware.
Here we'll cut off malformed UTF-8. */
state_.curLenA = state_.curLenW //TODO check (int)(bufEnd - buf)
state_.cursorAnimReset()
/* Preserve cursor position and undo/redo stack if we come back to same widget
For non-readonly widgets we might be able to require that TextAIsValid && TextA == buf ? (untested) and discard undo stack if user buffer has changed. */
val recycleState = state_.id == id
if (recycleState)
/* Recycle existing cursor/selection/undo stack but clamp position
Note a single mouse click will override the cursor/position immediately by calling
stb_textedit_click handler. */
state_.cursorClamp()
else {
state_.id = id
state_.scrollX = 0f
state_.stb.clear(!isMultiline)
if (!isMultiline && focusRequestedByCode)
selectAll = true
}
if (flags has InputTextFlag.AlwaysInsertMode)
state_.stb.insertMode = true
if (!isMultiline && (focusRequestedByTab || (userClicked && io.keyCtrl)))
selectAll = true
}
if (g.activeId != id && initMakeActive) {
assert(state_!!.id == id)
setActiveId(id, window)
setFocusId(id, window)
focusWindow(window)
// Declare our inputs
assert(NavInput.values().size < 32)
g.activeIdUsingNavDirMask = g.activeIdUsingNavDirMask or ((1 shl Dir.Left) or (1 shl Dir.Right))
if (isMultiline || flags has InputTextFlag.CallbackHistory)
g.activeIdUsingNavDirMask = g.activeIdUsingNavDirMask or ((1 shl Dir.Up) or (1 shl Dir.Down))
g.activeIdUsingNavInputMask = g.activeIdUsingNavInputMask or (1 shl NavInput.Cancel)
g.activeIdUsingKeyInputMask = g.activeIdUsingKeyInputMask or ((1L shl Key.Home) or (1L shl Key.End))
if (isMultiline)
g.activeIdUsingKeyInputMask = g.activeIdUsingKeyInputMask or ((1L shl Key.PageUp) or (1L shl Key.PageDown)) // FIXME-NAV: Page up/down actually not supported yet by widget, but claim them ahead.
if (flags has (InputTextFlag.CallbackCompletion or InputTextFlag.AllowTabInput)) // Disable keyboard tabbing out as we will use the \t character.
g.activeIdUsingKeyInputMask = g.activeIdUsingKeyInputMask or (1L shl Key.Tab)
}
// We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function)
if (g.activeId == id && state_ == null)
clearActiveId()
// Release focus when we click outside
if (g.activeId == id && io.mouseClicked[0] && !initState && !initMakeActive)
clearActiveId = true
// Lock the decision of whether we are going to take the path displaying the cursor or selection
val renderCursor = g.activeId == id || (state_ != null && userScrollActive)
var renderSelection = state_?.hasSelection == true && (RENDER_SELECTION_WHEN_INACTIVE || renderCursor)
var valueChanged = false
var enterPressed = false
// When read-only we always use the live data passed to the function
// FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :(
if (isReadOnly && state_ != null && (renderCursor || renderSelection)) {
val tmp = CharArray(buf.size) // TODO resize()?
System.arraycopy(state_.textW, 0, tmp, 0, state_.textW.size)
state_.curLenW = state_.textW.textStr(buf) // TODO check
state_.curLenA = state_.curLenW // TODO check
state_.cursorClamp()
renderSelection = renderSelection && state_.hasSelection
}
// Select the buffer to render.
val bufDisplayFromState = (renderCursor || renderSelection || g.activeId == id) && !isReadOnly && state_?.textAIsValid == true
val isDisplayingHint = hint != null && (if (bufDisplayFromState) state_!!.textA else buf)[0] == NUL
// Password pushes a temporary font with only a fallback glyph
if (isPassword && !isDisplayingHint)
g.inputTextPasswordFont.apply {
val glyph = g.font.findGlyph('*')!!
fontSize = g.font.fontSize
scale = g.font.scale
displayOffset = g.font.displayOffset
ascent = g.font.ascent
descent = g.font.descent
containerAtlas = g.font.containerAtlas
fallbackGlyph = glyph
fallbackAdvanceX = glyph.advanceX
assert(glyphs.isEmpty() && indexAdvanceX.isEmpty() && indexLookup.isEmpty())
pushFont(this)
}
// Process mouse inputs and character inputs
var backupCurrentTextLength = 0
if (g.activeId == id) {
val state = state_!!
backupCurrentTextLength = state.curLenA
state.apply {
bufCapacityA = buf.size
userFlags = flags
userCallback = callback
userCallbackData = callbackUserData
}
/* Although we are active we don't prevent mouse from hovering other elements unless we are interacting
right now with the widget.
Down the line we should have a cleaner library-wide concept of Selected vs Active. */
g.activeIdAllowOverlap = !io.mouseDown[0]
g.wantTextInputNextFrame = 1
// Edit in progress
val mouseX = io.mousePos.x - frameBb.min.x - style.framePadding.x + state.scrollX
val mouseY = when {
isMultiline -> io.mousePos.y - drawWindow.dc.cursorPos.y - style.framePadding.y
else -> g.fontSize * 0.5f
}
// OS X style: Double click selects by word instead of selecting whole text
val isOsx = io.configMacOSXBehaviors
if (selectAll || (hovered && !isOsx && io.mouseDoubleClicked[0])) {
state.selectAll()
state.selectedAllMouseLock = true
} else if (hovered && isOsx && io.mouseDoubleClicked[0]) {
// Double-click select a word only, OS X style (by simulating keystrokes)
state.onKeyPressed(TextEditState.K.WORDLEFT)
state.onKeyPressed(TextEditState.K.WORDRIGHT or TextEditState.K.SHIFT)
} else if (io.mouseClicked[0] && !state.selectedAllMouseLock) {
if (hovered) {
state.click(mouseX, mouseY)
state.cursorAnimReset()
}
} else if (io.mouseDown[0] && !state.selectedAllMouseLock && io.mouseDelta.anyNotEqual(0f)) {
state.stb.selectStart = state.stb.cursor
state.stb.selectEnd = state.locateCoord(mouseX, mouseY)
state.cursorFollow = true
state.cursorAnimReset()
}
if (state.selectedAllMouseLock && !io.mouseDown[0])
state.selectedAllMouseLock = false
// It is ill-defined whether the back-end needs to send a \t character when pressing the TAB keys.
// Win32 and GLFW naturally do it but not SDL.
val ignoreCharInputs = (io.keyCtrl && !io.keyAlt) || (isOsx && io.keySuper)
if (flags has InputTextFlag.AllowTabInput && Key.Tab.isPressed && !ignoreCharInputs && !io.keyShift && !isReadOnly)
if ('\t' !in io.inputQueueCharacters)
withChar {
it.set('\t') // Insert TAB
if (inputTextFilterCharacter(it, flags, callback, callbackUserData))
state.onKeyPressed(it().i)
}
// Process regular text input (before we check for Return because using some IME will effectively send a Return?)
// We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters.
if (io.inputQueueCharacters.size > 0)
/*if (io.inputQueueCharacters[0] != NUL) I cant explaing why JVM had this TODO check */ {
if (!ignoreCharInputs && !isReadOnly && !userNavInputStart)
io.inputQueueCharacters.filter { it != NUL || (it == '\t' && io.keyShift) }.map {
// TODO check
withChar { c ->
// Insert character if they pass filtering
if (inputTextFilterCharacter(c.apply { set(it) }, flags, callback, callbackUserData))
state.onKeyPressed(c().i)
}
}
// Consume characters
io.inputQueueCharacters.clear()
}
}
// Process other shortcuts/key-presses
var cancelEdit = false
if (g.activeId == id && !g.activeIdIsJustActivated && !clearActiveId) {
val state = state_!!
val kMask = if (io.keyShift) TextEditState.K.SHIFT else 0
val isOsx = io.configMacOSXBehaviors
// OS X style: Shortcuts using Cmd/Super instead of Ctrl
val isShortcutKey = (if (isOsx) io.keySuper && !io.keyCtrl else io.keyCtrl && !io.keySuper) && !io.keyAlt && !io.keyShift
val isOsxShiftShortcut = isOsx && io.keySuper && io.keyShift && !io.keyCtrl && !io.keyAlt
val isWordmoveKeyDown = if (isOsx) io.keyAlt else io.keyCtrl // OS X style: Text editing cursor movement using Alt instead of Ctrl
// OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
val isStartendKeyDown = isOsx && io.keySuper && !io.keyCtrl && !io.keyAlt
val isCtrlKeyOnly = io.keyCtrl && !io.keyShift && !io.keyAlt && !io.keySuper
val isShiftKeyOnly = io.keyShift && !io.keyCtrl && !io.keyAlt && !io.keySuper
val isCut = ((isShortcutKey && Key.X.isPressed) || (isShiftKeyOnly && Key.Delete.isPressed)) && !isReadOnly && !isPassword && (!isMultiline || state.hasSelection)
val isCopy = ((isShortcutKey && Key.C.isPressed) || (isCtrlKeyOnly && Key.Insert.isPressed)) && !isPassword && (!isMultiline || state.hasSelection)
val isPaste = ((isShortcutKey && Key.V.isPressed) || (isShiftKeyOnly && Key.Insert.isPressed)) && !isReadOnly
val isUndo = ((isShortcutKey && Key.Z.isPressed) && !isReadOnly && isUndoable)
val isRedo = ((isShortcutKey && Key.Y.isPressed) || (isOsxShiftShortcut && Key.Z.isPressed)) && !isReadOnly && isUndoable
when {
Key.LeftArrow.isPressed -> state.onKeyPressed(when {
isStartendKeyDown -> TextEditState.K.LINESTART
isWordmoveKeyDown -> TextEditState.K.WORDLEFT
else -> TextEditState.K.LEFT
} or kMask)
Key.RightArrow.isPressed -> state.onKeyPressed(when {
isStartendKeyDown -> TextEditState.K.LINEEND
isWordmoveKeyDown -> TextEditState.K.WORDRIGHT
else -> TextEditState.K.RIGHT
} or kMask)
Key.UpArrow.isPressed && isMultiline ->
if (io.keyCtrl)
drawWindow.setScrollY(glm.max(drawWindow.scroll.y - g.fontSize, 0f))
else
state.onKeyPressed((if (isStartendKeyDown) TextEditState.K.TEXTSTART else TextEditState.K.UP) or kMask)
Key.DownArrow.isPressed && isMultiline ->
if (io.keyCtrl)
drawWindow.setScrollY(glm.min(drawWindow.scroll.y + g.fontSize, scrollMaxY))
else
state.onKeyPressed((if (isStartendKeyDown) TextEditState.K.TEXTEND else TextEditState.K.DOWN) or kMask)
Key.Home.isPressed -> state.onKeyPressed((if (io.keyCtrl) TextEditState.K.TEXTSTART else TextEditState.K.LINESTART) or kMask)
Key.End.isPressed -> state.onKeyPressed((if (io.keyCtrl) TextEditState.K.TEXTEND else TextEditState.K.LINEEND) or kMask)
Key.Delete.isPressed && !isReadOnly -> state.onKeyPressed(TextEditState.K.DELETE or kMask)
Key.Backspace.isPressed && !isReadOnly -> {
if (!state.hasSelection)
if (isWordmoveKeyDown)
state.onKeyPressed(TextEditState.K.WORDLEFT or TextEditState.K.SHIFT)
else if (isOsx && io.keySuper && !io.keyAlt && !io.keyCtrl)
state.onKeyPressed(TextEditState.K.LINESTART or TextEditState.K.SHIFT)
state.onKeyPressed(TextEditState.K.BACKSPACE or kMask)
}
Key.Enter.isPressed || Key.KeyPadEnter.isPressed -> {
val ctrlEnterForNewLine = flags has InputTextFlag.CtrlEnterForNewLine
if (!isMultiline || (ctrlEnterForNewLine && !io.keyCtrl) || (!ctrlEnterForNewLine && io.keyCtrl)) {
clearActiveId = true
enterPressed = true
} else if (!isReadOnly)
withChar('\n') { c ->
// Insert new line
if (inputTextFilterCharacter(c, flags, callback, callbackUserData))
state.onKeyPressed(c().i)
}
}
Key.Escape.isPressed -> {
cancelEdit = true
clearActiveId = true
}
isUndo || isRedo -> {
state.onKeyPressed(if (isUndo) TextEditState.K.UNDO else TextEditState.K.REDO)
state.clearSelection()
}
isShortcutKey && Key.A.isPressed -> {
state.selectAll()
state.cursorFollow = true
}
isCut || isCopy -> {
// Cut, Copy
io.setClipboardTextFn?.let {
val ib = if (state.hasSelection) min(state.stb.selectStart, state.stb.selectEnd) else 0
val ie = if (state.hasSelection) max(state.stb.selectStart, state.stb.selectEnd) else state.curLenW
clipboardText = String(state.textW, ib, ie - ib)
}
if (isCut) {
if (!state.hasSelection)
state.selectAll()
state.cursorFollow = true
state.cut()
}
}
isPaste -> {
val clipboard = clipboardText
// Filter pasted buffer
val clipboardLen = clipboard.length
val clipboardFiltered = CharArray(clipboardLen)
var clipboardFilteredLen = 0
for (c in clipboard) {
if (c == NUL)
break
_c = c
if (!inputTextFilterCharacter(::_c, flags, callback, callbackUserData))
continue
clipboardFiltered[clipboardFilteredLen++] = _c
}
if (clipboardFilteredLen > 0) { // If everything was filtered, ignore the pasting operation
state.paste(clipboardFiltered, clipboardFilteredLen)
state.cursorFollow = true
}
}
}
// Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame.
renderSelection = renderSelection || (state.hasSelection && (RENDER_SELECTION_WHEN_INACTIVE || renderCursor))
}
// Process callbacks and apply result back to user's buffer.
if (g.activeId == id) {
val state = state_!!
var applyNewText = CharArray(0)
// var applyNewTextPtr = 0
var applyNewTextLength = 0
if (cancelEdit)
// Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.
if (!isReadOnly && !Arrays.equals(buf, state.initialTextA)) {
applyNewText = state.initialTextA
applyNewTextLength = state.initialTextA.size
}
/* When using `InputTextFlag.EnterReturnsTrue` as a special case we reapply the live buffer back to the
input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.
If we didn't do that, code like `inputInt()` with `InputTextFlag.EnterReturnsTrue` would fail.
Also this allows the user to use `inputText()` with `InputTextFlag.EnterReturnsTrue` without
maintaining any user-side storage. */
val applyEditBackToUserBuffer = !cancelEdit || (enterPressed && flags hasnt InputTextFlag.EnterReturnsTrue)
if (applyEditBackToUserBuffer) {
// Apply new value immediately - copy modified buffer back
// Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
// FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
// FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
if (!isReadOnly) {
state.textAIsValid = true
state.textA = CharArray(state.textW.size * 4) { state.textW.getOrElse(it) { NUL } }
}
// User callback
if (flags has (InputTextFlag.CallbackCompletion or InputTextFlag.CallbackHistory or InputTextFlag.CallbackAlways)) {
callback!!
val (eventFlag, eventKey) = when {
(flags has imgui.InputTextFlag.CallbackCompletion) and Key.Tab.isPressed -> Pair(imgui.InputTextFlag.CallbackCompletion.i, Key.Tab)
(flags has imgui.InputTextFlag.CallbackHistory) and Key.UpArrow.isPressed -> Pair(imgui.InputTextFlag.CallbackHistory.i, Key.UpArrow)
(flags has imgui.InputTextFlag.CallbackHistory) and Key.DownArrow.isPressed -> Pair(imgui.InputTextFlag.CallbackHistory.i, Key.DownArrow)
flags has imgui.InputTextFlag.CallbackAlways -> Pair(imgui.InputTextFlag.CallbackAlways.i, Key.Count)
else -> Pair(0, Key.Count)
}
if (eventFlag != 0) {
val cbData = TextEditCallbackData()
cbData.eventFlag = eventFlag
cbData.flags = flags
cbData.userData = callbackUserData
cbData.eventKey = eventKey
cbData.buf = state.textA
cbData.bufTextLen = state.curLenA
cbData.bufSize = state.bufCapacityA
cbData.bufDirty = false
val cursorPos = state.stb.cursor
val selectionStart = state.stb.selectStart
val selectionEnd = state.stb.selectEnd
cbData.cursorPos = cursorPos
cbData.selectionStart = selectionStart
cbData.selectionEnd = selectionEnd
callback.invoke(cbData)
assert(cbData.bufSize == state.bufCapacityA)
assert(cbData.flags == flags)
if (cbData.cursorPos != cursorPos) {
state.stb.cursor = cbData.cursorPos
}
if (cbData.selectionStart != selectionStart) {
state.stb.selectStart = cbData.selectionStart
}
if (cbData.selectionEnd != selectionEnd) {
state.stb.selectEnd = cbData.selectionEnd
}
if (cbData.bufDirty) {
assert(cbData.bufTextLen == cbData.buf.strlen)
if ((cbData.bufTextLen > backupCurrentTextLength) and isResizable)
TODO("pass a reference to buf and bufSize")
//TODO: Hacky
state.deleteChars(0, cursorPos)
state.insertChars(0, cbData.buf, 0, cbData.bufTextLen)
state.cursorAnimReset()
}
}
}
// Will copy result string if modified
if (!isReadOnly && !state.textA.cmp(buf)) {
applyNewText = state.textA
applyNewTextLength = state.curLenA
}
}
// Copy result to user buffer
if (applyNewText.isNotEmpty()) {
assert(applyNewTextLength >= 0)
if (backupCurrentTextLength != applyNewTextLength && isResizable) {
TODO("pass a reference to buf and bufSize")
// val callbackData = InputTextCallbackData().apply {
// eventFlag = Itf.CallbackResize.i
// this.flags = flags
// this.buf = buf
// bufTextLen = apply_new_text_length
//// bufSize = max(bufSize, applyNewTextLength)
// userData = callbackUserData
// }
// callback!!(callbackData)
// buf = callback_data.Buf
// buf_size = callback_data.BufSize
// apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1);
// IM_ASSERT(apply_new_text_length <= buf_size);
}
/* If the underlying buffer resize was denied or not carried to the next frame,
apply_new_text_length+1 may be >= buf_size. */
buf.strncpy(applyNewText, (applyNewTextLength + 1) min buf.size)
valueChanged = true
}
// Clear temporary user storage
state.apply {
userFlags = 0
userCallback = null
userCallbackData = null
}
}
// Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
if (clearActiveId && g.activeId == id) clearActiveId()
// Render frame
if (!isMultiline) {
renderNavHighlight(frameBb, id)
renderFrame(frameBb.min, frameBb.max, Col.FrameBg.u32, true, style.frameRounding)
}
val clipRect = Vec4(frameBb.min, frameBb.min + innerSize) // Not using frameBb.Max because we have adjusted size
val drawPos = if (isMultiline) Vec2(drawWindow.dc.cursorPos) else frameBb.min + style.framePadding
val textSize = Vec2()
/* Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line
without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether.
Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. */
val bufDisplayMaxLength = 2 * 1024 * 1024
var bufDisplay = if (bufDisplayFromState) state_!!.textA else buf
var bufDisplayEnd = -1 // We have specialized paths below for setting the length
if (isDisplayingHint) {
bufDisplay = hint!!.toCharArray()
bufDisplayEnd = hint.length
}
// Render text. We currently only render selection when the widget is active or while scrolling.
// FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive.
if (renderCursor || renderSelection) {
val state = state_!! // ~assert
if (!isDisplayingHint)
bufDisplayEnd = state.curLenA
/* Render text (with cursor and selection)
This is going to be messy. We need to:
- Display the text (this alone can be more easily clipped)
- Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d
cursor position calculation)
- Measure text height (for scrollbar)
We are attempting to do most of that in **one main pass** to minimize the computation cost
(non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an
extra refactoring effort) */
// FIXME: This should occur on bufDisplay but we'd need to maintain cursor/select_start/select_end for UTF-8.
val text = state.textW
val cursorOffset = Vec2()
val selectStartOffset = Vec2()
run {
// Find lines numbers straddling 'cursor' (slot 0) and 'select_start' (slot 1) positions.
val searchesInputPtr = IntArray(2)
val searchesResultLineNo = intArrayOf(-1000, -1000)
var searchesRemaining = 0
if (renderCursor) {
searchesInputPtr[0] = state.stb.cursor
searchesResultLineNo[0] = -1
searchesRemaining++
}
if (renderSelection) {
searchesInputPtr[1] = state.stb.selectStart min state.stb.selectEnd
searchesResultLineNo[1] = -1
searchesRemaining++
}
// Iterate all lines to find our line numbers
// In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searchesRemaining counter.
if (isMultiline) searchesRemaining++
var lineCount = 0
var s = 0
while (s < text.size && text[s] != NUL)
if (text[s++] == '\n') {
lineCount++
if (searchesResultLineNo[0] == -1 && s >= searchesInputPtr[0]) {
searchesResultLineNo[0] = lineCount
if (--searchesRemaining <= 0) break
}
if (searchesResultLineNo[1] == -1 && s >= searchesInputPtr[1]) {
searchesResultLineNo[1] = lineCount
if (--searchesRemaining <= 0) break
}
}
lineCount++
if (searchesResultLineNo[0] == -1)
searchesResultLineNo[0] = lineCount
if (searchesResultLineNo[1] == -1)
searchesResultLineNo[1] = lineCount
// Calculate 2d position by finding the beginning of the line and measuring distance
var start = text.beginOfLine(searchesInputPtr[0])
cursorOffset.x = inputTextCalcTextSizeW(text, start, searchesInputPtr[0]).x
cursorOffset.y = searchesResultLineNo[0] * g.fontSize
if (searchesResultLineNo[1] >= 0) {
start = text.beginOfLine(searchesInputPtr[1])
selectStartOffset.x = inputTextCalcTextSizeW(text, start, searchesInputPtr[1]).x
selectStartOffset.y = searchesResultLineNo[1] * g.fontSize
}
// Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
if (isMultiline)
textSize.put(innerSize.x, lineCount * g.fontSize)
}
// Scroll
if (renderCursor && state.cursorFollow) {
// Horizontal scroll in chunks of quarter width
if (flags hasnt InputTextFlag.NoHorizontalScroll) {
val scrollIncrementX = innerSize.x * 0.25f
if (cursorOffset.x < state.scrollX)
state.scrollX = floor(glm.max(0f, cursorOffset.x - scrollIncrementX))
else if (cursorOffset.x - innerSize.x >= state.scrollX)
state.scrollX = floor(cursorOffset.x - innerSize.x + scrollIncrementX)
} else
state.scrollX = 0f
// Vertical scroll
if (isMultiline) {
var scrollY = drawWindow.scroll.y
if (cursorOffset.y - g.fontSize < scrollY)
scrollY = glm.max(0f, cursorOffset.y - g.fontSize)
else if (cursorOffset.y - innerSize.y >= scrollY)
scrollY = cursorOffset.y - innerSize.y
drawPos.y += drawWindow.scroll.y - scrollY // Manipulate cursor pos immediately avoid a frame of lag
drawWindow.scroll.y = scrollY
}
state.cursorFollow = false
}
// Draw selection
val drawScroll = Vec2(state.scrollX, 0f)
if (renderSelection) {
val textSelectedBegin = glm.min(state.stb.selectStart, state.stb.selectEnd)
val textSelectedEnd = glm.max(state.stb.selectStart, state.stb.selectEnd)
val bgColor = getColorU32(Col.TextSelectedBg, if (renderCursor) 1f else 0.6f) // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests.
val bgOffYUp = if (isMultiline) 0f else -1f // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
val bgOffYDn = if (isMultiline) 0f else 2f
val rectPos = drawPos + selectStartOffset - drawScroll
var p = textSelectedBegin
while (p < textSelectedEnd) {
if (rectPos.y > clipRect.w + g.fontSize) break
if (rectPos.y < clipRect.y) {
while (p < textSelectedEnd)
if (text[p++] == '\n')
break
} else {
val rectSize = withInt {
inputTextCalcTextSizeW(text, p, textSelectedEnd, it, stopOnNewLine = true).also { p = it() }
}
// So we can see selected empty lines
if (rectSize.x <= 0f) rectSize.x = floor(g.font.getCharAdvance(' ') * 0.5f)
val rect = Rect(rectPos + Vec2(0f, bgOffYUp - g.fontSize), rectPos + Vec2(rectSize.x, bgOffYDn))
val clipRect_ = Rect(clipRect)
rect clipWith clipRect_
if (rect overlaps clipRect_)
drawWindow.drawList.addRectFilled(rect.min, rect.max, bgColor)
}
rectPos.x = drawPos.x - drawScroll.x
rectPos.y += g.fontSize
}
}
// We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash.
if (isMultiline || bufDisplayEnd < bufDisplayMaxLength) {
val col = getColorU32(if (isDisplayingHint) Col.TextDisabled else Col.Text)
drawWindow.drawList.addText(g.font, g.fontSize, drawPos - drawScroll, col, bufDisplay, bufDisplayEnd, 0f, clipRect.takeUnless { isMultiline })
}
// Draw blinking cursor
if (renderCursor) {
state.cursorAnim += io.deltaTime
val cursorIsVisible = !io.configInputTextCursorBlink || state.cursorAnim <= 0f || glm.mod(state.cursorAnim, 1.2f) <= 0.8f
val cursorScreenPos = drawPos + cursorOffset - drawScroll
val cursorScreenRect = Rect(cursorScreenPos.x, cursorScreenPos.y - g.fontSize + 0.5f, cursorScreenPos.x + 1f, cursorScreenPos.y - 1.5f)
if (cursorIsVisible && cursorScreenRect overlaps clipRect)
drawWindow.drawList.addLine(cursorScreenRect.min, cursorScreenRect.bl, Col.Text.u32)
// Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)
if (!isReadOnly)
g.platformImePos.put(cursorScreenPos.x - 1f, cursorScreenPos.y - g.fontSize)
}
} else {
// Render text only (no selection, no cursor)
if (isMultiline) {
_i = bufDisplayEnd
textSize.put(innerSize.x, inputTextCalcTextLenAndLineCount(bufDisplay, ::_i) * g.fontSize) // We don't need width
bufDisplayEnd = _i
} else if (!isDisplayingHint && g.activeId == id)
bufDisplayEnd = state_!!.curLenA
else if (!isDisplayingHint)
bufDisplayEnd = bufDisplay.strlen
if (isMultiline || bufDisplayEnd < bufDisplayMaxLength) {
val col = getColorU32(if (isDisplayingHint) Col.TextDisabled else Col.Text)
drawWindow.drawList.addText(g.font, g.fontSize, drawPos, col, bufDisplay, bufDisplayEnd, 0f, clipRect.takeUnless { isMultiline })
}
}
if (isMultiline) {
dummy(textSize + Vec2(0f, g.fontSize)) // Always add room to scroll an extra line
endChildFrame()
endGroup()
}
if (isPassword && !isDisplayingHint)
popFont()
// Log as text
if (g.logEnabled && !(isPassword && !isDisplayingHint))
logRenderedText(drawPos, String(bufDisplay), bufDisplayEnd)
if (labelSize.x > 0)
renderText(Vec2(frameBb.max.x + style.itemInnerSpacing.x, frameBb.min.y + style.framePadding.y), label)
if (valueChanged && flags hasnt InputTextFlag._NoMarkEdited)
markItemEdited(id)
ImGuiTestEngineHook_ItemInfo(id, label, window.dc.itemFlags)
return when {
flags has InputTextFlag.EnterReturnsTrue -> enterPressed
else -> valueChanged
}
}
/** Create text input in place of another active widget (e.g. used when doing a CTRL+Click on drag/slider widgets)
* FIXME: Facilitate using this in variety of other situations. */
fun tempInputTextScalar(bb: Rect, id: ID, label: String, dataType: DataType, pData: KMutableProperty0<*>,
format_: String): Boolean {
// On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id.
// We clear ActiveID on the first frame to allow the InputText() taking it back.
val init = g.tempInputTextId != id
if (init)
clearActiveId()
val fmtBuf = CharArray(32)
val format = parseFormatTrimDecorations(format_, fmtBuf)
var dataBuf = pData.format(dataType, format, 32)
dataBuf = trimBlanks(dataBuf)
g.currentWindow!!.dc.cursorPos put bb.min
val flags: InputTextFlags = InputTextFlag.AutoSelectAll or InputTextFlag._NoMarkEdited or when (dataType) {
DataType.Float, DataType.Double -> InputTextFlag.CharsScientific
else -> InputTextFlag.CharsDecimal
}
var valueChanged = inputTextEx(label, null, dataBuf, bb.size, flags)
if (init) {
assert(g.activeId == id) { "First frame we started displaying the InputText widget, we expect it to take the active id." }
g.tempInputTextId = g.activeId
}
if (valueChanged) {
valueChanged = dataTypeApplyOpFromText(dataBuf, g.inputTextState.initialTextA, dataType, pData)
if (valueChanged)
markItemEdited(id)
}
return valueChanged
}
fun tempInputTextIsActive(id: ID): Boolean = g.activeId == id && g.tempInputTextId == id
companion object {
/** Return false to discard a character. */
fun inputTextFilterCharacter(char: KMutableProperty0<Char>, flags: InputTextFlags, callback: InputTextCallback?, userData: Any?): Boolean {
var c by char
// Filter non-printable (NB: isprint is unreliable! see #2467) [JVM we can rely on custom ::isPrintable]
if (c < 0x20 && !c.isPrintable) {
var pass = false
pass = pass or (c == '\n' && flags has InputTextFlag._Multiline)
pass = pass or (c == '\t' && flags has InputTextFlag.AllowTabInput)
if (!pass) return false
}
// We ignore Ascii representation of delete (emitted from Backspace on OSX, see #2578, #2817)
if (c.i == 127)
return false
// Filter private Unicode range. GLFW on OSX seems to send private characters for special keys like arrow keys (FIXME)
if (c >= 0xE000 && c <= 0xF8FF) return false
// Filter Unicode ranges we are not handling in this build.
if (c > UNICODE_CODEPOINT_MAX)
return false
// Generic named filters
if (flags has (InputTextFlag.CharsDecimal or InputTextFlag.CharsHexadecimal or InputTextFlag.CharsUppercase or InputTextFlag.CharsNoBlank or InputTextFlag.CharsScientific)) {
if (flags has InputTextFlag.CharsDecimal)
if (c !in '0'..'9' && c != '.' && c != '-' && c != '+' && c != '*' && c != '/')
return false
if (flags has InputTextFlag.CharsScientific)
if (c !in '0'..'9' && c != '.' && c != '-' && c != '+' && c != '*' && c != '/' && c != 'e' && c != 'E')
return false
if (flags has InputTextFlag.CharsHexadecimal)
if (c !in '0'..'9' && c !in 'a'..'f' && c !in 'A'..'F')
return false
if (flags has InputTextFlag.CharsUppercase && c in 'a'..'z')
c = c + ('A' - 'a') // cant += because of https://youtrack.jetbrains.com/issue/KT-14833
if (flags has InputTextFlag.CharsNoBlank && c.isBlankW)
return false
}
// Custom callback filter
if (flags has InputTextFlag.CallbackCharFilter) {
callback!! //callback is non-null from all calling functions
val itcd = InputTextCallbackData()
itcd.eventFlag = imgui.InputTextFlag.CallbackCharFilter.i
itcd.eventChar = c
itcd.flags = flags
itcd.userData = userData
if (callback(itcd))
return false
if (itcd.eventChar == NUL)
return false
}
return true
}
fun inputTextCalcTextLenAndLineCount(text: CharArray, outTextEnd: KMutableProperty0<Int>): Int {
var lineCount = 0
var s = 0
while (text.getOrElse(s++) { NUL } != NUL) // We are only matching for \n so we can ignore UTF-8 decoding
if (text.getOrElse(s) { NUL } == '\n')
lineCount++
s--
if (text[s] != '\n' && text[s] != '\r')
lineCount++
outTextEnd.set(s)
return lineCount
}
fun inputTextCalcTextSizeW(text: CharArray, textBegin: Int, textEnd: Int, remaining: KMutableProperty0<Int>? = null,
outOffset: Vec2? = null, stopOnNewLine: Boolean = false): Vec2 {
val font = g.font
val lineHeight = g.fontSize
val scale = lineHeight / font.fontSize
val textSize = Vec2()
var lineWidth = 0f
var s = textBegin
while (s < textEnd) {
val c = text[s++]
if (c == '\n') {
textSize.x = glm.max(textSize.x, lineWidth)
textSize.y += lineHeight
lineWidth = 0f
if (stopOnNewLine)
break
continue
}
if (c == '\r') continue
// renaming ::getCharAdvance continuously every build because of bug, https://youtrack.jetbrains.com/issue/KT-19612
val charWidth = font.getCharAdvance(c) * scale
lineWidth += charWidth
}
if (textSize.x < lineWidth)
textSize.x = lineWidth
// offset allow for the possibility of sitting after a trailing \n
outOffset?.let {
it.x = lineWidth
it.y = textSize.y + lineHeight
}
if (lineWidth > 0 || textSize.y == 0f) // whereas size.y will ignore the trailing \n
textSize.y += lineHeight
remaining?.set(s)
return textSize
}
}
}
| 0
| null |
0
| 0
|
b06800f8db31a2da5aec3730e0d1e395583e5b35
| 50,025
|
imgui
|
MIT License
|
portal/core/src/main/java/com/serious/portal/DeploymentManager.kt
|
coolsamson7
| 700,938,199
| false
|
{"Kotlin": 283465, "TypeScript": 228658, "HTML": 30094, "SCSS": 11216, "JavaScript": 3100, "Dockerfile": 1558, "CSS": 1409, "Shell": 1112}
|
package com.serious.portal
/*
* @COPYRIGHT (C) 2016 Andreas Ernst
*
* All rights reserved
*/
import com.serious.portal.model.Deployment
import com.serious.portal.model.Feature
import com.serious.portal.model.Manifest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.*
import kotlin.collections.HashMap
// types
typealias ManifestFilter = (manifest: Manifest) -> Boolean
typealias FeatureFilter = (feature: Feature) -> Boolean
@Component
class DeploymentManager(@Autowired val manager: ManifestManager) {
// instance data
private val manifestFilters = mutableListOf<ManifestFilter>()
private val featureFilters = mutableListOf<FeatureFilter>()
// constructor
init {
filterManifest { manifest -> manifest.enabled }
filterFeature { feature -> feature.enabled }
// TODO: session
}
// fluent
fun filterManifest(filter: ManifestFilter): DeploymentManager {
manifestFilters.add(filter)
return this
}
fun filterFeature(filter: FeatureFilter): DeploymentManager {
featureFilters.add(filter)
return this
}
private fun check(manifest: Manifest) : Boolean {
for ( filter in manifestFilters)
if ( !filter(manifest))
return false
return true
}
private fun check(feature: Feature) : Boolean {
for ( filter in featureFilters)
if ( !filter(feature))
return false
return true
}
// public
fun create() : Deployment {
// local function
fun copyFeature(feature: Feature) : Feature {
val result = feature.copy()
val features = LinkedList<Feature>()
if ( feature.children != null)
for ( feature in feature.children!!) {
if ( check(feature))
features.add(copyFeature(feature))
}
result.children = features.toTypedArray()
return result
}
val deployment = Deployment(HashMap())
// add matching manifests
for ( manifest in manager.manifests)
if (check(manifest)) {
val result = manifest.copy()
deployment.modules.put(manifest.name, result);
val features = LinkedList<Feature>()
for ( feature in manifest.features) {
if ( check(feature))
features.add(copyFeature(feature))
}
result.features = features.toTypedArray()
}
// done
return deployment
}
}
| 0
|
Kotlin
|
0
| 1
|
ca1b6135229bf0ad902650dc0e7a87efd1ddd2cf
| 2,714
|
service
|
Apache License 2.0
|
enode/src/main/java/org/enodeframework/domain/AggregateCacheInfo.kt
|
anruence
| 165,245,292
| false
| null |
package org.enodeframework.domain
import org.enodeframework.common.extensions.SystemClock
import java.util.*
/**
* @author <EMAIL>
*/
class AggregateCacheInfo(var aggregateRoot: AggregateRoot) {
private var lastUpdateTime: Date
init {
lastUpdateTime = Date()
}
fun updateAggregateRoot(aggregateRoot: AggregateRoot) {
this.aggregateRoot = aggregateRoot
lastUpdateTime = Date()
}
fun isExpired(timeoutSeconds: Int): Boolean {
return (SystemClock.now() - lastUpdateTime.time) / 1000 >= timeoutSeconds
}
}
| 1
| null |
55
| 205
|
22c81b98b36a6a221d026272594eaf7817145e0f
| 569
|
enode
|
MIT License
|
app/src/main/java/com/example/happyweather/logic/model/Weather.kt
|
ambitionlin
| 468,588,496
| false
|
{"Kotlin": 28842}
|
package com.example.knweather.logic.model
data class Weather(val realtime: RealtimeResponse.Realtime, val daily: DailyResponse.Daily)
| 0
|
Kotlin
|
0
| 1
|
ff2f465fbae719810882d08914f03635c9c59cee
| 134
|
HappyWeather
|
Apache License 2.0
|
CRM/src/main/kotlin/org/example/crm/services/HistoryService.kt
|
M4tT3d
| 874,249,564
| false
|
{"Kotlin": 354206, "TypeScript": 180680, "JavaScript": 3610, "Dockerfile": 2844, "CSS": 2078, "HTML": 302}
|
package org.example.crm.services
import org.example.crm.dtos.HistoryDTO
import org.example.crm.dtos.request.create.CHistoryDTO
interface HistoryService {
fun create(createHistoryDTO: CHistoryDTO): HistoryDTO
fun findHistoryByMessageId(pageNumber: Int, limit: Int, messageId: Long): List<HistoryDTO>
}
| 0
|
Kotlin
|
0
| 0
|
26ff03cc3863e278d0ec6b87ced384122cf66c98
| 311
|
wa2-project-job-placement
|
MIT License
|
src/main/kotlin/herbaccara/map/naver/form/RasterForm.kt
|
herbaccara
| 616,228,341
| false
| null |
package herbaccara.map.naver.form
import com.toasttab.ksp.builder.annotations.GenerateBuilder
import herbaccara.map.Coordinate
@GenerateBuilder
data class RasterForm @JvmOverloads constructor(
val width: Int,
val height: Int,
val center: Coordinate? = null,
val crs: String? = null,
val level: Int? = null,
val mapType: MapType? = null,
val format: Format? = null,
val scale: Scale? = null,
val markers: List<Marker>? = null,
val lang: Lang? = null,
val publicTransit: Boolean? = null,
val dataVersion: String? = null
) {
companion object {
@JvmStatic
fun builder(): RasterFormBuilder = RasterFormBuilder()
}
enum class Format(val value: String) {
JPG("jpg"),
JPEG("jpeg"),
PNG8("png8"),
PNG("png")
}
enum class Lang(val value: String) {
KO("ko"),
EN("en"),
JA("ja"),
ZH("zh")
}
enum class MapType(val value: String) {
BASIC("basic"),
TRAFFIC("traffic"),
SATELLITE("satellite"),
SATELLITE_BASE("satellite_base"),
TERRAIN("terrain")
}
enum class Scale(val value: Int) {
LOW(1),
HIGH(2)
}
data class Marker @JvmOverloads constructor(
val pos: Coordinate,
val type: Type = Type.DEFAULT,
val size: Size = Size.MID,
val viewSizeRatio: Double = 1.0,
val color: String? = null,
val label: String? = null
) {
enum class Type(val value: String) {
DEFAULT("d"),
NUMBER("n"),
ALPHABET("a"),
TOOLTIP("t")
}
enum class Size(val value: String) {
TINY("tiny"),
SMALL("small"),
MID("mid")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
1bbc39e5e32d0a30a1ea5f14c4c82353e4ac52c2
| 1,789
|
spring-boot-starter-map
|
MIT License
|
backend/src/main/java/com/paligot/confily/backend/speakers/SpeakerDb.kt
|
GerardPaligot
| 444,230,272
| false
| null |
package org.gdglille.devfest.backend.speakers
data class SpeakerDb(
val id: String = "",
val displayName: String = "",
val pronouns: String? = null,
val bio: String = "",
val email: String? = null,
val jobTitle: String? = null,
val company: String? = null,
val photoUrl: String = "",
val website: String? = null,
val twitter: String? = null,
val mastodon: String? = null,
val github: String? = null,
val linkedin: String? = null
)
| 9
| null |
6
| 143
|
8c0985b73422d6b388012d79c7ab33c054dc55c1
| 484
|
Confily
|
Apache License 2.0
|
paymentsheet/src/androidTest/java/com/stripe/android/paymentsheet/PaymentMethodsUITest.kt
|
stripe
| 6,926,049
| false
| null |
package com.stripe.android.paymentsheet
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.test.SemanticsNodeInteraction
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.assertWidthIsEqualTo
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performScrollToNode
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import com.stripe.android.paymentsheet.model.SupportedPaymentMethod
import kotlinx.coroutines.flow.MutableStateFlow
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@ExperimentalAnimationApi
@RunWith(AndroidJUnit4::class)
internal class PaymentMethodsUITest {
@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()
private val bancontactTestTag by lazy {
TEST_TAG_LIST + composeTestRule.activity.resources.getString(
SupportedPaymentMethod.Bancontact.displayNameResource
)
}
private val epsTestTag by lazy {
TEST_TAG_LIST + composeTestRule.activity.resources.getString(
SupportedPaymentMethod.Eps.displayNameResource
)
}
@Test
fun test() {
composeTestRule.setContent {
PaymentMethodsUI(
paymentMethods = listOf(
SupportedPaymentMethod.Bancontact,
SupportedPaymentMethod.Sofort,
SupportedPaymentMethod.AfterpayClearpay,
SupportedPaymentMethod.Eps
),
selectedIndex = 0,
isEnabled = true,
onItemSelectedListener = {}
)
}
// Expect the value to be equal to the width of the screen
// minus the left and right padding for each card
// calculateViewWidth(
// composeTestRule.activity.resources.displayMetrics,
// paymentMethods.size
// ) - (CARD_HORIZONTAL_PADDING.dp * 2)
bancontact.assertWidthIsEqualTo(109.454544.dp)
}
@Test
fun testPmItemIsDisabledWhenListDisabled() {
val enableListControl = MutableStateFlow(true)
composeTestRule.setContent {
val enabled by enableListControl.collectAsState(true)
PaymentMethodsUI(
paymentMethods = listOf(
SupportedPaymentMethod.Bancontact,
SupportedPaymentMethod.SepaDebit,
SupportedPaymentMethod.Sofort,
SupportedPaymentMethod.Ideal,
SupportedPaymentMethod.Eps
),
selectedIndex = 0,
isEnabled = enabled,
onItemSelectedListener = {}
)
}
bancontact.assertIsEnabled()
enableListControl.value = false
bancontact.assertIsNotEnabled()
}
@Test
fun testScrollIsDisabledWhenListDisabled() {
val enableListControl = MutableStateFlow(true)
composeTestRule.setContent {
val enabled by enableListControl.collectAsState(true)
PaymentMethodsUI(
paymentMethods = listOf(
SupportedPaymentMethod.Bancontact,
SupportedPaymentMethod.SepaDebit,
SupportedPaymentMethod.Sofort,
SupportedPaymentMethod.Ideal,
SupportedPaymentMethod.Eps
),
selectedIndex = 0,
isEnabled = enabled,
onItemSelectedListener = {}
)
}
// scroll to the EPS label, which is not currently in view, bancontact the first item
// will no longer be in view
bancontact.assertIsDisplayed()
eps.assertDoesNotExist()
paymentMethodList.performScrollToNode(hasTestTag(epsTestTag))
bancontact.assertIsNotDisplayed()
eps.assertIsDisplayed()
eps.assertIsEnabled()
// When we disable the list no longer scroll to the first item in the list
enableListControl.value = false
bancontact.assertExists()
bancontact.assertIsNotDisplayed()
paymentMethodList.assertScrollToListItemDisabled(bancontactTestTag)
bancontact.assertIsNotDisplayed()
eps.assertIsDisplayed()
eps.assertIsNotEnabled()
}
/**
* Disabling of scrolling will fail because it will not be able to find the node
* in the scroll list.
*/
private fun SemanticsNodeInteraction.assertScrollToListItemDisabled(testTag: String) {
var errorMsg: String? = null
try {
this.performScrollToNode(
hasTestTag(testTag)
)
} catch (e: AssertionError) {
errorMsg = e.message
}
assertThat(errorMsg)
.contains(
"No node found that matches TestTag = '$testTag' in scrollable container"
)
}
private val bancontact
get() = composeTestRule.onNodeWithTag(
TEST_TAG_LIST + composeTestRule.activity.resources.getString(
SupportedPaymentMethod.Bancontact.displayNameResource
)
)
private val eps
get() = composeTestRule.onNodeWithTag(
TEST_TAG_LIST + composeTestRule.activity.resources.getString(
SupportedPaymentMethod.Eps.displayNameResource
)
)
private val paymentMethodList
get() = composeTestRule.onNodeWithTag(TEST_TAG_LIST)
}
| 64
|
Kotlin
|
522
| 935
|
bec4fc5f45b5401a98a310f7ebe5d383693936ea
| 5,937
|
stripe-android
|
MIT License
|
src/main/kotlin/com/github/darderion/mundaneassignmentpolice/checker/rule/section/SectionSizeRule.kt
|
Darderion
| 410,550,044
| false
|
{"Kotlin": 207843, "HTML": 185970, "TypeScript": 52959, "CSS": 7720, "Shell": 2338, "Python": 1435, "Dockerfile": 541}
|
package com.github.darderion.mundaneassignmentpolice.checker.rule.section
import com.github.darderion.mundaneassignmentpolice.checker.ComparisonType
import com.github.darderion.mundaneassignmentpolice.checker.RuleViolation
import com.github.darderion.mundaneassignmentpolice.checker.RuleViolationType
import com.github.darderion.mundaneassignmentpolice.checker.SectionName
import com.github.darderion.mundaneassignmentpolice.checker.SectionName.BIBLIOGRAPHY
import com.github.darderion.mundaneassignmentpolice.checker.rule.Rule
import com.github.darderion.mundaneassignmentpolice.pdfdocument.PDFArea
import com.github.darderion.mundaneassignmentpolice.pdfdocument.PDFDocument
import com.github.darderion.mundaneassignmentpolice.pdfdocument.PDFRegion
import com.github.darderion.mundaneassignmentpolice.statisticsservice.statistics.StatisticsBuilder
import com.github.darderion.mundaneassignmentpolice.utils.floatEquals
class SectionSizeRule(
name: String,
type: RuleViolationType,
val sections: List<SectionName>,
val comparisonType: ComparisonType,
val pageLimit: Int?,
val percentageLimit: Number?
) : Rule(PDFRegion.EVERYWHERE, name, type) {
init {
if (pageLimit == null && percentageLimit == null) throw Exception("Size limit was not specified")
}
override fun process(document: PDFDocument): List<RuleViolation> {
val statisticsBuilder = StatisticsBuilder()
val ruleViolations = mutableListOf<RuleViolation>()
if (sections.contains(BIBLIOGRAPHY)) {
val bibliographyStatistics = statisticsBuilder.getBibliographyStatistics(document)
if (isLimitViolated(bibliographyStatistics.areaSizeInPage, bibliographyStatistics.areaSizeInPercents)) {
val titleLine = document.text.first { it.area == PDFArea.BIBLIOGRAPHY }
ruleViolations.add(RuleViolation(listOf(titleLine), name, type))
}
}
val sectionsStatistic = statisticsBuilder.getSectionsStatistics(document).map { statistics ->
statistics to SectionName.getByTitle(statistics.section.title)
}.filter { sections.contains(it.second) }.map { it.first }
sectionsStatistic.forEach { statistics ->
if (isLimitViolated(statistics.areaSizeInPage, statistics.areaSizeInPercents)) {
val titleLines = document.getLines(statistics.section.titleIndex, statistics.section.contentIndex - 1)
ruleViolations.add(RuleViolation(titleLines, name, type))
}
}
return ruleViolations
}
private fun isLimitViolated(sectionSize: Int, sectionPercentage: Float): Boolean {
var isViolatedPageLimit = false
var isViolatedPercentageLimit = false
pageLimit?.let { limit -> isViolatedPageLimit = !comparisonType.compare(sectionSize, limit) }
percentageLimit?.let { limit ->
isViolatedPercentageLimit = !comparisonType.compare(sectionPercentage, limit.toFloat(), ::floatEquals)
}
return isViolatedPageLimit || isViolatedPercentageLimit
}
}
| 7
|
Kotlin
|
7
| 14
|
57c28f157c40d752da6ebe89a41e6bc0b0137ae1
| 3,090
|
map
|
MIT License
|
src/main/kotlin/com/github/kotlin_di/common/plugins/KeyDefinition.kt
|
Kotlin-DI
| 458,728,871
| false
| null |
package com.github.kotlin_di.common.plugins
import com.github.kotlin_di.common.types.Key
interface KeyDefinition {
val version: String
fun keys(): List<Key<*, *>>
}
| 0
|
Kotlin
|
0
| 0
|
63c912e1d75e3aa649ebc97db5d564ac9093dc77
| 176
|
common
|
MIT License
|
src/main/kotlin/com/myworld/schat/data/repository/ChatGroupPhotoRepository.kt
|
bellmit
| 463,833,836
| false
| null |
package com.myworld.schat.data.repository
import com.myworld.schat.data.entity.ChatGroupPhoto
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional
@Transactional
@Repository
interface ChatGroupPhotoRepository : JpaRepository<ChatGroupPhoto, String>
| 0
| null |
0
| 0
|
581532fb1253f0c4cd6b5a8d83f3e3f1c39a7d65
| 372
|
schatsql
|
MIT License
|
app/src/main/java/com/example/yemekuygulamasi/data/entitiy/YemekCevap.kt
|
muhammedsametakgul
| 628,969,772
| false
| null |
package com.example.yemekuygulamasi.data.entitiy
data class YemekCevap(var yemekler : List<Yemekler>,var success:Int)
| 0
|
Kotlin
|
0
| 5
|
1856a252748f32d66586288166ff69b3915a8bf0
| 119
|
Food_Order_App
|
MIT License
|
src/main/kotlin/com/github/cnrture/quickprojectwizard/xmlarch/ui/EmptyMainFragment.kt
|
cnrture
| 849,704,826
| false
|
{"Kotlin": 138780}
|
package com.github.cnrture.quickprojectwizard.xmlarch.ui
fun emptyMainFragment(packageName: String, screen: String, isHiltEnable: Boolean): String {
return if (isHiltEnable) {
hilt(packageName, screen)
} else {
withoutHilt(packageName, screen)
}
}
private fun hilt(packageName: String, screen: String) = """
package $packageName.ui.${screen.lowercase()}
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import $packageName.common.collect
import $packageName.databinding.Fragment${screen}Binding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ${screen}Fragment : Fragment() {
private var _binding: Fragment${screen}Binding? = null
private val binding get() = _binding!!
private val viewModel by viewModels<${screen}ViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = Fragment${screen}Binding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(binding) {}
collectState()
}
private fun collectState() {
with(binding) {
viewModel.uiState.collect(viewLifecycleOwner) { state ->
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
"""
private fun withoutHilt(packageName: String, screen: String) = """
package $packageName.ui.${screen.lowercase()}
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import $packageName.common.collect
import $packageName.databinding.Fragment${screen}Binding
class ${screen}Fragment : Fragment() {
private var _binding: Fragment${screen}Binding? = null
private val binding get() = _binding!!
private val viewModel by viewModels<${screen}ViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = Fragment${screen}Binding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(binding) {}
collectState()
}
private fun collectState() {
with(binding) {
viewModel.uiState.collect(viewLifecycleOwner) { state ->
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
"""
| 2
|
Kotlin
|
2
| 32
|
f52310e5738c0974bf5e6b3e5c51c5b0070d2316
| 2,960
|
QuickProjectWizard
|
Apache License 2.0
|
app/src/main/kotlin/com/dmko/bulldogvods/di/modules/NetworkModule.kt
|
dmitrykochanov
| 477,314,891
| false
| null |
package com.dmko.bulldogvods.di.modules
import com.apollographql.apollo3.ApolloClient
import com.dmko.bulldogvods.app.common.network.ApolloClientFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {
@Provides
@Singleton
fun provideApolloClient(apolloClientFactory: ApolloClientFactory): ApolloClient {
return apolloClientFactory.createApolloClient()
}
}
| 0
|
Kotlin
|
0
| 1
|
0aa6ec12113a0366c81c236cc6288e72ed15798c
| 555
|
BulldogVods
|
MIT License
|
idea/testData/quickfix/modifiers/suspend/public.kt
|
JakeWharton
| 99,388,807
| false
| null |
// "Make bar suspend" "true"
suspend fun foo() {}
public fun bar() {
<caret>foo()
}
// FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.AddSuspendModifierFix
| 1
| null |
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 167
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/kardia/membership/domain/api/TwitterAPI.kt
|
trungthaihieu93-dev
| 359,315,080
| false
| null |
package com.kardia.membership.domain.api
import com.kardia.membership.domain.entities.news.LatestNewsEntity
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Headers
internal interface TwitterAPI {
companion object {
private const val GET_LATEST_NEW = "1.1/search/tweets.json?q=from:kardiachain%20AND%20-filter:retweets%20AND%20-filter:replies&count=20&result_type=recent&tweet_mode=extended"
}
@GET(GET_LATEST_NEW)
@Headers("No-Authentication: true",
"Authorization: Bearer AAAAAAAAAAAAAAAAAAAAAMHMNwEAAAAATHxIoEgKUYhdcjDBnVGJIpgPL54%3Dane0BGzcZ6gJjEYChdCayhs4wKN1KEgwZRGPM44HOxMOz32Kli")
fun getLatestNews(): Call<LatestNewsEntity>
}
| 0
| null |
0
| 0
|
00e51171479e259edbccf36ee155dc8e4489e40f
| 696
|
kai-membership-kotlin
|
MIT License
|
platform/testFramework/core/src/com/intellij/platform/testFramework/core/FileComparisonFailedError.kt
|
JetBrains
| 2,489,216
| false
| null |
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.platform.testFramework.core
import com.intellij.rt.execution.junit.FileComparisonData
import org.opentest4j.AssertionFailedError
import org.opentest4j.FileInfo
import org.opentest4j.ValueWrapper
import java.io.File
import java.nio.charset.StandardCharsets
class FileComparisonFailedError @JvmOverloads constructor(
message: String?,
expected: String,
actual: String,
expectedFilePath: String? = null,
actualFilePath: String? = null
) : AssertionFailedError(
message,
createFileInfo(expected, expectedFilePath),
createFileInfo(actual, actualFilePath)
), FileComparisonData {
init {
require(expectedFilePath == null || File(expectedFilePath).isFile) {
"'expectedFilePath' should point to the existing file or be null"
}
require(actualFilePath == null || File(actualFilePath).isFile) {
"'actualFilePath' should point to the existing file or be null"
}
}
override fun getFilePath(): String? {
return getFilePath(expected)
}
override fun getActualFilePath(): String? {
return getFilePath(actual)
}
override fun getActualStringPresentation(): String {
return getFileText(actual)
}
override fun getExpectedStringPresentation(): String {
return getFileText(expected)
}
companion object {
private val CONTENT_CHARSET = StandardCharsets.UTF_8
private fun createFileInfo(text: String, path: String?): ValueWrapper {
val contents = text.toByteArray(CONTENT_CHARSET)
if (path != null) {
val fileInfo = FileInfo(path, contents)
return ValueWrapper.create(fileInfo)
}
return ValueWrapper.create(text)
}
private fun getFileText(valueWrapper: ValueWrapper): String {
val value: Any = valueWrapper.value
if (value is FileInfo) {
return value.getContentsAsString(CONTENT_CHARSET)
}
return value as String
}
private fun getFilePath(valueWrapper: ValueWrapper): String? {
val value: Any = valueWrapper.value
if (value is FileInfo) {
return value.path
}
return null
}
}
}
| 284
| null |
5162
| 16,707
|
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
| 2,219
|
intellij-community
|
Apache License 2.0
|
libs/messaging/messaging-impl/src/test/kotlin/net/corda/messaging/subscription/consumer/listener/OffsetProviderListenerTest.kt
|
corda
| 346,070,752
| false
|
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
|
package net.corda.messaging.subscription.consumer.listener
import net.corda.messagebus.api.CordaTopicPartition
import net.corda.messagebus.api.consumer.CordaConsumer
import net.corda.messaging.api.exception.CordaMessageAPIFatalException
import net.corda.messaging.api.subscription.listener.ConsumerOffsetProvider
import net.corda.messaging.api.subscription.listener.PartitionAssignmentListener
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.mockito.Mockito.mock
import org.mockito.kotlin.any
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoInteractions
import org.mockito.kotlin.whenever
class OffsetProviderListenerTest {
private val clientId = "c1"
private val partitionAssignmentListener = mock<PartitionAssignmentListener>()
private val offsetProvider = mock<ConsumerOffsetProvider>().apply {
whenever(getStartingOffsets(any())).thenReturn(
mapOf("t" to 2 to 200, "t" to 1 to 100)
)
}
private val consumer = mock<CordaConsumer<*, *>>()
private val partition1 = CordaTopicPartition("t", 1)
private val partition2 = CordaTopicPartition("t", 2)
private val topicPartitions = listOf(partition1, partition2)
/**
* Given no partition assignment listener is specified
* And no offset provider is specified
* When partitions revoked
* Then nothing happens
*/
@Test
fun `partitions revoked - no lister set - no provider set`() {
OffsetProviderListener(clientId, null, null, consumer)
.onPartitionsRevoked(topicPartitions)
}
/**
* Given partition assignment listener is specified
* And no offset provider is specified
* When partitions revoked
* Then nothing happens
*/
@Test
fun `partitions revoked - lister set - no provider set`() {
OffsetProviderListener(clientId, partitionAssignmentListener, null, consumer)
.onPartitionsRevoked(topicPartitions)
verify(partitionAssignmentListener).onPartitionsUnassigned(listOf("t" to 1, "t" to 2))
}
/**
* Given partition assignment listener is specified
* And offset provider is specified
* When partitions revoked
* Then nothing happens
*/
@Test
fun `partitions revoked - lister set - provider set`() {
OffsetProviderListener(clientId, partitionAssignmentListener, offsetProvider, consumer)
.onPartitionsRevoked(topicPartitions)
verify(partitionAssignmentListener).onPartitionsUnassigned(listOf("t" to 1, "t" to 2))
verifyNoInteractions(offsetProvider)
}
/**
* Given no partition assignment listener is specified
* And offset provider is specified
* When partitions revoked
* Then nothing happens
*/
@Test
fun `partitions revoked - no lister set - provider set`() {
OffsetProviderListener(clientId, null, offsetProvider, consumer)
.onPartitionsRevoked(topicPartitions)
verifyNoInteractions(offsetProvider)
}
/**
* Given no partition assignment listener is specified
* And no offset provider is specified
* When partitions revoked
* Then nothing happens
*/
@Test
fun `partitions assigned - no lister set - no provider set`() {
OffsetProviderListener(clientId, null, null, consumer)
.onPartitionsAssigned(topicPartitions)
}
/**
* Given partition assignment listener is specified
* And no offset provider is specified
* When partitions revoked
* Then call assigned on listener
*/
@Test
fun `partitions assigned - lister set - no provider set`() {
OffsetProviderListener(clientId, partitionAssignmentListener, null, consumer)
.onPartitionsAssigned(topicPartitions)
verify(partitionAssignmentListener).onPartitionsAssigned(listOf("t" to 1, "t" to 2))
}
/**
* Given partition assignment listener is specified
* And offset provider is specified
* When partitions revoked
* Then call assigned on listener
* And reset offsets to provider offsets
*/
@Test
fun `partitions assigned - lister set - provider set`() {
OffsetProviderListener(clientId, partitionAssignmentListener, offsetProvider, consumer)
.onPartitionsAssigned(topicPartitions)
verify(partitionAssignmentListener).onPartitionsAssigned(listOf("t" to 1, "t" to 2))
verify(consumer).seek(partition1, 100)
verify(consumer).seek(partition2, 200)
}
/**
* Given no partition assignment listener is specified
* And offset provider is specified
* When partitions assigned
* Then reset offsets to provider offsets
*/
@Test
fun `partitions assigned - no lister set - provider set`() {
OffsetProviderListener(clientId, null, offsetProvider, consumer)
.onPartitionsAssigned(topicPartitions)
verifyNoInteractions(partitionAssignmentListener)
verify(consumer).seek(partition1, 100)
verify(consumer).seek(partition2, 200)
}
/**
* Given no partition assignment listener is specified
* And offset provider is specified
* When partitions assigned
* And provider fails to return offsets for all partitions
* Then throw a fatal exception
*/
@Test
fun `partitions assigned - no lister set - provider set - invalid offsets`() {
val partition3 = CordaTopicPartition("t", 3)
assertThrows<CordaMessageAPIFatalException> {
OffsetProviderListener(clientId, null, offsetProvider, consumer)
.onPartitionsAssigned(listOf(partition1, partition2, partition3))
}
}
}
| 14
|
Kotlin
|
27
| 69
|
0766222eb6284c01ba321633e12b70f1a93ca04e
| 5,732
|
corda-runtime-os
|
Apache License 2.0
|
helm-plugin/src/test/kotlin/org/unbrokendome/gradle/plugins/helm/testutil/exec/ExecutableGradleExecMock.kt
|
unbroken-dome
| 145,379,286
| false
|
{"Kotlin": 525796}
|
package com.citi.gradle.plugins.helm.testutil.exec
import com.citi.gradle.plugins.helm.testutil.startsWith
import java.io.File
import java.io.PrintWriter
/**
* Implementation of [GradleExecMock] based on a script file that is used in place of the "real" helm executable.
* The script forwards the arguments and environment of the process to a local server, which records them for later
* verification.
*
* The reason for this roundabout way of checking the exec invocations is that it is next to impossible to inject
* a mocked version of a service (e.g. `ExecOperations` or `ProcessOperations`) into Gradle's service registry,
* especially when the worker API is used.
*/
interface ExecutableGradleExecMock : GradleExecMock, AutoCloseable {
/**
* Starts recording of invocations.
*
* Behaviors may still be added after this.
*/
fun start()
/**
* Resets the mock, erasing all recorded invocations and clearing all behaviors.
*/
fun reset()
/**
* Creates a script file that can be used instead of the "real" executable.
*/
fun createScriptFile(scriptLocation: File)
}
class DefaultExecutableGradleExecMock : ExecutableGradleExecMock {
private class Behavior(
val argsPrefix: List<String>,
val block: GradleExecBehaviorBuilder.() -> Unit
)
private val behaviors = mutableListOf<Behavior>()
private val allInvocations = mutableListOf<Invocation>()
private var registration: ExecMockServer.MockRegistration? = null
private val callback = object : ExecMockServer.Callback {
override fun invocation(invocation: Invocation, stdoutWriter: PrintWriter) {
allInvocations.add(invocation)
val behaviorBuilder = object : GradleExecBehaviorBuilder {
override fun printsOnStdout(block: (PrintWriter) -> Unit) {
block(stdoutWriter)
}
}
for (behavior in behaviors) {
if (invocation.args.startsWith(behavior.argsPrefix)) {
behavior.block(behaviorBuilder)
break
}
}
}
}
override fun start() {
registration = execMockServer.registerMock(callback)
}
override fun reset() {
behaviors.clear()
allInvocations.clear()
}
override fun createScriptFile(scriptLocation: File) {
val reg = checkNotNull(registration) { "ExecMock must be started before the script file is available." }
scriptLocation.parentFile.mkdirs()
scriptLocation.writeText(reg.getShellScript())
scriptLocation.setExecutable(true)
}
override fun close() {
val reg = registration
registration = null
reg?.unregister()
}
override fun forCommand(argsPrefix: List<String>): GradleExecMock =
Prefixed(argsPrefix)
override fun everyExec(block: GradleExecBehaviorBuilder.() -> Unit) {
behaviors.add(Behavior(emptyList(), block))
}
override val invocations: List<Invocation>
get() = allInvocations
private inner class Prefixed(
val prefix: List<String>
) : GradleExecMock {
override fun forCommand(argsPrefix: List<String>): GradleExecMock =
Prefixed(this.prefix + argsPrefix)
override fun everyExec(block: GradleExecBehaviorBuilder.() -> Unit) {
behaviors.add(Behavior(prefix, block))
}
override val invocations: List<Invocation>
get() = allInvocations.filter { it.args.startsWith(prefix) }
override fun toString(): String = buildString {
val invocations = invocations
append("GradleExecMock for prefix: $prefix")
if (invocations.isEmpty()) {
append(" (no recorded invocations)")
} else {
appendLine()
appendLine(" Recorded invocations (${invocations.size}):")
appendLine(formatInvocations(invocations))
}
val otherInvocations = allInvocations - invocations
if (otherInvocations.isNotEmpty()) {
appendLine(" Other invocations (${otherInvocations.size}):")
appendLine(formatInvocations(otherInvocations))
}
}
}
private fun formatInvocations(invocations: List<Invocation>) =
invocations.joinToString(separator = "\n") { " - ${it.args}"}
}
| 21
|
Kotlin
|
50
| 51
|
c0d74916bad3c3a441666c4b076245defef91944
| 4,496
|
gradle-helm-plugin
|
MIT License
|
app/src/main/java/com/example/googlemapsapplication/data/responses/LoginResponse.kt
|
yogoh31
| 460,571,160
| false
| null |
package com.example.googlemapsapplication.data.responses
import com.example.googlemapsapplication.data.models.User
import com.google.gson.annotations.SerializedName
data class LoginResponse (
@SerializedName("code")
var statusCode: Int,
@SerializedName("access")
var authToken: String,
@SerializedName("user")
var user: User?
)
| 0
|
Kotlin
|
0
| 0
|
bffbf615499d3e4788f5e1ebf56ab4a585771408
| 355
|
Repath-App-Mobile-Kotlin
|
MIT License
|
idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/MoveKotlinTopLevelDeclarationsModel.kt
|
Ndex471
| 236,524,761
| false
| null |
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.options.ConfigurationException
import com.intellij.psi.*
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.MoveDestination
import com.intellij.refactoring.PackageWrapper
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.moveClassesOrPackages.AutocreatingSingleSourceRootMoveDestination
import com.intellij.refactoring.move.moveClassesOrPackages.MultipleRootsMoveDestination
import com.intellij.util.IncorrectOperationException
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringBundle
import org.jetbrains.kotlin.idea.refactoring.getOrCreateKotlinFile
import org.jetbrains.kotlin.idea.refactoring.move.getOrCreateDirectory
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.*
import org.jetbrains.kotlin.idea.refactoring.move.updatePackageDirective
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import java.io.File
import java.nio.file.InvalidPathException
import java.nio.file.Paths
internal class MoveKotlinTopLevelDeclarationsModel(
val project: Project,
val elementsToMove: List<KtNamedDeclaration>,
val targetPackage: String,
val selectedPsiDirectory: PsiDirectory?,
val fileNameInPackage: String,
val targetFilePath: String,
val isMoveToPackage: Boolean,
val isSearchReferences: Boolean,
val isSearchInComments: Boolean,
val isSearchInNonJavaFiles: Boolean,
val isDeleteEmptyFiles: Boolean,
val isUpdatePackageDirective: Boolean,
val isFullFileMove: Boolean,
val moveCallback: MoveCallback?
) : Model<BaseRefactoringProcessor> {
private inline fun <T, K> List<T>.mapToSingleOrNull(transform: (T) -> K?): K? =
mapTo(mutableSetOf(), transform).singleOrNull()
private val sourceDirectory by lazy {
sourceFiles.mapToSingleOrNull { it.parent } ?: throw ConfigurationException("Can't determine sources directory")
}
private val sourceFiles = elementsToMove.map { it.containingKtFile }.distinct()
private data class TargetDirAndDestination(val targetDir: VirtualFile?, val destination: MoveDestination)
private fun selectPackageBasedTargetDirAndDestination(): TargetDirAndDestination {
val targetPackageWrapper = PackageWrapper(PsiManager.getInstance(project), targetPackage)
return if (selectedPsiDirectory == null)
TargetDirAndDestination(null, MultipleRootsMoveDestination(targetPackageWrapper))
else {
TargetDirAndDestination(
selectedPsiDirectory.virtualFile,
AutocreatingSingleSourceRootMoveDestination(targetPackageWrapper, selectedPsiDirectory.virtualFile)
)
}
}
private fun checkTargetFileName(fileName: String) {
if (FileTypeManager.getInstance().getFileTypeByFileName(fileName) != KotlinFileType.INSTANCE) {
throw ConfigurationException(KotlinRefactoringBundle.message("refactoring.move.non.kotlin.file"))
}
}
private fun getFilesExistingInTargetDir(
targetFileName: String?,
targetDirectory: PsiDirectory
): Set<PsiFile> {
return if (targetFileName != null) {
targetDirectory.findFile(targetFileName)?.let { setOf(it) }.orEmpty()
} else {
sourceFiles.mapNotNullTo(mutableSetOf()) { targetDirectory.findFile(it.name) }
}
}
private fun selectMoveTargetToPackage(): KotlinMoveTarget {
require(sourceFiles.isNotEmpty())
val (targetDir, moveDestination) = selectPackageBasedTargetDirAndDestination()
val targetDirectory = moveDestination.getTargetIfExists(sourceDirectory)
?: throw ConfigurationException("Can't get target directory for selected package")
val destination = sourceFiles
.mapToSingleOrNull { moveDestination.getTargetIfExists(it) }
?: throw ConfigurationException("Can't get target for all source elements")
val singleSourceFileMode = sourceFiles.size == 1
val targetFileName = if (singleSourceFileMode) fileNameInPackage.also(::checkTargetFileName) else null
val filesExistingInTargetDir = getFilesExistingInTargetDir(targetFileName, targetDirectory)
if (filesExistingInTargetDir.isNotEmpty()) {
if (singleSourceFileMode) {
val singeTargetFile = filesExistingInTargetDir.single() as? KtFile
if (singeTargetFile != null) {
return KotlinMoveTargetForExistingElement(singeTargetFile)
}
} else {
val filePathsToReport = filesExistingInTargetDir.joinToString(
separator = "\n",
prefix = "Cannot perform refactoring since the following files already exist:\n\n"
) { it.virtualFile.path }
throw ConfigurationException(filePathsToReport)
}
}
return KotlinMoveTargetForDeferredFile(
FqName(targetPackage),
destination,
targetDir
) {
val deferredFileName = if (singleSourceFileMode) fileNameInPackage else it.name
val deferredFileDirectory = moveDestination.getTargetDirectory(it)
getOrCreateKotlinFile(deferredFileName, deferredFileDirectory)
}
}
private fun selectMoveTargetToFile(): KotlinMoveTarget {
try {
Paths.get(targetFilePath)
} catch (e: InvalidPathException) {
throw ConfigurationException("Invalid target path $targetFilePath")
}
val targetFile = File(targetFilePath)
checkTargetFileName(targetFile.name)
val jetFile = targetFile.toPsiFile(project) as? KtFile
if (jetFile != null) {
if (sourceFiles.size == 1 && sourceFiles.contains(jetFile)) {
throw ConfigurationException("Can't move to the original file")
}
return KotlinMoveTargetForExistingElement(jetFile)
}
val targetDirPath = targetFile.toPath().parent
?: throw ConfigurationException("Incorrect target path. Directory is not specified.")
val projectBasePath = project.basePath
?: throw ConfigurationException("Can't move for current project")
if (!targetDirPath.startsWith(projectBasePath)) {
throw ConfigurationException("Incorrect target path. Directory $targetDirPath does not belong to current project.")
}
val absoluteTargetDirPath = targetDirPath.toString()
val psiDirectory: PsiDirectory
try {
psiDirectory = getOrCreateDirectory(absoluteTargetDirPath, project)
} catch (e: IncorrectOperationException) {
throw ConfigurationException("Failed to create parent directory: $absoluteTargetDirPath")
}
val targetPackageFqName = sourceFiles.singleOrNull()?.packageFqName
?: JavaDirectoryService.getInstance().getPackage(psiDirectory)?.let { FqName(it.qualifiedName) }
?: throw ConfigurationException("Could not find package corresponding to $absoluteTargetDirPath")
val finalTargetPackageFqName = targetPackageFqName.asString()
return KotlinMoveTargetForDeferredFile(
targetPackageFqName,
psiDirectory,
targetFile = null
) { getOrCreateKotlinFile(targetFile.name, psiDirectory, finalTargetPackageFqName) }
}
private fun selectMoveTarget() =
if (isMoveToPackage) selectMoveTargetToPackage() else selectMoveTargetToFile()
private fun verifyBeforeRun() {
if (elementsToMove.isEmpty()) throw ConfigurationException("At least one member must be selected")
if (sourceFiles.isEmpty()) throw ConfigurationException("None elements were selected")
if (sourceFiles.size == 1 && fileNameInPackage.isBlank()) throw ConfigurationException("File name may not be empty")
if (isMoveToPackage) {
if (targetPackage.isNotEmpty() && !PsiNameHelper.getInstance(project).isQualifiedName(targetPackage)) {
throw ConfigurationException("\'$targetPackage\' is invalid destination package name")
}
} else {
val targetFile = File(targetFilePath).toPsiFile(project)
if (targetFile != null && targetFile !is KtFile) {
throw ConfigurationException(KotlinRefactoringBundle.message("refactoring.move.non.kotlin.file"))
}
}
}
@Throws(ConfigurationException::class)
override fun computeModelResult() = computeModelResult(throwOnConflicts = false)
@Throws(ConfigurationException::class)
override fun computeModelResult(throwOnConflicts: Boolean): BaseRefactoringProcessor {
verifyBeforeRun()
if (isFullFileMove && isMoveToPackage) {
tryMoveFile(throwOnConflicts)?.let { return it }
}
return moveDeclaration(throwOnConflicts)
}
private fun tryMoveFile(throwOnConflicts: Boolean): BaseRefactoringProcessor? {
val targetFileName = if (sourceFiles.size > 1) null else fileNameInPackage
if (targetFileName != null) checkTargetFileName(targetFileName)
val moveDestination = selectPackageBasedTargetDirAndDestination().destination
val targetDir = moveDestination.getTargetIfExists(sourceDirectory) ?: return null
val filesExistingInTargetDir = getFilesExistingInTargetDir(targetFileName, targetDir)
val moveAsFile = filesExistingInTargetDir.isEmpty() ||
filesExistingInTargetDir.singleOrNull()?.let { sourceFiles.contains(it) } == true
if (!moveAsFile) return null
val targetDirectory = project.executeCommand(RefactoringBundle.message("move.title"), null) {
runWriteAction<PsiDirectory> { moveDestination.getTargetDirectory(sourceDirectory) }
}
sourceFiles.forEach { it.updatePackageDirective = isUpdatePackageDirective }
return if (targetFileName != null)
MoveToKotlinFileProcessor(
project,
sourceFiles.first(),
targetDirectory,
targetFileName,
searchInComments = isSearchInComments,
searchInNonJavaFiles = isSearchInNonJavaFiles,
moveCallback = moveCallback,
throwOnConflicts = throwOnConflicts
)
else
KotlinAwareMoveFilesOrDirectoriesProcessor(
project,
sourceFiles,
targetDirectory,
isSearchReferences,
searchInComments = isSearchInComments,
searchInNonJavaFiles = isSearchInNonJavaFiles,
moveCallback = moveCallback,
throwOnConflicts = throwOnConflicts
)
}
private fun moveDeclaration(throwOnConflicts: Boolean): BaseRefactoringProcessor {
val target = selectMoveTarget()
for (element in elementsToMove) {
target.verify(element.containingFile)?.let { throw ConfigurationException(it) }
}
val options = MoveDeclarationsDescriptor(
project,
MoveSource(elementsToMove),
target,
MoveDeclarationsDelegate.TopLevel,
isSearchInComments,
isSearchInNonJavaFiles,
deleteSourceFiles = isFullFileMove && isDeleteEmptyFiles,
moveCallback = moveCallback,
openInEditor = false,
allElementsToMove = null,
analyzeConflicts = true,
searchReferences = isSearchReferences
)
return MoveKotlinDeclarationsProcessor(options, Mover.Default, throwOnConflicts)
}
}
| 0
| null |
0
| 1
|
f7626d6474bff5fceba8506c37480e8918bd11cf
| 12,514
|
kotlin
|
Apache License 2.0
|
src/webapp/Home.kt
|
AlexandreBrown
| 249,043,377
| false
| null |
package com.raywenderlich.webapp
import com.raywenderlich.models.EPSession
import com.raywenderlich.repositories.Repository
import io.ktor.application.call
import io.ktor.freemarker.FreeMarkerContent
import io.ktor.locations.KtorExperimentalLocationsAPI
import io.ktor.locations.Location
import io.ktor.locations.get
import io.ktor.response.respond
import io.ktor.routing.Route
import io.ktor.sessions.get
import io.ktor.sessions.sessions
const val HOME = "/"
@KtorExperimentalLocationsAPI
@Location(HOME)
class Home
@KtorExperimentalLocationsAPI
fun Route.home(db: Repository) {
get<Home> {
val user = call.sessions.get<EPSession>()?.let { db.user(it.userId) }
call.respond(FreeMarkerContent("home.ftl", mapOf(
"user" to user
)))
}
}
| 0
|
Kotlin
|
0
| 0
|
280d8e08e62e3a6e54d3bc5704612de1c68cb186
| 785
|
EmojiPhrases
|
MIT License
|
app/src/main/java/com/surrus/peopleinspace/di/NetworkModule.kt
|
Shivamdhuria
| 461,997,397
| false
|
{"Kotlin": 58108, "Swift": 13249, "Ruby": 1899}
|
package com.surrus.peopleinspace.di
import com.surrus.common.network.DogService
import com.surrus.common.network.DogServiceImpl
import com.surrus.common.network.models.DogDtoMapper
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Singleton
@Provides
fun provideRecipeService(): DogService {
return DogServiceImpl()
}
@Singleton
@Provides
fun provideRecipeMapper(): DogDtoMapper {
return DogDtoMapper()
}
}
| 0
|
Kotlin
|
0
| 1
|
88cea78b5307221233caae8fdf6a29b31908c6ec
| 633
|
kotlinMp
|
Apache License 2.0
|
core/src/main/java/com/redpine/core/base/BaseViewModel.kt
|
maiow
| 600,207,272
| false
|
{"Kotlin": 188157}
|
package com.redpine.core.base
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.FirebaseNetworkException
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.redpine.core.state.LoadState
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
abstract class BaseViewModel : ViewModel() {
protected val _loadState = MutableStateFlow(LoadState.START)
val loadState = _loadState.asStateFlow()
protected val handler = CoroutineExceptionHandler { _, e ->
Log.e("Kart", "${e.message} ${e}")
_loadState.value = when (e) {
is FirebaseAuthInvalidCredentialsException -> LoadState.ERROR_AUTH
is FirebaseBaseExceptionNullResponse -> LoadState.NULL_RESPONSE
is FirebaseSearchExceptionNullResponse -> LoadState.NULL_SEARCH
else -> LoadState.ERROR_NETWORK
}
}
protected fun scopeLaunch(
context: CoroutineContext = Dispatchers.IO + handler,
startLoadingState: LoadState = LoadState.LOADING,
endLoadingState: LoadState = LoadState.SUCCESS,
block: suspend () -> Unit,
) {
viewModelScope.launch(context) {
_loadState.value = startLoadingState
block()
_loadState.value = endLoadingState
}
}
}
class FirebaseBaseExceptionNullResponse(
val errorMessage: String = "Null Response"
) : FirebaseNetworkException(errorMessage)
class FirebaseSearchExceptionNullResponse(
val errorMessage: String = "Null Response"
) : FirebaseNetworkException(errorMessage)
| 36
|
Kotlin
|
1
| 5
|
a5a4344c45c22e20dec25d319201174ed0e6c158
| 1,837
|
dog-shelter
|
MIT License
|
adoptopenjdk-api-v3-persistance/src/main/kotlin/net/adoptopenjdk/api/v3/dataSources/persitence/mongo/MongoClient.kt
|
jerboaa
| 236,009,857
| true
|
{"Kotlin": 255110, "CSS": 992, "HTML": 988, "Shell": 948}
|
package net.adoptopenjdk.api.v3.dataSources.persitence.mongo
import org.litote.kmongo.coroutine.CoroutineClient
import org.litote.kmongo.coroutine.CoroutineDatabase
import org.litote.kmongo.coroutine.coroutine
import org.litote.kmongo.reactivestreams.KMongo
import org.slf4j.LoggerFactory
object MongoClientFactory {
// Current default impl is mongo impl
private var impl: MongoClient? = null
fun get(): MongoClient {
if (impl == null) {
impl = MongoClient()
}
return impl!!
}
fun set(impl: MongoClient?) {
MongoClientFactory.impl = impl
}
}
class MongoClient {
val database: CoroutineDatabase
val client: CoroutineClient
companion object {
@JvmStatic
private val LOGGER = LoggerFactory.getLogger(this::class.java)
}
init {
val dbName = System.getenv("MONGODB_DBNAME") ?: "api-data"
val username = System.getenv("MONGODB_USER")
val password = System.getenv("MONGODB_PASSWORD")
val host = System.getenv("MONGODB_HOST") ?: "localhost"
val port = System.getenv("MONGODB_PORT") ?: "27017"
LOGGER.info("Connecting to mongodb://${username}:a-password@${host}:${port}/${dbName}")
var uri = if (username != null && password != null) {
"mongodb://${username}:${password}@${host}:${port}/${dbName}"
} else {
"mongodb://${host}:${port}"
}
if (System.getProperty("MONGO_DB") != null) {
uri = System.getProperty("MONGO_DB")
}
client = KMongo.createClient(uri).coroutine
database = client.getDatabase(dbName)
}
}
| 0
| null |
0
| 0
|
1c14ff90d14f2900691993d6dbb2e9c7e2555df7
| 1,658
|
openjdk-api-v3
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.