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.jaychang.sac/demo/User.kt
|
jaychang0917
| 105,370,527
| false
| null |
package com.jaychang.sac.demo
import com.squareup.moshi.Json
data class User(
@Json(name = "login")
val name: String
)
| 6
|
Kotlin
|
15
| 145
|
45a688a6f4f1cc346fe534ecc348d54bb257977c
| 124
|
SimpleApiClient
|
Apache License 2.0
|
base/src/main/kotlin/com/hieunv/mvvmarch/base/db/DatabaseModule.kt
|
lvhieut
| 694,577,582
| false
|
{"Kotlin": 115915}
|
package com.hieunv.mvvmarch.base.db
import androidx.room.Room
import android.content.Context
import dagger.Module
import dagger.Provides
import com.hieunv.mvvmarch.base.db.user.UserDao
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Singleton
@Module
@InstallIn(ApplicationComponent::class)
class DatabaseModule {
@Provides
@Singleton
fun provideAppDatabase(@ApplicationContext application: Context): AppDatabase {
return Room.databaseBuilder(application, AppDatabase::class.java, "sample.db")
.allowMainThreadQueries()
.build()
}
@Provides
@Singleton
fun provideUserDao(db: AppDatabase): UserDao {
return db.userDao()
}
}
| 1
|
Kotlin
|
0
| 0
|
92b56b13990606a02c9a8d9f94ff15d1c37516b5
| 825
|
Base_mvvm_clone
|
MIT License
|
subprojects/gradle/gradle-logger/src/main/kotlin/com/avito/logger/formatter/AppendPrefixFormatter.kt
|
StanlyT
| 344,157,673
| true
|
{"Kotlin": 2773538, "HTML": 121161, "Shell": 17522, "Python": 14168, "Makefile": 7187, "Dockerfile": 7134}
|
package com.avito.logger.formatter
import com.avito.logger.LoggingFormatter
internal class AppendPrefixFormatter(
private val prefix: String
) : LoggingFormatter {
override fun format(message: String) = "[$prefix] $message"
}
| 0
|
Kotlin
|
0
| 0
|
96463f7714c0550e331d2a37fb32ad98fac9d62d
| 237
|
avito-android
|
MIT License
|
runner/src/main/kotlin/net/lachlanmckee/flankci/runner/presentation/TestRerunScreen.kt
|
LachlanMcKee
| 287,003,030
| false
| null |
package net.lachlanmckee.flankci.runner.presentation
import io.ktor.application.*
import kotlinx.html.*
import net.lachlanmckee.flankci.core.data.datasource.local.ConfigDataSource
import net.lachlanmckee.flankci.core.data.entity.ConfigurationId
import net.lachlanmckee.flankci.core.presentation.ErrorScreenFactory
import net.lachlanmckee.flankci.runner.domain.entity.RerunModel
import net.lachlanmckee.flankci.runner.domain.interactor.TestRerunInteractor
internal class TestRerunScreen(
private val configDataSource: ConfigDataSource,
private val errorScreenFactory: ErrorScreenFactory,
private val testRerunInteractor: TestRerunInteractor
) {
suspend fun respondHtml(call: ApplicationCall, configurationId: ConfigurationId, buildSlug: String) {
testRerunInteractor
.execute(configurationId, buildSlug)
.onSuccess {
val configuration = configDataSource.getConfig().configuration(configurationId)
TestRunnerScreenDelegate {
val options = configuration.testData.options
options.rerun ?: options.standard
}.respondHtml(call, configurationId, "${configuration.displayName} Test Rerun") {
addTestRerunOptions(it)
}
}
.onFailure { errorScreenFactory.respondHtml(call, "Failed to parse content", it.message!!) }
}
private fun HtmlBlockTag.addTestRerunOptions(rerunModel: RerunModel) {
input {
id = "defaultBranch"
name = "defaultBranch"
type = InputType.hidden
value = rerunModel.branch
}
input {
id = "isRerun"
name = "isRerun"
type = InputType.hidden
value = "true"
}
p {
id = "classes-heading"
classes = setOf("heading")
text("Classes")
}
div {
classes = setOf("test-runner-group", "classes", "data-list", "content")
fieldSet {
id = "classes-field-set"
rerunModel.failedTests.forEachIndexed { index, test ->
div {
input {
placeholder = "full_class$index"
type = InputType.checkBox
id = "full_class$index"
name = "full_class"
value = test
}
label {
htmlFor = "full_class$index"
text(test)
}
}
}
}
}
}
}
| 7
|
Kotlin
|
0
| 2
|
51c9bc50763443752010e576caf60ae9f8daabfd
| 2,314
|
FlankCI
|
MIT License
|
pickers-emoji/src/main/java/com/namtarr/reactionpickers/emoji/model/StaticCategories.kt
|
NamtarR
| 516,175,643
| false
| null |
package com.namtarr.reactionpickers.emoji.model
import com.namtarr.reactionpickers.core.model.Category
import com.namtarr.reactionpickers.emoji.R
object History: Category {
override val id = R.id.id_emoji_history.toLong()
override val title: String = ""
override val icon: Int = R.drawable.ic_emoji_people_faces
}
object People: Category {
override val id = R.id.id_emoji_people_faces.toLong()
override val title: String = ""
override val icon: Int = R.drawable.ic_emoji_people_faces
}
object Nature: Category {
override val id = R.id.id_emoji_animals_nature.toLong()
override val title: String = ""
override val icon: Int = R.drawable.ic_emoji_animals_nature
}
object Food: Category {
override val id = R.id.id_emoji_food_drink.toLong()
override val title: String = ""
override val icon: Int = R.drawable.ic_emoji_food_drink
}
object Activity: Category {
override val id = R.id.id_emoji_activity.toLong()
override val title: String = ""
override val icon: Int = R.drawable.ic_emoji_activity
}
object Travel: Category {
override val id = R.id.id_emoji_travel_places.toLong()
override val title: String = ""
override val icon: Int = R.drawable.ic_emoji_travel_places
}
object Objects: Category {
override val id = R.id.id_emoji_objects.toLong()
override val title: String = ""
override val icon: Int = R.drawable.ic_emoji_objects
}
object Symbols: Category {
override val id = R.id.id_emoji_symbols.toLong()
override val title: String = ""
override val icon: Int = R.drawable.ic_emoji_symbols
}
object Flags: Category {
override val id = R.id.id_emoji_flags.toLong()
override val title: String = ""
override val icon: Int = R.drawable.ic_emoji_flags
}
| 0
|
Kotlin
|
0
| 0
|
98dd90bf65290cca2dd95ab87dcc3a1a3b014e63
| 1,769
|
reaction-pickers
|
MIT License
|
common/src/main/kotlin/io/github/igloo_libraries/kotlin_extensions/IglooKotlinExtensions.kt
|
Igloo-Libraries
| 740,583,799
| false
|
{"Kotlin": 6808, "Java": 410}
|
package io.github.igloo_libraries.kotlin_extensions
object IglooKotlinExtensions {
}
| 0
|
Kotlin
|
0
| 2
|
3b772d3296c47e6b55ba42c413355e72216dc844
| 86
|
igloo-kotlin-extensions
|
Apache License 2.0
|
demo/src/main/java/de/check24/compose/demo/features/viewpager/ViewPagerAdapter.kt
|
check24-profis
| 469,706,312
| false
| null |
package de.check24.compose.demo.features.viewpager
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
internal class ViewPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {
override fun getItemCount(): Int = 5
override fun createFragment(position: Int): Fragment = ViewPagerFragment(position)
}
| 0
|
Kotlin
|
3
| 11
|
abd64a7d2edac0dbedb4d67d3c0f7b49d9173b88
| 434
|
jetpack-compose-is-like-android-view
|
MIT License
|
app/src/sharedTest/kotlin/com/alexvanyo/composelife/ui/ComposeLifeAppTests.kt
|
alexvanyo
| 375,146,193
| false
| null |
package com.alexvanyo.composelife.ui
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.performClick
import com.alexvanyo.composelife.R
import com.alexvanyo.composelife.test.BaseAndroidTest
import dagger.hilt.android.testing.BindValue
import dagger.hilt.android.testing.HiltAndroidTest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Rule
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
@HiltAndroidTest
class ComposeLifeAppTests : BaseAndroidTest() {
@get:Rule(order = 1)
val composeTestRule = createAndroidComposeRule<MainActivity>()
@BindValue
val fileProvider = preferencesRule.fileProvider
@Test
fun app_does_not_crash() = runTest {
composeTestRule.onNodeWithContentDescription(context.getString(R.string.pause)).performClick()
composeTestRule.awaitIdle()
}
@Test
fun app_does_not_crash_when_recreating() = runTest {
composeTestRule.onNodeWithContentDescription(context.getString(R.string.pause)).performClick()
composeTestRule.activityRule.scenario.recreate()
composeTestRule.awaitIdle()
}
}
| 7
|
Kotlin
|
0
| 3
|
d8410d3a4bef0d3e9dea5041aaa2b8250afc1eb4
| 1,268
|
composelife
|
Apache License 2.0
|
src/main/kotlin/com/bill/blog/dto/CommentDto.kt
|
xinqilin
| 392,696,045
| false
| null |
package com.bill.blog.dto
/**
* @author Bill.Lin on 2021/10/23
*/
data class CommentDto(
var commentId: Long? = null
) {}
| 0
|
Kotlin
|
0
| 0
|
aadf84bf1348fb347b4bc679294bc36de6181e51
| 132
|
kotlin-blog
|
MIT License
|
loginLibrary/src/main/java/com/github/mohamedwael/login/signup/SignUpFragment.kt
|
MohamedWael
| 270,424,052
| false
| null |
package com.github.mohamedwael.login.signup
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.github.mohamedwael.login.base.BaseLoginFragment
import com.github.mohamedwael.login.config.BROADCAST_ACTION_SUCCESS
import com.github.mohamedwael.login.databinding.SignUpFragmentBinding
class SignUpFragment : BaseLoginFragment() {
companion object {
fun newInstance() = SignUpFragment()
}
private lateinit var viewModel: SignUpViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewModel = createViewModel(SignUpViewModel::class.java, SignUpViewModelFactory)
observeHideKeyboardEvent(viewModel)
val binding = SignUpFragmentBinding.inflate(inflater, container, false)
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.onSignUpSuccessLiveData.observe(viewLifecycleOwner, Observer {
activity?.sendBroadcast(Intent(BROADCAST_ACTION_SUCCESS).putExtras(it))
})
}
}
| 0
|
Kotlin
|
0
| 1
|
ed50417bf60692efd15cebd29e6171a912580843
| 1,386
|
Login-library
|
MIT License
|
src/main/kotlin/com/github/cirry/wereadjetbrainsplugin/toolWindow/MyToolWindowFactory.kt
|
cirry
| 848,678,285
| false
|
{"Kotlin": 4847, "CSS": 814}
|
package com.github.cirry.wereadjetbrainsplugin.toolWindow
import com.github.cirry.wereadjetbrainsplugin.MyBundle
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBPanel
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.jcef.JBCefApp
import com.intellij.ui.jcef.JBCefBrowser
import java.awt.BorderLayout
import java.awt.Dimension
class MyToolWindowFactory : ToolWindowFactory {
init {
}
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
val myToolWindow = MyToolWindow()
val content = ContentFactory.getInstance().createContent(myToolWindow.getContent(), "", false)
toolWindow.contentManager.addContent(content)
}
override fun shouldBeAvailable(project: Project) = true
class MyToolWindow() {
fun getContent() = JBPanel<JBPanel<*>>().apply {
val noSupportLabel = JBLabel(MyBundle.message("noSupport"))
if (JBCefApp.isSupported()) {
val jbcef = JBCefBrowser()
jbcef.component.preferredSize = Dimension(900,900)
add(jbcef.component, BorderLayout.CENTER)
jbcef.loadURL("https://weread.qq.com/")
} else {
add(noSupportLabel)
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
7fd2d214fdde7a17219d81e44a8064b8d9335c92
| 1,445
|
Weread-Jetbrains-Plugin
|
MIT License
|
src/main/kotlin/com/kakao/gitnewtagextended/GitTagExtendedComparator.kt
|
sumniy
| 551,307,060
| false
| null |
package com.kakao.gitnewtagextended
class GitTagExtendedComparator : Comparator<GitTagExtended> {
override fun compare(o1: GitTagExtended, o2: GitTagExtended): Int {
return o1.order.compareTo(o2.order)
}
}
| 0
|
Kotlin
|
1
| 0
|
fc35d7fdaf2879738e6b0edd55722f491f0c079e
| 222
|
Git-New-Tag-Extended
|
Apache License 2.0
|
xesar-connect/src/main/kotlin/com/open200/xesar/connect/XesarConnect.kt
|
open200
| 684,928,079
| false
|
{"Kotlin": 909056}
|
package com.open200.xesar.connect
import QueryElementResource
import QueryListResource
import com.open200.xesar.connect.exception.*
import com.open200.xesar.connect.filters.*
import com.open200.xesar.connect.messages.ApiError
import com.open200.xesar.connect.messages.SingleEventResult
import com.open200.xesar.connect.messages.command.*
import com.open200.xesar.connect.messages.decodeError
import com.open200.xesar.connect.messages.event.*
import com.open200.xesar.connect.messages.query.*
import java.util.*
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CopyOnWriteArraySet
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import mu.KotlinLogging
val logger = KotlinLogging.logger {}
/**
* Xesar Highlevel API
*
* Handles the connection and the session of the Xesar API client in a stateful manner.
*/
class XesarConnect(private val client: IXesarMqttClient, val config: Config) : AutoCloseable {
private val subscribedTopics = CopyOnWriteArraySet<String>()
private val listeners = CopyOnWriteArrayList<Listener>()
private val connectionChannel = Channel<ConnectionEvent>()
private val coroutineScopeForSendCommand = CoroutineScope(Dispatchers.IO)
lateinit var token: Token
/**
* Configuration for a request.
*
* @property timeout The timeout value in milliseconds (default: 5000).
* @property token The token to be included in the request.
*/
data class RequestConfig(val timeout: Long = 5000L)
internal fun buildRequestConfig(): RequestConfig {
return RequestConfig()
}
init {
client.onDisconnect = { connectionChannel.trySend(ConnectionEvent.DISCONNECTED) }
client.onMessage = { topic, message ->
// call all listeners on the topic
val decodedMessage = message.decodeToString()
listeners
.filter { it.filter.filter(topic, decodedMessage) }
.forEach { it.messageHandler.handle(MessageHandler.Message(topic, decodedMessage)) }
}
}
/**
* Subscribes to the specified topics asynchronously.
* 1. QoS 0 (At most once): The message is delivered once, but there is no guarantee of
* delivery. It is a best-effort approach, where messages may be lost or duplicated.
* 2. QoS 1 (At least once): The message is guaranteed to be delivered at least once, but it may
* be delivered multiple times due to network issues or failures.
* 3. QoS 2 (Exactly once): The message is guaranteed to be delivered exactly once. It involves
* a more complex handshake process between the publisher and subscriber to ensure reliable
* delivery.
*
* @param topics The topics to subscribe to.
* @param qos The MQTT quality of service
* @return A deferred object that resolves to [Unit] when the subscription is successful.
*/
fun subscribeAsync(topics: Topics, qos: Int = 0): Deferred<Unit> {
return client.subscribeAsync(topics.topics, qos).apply {
subscribedTopics.addAll(topics.topics)
}
}
/**
* Registers a listener for incoming messages that match the specified message filter.
*
* @param messageFilter The filter to match incoming messages against.
* @param onMessage The message handler that will be invoked when a matching message is
* received.
* @return The created listener object.
*/
fun on(messageFilter: MessageFilter, onMessage: MessageHandler): Listener {
val listener = Listener(this, onMessage, messageFilter)
addListener(listener)
return listener
}
/**
* Retrieves a list of currently subscribed topics.
*
* @return The list of subscribed topics.
*/
fun getSubscribedTopics(): List<String> {
return subscribedTopics.toList()
}
/**
* Unsubscribes from the specified topics.
*
* @param topics The topics to unsubscribe from.
*/
fun unsubscribeTopics(topics: Topics) {
subscribedTopics.removeAll(topics.topics.toSet())
client.unsubscribe(topics)
}
private fun addListener(listener: Listener) {
listeners.add(listener)
}
internal fun removeListener(listener: Listener) {
listeners.remove(listener)
}
/**
* Performs an asynchronous login operation where the internal token will be set within
* XesarConnect You can either log in with a username and a password or with a token.
*
* @param username The username for authentication.
* @param password The password for authentication.
* @param requestConfig The request configuration (optional).
* @return A deferred object that resolves to a token upon successful login.
* @throws ConnectionFailedException if the login operation fails due to a connection issue.
* @throws UnauthorizedLoginAttemptException if the login attempt is unauthorized.
*/
suspend fun loginAsync(
username: String,
password: String,
requestConfig: RequestConfig = buildRequestConfig(),
): Deferred<Token> {
val deferred = CompletableDeferred<Token>()
val commandId = config.uuidGenerator.generateId()
handleStandardExceptions(deferred, "Login") {
withTimeout(requestConfig.timeout) {
val successListener =
on(CommandIdFilter(commandId)) {
try {
val loggedIn = decodeEvent<LoggedIn>(it.message)
deferred.complete(loggedIn.event.token)
} catch (e: Exception) {
deferred.completeExceptionally(
ConnectionFailedException("Login failed", e))
}
}
val unauthorizedListener =
on(TopicFilter(Topics.Event.UNAUTHORIZED_LOGIN_ATTEMPT)) {
val loggedIn = decodeEvent<UnauthorizedLoginAttempt>(it.message)
if (loggedIn.event.username == username) {
logger.warn("Login failed.")
deferred.completeExceptionally(
UnauthorizedLoginAttemptException(
"Probably invalid credentials were used"))
}
}
closeListenerOnCompletion(deferred, successListener, unauthorizedListener)
client
.publishAsync(
Topics.Command.LOGIN,
encodeCommand(
Login(commandId = commandId, username = username, password = <PASSWORD>)))
.await()
token = deferred.await()
}
}
return deferred
}
/**
* Performs an asynchronous logout operation. The previously used access token will be
* invalidated by the Xesar system and cannot be used again.
*
* @param requestConfig The request configuration (optional).
* @return A deferred object that resolves to the logged out token upon successful logout.
* @throws ConnectionFailedException if the logout operation fails due to a connection issue.
* @throws LoggedOutException if an error occurs during the logout process.
*/
suspend fun logoutAsync(requestConfig: RequestConfig = buildRequestConfig()): Deferred<Token> {
val deferredToken = CompletableDeferred<Token>()
handleStandardExceptions(deferredToken, "Logout") {
withTimeout(requestConfig.timeout) {
val successfulListener =
on(TopicFilter(Topics.Event.LOGGED_OUT)) {
try {
val loggedOut = decodeEvent<LoggedOut>(it.message)
val tokenOut = loggedOut.event.token
if (tokenOut == token) {
deferredToken.complete(tokenOut)
}
} catch (e: Exception) {
deferredToken.completeExceptionally(LoggedOutException())
}
}
closeListenerOnCompletion(deferredToken, successfulListener)
client.publishAsync(Topics.Command.LOGOUT, encodeCommand(Logout(token))).await()
deferredToken.await()
}
}
return deferredToken
}
/**
* Queries the list of access protocols asynchronously.
*
* @param params The query parameters (optional).
* @param requestConfig The request configuration (optional).
* @return A deferred object that resolves to a response containing a list of access protocols.
*/
suspend fun queryAccessProtocolEventListAsync(
params: Query.Params? = null,
requestConfig: RequestConfig = buildRequestConfig()
): Deferred<QueryList.Response<AccessProtocolEvent>> {
return queryListAsync(AccessProtocolEvent.QUERY_RESOURCE, params, requestConfig)
}
internal suspend inline fun <reified T : QueryListResource> queryListAsync(
resource: String,
params: Query.Params? = null,
requestConfig: RequestConfig = buildRequestConfig()
): Deferred<QueryList.Response<T>> {
val deferred = CompletableDeferred<QueryList.Response<T>>()
val requestId = config.uuidGenerator.generateId()
val query = Query(resource, requestId, token, id = null, params = params)
handleStandardExceptions(deferred, "Query") {
withTimeout(requestConfig.timeout) {
val queryIdListener =
on(QueryIdFilter(requestId)) {
val decoded = decodeQueryList<T>(it.message)
deferred.complete(decoded.response)
}
val apiErrorListener = registerDefaultApiErrorListener(requestId, deferred)
closeListenerOnCompletion(deferred, queryIdListener, apiErrorListener)
client.publishAsync(Topics.Query.REQUEST, encodeCommand(query)).await()
deferred.await()
}
}
return deferred
}
internal suspend inline fun <reified T : QueryElementResource> queryElementAsync(
resource: String,
id: UUID,
requestConfig: RequestConfig = buildRequestConfig()
): Deferred<T> {
val deferred = CompletableDeferred<T>()
val requestId = config.uuidGenerator.generateId()
handleStandardExceptions(deferred, "Query") {
withTimeout(requestConfig.timeout) {
val queryListener =
on(QueryIdFilter(requestId)) {
val decoded = decodeQueryElement<T>(it.message)
deferred.complete(decoded.response)
}
val errorListener = registerDefaultApiErrorListener(requestId, deferred)
closeListenerOnCompletion(deferred, queryListener, errorListener)
client
.publishAsync(
Topics.Query.REQUEST,
encodeCommand(Query(resource, requestId, token, id = id, params = null)))
.await()
deferred.await()
}
}
return deferred
}
private fun <T> closeListenerOnCompletion(
deferred: CompletableDeferred<T>,
vararg listeners: Listener
) {
deferred.invokeOnCompletion { listeners.forEach { it.close() } }
}
private fun closeListener(listeners: List<Listener>) {
listeners.forEach { it.close() }
}
private suspend inline fun <T> handleStandardExceptions(
deferred: CompletableDeferred<T>,
messageType: String,
block: suspend () -> (Unit)
) {
try {
block.invoke()
} catch (e: TimeoutCancellationException) {
logger.error("Timeout while waiting for $messageType response", e)
deferred.completeExceptionally(
ConnectionFailedException("$messageType request timed out", e))
} catch (e: Exception) {
logger.error("Error while waiting for $messageType response")
deferred.completeExceptionally(ConnectionFailedException("$messageType failed", e))
}
}
/**
* Sends a command and returns a [com.open200.xesar.connect.messages.SingleEventResult]
* asynchronously. If the event is not received within the specified timeout, a
* [RequiredEventException] or an [OptionalEventException] is thrown for the [Deferred] of the
* event. To analyse these timeout exceptions check
* [com.open200.xesar.connect.messages.SingleEventResult.apiErrorDeferred] for an [ApiError].
*
* @param topicCommand The topic to send the command.
* @param topicEvent The topic to wait for the event.
* @param eventRequired Whether the event is required.
* @param command The command to send.
* @param requestConfig The request configuration (optional).
*/
internal suspend inline fun <reified C : Command, reified E1 : Event> sendCommandAsync(
topicCommand: String,
topicEvent: String,
eventRequired: Boolean,
command: C,
requestConfig: RequestConfig = buildRequestConfig()
): SingleEventResult<E1> {
val firstEventDeferred = CompletableDeferred<E1>()
val apiErrorDeferred = CompletableDeferred<Optional<ApiError>>()
val firstEventListener =
registerCommandEventListenerAsync<C, E1>(command, topicEvent, firstEventDeferred)
val errorListener = registerApiErrorListener<C>(command, apiErrorDeferred)
val listener = listOf(errorListener, firstEventListener)
val sendCommandJob =
sendAndWaitForCommandAsync<C>(
requestConfig,
topicCommand,
command,
listOf(firstEventDeferred),
apiErrorDeferred,
listener)
sendCommandJob.invokeOnCompletion { commandException ->
if (commandException == null) {
val eventJob =
waitingForEventAsync<E1>(
requestConfig, firstEventDeferred, eventRequired, topicEvent, listener[1])
registerToCloseResourcesOnCancellation(eventJob, listener[1], firstEventDeferred)
val apiErrorJob =
waitingForApiErrorAsync(requestConfig, apiErrorDeferred, listener[0])
registerToCloseResourcesOnCancellation(apiErrorJob, listener[0], apiErrorDeferred)
}
}
return SingleEventResult(firstEventDeferred, apiErrorDeferred)
}
private fun <T> registerToCloseResourcesOnCancellation(
job: Job,
listener: Listener,
deferred: CompletableDeferred<T>
) {
job.invokeOnCompletion {
when (it) {
is CancellationException -> {
listener.close()
deferred.completeExceptionally(it)
}
}
}
}
/**
* Sends a command and returns a [Triple] including the two [Deferred] for two events and one
* [Deferred] for the [ApiError] asynchronously. If the events are not received within the
* specified timeout, a [RequiredEventException] or an [OptionalEventException] is thrown for
* the [Deferred] of the events respectively. To analyse these timeout exceptions check the
* [Deferred] for the [ApiError].
*
* @param topicCommand The topic to send the command.
* @param firstTopicEvent The topic to wait for the first event.
* @param firstEventRequired Whether the first event is required.
* @param secondTopicEvent The topic to wait for the second event.
* @param secondEventRequired Whether the second event is required.
* @param command The command to send.
* @param requestConfig The request configuration (optional).
*/
internal suspend inline fun <
reified C : Command, reified E1 : Event, reified E2 : Event> sendCommandAsync(
topicCommand: String,
firstTopicEvent: String,
firstEventRequired: Boolean,
secondTopicEvent: String,
secondEventRequired: Boolean,
command: C,
requestConfig: RequestConfig = buildRequestConfig(),
): Triple<Deferred<E1>, Deferred<E2>, Deferred<Optional<ApiError>>> {
val firstEventDeferred = CompletableDeferred<E1>()
val secondEventDeferred = CompletableDeferred<E2>()
val apiErrorDeferred = CompletableDeferred<Optional<ApiError>>()
val firstEventListener =
registerCommandEventListenerAsync<C, E1>(command, firstTopicEvent, firstEventDeferred)
val secondEventListener =
registerCommandEventListenerAsync<C, E2>(command, secondTopicEvent, secondEventDeferred)
val errorListener = registerApiErrorListener<C>(command, apiErrorDeferred)
val listener = listOf(errorListener, firstEventListener, secondEventListener)
logger.debug { "waited for all listeners" }
val sendCommandJob =
sendAndWaitForCommandAsync<C>(
requestConfig,
topicCommand,
command,
listOf(firstEventDeferred, secondEventDeferred),
apiErrorDeferred,
listener)
sendCommandJob.invokeOnCompletion { commandException ->
if (commandException == null) {
logger.debug { "start waiting for events" }
val firstEventJob =
waitingForEventAsync<E1>(
requestConfig,
firstEventDeferred,
firstEventRequired,
firstTopicEvent,
listener[1])
registerToCloseResourcesOnCancellation(
firstEventJob, listener[1], firstEventDeferred)
val secondEventJob =
waitingForEventAsync<E2>(
requestConfig,
secondEventDeferred,
secondEventRequired,
secondTopicEvent,
listener[2])
registerToCloseResourcesOnCancellation(
secondEventJob, listener[2], secondEventDeferred)
val apiErrorJob =
waitingForApiErrorAsync(requestConfig, apiErrorDeferred, listener[0])
registerToCloseResourcesOnCancellation(apiErrorJob, listener[0], apiErrorDeferred)
}
}
return Triple(firstEventDeferred, secondEventDeferred, apiErrorDeferred)
}
/**
* Sends a command and returns a [Pair] including a [Triple] with three [Deferred] for three
* events and one [Deferred] for the [ApiError] asynchronously. If the events are not received
* within the specified timeout, a [RequiredEventException] or an [OptionalEventException] is
* thrown for the [Deferred] of the events respectively. To analyse these timeout exceptions
* check the [Deferred] for the [ApiError].
*
* @param topicCommand The topic to send the command.
* @param firstTopicEvent The topic to wait for the first event.
* @param firstEventRequired Whether the first event is required.
* @param secondTopicEvent The topic to wait for the second event.
* @param secondEventRequired Whether the second event is required.
* @param thirdTopicEvent The topic to wait for the third event.
* @param thirdEventRequired Whether the third event is required.
* @param command The command to send.
* @param requestConfig The request configuration (optional).
*/
internal suspend inline fun <
reified C : Command,
reified E1 : Event,
reified E2 : Event,
reified E3 : Event> sendCommandAsync(
topicCommand: String,
firstTopicEvent: String,
firstEventRequired: Boolean,
secondTopicEvent: String,
secondEventRequired: Boolean,
thirdTopicEvent: String,
thirdEventRequired: Boolean,
command: C,
requestConfig: RequestConfig = buildRequestConfig(),
): Pair<Triple<Deferred<E1>, Deferred<E2>, Deferred<E3>>, Deferred<Optional<ApiError>>> {
val firstEventDeferred = CompletableDeferred<E1>()
val secondEventDeferred = CompletableDeferred<E2>()
val thirdEventDeferred = CompletableDeferred<E3>()
val apiErrorDeferred = CompletableDeferred<Optional<ApiError>>()
val firstEventListenerDeferred =
registerCommandEventListenerAsync<C, E1>(command, firstTopicEvent, firstEventDeferred)
val secondEventListenerDeferred =
registerCommandEventListenerAsync<C, E2>(command, secondTopicEvent, secondEventDeferred)
val thirdEventListenerDeferred =
registerCommandEventListenerAsync<C, E3>(command, thirdTopicEvent, thirdEventDeferred)
val errorListener = registerApiErrorListener<C>(command, apiErrorDeferred)
val listener =
listOf(
errorListener,
firstEventListenerDeferred,
secondEventListenerDeferred,
thirdEventListenerDeferred)
logger.debug { "awaited all listener" }
val sendCommandJob =
sendAndWaitForCommandAsync<C>(
requestConfig,
topicCommand,
command,
listOf(firstEventDeferred, secondEventDeferred, thirdEventDeferred),
apiErrorDeferred,
listener)
sendCommandJob.invokeOnCompletion { commandException ->
if (commandException == null) {
logger.debug { "start waiting for events" }
val firstEventJob =
waitingForEventAsync<E1>(
requestConfig,
firstEventDeferred,
firstEventRequired,
firstTopicEvent,
listener[1])
registerToCloseResourcesOnCancellation(
firstEventJob, listener[1], firstEventDeferred)
val secondEventJob =
waitingForEventAsync<E2>(
requestConfig,
secondEventDeferred,
secondEventRequired,
secondTopicEvent,
listener[2])
registerToCloseResourcesOnCancellation(
secondEventJob, listener[2], secondEventDeferred)
val thirdEventJob =
waitingForEventAsync<E3>(
requestConfig,
thirdEventDeferred,
thirdEventRequired,
thirdTopicEvent,
listener[3])
registerToCloseResourcesOnCancellation(
thirdEventJob, listener[3], thirdEventDeferred)
val apiErrorJob =
waitingForApiErrorAsync(requestConfig, apiErrorDeferred, listener[0])
registerToCloseResourcesOnCancellation(apiErrorJob, listener[0], apiErrorDeferred)
}
}
return Pair(
Triple(firstEventDeferred, secondEventDeferred, thirdEventDeferred), apiErrorDeferred)
}
private inline fun <reified C : Command> sendAndWaitForCommandAsync(
requestConfig: RequestConfig,
topicCommand: String,
command: C,
listOfEventDeferred: List<CompletableDeferred<out Event>>,
apiErrorDeferred: CompletableDeferred<Optional<ApiError>>,
listeners: List<Listener>
): Job {
var publishDeferred = CompletableDeferred<Unit>()
return coroutineScopeForSendCommand.launch {
try {
withTimeout(requestConfig.timeout) {
logger.debug { "send commmand now" }
publishDeferred =
client.publishAsync(topicCommand, encodeCommand(command))
as CompletableDeferred<Unit>
publishDeferred.await()
}
} catch (e: TimeoutCancellationException) {
logger.error { "timeout while sending the command" }
completeWithSpecificException(
ConnectionFailedException("Command Response timed out", e),
publishDeferred,
*listOfEventDeferred.toTypedArray(),
apiErrorDeferred)
closeListener(listeners)
} catch (e: Exception) {
logger.error { "error while sending the command" }
completeWithSpecificException(
ConnectionFailedException("Command request was invalid", e),
publishDeferred,
*listOfEventDeferred.toTypedArray(),
apiErrorDeferred)
closeListener(listeners)
}
}
}
private fun waitingForApiErrorAsync(
requestConfig: RequestConfig,
apiErrorDeferred: CompletableDeferred<Optional<ApiError>>,
listener: Listener
): Job =
coroutineScopeForSendCommand.launch {
logger.debug { "waiting for api error" }
try {
withTimeout(requestConfig.timeout) { apiErrorDeferred.await() }
} catch (e: TimeoutCancellationException) {
logger.error { "timeout while waiting for api error" }
apiErrorDeferred.complete(Optional.empty())
} catch (e: Exception) {
logger.error {
"exception while waiting for api error ${e.cause.toString().orEmpty()}"
}
apiErrorDeferred.completeExceptionally(e)
} finally {
listener.close()
}
}
private inline fun <reified E : Event> waitingForEventAsync(
requestConfig: RequestConfig,
eventDeferred: CompletableDeferred<E>,
eventRequired: Boolean,
topicEvent: String,
listener: Listener
): Job =
coroutineScopeForSendCommand.launch {
logger.debug { "waiting for event $topicEvent" }
try {
withTimeout(requestConfig.timeout) { eventDeferred.await() }
} catch (e: TimeoutCancellationException) {
logger.error { "timeout while waiting for event $topicEvent" }
completeWithSpecificException(
getTypeOfExceptionDependingOnEventRequired(eventRequired, topicEvent, e),
eventDeferred)
} catch (e: Exception) {
logger.error { "exception while waiting for event $topicEvent" }
completeWithSpecificException(e, eventDeferred)
} finally {
listener.close()
}
}
private inline fun <reified C : Command> registerApiErrorListener(
command: C,
apiErrorDeferred: CompletableDeferred<Optional<ApiError>>
): Listener =
on(ApiErrorFilter(command.commandId, Topics.Event.error(config.apiProperties.userId))) {
try {
logger.debug { "decode api error message" }
val apiError = decodeError(it.message)
apiErrorDeferred.complete(Optional.of(apiError))
} catch (e: Exception) {
logger.error { "exception while waiting for api error: ${e.message}" }
apiErrorDeferred.completeExceptionally(e)
}
}
private inline fun <reified C : Command, reified E : Event> registerCommandEventListenerAsync(
command: C,
topicEvent: String,
eventDeferred: CompletableDeferred<E>
): Listener =
on(EventAndCommandIdFilter(command.commandId, topicEvent)) {
try {
logger.debug { "decode $topicEvent message" }
val apiEvent = decodeEvent<E>(it.message)
eventDeferred.complete(apiEvent.event)
} catch (e: Exception) {
eventDeferred.completeExceptionally(ParsingException())
}
}
private fun <T> registerDefaultApiErrorListener(
id: UUID,
deferred: CompletableDeferred<T>
): Listener =
on(ApiErrorFilter(id, Topics.Event.error(config.apiProperties.userId))) {
try {
val apiError = decodeError(it.message)
deferred.completeExceptionally(
HttpErrorException(
"HTTP error code: ${apiError.error} ${apiError.reason.orEmpty()}",
apiError.error))
} catch (e: Exception) {
deferred.completeExceptionally(e)
}
}
private fun completeWithSpecificException(
e: Exception,
vararg deferreds: CompletableDeferred<*>
) {
deferreds.forEach { it.completeExceptionally(e) }
}
private fun getTypeOfExceptionDependingOnEventRequired(
eventRequired: Boolean,
topic: String,
e: Throwable
): XesarApiException {
return if (eventRequired) {
RequiredEventException("Required $topic event not received within timeout", e)
} else {
OptionalEventException("Optional $topic event not received within timeout", e)
}
}
/**
* Suspends the execution of the current coroutine until a disconnection event occurs in the
* specified channel.
*
* This function monitors the `connectionChannel` for the `ConnectionEvent.DISCONNECTED` event.
* It suspends the coroutine until the disconnection event is received, at which point it sets
* `connected` to `false` and closes the `connectionChannel`.
*
* @throws CancellationException if the coroutine is canceled while waiting.
*/
suspend fun delayUntilClose() {
var connected = true
while (connected) {
// Wait for a disconnection event in the channel.
if (connectionChannel.receive() == ConnectionEvent.DISCONNECTED) {
connected = false
connectionChannel.close()
}
}
}
/**
* This clean up function does the following:
* 1. If the connection channel is closed, return immediately.
* 2. If the logoutOnClose configuration is set to true and a token was used for login, perform
* a logout operation.
* 3. Cancel and clean up all underlying coroutines (close listener, complete deferred).
*/
override fun close() {
if (connectionChannel.isClosedForSend) {
return
}
if (config.logoutOnClose && token.isNotEmpty()) {
runBlocking { launch { logoutAsync().await() } }
}
client.close()
runBlocking { launch { coroutineScopeForSendCommand.cancel("program was closed") } }
}
companion object {
/**
* Asynchronously connects to the Xesar API, performs a login operation, and returns an
* instance of the XesarApi. Internally subscribes to the following topics:
* [Topics.Event.loggedIn],[Topics.Event.LOGGED_OUT],[Topics.Event.error],[Topics.Event.UNAUTHORIZED_LOGIN_ATTEMPT],
*
* @param config The configuration for connecting to the Xesar system.
* @param userCredentials Optional user credentials for authentication, including a username
* and password.
* @return A [Deferred] object representing the result of the connection and login process.
* The [Deferred] result is of type [XesarConnect].
* @throws Exception if an error occurs during the connection or login process.
*/
suspend fun connectAndLoginAsync(
config: Config,
userCredentials: UserCredentials? = null,
): Deferred<XesarConnect> {
val deferred = CompletableDeferred<XesarConnect>()
try {
val client = XesarMqttClient.connectAsync(config).await()
val api = XesarConnect(client, config)
api.subscribeAsync(
Topics(
Topics.Event.loggedIn(config.apiProperties.userId),
Topics.Event.UNAUTHORIZED_LOGIN_ATTEMPT,
Topics.Event.LOGGED_OUT,
Topics.Event.error(config.apiProperties.userId)))
.await()
if (userCredentials != null) {
api.loginAsync(userCredentials.username, userCredentials.password).await()
deferred.complete(api)
} else if (config.apiProperties.token != null) {
api.token = config.apiProperties.token
deferred.complete(api)
} else {
deferred.completeExceptionally(
ConnectionFailedException("Neither token nor credentials provided"))
}
} catch (e: Exception) {
deferred.completeExceptionally(e)
}
return deferred
}
}
}
| 18
|
Kotlin
|
1
| 10
|
3ddc0609408e5cdc3bd30f4c41626933a2ff26a9
| 33,622
|
xesar-connect
|
Apache License 2.0
|
data/src/main/java/com/nikitamaslov/data/model/ForecastObject.kt
|
nikitamasloff
| 173,980,211
| false
| null |
package com.nikitamaslov.data.model
data class ForecastObject(
val currentWeather: WeatherObject,
val futureWeather: Set<WeatherObject>,
val metadata: Metadata
) {
data class Metadata(
val location: LocationObject,
val temperatureUnit: TemperatureObject.Unit,
val dateTime: DateTimeObject
)
}
| 0
| null |
0
| 0
|
110fb59984f7f376c982b68056efed91b6247b4b
| 338
|
weatherr
|
Apache License 2.0
|
app/src/main/java/com/example/pharmacologyapp/MainActivity.kt
|
JoshD898
| 758,310,198
| false
|
{"Kotlin": 45619}
|
package com.example.pharmacologyapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.pharmacologyapp.classes.Drug
import com.example.pharmacologyapp.classes.ExperimentData
import com.example.pharmacologyapp.ui.theme.PharmacologyAppTheme
import com.google.gson.Gson
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
// Define the keys for storing data
private object PreferencesKeys {
val UNKNOWN_DRUG = stringPreferencesKey("unknown_drug")
val UNKNOWN_DRUG_INDEX = stringPreferencesKey("unknown_drug_index")
val UNKNOWN_CONCENTRATION = floatPreferencesKey("unknown_concentration")
}
// Extension property to create DataStore
private val ComponentActivity.dataStore: DataStore<Preferences> by preferencesDataStore(name = "experiment_data")
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
// Load persisted data
val experimentData = runBlocking {
loadExperimentData(dataStore)
}
setContent {
PharmacologyAppTheme {
MainApp(
initialExperimentData = experimentData,
onSaveExperimentData = { data: ExperimentData ->
runBlocking {
saveExperimentData(dataStore, data.unknownDrugPair, data.unknownConcentration)
}
}
)
}
}
}
// Function to load the experiment data from a dataStore
private suspend fun loadExperimentData(dataStore: DataStore<Preferences>): ExperimentData {
val preferences = dataStore.data.first()
val unknownDrugJson = preferences[PreferencesKeys.UNKNOWN_DRUG]
val unknownDrugIndexJson = preferences[PreferencesKeys.UNKNOWN_DRUG_INDEX]
val unknownConcentration = preferences[PreferencesKeys.UNKNOWN_CONCENTRATION] ?: 0.0f
// Deserialize JSON into objects
val unknownDrug = Gson().fromJson(unknownDrugJson, Drug::class.java)
val unknownDrugIndex = Gson().fromJson(unknownDrugIndexJson, Int::class.java)
val unknownDrugPair = Pair(unknownDrug, unknownDrugIndex)
return ExperimentData(unknownDrugPair, unknownConcentration)
}
// Function to save the data to DataStore
private suspend fun saveExperimentData(
dataStore: DataStore<Preferences>,
unknownDrugPair: Pair<Drug?, Int?>,
unknownConcentration: Float
) {
dataStore.edit { preferences ->
preferences[PreferencesKeys.UNKNOWN_DRUG] = Gson().toJson(unknownDrugPair.first)
preferences[PreferencesKeys.UNKNOWN_DRUG_INDEX] = Gson().toJson(unknownDrugPair.second)
preferences[PreferencesKeys.UNKNOWN_CONCENTRATION] = unknownConcentration
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d87d692aff144721f8f51de80db5d47af268cf79
| 3,366
|
PCTH-Simulator
|
MIT License
|
androidApp/src/main/java/app/trian/tudu/data/domain/task/UpdateTaskDueTimeUseCase.kt
|
trianapp
| 452,765,555
| false
|
{"Kotlin": 448664, "Shell": 1721, "Ruby": 1696}
|
package app.trian.tudu.data.domain.task
import app.trian.tudu.data.utils.Response
import app.trian.tudu.sqldelight.Database
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import java.time.LocalDateTime
import java.time.LocalTime
import javax.inject.Inject
class UpdateTaskDueTimeUseCase @Inject constructor(
private val db: Database
) {
operator fun invoke(
taskId: String,
taskDueTime: LocalTime
): Flow<Response<Boolean>> = flow {
emit(Response.Loading)
db.taskQueries.updateTaskDueTime(
taskId = taskId,
taskDueTime = taskDueTime.toString(),
updatedAt = LocalDateTime.now().toString()
)
emit(Response.Result(true))
}.flowOn(Dispatchers.Default)
}
| 1
|
Kotlin
|
1
| 1
|
6ab45a3a808405ebcd67c286a1e960c1901922eb
| 852
|
tudu
|
Apache License 2.0
|
src/main/kotlin/icu/windea/pls/config/config/CwtScopeConfig.kt
|
DragonKnightOfBreeze
| 328,104,626
| false
|
{"Kotlin": 3214853, "Java": 164704, "Lex": 42942, "HTML": 24942, "Shell": 2741}
|
package icu.windea.pls.config.config
import com.intellij.psi.*
import icu.windea.pls.core.*
import icu.windea.pls.core.annotations.*
import icu.windea.pls.cwt.psi.*
/**
* @property aliases aliases: string[]
*/
class CwtScopeConfig private constructor(
override val pointer: SmartPsiElementPointer<out CwtProperty>,
override val info: CwtConfigGroupInfo,
val name: String,
val aliases: Set<@CaseInsensitive String>
) : CwtConfig<CwtProperty> {
companion object Resolver {
fun resolve(config: CwtPropertyConfig, name: String): CwtScopeConfig? {
var aliases: Set<String>? = null
val props = config.properties
if(props.isNullOrEmpty()) return null
for(prop in props) {
if(prop.key == "aliases") aliases = prop.values?.mapNotNullTo(caseInsensitiveStringSet()) { it.stringValue }
}
if(aliases == null) aliases = emptySet()
return CwtScopeConfig(config.pointer, config.info, name, aliases)
}
}
}
| 12
|
Kotlin
|
4
| 31
|
3720f130cfe0bf1a7fc00cd1d5f062610b090b03
| 1,033
|
Paradox-Language-Support
|
MIT License
|
firebase-vertexai/src/main/kotlin/com/google/firebase/vertexai/type/HarmSeverity.kt
|
firebase
| 146,941,185
| false
|
{"Java": 13568535, "PureBasic": 10781995, "Kotlin": 2658699, "Python": 104323, "C++": 86300, "Makefile": 21902, "Shell": 13966, "HCL": 11091, "C": 6939, "JavaScript": 5482, "Mustache": 4729, "Ruby": 2545, "AIDL": 1486, "HTML": 215}
|
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.google.firebase.vertexai.type
/** Represents the severity of a [HarmCategory] being applicable in a [SafetyRating]. */
public class HarmSeverity private constructor(public val ordinal: Int) {
public companion object {
/** A new and not yet supported value. */
@JvmField public val UNKNOWN: HarmSeverity = HarmSeverity(0)
/** Severity for harm is negligible. */
@JvmField public val NEGLIGIBLE: HarmSeverity = HarmSeverity(1)
/** Low level of harm severity. */
@JvmField public val LOW: HarmSeverity = HarmSeverity(2)
/** Medium level of harm severity. */
@JvmField public val MEDIUM: HarmSeverity = HarmSeverity(3)
/** High level of harm severity. */
@JvmField public val HIGH: HarmSeverity = HarmSeverity(4)
}
}
| 440
|
Java
|
575
| 2,270
|
0697dd3aadd6c13d9e2d321c75173992bfbaac3b
| 1,369
|
firebase-android-sdk
|
Apache License 2.0
|
sessionkotlin/lib/src/test/kotlin/api/EndpointTest.kt
|
sessionkotlin
| 467,159,660
| false
|
{"Kotlin": 365663, "Makefile": 1801}
|
package api
import com.github.sessionkotlin.lib.api.exception.SKLinearException
import org.junit.jupiter.api.Test
import kotlin.test.assertFailsWith
class EndpointTest {
@Test
fun `test linear endpoint`() {
val e = com.github.sessionkotlin.lib.api.SKLinearEndpoint()
e.use()
assertFailsWith<SKLinearException> {
e.use()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
558837e9525987c9196e00f796489c041928a50d
| 385
|
sessionkotlin
|
MIT License
|
api/src/main/kotlin/nebulosa/api/services/CameraService.kt
|
tiagohm
| 568,578,345
| false
| null |
package nebulosa.api.services
import jakarta.annotation.PostConstruct
import nebulosa.api.data.entities.SavedCameraImageEntity
import nebulosa.api.data.events.CameraCaptureFinished
import nebulosa.api.data.requests.CameraStartCaptureRequest
import nebulosa.api.data.responses.CameraResponse
import nebulosa.api.repositories.SavedCameraImageRepository
import nebulosa.indi.device.PropertyChangedEvent
import nebulosa.indi.device.camera.CameraAttached
import nebulosa.indi.device.camera.CameraDetached
import nebulosa.indi.device.camera.CameraEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.springframework.stereotype.Service
import java.nio.file.Path
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutorService
import kotlin.io.path.createDirectories
import kotlin.io.path.exists
import kotlin.io.path.isDirectory
@Service
class CameraService(
private val equipmentService: EquipmentService,
private val savedCameraImageRepository: SavedCameraImageRepository,
private val capturesDirectory: Path,
private val cameraExecutorService: ExecutorService,
private val webSocketService: WebSocketService,
private val eventBus: EventBus,
) {
private val runningTasks = Collections.synchronizedMap(HashMap<String, CameraExposureTask>(2))
@PostConstruct
private fun initialize() {
eventBus.register(this)
}
@Subscribe(threadMode = ThreadMode.ASYNC)
fun onSavedCameraImageEvent(event: SavedCameraImageEntity) {
event.id = savedCameraImageRepository.withPath(event.path)?.id ?: event.id
savedCameraImageRepository.save(event)
webSocketService.sendSavedCameraImageEvent(event)
}
@Subscribe(threadMode = ThreadMode.ASYNC)
fun onCameraEvent(event: CameraEvent) {
when (event) {
is PropertyChangedEvent -> webSocketService.sendCameraUpdated(event.device!!)
is CameraCaptureFinished -> webSocketService.sendCameraCaptureFinished(event.device)
is CameraAttached -> webSocketService.sendCameraAttached(event.device)
is CameraDetached -> webSocketService.sendCameraDetached(event.device)
}
}
fun attachedCameras(): List<CameraResponse> {
return equipmentService.cameras().map(::CameraResponse)
}
operator fun get(name: String): CameraResponse {
val camera = requireNotNull(equipmentService.camera(name))
return CameraResponse(camera)
}
fun connect(name: String) {
val camera = requireNotNull(equipmentService.camera(name))
camera.connect()
}
fun disconnect(name: String) {
val camera = requireNotNull(equipmentService.camera(name))
camera.disconnect()
}
fun isCapturing(name: String): Boolean {
return runningTasks.containsKey(name)
}
fun setpointTemperature(name: String, temperature: Double) {
val camera = requireNotNull(equipmentService.camera(name))
camera.temperature(temperature)
}
fun cooler(name: String, enable: Boolean) {
val camera = requireNotNull(equipmentService.camera(name))
camera.cooler(enable)
}
@Synchronized
fun startCapture(name: String, data: CameraStartCaptureRequest) {
if (isCapturing(name)) return
val camera = requireNotNull(equipmentService.camera(name))
val savePath = data.savePath?.ifBlank { null }?.let(Path::of)
?.takeIf { it.exists() && it.isDirectory() }
?: Path.of("$capturesDirectory", name).createDirectories()
val task = CameraExposureTask(camera, data, savePath)
val future = CompletableFuture.runAsync(task, cameraExecutorService)
runningTasks[name] = task
future.whenComplete { _, _ ->
runningTasks.remove(name)
}
}
fun abortCapture(name: String) {
runningTasks[name]?.abort()
}
}
| 0
|
Kotlin
|
0
| 1
|
435ba0de2391ea6f223e3b7596cd72c6f7ae1485
| 4,004
|
nebulosa
|
MIT License
|
app/src/main/java/com/d10ng/compose/demo/pages/StepperScreen.kt
|
D10NGYANG
| 445,078,597
| false
|
{"Kotlin": 380021}
|
package com.d10ng.compose.demo.pages
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.d10ng.compose.ui.AppColor
import com.d10ng.compose.ui.PageTransitions
import com.d10ng.compose.ui.base.Cell
import com.d10ng.compose.ui.base.CellGroup
import com.d10ng.compose.ui.form.Stepper
import com.d10ng.compose.ui.form.StepperStyle
import com.d10ng.compose.ui.navigation.NavBar
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.annotation.RootNavGraph
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
/**
* 步进器
* @Author d10ng
* @Date 2023/9/6 17:47
*/
@RootNavGraph
@Destination(style = PageTransitions::class)
@Composable
fun StepperScreen(
nav: DestinationsNavigator
) {
StepperScreenView(onClickBack = nav::navigateUp)
}
@Composable
private fun StepperScreenView(
onClickBack: () -> Unit = {},
) {
Column(
modifier = Modifier
.fillMaxSize()
.background(AppColor.Neutral.bg)
) {
NavBar(title = "Stepper", onClickBack = onClickBack)
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
CellGroup(title = "使用方式", inset = true) {
Cell(title = "基础用法") {
var value1 by remember { mutableIntStateOf(1) }
Stepper(value = value1, onValueChange = { value1 = it })
}
Cell(title = "步长设置") {
var value1 by remember { mutableIntStateOf(0) }
Stepper(value = value1, onValueChange = { value1 = it }, step = 2)
}
Cell(title = "限制输入范围") {
var value1 by remember { mutableIntStateOf(10) }
Stepper(value = value1, onValueChange = { value1 = it }, max = 10)
}
Cell(title = "禁用状态") {
var value1 by remember { mutableIntStateOf(0) }
Stepper(value = value1, onValueChange = { value1 = it }, disabled = true)
}
Cell(title = "禁用输入框") {
var value1 by remember { mutableIntStateOf(0) }
Stepper(value = value1, onValueChange = { value1 = it }, canInput = false)
}
Cell(title = "圆角风格") {
var value1 by remember { mutableIntStateOf(0) }
Stepper(value = value1, onValueChange = { value1 = it }, style = StepperStyle.Round)
}
}
}
}
}
@Preview
@Composable
private fun StepperScreenViewPreview() {
StepperScreenView()
}
| 0
|
Kotlin
|
1
| 9
|
87ce1244067b555c000ecaf8cdb635d88625a3e3
| 3,209
|
DLJetpackComposeUtil
|
MIT License
|
app/src/main/java/com/hossainkhan/vision/data/HkVisionApi.kt
|
hossain-khan
| 262,681,367
| false
|
{"Kotlin": 21238}
|
package com.hossainkhan.vision.data
import com.hossainkhan.vision.model.VisionPhotos
import retrofit2.Call
import retrofit2.http.GET
/**
* Access the photos using retrofit.
*
* https://square.github.io/retrofit/
*/
interface HkVisionApi {
@GET("photos.json")
fun photos(): Call<VisionPhotos>
}
| 3
|
Kotlin
|
0
| 5
|
710ff81f85a2c53ff896af1a91256795acbef901
| 308
|
android-hk-vision-muzei-plugin
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/nomisprisonerapi/jpa/PayBand.kt
|
ministryofjustice
| 444,895,409
| false
|
{"Kotlin": 3166159, "PLSQL": 324757, "Dockerfile": 1112}
|
package uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa
import jakarta.persistence.DiscriminatorValue
import jakarta.persistence.Entity
@Entity
@DiscriminatorValue(PayBand.PAY_BAND)
class PayBand(code: String, description: String) : ReferenceCode(PAY_BAND, code, description) {
companion object {
const val PAY_BAND = "PAY_BAND"
fun pk(code: String): Pk = Pk(PAY_BAND, code)
}
}
| 1
|
Kotlin
|
2
| 0
|
467c7057cb0d8bc045143171c4678ed4fe9ba592
| 396
|
hmpps-nomis-prisoner-api
|
MIT License
|
app-performance-tracker-core/src/main/kotlin/com/github/felipehjcosta/perf/metrics/MetricTracker.kt
|
felipehjcosta
| 257,076,397
| false
| null |
package com.github.felipehjcosta.perf.metrics
interface MetricTracker<T : Any> {
fun trackMetric(block: (T) -> Unit)
}
| 0
|
Kotlin
|
0
| 0
|
5d306a60b0b2f69c9518c425055a080a9e90e3d2
| 123
|
android-app-performance-tracker
|
MIT License
|
engine/src/main/kotlin/rs/dusk/engine/entity/character/update/visual/ForceChat.kt
|
Palmfeldt
| 673,267,966
| true
|
{"Kotlin": 1529507}
|
package rs.dusk.engine.entity.character.update.visual
import rs.dusk.engine.entity.character.Character
import rs.dusk.engine.entity.character.npc.NPC
import rs.dusk.engine.entity.character.npc.NPCEvent
import rs.dusk.engine.entity.character.player.Player
import rs.dusk.engine.entity.character.player.PlayerEvent
import rs.dusk.engine.entity.character.update.Visual
/**
* @author <NAME> <<EMAIL>>
* @since April 25, 2020
*/
data class ForceChat(var text: String = "") : Visual {
override fun reset(character: Character) {
text = ""
}
}
const val PLAYER_FORCE_CHAT_MASK = 0x4000
const val NPC_FORCE_CHAT_MASK = 0x2
fun Player.flagForceChat() = visuals.flag(PLAYER_FORCE_CHAT_MASK)
fun NPC.flagForceChat() = visuals.flag(NPC_FORCE_CHAT_MASK)
fun Player.getForceChat() = visuals.getOrPut(PLAYER_FORCE_CHAT_MASK) { ForceChat() }
fun NPC.getForceChat() = visuals.getOrPut(NPC_FORCE_CHAT_MASK) { ForceChat() }
fun PlayerEvent.force(chatText: String) {
player.forceChat = chatText
}
fun NPCEvent.force(chatText: String) {
npc.forceChat = chatText
}
var Player.forceChat: String
get() = getForceChat().text
set(value) {
getForceChat().text = value
flagForceChat()
}
var NPC.forceChat: String
get() = getForceChat().text
set(value) {
getForceChat().text = value
flagForceChat()
}
| 0
|
Kotlin
|
0
| 0
|
0b3a4fe8eb9f2e2e29f8834d028fd3edf038cd2f
| 1,365
|
NostalgiaScape
|
Creative Commons Attribution 3.0 Unported
|
app/src/main/java/com/vicky7230/flux/ui/tvDetails/TvDetailsMvpView.kt
|
sam43
| 143,965,801
| true
|
{"Kotlin": 211153}
|
package com.vicky7230.flux.ui.tvDetails
import com.vicky7230.flux.data.network.model.tvDetails.Videos
import com.vicky7230.flux.data.network.model.tvDetails.TvDetails
import com.vicky7230.flux.ui.base.MvpView
/**
* Created by vicky on 21/3/18.
*/
interface TvDetailsMvpView : MvpView {
fun showDetails(tvDetails: TvDetails?)
fun showLoginScreen()
}
| 0
|
Kotlin
|
0
| 0
|
373af1fee22a6b0973f7965f22ab2cf7055f96f6
| 361
|
Flux
|
Apache License 2.0
|
app/src/main/java/com/eky/evimiss/ui/custom/chart/MyChart.kt
|
EnesKy
| 400,728,510
| false
| null |
package com.eky.evimiss.ui.custom.chart
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.eky.evimiss.ui.theme.primaryLight
import com.eky.evimiss.ui.theme.secondary
import com.eky.evimiss.ui.theme.secondaryDark
import com.eky.evimiss.ui.theme.secondaryLight
@Composable
fun MyChart(modifier: Modifier) {
Main(modifier)
}
@Composable
fun Main(modifier: Modifier) {
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier.weight(2.5f).aspectRatio(1f)
) {
Canvas(modifier = Modifier.align(Alignment.Center).fillMaxSize().padding(32.dp)) {
drawArc(
color = primaryLight,
startAngle = 0f,
sweepAngle = 360f,
useCenter = false,
style = Stroke(width = 32f, cap = StrokeCap.Round)
)
drawArc(
color = secondaryLight,
startAngle = 0f,
sweepAngle = 30f,
useCenter = false,
style = Stroke(width = 56f, cap = StrokeCap.Round)
)
drawArc(
color = secondaryDark,
startAngle = 30f,
sweepAngle = 60f,
useCenter = false,
style = Stroke(width = 56f, cap = StrokeCap.Round)
)
}
Text(
modifier = Modifier.align(Alignment.Center),
text = "1450,55 TL",
color = Color.White,
style = MaterialTheme.typography.body1
)
}
//Categories
Column(modifier = Modifier.weight(1f)) {
for (i in listOf(1,2,3,4)) {
Row(
modifier = Modifier.padding(4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center) {
Canvas(
Modifier
.size(4.dp)
.align(Alignment.CenterVertically)) {
drawCircle(color = secondary)
}
Text(
modifier = Modifier.padding(start = 4.dp),
text = stringResource(com.eky.evimiss.R.string.label_expense_type),
color = Color.White,
style = MaterialTheme.typography.caption
)
}
}
}
}
}
@Composable
fun drawArc(
drawScope: DrawScope,
//newExpense: Float,
expenseType: ExpenseType) {
//val income = 36
with(drawScope) {
drawArc(
color = expenseType.color,
startAngle = 0f,
sweepAngle = 360f,
useCenter = false,
style = Stroke(width = 45f)
)
}
}
@Preview
@Composable
fun PreviewMyChart() {
Main(modifier = Modifier.fillMaxWidth())
}
| 0
|
Kotlin
|
0
| 1
|
fa105d04962425f65fed2a13838da454b8e3d325
| 3,745
|
Evimiss
|
MIT License
|
app/src/main/java/com/eky/evimiss/ui/custom/chart/MyChart.kt
|
EnesKy
| 400,728,510
| false
| null |
package com.eky.evimiss.ui.custom.chart
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.eky.evimiss.ui.theme.primaryLight
import com.eky.evimiss.ui.theme.secondary
import com.eky.evimiss.ui.theme.secondaryDark
import com.eky.evimiss.ui.theme.secondaryLight
@Composable
fun MyChart(modifier: Modifier) {
Main(modifier)
}
@Composable
fun Main(modifier: Modifier) {
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier.weight(2.5f).aspectRatio(1f)
) {
Canvas(modifier = Modifier.align(Alignment.Center).fillMaxSize().padding(32.dp)) {
drawArc(
color = primaryLight,
startAngle = 0f,
sweepAngle = 360f,
useCenter = false,
style = Stroke(width = 32f, cap = StrokeCap.Round)
)
drawArc(
color = secondaryLight,
startAngle = 0f,
sweepAngle = 30f,
useCenter = false,
style = Stroke(width = 56f, cap = StrokeCap.Round)
)
drawArc(
color = secondaryDark,
startAngle = 30f,
sweepAngle = 60f,
useCenter = false,
style = Stroke(width = 56f, cap = StrokeCap.Round)
)
}
Text(
modifier = Modifier.align(Alignment.Center),
text = "1450,55 TL",
color = Color.White,
style = MaterialTheme.typography.body1
)
}
//Categories
Column(modifier = Modifier.weight(1f)) {
for (i in listOf(1,2,3,4)) {
Row(
modifier = Modifier.padding(4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center) {
Canvas(
Modifier
.size(4.dp)
.align(Alignment.CenterVertically)) {
drawCircle(color = secondary)
}
Text(
modifier = Modifier.padding(start = 4.dp),
text = stringResource(com.eky.evimiss.R.string.label_expense_type),
color = Color.White,
style = MaterialTheme.typography.caption
)
}
}
}
}
}
@Composable
fun drawArc(
drawScope: DrawScope,
//newExpense: Float,
expenseType: ExpenseType) {
//val income = 36
with(drawScope) {
drawArc(
color = expenseType.color,
startAngle = 0f,
sweepAngle = 360f,
useCenter = false,
style = Stroke(width = 45f)
)
}
}
@Preview
@Composable
fun PreviewMyChart() {
Main(modifier = Modifier.fillMaxWidth())
}
| 0
|
Kotlin
|
0
| 1
|
fa105d04962425f65fed2a13838da454b8e3d325
| 3,745
|
Evimiss
|
MIT License
|
krait-core/src/main/kotlin/com/github/kam1sh/krait/core/exceptions/KraitException.kt
|
kam1sh
| 300,851,297
| false
| null |
package com.github.kam1sh.krait.core.exceptions
import java.lang.Exception
/**
* Base Krait exception.
*/
open class KraitException(message: String) : Exception(message)
| 0
|
Kotlin
|
0
| 1
|
fa17c41038d5119b50363ce59b7f8482e53689d4
| 173
|
krait
|
MIT License
|
core/src/main/java/com/yupfeg/logger/ext/LoggerExt.kt
|
yuPFeG1819
| 352,538,832
| false
| null |
package com.yupfeg.logger.ext
import com.yupfeg.logger.Logger
import com.yupfeg.logger.LoggerConfig
/**
* 使用kotlin DSL方式,配置Logger参数
* @param init dsl方式配置
* */
@Deprecated(
message = "已统合到Logger类的静态方法",
replaceWith = ReplaceWith(
expression = "Logger.prepare(init)",
imports = ["com.yupfeg.logger.Logger"]
)
)
fun setDslLoggerConfig(init : LoggerConfig.()->Unit) : Logger{
return Logger.prepare(init)
}
// <editor-fold desc="快捷输出Verbose等级的日志">
/**
* 输出verbose等级的日志
* * 使用全局的日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
@Deprecated(
message = "当前命名会与AS自带的模板冲突,无法快速导入",
replaceWith = ReplaceWith(
expression = "loggv(msg)",
imports = ["com.yupfeg.logger.ext.loggv"]
)
)
fun logv(msg : Any) = Logger.GLOBAL.v(msg = msg)
/**
* 输出debug等级的日志
* @param tag 日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
@Deprecated(
message = "当前命名会与AS自带的模板冲突,无法快速导入",
replaceWith = ReplaceWith(
expression = "loggv(tag,msg)",
imports = ["com.yupfeg.logger.ext.loggv"]
)
)
fun logv(tag : String,msg: Any) = Logger.GLOBAL.v(tag, msg)
/**
* 输出verbose等级的日志,默认使用全局配置日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
fun loggv(msg : Any) = Logger.GLOBAL.v(msg)
/**
* 输出debug等级的日志,默认使用全局配置日志tag
* @param tag 日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
fun loggv(tag : String,msg: Any) = Logger.GLOBAL.v(tag, msg)
// </editor-fold>
// <editor-fold desc="快捷输出Debug等级的日志">
/**
* 输出debug等级的日志
* * 使用全局的日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
@Deprecated(
message = "当前命名会与AS自带的模板冲突,无法快速导入",
replaceWith = ReplaceWith(
expression = "loggd(msg)",
imports = ["com.yupfeg.logger.ext.loggd"]
)
)
fun logd(msg : Any) = Logger.GLOBAL.d(msg = msg)
/**
* 输出debug等级的日志
* @param tag 日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
@Deprecated(
message = "当前命名会与AS自带的模板冲突,无法快速导入",
replaceWith = ReplaceWith(
expression = "loggd(tag,msg)",
imports = ["com.yupfeg.logger.ext.loggd"]
)
)
fun logd(tag : String, msg : Any?) = Logger.GLOBAL.d(tag,msg)
/**
* 输出debug等级的日志,默认使用全局配置日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
fun loggd(msg : Any) = Logger.GLOBAL.d(msg)
/**
* 输出debug等级的日志,默认使用全局配置日志tag
* @param tag 日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
fun loggd(tag : String,msg: Any) = Logger.GLOBAL.d(tag, msg)
// </editor-fold>
// <editor-fold desc="快捷输出info等级的日志">
/**
* 输出info等级的日志
* * 使用全局的日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
@Deprecated(
message = "当前命名会与AS自带的模板冲突,无法快速导入",
replaceWith = ReplaceWith(
expression = "loggi(msg)",
imports = ["com.yupfeg.logger.ext.loggi"]
)
)
fun logi(msg : Any?) = Logger.GLOBAL.i(msg = msg)
/**
* 输出info等级的日志
* @param tag 日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
@Deprecated(
message = "当前命名会与AS自带的模板冲突,无法快速导入",
replaceWith = ReplaceWith(
expression = "loggi(tag,msg)",
imports = ["com.yupfeg.logger.ext.loggi"]
)
)
fun logi(tag : String, msg : Any) = Logger.GLOBAL.i(tag,msg)
/**
* 输出info等级的日志,默认使用全局配置日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
fun loggi(msg : Any) = Logger.GLOBAL.i(msg)
/**
* 输出info等级的日志,默认使用全局配置日志tag
* @param tag 日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
fun loggi(tag : String,msg: Any) = Logger.GLOBAL.i(tag, msg)
// </editor-fold>
// <editor-fold desc="快捷输出warn等级的日志">
/**
* 输出waring等级的日志
* * 使用全局的日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
@Deprecated(
message = "当前命名会与AS自带的模板冲突,无法快速导入",
replaceWith = ReplaceWith(
expression = "loggw(msg)",
imports = ["com.yupfeg.logger.ext.loggw"]
)
)
fun logw(msg: Any?) = Logger.GLOBAL.w(msg = msg)
/**
* 输出waring等级的日志
* @param tag 日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
@Deprecated(
message = "当前命名会与AS自带的模板冲突,无法快速导入",
replaceWith = ReplaceWith(
expression = "loggw(tag,msg)",
imports = ["com.yupfeg.logger.ext.loggw"]
)
)
fun logw(tag: String,msg: Any?) = Logger.GLOBAL.w(tag,msg)
/**
* 输出warn等级的日志,默认使用全局配置日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
fun loggw(msg : Any) = Logger.GLOBAL.w(msg)
/**
* 输出warn等级的日志,默认使用全局配置日志tag
* @param tag 日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
fun loggw(tag : String,msg: Any) = Logger.GLOBAL.w(tag, msg)
// </editor-fold>
// <editor-fold desc="快捷输出error等级的日志">
/**
* 输出error等级的日志
* * 使用全局的日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
@Deprecated(
message = "当前命名会与AS自带的模板冲突,无法快速导入",
replaceWith = ReplaceWith(
expression = "logge(tag,msg)",
imports = ["com.yupfeg.logger.ext.logge"]
)
)
fun loge(msg: Any?) = Logger.GLOBAL.e(msg = msg)
/**
* 输出error等级的日志
* @param tag 日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
@Deprecated(
message = "当前命名会与AS自带的模板冲突,无法快速导入",
replaceWith = ReplaceWith(
expression = "logge(tag,msg)",
imports = ["com.yupfeg.logger.ext.logge"]
)
)
fun loge(tag : String,msg : Any?) = Logger.GLOBAL.e(tag,msg)
/**
* 输出error等级的日志,默认使用全局配置日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
fun logge(msg : Any) = Logger.GLOBAL.e(msg)
/**
* 输出error等级的日志,默认使用全局配置日志tag
* @param tag 日志tag
* @param msg 日志内容
*/
@Suppress("SpellCheckingInspection", "unused")
fun logge(tag : String,msg: Any) = Logger.GLOBAL.e(tag, msg)
// </editor-fold>
| 0
|
Kotlin
|
0
| 0
|
60795d9432d9c0f68c0242bacb90f52916959c12
| 5,841
|
Logger
|
Apache License 2.0
|
composeApp/src/commonMain/kotlin/data/local/database/dao/TransactionDao.kt
|
saifi369
| 833,042,897
| false
|
{"Kotlin": 116258, "Swift": 632}
|
package data.local.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import data.local.model.TransactionEntity
import data.local.model.TransactionType
import kotlinx.coroutines.flow.Flow
@Dao
interface TransactionDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertExpense(transactionEntity: TransactionEntity)
@Query("SELECT * FROM `transaction` WHERE walletId =:walletId")
fun getTransactionForWallet(walletId: Int): Flow<List<TransactionEntity>>
@Query("SELECT SUM(amount) FROM `transaction` WHERE walletID =:walletId AND transactionType =:type")
fun getTotalTransactionSum(walletId: Int, type: TransactionType): Flow<Double>
}
| 0
|
Kotlin
|
0
| 0
|
5be256ee98e067b394d960ac8748e7a33a782e82
| 764
|
KMP-ExpenseTracker
|
Apache License 2.0
|
libraries/cache/src/main/kotlin/io/plastique/core/cache/CacheCleaner.kt
|
plastiqueapp
| 150,879,887
| false
| null |
package io.plastique.core.cache
import android.annotation.SuppressLint
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Provider
class CacheCleaner @Inject constructor(
private val cleanableRepository: Provider<Set<CleanableRepository>>
) {
@SuppressLint("CheckResult")
fun clean() {
Observable.fromIterable(cleanableRepository.get())
.concatMapCompletable { it.cleanCache() }
.subscribeOn(Schedulers.io())
.subscribe({
Timber.tag(LOG_TAG).d("Cleanup complete")
}, { error ->
Timber.tag(LOG_TAG).e(error)
})
}
companion object {
private const val LOG_TAG = "CacheCleaner"
}
}
| 0
|
Kotlin
|
2
| 9
|
9271853f3741add18822858cbad9d4f8e8104f54
| 807
|
plastique
|
Apache License 2.0
|
gabimoreno/src/main/java/soy/gabimoreno/presentation/navigation/NavItem.kt
|
soygabimoreno
| 477,796,937
| false
|
{"Kotlin": 364408, "Swift": 648, "Shell": 441}
|
package soy.gabimoreno.presentation.navigation
import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Podcasts
import androidx.compose.material.icons.filled.WorkspacePremium
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.navigation.NavType
import androidx.navigation.navArgument
import soy.gabimoreno.R
enum class NavItem(
val navCommand: NavCommand,
val icon: ImageVector,
@StringRes val titleResId: Int,
) {
PODCAST(
navCommand = NavCommand.ContentType(Feature.PODCAST),
icon = Icons.Default.Podcasts,
titleResId = R.string.nav_item_podcast
),
PREMIUM(
navCommand = NavCommand.ContentType(Feature.PREMIUM),
icon = Icons.Default.WorkspacePremium,
titleResId = R.string.nav_item_premium
)
}
sealed class NavCommand(
internal val feature: Feature,
internal val subRoute: String = "home",
private val navArgs: List<NavArg> = emptyList(),
) {
class ContentType(feature: Feature) : NavCommand(feature)
class ContentDetail(
feature: Feature,
navArgs: List<NavArg>,
) : NavCommand(
feature,
"detail",
navArgs
) {
fun createRoute(audioId: String) = "${feature.route}/$subRoute/$audioId"
}
class ContentWebView(feature: Feature) : NavCommand(
feature,
"webView",
listOf(NavArg.EncodedUrl)
) {
fun createRoute(encodedUrl: String) = "${feature.route}/$subRoute/$encodedUrl"
}
val route = run {
val argValues = navArgs.map { "{${it.key}}" }
listOf(feature.route, subRoute)
.plus(argValues)
.joinToString("/")
}
val args = navArgs.map {
navArgument(it.key) { type = it.navType }
}
}
enum class NavArg(
val key: String,
val navType: NavType<*>,
) {
EpisodeId("episodeId", NavType.StringType),
EncodedUrl("encodedUrl", NavType.StringType),
PremiumAudioId("premiumAudioId", NavType.StringType)
}
| 6
|
Kotlin
|
10
| 13
|
5d5ff8117cda10f7567ac0caf152501c1d439baa
| 2,070
|
Base
|
Apache License 2.0
|
app/src/main/java/com/example/simpletodo/MainActivity.kt
|
jackkououou
| 448,470,497
| false
| null |
package com.example.simpletodo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.apache.commons.io.FileUtils
import java.io.File
import java.io.IOException
import java.nio.charset.Charset
class MainActivity : AppCompatActivity() {
var listOfTasks = mutableListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lateinit var adapter: TaskItemAdapter
//----Long Click to delete -----------
val onLongClickListener = object : TaskItemAdapter.OnLongClickListener {
override fun onItemLongClicked(position: Int) {
// delete item at pos
listOfTasks.removeAt(position)
//notify adapter
adapter.notifyDataSetChanged()
saveItems()
}
}
loadItems()
// look up recycler view in layout
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
// create adapter passing in the sample data
adapter = TaskItemAdapter(listOfTasks, onLongClickListener)
// attach adapter to rv
recyclerView.adapter = adapter
// set layout manager
recyclerView.layoutManager = LinearLayoutManager(this)
val inputTextField = findViewById<EditText>(R.id.addTaskField)
//----------- Add to list ----------------
findViewById<Button>(R.id.button).setOnClickListener {
//1. Grab the text user put into text field
val userInputtedTask = inputTextField.text.toString()
//2. Add string to list of task
listOfTasks.add(userInputtedTask)
// Notify adapter that data updated
adapter.notifyItemInserted(listOfTasks.size - 1)
//3. clear field after adding
findViewById<EditText>(R.id.addTaskField).setText("")
saveItems()
}
}
//------------Save input data by writing and reading in a file-----------
//1. create a method to get data file
fun getDataFile() : File {
return File(filesDir, "data.txt")
}
//2. load the items by reading all the lines
fun loadItems() {
try {
listOfTasks = FileUtils.readLines(getDataFile(), Charset.defaultCharset())
} catch (ioException: IOException) {
ioException.printStackTrace()
}
}
//3. save items by writing to the file
fun saveItems() {
try{
FileUtils.writeLines(getDataFile(), listOfTasks)
} catch (ioException: IOException) {
ioException.printStackTrace()
}
}
}
| 1
|
Kotlin
|
0
| 0
|
8afb9ac787067d73b0c94b7b88bc9fec73c74522
| 2,880
|
prework-repo
|
Apache License 2.0
|
feeder-stock/src/main/kotlin/ru/timmson/feeder/stock/model/MEStock.kt
|
timmson
| 603,205,306
| false
|
{"Kotlin": 86003, "Dockerfile": 376}
|
package ru.timmson.feeder.stock.model
class MEStock {
lateinit var marketdata: MEMarketData
override fun toString(): String {
return "MEStock(securities=$marketdata)"
}
}
| 0
|
Kotlin
|
0
| 0
|
4d3914a1c4b77f192ab8e29b3f45cf7fc3ad08fc
| 192
|
feeder
|
MIT License
|
src/main/java/com/sayzen/campfiresdk/models/cards/post_pages/CardPageUnknown.kt
|
ZeonXX
| 381,986,881
| false
|
{"Kotlin": 2097097}
|
package com.sayzen.campfiresdk.models.cards.post_pages
import android.view.View
import android.widget.TextView
import com.dzen.campfire.api.API_TRANSLATE
import com.dzen.campfire.api.models.publications.PagesContainer
import com.dzen.campfire.api.models.publications.post.Page
import com.sayzen.campfiresdk.R
import com.sayzen.campfiresdk.controllers.t
class CardPageUnknown(
pagesContainer: PagesContainer?,
page: Page
) : CardPage(R.layout.card_page_unknown, pagesContainer, page) {
override fun bindView(view: View) {
super.bindView(view)
val vSystemMessage:TextView = view.findViewById(R.id.vSystemMessage)
vSystemMessage.text = t(API_TRANSLATE.error_unknown)
}
override fun notifyItem() {}
}
| 0
|
Kotlin
|
2
| 0
|
9930e65c1f213bac9266046be22eb937a03f151e
| 755
|
CampfireSDK
|
Apache License 2.0
|
src/main/kotlin/org/taktik/couchdb/support/views/ExternalViewRepository.kt
|
icure
| 512,831,778
| false
|
{"Kotlin": 222433, "JavaScript": 7399}
|
package org.taktik.couchdb.support.views
import org.taktik.couchdb.entity.View
data class ExternalViewRepository(
val secondaryPartition: String?,
val klass: Class<*>,
val views: Map<String, View>
)
| 4
|
Kotlin
|
1
| 0
|
04c49e22a083e2887f93120f4482b5d1150151b7
| 203
|
krouch
|
Apache License 2.0
|
parserss/src/main/java/com/github/muhrifqii/parserss/RSSObject.kt
|
muhrifqii
| 203,285,159
| false
| null |
package com.github.muhrifqii.parserss
data class RSSFeedObject(
override var version: RSSVersion = RSSVersion.TBD,
override var title: String? = null,
override var description: String? = null,
override var link: String? = null,
override var publishDate: String? = null,
override var lastBuildDate: String? = null,
override var language: String? = null,
override var image: RSSImage? = null,
override var copyright: String? = null,
override var rights: String? = null,
override var items: MutableList<RSSItem> = mutableListOf()
) : RSSFeed
data class RSSItemObject(
override var title: String? = null,
override var description: String? = null,
override var link: String? = null,
override var publishDate: String? = null,
override var guId: GUId? = null,
override var media: MutableList<RSSMedia> = mutableListOf(),
override var author: String? = null,
override var category: MutableList<RSSCategory> = mutableListOf(),
override var comments: String? = null
) : RSSItem
data class RSSImageObject(
override var url: String = "",
override var link: String? = null,
override var title: String? = null
) : RSSImage
data class RSSMediaObject(
override var medium: MediaType = MediaType.Unspecified,
override var url: String = "",
override var width: Int = 0,
override var height: Int = 0,
override var credit: String? = null,
override var description: String? = null
) : RSSMedia
data class RSSCategoryObject(
override var domain: String?,
override var name: String
) : RSSCategory
| 2
|
Kotlin
|
1
| 17
|
c38d56d4567ded6d5bc6c6d532afc370f5e898c0
| 1,604
|
ParseRSS
|
MIT License
|
src/main/kotlin/com/deflatedpickle/faosdance/gui/settings/general/RotationCategory.kt
|
DeflatedPickle
| 151,769,595
| false
| null |
package com.deflatedpickle.faosdance.gui.settings.general
import com.deflatedpickle.faosdance.util.GlobalValues
import com.deflatedpickle.faosdance.gui.settings.SettingsDialog
import com.deflatedpickle.faosdance.util.Lang
import java.awt.Frame
import java.awt.GridBagLayout
import javax.swing.*
import kotlin.math.roundToInt
class RotationCategory(owner: Frame, val settings: SettingsDialog) : JPanel() {
private val gridBagLayout = GridBagLayout()
var zRotationWidgets: Triple<JComponent, JSlider, JSpinner>? = null
init {
this.layout = gridBagLayout
this.border = BorderFactory.createTitledBorder(Lang.bundle.getString("settings.rotation"))
// TODO: Add 3D rotation
zRotationWidgets = GlobalValues.addComponentSliderSpinner<Int>(
this,
this.layout as GridBagLayout,
JLabel("${Lang.bundle.getString("settings.rotation.z")}:"),
GlobalValues.optionsMap.getMap("sprite")!!.getMap("rotation")!!.getOption<Int>("z")!!,
360,
0
).apply {
third.addChangeListener {
GlobalValues.optionsMap.getMap("sprite")!!.getMap("rotation")!!.setOption("z", when {
(it.source as JSpinner).model.value is Int -> (it.source as JSpinner).model.value as Int
(it.source as JSpinner).model.value is Double -> ((it.source as JSpinner).model.value as Double).roundToInt()
else -> 0
})
GlobalValues.updateScripts("sprite.rotation.z", GlobalValues.optionsMap.getMap("sprite")!!.getMap("rotation")!!.getOption<Int>("z")!!)
}
}
this.settings.widgets.add(zRotationWidgets!!.first)
this.settings.widgets.add(zRotationWidgets!!.second)
this.settings.widgets.add(zRotationWidgets!!.third)
}
}
| 6
|
Kotlin
|
2
| 25
|
cef3d0d44cdc340c337855c0c1b40f028d1f5ca3
| 1,852
|
FAOSDance
|
MIT License
|
buildSrc/src/main/kotlin/Utils.kt
|
TheFloodDragon
| 729,364,851
| false
|
{"Kotlin": 45172}
|
import java.net.URL
val currentISODate: String
get() = isoInstantFormat.format(System.currentTimeMillis())
val systemUserName: String
get() = System.getProperty("user.name")
val systemOS: String
get() = System.getProperty("os.name").lowercase()
val systemIP: String
get() = URL("http://ipinfo.io/ip").readText()
| 0
|
Kotlin
|
0
| 1
|
3ef3f7aa71f8eb75013a2ccec66235cd4aaf8d32
| 331
|
Script-Artemisia
|
MIT License
|
app/src/main/java/com/starts/movieguide/network/MovieClient.kt
|
ZhaoSiBo
| 278,286,809
| false
| null |
package com.starts.movieguide.network
import com.skydoves.sandwich.ApiResponse
import com.skydoves.sandwich.request
import com.starts.movieguide.model.MoviePopularResponse
/**
*文件描述:.
*作者:Created by Administrator on 2020/9/19.
*版本号:1.0
*/
class MovieClient(private val movieService: MovieService) {
fun requestPopularMovieList(
page: Int,
onResult: (response: ApiResponse<MoviePopularResponse>) -> Unit
) {
movieService.requestPopularMovieList(page)
.request(onResult)
}
}
| 0
|
Kotlin
|
0
| 1
|
0b663068a9eb1df32f76f60272d2bc3579e47196
| 529
|
MovieGuide
|
MIT License
|
model/src/commonMain/kotlin/com/mindovercnc/model/Point3D.kt
|
85vmh
| 543,628,296
| false
|
{"Kotlin": 956103, "C++": 75148, "Java": 7157, "Makefile": 2742, "HTML": 419, "Shell": 398, "CSS": 108}
|
package com.mindovercnc.model
data class Point3D(
val x: Float,
val y: Float,
val z: Float,
)
| 0
|
Kotlin
|
1
| 3
|
5cf42426895ba8691c9b53ba1b97c274bbdabc07
| 107
|
mindovercnclathe
|
Apache License 2.0
|
app/src/main/java/master/mb/texify/ui/compose/MainScreen.kt
|
mbednarek98
| 699,059,736
| false
|
{"Kotlin": 23666}
|
package master.mb.texify.ui.compose
import android.content.Context
import android.graphics.drawable.shapes.Shape
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.CameraSelector
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
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.layout.wrapContentHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.BottomAppBar
import androidx.compose.material.Button
import androidx.compose.material.ExtendedFloatingActionButton
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Face
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.MultiplePermissionsState
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import master.mb.texify.ui.theme.*
import master.mb.texify.R
import master.mb.texify.fileproviders.ComposeFileProvider
import master.mb.texify.ui.theme.Shapes
import master.mb.texify.viewmodels.TranslationViewModel
import master.mb.texify.ui.theme.TexifyTheme
import master.mb.texify.viewmodels.ImageViewModel
// TODO: JavaDoc for this function
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun MainScreen(mainViewModel: TranslationViewModel = viewModel()) {
val multiplePermissionsState = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> {
rememberMultiplePermissionsState(
listOf(
android.Manifest.permission.READ_MEDIA_IMAGES,
android.Manifest.permission.CAMERA,
android.Manifest.permission.INTERNET,
)
)
}
else -> {
rememberMultiplePermissionsState(
listOf(
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.CAMERA,
android.Manifest.permission.INTERNET,
)
)
}
}
val uiState by mainViewModel.uiState.collectAsState()
when {
multiplePermissionsState.allPermissionsGranted -> {
MainLayout(
excText = uiState.captureText,
tranText = uiState.translatedText,
onUriChange = {mainViewModel.changeImageValue(uri = it)},
onImageChange = {mainViewModel.getTextFromImage(context = it)})
}
else -> CameraDeniedLayout(
multiplePermissionsState = multiplePermissionsState
) { mainViewModel.getTextToShowGivenPermissions(
multiplePermissionsState.revokedPermissions,
multiplePermissionsState.shouldShowRationale
)
}
}
}
// TODO: JavaDoc for this function
@Composable
fun MainLayout(imageViewModel: ImageViewModel = viewModel(),
excText: String,
tranText: String,
onUriChange : (Uri) -> Unit,
onImageChange: (Context) -> Unit) {
val uiState by imageViewModel.uiState.collectAsState()
val context = LocalContext.current
val imagePicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetContent(),
onResult = { uri ->
imageViewModel.onImageSelected(uri)
if (uri != null) {
onUriChange(uri)
onImageChange(context)
}
}
)
val cameraLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.TakePicture(),
onResult = { success ->
imageViewModel.onImageCaptured(success)
onImageChange(context)
}
)
Scaffold(topBar = { TopAppBar(title = {
Text("Textify")
}, actions = {
IconButton(
modifier = Modifier.padding(12.dp),
onClick = { /*TODO: To SettingsActivity*/ }) {
Icon(
modifier = Modifier.size(36.dp),
imageVector = Icons.Default.Settings,
contentDescription = "Settings"
)
}
})} ,
floatingActionButton = {
Column {
ExtendedFloatingActionButton(
backgroundColor = Purple500,
onClick = { val uri = ComposeFileProvider.getImageUri(context)
onUriChange(uri)
imageViewModel.onCameraClick(uri,cameraLauncher) },
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_camera_24),
contentDescription = "Camera"
)
},
text = { Text("Camera") }
)
Spacer(modifier = Modifier.height(16.dp))
ExtendedFloatingActionButton(
backgroundColor = Purple500,
onClick = { imagePicker.launch("image/*") },
icon = {
Icon( painter = painterResource(id = R.drawable.ic_library_add_24),
contentDescription = "Library"
)
},
text = { Text("Library ") }
)
}
}
, content = {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(it)
.fillMaxSize()
.verticalScroll(rememberScrollState())
.height(1000.dp)
) {
Box(modifier = Modifier
.wrapContentHeight(align = Alignment.CenterVertically)
.align(Alignment.CenterHorizontally)
.clip(RoundedCornerShape(32.dp)).size(350.dp)){
if (uiState.hasImage && uiState.imageUri != null) {
AsyncImage(
model = uiState.imageUri,
modifier = Modifier
.background(color = Color.LightGray)
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.size(350.dp),
contentDescription = "Selected Image"
)
}
}
Spacer(modifier = Modifier.height(32.dp))
Text(fontWeight = FontWeight.Bold,
text = "Extracted from Image")
Box(modifier = Modifier
.width(350.dp)
.padding(8.dp)
.align(Alignment.CenterHorizontally)){
Text(modifier = Modifier.align(Alignment.Center),
text = excText)
}
Spacer(modifier = Modifier.height(16.dp))
Text(fontWeight = FontWeight.Bold,
text = "Translated Text")
Box(modifier = Modifier
.width(350.dp)
.padding(8.dp)
.align(Alignment.CenterHorizontally)){
Text(modifier = Modifier.align(Alignment.Center),
text = tranText)
}
Spacer(modifier = Modifier.height(32.dp))
} })
}
// TODO: JavaDoc for this function
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun CameraDeniedLayout(
multiplePermissionsState: MultiplePermissionsState,
getShowPermissionText: () -> String
){
Column(
modifier = Modifier
.fillMaxSize()
.wrapContentHeight(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(textAlign = TextAlign.Center,
modifier = Modifier.padding(16.dp),
text = getShowPermissionText())
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = { multiplePermissionsState.launchMultiplePermissionRequest() }) {
Text("Request permission")
}
}
}
/**
* Displays a camera preview using the provided CameraX API.
* Uses 'AndroidView' to integrate CameraPreview as there isn't a build in implementation for it in Android Compose.
*
* @param modifier The modifier for styling and positioning the camera preview.
* @param cameraSelector The camera selector to choose the desired camera (default is the back camera).
* @param scaleType The scale type for the preview view (default is FILL_CENTER).
*/
@Composable
fun CameraPreview(
modifier: Modifier = Modifier,
cameraSelector: CameraSelector = CameraSelector.DEFAULT_BACK_CAMERA,
scaleType: PreviewView.ScaleType = PreviewView.ScaleType.FILL_CENTER,
) {
val lifecycleOwner = LocalLifecycleOwner.current
val context = LocalContext.current
val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
val previewView = remember { PreviewView(context).apply { this.scaleType = scaleType } }
AndroidView(
modifier = modifier.size(130.dp),
factory = { previewView }
) {
cameraProviderFuture.addListener(
{
val cameraProvider = cameraProviderFuture.get()
val preview = androidx.camera.core.Preview.Builder().build().also {
it.setSurfaceProvider(previewView.surfaceProvider)
}
try {
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(
lifecycleOwner, cameraSelector, preview
)
} catch (exc: Exception) {
Log.e("CameraPreview", "Use case binding failed", exc)
}
},
ContextCompat.getMainExecutor(context)
)
}
}
/**
* Displays a settings button.
*
* @param modifier The modifier to be applied to the settings button.
*/
@Composable
fun SettingsButton(modifier: Modifier){
IconButton(
modifier = modifier.padding(12.dp),
onClick = { /*TODO: To SettingsActivity*/ }) {
Icon(
modifier = Modifier.size(36.dp),
imageVector = Icons.Default.Settings,
contentDescription = "Icon",
tint = Color.Black,
)
}
}
| 0
|
Kotlin
|
0
| 0
|
d6a1bd3ec9a251d5f4ca05b12f80988dfa7c145c
| 12,963
|
Textify
|
MIT License
|
domain/src/main/java/io/genry/template/domain/usecases/CreateNewItemUseCase.kt
|
wookoowooko
| 762,817,361
| false
|
{"Kotlin": 36851}
|
package io.genry.template.domain.usecases
import io.genry.template.domain.models.ItemModel
import io.genry.template.domain.repositories.IDataSource
import javax.inject.Inject
class CreateNewItemUseCase @Inject constructor (
private val iDataSource: IDataSource
) {
suspend fun execute(item: ItemModel) = iDataSource.createNewItem(item)
}
| 0
|
Kotlin
|
0
| 0
|
f8aeef9fb373ae0e7c43a5554454008cae176838
| 347
|
Template_Jetpack_Compose_CleanArchitecture_MultiModule_MVVM_ROOM_CRUD_Destinations_Dagger_Hilt
|
MIT License
|
src/main/kotlin/mathlingua/frontend/chalktalk/phase2/ast/clause/TupleNode.kt
|
DominicKramer
| 203,428,613
| false
| null |
/*
* Copyright 2020 The MathLingua Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 mathlingua.frontend.chalktalk.phase2.ast.clause
import mathlingua.frontend.chalktalk.phase1.ast.Inlineable
import mathlingua.frontend.chalktalk.phase1.ast.Phase1Node
import mathlingua.frontend.chalktalk.phase1.ast.Tuple
import mathlingua.frontend.chalktalk.phase2.ast.DEFAULT_TUPLE
import mathlingua.frontend.chalktalk.phase2.ast.common.ZeroPartNode
import mathlingua.frontend.chalktalk.phase2.ast.validateByInlineableTransform
import mathlingua.frontend.support.ParseError
internal data class TupleNode(
val tuple: Tuple,
override val row: Int,
override val column: Int,
override val isInline: Boolean
) : ZeroPartNode(tuple), Target, Inlineable
internal fun isTuple(node: Phase1Node) = node is Tuple
internal fun validateTupleNode(
node: Phase1Node, errors: MutableList<ParseError>, isInline: Boolean
): TupleNode =
validateByInlineableTransform(
node = node.resolve(),
errors = errors,
default = DEFAULT_TUPLE,
message = "Expected a tuple",
isInline = isInline,
transform = { it as? Tuple },
builder = ::TupleNode)
| 4
|
Kotlin
|
0
| 67
|
c264bc61ac7d9e520018f2652b110c4829876c82
| 1,718
|
mathlingua
|
Apache License 2.0
|
src/Day01.kt
|
robinpokorny
| 572,434,148
| false
| null |
typealias Backpack = List<Int>
private fun parse(input: String): List<Backpack> = input
.split("\n\n")
.map { it.lines().map(String::toInt) }
private fun sumOfLargestBackpack(input: List<Backpack>): Int = input
.maxOf { it.sum() }
private fun sumOf3LargestBackpacks(input: List<Backpack>): Int = input
.map { it.sum() }
.sorted()
.takeLast(3)
.sum()
fun main() {
val input = parse(readDayInput(1).joinToString("\n"))
val testInput = parse(rawTestInput)
// PART 1
assertEquals(sumOfLargestBackpack(testInput), 24000)
println("Part1: ${sumOfLargestBackpack(input)}")
// PART 2
assertEquals(sumOf3LargestBackpacks(testInput), 45000)
println("Part2: ${sumOf3LargestBackpacks(input)}")
}
private val rawTestInput = """
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
""".trimIndent()
| 0
|
Kotlin
|
0
| 3
|
56a108aaf90b98030a7d7165d55d74d2aff22ecc
| 852
|
advent-of-code-2022
|
MIT License
|
core/network/src/main/java/com/griffin/core/network/source/user/UserDataSource.kt
|
Chen-Xi-g
| 769,860,561
| false
|
{"Kotlin": 241849}
|
package com.griffin.core.network.source.user
import com.griffin.core.data.model.Resource
/**
* 用户数据仓库
*/
interface UserDataSource {
/**
* 用户登录
*
* @param code 验证码内容
* @param password 密码
* @param username 用户名
* @param uuid 验证码uuid
*/
suspend fun login(code: String, password: String, username: String, uuid: String): Resource<String>
/**
* 用户注册
*
* @param code 验证码内容
* @param email 邮箱
* @param password 密码
* @param username 用户名
* @param uuid 验证码uuid
*/
suspend fun register(code: String, email: String, password: String, username: String, uuid: String): Resource<String>
/**
* 忘记密码
*
* @param code 验证码内容
* @param confirmPassword 确认密码
* @param password 密码
* @param username 用户名
* @param uuid 验证码uuid
*/
suspend fun forgetPassword(code: String, confirmPassword: String, password: String, username: String, uuid: String): Resource<String>
/**
* 激活账户
*
* @param code 验证码内容
* @param username 用户名
* @param uuid 验证码uuid
*/
suspend fun activate(code: String, username: String, uuid: String): Resource<String>
}
| 0
|
Kotlin
|
0
| 1
|
ab3507211daafe8c117bac67d6eedf03473821d4
| 1,186
|
VerveLedger
|
MIT License
|
s21_bootcamp/06_team_00/src/SomethingCalc/app/src/main/java/com/example/something_calc/navigation/SomethingCalcNavHost.kt
|
Hasuk1
| 740,111,124
| false
|
{"Kotlin": 208642}
|
package com.example.something_calc.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.core.utility.AppScreens
import com.example.feature.circles_2.ui.CirclesScreen
import com.example.feature.speech.ui.SpeechScreen
import com.example.prime_numbers.ui.PrimeScreen
import com.example.something_calc.ui.SomethingCalcApp
import com.example.thermohydrometer.ui.ThermohydrometerScreen
@Composable
fun SomethingCalcNavHost(navController: NavHostController, startRoute: String) {
NavHost(navController = navController, startDestination = startRoute) {
composable(AppScreens.MENU.route) {
SomethingCalcApp(navController)
}
composable(AppScreens.CIRCLE.route) {
CirclesScreen {
navController.navigateUp()
}
}
composable(AppScreens.PRIMENUMBERS.route) {
PrimeScreen {
navController.navigateUp()
}
}
composable(AppScreens.THERMOHYDROMETER.route) {
ThermohydrometerScreen {
navController.navigateUp()
}
}
composable(AppScreens.SPEECH.route) {
SpeechScreen {
navController.navigateUp()
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
0b1a69f561bbff5f7490554ed3678284469c16f3
| 1,266
|
kotlin_projects
|
MIT License
|
platform/backend/api/src/integrationTest/kotlin/io/hamal/api/web/exec/ListExecsControllerTest.kt
|
hamal-io
| 622,870,037
| false
|
{"Kotlin": 1744717, "C": 1398401, "TypeScript": 54320, "C++": 40651, "Lua": 36419, "Makefile": 11728, "Java": 7564, "CMake": 2881, "JavaScript": 1532, "HTML": 694, "Shell": 456, "CSS": 118}
|
package io.hamal.api.web.exec
import io.hamal.lib.domain.vo.ExecId
import io.hamal.lib.http.HttpStatusCode.Ok
import io.hamal.lib.http.SuccessHttpResponse
import io.hamal.lib.sdk.api.ApiExecList
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.*
import org.junit.jupiter.api.Test
internal class ListExecsControllerTest : BaseExecControllerTest() {
@Test
fun `No execs`() {
val response = httpTemplate.get("/v1/groups/{groupId}/execs")
.path("groupId", testGroup.id)
.execute()
assertThat(response.statusCode, equalTo(Ok))
require(response is SuccessHttpResponse)
val result = response.result(ApiExecList::class)
assertThat(result.execs, empty())
}
@Test
fun `Single exec`() {
val execId = awaitCompleted(createAdhocExec()).id(::ExecId)
val response = httpTemplate.get("/v1/groups/{groupId}/execs")
.path("groupId", testGroup.id)
.execute()
assertThat(response.statusCode, equalTo(Ok))
require(response is SuccessHttpResponse)
with(response.result(ApiExecList::class)) {
assertThat(execs, hasSize(1))
with(execs.first()) {
assertThat(id, equalTo(execId))
}
}
}
@Test
fun `Limit execs`() {
awaitCompleted(
IntRange(1, 50).map { createAdhocExec() }
)
val response = httpTemplate.get("/v1/groups/{groupId}/execs")
.path("groupId", testGroup.id)
.parameter("limit", 42)
.execute()
assertThat(response.statusCode, equalTo(Ok))
require(response is SuccessHttpResponse)
with(response.result(ApiExecList::class)) {
assertThat(execs, hasSize(42))
}
}
@Test
fun `Skip and limit execs`() {
val requests = awaitCompleted(IntRange(1, 100).map { createAdhocExec() })
val fortyFifthRequest = requests.drop(44).take(1).first()
val fortySixthRequest = requests.drop(45).take(1).first()
val response = httpTemplate.get("/v1/groups/{groupId}/execs")
.path("groupId", testGroup.id)
.parameter("limit", 1)
.parameter("after_id", fortySixthRequest.id)
.execute()
assertThat(response.statusCode, equalTo(Ok))
require(response is SuccessHttpResponse)
with(response.result(ApiExecList::class)) {
assertThat(execs, hasSize(1))
execs.forEach { exec ->
assertThat(exec.id, equalTo(fortyFifthRequest.id(::ExecId)))
}
}
}
}
| 6
|
Kotlin
|
0
| 0
|
6c7f5cc645ba67fb85df20d9a5d2e18372a012f4
| 2,650
|
hamal
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/org/zlobste/spotter/util/validator/PasswordValidator.kt
|
zlobste
| 372,320,932
| false
| null |
package org.tokend.muna.util.validator
/**
* Validator of password strength
*/
object PasswordValidator :
RegexValidator("^.{6,}$")
| 0
|
Kotlin
|
0
| 0
|
e5135d0da1c14abd2eba906022a3d6ecc3d473bf
| 138
|
spotter-android-client
|
MIT License
|
data/home/src/main/java/com/example/securenotes/data/home/ByteArrayExtensions.kt
|
emresarincioglu
| 742,472,669
| false
|
{"Kotlin": 146624}
|
package com.example.securenotes.data.home
fun Int.toByteArray() = ByteArray(4) { i ->
(this ushr (i * 8)).toByte()
}
fun ByteArray.toInt(): Int {
var result = 0
repeat(4) { i ->
result = result or (this[i].toInt() and 0xFF shl (i * 8))
}
return result
}
/**
* @param index End of the first part (exclusive)
*/
fun ByteArray.split(index: Int): Pair<ByteArray?, ByteArray?> {
return if (index <= 0) {
null to this
} else if (index >= size) {
this to null
} else {
copyOfRange(0, index) to copyOfRange(index, size)
}
}
| 0
|
Kotlin
|
0
| 0
|
059115549d708dedd39b22bdcf7b654bc54ce8bc
| 589
|
secure-notes-app
|
MIT License
|
test/com/rti/charisma/api/content/serialiser/PageConversionsTest.kt
|
rti-international-charisma
| 343,861,997
| false
| null |
package com.rti.charisma.api.content.serialiser
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.rti.charisma.api.content.*
import com.rti.charisma.api.fixtures.PageContentFixture
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class PageConversionsTest {
@Test
fun `it should serialise page content with video section `() {
val pageContent = PageContentFixture.pageWithVideoSection("published")
val json = jacksonObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(pageContent)
assertEquals(PageContentFixture.pageWithVideoSectionResponseJson(), json?.replace("\r", ""))
}
@Test
fun `it should ignore page content with empty image fields `() {
val pageContent = givenPageWithEmptyUrls()
val json = jacksonObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(pageContent)
assertEquals(expectedJsonWithNullAssets(), json?.replace("\r", ""))
}
@Test
fun `it should ignore page content with no image fields `() {
val pageContent = givenPageWithNoUrls()
val json = jacksonObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(pageContent)
assertEquals(expectedJsonWithNullAssets(), json?.replace("\r", ""))
}
@Test
fun `it should serialise page content with counselling modules`() {
val pageContent = PageContentFixture.pageWithCounsellingModules("published")
val json = jacksonObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(pageContent)
assertEquals(PageContentFixture.pageWithCounsellingResponseJson(), json.replace("\r", ""))
}
@Test
fun `it should serialise only published page`() {
val pageContent = PageContentFixture.pageWithVideoSection("archived")
val json = jacksonObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(pageContent)
assertEquals("""{ }""", json)
}
@Test
fun `it should return empty page for no status`() {
val pageContent = PageContentFixture.pageWithVideoSection("")
val json = jacksonObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(pageContent)
assertEquals("""{ }""", json?.replace("\r", ""))
}
@Test
fun `it should serialise minimal content - no video and counselling modules`() {
val pageContent = PageContentFixture.withNoVideoSectionAndSteps("published")
val json = jacksonObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(pageContent)
assertEquals(PageContentFixture.pageWithoutVideoAndStepsJson(), json.replace("\r", ""))
}
private fun givenPageWithEmptyUrls(): Page {
val heroImage = HeroImage("title", "intro", "")
val image = PageImage(ImageFile("", "title"))
val document = PageDocuments(Document("", "title"))
val videoSection = VideoSection(
videos = listOf(
PageVideo(
videoUrl = "",
youtubeVideoUrl = "",
videoImage = "",
actionText = "",
actionLink = "",
isPrivate = false
)
)
)
return Page(
"id", null, null, null,
null, "Published",
heroImage,
"This is caption for completed test",
"This is caption for partially completed test",
listOf(image),
listOf(document),
videoSection,
null,
null,
null,
null
)
}
private fun givenPageWithNoUrls(): Page {
val heroImage = HeroImage("title", "intro", "")
val image = PageImage(ImageFile("", "title"))
val document = PageDocuments(Document("", "title"))
val videoSection = VideoSection(
videos = listOf(
PageVideo(
videoUrl = null,
youtubeVideoUrl = null,
videoImage = null,
actionText = "",
actionLink = "",
isPrivate = false
)
)
)
return Page(
"id", null, null, null,
null, "Published",
heroImage,
"This is caption for completed test",
"This is caption for partially completed test",
listOf(image),
listOf(document),
videoSection,
null,
null,
null,
null
)
}
private fun expectedJsonWithNullAssets() = """{
"title" : null,
"introduction" : null,
"description" : null,
"summary" : null,
"heroImageCaptionTestComplete" : "This is caption for completed test",
"heroImageCaptionTestIncomplete" : "This is caption for partially completed test",
"heroImage" : {
"title" : "title",
"introduction" : "intro",
"imageUrl" : null
},
"images" : [ {
"title" : "title",
"imageUrl" : null
} ],
"documents" : [ {
"title" : "title",
"documentUrl" : null
} ],
"videoSection" : {
"introduction" : "",
"summary" : "",
"videos" : [ {
"title" : "",
"description" : "",
"videoUrl" : null,
"youtubeVideoUrl" : null,
"videoImage" : null,
"actionText" : "",
"actionLink" : "",
"isPrivate" : false
} ]
}
}"""
}
| 0
|
Kotlin
|
0
| 0
|
57ef1ab083fac87ef41b5536ce05149a9ab761ad
| 5,513
|
Application-Programming-Interface
|
Apache License 2.0
|
src/main/kotlin/com/jaffa/rpc/lib/common/ProtocolController.kt
|
dredwardhyde
| 146,790,214
| false
| null |
package com.jaffa.rpc.lib.common
import org.springframework.context.ApplicationContext
interface ProtocolController {
fun loadProtocolProperties()
fun prepareServiceRegistration(context: ApplicationContext)
fun initialize(context: ApplicationContext)
fun shutdown()
}
| 0
|
Kotlin
|
2
| 6
|
42409ca5a5e224d80753d36401fd0d871ebbbc25
| 286
|
jaffa-rpc-library
|
Apache License 2.0
|
src/main/kotlin/no/nav/familie/ef/iverksett/brev/DistribuerJournalpostResponseTo.kt
|
navikt
| 357,821,728
| false
|
{"Kotlin": 810975, "Gherkin": 73692, "Dockerfile": 186}
|
package no.nav.familie.ef.iverksett.brev
data class DistribuerJournalpostResponseTo(
val bestillingsId: String,
)
| 0
|
Kotlin
|
0
| 0
|
d29e3163efac8cf9075b92795c4002797c713bb9
| 119
|
familie-ef-iverksett
|
MIT License
|
CMPE451/Android/app/src/main/java/com/example/carousel/AddCardFragment.kt
|
oztasoi
| 446,209,037
| false
|
{"Jupyter Notebook": 6340924, "JavaScript": 731585, "CSS": 625767, "Python": 401797, "Kotlin": 270488, "Java": 175718, "C++": 94490, "TeX": 88758, "HTML": 50873, "Prolog": 31901, "MATLAB": 12390, "Assembly": 8243, "Racket": 6521, "Shell": 1935, "QMake": 1422, "CMake": 1123, "Dockerfile": 638, "Makefile": 253}
|
package com.example.carousel
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.Fragment
import com.example.carousel.application.ApplicationContext
import com.example.carousel.map.ApiCaller
import com.example.carousel.map.ApiClient
import com.example.carousel.pojo.*
import kotlinx.android.synthetic.main.fragment_add_address.view.*
import kotlinx.android.synthetic.main.fragment_add_address.view.back_button
import kotlinx.android.synthetic.main.fragment_add_address.view.save_button
import kotlinx.android.synthetic.main.fragment_add_card.view.*
class AddCardFragment : Fragment() {
var type = "GUEST"
var isFromOrder = false
override fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
arguments?.let { isFromOrder = it.getBoolean("isFromOrder") }
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
type = ApplicationContext.instance.whoAmI().toString()
return inflater.inflate(R.layout.fragment_add_card, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
getActivity()?.getWindow()?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
view.back_button.setOnClickListener{
val fragment = when(isFromOrder){ true -> OrderFragment() false -> Settings()}
activity?.supportFragmentManager?.beginTransaction()
?.replace(R.id.activity_main_nav_host_fragment, fragment)
?.commit()
}
view.save_button.setOnClickListener {
val cardName = view.card_name.text.toString()
val cardNumber = view.card_number.text.toString()
val cardDate = view.card_date.text.toString()
val cardCVC = view.card_cvc.text.toString()
var id: String
var name: String
var lastName: String
var email: String
var isSuspended: Boolean
var isActive: Boolean
var shoppingLists: List<List<Product>>?
var orders: List<ExampleObject>?
var cart: List<ExampleObject>?
var addresses: List<Address>?
var telephoneNumber: String?
var birthday: String?
var creditCards: List<Card>?
val apiCaller: ApiCaller<ResponseCustomerMe2> = ApiCaller(activity)
apiCaller.Caller = ApiClient.getClient.customerMe2()
apiCaller.Success = { it ->
if (it != null) {
activity?.runOnUiThread(Runnable { //Handle UI here
id = it.data.id
name = it.data.name
lastName = it.data.lastName
email = it.data.email
isSuspended = it.data.isSuspended
isActive = it.data.isActive
shoppingLists = it.data.shoppingLists
orders = it.data.orders
cart = it.data.cart
addresses = it.data.addresses
telephoneNumber = it.data.telephoneNumber
birthday = it.data.birthday
val newCard = Card(
cardNumber,
cardCVC,
cardDate,
cardName
)
creditCards = it.data.creditCards
var tempCreditCards = creditCards?.toMutableList()
if (tempCreditCards != null) {
tempCreditCards.add(newCard)
}else{
tempCreditCards = mutableListOf<Card>()
tempCreditCards.add(newCard)
}
creditCards = tempCreditCards.toList()
var newData = DataCustomerMe2(
id,
name,
lastName,
email,
isSuspended,
isActive,
shoppingLists,
orders,
cart,
addresses!!,
telephoneNumber,
birthday,
creditCards
)
val apiCallerPatch: ApiCaller<ResponseCustomerMe2> = ApiCaller(activity)
apiCallerPatch.Caller = ApiClient.getClient.customerUpdate2(newData)
apiCallerPatch.Success = { it ->
if (it != null) {
activity?.runOnUiThread(Runnable { //Handle UI here
val fragment = when(isFromOrder){ true -> OrderFragment() false -> Settings()}
activity?.supportFragmentManager?.beginTransaction()
?.replace(R.id.activity_main_nav_host_fragment, fragment)
?.commit()
})
}
}
apiCallerPatch.Failure = {}
apiCallerPatch.run()
})
}
}
apiCaller.Failure = {}
apiCaller.run()
}
}
}
| 0
|
Jupyter Notebook
|
0
| 0
|
a3e3a39efc9fed09db7290227848552f9604befa
| 5,778
|
bachelor-projects
|
MIT License
|
src/test/kotlin/io/github/yearnlune/excel/TestExcelCreator.kt
|
yearnlune
| 503,232,925
| false
|
{"Kotlin": 53449}
|
package io.github.yearnlune.excel
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.xssf.streaming.SXSSFWorkbook
@ExcelCreator
class TestExcelCreator : ExcelCreatable {
override fun createExcel(data: ExcelMeta): Workbook {
return SXSSFWorkbook()
}
}
| 0
|
Kotlin
|
0
| 0
|
9e61bf92dc4e541bcb0637087a4ee9d6c2a96e34
| 285
|
excel-exporter
|
MIT License
|
aws-runtime/regions/common/src/aws/sdk/kotlin/runtime/regions/providers/DefaultAwsRegionProviderChain.kt
|
archdsp
| 412,071,077
| true
|
{"Kotlin": 546074, "Python": 2871, "Shell": 372}
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
package aws.sdk.kotlin.runtime.regions.providers
/**
* [AwsRegionProvider] that looks for region in this order:
* 1. Check `aws.region` system property (JVM only)
* 2. Check the `AWS_REGION` environment variable (JVM, Node, Native)
* 3. Check the AWS config files/profile for region information
* 4. If running on EC2, check the EC2 metadata service for region
*/
public expect class DefaultAwsRegionProviderChain public constructor() : AwsRegionProvider
| 0
| null |
0
| 0
|
ce7efeaea6aa7762976418bdf99f5775f9bf25e8
| 584
|
aws-sdk-kotlin
|
Apache License 2.0
|
bot/storage-mongo/target/generated-sources/kapt/compile/fr/vsct/tock/bot/mongo/NlpStatsColId_.kt
|
Bertrand
| 141,590,702
| true
|
{"Kotlin": 2169311, "TypeScript": 350752, "HTML": 141041, "CSS": 32397, "JavaScript": 5174, "Shell": 1591}
|
package fr.vsct.tock.bot.mongo
import fr.vsct.tock.bot.engine.action.Action
import fr.vsct.tock.bot.engine.dialog.Dialog
import kotlin.String
import kotlin.Suppress
import kotlin.collections.Collection
import kotlin.reflect.KProperty1
import org.litote.kmongo.Id
import org.litote.kmongo.property.KCollectionPropertyPath
import org.litote.kmongo.property.KPropertyPath
internal class NlpStatsColId_<T>(previous: KPropertyPath<T, *>?, property: KProperty1<*, NlpStatsColId?>) : KPropertyPath<T, NlpStatsColId?>(previous,property) {
val actionId: KProperty1<T, Id<Action>?>
get() = org.litote.kmongo.property.KPropertyPath(this,NlpStatsColId::actionId)
val dialogId: KProperty1<T, Id<Dialog>?>
get() = org.litote.kmongo.property.KPropertyPath(this,NlpStatsColId::dialogId)
companion object {
val ActionId: KProperty1<NlpStatsColId, Id<Action>?>
get() = NlpStatsColId::actionId
val DialogId: KProperty1<NlpStatsColId, Id<Dialog>?>
get() = NlpStatsColId::dialogId}
}
internal class NlpStatsColId_Col<T>(
previous: KPropertyPath<T, *>?,
property: KProperty1<*, Collection<NlpStatsColId>?>,
additionalPath: String? = null
) : KCollectionPropertyPath<T, NlpStatsColId?>(previous,property,additionalPath) {
override val arrayProjection: NlpStatsColId_Col<T>
@Suppress("UNCHECKED_CAST")
get() = NlpStatsColId_Col(null, this as KProperty1<*, Collection<NlpStatsColId>?>, "$")
val actionId: KProperty1<T, Id<Action>?>
get() = org.litote.kmongo.property.KPropertyPath(this,NlpStatsColId::actionId)
val dialogId: KProperty1<T, Id<Dialog>?>
get() = org.litote.kmongo.property.KPropertyPath(this,NlpStatsColId::dialogId)
}
| 0
|
Kotlin
|
0
| 0
|
eaf43d68e8ab475707faa44d84911db717c74885
| 1,750
|
tock
|
Apache License 2.0
|
MainActivity.kt
|
iffysravioli
| 535,949,840
| false
| null |
package com.example.recyclerview
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
wishList = ArrayList()
recyclerView = findViewById(R.id.rvWishes)
btnSubmit = findViewById(R.id.btnSubmit)
adapter = WishListAdapter(this,wishList)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
val Name = findViewById<EditText>(R.id.etName)
val Price = findViewById<EditText>(R.id.etPrice)
val Link = findViewById<EditText>(R.id.etLink)
Submit_btn.setOnClickListener {
val name = Name.text.toString()
val price = Price.text.toString().toDouble()
val link = Link.text.toString()
wishList.add(Wish("Name: $name","Price: $price", "$link"))
adapter.notifyDataSetChanged()
recyclerView.smoothScrollToPosition(adapter.itemCount - 1)
Link.setText("")
Price.setText("")
Name.setText("")
}
}
}
| 1
|
Kotlin
|
0
| 0
|
bb3d29abf9ff4271583e0f3791ac414a970727a7
| 1,222
|
recyclerview
|
Apache License 2.0
|
Hilt/app/src/main/java/com/kimmandoo/hilt/practice_binds/EngineModule.kt
|
kimmandoo
| 810,895,614
| false
|
{"Kotlin": 177005}
|
package com.kimmandoo.hilt.practice_binds
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
// Binds를 위한 추상 모듈을 만들어 준다
abstract class EngineModule {
// @Binds
// abstract fun bindGasolineEngine(engine: GasolineEngine): Engine
@Binds
abstract fun bindDieselEngine(engine: DieselEngine): Engine
}
| 0
|
Kotlin
|
0
| 0
|
ab1ce23e1dc557ebf56f386c49216cb6239ff6ba
| 427
|
android-drill
|
MIT License
|
formula/src/main/java/com/instacart/formula/internal/Frame.kt
|
instacart
| 171,923,573
| false
| null |
package com.instacart.formula.internal
import com.instacart.formula.Evaluation
/**
* A frame is a representation of state after a process round. After each processing round
* we need to look at what children and updates exist and do a diff.
*/
internal class Frame<Input, State, Output>(
val snapshot: SnapshotImpl<Input, State>,
val evaluation: Evaluation<Output>,
val transitionID: Long,
) {
val input: Input = snapshot.input
val state: State = snapshot.state
}
| 10
|
Kotlin
|
13
| 145
|
8f00606f37c017d60d4356ee8f9f0b464e88cbb5
| 489
|
formula
|
BSD 3-Clause Clear License
|
buffer/src/commonMain/kotlin/org/angproj/io/buf/data/AbstractDataBuffer.kt
|
angelos-project
| 487,995,451
| false
| null |
/**
* Copyright (c) 2022 by <NAME> <<EMAIL>>.
*
* This software is available under the terms of the MIT license. Parts are licensed
* under different terms if stated. The legal terms are attached to the LICENSE file
* and are made available on:
*
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*
* Contributors:
* <NAME> - initial implementation
*/
package org.angproj.io.buf.data
import org.angproj.io.buf.AbstractBuffer
import org.angproj.io.buf.Buffer
import org.angproj.io.buf.BufferOverflowWarning
import org.angproj.io.buf.Endianness
/**
* Abstract base class for all data-buffers.
*
* @constructor
*
* @param size Total size of the buffer.
* @param limit The initial limitation of how far to operate into the buffer. Must never exceed the size.
* @param endianness The initial current endianness of the buffer.
*/
abstract class AbstractDataBuffer internal constructor(
size: Int,
limit: Int,
endianness: Endianness,
) : AbstractBuffer(size, limit, endianness), DataBuffer {
override fun limit(limit: Int) {
require(limit in 0..size)
_limit = limit
}
override fun remaining(position: Int): Int = remaining(this, position)
override fun hasRemaining(position: Int, size: Int) = hasRemaining(this, position, size)
override fun getRetrieveByte(position: Int): Byte {
hasRemaining(this, position, Buffer.BYTE_SIZE)
return readByte(position)
}
override fun getRetrieveUByte(position: Int): UByte {
hasRemaining(this, position, Buffer.UBYTE_SIZE)
return readUByte(position)
}
override fun getRetrieveChar(position: Int): Char {
hasRemaining(this, position, Buffer.CHAR_SIZE)
return readChar(position)
}
override fun getRetrieveShort(position: Int): Short {
hasRemaining(this, position, Buffer.SHORT_SIZE)
return readShort(position)
}
override fun getRetrieveUShort(position: Int): UShort {
hasRemaining(this, position, Buffer.USHORT_SIZE)
return readUShort(position)
}
override fun getRetrieveInt(position: Int): Int {
hasRemaining(this, position, Buffer.INT_SIZE)
return readInt(position)
}
override fun getRetrieveUInt(position: Int): UInt {
hasRemaining(this, position, Buffer.UINT_SIZE)
return readUInt(position)
}
override fun getRetrieveLong(position: Int): Long {
hasRemaining(this, position, Buffer.LONG_SIZE)
return readLong(position)
}
override fun getRetrieveULong(position: Int): ULong {
hasRemaining(this, position, Buffer.ULONG_SIZE)
return readULong(position)
}
override fun getRetrieveFloat(position: Int): Float {
hasRemaining(this, position, Buffer.FLOAT_SIZE)
return readFloat(position)
}
override fun getRetrieveDouble(position: Int): Double {
hasRemaining(this, position, Buffer.DOUBLE_SIZE)
return readDouble(position)
}
internal abstract fun readByte(position: Int): Byte
internal abstract fun readUByte(position: Int): UByte
internal abstract fun readChar(position: Int): Char
internal abstract fun readShort(position: Int): Short
internal abstract fun readUShort(position: Int): UShort
internal abstract fun readInt(position: Int): Int
internal abstract fun readUInt(position: Int): UInt
internal abstract fun readLong(position: Int): Long
internal abstract fun readULong(position: Int): ULong
internal abstract fun readFloat(position: Int): Float
internal abstract fun readDouble(position: Int): Double
companion object {
internal inline fun remaining(buf: DataBuffer, position: Int): Int {
return buf.limit - position + 1
}
internal inline fun hasRemaining(buf: DataBuffer, position: Int, size: Int) {
if (remaining(buf, position) <= size)
throw BufferOverflowWarning()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f5f540d5d894bd08eef7dbf49cae59adf5e789f9
| 4,017
|
angelos-project-buffer
|
MIT License
|
app/src/main/java/com/softcross/eatzy/presentation/splash/SplashContract.kt
|
ErenMlg
| 860,953,275
| false
|
{"Kotlin": 354864}
|
package com.softcross.eatzy.presentation.splash
object SplashContract {
sealed class UiEffect {
data object NavigateToMainScreen : UiEffect()
data object NavigateToIntroduceScreen : UiEffect()
}
}
| 0
|
Kotlin
|
0
| 0
|
f449aefa77a0ff2ccfa31f33ceab0ea75ba86517
| 221
|
Eatzy
|
Apache License 2.0
|
measurements/src/main/java/be/appwise/measurements/units/UnitDuration.kt
|
wisemen-digital
| 349,150,482
| false
|
{"Kotlin": 350139}
|
package be.appwise.measurements.units
import android.icu.util.MeasureUnit
import android.icu.util.TimeUnit
import android.os.Build
import androidx.annotation.RequiresApi
import be.appwise.measurements.converters.UnitConverter
import be.appwise.measurements.converters.UnitConverterLinear
import be.appwise.measurements.isAtLeastO
class UnitDuration(symbol: String, converter: UnitConverter, measureUnit: MeasureUnit? = null) : Dimension(symbol, converter, measureUnit) {
private constructor(symbol: String, coefficient: Double) : this(symbol, UnitConverterLinear(coefficient))
private constructor(symbol: String, coefficient: Double, measureUnit: MeasureUnit?) : this(symbol, UnitConverterLinear(coefficient), measureUnit)
private object Symbol {
const val seconds = "s"
const val minutes = "m"
const val hours = "h"
}
private object Coefficient {
const val seconds = 1.0
const val minutes = 60.0
const val hours = 3600.0
}
companion object {
val seconds: UnitDuration = UnitDuration(Symbol.seconds, Coefficient.seconds)
val minutes: UnitDuration = UnitDuration(Symbol.minutes, Coefficient.minutes)
val hours: UnitDuration = UnitDuration(Symbol.hours, Coefficient.hours)
}
override fun baseUnit(): UnitDuration {
return seconds
}
}
| 26
|
Kotlin
|
4
| 5
|
be64167d99ff62ae62cfa08745d2950158a36856
| 1,360
|
AndroidCore
|
MIT License
|
src/main/kotlin/org/digma/intellij/plugin/ui/list/insights/SlowEndpointPanel.kt
|
doveroni
| 569,591,128
| true
|
{"Java Properties": 3, "YAML": 9, "Gradle Kotlin DSL": 17, "Markdown": 2, "Shell": 1, "Batchfile": 1, "Text": 1, "Ignore List": 3, "Java": 90, "Kotlin": 149, "SVG": 21, "Microsoft Visual Studio Solution": 1, "XML": 20, "C#": 29, "INI": 3, "HTML": 1, "JSON": 2}
|
package org.digma.intellij.plugin.ui.list.insights
import org.digma.intellij.plugin.model.rest.insights.Duration
import org.digma.intellij.plugin.model.rest.insights.SlowEndpointInsight
import org.digma.intellij.plugin.ui.common.Laf
import org.digma.intellij.plugin.ui.common.asHtml
import org.digma.intellij.plugin.ui.common.span
import org.digma.intellij.plugin.ui.list.PanelsLayoutHelper
import java.math.BigDecimal
import java.math.RoundingMode
import javax.swing.JLabel
import javax.swing.JPanel
fun slowEndpointPanel(insight: SlowEndpointInsight, panelsLayoutHelper: PanelsLayoutHelper): JPanel {
val bodyContents = genContent(insight)
val durationLabel = JLabel(evalDuration(insight.median))
val result = createInsightPanel("Slow Endpoint", bodyContents, Laf.Icons.Insight.SLOW, durationLabel, null, panelsLayoutHelper)
result.toolTipText = asHtml(genToolTip(insight))
return result
}
fun genToolTip(insight: SlowEndpointInsight): String {
return """
server processed 50% of requests in less than ${evalDuration(insight.endpointsMedian)}
<br>
server processed 25% of requests in higher than ${evalDuration(insight.endpointsP75)}
"""
}
fun evalDuration(duration: Duration): String {
return "${duration.value}${duration.unit}"
}
fun genContent(insight: SlowEndpointInsight): String {
val pctVal = computePercentageDiff(insight)
return "On average requests are slower than other endpoints by ${span(Laf.Colors.ERROR_RED,pctVal)}"
}
fun computePercentageDiff(insight: SlowEndpointInsight): String {
val decimal = computePercentageDiff(insight.median.raw, insight.endpointsMedianOfMedians.raw)
return "${decimal.toPlainString()}%"
}
fun computePercentageDiff(value: Long, compare: Long): BigDecimal {
val decimal = BigDecimal((value.toDouble() / compare.toDouble() - 1) * 100).setScale(0, RoundingMode.HALF_DOWN)
return decimal
}
| 0
| null |
0
| 0
|
c8b4827c7c48aaffe1135aee03f4ffb8703d8c2f
| 1,892
|
digma-intellij-plugin
|
MIT License
|
src/main/kotlin/com/github/theapache64/ambientide/model/IDE.kt
|
theapache64
| 598,237,118
| false
| null |
package com.github.theapache64.ambientide.model
enum class IDE(
val defaultConfig : String,
val configName : String
) {
AndroidStudio(defaultConfig = "default_android_studio_rules.json", "android_studio_rules.json"),
IntelliJ("default_intellij_idea_rules.json", "intellij_idea_rules.json")
}
| 0
|
Kotlin
|
0
| 3
|
55063b0be8b3152905f4e108ce5dff700892fb16
| 308
|
ambient-IDE
|
Apache License 2.0
|
src/main/kotlin/com/gt/intellij/matlab/psi/MatlabFile.kt
|
GuillaumeTaffin
| 617,636,677
| false
| null |
package com.gt.intellij.matlab.psi
import com.gt.intellij.matlab.language.MatlabFileType
import com.gt.intellij.matlab.language.MatlabLanguage
import com.intellij.extapi.psi.PsiFileBase
import com.intellij.openapi.fileTypes.FileType
import com.intellij.psi.FileViewProvider
class MatlabFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, MatlabLanguage) {
override fun getFileType(): FileType = MatlabFileType.INSTANCE
override fun toString(): String = "Matlab File"
}
| 0
|
Kotlin
|
0
| 0
|
0f2b769471711bf151e88e743862f611c279b6a1
| 492
|
matlab-language-intellij-plugin
|
MIT License
|
app/src/main/java/com/denicks21/contactlist/composables/ImagePicker.kt
|
ndenicolais
| 682,530,051
| false
| null |
package com.denicks21.contactlist.composables
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.denicks21.contactlist.R
import java.io.ByteArrayOutputStream
@Composable
fun ImagePicker(
initialImage: Bitmap? = null,
onPhotoSelected: (Bitmap) -> Unit
) {
val context = LocalContext.current
var image by remember { mutableStateOf(initialImage) }
val launcher =
rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri: Uri? ->
uri?.let {
try {
val bitmap = if (Build.VERSION.SDK_INT < 28) {
MediaStore.Images.Media.getBitmap(context.contentResolver, it)
} else {
val source = ImageDecoder.createSource(context.contentResolver, it)
ImageDecoder.decodeBitmap(source)
}
val compressedBitmap = Bitmap.createScaledBitmap(bitmap, 800, 800, true)
val outputStream = ByteArrayOutputStream()
compressedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream)
val compressedData = outputStream.toByteArray()
val compressedImage =
BitmapFactory.decodeByteArray(compressedData, 0, compressedData.size)
image = compressedImage
onPhotoSelected(compressedImage)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
image?.let {
Image(
bitmap = it.asImageBitmap(),
contentDescription = "Shoes photo",
modifier = Modifier
.size(120.dp)
.clip(CircleShape)
.clickable { launcher.launch("image/*") },
contentScale = ContentScale.Crop
)
} ?: run {
Image(
painter = painterResource(id = R.drawable.github_logo),
contentDescription = "Add photo",
modifier = Modifier
.size(100.dp)
.clickable { launcher.launch("image/*") }
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
1451506e9e99bec1c52a36a4367df7aba02e6d5d
| 3,321
|
ContactList
|
MIT License
|
kotlin-antd/src/main/kotlin/antd/empty/EmptyDsl.kt
|
ricsonhoo
| 251,039,996
| true
|
{"Kotlin": 1197966, "CSS": 29526, "HTML": 6470, "JavaScript": 980}
|
package antd.empty
import react.RBuilder
import react.RHandler
fun RBuilder.empty(handler: RHandler<EmptyProps>) = child(EmptyComponent::class, handler)
| 0
| null |
0
| 0
|
7d92fb58ae96ed7a16d70cb2832284acff023bcf
| 155
|
kotlin-js-wrappers
|
Apache License 2.0
|
app/src/main/java/com/none/tom/exiferaser/ui/images/ImagesFragment.kt
|
szpak-forks
| 272,286,315
| true
|
{"Kotlin": 101863}
|
// Copyright (c) 2018-2020, <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY,WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package com.none.tom.exiferaser.ui.images
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import com.none.tom.exiferaser.R
import com.none.tom.exiferaser.databinding.FragmentImagesBinding
import com.none.tom.exiferaser.reactive.images.ImageSelection
import com.none.tom.exiferaser.reactive.images.ImagesSelection
import com.none.tom.exiferaser.showShortSnackbar
import com.none.tom.exiferaser.ui.BaseFragment
class ImagesFragment : BaseFragment<FragmentImagesBinding>(R.layout.fragment_images) {
private val shareImage = registerForActivityResult(ShareImage()) {}
private val shareImages = registerForActivityResult(ShareImages()) {}
private val createDocument = registerForActivityResult(CreateDocument()) { uri ->
if (uri != null) {
viewModel.saveImage(uri)
} else {
findNavController().navigateUp()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
super.onViewCreated(view, savedInstanceState)
viewModel.imageModified.observe(viewLifecycleOwner, Observer { event ->
event.getContentOrNull()?.let { result ->
if (result.image != null) {
val displayName = viewModel.getImageDisplayNameAndSuffix(result.fileName)
createDocument.launch(displayName to viewModel.getDefaultSavePath())
}
}
})
viewModel.imageSaved.observe(viewLifecycleOwner, Observer { event ->
event.getContentOrNull()?.let { result ->
if (!result.success) {
showShortSnackbar(R.string.image_save_failed)
}
}
})
viewModel.imagesModified.observe(viewLifecycleOwner, Observer { event ->
event.getContentOrNull()?.let { result ->
getBindingSafe().apply {
spinner.visibility = View.GONE
modified.text = resources.getQuantityString(
R.plurals.images_modified,
result.imagesModified,
result.imagesModified,
result.imagesTotal
)
val numberOfSkippedImages = result.imagesTotal - result.imagesModified
skipped.text = resources.getQuantityString(
R.plurals.images_skipped,
numberOfSkippedImages,
numberOfSkippedImages,
result.imagesTotal
)
done.visibility = View.VISIBLE
}
requireActivity().invalidateOptionsMenu()
}
})
viewModel.modifyImageOrImagesSelectionOrResolveImageDirectory()
}
override fun onCreateOptionsMenu(
menu: Menu,
inflater: MenuInflater
) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_images, menu)
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menu.findItem(R.id.action_share).isVisible = viewModel.isFinishedAndModifiedImageOrImages()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if (item.itemId == R.id.action_share) {
when (val selection = viewModel.selection) {
is ImageSelection -> shareImage.launch(selection.uriModified)
is ImagesSelection -> shareImages.launch(selection.images.map { image -> image.uriModified })
else -> return false
}
true
} else {
super.onOptionsItemSelected(item)
}
}
override fun bindLayout(view: View): FragmentImagesBinding = FragmentImagesBinding.bind(view)
}
| 0
| null |
0
| 0
|
3013c5dae16504a130998e69622f8f4afa56586a
| 5,244
|
exif-eraser
|
MIT License
|
app/src/main/java/com/example/mykotlinapp/ui/BottomSheetFormFragment.kt
|
vbounyasit
| 522,266,559
| false
|
{"Kotlin": 507212}
|
package com.example.mykotlinapp.ui
import com.example.mykotlinapp.model.dto.inputs.form.InputDTO
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.coroutines.Job
abstract class BottomSheetFormFragment<T : InputDTO>(
private val confirmFunction: (T) -> Job?,
) : BottomSheetDialogFragment(), DialogForm<T> {
override var initialInput: T? = null
override fun submit(input: T) {
confirmFunction(input)?.invokeOnCompletion { dismiss() }
}
}
| 0
|
Kotlin
|
0
| 1
|
a9812a061f9214b44ba326b77afe335a003cc22e
| 503
|
MyAndroidApp
|
Apache License 2.0
|
db-objekts-mariadb/src/generated-sources/kotlin/com/dbobjekts/mariadb/testdb/nation/Nation.kt
|
jaspersprengers
| 576,889,038
| false
| null |
package com.dbobjekts.mariadb.testdb.nation
import com.dbobjekts.metadata.Schema
/**
* Auto-generated metadata object representing a schema consisting of one or more tables.
*
* Do not edit this file manually! Always use [com.dbobjekts.codegen.CodeGenerator] when the metadata model is no longer in sync with the database.
*/
object Nation : Schema("nation", listOf(Continents, Countries, CountryLanguages, CountryStats, Guests, Languages, Regions, RegionAreas, Vips)){
/**
* Refers to metadata object for table continents
*/
val continents = Continents
/**
* Refers to metadata object for table countries
*/
val countries = Countries
/**
* Refers to metadata object for table country_languages
*/
val countryLanguages = CountryLanguages
/**
* Refers to metadata object for table country_stats
*/
val countryStats = CountryStats
/**
* Refers to metadata object for table guests
*/
val guests = Guests
/**
* Refers to metadata object for table languages
*/
val languages = Languages
/**
* Refers to metadata object for table regions
*/
val regions = Regions
/**
* Refers to metadata object for table region_areas
*/
val regionAreas = RegionAreas
/**
* Refers to metadata object for table vips
*/
val vips = Vips
}
| 0
|
Kotlin
|
2
| 4
|
51b40a89c2ae648cb720073538ca7a3ee712b49e
| 1,510
|
db-objekts
|
Apache License 2.0
|
src/main/kotlin/no/nav/pensjon/simulator/core/domain/regler/beregning2011/Reduksjonsinformasjon.kt
|
navikt
| 753,551,695
| false
|
{"Kotlin": 1452773, "Java": 2774, "Dockerfile": 144}
|
package no.nav.pensjon.simulator.core.domain.regler.beregning2011
import no.nav.pensjon.simulator.core.domain.regler.Merknad
import no.nav.pensjon.simulator.core.domain.regler.kode.BarnetilleggRegelverkCti
/**
* @author <NAME> PK-20946
*/
class Reduksjonsinformasjon {
/**
* Antall prosent brutto totalytelse ved 100% uføregrad utgjør av OIFU. Ytelse inkluderer ordinær
* uføretrygd, barnetillegg og et eventuelt gjenlevendetillegg.
*/
var andelYtelseAvOIFU: Double = 0.0
/**
* Beskriver hvilket regelverk som er benyttet i beregning av regelverk, se kodeverk K_BT_REGELVERK
*/
var barnetilleggRegelverkType: BarnetilleggRegelverkCti? = null
/**
* Barnetillegg fellesbarn brutto per år
*/
var btFBEtterReduksjon: Int = 0
/**
* Barnetillegg særkullsbarn per år
*/
var btSBEtterReduksjon: Int = 0
/**
* 95% av oppjustert IFU (tak)
*/
var gradertOppjustertIFU: Int = 0
/**
* Samlet brutto etter reduksjon for barnetillegg særkullsbarn/fellesbarn
*/
var sumBruttoEtterReduksjonBT: Int = 0
/**
* Samlet brutto før reduksjon for barnetillegg særkullsbarn/fellesbarn
*/
var sumBruttoForReduksjonBT: Int = 0
/**
* Sum av uføretrygd, gjenlevendetillegg og barnetillegg
*/
var sumUTBT: Int = 0
/**
* Antall felles- og særkullsbarn
*/
var totaltAntallBarn: Int = 0
/**
* Angir prosentsatsen som brukes til å beregne taket for hvor stor samlet ugradert uføretrygd og brutto barnetillegg brukeren kan ha i forhold til oppjustert IFU før brutto
* barnetillegg blir redusert
*/
var prosentsatsOIFUForTak: Int = 0
var merknader: MutableList<Merknad> = mutableListOf()
constructor() : super() {}
constructor(rg: Reduksjonsinformasjon) : super() {
this.sumUTBT = rg.sumUTBT
this.gradertOppjustertIFU = rg.gradertOppjustertIFU
this.totaltAntallBarn = rg.totaltAntallBarn
this.sumBruttoForReduksjonBT = rg.sumBruttoForReduksjonBT
this.sumBruttoEtterReduksjonBT = rg.sumBruttoEtterReduksjonBT
this.btFBEtterReduksjon = rg.btFBEtterReduksjon
this.btSBEtterReduksjon = rg.btSBEtterReduksjon
this.prosentsatsOIFUForTak = rg.prosentsatsOIFUForTak
if (rg.barnetilleggRegelverkType != null) {
this.barnetilleggRegelverkType = BarnetilleggRegelverkCti(rg.barnetilleggRegelverkType)
}
this.merknader = rg.merknader
this.andelYtelseAvOIFU = rg.andelYtelseAvOIFU
}
constructor(
andelYtelseAvOIFU: Double = 0.0,
barnetilleggRegelverkType: BarnetilleggRegelverkCti? = null,
merknader: MutableList<Merknad> = mutableListOf(),
btFBEtterReduksjon: Int = 0,
btSBEtterReduksjon: Int = 0,
gradertOppjustertIFU: Int = 0,
sumBruttoEtterReduksjonBT: Int = 0,
sumBruttoForReduksjonBT: Int = 0,
sumUTBT: Int = 0,
totaltAntallBarn: Int = 0,
prosentsatsOIFUForTak: Int = 0
) {
this.andelYtelseAvOIFU = andelYtelseAvOIFU
this.barnetilleggRegelverkType = barnetilleggRegelverkType
this.merknader = merknader
this.btFBEtterReduksjon = btFBEtterReduksjon
this.btSBEtterReduksjon = btSBEtterReduksjon
this.gradertOppjustertIFU = gradertOppjustertIFU
this.sumBruttoEtterReduksjonBT = sumBruttoEtterReduksjonBT
this.sumBruttoForReduksjonBT = sumBruttoForReduksjonBT
this.sumUTBT = sumUTBT
this.totaltAntallBarn = totaltAntallBarn
this.prosentsatsOIFUForTak = prosentsatsOIFUForTak
}
}
| 1
|
Kotlin
|
0
| 0
|
77b8c4e0a80e5bf44cb44468466362956fe82da8
| 3,653
|
pensjonssimulator
|
MIT License
|
material-icon/src/main/kotlin/team/duckie/quackquack/material/icon/quackicon/outlined/Bookmark.kt
|
duckie-team
| 523,387,054
| false
|
{"Kotlin": 901061, "MDX": 51559, "JavaScript": 6871, "CSS": 1060}
|
/*
* Designed and developed by Duckie Team 2023.
*
* Licensed under the MIT.
* Please see full license: https://github.com/duckie-team/quack-quack-android/blob/main/LICENSE
*/
package team.duckie.quackquack.material.icon.quackicon.outlined
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
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 team.duckie.quackquack.material.icon.quackicon.OutlinedGroup
public val OutlinedGroup.Bookmark: ImageVector
get() {
if (_bookmark != null) {
return _bookmark!!
}
_bookmark = Builder(
name = "Bookmark", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF222222)),
strokeLineWidth = 1.5f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(7.5151f, 4.945f)
curveTo(7.1485f, 4.945f, 6.797f, 5.0906f, 6.5378f, 5.3498f)
curveTo(6.2787f, 5.609f, 6.1331f, 5.9605f, 6.1331f, 6.327f)
verticalLineTo(17.673f)
curveTo(6.1323f, 17.9158f, 6.1956f, 18.1546f, 6.3165f, 18.3651f)
curveTo(6.4375f, 18.5757f, 6.6118f, 18.7507f, 6.8219f, 18.8724f)
curveTo(7.0321f, 18.9941f, 7.2706f, 19.0582f, 7.5134f, 19.0583f)
curveTo(7.7562f, 19.0584f, 7.9948f, 18.9945f, 8.2051f, 18.873f)
lineTo(9.0661f, 18.373f)
lineTo(12.0001f, 16.679f)
lineTo(14.9331f, 18.372f)
lineTo(15.7941f, 18.872f)
curveTo(16.0043f, 18.9935f, 16.2429f, 19.0574f, 16.4857f, 19.0573f)
curveTo(16.7285f, 19.0572f, 16.967f, 18.9931f, 17.1772f, 18.8714f)
curveTo(17.3873f, 18.7497f, 17.5616f, 18.5747f, 17.6826f, 18.3641f)
curveTo(17.8035f, 18.1536f, 17.8668f, 17.9148f, 17.8661f, 17.672f)
verticalLineTo(6.327f)
curveTo(17.8662f, 6.1454f, 17.8305f, 5.9655f, 17.761f, 5.7977f)
curveTo(17.6916f, 5.63f, 17.5897f, 5.4775f, 17.4612f, 5.3491f)
curveTo(17.3328f, 5.2208f, 17.1802f, 5.119f, 17.0124f, 5.0496f)
curveTo(16.8445f, 4.9803f, 16.6647f, 4.9447f, 16.4831f, 4.945f)
horizontalLineTo(7.5151f)
close()
}
}
.build()
return _bookmark!!
}
private var _bookmark: ImageVector? = null
| 45
|
Kotlin
|
8
| 99
|
24d44663cf5bea29fc73595b5f60be03b08e162b
| 2,774
|
quack-quack-android
|
MIT License
|
build-logic/convention/src/main/kotlin/AndroidLibraryConventionPlugin.kt
|
KellyZ
| 640,846,392
| false
| null |
import com.android.build.gradle.LibraryExtension
import module.plugin.build.configureKotlinAndroid
import module.plugin.build.kotlinAndroid
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.getByType
class AndroidLibraryConventionPlugin: Plugin<Project> {
override fun apply(target: Project) {
with(target) {
with(pluginManager) {
apply("com.android.library")
apply("org.jetbrains.kotlin.android")
apply("kotlinx-serialization")
}
kotlinAndroid {
jvmToolchain(11)
}
val extension = extensions.getByType<LibraryExtension>()
extension.apply {
buildFeatures {
dataBinding = true
}
configureKotlinAndroid(this)
defaultConfig.targetSdk = 33
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
41f00715f73e08fa899139b10427e8cb0be9a1e0
| 942
|
AndroidModulesSample
|
Apache License 2.0
|
common/src/main/java/com/jon/common/repositories/impl/StatusRepository.kt
|
b9389
| 547,559,544
| true
|
{"Kotlin": 310705, "Java": 3012}
|
package com.jon.common.repositories.impl
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.jon.common.repositories.IStatusRepository
import com.jon.common.service.ServiceState
import javax.inject.Inject
class StatusRepository @Inject constructor() : IStatusRepository {
private val lock = Any()
private val currentStatus = MutableLiveData<ServiceState>().apply { value = ServiceState.STOPPED }
override fun getStatus(): LiveData<ServiceState> {
synchronized(lock) {
return currentStatus
}
}
override fun postStatus(state: ServiceState) {
synchronized(lock) {
currentStatus.postValue(state)
}
}
}
| 0
| null |
0
| 0
|
ae8809555a1e9e2a62f64ce90f2ff6fa5c6ef0fd
| 718
|
cotgenerator
|
Apache License 2.0
|
resources-generator/src/main/kotlin/dev/icerock/gradle/generator/resources/image/AppleImageResourceGenerator.kt
|
icerockdev
| 204,874,263
| false
|
{"Kotlin": 456033, "Shell": 1362}
|
/*
* Copyright 2024 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.gradle.generator.resources.image
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.TypeSpec.Builder
import dev.icerock.gradle.generator.Constants
import dev.icerock.gradle.generator.PlatformResourceGenerator
import dev.icerock.gradle.generator.addAppleContainerBundleInitializerProperty
import dev.icerock.gradle.generator.addValuesFunction
import dev.icerock.gradle.metadata.resource.ImageMetadata
import dev.icerock.gradle.metadata.resource.ImageMetadata.ImageItem
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import org.gradle.api.InvalidUserDataException
import java.io.File
internal class AppleImageResourceGenerator(
private val assetsGenerationDir: File,
) : PlatformResourceGenerator<ImageMetadata> {
override fun imports(): List<ClassName> = emptyList()
override fun generateInitializer(metadata: ImageMetadata): CodeBlock {
return CodeBlock.of(
"ImageResource(assetImageName = %S, bundle = %L)",
metadata.key,
Constants.Apple.platformContainerBundlePropertyName
)
}
@Suppress("LongMethod")
override fun generateResourceFiles(data: List<ImageMetadata>) {
val assetsDirectory = File(assetsGenerationDir, Constants.Apple.assetsDirectoryName)
data.forEach { imageMetadata ->
val assetDir = File(assetsDirectory, "${imageMetadata.key}.imageset")
assetDir.mkdirs()
val contentsFile = File(assetDir, "Contents.json")
val validItems: List<ImageMetadata.ImageItem> =
imageMetadata.values.filter { item ->
item.quality == null || VALID_SIZES.any { item.quality == it.toString() }
}
resourceIsValidOrError(validItems, imageMetadata)
validItems.forEach { it.filePath.copyTo(File(assetDir, it.filePath.name)) }
val imagesContent: JsonArray = getImagesContent(validItems, imageMetadata)
val content: String = prepareContentInfo(imagesContent, validItems)
contentsFile.writeText(content)
}
}
override fun generateBeforeProperties(
builder: Builder,
metadata: List<ImageMetadata>,
modifier: KModifier?,
) {
builder.addAppleContainerBundleInitializerProperty(modifier)
}
override fun generateAfterProperties(
builder: Builder,
metadata: List<ImageMetadata>,
modifier: KModifier?,
) {
builder.addValuesFunction(
metadata = metadata,
classType = Constants.imageResourceName,
modifier = modifier
)
}
private fun getImagesContent(
validItems: List<ImageItem>,
imageMetadata: ImageMetadata,
): JsonArray {
return buildJsonArray {
validItems.map { item ->
buildJsonObject {
put(
key = "idiom",
element = JsonPrimitive("universal")
)
put(
key = "filename",
element = JsonPrimitive(item.filePath.name)
)
item.quality?.let { quality ->
put(
key = "scale",
element = JsonPrimitive(quality + "x")
)
}
if (imageMetadata.isThemed) {
put(
key = "appearances",
element = buildJsonArray {
add(
buildJsonObject {
put(
key = "appearance",
element = JsonPrimitive("luminosity")
)
put(
key = "value",
element = JsonPrimitive(item.appearance.name.lowercase())
)
}
)
}
)
}
}
}.forEach { add(it) }
}
}
private fun resourceIsValidOrError(
validItems: List<ImageItem>,
imageMetadata: ImageMetadata,
) {
if (validItems.isEmpty()) {
val errorMessage: String = buildString {
val name: String = imageMetadata.key
appendLine("Apple Generator cannot find a valid scale for file with name \"${name}\".")
append("Note: Apple resources can have only 1x, 2x and 3x scale factors ")
append("(https://developer.apple.com/design/human-interface-guidelines/ios/")
appendLine("icons-and-images/image-size-and-resolution/).")
append("It is still possible to use 4x images for android, but you need to ")
append("add a valid iOS variant.")
}
throw InvalidUserDataException(errorMessage)
}
}
private fun prepareContentInfo(
imagesContent: JsonArray,
validItems: List<ImageItem>,
): String {
return buildJsonObject {
put(key = "images", element = imagesContent)
put(
key = "info",
element = buildJsonObject {
put(key = "version", element = JsonPrimitive(1))
put(key = "author", element = JsonPrimitive("xcode"))
}
)
if (validItems.any { it.quality == null }) {
put(
key = "properties",
element = buildJsonObject {
put(
key = "preserves-vector-representation",
element = JsonPrimitive(true)
)
}
)
}
}.toString()
}
private companion object {
val VALID_SIZES: IntRange = 1..3
}
}
| 147
|
Kotlin
|
121
| 1,077
|
2c484808c928a13ab4d0523b82db3b5ab4e90db5
| 6,575
|
moko-resources
|
Apache License 2.0
|
app/src/main/java/com/winterprojects/tvmazeapp/presentation/season/SeasonViewModel.kt
|
CristianoWinter10
| 427,190,987
| false
|
{"Kotlin": 100578}
|
package com.winterprojects.tvmazeapp.presentation.season
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.winterprojects.tvmazeapp.business.shows.FetchSeasonUseCase
import com.winterprojects.tvmazeapp.domain.helpers.ResultState
import com.winterprojects.tvmazeapp.domain.season.SeasonModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class SeasonViewModel(
private val showId: Int,
private val fetchSeasonUseCase: FetchSeasonUseCase,
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.IO
) : ViewModel() {
private var mutableSeasons = MutableLiveData<ResultState<List<SeasonModel>>>()
val seasons: LiveData<ResultState<List<SeasonModel>>>
get() = mutableSeasons
init {
viewModelScope.launch {
withContext(defaultDispatcher) {
fetchSeasonUseCase(showId).let { result ->
mutableSeasons.postValue(result)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
172516b151689332e0671449105b501cbd665ac8
| 1,184
|
tvmaze-app-android
|
MIT License
|
app/src/main/java/com/jaimegc/covid19tracker/common/extensions/CoroutinesExtensions.kt
|
mbobiosio
| 321,923,998
| true
|
{"Kotlin": 734625}
|
package com.jaimegc.covid19tracker.common.extensions
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
fun main(work: suspend(() -> Unit)) =
CoroutineScope(Dispatchers.Main).launch { work() }
fun io(work: suspend(() -> Unit)) =
CoroutineScope(Dispatchers.IO).launch { work() }
fun default(work: suspend(() -> Unit)) =
CoroutineScope(Dispatchers.Default).launch { work() }
fun unconfined(work: suspend(() -> Unit)) =
CoroutineScope(Dispatchers.Unconfined).launch { work() }
fun LifecycleOwner.ioMain(workIO: suspend(() -> Unit), workMain: () -> Unit) {
lifecycleScope.launch(Dispatchers.IO) {
workIO()
launch(Dispatchers.Main) { workMain() }
}
}
| 0
| null |
0
| 0
|
897a57c116dfa09926db3043a9a10eff8d235538
| 834
|
Covid19Tracker
|
Apache License 2.0
|
blockchain-development-kit/accelerators/corda-integration-accelerator/service-bus-integration/corda-transaction-builder/src/main/kotlin/net/corda/workbench/transactionBuilder/app/AgentRepo.kt
|
bretf-ik
| 160,744,025
| true
|
{"HTML": 3970966, "Python": 1081109, "Java": 880816, "C#": 487762, "Kotlin": 314832, "JavaScript": 161542, "PowerShell": 84190, "CSS": 23314, "PLpgSQL": 16377, "Shell": 12161, "Batchfile": 8685, "Dockerfile": 3541, "Scala": 840, "ASP": 105}
|
package net.corda.workbench.transactionBuilder.app
import net.corda.workbench.commons.event.EventStore
import net.corda.workbench.commons.event.Filter
import sun.security.provider.certpath.UntrustedChecker
class AgentRepo(val es: EventStore) {
// reduce events to find the current port
fun agentPort(network: String): Int {
return es.retrieve(Filter(aggregateId = network))
.fold(0) { port, event ->
when {
@Suppress("UNCHECKED_CAST")
event.type == "AgentStarted" ->
event.payload["port"] as Int
event.type == "AgentStopped" -> 0
else -> port
}
}
}
}
| 0
|
HTML
|
0
| 0
|
99360c7092810e8f5405f4fc8ebcfc6a3caa7901
| 771
|
blockchain
|
MIT License
|
RetrofitApp/app/src/main/java/com/jamil/retrofitapp/adapter/NewsAdapter.kt
|
Jamil226
| 791,254,798
| false
|
{"Kotlin": 93547, "Java": 2228}
|
package com.jamil.retrofitapp.adapter
class NewsAdapter {
}
| 0
|
Kotlin
|
31
| 34
|
6a401956146dc3a8f3194a849d1ac1f0b714f061
| 60
|
AndroidDev
|
Apache License 2.0
|
src/test/kotlin/me/oldjing/quickconnect/QuickConnectResolverTest.kt
|
wujingwe
| 51,501,606
| false
| null |
package me.oldjing.quickconnect
import com.google.gson.Gson
import me.oldjing.quickconnect.json.pingPong
import me.oldjing.quickconnect.json.serverInfo
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class QuickConnectResolverTest {
@get:Rule
var mockWebServer = MockWebServer()
private val gson = Gson()
@Test
fun getServerInfo() {
val serverInfoJson =
serverInfo {
server = server {
serverID = "dsm"
ddns = "ddns"
fqdn = "fqdn"
gateway = "gateway"
ifaces = listOf(
iface {
ip = "localhost"
ipv6 = null
mask = "mask"
name = "eth0"
}
)
external = external {
ip = "external"
ipv6 = "external_ipv6"
}
}
env = env {
relayRegion = "tw"
controlHost = "twc.quickconnect.to"
}
service = service {
port = 5000
extPort = 0
relayIp = null
relayIpv6 = null
relayPort = null
}
}
mockWebServer.enqueue(MockResponse().setBody(gson.toJson(serverInfoJson)))
val resolver = QuickConnectResolver(mockWebServer.url("/"))
val result = resolver.getServerInfo(mockWebServer.url("/"), "demo", "dsm_portal")
assertNotNull(result)
assertEquals(result, serverInfoJson)
}
@Test
fun pingDSM() {
val pingPongJson =
pingPong {
bootDone = true
diskHibernation = false
ezid = "ezid"
success = true
}
mockWebServer.enqueue(MockResponse().setBody(gson.toJson(pingPongJson)))
val serverInfoJson =
serverInfo {
sites = null
server = server {
serverID = "dsm"
ddns = "NULL"
fqdn = "NULL"
gateway = "gateway"
ifaces = listOf(
iface {
ip = "localhost"
ipv6 = null
mask = "mask"
name = "eth0"
}
)
external = null
}
env = env {
relayRegion = "tw"
controlHost = "twc.quickconnect.to"
}
service = service {
port = mockWebServer.port
extPort = 0
relayIp = null
relayIpv6 = null
relayPort = null
}
}
val resolver = QuickConnectResolver(mockWebServer.url("/"))
val url = resolver.pingDSM(serverInfoJson)
assertNotNull(url)
assertEquals(url, mockWebServer.url("/"))
}
@Test
fun requestTunnel() {
val serverInfoJson =
serverInfo {
server = server {
serverID = "dsm"
ddns = "ddns"
fqdn = "fqdn"
gateway = "gateway"
ifaces = listOf(
iface {
ip = "localhost"
ipv6 = null
mask = "mask"
name = "eth0"
}
)
external = external {
ip = "external"
ipv6 = "external_ipv6"
}
}
env = env {
relayRegion = "tw"
controlHost = mockWebServer.url("/").host() + ":" + mockWebServer.port
}
service = service {
port = 5000
extPort = 0
relayIpv6 = null
relayPort = null
}
}
mockWebServer.enqueue(MockResponse().setBody(gson.toJson(serverInfoJson)))
val resolver = QuickConnectResolver(mockWebServer.url("/"))
val result = resolver.requestTunnel(serverInfoJson, "demo", "dsm_portal")
assertNotNull(result)
assertEquals(result, serverInfoJson)
}
}
| 0
|
Kotlin
|
0
| 3
|
4980b9fae88f38cd96045ef89b8a9f388d40ccca
| 3,785
|
quickconnect-interceptor-kotlin
|
Apache License 2.0
|
src/xqt-platform-xpath/commonMain/xqt/platform/xpath/v2/lexer/tokens/XPath20TokenProvider.kt
|
rhdunn
| 556,273,711
| false
| null |
// Copyright (C) 2022 <NAME>. SPDX-License-Identifier: Apache-2.0
package xqt.platform.xpath.v2.lexer.tokens
import xqt.platform.xml.W3CRecommendation
import xqt.platform.xml.lexer.tokens.KeywordTokenType
import xqt.platform.xml.lexer.tokens.SymbolTokenType
import xqt.platform.xml.lexer.tokens.TerminalSymbolTokenType
import xqt.platform.xpath.v1.lexer.tokens.XPath10TokenProvider
/**
* The tokens present in the XPath 2.0 grammar.
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#id-grammar">XPath 2.0 (REC) EBNF</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#terminal-symbols">XPath 2.0 (REC) Terminal Symbols</a>
*/
@W3CRecommendation
@Suppress("PropertyName")
interface XPath20TokenProvider : XPath10TokenProvider {
/**
* The abbreviated `attribute::` selector token ("`@`").
*
* AbbrevAttributeToken ::= "@"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-AbbrevForwardStep">XPath 2.0 (REC) AbbrevForwardStep</a>
*/
override val AbbrevAttribute: SymbolTokenType
/**
* The abbreviated `descendant-or-self::node()` selector token ("`//`").
*
* AbbrevDescendantOrSelfToken ::= "//"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-RelativePathExpr">XPath 2.0 (REC) RelativePathExpr</a>
*/
override val AbbrevDescendantOrSelf: SymbolTokenType
/**
* The abbreviated `parent::node()` selector token ("`..`").
*
* AbbrevParentToken ::= ".."
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-AbbrevReverseStep">XPath 2.0 (REC) AbbrevReverseStep</a>
*/
override val AbbrevParent: SymbolTokenType
/**
* The axis separator token ("`::`").
*
* AxisSeparatorToken ::= "::"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ForwardAxis">XPath 2.0 (REC) ForwardAxis</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ReverseAxis">XPath 2.0 (REC) ReverseAxis</a>
*/
override val AxisSeparator: SymbolTokenType
/**
* The colon token ("`:`").
*
* ColonToken ::= ":"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-Wildcard">XPath 2.0 (REC) Wildcard</a>
*/
override val Colon: SymbolTokenType
/**
* The comma token ("`,`").
*
* CommaToken ::= ","
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-Expr">XPath 2.0 (REC) Expr</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SimpleForClause">XPath 2.0 (REC) SimpleForClause</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-QuantifiedExpr">XPath 2.0 (REC) QuantifiedExpr</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-AttributeTest">XPath 2.0 (REC) AttributeTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ElementTest">XPath 2.0 (REC) ElementTest</a>
*/
override val Comma: SymbolTokenType
/**
* The comment close token ("`:)`").
*
* CommentCloseToken ::= ":)"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-Comment">XPath 2.0 (REC) Comment</a>
*/
val CommentClose: SymbolTokenType
/**
* The comment open token ("`(:`").
*
* CommentOpenToken ::= "(:"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-Comment">XPath 2.0 (REC) Comment</a>
*/
val CommentOpen: SymbolTokenType
/**
* The context item token ("`.`").
*
* ContextItemToken ::= "."
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ContextItemExpr">XPath 2.0 (REC) ContextItemExpr</a>
*/
override val ContextItem: SymbolTokenType
/**
* The equals token ("`=`").
*
* EqualsToken ::= "="
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-GeneralComp">XPath 2.0 (REC) GeneralComp</a>
*/
override val Equals: SymbolTokenType
/**
* The escaped apostrophe token ("`''`").
*
* EscapeAposToken ::= "''"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-EscapeApos">XPath 2.0 (REC) EscapeApos</a>
*/
val EscapeApos: SymbolTokenType
/**
* The escaped quotation mark token ('`""`').
*
* EscapeQuotToken ::= '""'
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-EscapeQuot">XPath 2.0 (REC) EscapeQuot</a>
*/
val EscapeQuot: SymbolTokenType
/**
* The greater than token ("`>`").
*
* GreaterThanToken ::= ">"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-GeneralComp">XPath 2.0 (REC) GeneralComp</a>
*/
override val GreaterThan: SymbolTokenType
/**
* The greater than or equals token ("`>=`").
*
* GreaterThanOrEqualsToken ::= ">="
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-GeneralComp">XPath 2.0 (REC) GeneralComp</a>
*/
override val GreaterThanOrEquals: SymbolTokenType
/**
* The less than token ("`<`").
*
* LessThanToken ::= "<"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-GeneralComp">XPath 2.0 (REC) GeneralComp</a>
*/
override val LessThan: SymbolTokenType
/**
* The less than or equals token ("`<=`").
*
* LessThanOrEqualsToken ::= "<="
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-GeneralComp">XPath 2.0 (REC) GeneralComp</a>
*/
override val LessThanOrEquals: SymbolTokenType
/**
* The node follows token ("`>>`").
*
* NodeFollowsToken ::= ">>"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-NodeComp">XPath 2.0 (REC) NodeComp</a>
*/
val NodeFollows: SymbolTokenType
/**
* The node precedes token ("`<<`").
*
* NodePrecedesToken ::= "<<"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-NodeComp">XPath 2.0 (REC) NodeComp</a>
*/
val NodePrecedes: SymbolTokenType
/**
* The not equals token ("`!=`").
*
* NotEqualsToken ::= "!="
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-GeneralComp">XPath 2.0 (REC) GeneralComp</a>
*/
override val NotEquals: SymbolTokenType
/**
* The path operator token ("`/`").
*
* PathOperatorToken ::= "/"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-RelativePathExpr">XPath 2.0 (REC) RelativePathExpr</a>
*/
override val PathOperator: SymbolTokenType
/**
* The parenthesis close token ("`)`").
*
* ParenthesisCloseToken ::= ")"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-IfExpr">XPath 2.0 (REC) IfExpr</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ParenthesizedExpr">XPath 2.0 (REC) ParenthesizedExpr</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SequenceType">XPath 2.0 (REC) SequenceType</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ItemType">XPath 2.0 (REC) ItemType</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-AnyKindTest">XPath 2.0 (REC) AnyKindTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-DocumentTest">XPath 2.0 (REC) DocumentTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-TextTest">XPath 2.0 (REC) TextTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-CommentTest">XPath 2.0 (REC) CommentTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-PITest">XPath 2.0 (REC) PITest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-AttributeTest">XPath 2.0 (REC) AttributeTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SchemaAttributeTest">XPath 2.0 (REC) SchemaAttributeTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ElementTest">XPath 2.0 (REC) ElementTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SchemaElementTest">XPath 2.0 (REC) SchemaElementTest</a>
*/
override val ParenthesisClose: SymbolTokenType
/**
* The parenthesis open token ("`(`").
*
* ParenthesisOpenToken ::= "("
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-IfExpr">XPath 2.0 (REC) IfExpr</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ParenthesizedExpr">XPath 2.0 (REC) ParenthesizedExpr</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SequenceType">XPath 2.0 (REC) SequenceType</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ItemType">XPath 2.0 (REC) ItemType</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-AnyKindTest">XPath 2.0 (REC) AnyKindTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-DocumentTest">XPath 2.0 (REC) DocumentTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-TextTest">XPath 2.0 (REC) TextTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-CommentTest">XPath 2.0 (REC) CommentTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-PITest">XPath 2.0 (REC) PITest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-AttributeTest">XPath 2.0 (REC) AttributeTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SchemaAttributeTest">XPath 2.0 (REC) SchemaAttributeTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ElementTest">XPath 2.0 (REC) ElementTest</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SchemaElementTest">XPath 2.0 (REC) SchemaElementTest</a>
*/
override val ParenthesisOpen: SymbolTokenType
/**
* The plus token ("`+`").
*
* PlusToken ::= "+"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-UnaryExpr">XPath 2.0 (REC) UnaryExpr</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-OccurrenceIndicator">XPath 2.0 (REC) OccurrenceIndicator</a>
*/
override val Plus: SymbolTokenType
/**
* The question mark token ("`?`").
*
* QuestionMarkToken ::= "?"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SingleType">XPath 2.0 (REC) SingleType</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-OccurrenceIndicator">XPath 2.0 (REC) OccurrenceIndicator</a>
*/
val QuestionMark: SymbolTokenType
/**
* The star token ("`*`").
*
* StarToken ::= "*"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-MultiplicativeExpr">XPath 2.0 (REC) MultiplicativeExpr</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-Wildcard">XPath 2.0 (REC) Wildcard</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-OccurrenceIndicator">XPath 2.0 (REC) OccurrenceIndicator</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-AttribNameOrWildcard">XPath 2.0 (REC) AttribNameOrWildcard</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ElementNameOrWildcard">XPath 2.0 (REC) ElementNameOrWildcard</a>
*/
override val Star: SymbolTokenType
/**
* The string literal apostrophe token ("`'`").
*
* StringLiteralAposToken ::= "'"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-StringLiteral">XPath 2.0 (REC) StringLiteral</a>
*/
val StringLiteralApos: SymbolTokenType
/**
* The string literal quotation mark token ('`"`').
*
* StringLiteralQuotToken ::= '"'
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-StringLiteral">XPath 2.0 (REC) StringLiteral</a>
*/
val StringLiteralQuot: SymbolTokenType
/**
* The variable indicator token ("`$`").
*
* VariableIndicatorToken ::= "$"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SimpleForClause">XPath 2.0 (REC) SimpleForClause</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-QuantifiedExpr">XPath 2.0 (REC) QuantifiedExpr</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-VarRef">XPath 2.0 (REC) VarRef</a>
*/
override val VariableIndicator: SymbolTokenType
/**
* The integer literal token (`IntegerLiteral`).
*
* IntegerLiteral ::= Digits
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-IntegerLiteral">XPath 2.0 (REC) IntegerLiteral</a>
*/
val IntegerLiteral: TerminalSymbolTokenType
/**
* The decimal literal token (`DecimalLiteral`).
*
* DecimalLiteral ::= ("." Digits)
* | (Digits "." Digits?)
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-DecimalLiteral">XPath 2.0 (REC) DecimalLiteral</a>
*/
val DecimalLiteral: TerminalSymbolTokenType
/**
* The double literal token (`DoubleLiteral`).
*
* DoubleLiteral ::= (Digits [eE] [+-]? Digits)
* | ("." Digits [eE] [+-]? Digits)
* | (Digits "." Digits? [eE] [+-]? Digits)
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-DoubleLiteral">XPath 2.0 (REC) DoubleLiteral</a>
*/
val DoubleLiteral: TerminalSymbolTokenType
/**
* The string literal apostrophe contents token.
*
* StringLiteralAposContents ::= (Char - "'")*
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-StringLiteral">XPath 2.0 (REC) StringLiteral</a>
*/
val StringLiteralAposContents: TerminalSymbolTokenType
/**
* The string literal quotation mark contents token.
*
* StringLiteralQuotContents ::= (Char - '"')*
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-StringLiteral">XPath 2.0 (REC) StringLiteral</a>
*/
val StringLiteralQuotContents: TerminalSymbolTokenType
/**
* The comment contents token (`CommentContents`).
*
* CommentContents ::= (Char+ - (Char* ('(:' | ':)') Char*))
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-CommentContents">XPath 2.0 (REC) CommentContents</a>
*/
val CommentContents: TerminalSymbolTokenType
/**
* The `ancestor` keyword token.
*
* KAncestorToken ::= "ancestor"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ReverseAxis">XPath 2.0 (REC) ReverseAxis</a>
*/
override val KAncestor: KeywordTokenType
/**
* The `ancestor-or-self` keyword token.
*
* KAncestorOrSelfToken ::= "ancestor-or-self"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ReverseAxis">XPath 2.0 (REC) ReverseAxis</a>
*/
override val KAncestorOrSelf: KeywordTokenType
/**
* The `as` keyword token.
*
* KAsToken ::= "as"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-TreatExpr">XPath 2.0 (REC) TreatExpr</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-CastableExpr">XPath 2.0 (REC) CastableExpr</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-CastExpr">XPath 2.0 (REC) CastExpr</a>
*/
val KAs: KeywordTokenType
/**
* The `attribute` keyword token.
*
* KAttributeToken ::= "attribute"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ForwardAxis">XPath 2.0 (REC) ForwardAxis</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-AttributeTest">XPath 2.0 (REC) AttributeTest</a>
*/
override val KAttribute: KeywordTokenType
/**
* The `cast` keyword token.
*
* KCastToken ::= "cast"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-CastExpr">XPath 2.0 (REC) CastExpr</a>
*/
val KCast: KeywordTokenType
/**
* The `castable` keyword token.
*
* KCastableToken ::= "castable"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-CastableExpr">XPath 2.0 (REC) CastableExpr</a>
*/
val KCastable: KeywordTokenType
/**
* The `child` keyword token.
*
* KChildToken ::= "child"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ForwardAxis">XPath 2.0 (REC) ForwardAxis</a>
*/
override val KChild: KeywordTokenType
/**
* The `comment` keyword token.
*
* KCommentToken ::= "comment"
*
* @see <a href="https://www.w3.org/TR/1999/REC-xpath-19991116/#NT-NodeType">XPath 1.0 (REC) NodeType</a>
*/
override val KComment: KeywordTokenType
/**
* The `descendant` keyword token.
*
* KDescendantToken ::= "descendant"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ForwardAxis">XPath 2.0 (REC) ForwardAxis</a>
*/
override val KDescendant: KeywordTokenType
/**
* The `descendant-or-self` keyword token.
*
* KDescendantOrSelfToken ::= "descendant-or-self"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ForwardAxis">XPath 2.0 (REC) ForwardAxis</a>
*/
override val KDescendantOrSelf: KeywordTokenType
/**
* The `document-node` keyword token.
*
* KDocumentNodeToken ::= "document-node"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-DocumentTest">XPath 2.0 (REC) DocumentTest</a>
*/
val KDocumentNode: KeywordTokenType
/**
* The `element` keyword token.
*
* KElementToken ::= "element"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ElementTest">XPath 2.0 (REC) ElementTest</a>
*/
val KElement: KeywordTokenType
/**
* The `else` keyword token.
*
* KElseToken ::= "else"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-IfExpr">XPath 2.0 (REC) IfExpr</a>
*/
val KElse: KeywordTokenType
/**
* The `empty-sequence` keyword token.
*
* KEmptySequenceToken ::= "empty-sequence"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SequenceType">XPath 2.0 (REC) SequenceType</a>
*/
val KEmptySequence: KeywordTokenType
/**
* The `eq` keyword token.
*
* KEqToken ::= "eq"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ValueComp">XPath 2.0 (REC) ValueComp</a>
*/
val KEq: KeywordTokenType
/**
* The `every` keyword token.
*
* KEveryToken ::= "every"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-QuantifiedExpr">XPath 2.0 (REC) QuantifiedExpr</a>
*/
val KEvery: KeywordTokenType
/**
* The `except` keyword token.
*
* KExceptToken ::= "except"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-IntersectExceptExpr">XPath 2.0 (REC) IntersectExceptExpr</a>
*/
val KExcept: KeywordTokenType
/**
* The `following` keyword token.
*
* KFollowingToken ::= "following"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ForwardAxis">XPath 2.0 (REC) ForwardAxis</a>
*/
override val KFollowing: KeywordTokenType
/**
* The `following-sibling` keyword token.
*
* KFollowingSiblingToken ::= "following-sibling"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ForwardAxis">XPath 2.0 (REC) ForwardAxis</a>
*/
override val KFollowingSibling: KeywordTokenType
/**
* The `for` keyword token.
*
* KForToken ::= "for"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SimpleForClause">XPath 2.0 (REC) SimpleForClause</a>
*/
val KFor: KeywordTokenType
/**
* The `ge` keyword token.
*
* KGeToken ::= "ge"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ValueComp">XPath 2.0 (REC) ValueComp</a>
*/
val KGe: KeywordTokenType
/**
* The `gt` keyword token.
*
* KGtToken ::= "gt"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ValueComp">XPath 2.0 (REC) ValueComp</a>
*/
val KGt: KeywordTokenType
/**
* The `idiv` keyword token.
*
* KIDivToken ::= "idiv"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-MultiplicativeExpr">XPath 2.0 (REC) MultiplicativeExpr</a>
*/
val KIDiv: KeywordTokenType
/**
* The `if` keyword token.
*
* KIfToken ::= "if"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-IfExpr">XPath 2.0 (REC) IfExpr</a>
*/
val KIf: KeywordTokenType
/**
* The `in` keyword token.
*
* KInToken ::= "in"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SimpleForClause">XPath 2.0 (REC) SimpleForClause</a>
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-QuantifiedExpr">XPath 2.0 (REC) QuantifiedExpr</a>
*/
val KIn: KeywordTokenType
/**
* The `instance` keyword token.
*
* KInstanceToken ::= "instance"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-InstanceofExpr">XPath 2.0 (REC) InstanceofExpr</a>
*/
val KInstance: KeywordTokenType
/**
* The `intersect` keyword token.
*
* KIntersectToken ::= "intersect"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-IntersectExceptExpr">XPath 2.0 (REC) IntersectExceptExpr</a>
*/
val KIntersect: KeywordTokenType
/**
* The `is` keyword token.
*
* KIsToken ::= "is"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-NodeComp">XPath 2.0 (REC) NodeComp</a>
*/
val KIs: KeywordTokenType
/**
* The `item` keyword token.
*
* KItemToken ::= "item"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ItemType">XPath 2.0 (REC) ItemType</a>
*/
val KItem: KeywordTokenType
/**
* The `le` keyword token.
*
* KLeToken ::= "le"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ValueComp">XPath 2.0 (REC) ValueComp</a>
*/
val KLe: KeywordTokenType
/**
* The `lt` keyword token.
*
* KLtToken ::= "lt"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ValueComp">XPath 2.0 (REC) ValueComp</a>
*/
val KLt: KeywordTokenType
/**
* The `namespace` keyword token.
*
* KNamespaceToken ::= "namespace"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ForwardAxis">XPath 2.0 (REC) ForwardAxis</a>
*/
override val KNamespace: KeywordTokenType
/**
* The `ne` keyword token.
*
* KNeToken ::= "ne"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ValueComp">XPath 2.0 (REC) ValueComp</a>
*/
val KNe: KeywordTokenType
/**
* The `node` keyword token.
*
* KNodeToken ::= "node"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-AnyKindTest">XPath 2.0 (REC) AnyKindTest</a>
*/
override val KNode: KeywordTokenType
/**
* The `of` keyword token.
*
* KOfToken ::= "of"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-InstanceofExpr">XPath 2.0 (REC) InstanceofExpr</a>
*/
val KOf: KeywordTokenType
/**
* The `parent` keyword token.
*
* KParentToken ::= "parent"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ReverseAxis">XPath 2.0 (REC) ReverseAxis</a>
*/
override val KParent: KeywordTokenType
/**
* The `preceding` keyword token.
*
* KPrecedingToken ::= "preceding"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ReverseAxis">XPath 2.0 (REC) ReverseAxis</a>
*/
override val KPreceding: KeywordTokenType
/**
* The `preceding-sibling` keyword token.
*
* KPrecedingSiblingToken ::= "preceding-sibling"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ReverseAxis">XPath 2.0 (REC) ReverseAxis</a>
*/
override val KPrecedingSibling: KeywordTokenType
/**
* The `processing-instruction` keyword token.
*
* KProcessingInstructionToken ::= "processing-instruction"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-PITest">XPath 2.0 (REC) PITest</a>
*/
override val KProcessingInstruction: KeywordTokenType
/**
* The `return` keyword token.
*
* KReturnToken ::= "return"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ForExpr">XPath 2.0 (REC) ForExpr</a>
*/
val KReturn: KeywordTokenType
/**
* The `satisfies` keyword token.
*
* KSatisfiesToken ::= "satisfies"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-QuantifiedExpr">XPath 2.0 (REC) QuantifiedExpr</a>
*/
val KSatisfies: KeywordTokenType
/**
* The `self` keyword token.
*
* KSelfToken ::= "self"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-ForwardAxis">XPath 2.0 (REC) ForwardAxis</a>
*/
override val KSelf: KeywordTokenType
/**
* The `schema-attribute` keyword token.
*
* KSchemaAttributeToken ::= "schema-attribute"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SchemaAttributeTest">XPath 2.0 (REC) SchemaAttributeTest</a>
*/
val KSchemaAttribute: KeywordTokenType
/**
* The `schema-element` keyword token.
*
* KSchemaElementToken ::= "schema-element"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-SchemaElementTest">XPath 2.0 (REC) SchemaElementTest</a>
*/
val KSchemaElement: KeywordTokenType
/**
* The `some` keyword token.
*
* KSomeToken ::= "some"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-QuantifiedExpr">XPath 2.0 (REC) QuantifiedExpr</a>
*/
val KSome: KeywordTokenType
/**
* The `text` keyword token.
*
* KTextToken ::= "text"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-TextTest">XPath 2.0 (REC) TextTest</a>
*/
override val KText: KeywordTokenType
/**
* The `then` keyword token.
*
* KThenToken ::= "then"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-IfExpr">XPath 2.0 (REC) IfExpr</a>
*/
val KThen: KeywordTokenType
/**
* The `to` keyword token.
*
* KToToken ::= "to"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-RangeExpr">XPath 2.0 (REC) RangeExpr</a>
*/
val KTo: KeywordTokenType
/**
* The `treat` keyword token.
*
* KTreatToken ::= "treat"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-TreatExpr">XPath 2.0 (REC) TreatExpr</a>
*/
val KTreat: KeywordTokenType
/**
* The `union` keyword token.
*
* KUnionToken ::= "union"
*
* @see <a href="https://www.w3.org/TR/2010/REC-xpath20-20101214/#doc-xpath-UnionExpr">XPath 2.0 (REC) UnionExpr</a>
*/
val KUnion: KeywordTokenType
}
| 0
|
Kotlin
|
0
| 6
|
115e29cfa6f646a4be04bac08434c44af4ec9162
| 29,448
|
xqt-platform
|
Apache License 2.0
|
app/src/androidTest/java/com/example/parstagram_k/ExampleInstrumentedTest.kt
|
kevinhui98
| 733,735,592
| false
|
{"Kotlin": 9523}
|
package com.example.parstagram_k
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.parstagram_k", appContext.packageName)
}
}
| 0
|
Kotlin
|
0
| 0
|
a2eb545b35e03b77f9981aa38d37d13a99c33e2c
| 675
|
parstagram_k
|
Apache License 2.0
|
app/src/main/java/com/example/myapplication/ui/adapter/FriendListAdapter.kt
|
yo-lolo
| 660,058,834
| false
|
{"Kotlin": 359293, "HTML": 13397, "Java": 2266}
|
package com.example.myapplication.ui.adapter
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.database.entity.FriendInfo
import com.example.myapplication.database.entity.User
import com.example.myapplication.databinding.LayoutFriendListItemBinding
import com.example.myapplication.util.GlideImageLoader
import com.example.myapplication.util.layoutInflater
/**
* @Copyright : China Telecom Quantum Technology Co.,Ltd
* @ProjectName : My Application
* @Package : com.example.myapplication.ui.adapter
* @ClassName : FriendListAdapter
* @Description : 文件描述
* @Author : yulu
* @CreateDate : 2023/7/18 10:10
* @UpdateUser : yulu
* @UpdateDate : 2023/7/18 10:10
* @UpdateRemark : 更新说明
*/
class FriendListAdapter : RecyclerView.Adapter<FriendListAdapter.FriendListViewHolder>() {
var list: Map<FriendInfo, User> = mapOf()
var goUserDetail: (Long) -> Unit = { }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FriendListViewHolder {
return FriendListViewHolder(parent)
}
override fun onBindViewHolder(holder: FriendListViewHolder, position: Int) {
holder.setData(list.keys.toList()[position], list.values.toList()[position], goUserDetail)
}
override fun getItemCount(): Int {
return list.size
}
class FriendListViewHolder(
parent: ViewGroup,
val binding: LayoutFriendListItemBinding = LayoutFriendListItemBinding.inflate(
parent.context.layoutInflater(),
parent,
false
)
) :
RecyclerView.ViewHolder(binding.root) {
fun setData(
friend: FriendInfo,
user: User,
goUserDetail: (Long) -> Unit
) {
binding.friendName.text = user.neck
binding.friendItem.setOnClickListener {
goUserDetail.invoke(friend.friendNumber)
}
GlideImageLoader().displayLocalFile(user.image, binding.friendIcon)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
cf7ff1bc88a11637165720e528b271bbe9bb829c
| 2,039
|
yolo
|
Apache License 2.0
|
app/src/test/java/com/example/missingseven/ItemRepositoryTest.kt
|
csc301-fall-2022
| 539,005,226
| false
| null |
package com.example.missingseven
import com.example.missingseven.Database.DAO.ItemDAO
import com.example.missingseven.Database.Entity.Item
import com.example.missingseven.Database.PrefManager
import com.example.missingseven.Database.Repository.ItemRepository
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
class ItemRepositoryTest {
private val itemDAO: ItemDAO = mock()
private val prefManager: PrefManager = mock()
private lateinit var itemRepository: ItemRepository
@Before
fun setup(){
itemRepository = ItemRepository(prefManager, itemDAO)
whenever(prefManager.getInt(any())).thenReturn(9)
}
@Test
fun testGetItem() = runBlocking {
whenever(itemDAO.getAllItems()).thenReturn(
flow {
emit(emptyList())
}
)
var result: List<Item>? = null
itemRepository.getItems {
result = it
}
assertEquals(emptyList<Item>(), result)
}
@Test
fun testAddItem() = runBlocking {
var result = false
itemRepository.insertAllItems(emptyList()){
result = true
}
assertEquals(true, result)
}
@Test
fun testDeleteItem() = runBlocking {
var result = false
itemRepository.deleteAllItems {
result = true
}
assertEquals(true, result)
}
}
| 0
|
Kotlin
|
1
| 0
|
866c02d651645fa2cee25f7b85a85af9797e566c
| 1,588
|
team-project-4-engineers-without-boarders-canada-t
|
MIT License
|
app/src/test/java/com/example/missingseven/ItemRepositoryTest.kt
|
csc301-fall-2022
| 539,005,226
| false
| null |
package com.example.missingseven
import com.example.missingseven.Database.DAO.ItemDAO
import com.example.missingseven.Database.Entity.Item
import com.example.missingseven.Database.PrefManager
import com.example.missingseven.Database.Repository.ItemRepository
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
class ItemRepositoryTest {
private val itemDAO: ItemDAO = mock()
private val prefManager: PrefManager = mock()
private lateinit var itemRepository: ItemRepository
@Before
fun setup(){
itemRepository = ItemRepository(prefManager, itemDAO)
whenever(prefManager.getInt(any())).thenReturn(9)
}
@Test
fun testGetItem() = runBlocking {
whenever(itemDAO.getAllItems()).thenReturn(
flow {
emit(emptyList())
}
)
var result: List<Item>? = null
itemRepository.getItems {
result = it
}
assertEquals(emptyList<Item>(), result)
}
@Test
fun testAddItem() = runBlocking {
var result = false
itemRepository.insertAllItems(emptyList()){
result = true
}
assertEquals(true, result)
}
@Test
fun testDeleteItem() = runBlocking {
var result = false
itemRepository.deleteAllItems {
result = true
}
assertEquals(true, result)
}
}
| 0
|
Kotlin
|
1
| 0
|
866c02d651645fa2cee25f7b85a85af9797e566c
| 1,588
|
team-project-4-engineers-without-boarders-canada-t
|
MIT License
|
app/src/main/java/dog/snow/androidrecruittest/data/repository/SourceRepository.kt
|
GhulJr
| 294,069,589
| true
|
{"Kotlin": 70858}
|
package dog.snow.androidrecruittest.data.repository
import dog.snow.androidrecruittest.data.source.remote.Resource
import io.reactivex.Single
interface SourceRepository {
fun pullData(): Single<out Resource<Void>>
}
| 0
|
Kotlin
|
0
| 0
|
980bf5d4bf12162489b6303406bb1c95c0362d9b
| 222
|
android-recruitment-test
|
Apache License 2.0
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/HrPerson.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.HrPerson: ImageVector
get() {
if (_hrPerson != null) {
return _hrPerson!!
}
_hrPerson = Builder(name = "HrPerson", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(9.5f, 2.5f)
curveToRelative(0.0f, -1.381f, 1.119f, -2.5f, 2.5f, -2.5f)
reflectiveCurveToRelative(2.5f, 1.119f, 2.5f, 2.5f)
reflectiveCurveToRelative(-1.119f, 2.5f, -2.5f, 2.5f)
reflectiveCurveToRelative(-2.5f, -1.119f, -2.5f, -2.5f)
close()
moveTo(11.373f, 11.128f)
curveToRelative(0.347f, 0.347f, 0.909f, 0.347f, 1.255f, 0.0f)
lineToRelative(1.42f, -1.42f)
curveToRelative(0.566f, -0.566f, 1.229f, -0.999f, 1.952f, -1.288f)
verticalLineToRelative(-0.42f)
curveToRelative(0.0f, -1.105f, -0.895f, -2.0f, -2.0f, -2.0f)
horizontalLineToRelative(-4.0f)
curveToRelative(-1.105f, 0.0f, -2.0f, 0.895f, -2.0f, 2.0f)
verticalLineToRelative(0.461f)
curveToRelative(0.738f, 0.298f, 1.435f, 0.729f, 2.033f, 1.327f)
lineToRelative(1.34f, 1.34f)
close()
moveTo(21.513f, 4.0f)
curveToRelative(-1.379f, 0.0f, -2.5f, 1.122f, -2.5f, 2.5f)
verticalLineToRelative(3.605f)
curveToRelative(-1.239f, -0.278f, -2.589f, 0.055f, -3.551f, 1.017f)
lineToRelative(-3.482f, 3.482f)
curveToRelative(-0.155f, -0.177f, -0.313f, -0.354f, -0.486f, -0.527f)
lineToRelative(-2.877f, -2.875f)
curveToRelative(-0.987f, -0.987f, -2.349f, -1.362f, -3.604f, -1.099f)
verticalLineToRelative(-3.603f)
curveToRelative(0.0f, -1.378f, -1.121f, -2.5f, -2.5f, -2.5f)
reflectiveCurveTo(0.013f, 5.122f, 0.013f, 6.5f)
verticalLineToRelative(11.015f)
curveToRelative(0.0f, 2.004f, 0.78f, 3.888f, 2.197f, 5.303f)
lineToRelative(0.742f, 0.743f)
curveToRelative(0.292f, 0.293f, 0.677f, 0.439f, 1.061f, 0.439f)
reflectiveCurveToRelative(0.768f, -0.146f, 1.061f, -0.439f)
curveToRelative(0.586f, -0.585f, 0.586f, -1.535f, 0.0f, -2.122f)
lineToRelative(-0.742f, -0.743f)
curveToRelative(-0.851f, -0.849f, -1.318f, -1.979f, -1.318f, -3.182f)
verticalLineToRelative(-1.119f)
lineToRelative(2.443f, 2.425f)
curveToRelative(0.589f, 0.583f, 1.538f, 0.58f, 2.121f, -0.008f)
curveToRelative(0.584f, -0.588f, 0.58f, -1.538f, -0.008f, -2.122f)
lineToRelative(-2.449f, -2.431f)
curveToRelative(-0.102f, -0.167f, -0.141f, -0.362f, -0.11f, -0.559f)
curveToRelative(0.024f, -0.158f, 0.105f, -0.383f, 0.35f, -0.556f)
curveToRelative(0.312f, -0.223f, 0.812f, -0.145f, 1.137f, 0.178f)
lineToRelative(2.877f, 2.875f)
curveToRelative(1.095f, 1.095f, 1.627f, 2.237f, 1.627f, 3.492f)
verticalLineToRelative(2.81f)
curveToRelative(0.0f, 0.829f, 0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.671f, 1.5f, -1.5f)
verticalLineToRelative(-2.81f)
curveToRelative(0.0f, -0.842f, -0.149f, -1.654f, -0.429f, -2.436f)
lineToRelative(4.012f, -4.012f)
curveToRelative(0.314f, -0.313f, 0.859f, -0.314f, 1.174f, 0.0f)
curveToRelative(0.271f, 0.271f, 0.317f, 0.694f, 0.123f, 1.017f)
lineToRelative(-2.424f, 2.405f)
curveToRelative(-0.588f, 0.583f, -0.592f, 1.533f, -0.008f, 2.122f)
curveToRelative(0.293f, 0.295f, 0.679f, 0.443f, 1.064f, 0.443f)
curveToRelative(0.382f, 0.0f, 0.764f, -0.145f, 1.057f, -0.435f)
lineToRelative(2.443f, -2.424f)
verticalLineToRelative(1.144f)
curveToRelative(0.0f, 1.202f, -0.468f, 2.333f, -1.317f, 3.182f)
lineToRelative(-0.743f, 0.743f)
curveToRelative(-0.586f, 0.585f, -0.586f, 1.535f, 0.0f, 2.122f)
curveToRelative(0.292f, 0.293f, 0.677f, 0.439f, 1.061f, 0.439f)
reflectiveCurveToRelative(0.768f, -0.146f, 1.061f, -0.439f)
lineToRelative(0.743f, -0.743f)
curveToRelative(1.416f, -1.416f, 2.196f, -3.299f, 2.196f, -5.303f)
lineTo(24.015f, 6.5f)
curveToRelative(0.0f, -1.378f, -1.121f, -2.5f, -2.5f, -2.5f)
close()
}
}
.build()
return _hrPerson!!
}
private var _hrPerson: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 5,720
|
icons
|
MIT License
|
src/nativeTest/kotlin/commands/SendToNodeTest.kt
|
ACINQ
| 653,627,568
| false
| null |
package commands
import api.IEclairClientBuilder
import kotlinx.cli.ArgParser
import kotlinx.cli.ExperimentalCli
import mocks.DummyEclairClient
import mocks.DummyResultWriter
import mocks.FailingEclairClient
import types.ApiError
import types.InvoiceResult
import types.Serialization
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
@OptIn(ExperimentalCli::class)
class SendToNodeCommandTest {
private fun runTest(eclairClient: IEclairClientBuilder): DummyResultWriter {
val resultWriter = DummyResultWriter()
val command = SendToNodeCommand(resultWriter, eclairClient)
val parser = ArgParser("test")
parser.subcommands(command)
parser.parse(
arrayOf(
"sendtonode",
"-p",
"<PASSWORD>",
"--nodeId",
"02f666711319435b7905dd77d10c269d8d50c02668b975f526577167d370b50a3e",
"--amountMsat",
"1000",
)
)
return resultWriter
}
@Test
fun `successful request`() {
val resultWriter = runTest(DummyEclairClient())
assertNull(resultWriter.lastError)
assertNotNull(resultWriter.lastResult)
val expectedOutput =
Serialization.encode(InvoiceResult(true, DummyEclairClient.validSendToNodeResponse))
assertEquals(expectedOutput, resultWriter.lastResult)
}
@Test
fun `api error`() {
val error = ApiError(42, "test failure message")
val resultWriter = runTest(FailingEclairClient(error))
assertNull(resultWriter.lastResult)
assertEquals(error, resultWriter.lastError)
}
}
| 1
|
Kotlin
|
2
| 3
|
78ac5ed1fc6fbe9facf3205d3ca0832cf96fea8d
| 1,732
|
eclair-cli
|
Apache License 2.0
|
taxfreeandroidui/src/main/java/global/ututaxfree/taxfreeandroidui/OnTextClearedListener.kt
|
UTU-Global
| 214,968,127
| false
|
{"Kotlin": 149371}
|
package global.ututaxfree.taxfreeandroidui
interface OnTextClearedListener {
fun onTextCleared()
}
| 0
|
Kotlin
|
0
| 0
|
335d4aa112ecc727e7efd69a4c028a4ecf06f0fc
| 103
|
UTU.AtomicUI.Android
|
Apache License 2.0
|
korge-foundation/src@js/korlibs/js/JSStackTrace.kt
|
korlibs
| 80,095,683
| false
|
{"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41}
|
package korlibs.js
data class JSStackTrace(val message: String, val entries: List<Entry>) {
data class Entry(val method: String, val file: String, val line: Int, val column: Int = -1)
companion object {
operator fun invoke(): JSStackTrace = current()
fun parse(stack: String, message: String? = null): JSStackTrace {
val entries = arrayListOf<Entry>()
var messageLines = arrayListOf<String>()
var isChrome = false
for ((index, strLine) in stack.lines().withIndex()) {
val strLine = strLine.trimEnd()
if (strLine.isEmpty() && !isChrome) continue
// Chrome first line
when {
(strLine.startsWith("Error: ") || strLine == "Error") && index == 0 -> {
isChrome = true
messageLines.add(strLine.substring(7))
}
strLine.startsWith(" at ") -> {
val part = strLine.substring(7).trimEnd(')')
val column = part.substringAfterLast(':')
val part0 = part.substringBeforeLast(':')
val line = part0.substringAfterLast(':')
val part1 = part0.substringBeforeLast(':')
val (method, file) = if (part1.contains('(')) {
part1.split("(").map { it.trim() }
} else {
listOf("", part1.trim())
}
entries += Entry(method, file, line.toIntOrNull() ?: -1, column.toIntOrNull() ?: -1)
}
isChrome -> {
messageLines.add(strLine)
}
else -> {
var cline = strLine
val numParts = arrayListOf<Int>()
for (n in 0 until 2) {
cline = Regex("^(.*):(\\d+)$").replace(cline) {
numParts.add(0, it.groupValues[2].toIntOrNull() ?: -1)
it.groupValues[1]
}
}
val file = cline.substringAfterLast('@')
val method = cline.substringBeforeLast('@')
val line = numParts.firstOrNull() ?: -1
val column = if (numParts.size >= 2) numParts.lastOrNull() ?: -1 else -1
entries += Entry(method, file, line, column)
}
}
//println("STACK: ${stack!!.groupValues}")
}
if (!isChrome) {
messageLines = arrayListOf(message ?: "")
}
if (entries.isEmpty()) {
entries.add(Entry("<unknown>", "<unknown>", -1))
}
return JSStackTrace(messageLines.joinToString("\n"), entries)
}
fun from(e: Exception): JSStackTrace = parse(e.stackTraceToString(), e.message)
fun current(): JSStackTrace = from(Exception(""))
}
}
| 444
|
WebAssembly
|
121
| 2,207
|
dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a
| 3,182
|
korge
|
Apache License 2.0
|
src/main/kotlin/de/neusta/ncc/application/validator/LdapUserUniqueValidator.kt
|
larmic
| 123,574,305
| false
| null |
package de.neusta.ncc.application.validator
import de.neusta.ncc.application.validator.exception.LdapUserIsNotUniqueException
import org.springframework.stereotype.Component
/**
* Validate each ldap user is unique in given list of strings (with ignoring case-sensitive).
* Acceptance criteria: A person exists only once in an import file
*/
@Component
class LdapUserUniqueValidator {
@Throws(LdapUserIsNotUniqueException::class)
fun validate(ldapUsers: List<String>) {
if (ldapUsers.areNotUnique()) {
throw LdapUserIsNotUniqueException()
}
}
private fun List<String>.areNotUnique() = !StringListUniqueChecker().itemsUnique(this)
}
| 1
|
Kotlin
|
0
| 2
|
4133829bd660aac0bd110cd9b820404072660bc1
| 681
|
neusta-code-challange-kotlin
|
Apache License 2.0
|
app/src/main/java/org/ksetrin/ksetrin/fragments/RemindersFragment.kt
|
Ksetrin-Org
| 453,751,827
| false
| null |
package org.ksetrin.ksetrin.fragments
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import org.json.JSONArray
import org.json.JSONObject
import org.ksetrin.ksetrin.helpers.NewsData
import org.ksetrin.ksetrin.R
import org.ksetrin.ksetrin.adapters.NewsAdapter
import org.ksetrin.ksetrin.adapters.RemindersBigAdapter
import org.ksetrin.ksetrin.helpers.RemindersData
class RemindersFragment : Fragment() {
private val coroutineScope = CoroutineScope(Dispatchers.IO)
private lateinit var floatingActionButton: FloatingActionButton
private lateinit var recyclerView: RecyclerView
private lateinit var sharedPreferences : SharedPreferences
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViews()
initListeners()
modifyNews()
getReminders()
}
private fun initViews() {
sharedPreferences = requireActivity().getSharedPreferences("PREFERENCES", Context.MODE_PRIVATE)
floatingActionButton = requireActivity().findViewById(R.id.remindersFragmentFloatingButton)
recyclerView = requireActivity().findViewById(R.id.remindersFragmentRecyclerView)
}
private fun initListeners() {
floatingActionButton.setOnClickListener {
setFragment(AddReminderFragment())
}
}
private fun modifyNews(){
recyclerView.layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
recyclerView.adapter = RemindersBigAdapter(mutableListOf())
}
private fun getReminders() {
val data = sharedPreferences.getString("remindersData", null)
if (data != null){
val jsonArray = JSONArray(data)
println(jsonArray)
val list = jsonArrayToList(jsonArray)
activity?.runOnUiThread {
recyclerView.adapter = RemindersBigAdapter(list)
}
}
}
private fun jsonArrayToList(articles: JSONArray) : MutableList<RemindersData>{
val mutableList : MutableList<RemindersData> = mutableListOf()
for (i in 0 until articles.length()){
val element = JSONObject(articles.getString(i))
val data = RemindersData(
element.getString("title"),
element.getString("time"),
element.getString("date"),
element.getString("repeat")
)
mutableList.add(data)
}
return mutableList
}
private fun setFragment(fragment: Fragment) {
val fragmentInFrame = activity?.supportFragmentManager?.findFragmentById(R.id.frameLayout)
if (fragmentInFrame != null && fragmentInFrame::class == fragment::class) return
activity?.supportFragmentManager?.beginTransaction()
?.replace(R.id.frameLayout, fragment)
?.commit()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_reminders, container, false)
}
}
| 0
|
Kotlin
|
2
| 0
|
738016e315341bd3a9a58acce6979d69014426d5
| 3,552
|
ksetrin-android
|
Apache License 2.0
|
src/test/kotlin/io/articulus/fhir/model/dstu3/TestReportDataTest.kt
|
Articulus-Tech
| 160,540,104
| false
| null |
package io.articulus.fhir.model.dstu3
import java.io.File
import java.lang.SuppressWarnings
import kotlin.test.assertTrue
import org.junit.jupiter.api.Test
class TestReportDataTest : DataTests() {
@Test
fun `testreport-example 5 Test`() {
val json = File("./src/test/resources/model/sample_data/dstu3/testreport-example.json").readTextAndClose()
val obj = mapper.fromJson(json, TestReport::class.java)
assertTrue(stringMatch("TestReport", obj.resourceType))
assertTrue(stringMatch("testreport-example", obj.id))
assertTrue(stringMatch("generated", obj.text!!.status))
assertTrue(stringMatch("<div xmlns=\"http://www.w3.org", obj.text!!.div))
assertTrue(stringMatch("urn:ietf:rfc:3986", obj.identifier!!.system))
assertTrue(stringMatch("urn:oid:1.3.6.1.4.1.21367.200", obj.identifier!!.value))
assertTrue(stringMatch("TestReport Example for TestSc", obj.name))
assertTrue(stringMatch("completed", obj.status))
assertTrue(stringMatch("TestScript/testscript-example", obj.testScript.reference))
assertTrue(stringMatch("pass", obj.result))
assertTrue(stringMatch("%.2f".format(100.0f), "%.2f".format(obj.score)))
assertTrue(stringMatch("HL7 Execution Engine", obj.tester))
assertTrue(stringMatch("2016-10-07T08:25:34-05:00", obj.issued))
assertTrue(stringMatch("test-engine", obj.participant[0].type))
assertTrue(stringMatch("http://projectcrucible.org", obj.participant[0].uri))
assertTrue(stringMatch("Crucible", obj.participant[0].display))
assertTrue(stringMatch("server", obj.participant[1].type))
assertTrue(stringMatch("http://fhir3.healthintersecti", obj.participant[1].uri))
assertTrue(stringMatch("HealthIntersections STU3", obj.participant[1].display))
assertTrue(stringMatch("pass", obj.setup!!.action[0].operation!!.result))
assertTrue(stringMatch("DELETE Patient", obj.setup!!.action[0].operation!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.setup!!.action[0].operation!!.detail))
assertTrue(stringMatch("pass", obj.setup!!.action[1].assert_fhir!!.result))
assertTrue(stringMatch("HTTP 204", obj.setup!!.action[1].assert_fhir!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.setup!!.action[1].assert_fhir!!.detail))
assertTrue(stringMatch("pass", obj.setup!!.action[2].operation!!.result))
assertTrue(stringMatch("POST Patient/fixture-patient-", obj.setup!!.action[2].operation!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.setup!!.action[2].operation!!.detail))
assertTrue(stringMatch("pass", obj.setup!!.action[3].assert_fhir!!.result))
assertTrue(stringMatch("HTTP 201", obj.setup!!.action[3].assert_fhir!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.setup!!.action[3].assert_fhir!!.detail))
assertTrue(stringMatch("01-ReadPatient", obj.test[0].id))
assertTrue(stringMatch("Read Patient", obj.test[0].name))
assertTrue(stringMatch("Read a Patient and validate r", obj.test[0].description))
assertTrue(stringMatch("pass", obj.test[0].action[0].operation!!.result))
assertTrue(stringMatch("GET Patient/fixture-patient-c", obj.test[0].action[0].operation!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.test[0].action[0].operation!!.detail))
assertTrue(stringMatch("pass", obj.test[0].action[1].assert_fhir!!.result))
assertTrue(stringMatch("HTTP 200", obj.test[0].action[1].assert_fhir!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.test[0].action[1].assert_fhir!!.detail))
assertTrue(stringMatch("pass", obj.test[0].action[2].assert_fhir!!.result))
assertTrue(stringMatch("Last-Modified Present", obj.test[0].action[2].assert_fhir!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.test[0].action[2].assert_fhir!!.detail))
assertTrue(stringMatch("pass", obj.test[0].action[3].assert_fhir!!.result))
assertTrue(stringMatch("Response is Patient", obj.test[0].action[3].assert_fhir!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.test[0].action[3].assert_fhir!!.detail))
assertTrue(stringMatch("pass", obj.test[0].action[4].assert_fhir!!.result))
assertTrue(stringMatch("Response validates", obj.test[0].action[4].assert_fhir!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.test[0].action[4].assert_fhir!!.detail))
assertTrue(stringMatch("pass", obj.test[0].action[5].assert_fhir!!.result))
assertTrue(stringMatch("Patient.name.family 'Chalmers", obj.test[0].action[5].assert_fhir!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.test[0].action[5].assert_fhir!!.detail))
assertTrue(stringMatch("pass", obj.test[0].action[6].assert_fhir!!.result))
assertTrue(stringMatch("Patient.name.given 'Peter'", obj.test[0].action[6].assert_fhir!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.test[0].action[6].assert_fhir!!.detail))
assertTrue(stringMatch("pass", obj.test[0].action[7].assert_fhir!!.result))
assertTrue(stringMatch("Patient.name.family 'Chalmers", obj.test[0].action[7].assert_fhir!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.test[0].action[7].assert_fhir!!.detail))
assertTrue(stringMatch("pass", obj.test[0].action[8].assert_fhir!!.result))
assertTrue(stringMatch("Patient.name.family 'Chalmers", obj.test[0].action[8].assert_fhir!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.test[0].action[8].assert_fhir!!.detail))
assertTrue(stringMatch("pass", obj.test[0].action[9].assert_fhir!!.result))
assertTrue(stringMatch("Patient expected values.", obj.test[0].action[9].assert_fhir!!.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.test[0].action[9].assert_fhir!!.detail))
assertTrue(stringMatch("pass", obj.teardown!!.action[0].operation.result))
assertTrue(stringMatch("DELETE Patient/fixture-patien", obj.teardown!!.action[0].operation.message))
assertTrue(stringMatch("http://projectcrucible.org/pe", obj.teardown!!.action[0].operation.detail))
}
fun `testreport-example Init`(@SuppressWarnings("unused") obj: Bundle) {
obj.identifier // No-Op to suprress unused warnings
}
}
| 0
|
Kotlin
|
0
| 3
|
90b7b912048fc61ad3696497d1ceaf76459852cb
| 6,622
|
kotlin-fhir-model
|
Apache License 2.0
|
app/src/main/java/com/example/bonusapp/Reminder.kt
|
akinbojo
| 732,840,757
| false
|
{"Kotlin": 30943}
|
package com.example.bonusapp
import android.icu.text.SimpleDateFormat
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.Date
import java.util.Locale
import java.util.UUID
@Entity
data class Reminder(
//I set a UUID to this data class to make each item unique in a database
@PrimaryKey val id: UUID,
val title: String = "",
val description: String = "",
//I'm making the date and time one variable since both are stored in the same Date object anyway
val dateAndTime: Date,
) {
fun dateAndTimeToString(): String {
val sdf = SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.getDefault())
return sdf.format(dateAndTime)
}
fun dateToString(): String {
val sdf = SimpleDateFormat("MMMM dd, yyyy", Locale.getDefault())
return sdf.format(dateAndTime)
}
fun timeToString(): String {
val sdf = SimpleDateFormat("hh:mm a", Locale.getDefault())
return sdf.format(dateAndTime)
}
}
| 0
|
Kotlin
|
0
| 0
|
05eee081f72325428cb10f5df5c4f0016bcb9f48
| 993
|
BonusApp1
|
Apache License 2.0
|
library/src/main/java/renetik/android/core/lang/CSDrawable.kt
|
renetik
| 506,035,450
| false
| null |
package renetik.android.core.lang
interface CSHasDrawable {
val drawable: Int
}
| 0
|
Kotlin
|
1
| 3
|
aa6a08a94f4faac94a53d2cb6570436e388b0508
| 84
|
renetik-android-core
|
MIT License
|
app/src/main/java/io/github/emusute1212/makasetechoice/settings/SettingItem.kt
|
emusute1212
| 264,396,740
| false
| null |
package io.github.emusute1212.makasetechoice.settings
import android.view.View
import com.xwray.groupie.viewbinding.BindableItem
import io.github.emusute1212.makasetechoice.R
import io.github.emusute1212.makasetechoice.databinding.SettingItemViewBinding
data class SettingItem(
private val item: SettingMenuItems,
private val viewModel: SettingsViewModel
) : BindableItem<SettingItemViewBinding>(
item.hashCode().toLong()
) {
override fun getLayout(): Int = R.layout.setting_item_view
override fun bind(viewBinding: SettingItemViewBinding, position: Int) {
viewBinding.item = item
viewBinding.viewModel = viewModel
}
override fun initializeViewBinding(view: View): SettingItemViewBinding {
return SettingItemViewBinding.bind(view)
}
}
| 7
|
Kotlin
|
0
| 0
|
90dd73bcd165203da1374a1bc5c9f41596d80d3f
| 794
|
MakaseteChoiceForAndroid
|
MIT License
|
docs/code/test/ListsTests.kt
|
adamko-dev
| 465,838,213
| false
|
{"Kotlin": 70444}
|
// This file was automatically generated from lists.md by Knit tool. Do not edit.
@file:Suppress("JSUnusedLocalSymbols")
package dev.adamko.kxstsgen.example.test
import dev.adamko.kxstsgen.util.*
import io.kotest.core.spec.style.*
import io.kotest.matchers.*
import kotlinx.knit.test.*
class ListsTests : FunSpec({
tags(Knit)
context("ExampleListPrimitive01") {
val caseName = testCase.name.testName
val actual = captureOutput(caseName) {
dev.adamko.kxstsgen.example.exampleListPrimitive01.main()
}.normalizeJoin()
test("expect actual matches TypeScript") {
actual.shouldBe(
// language=TypeScript
"""
|export interface MyLists {
| strings: string[];
| ints: number[];
| longs: number[];
|}
""".trimMargin()
.normalize()
)
}
test("expect actual compiles").config(tags = tsCompile) {
actual.shouldTypeScriptCompile(caseName)
}
}
context("ExampleListObjects01") {
val caseName = testCase.name.testName
val actual = captureOutput(caseName) {
dev.adamko.kxstsgen.example.exampleListObjects01.main()
}.normalizeJoin()
test("expect actual matches TypeScript") {
actual.shouldBe(
// language=TypeScript
"""
|export interface MyLists {
| colours: Colour[];
| colourGroups: Colour[][];
| colourGroupGroups: Colour[][][];
|}
|
|export interface Colour {
| rgb: string;
|}
""".trimMargin()
.normalize()
)
}
test("expect actual compiles").config(tags = tsCompile) {
actual.shouldTypeScriptCompile(caseName)
}
}
context("ExampleListObjects02") {
val caseName = testCase.name.testName
val actual = captureOutput(caseName) {
dev.adamko.kxstsgen.example.exampleListObjects02.main()
}.normalizeJoin()
test("expect actual matches TypeScript") {
actual.shouldBe(
// language=TypeScript
"""
|export interface MyLists {
| listOfMaps: { [key: string]: number }[];
| listOfColourMaps: { [key: string]: Colour }[];
|}
|
|export interface Colour {
| rgb: string;
|}
""".trimMargin()
.normalize()
)
}
test("expect actual compiles").config(tags = tsCompile) {
actual.shouldTypeScriptCompile(caseName)
}
}
})
| 11
|
Kotlin
|
5
| 56
|
9a0866cd6e64456bff0c35ded462e91f1b144150
| 2,491
|
kotlinx-serialization-typescript-generator
|
Apache License 2.0
|
bindk/src/main/java/com/mozhimen/bindk/impls/viewdatabinding/DelegateVDBDialog.kt
|
mozhimen
| 353,952,154
| false
|
{"Kotlin": 177887, "AIDL": 964}
|
package com.mozhimen.bindk.impls.viewdatabinding
import android.app.Dialog
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleOwner
import com.mozhimen.bindk.bases.viewdatabinding.BaseDelegateVDB
/**
* @ClassName DialogViewBindingDelegate
* @Description TODO
* @Author Mozhimen / <NAME>
* @Date 2024/9/29 0:38
* @Version 1.0
*/
class DelegateVDBDialog<D, VDB : ViewDataBinding>(
clazz: Class<VDB>,
dialog: D
) : BaseDelegateVDB<D, VDB>(clazz, dialog) where D : Dialog, D : LifecycleOwner
| 1
|
Kotlin
|
15
| 119
|
59f6cac488e8089c901a3bc346238c266ee62098
| 531
|
SwiftKit
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.