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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
editor/src/main/java/com/miracle/view/imageeditor/view/MosaicMode.kt | lauhwong | 95,762,361 | false | null | package com.miracle.view.imageeditor.view
import com.miracle.view.imageeditor.R
/**
* ## Mosaic mode supported in current version
*
* Created by lxw
*/
enum class MosaicMode {
Grid {
override fun getModeBgResource() = R.drawable.selector_edit_image_traditional_mosaic
},
Blur {
override fun getModeBgResource() = R.drawable.selector_edit_image_brush_mosaic
};
abstract fun getModeBgResource(): Int
} | 1 | Kotlin | 9 | 29 | 0b5a5656bcf35f11a67538fa09ebacf610014de9 | 443 | ImageEditor | Apache License 2.0 |
core/network/src/main/java/com/andannn/melodify/core/network/model/LyricData.kt | andannn | 871,178,947 | false | {"Kotlin": 41579, "Swift": 621} | package com.andannn.aozora.core.network.model
import kotlin.Boolean
import kotlin.String
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class LyricData(
@SerialName(value = "id")
val id: Long,
@SerialName(value = "name")
val name: String,
@SerialName(value = "trackName")
val trackName: String,
@SerialName(value = "artistName")
val artistName: String,
@SerialName(value = "albumName")
val albumName: String,
@SerialName(value = "duration")
val duration: Double,
@SerialName(value = "instrumental")
val instrumental: Boolean,
@SerialName(value = "plainLyrics")
val plainLyrics: String,
@SerialName(value = "syncedLyrics")
val syncedLyrics: String,
)
| 7 | Kotlin | 0 | 0 | 8bb328b4908fd85df762fe8b3c0f3739635244fb | 786 | Melodify | Apache License 2.0 |
src/main/kotlin/com/zufar/urlshortener/shorten/service/UrlExpirationTimeDeletionScheduler.kt | Sunagatov | 163,110,132 | false | null | package com.zufar.urlshortener.service
import com.zufar.urlshortener.repository.UrlRepository
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.LocalDateTime
@Component
class UrlExpirationTimeDeletionScheduler(
private val urlRepository: UrlRepository
) {
private val log = LoggerFactory.getLogger(UrlExpirationTimeDeletionScheduler::class.java)
@Scheduled(cron = "0 0 0 * * *")// Run once every 24 hours at midnight
fun deleteExpiredUrls() {
log.info("Checking for expired URLs")
val expiredUrls = urlRepository.findAll().filter { it.expirationDate.isBefore(LocalDateTime.now()) }
if (expiredUrls.isNotEmpty()) {
log.info("Found {} expired URLs, deleting them...", expiredUrls.size)
urlRepository.deleteAll(expiredUrls)
} else {
log.info("No expired URLs found.")
}
}
}
| 0 | null | 1 | 32 | 40618a5fc3fa2ced0c606c9d2f863470029b68a6 | 976 | URL-Shortener | RSA Message-Digest License |
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/inspect/DownloadPluginXmlElementGenerator.kt | JetBrains | 49,584,664 | false | {"Kotlin": 2711266, "C#": 319161, "Java": 95520, "Dockerfile": 831, "CSS": 123} |
package jetbrains.buildServer.inspect
import jetbrains.buildServer.XmlElement
import jetbrains.buildServer.agent.runner.LoggerService
/**
* Provides download specification, for example:
* <Download Id="Plugin.Id" Version="1.2.0.0"></Download>
*/
class DownloadPluginXmlElementGenerator(
private val _loggerService: LoggerService
) : PluginXmlElementGenerator {
override val sourceId = "download"
override fun generateXmlElement(strValue: String) =
strValue.split("/").let { parts ->
val result = XmlElement("Download")
if (parts.size == 2) {
result
.withAttribute("Id", parts[0])
.withAttribute("Version", parts[1])
} else {
_loggerService.writeWarning("Invalid R# CLT plugin descriptor for downloading: \"$strValue\", it will be ignored.")
}
result
}
} | 3 | Kotlin | 25 | 94 | cdecbf2c7721a40265a031453262614809d5378d | 922 | teamcity-dotnet-plugin | Apache License 2.0 |
app/src/main/java/com/antonioleiva/notes/ui/main/MainViewModel.kt | antoniolg | 580,071,612 | false | {"Kotlin": 20527} | package com.antonioleiva.notes.ui.main
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.antonioleiva.notes.data.Note
import com.antonioleiva.notes.data.NotesRepository
import kotlinx.coroutines.launch
class MainViewModel(private val notesRepository: NotesRepository) : ViewModel() {
val notes = notesRepository.getAll()
fun delete(note: Note) {
viewModelScope.launch {
notesRepository.delete(note)
}
}
}
@Suppress("UNCHECKED_CAST")
class MainViewModelFactory(private val notesRepository: NotesRepository) :
ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return MainViewModel(notesRepository) as T
}
} | 0 | Kotlin | 0 | 6 | dacc7a0e804d18d29c3ca0ea35ea0d3880a7874a | 793 | migration-compose-workshop | Apache License 2.0 |
ktx-radix-adapter/ktx-radix-adapter-shared/src/main/java/io/arkitik/ktx/radix/adapter/shared/repository/KtxRepository.kt | arkitik | 305,525,406 | false | null | package io.arkitik.ktx.radix.adapter.shared.repository
import io.arkitik.ktx.radix.develop.identity.Identity
import org.springframework.data.repository.NoRepositoryBean
import org.springframework.data.repository.PagingAndSortingRepository
import java.io.Serializable
/**
* Created By [*<NAME> *](https://www.linkedin.com/in/iloom/)
* Created At 30, **Fri Oct, 2020**
* Project *ktx-radix* [https://arkitik.io]
*/
@NoRepositoryBean
interface KtxRepository<ID : Serializable, I : Identity<ID>> : PagingAndSortingRepository<I, ID> {
fun findByUuid(id: ID): I?
}
| 1 | Kotlin | 1 | 0 | fc6f66dadecf3ebec5cad051ece06a37828889fb | 570 | ktx-radix | Apache License 2.0 |
app/src/main/java/com/devspace/myapplication/RecipesDetailScreen.kt | metaces | 833,882,487 | false | {"Kotlin": 31199} | package com.devspace.myapplication
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.devspace.myapplication.components.ERHtmlText
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
@Composable
fun RecipesDetailScreen(id: String, navController: NavHostController) {
var recipeDto by remember { mutableStateOf<RecipeDto?>(null) }
val service = RetrofitClient.retrofitInstance.create(ApiService::class.java)
service.getRecipeById(id).enqueue(object : Callback<RecipeDto> {
override fun onResponse(call: Call<RecipeDto>, response: Response<RecipeDto>) {
if (response.isSuccessful) {
recipeDto = response.body()
} else {
Log.d("RecipesDetailScreen", "Error: ${response.errorBody()}")
}
}
override fun onFailure(call: Call<RecipeDto>, t: Throwable) {
Log.d("RecipesDetailScreen", "Error: ${t.message}")
}
})
Surface(
modifier = Modifier.fillMaxSize()
) {
recipeDto?.let {
Column(
modifier = Modifier.fillMaxSize()
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(onClick = {
navController.popBackStack()
}) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = "Back"
)
}
Text(
modifier = Modifier.padding(start = 4.dp),
text = it.title
)
}
RecipesDetailContent(recipe = it)
}
}
}
}
@Composable
fun RecipesDetailContent(recipe: RecipeDto) {
Column(
modifier = Modifier
.fillMaxSize()
) {
AsyncImage(
modifier = Modifier
.height(200.dp)
.fillMaxSize(),
contentScale = ContentScale.Crop,
model = recipe.image,
contentDescription = "${recipe.title} image"
)
ERHtmlText(
text = recipe.summary
)
}
} | 0 | Kotlin | 0 | 0 | 7761251989cafb2d7ab014290dc79c82da7c6e18 | 3,340 | easy-recipes | The Unlicense |
src/main/kotlin/com/target/liteforjdbc/Db.kt | target | 530,689,815 | false | null | package com.target.liteforjdbc
import java.sql.Connection
import java.sql.PreparedStatement
import javax.sql.DataSource
/**
* Utility to remove necessary database boilerplate code and perform the proper cleanup.
*
* NAMED PARAMETERS
* These parameters use a colon prefix to provide a label for the query parameter. For example
*
* SELECT * FROM table WHERE field = :value
*
* To use this query syntax, call the methods which accept map for the arg values, and use the parameter name as the key.
*
* Colons inside of quotes or double quotes will be left in the query as is. If you need to escape a colon outside of
* quotes, you can use a double colon :: which will translate to a single colon.
*
* POSITIONAL PARAMETERS
* This is the normal JDBC syntax, where question marks represent parameters, and the values are provided based on the
* position in the query. For example
*
* SELECT * FROM table WHERE field = ?
*
* To use this query syntax call the methods with the "PositionalParams" suffix. The parameters are then passed into the
* varargs in the order they appear in the query.
*
* RECOMMENDED USAGE
* It is recommended to use the named parameters to help make your code easier to read and maintain.
*
*/
open class Db(
private val dataSource: DataSource,
) {
constructor(config: DbConfig) : this(DataSourceFactory.dataSource(config))
/**
* @see AutoCommit#executeUpdatePositionalParams
*/
fun executeUpdatePositionalParams(sql: String, vararg args: Any?): Int = withAutoCommit { it.executeUpdatePositionalParams(sql, *args) }
/**
* @see AutoCommit#executeUpdate
*/
fun executeUpdate(sql: String, args: Map<String, Any?> = mapOf()): Int = withAutoCommit { it.executeUpdate(sql, args) }
/**
* @see AutoCommit#executeWithGeneratedKeysPositionalParams
*/
fun <T> executeWithGeneratedKeysPositionalParams(sql: String, rowMapper: RowMapper<T>, vararg args: Any?): List<T> =
withAutoCommit { it.executeWithGeneratedKeysPositionalParams(sql, rowMapper, *args) }
/**
* @see AutoCommit#executeWithGeneratedKeys
*/
fun <T> executeWithGeneratedKeys(sql: String, args: Map<String, Any?> = mapOf(), rowMapper: RowMapper<T>): List<T> =
withAutoCommit { it.executeWithGeneratedKeys(sql, args, rowMapper) }
/**
* @see AutoCommit#executeBatchPositionalParams
*/
fun executeBatchPositionalParams(sql: String, args: List<List<Any?>>): List<Int> =
withAutoCommit { it.executeBatchPositionalParams(sql, args) }
/**
* @see AutoCommit#executeBatchPositionalParams
*/
fun <T> executeBatchPositionalParams(sql: String, args: List<List<Any?>>, rowMapper: RowMapper<T>): List<T> =
withAutoCommit { it.executeBatchPositionalParams(sql, args, rowMapper) }
/**
* @see AutoCommit#executeBatch
*/
fun executeBatch(sql: String, args: List<Map<String, Any?>>): List<Int> =
withAutoCommit { it.executeBatch(sql, args) }
/**
* @see AutoCommit#executeBatch
*/
fun <T> executeBatch(sql: String, args: List<Map<String, Any?>>, rowMapper: RowMapper<T>): List<T> =
withAutoCommit { it.executeBatch(sql, args, rowMapper) }
/**
* @see AutoCommit#executeQueryPositionalParams
*/
fun <T> executeQueryPositionalParams(sql: String, rowMapper: RowMapper<T>, vararg args: Any?): T? =
withAutoCommit { it.executeQueryPositionalParams(sql, rowMapper, *args) }
/**
* @see AutoCommit#executeQuery
*/
fun <T> executeQuery(sql: String, args: Map<String, Any?> = mapOf(), rowMapper: RowMapper<T>): T? =
withAutoCommit { it.executeQuery(sql, args, rowMapper) }
/**
* @see AutoCommit#findAllPositionalParams
*/
fun <T> findAllPositionalParams(sql: String, rowMapper: RowMapper<T>, vararg args: Any?): List<T> =
withAutoCommit { it.findAllPositionalParams(sql, rowMapper, *args) }
/**
* @see AutoCommit#findAll
*/
fun <T> findAll(sql: String, args: Map<String, Any?> = mapOf(), rowMapper: RowMapper<T>): List<T> =
withAutoCommit { it.findAll(sql, args, rowMapper) }
/**
* Uses the JDBC connection, and closes it once the block is executed. This can be useful to perform functions that
* aren't provided by the existing methods on this class
*/
fun <T> useConnection(block: (Connection) -> T): T = dataSource.connection.use(block)
/**
* Uses a com.target.liteforjdbc.Transaction, and commits it once to the block is executed successfully,
* or rolls back if it throws an exception. This is required to perform any DB interactions that need transaction
* support.
*/
fun <T> withTransaction(
isolationLevel: IsolationLevel,
block: (Transaction) -> T
): T {
val transaction = Transaction(connection = dataSource.connection)
val currentIsolationLevel = transaction.connection.transactionIsolation
return transaction.use {
try {
transaction.connection.transactionIsolation = isolationLevel.intCode
val result = block(transaction)
transaction.commit()
result
} catch (t: Throwable) {
transaction.rollback()
throw t
} finally {
transaction.connection.transactionIsolation = currentIsolationLevel
}
}
}
/**
* Uses a com.target.liteforjdbc.Transaction, and commits it once to the block is executed successfully,
* or rolls back if it throws an exception. This is required to perform any DB interactions that need transaction
* support.
*/
fun <T> withTransaction(block: (Transaction) -> T): T = withTransaction(IsolationLevel.TRANSACTION_READ_COMMITTED, block)
/**
* Uses a com.target.liteforjdbc.AutoCommit and closes it once teh block is executed. This can be useful to use a
* single connection from the DataSource for a series of actions. Using other convenience query methods on this
* class will use a new AutoCommit object per call, which will be less efficient for multiple calls.
*/
open fun <T> withAutoCommit(block: (AutoCommit) -> T): T = AutoCommit(connection = dataSource.connection).use(block)
/**
* @see AutoCommit#usePreparedStatement
*/
fun <T> usePreparedStatement(sql: String, block: (PreparedStatement) -> T): T = withAutoCommit { it.usePreparedStatement(sql, block) }
/**
* @see AutoCommit#useNamedParamPreparedStatement
*/
fun <T> useNamedParamPreparedStatement(sql: String, block: (NamedParamPreparedStatement) -> T): T =
withAutoCommit { it.useNamedParamPreparedStatement(sql, block) }
/**
* @see AutoCommit#usePreparedStatementWithAutoGenKeys
*/
fun <T> usePreparedStatementWithAutoGenKeys(sql: String, block: (PreparedStatement) -> T): T =
withAutoCommit { it.usePreparedStatementWithAutoGenKeys(sql, block) }
/**
* @see AutoCommit#useNamedParamPreparedStatementWithAutoGenKeys
*/
fun <T> useNamedParamPreparedStatementWithAutoGenKeys(sql: String, block: (NamedParamPreparedStatement) -> T): T =
withAutoCommit { it.useNamedParamPreparedStatementWithAutoGenKeys(sql, block) }
/**
* Checks for the health of the underlying DataSource
*
* @return true if the dataSource returns a functioning connection
*/
fun isDataSourceHealthy() = useConnection { !it.isClosed }
enum class IsolationLevel(val intCode: Int) {
TRANSACTION_READ_COMMITTED(Connection.TRANSACTION_READ_COMMITTED),
TRANSACTION_REPEATABLE_READ(Connection.TRANSACTION_REPEATABLE_READ),
TRANSACTION_SERIALIZABLE(Connection.TRANSACTION_SERIALIZABLE)
}
}
| 5 | Kotlin | 7 | 8 | 6086621e2510fd483ac72d02c90ea9be552a13ef | 7,814 | lite-for-jdbc | MIT License |
mvvm/src/androidMain/kotlin/dev/icerock/moko/mvvm/MvvmFragment.kt | eligat | 210,386,631 | true | {"Kotlin": 36446, "Swift": 15080, "Ruby": 1370} | /*
* Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.mvvm
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
abstract class MvvmFragment<DB : ViewDataBinding, VM : ViewModel> : Fragment() {
protected lateinit var binding: DB
protected lateinit var viewModel: VM
protected abstract val layoutId: Int
protected abstract val viewModelVariableId: Int
protected abstract val viewModelClass: Class<VM>
protected abstract fun viewModelFactory(): ViewModelProvider.Factory
protected open fun viewModelStoreOwner(): ViewModelStoreOwner = this
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(viewModelStoreOwner(), viewModelFactory())[viewModelClass]
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, layoutId, container, false)
binding.lifecycleOwner = this
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.setVariable(viewModelVariableId, viewModel)
}
}
| 0 | null | 0 | 0 | 3caa7995f7cd1e68851a535aff228a7511cbaaf6 | 1,665 | moko-mvvm | Apache License 2.0 |
src/main/kotlin/com/exploids/plantumlfromsource/gradle/Visibility.kt | exploids | 291,966,628 | false | null | package com.exploids.plantumlfromsource.gradle
import com.thoughtworks.qdox.model.JavaClass
import com.thoughtworks.qdox.model.JavaMember
/**
*
* @author <NAME>
*/
enum class Visibility(val symbol: Char) {
PUBLIC('+'),
PROTECTED('#'),
PACKAGE_PRIVATE('~'),
PRIVATE('-');
infix fun within(other: Visibility?): Boolean {
return ordinal <= (other?.ordinal ?: -1)
}
override fun toString(): String {
return symbol.toString()
}
}
fun String.toVisibility(): Visibility {
return when (this) {
"public" -> Visibility.PUBLIC
"protected" -> Visibility.PROTECTED
"package private" -> Visibility.PACKAGE_PRIVATE
"private" -> Visibility.PRIVATE
else -> throw IllegalArgumentException("\"$this\" is not a valid value " +
"(valid values are \"public\", \"protected\", \"package private\" and \"private\")")
}
}
fun visibilityOf(member: JavaClass): Visibility {
return when {
member.isPublic -> Visibility.PUBLIC
member.isProtected -> Visibility.PROTECTED
member.isPrivate -> Visibility.PRIVATE
else -> Visibility.PACKAGE_PRIVATE
}
}
fun visibilityOf(member: JavaMember): Visibility {
return when {
member.isPublic -> Visibility.PUBLIC
member.isProtected -> Visibility.PROTECTED
member.isPrivate -> Visibility.PRIVATE
else -> Visibility.PACKAGE_PRIVATE
}
}
| 1 | Kotlin | 1 | 1 | 1b0cc96fb0f75575a02b5483e42e1873c52f6b42 | 1,444 | plantuml-from-source | Apache License 2.0 |
ktask-base/src/main/kotlin/ktask/base/env/health/checks/SchedulerCheck.kt | perracodex | 810,476,641 | false | {"Kotlin": 224604, "HTML": 15739, "Dockerfile": 3127} | /*
* Copyright (c) 2024-Present Perracodex. Use of this source code is governed by an MIT license.
*/
package ktask.base.env.health.checks
import kotlinx.serialization.Serializable
import ktask.base.env.health.annotation.HealthCheckAPI
import ktask.base.scheduler.service.core.SchedulerService
import ktask.base.settings.AppSettings
/**
* Used to check the health of the scheduler.
*
* @property errors The list of errors that occurred during the check.
* @property isStarted Whether the scheduler is started.
* @property isPaused Whether the scheduler is paused.
* @property totalTasks The total number of tasks in the scheduler.
* @property email The email specification for the scheduler.
*
*/
@HealthCheckAPI
@Serializable
data class SchedulerCheck(
val errors: MutableList<String>,
val isStarted: Boolean,
val isPaused: Boolean,
val totalTasks: Int,
val email: EmailSpec,
val templatesPath: String
) {
constructor() : this(
errors = mutableListOf(),
isStarted = SchedulerService.isStarted(),
isPaused = SchedulerService.isPaused(),
totalTasks = SchedulerService.totalTasks(),
email = EmailSpec(),
templatesPath = AppSettings.scheduler.templatesPath
) {
if (!isStarted) {
errors.add("${this::class.simpleName}. Scheduler is not started.")
}
if (email.hostName.isBlank()) {
errors.add("${this::class.simpleName}. Email host name is empty.")
}
if (email.smtpPort <= 0) {
errors.add("${this::class.simpleName}. Email SMTP port is invalid.")
}
if (templatesPath.isBlank()) {
errors.add("${this::class.simpleName}. Templates path is empty.")
}
}
/**
* Contains settings related to email communication.
*
* @property hostName The hostname of the outgoing mail server.
* @property smtpPort The non-SSL port number of the outgoing mail server.
* @property isSSLOnConnect Whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTP/POP).
*/
@Serializable
data class EmailSpec(
val hostName: String = AppSettings.scheduler.emailSpec.hostName,
val smtpPort: Int = AppSettings.scheduler.emailSpec.smtpPort,
val isSSLOnConnect: Boolean = AppSettings.scheduler.emailSpec.isSSLOnConnect,
)
}
| 0 | Kotlin | 0 | 1 | c11fed5c781470b08f7facadcd71ad249761dced | 2,395 | KTask | MIT License |
app/src/main/java/com/danielvilha/kotlincamerax/activity/MainActivity.kt | danielvilha | 195,789,881 | false | null | package com.danielvilha.kotlincamerax.activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.navigation.Navigation.findNavController
import com.danielvilha.kotlincamerax.R
/**
* Created by danielvilha on 2019-15-08
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onResume() {
super.onResume()
findNavController(this, R.id.mainContent).currentDestination
?.id
?.let { destinationId ->
if (destinationId == R.id.permissionFragment) {
showSystemUI()
} else {
hideSystemUI()
}
}
}
private fun hideSystemUI() {
// window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
// or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
// or View.SYSTEM_UI_FLAG_FULLSCREEN)
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_VISIBLE)
}
private fun showSystemUI() {
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
}
}
| 0 | Kotlin | 1 | 1 | f73a195389c0e605096c4c70a0ab29aa35810263 | 1,477 | kotlin-camera-x | The Unlicense |
foundation/src/commonMain/kotlin/net/ntworld/foundation/MessageBroker.kt | nhat-phan | 201,625,092 | false | null | package net.ntworld.foundation
import kotlinx.coroutines.channels.Channel
interface MessageBroker {
fun send(message: Message)
fun send(message: Message, replyTo: Channel<Message>, timeout: Int)
} | 0 | Kotlin | 3 | 3 | 2fd4b0f0a4966e3aa687f7108d3b0a1cb800c6be | 207 | foundation | MIT License |
foundation/src/commonMain/kotlin/net/ntworld/foundation/MessageBroker.kt | nhat-phan | 201,625,092 | false | null | package net.ntworld.foundation
import kotlinx.coroutines.channels.Channel
interface MessageBroker {
fun send(message: Message)
fun send(message: Message, replyTo: Channel<Message>, timeout: Int)
} | 0 | Kotlin | 3 | 3 | 2fd4b0f0a4966e3aa687f7108d3b0a1cb800c6be | 207 | foundation | MIT License |
src/test/kotlin/org/springframework/samples/petclinic/rest/controller/PetRestControllerWebMvcTests.kt | junoyoon | 664,329,578 | false | null | /*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.rest.controller
import org.junit.jupiter.api.Test
import org.mockito.kotlin.whenever
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.samples.petclinic.mapper.PetMapper
import org.springframework.samples.petclinic.rest.dto.PetDto
import org.springframework.samples.petclinic.rest.dto.PetTypeDto
import org.springframework.samples.petclinic.service.ClinicService
import org.springframework.security.test.context.support.WithMockUser
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import java.time.LocalDate
/**
* Test class for [PetRestController]
*
* @author <NAME>
*/
@WebMvcTest(PetRestController::class)
class PetRestControllerWebMvcTests(
@Autowired val mockMvc : MockMvc,
@Autowired @MockBean val clinicService: ClinicService
) {
private val pets = listOf(
PetDto(
id = 3, name = "Rosy", birthDate = LocalDate.now(),
type = PetTypeDto(id = 2, name = "dog"), visits = emptyList()
),
PetDto(id = 4, name = "Jewel", birthDate = LocalDate.now(), type = PetTypeDto(id = 2, name = "dog"))
)
@Test
@WithMockUser(roles = ["OWNER_ADMIN"])
fun testGetPetSuccess() {
whenever(clinicService.findPetById(3)).thenReturn(PetMapper.toPet(pets[0]))
mockMvc.perform(
MockMvcRequestBuilders.get("/api/pets/3")
.accept(MediaType.APPLICATION_JSON_VALUE)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType("application/json"))
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(3))
.andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Rosy"))
}
}
| 0 | Kotlin | 0 | 0 | c339ab5260583d07871bfb2617f35f754d8b3492 | 2,720 | fastcampus-test | Apache License 2.0 |
project/graphql-provider/src/main/kotlin/org/babyfish/graphql/provider/meta/impl/ModelPropImpl.kt | babyfish-ct | 441,469,557 | false | null | package org.babyfish.graphql.provider.meta.impl
import org.babyfish.graphql.provider.ModelException
import org.babyfish.graphql.provider.meta.*
import org.babyfish.kimmer.sql.meta.spi.EntityPropImpl
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
internal class ModelPropImpl(
declaringType: ModelTypeImpl,
kotlinProp: KProperty1<*, *>
): EntityPropImpl(declaringType, kotlinProp), ModelProp {
private var _userImplementation: UserImplementation? = null
private var _filter: Filter? = null
private var _hidden: Boolean = false
private var _batchSize: Int? = null
private var _securityPredicate: SecurityPredicate? = null
override val arguments: Arguments
get() = _userImplementation?.arguments
?: _filter?.arguments
?: Arguments.EMPTY
override val userImplementation: UserImplementation?
get() = _userImplementation
override val filter: Filter?
get() = _filter
override val hidden: Boolean
get() = hidden
override val batchSize: Int?
get() = _batchSize
override val securityPredicate: SecurityPredicate?
get() = _securityPredicate
override val name: String
get() = super.name
override val declaringType: ModelType
get() = super.declaringType as ModelType
override val targetType: ModelType?
get() = super.targetType as ModelType?
override val targetRawClass: KClass<*>
get() = super.targetType?.kotlinType ?: super.returnType
internal fun setUserImplementation(
userImplementation: UserImplementation
) {
if (!isTransient) {
error("Internal bug: '$this' is not transient property")
}
if (_userImplementation !== null) {
throw ModelException(
"The user implementation of '$this' has already been specified, don't specify again"
)
}
if (_filter !== null) {
throw ModelException(
"Cannot set the user implementation of '$this' because it filter has been set"
)
}
_userImplementation = userImplementation
}
internal fun setFilter(
filter: Filter
) {
if (_filter !== null) {
error("Internal bug: filter of '$this' can only be set once")
}
if (_userImplementation !== null) {
throw ModelException(
"Cannot set the filter of '$this' because it user implementation has been set"
)
}
_filter = filter
}
internal fun setHidden(hidden: Boolean) {
_hidden = hidden
}
internal fun setBatchSize(batchSize: Int?) {
_batchSize = batchSize
}
internal fun setSecurityPredicate(predicate: SecurityPredicate?) {
_securityPredicate = predicate
}
} | 0 | Kotlin | 2 | 14 | fa7c4aa64671a4f1050352130c6deadaa4f52985 | 2,862 | graphql-provider | MIT License |
app/src/main/java/com/qwict/studyplanetandroid/data/Planet.kt | Qwict | 698,396,315 | false | {"Kotlin": 62336} | package com.qwict.studyplanetandroid.data
import android.util.Log
import androidx.annotation.DrawableRes
import com.qwict.studyplanetandroid.R
class Planet constructor(
id: Int = 0,
name: String = "Unknown Planet",
@DrawableRes imageId: Int = R.drawable.earth,
) {
val id = id
val name = name
val imageId = imageId
init {
Log.d("Planet", "Planet created with name: $name and id: $id")
}
}
| 0 | Kotlin | 0 | 0 | 1e4944acab467afa1d066bc137b1ef130996eb4d | 432 | StudyPlanetAndroid | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/cloudwatch/CompositeAlarmPropsDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.cloudwatch
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.Boolean
import kotlin.String
import software.amazon.awscdk.Duration
import software.amazon.awscdk.services.cloudwatch.CompositeAlarmProps
import software.amazon.awscdk.services.cloudwatch.IAlarm
import software.amazon.awscdk.services.cloudwatch.IAlarmRule
/**
* Properties for creating a Composite Alarm.
*
* Example:
* ```
* Alarm alarm1;
* Alarm alarm2;
* Alarm alarm3;
* Alarm alarm4;
* IAlarmRule alarmRule = AlarmRule.anyOf(AlarmRule.allOf(AlarmRule.anyOf(alarm1,
* AlarmRule.fromAlarm(alarm2, AlarmState.OK), alarm3), AlarmRule.not(AlarmRule.fromAlarm(alarm4,
* AlarmState.INSUFFICIENT_DATA))), AlarmRule.fromBoolean(false));
* CompositeAlarm.Builder.create(this, "MyAwesomeCompositeAlarm")
* .alarmRule(alarmRule)
* .build();
* ```
*/
@CdkDslMarker
public class CompositeAlarmPropsDsl {
private val cdkBuilder: CompositeAlarmProps.Builder = CompositeAlarmProps.builder()
/** @param actionsEnabled Whether the actions for this alarm are enabled. */
public fun actionsEnabled(actionsEnabled: Boolean) {
cdkBuilder.actionsEnabled(actionsEnabled)
}
/**
* @param actionsSuppressor Actions will be suppressed if the suppressor alarm is in the ALARM
* state.
*/
public fun actionsSuppressor(actionsSuppressor: IAlarm) {
cdkBuilder.actionsSuppressor(actionsSuppressor)
}
/**
* @param actionsSuppressorExtensionPeriod The maximum duration that the composite alarm waits
* after suppressor alarm goes out of the ALARM state. After this time, the composite alarm
* performs its actions.
*/
public fun actionsSuppressorExtensionPeriod(actionsSuppressorExtensionPeriod: Duration) {
cdkBuilder.actionsSuppressorExtensionPeriod(actionsSuppressorExtensionPeriod)
}
/**
* @param actionsSuppressorWaitPeriod The maximum duration that the composite alarm waits for
* the suppressor alarm to go into the ALARM state. After this time, the composite alarm
* performs its actions.
*/
public fun actionsSuppressorWaitPeriod(actionsSuppressorWaitPeriod: Duration) {
cdkBuilder.actionsSuppressorWaitPeriod(actionsSuppressorWaitPeriod)
}
/** @param alarmDescription Description for the alarm. */
public fun alarmDescription(alarmDescription: String) {
cdkBuilder.alarmDescription(alarmDescription)
}
/**
* @param alarmRule Expression that specifies which other alarms are to be evaluated to
* determine this composite alarm's state.
*/
public fun alarmRule(alarmRule: IAlarmRule) {
cdkBuilder.alarmRule(alarmRule)
}
/** @param compositeAlarmName Name of the alarm. */
public fun compositeAlarmName(compositeAlarmName: String) {
cdkBuilder.compositeAlarmName(compositeAlarmName)
}
public fun build(): CompositeAlarmProps = cdkBuilder.build()
}
| 4 | Kotlin | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 3,220 | awscdk-dsl-kotlin | Apache License 2.0 |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/ses/CfnVdmAttributesPropsDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.ses
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.ses.CfnVdmAttributesProps
@Generated
public fun buildCfnVdmAttributesProps(initializer: @AwsCdkDsl
CfnVdmAttributesProps.Builder.() -> Unit): CfnVdmAttributesProps =
CfnVdmAttributesProps.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | 451a1e42282de74a9a119a5716bd95b913662e7c | 419 | aws-cdk-kt | Apache License 2.0 |
src/commonMain/kotlin/com/codeborne/selenide/impl/TailOfCollection.kt | TarCV | 358,762,107 | true | {"Kotlin": 998044, "Java": 322706, "HTML": 46587, "XSLT": 7418} | package com.codeborne.selenide.impl
import com.codeborne.selenide.Driver
import org.openqa.selenium.WebElement
class TailOfCollection(private val originalCollection: CollectionSource, private val size: Int) : CollectionSource {
private var alias = Alias.NONE
override suspend fun getElements(): List<org.openqa.selenium.WebElement> {
val source = originalCollection.getElements()
val sourceCollectionSize = source.size
return source.subList(startingIndex(sourceCollectionSize), sourceCollectionSize)
}
override suspend fun getElement(index: Int): org.openqa.selenium.WebElement {
val source = originalCollection.getElements()
val sourceCollectionSize = source.size
val startingIndex = startingIndex(sourceCollectionSize)
return originalCollection.getElement(startingIndex + index)
}
private fun startingIndex(sourceCollectionSize: Int): Int {
return sourceCollectionSize - kotlin.math.min(sourceCollectionSize, size)
}
override fun description(): String {
return alias.getOrElse { originalCollection.description() + ":last(" + size + ')' }
}
override fun driver(): Driver {
return originalCollection.driver()
}
override fun setAlias(alias: String) {
this.alias = Alias(alias)
}
}
| 0 | Kotlin | 0 | 0 | c86103748bdf214adb8a027492d21765059d3629 | 1,324 | selenide.kt-js | MIT License |
app/src/main/java/com/prosabdev/fluidmusic/viewmodels/models/explore/AlbumArtistItemViewModel.kt | 4kpros | 555,755,264 | false | {"Kotlin": 948923, "Java": 1923} | package com.prosabdev.fluidmusic.viewmodels.models.explore
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import com.prosabdev.common.models.view.AlbumArtistItem
import com.prosabdev.common.roomdatabase.repositories.explore.AlbumArtistItemRepository
class AlbumArtistItemViewModel(app: Application) : AndroidViewModel(app) {
private var mRepository: AlbumArtistItemRepository? = AlbumArtistItemRepository(app)
suspend fun getAtName(name : String) : AlbumArtistItem? {
return mRepository?.getAtName(name)
}
suspend fun getAll(orderBy: String) : LiveData<List<AlbumArtistItem>>? {
return mRepository?.getAll(orderBy)
}
suspend fun getAllDirectly(orderBy: String) : List<AlbumArtistItem>? {
return mRepository?.getAllDirectly(orderBy)
}
} | 0 | Kotlin | 0 | 2 | c9363fa150d1cd34b0fac119c825bfe75e2f96e1 | 853 | FluidMusic | Apache License 2.0 |
data/RF03643/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF03643"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
3 to 7
68 to 72
}
value = "#3469c3"
}
color {
location {
9 to 14
61 to 66
}
value = "#dc27a8"
}
color {
location {
16 to 30
45 to 59
}
value = "#de84cb"
}
color {
location {
32 to 33
42 to 43
}
value = "#0f4e6c"
}
color {
location {
8 to 8
67 to 67
}
value = "#e2e8a8"
}
color {
location {
15 to 15
60 to 60
}
value = "#6fed4f"
}
color {
location {
31 to 31
44 to 44
}
value = "#620c0d"
}
color {
location {
34 to 41
}
value = "#d5edbb"
}
color {
location {
1 to 2
}
value = "#7c0dba"
}
color {
location {
73 to 74
}
value = "#6a28cf"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 1,647 | Rfam-for-RNArtist | MIT License |
src/main/kotlin/no/skatteetaten/aurora/gobo/security/SharedSecretReader.kt | Skatteetaten | 135,263,220 | false | null | package no.skatteetaten.aurora.gobo.security
import mu.KotlinLogging
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import java.io.File
import java.io.IOException
private val logger = KotlinLogging.logger {}
/**
* Component for reading the shared secret used for authentication. You may specify the shared secret directly using
* the aurora.token.value property, or specify a file containing the secret with the aurora.token.location property.
*/
@Component
class SharedSecretReader(
@Value("\${aurora.token.location:}") private val secretLocation: String?,
@Value("\${aurora.token.value:}") private val secretValue: String?
) {
val secret = initSecret(secretValue)
private fun initSecret(secretValue: String?) =
if (secretLocation.isNullOrEmpty() && secretValue.isNullOrEmpty()) {
throw IllegalArgumentException("Either aurora.token.location or aurora.token.value must be specified")
} else {
if (secretValue.isNullOrEmpty()) {
val secretFile = File(secretLocation).absoluteFile
try {
logger.info("Reading token from file {}", secretFile.absolutePath)
secretFile.readText()
} catch (e: IOException) {
throw IllegalStateException("Unable to read shared secret from specified location [${secretFile.absolutePath}]")
}
} else {
secretValue
}
}
}
| 0 | null | 0 | 3 | 9a28e1d711756479696672f139568fdeadb74ac1 | 1,539 | gobo | Apache License 2.0 |
experimental/examples/imageviewer/shared/src/commonMain/kotlin/example/imageviewer/Dependencies.kt | JetBrains | 293,498,508 | false | null | package example.imageviewer
import androidx.compose.ui.graphics.ImageBitmap
import example.imageviewer.core.BitmapFilter
import example.imageviewer.core.FilterType
import example.imageviewer.model.ContentRepository
import example.imageviewer.model.Picture
import example.imageviewer.model.name
import io.ktor.client.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.serialization.json.Json
interface Dependencies {
val httpClient: HttpClient
val ioScope: CoroutineScope
fun getFilter(type: FilterType): BitmapFilter
val localization: Localization
val imageRepository: ContentRepository<ImageBitmap>
val notification: Notification
val json: Json get() = jsonReader
}
interface Notification {
fun notifyInvalidRepo()
fun notifyRepoIsEmpty()
fun notifyNoInternet()
fun notifyLoadImageUnavailable()
fun notifyLastImage()
fun notifyFirstImage()
fun notifyImageData(picture: Picture)
fun notifyRefreshUnavailable()
}
abstract class PopupNotification(private val localization: Localization) : Notification {
abstract fun showPopUpMessage(text: String)
override fun notifyInvalidRepo() = showPopUpMessage(localization.repoInvalid)
override fun notifyRepoIsEmpty() = showPopUpMessage(localization.repoEmpty)
override fun notifyNoInternet() = showPopUpMessage(localization.noInternet)
override fun notifyLoadImageUnavailable() =
showPopUpMessage(
"""
${localization.noInternet}
${localization.loadImageUnavailable}
""".trimIndent()
)
override fun notifyLastImage() = showPopUpMessage(localization.lastImage)
override fun notifyFirstImage() = showPopUpMessage(localization.firstImage)
override fun notifyImageData(picture: Picture) = showPopUpMessage(
"${localization.picture} ${picture.name}"
)
override fun notifyRefreshUnavailable() = showPopUpMessage(
"""
${localization.noInternet}
${localization.refreshUnavailable}
""".trimIndent()
)
}
interface Localization {
val back: String
val appName: String
val loading: String
val repoInvalid: String
val repoEmpty: String
val noInternet: String
val loadImageUnavailable: String
val lastImage: String
val firstImage: String
val picture: String
val size: String
val pixels: String
val refreshUnavailable: String
}
private val jsonReader: Json = Json {
ignoreUnknownKeys = true
}
| 824 | Kotlin | 779 | 10,200 | aa64d2d232d7f8fd310f7423fec9a3f8dd90a840 | 2,512 | compose-jb | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Elephant.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.Elephant: ImageVector
get() {
if (_elephant != null) {
return _elephant!!
}
_elephant = Builder(name = "Elephant", 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(21.995f, 17.0f)
verticalLineToRelative(2.899f)
curveToRelative(0.0f, 0.537f, -0.364f, 1.015f, -0.829f, 1.087f)
curveToRelative(-0.297f, 0.044f, -0.584f, -0.031f, -0.804f, -0.219f)
curveToRelative(-0.221f, -0.189f, -0.348f, -0.469f, -0.348f, -0.768f)
verticalLineToRelative(-10.547f)
curveToRelative(0.0f, -1.794f, -0.908f, -3.481f, -2.396f, -4.494f)
curveToRelative(-0.854f, -2.349f, -3.11f, -3.958f, -5.618f, -3.958f)
curveToRelative(-2.757f, 0.0f, -5.0f, 2.243f, -5.0f, 5.0f)
reflectiveCurveToRelative(2.243f, 5.0f, 5.0f, 5.0f)
verticalLineToRelative(2.0f)
curveToRelative(-3.859f, 0.0f, -7.0f, -3.14f, -7.0f, -7.0f)
curveToRelative(0.0f, -1.068f, 0.247f, -2.077f, 0.677f, -2.984f)
curveToRelative(-3.158f, 0.169f, -5.677f, 2.784f, -5.677f, 5.984f)
verticalLineToRelative(14.0f)
horizontalLineToRelative(4.99f)
lineToRelative(0.01f, -4.0f)
horizontalLineToRelative(6.5f)
lineToRelative(-0.009f, 4.0f)
horizontalLineToRelative(4.528f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(1.995f)
verticalLineToRelative(0.998f)
curveToRelative(0.0f, 0.883f, 0.381f, 1.717f, 1.046f, 2.288f)
curveToRelative(0.542f, 0.464f, 1.23f, 0.713f, 1.941f, 0.713f)
curveToRelative(0.156f, 0.0f, 0.313f, -0.012f, 0.471f, -0.036f)
curveToRelative(1.438f, -0.224f, 2.522f, -1.541f, 2.522f, -3.063f)
verticalLineToRelative(-2.899f)
horizontalLineToRelative(-2.0f)
close()
}
}
.build()
return _elephant!!
}
private var _elephant: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,061 | icons | MIT License |
app/src/main/java/com/example/favfood/FavFoodApp.kt | Ali-PRGW | 837,326,364 | false | {"Kotlin": 30278} | package com.example.favfood
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class FavFoodApp : Application() {
} | 0 | Kotlin | 0 | 0 | afecb7aa9399fe75712eb5510eb43ac4243ebf4e | 155 | favFoodMain | MIT License |
src/v_builders/_37_StringAndMapBuilders.kt | dreamoftch | 87,521,265 | true | {"Kotlin": 86137, "Java": 4349} | package v_builders
import util.TODO
fun buildStringExample(): String {
fun buildString(build: StringBuilder.() -> Unit): String {
val stringBuilder = StringBuilder()
stringBuilder.build()
return stringBuilder.toString()
}
return buildString {
this.append("Numbers: ")
for (i in 1..10) {
// 'this' can be omitted
append(i)
}
}
}
fun todoTask37(): Nothing = TODO(
"""
Task 37.
Uncomment the commented code and make it compile.
Add and implement function 'buildMap' with one parameter (of type extension function) creating a new HashMap,
building it and returning it as a result.
"""
)
//build: MutableMap<K, V>.() -> Unit 跟前面的测试中val isOdd: Int.() -> Boolean { this % 2 == 0} 一样,相当于
//定义了一个匿名扩展函数,并赋给了一个变量
fun <K, V> buildMap(build: MutableMap<K, V>.() -> Unit): MutableMap<K, V> {
val map = mutableMapOf<K, V>()
map.build()
return map
}
fun task37(): Map<Int, String> {
return buildMap {
put(0, "0")
for (i in 1..10) {
put(i, "$i")
}
}
}
| 0 | Kotlin | 0 | 0 | a7f98762d65826e17a4384c462eb0e8d68a9f2ef | 1,125 | kotlin-koans | MIT License |
eth/abi/src/commonMain/kotlin/kosh/eth/abi/coder/Eip712MessageDecoder.kt | niallkh | 855,100,709 | false | {"Kotlin": 1813876, "Swift": 594} | package kosh.eth.abi.coder
import com.ionspin.kotlin.bignum.integer.Sign
import com.ionspin.kotlin.bignum.integer.toBigInteger
import kosh.eth.abi.Type
import kosh.eth.abi.Value
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
import okio.ByteString.Companion.decodeHex
internal class Eip712MessageDecoder(
message: JsonElement,
) : Coder {
private val jsonStack = ArrayDeque(listOf(message))
internal val valueStack = ArrayDeque<Value>()
internal inline fun <reified V : Value> value(): V = valueStack.last() as V
private inline fun <reified V : Value> popValue(): V = valueStack.removeLast() as V
override fun uint(type: Type.UInt) {
bigint()
val value = popValue<Value.BigNumber>()
check(value.value.getSign() != Sign.NEGATIVE)
valueStack += value
}
override fun int(type: Type.Int) {
bigint()
}
private fun bigint() {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
jsonPrimitive.longOrNull?.let {
valueStack += Value.BigNumber(it.toBigInteger())
}
val bigInt = if (jsonPrimitive.content.startsWith("0x")) {
jsonPrimitive.content.toBigInteger(16)
} else {
jsonPrimitive.content.toBigInteger()
}
valueStack += Value.BigNumber(bigInt)
}
override fun bool(type: Type.Bool) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
valueStack += Value.Bool(jsonPrimitive.boolean)
}
override fun address(type: Type.Address) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
valueStack += Value.Address(jsonPrimitive.content.removePrefix("0x").decodeHex())
}
override fun fixedBytes(type: Type.FixedBytes) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
valueStack += Value.Bytes(jsonPrimitive.content.removePrefix("0x").decodeHex())
}
override fun function(type: Type.Function) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
val bytes = jsonPrimitive.content.removePrefix("0x").decodeHex()
valueStack += Value.Function(Value.Address(bytes.substring(0, 20)), bytes.substring(20, 24))
}
override fun dynamicBytes(type: Type.DynamicBytes) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
valueStack += Value.Bytes(jsonPrimitive.content.removePrefix("0x").decodeHex())
}
override fun dynamicString(type: Type.DynamicString) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
valueStack += Value.String(jsonPrimitive.content)
}
override fun dynamicArray(type: Type.DynamicArray) {
return fixedArray(
size = jsonStack.last().jsonArray.size.toUInt(),
childType = type.type
)
}
override fun fixedArray(type: Type.FixedArray) {
fixedArray(type.size, type.type)
}
private fun fixedArray(size: UInt, childType: Type) {
val jsonArray = jsonStack.removeLast().jsonArray
check(jsonArray.size == size.toInt())
valueStack.addLast(Value.Array(
jsonArray.map { jsonElement ->
jsonStack.addLast(jsonElement)
childType.code(this)
popValue()
}
))
}
override fun tuple(tuple: Type.Tuple) {
val jsonObject = jsonStack.removeLast().jsonObject
check(tuple.size == jsonObject.size)
valueStack.addLast(Value.Tuple(
tuple.map {
val jsonElement = jsonObject[it.name] ?: error("no value for param ${it.name}")
jsonStack.addLast(jsonElement)
it.type.code(this)
popValue()
}
))
}
}
| 0 | Kotlin | 0 | 3 | f48555a563dfee5b07184771a6c94c065765d570 | 3,982 | kosh | MIT License |
eth/abi/src/commonMain/kotlin/kosh/eth/abi/coder/Eip712MessageDecoder.kt | niallkh | 855,100,709 | false | {"Kotlin": 1813876, "Swift": 594} | package kosh.eth.abi.coder
import com.ionspin.kotlin.bignum.integer.Sign
import com.ionspin.kotlin.bignum.integer.toBigInteger
import kosh.eth.abi.Type
import kosh.eth.abi.Value
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
import okio.ByteString.Companion.decodeHex
internal class Eip712MessageDecoder(
message: JsonElement,
) : Coder {
private val jsonStack = ArrayDeque(listOf(message))
internal val valueStack = ArrayDeque<Value>()
internal inline fun <reified V : Value> value(): V = valueStack.last() as V
private inline fun <reified V : Value> popValue(): V = valueStack.removeLast() as V
override fun uint(type: Type.UInt) {
bigint()
val value = popValue<Value.BigNumber>()
check(value.value.getSign() != Sign.NEGATIVE)
valueStack += value
}
override fun int(type: Type.Int) {
bigint()
}
private fun bigint() {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
jsonPrimitive.longOrNull?.let {
valueStack += Value.BigNumber(it.toBigInteger())
}
val bigInt = if (jsonPrimitive.content.startsWith("0x")) {
jsonPrimitive.content.toBigInteger(16)
} else {
jsonPrimitive.content.toBigInteger()
}
valueStack += Value.BigNumber(bigInt)
}
override fun bool(type: Type.Bool) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
valueStack += Value.Bool(jsonPrimitive.boolean)
}
override fun address(type: Type.Address) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
valueStack += Value.Address(jsonPrimitive.content.removePrefix("0x").decodeHex())
}
override fun fixedBytes(type: Type.FixedBytes) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
valueStack += Value.Bytes(jsonPrimitive.content.removePrefix("0x").decodeHex())
}
override fun function(type: Type.Function) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
val bytes = jsonPrimitive.content.removePrefix("0x").decodeHex()
valueStack += Value.Function(Value.Address(bytes.substring(0, 20)), bytes.substring(20, 24))
}
override fun dynamicBytes(type: Type.DynamicBytes) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
valueStack += Value.Bytes(jsonPrimitive.content.removePrefix("0x").decodeHex())
}
override fun dynamicString(type: Type.DynamicString) {
val jsonPrimitive = jsonStack.removeLast().jsonPrimitive
valueStack += Value.String(jsonPrimitive.content)
}
override fun dynamicArray(type: Type.DynamicArray) {
return fixedArray(
size = jsonStack.last().jsonArray.size.toUInt(),
childType = type.type
)
}
override fun fixedArray(type: Type.FixedArray) {
fixedArray(type.size, type.type)
}
private fun fixedArray(size: UInt, childType: Type) {
val jsonArray = jsonStack.removeLast().jsonArray
check(jsonArray.size == size.toInt())
valueStack.addLast(Value.Array(
jsonArray.map { jsonElement ->
jsonStack.addLast(jsonElement)
childType.code(this)
popValue()
}
))
}
override fun tuple(tuple: Type.Tuple) {
val jsonObject = jsonStack.removeLast().jsonObject
check(tuple.size == jsonObject.size)
valueStack.addLast(Value.Tuple(
tuple.map {
val jsonElement = jsonObject[it.name] ?: error("no value for param ${it.name}")
jsonStack.addLast(jsonElement)
it.type.code(this)
popValue()
}
))
}
}
| 0 | Kotlin | 0 | 3 | f48555a563dfee5b07184771a6c94c065765d570 | 3,982 | kosh | MIT License |
src/main/java/com/github/shur/harukatrade/HarukaTrade.kt | SigureRuri | 388,654,817 | false | null | package com.github.shur.harukatrade
import com.github.shur.harukatrade.api.TradeRegistry
import com.github.shur.harukatrade.command.HarukaTradeCommand
import com.github.shur.harukatrade.listener.PlayerInteractListener
import com.github.shur.harukatrade.tradeloader.TradeLoader
import com.github.shur.harukatrade.tradeloader.drip.DripTradeLoader
import org.bukkit.plugin.java.JavaPlugin
class HarukaTrade : JavaPlugin() {
override fun onEnable() {
instance = this
tradeRegistry = HarukaTradeRegistry()
tradeLoaders.add(DripTradeLoader())
loadTrades()
HarukaTradeCommand.registerCommand()
server.pluginManager.registerEvents(PlayerInteractListener(), this)
}
fun loadTrades() {
tradeLoaders.forEach {
it.load()
}
}
companion object {
lateinit var instance: HarukaTrade
private set
lateinit var tradeRegistry: TradeRegistry
private set
val tradeLoaders: MutableList<TradeLoader> = mutableListOf()
}
} | 0 | Kotlin | 0 | 0 | 42b343f7466e6d4cc3034cc4d662b33167ac0071 | 1,059 | HarukaTrade | MIT License |
healthcheck/healthcheck/src/test/kotlin/com/manhinhang/ibgatewaydocker/healthcheck/AppTest.kt | manhinhang | 269,861,279 | false | {"Kotlin": 13171, "Python": 7322, "Dockerfile": 3679, "Shell": 2121} | /*
* This source file was generated by the Gradle 'init' task
*/
package com.manhinhang.ibgatewaydocker.healthcheck
import kotlin.test.Test
import kotlin.test.assertNotNull
class AppTest {
@Test fun appHasAGreeting() {
}
}
| 3 | Kotlin | 42 | 90 | a57a48a156e696302a1084bbf852228ca36ee471 | 236 | ib-gateway-docker | MIT License |
src/main/kotlin/tech/kaxon/projects/bot/utils/UtilAcronymConverter.kt | kaxlabs | 298,455,167 | false | null | package tech.kaxon.projects.bot.utils
import tech.kaxon.projects.bot.main.Main
import java.math.BigDecimal
import java.text.DecimalFormat
object UtilAcronymConverter {
fun convertBigDecimal(number: String): String {
if (number.length <= 1) return "0"
val last = number[number.length - 1]
var value = if (number.length > 1) {
BigDecimal(number.substring(0, number.length - 1))
} else {
BigDecimal(number)
}
when (last.toLowerCase()) {
'k' -> value = value.multiply(BigDecimal("1000"))
'm' -> value = value.multiply(BigDecimal("1000000"))
}
return value.toString()
}
fun reverseBigDecimal(number: BigDecimal): String {
val value: BigDecimal
val result: String
when {
number.divide(BigDecimal("1000000")) < BigDecimal.ONE -> {
value = number.divide(BigDecimal("1000"))
result = Main.decimalFormatter.format(value) + "K"
}
number.divide(BigDecimal("1000000")) >= BigDecimal.ONE -> {
value = number.divide(BigDecimal("1000000"))
result = DecimalFormat("0.#####").format(value) + "M"
}
else -> throw NullPointerException("Couldn't reverse value!")
}
return result
}
fun formatInt(number: String): Int {
if (number.length <= 1) return 0
val last = number[number.length - 1]
var value = if (number.length > 1) {
number.substring(0, number.length - 1).toInt()
} else {
number.toInt()
}
when (last.toLowerCase()) {
'k' -> value *= 1000
'm' -> value *= 1000000
}
return value
}
} | 0 | Kotlin | 0 | 0 | c4b41e87df5d0240180926b9abdf20fdd8d50cd1 | 1,784 | discord-sbs-bot | Creative Commons Zero v1.0 Universal |
shared-ui-compose/src/desktopMain/kotlin/com/expressus/compose/desktop/rightPanel/PlasticTilePreview.kt | GuilhE | 483,274,962 | false | {"Kotlin": 123318, "Swift": 43152, "Ruby": 4889} | package com.expressus.android.presentation.previews.rightPanel
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.expressus.compose.components.rightPanel.PlasticTile
import com.expressus.compose.themes.CoffeeSelectorsTheme
@Composable
@Preview
private fun PlasticTilePreview() {
CoffeeSelectorsTheme {
Column {
PlasticTile(
Modifier
.fillMaxWidth()
.height(30.dp),
backgroundColor = MaterialTheme.colorScheme.secondary,
)
Spacer(Modifier.size(10.dp))
PlasticTile(
Modifier
.fillMaxWidth()
.height(30.dp),
backgroundColor = MaterialTheme.colorScheme.secondary,
withGlossy = false
)
}
}
} | 0 | Kotlin | 10 | 110 | 4e050cc9cfa31baddfe18f344b7f67dceb968320 | 1,254 | Expressus | Apache License 2.0 |
src/main/kotlin/br/com/lambdateam/myaccess/model/PostUser.kt | kbmbarreto | 501,107,203 | false | null | package br.com.lambdateam.myaccess.model
data class PostUser (
val userName: String,
val email: String,
val password: String
) | 0 | Kotlin | 0 | 1 | fd657935b6f8682d72c312069126888fba602715 | 140 | myaccess_backend_kotlin | MIT License |
src/main/kotlin/data/loading/LoadSystemData.kt | Lukas22041 | 584,573,431 | false | {"Kotlin": 73683} | package data.loading
import data.*
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.csv.Csv
import kotlinx.serialization.csv.CsvConfiguration
import java.io.File
class LoadSystemData(var basepath: String, var modID: String)
{
fun load()
{
loadCSV()
}
@OptIn(ExperimentalSerializationApi::class)
private fun loadCSV()
{
val file = File(basepath + DataPath.ShipSystemsCSV)
val config = CsvConfiguration(ignoreEmptyLines = true, ignoreUnknownColumns = true, hasHeaderRecord = true, recordSeparator = "\n")
val csv = Csv(config)
var data = csv.decodeFromString(ListSerializer(ShipsystemData.serializer()), file.readText())
LoadedData.LoadedShipsystemData.put(modID, data.toMutableList())
}
} | 0 | Kotlin | 0 | 0 | a62a3d2ce63ce3d53fab6848df5d07e97cce0d1b | 859 | Codex | MIT License |
domain/src/main/java/com/bottlerocketstudios/brarchitecture/domain/models/Author.kt | BottleRocketStudios | 323,985,026 | false | null | package com.bottlerocketstudios.brarchitecture.domain.models
data class Author(
val user: User?,
)
| 1 | Kotlin | 1 | 9 | e8541ccaa52782c5c2440b8a4fe861ef9178111e | 104 | Android-ArchitectureDemo | Apache License 2.0 |
app/src/main/java/com/jetpack/countrylist/MainActivity.kt | MakeItEasyDev | 409,824,181 | false | {"Kotlin": 10407} | package com.jetpack.countrylist
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.jetpack.countrylist.ui.theme.CountryListTheme
import com.jetpack.countrylist.ui.theme.Purple500
import java.util.*
import kotlin.collections.ArrayList
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CountryListTheme {
Surface(color = MaterialTheme.colors.background) {
Scaffold(
topBar = { TopBar() },
backgroundColor = Purple500
) {
CountryNavigation()
}
}
}
}
}
}
@Composable
fun TopBar() {
TopAppBar(
title = { Text(text = "Country List", fontSize = 20.sp, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center) },
backgroundColor = Purple500,
contentColor = Color.White
)
}
@Composable
fun CountryNavigation() {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = "CountryList"
) {
composable("CountryList") {
CountryListScreen(navController)
}
}
}
@Composable
fun CountryListScreen(navController: NavHostController) {
val textVal = remember { mutableStateOf(TextFieldValue("")) }
Column {
SearchCountryList(textVal)
CountryList(textVal)
}
}
@Composable
fun SearchCountryList(textVal: MutableState<TextFieldValue>) {
TextField(
value = textVal.value,
onValueChange = { textVal.value = it },
placeholder = { Text(text = "Search Country Name") },
modifier = Modifier
.fillMaxWidth(),
textStyle = TextStyle(Color.Black, fontSize = 18.sp),
leadingIcon = {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = "Search",
modifier = Modifier
.padding(15.dp)
.size(24.dp)
)
},
trailingIcon = {
if (textVal.value != TextFieldValue("")) {
IconButton(
onClick = {
textVal.value = TextFieldValue("")
}
) {
Icon(
imageVector = Icons.Filled.Close,
contentDescription = "Close",
modifier = Modifier
.padding(15.dp)
.size(24.dp)
)
}
}
},
singleLine = true,
shape = RectangleShape,
colors = TextFieldDefaults.textFieldColors(
textColor = Color.Black,
cursorColor = Color.Black,
leadingIconColor = Color.Black,
trailingIconColor = Color.Black,
backgroundColor = Color.White,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent
)
)
}
@Composable
fun CountryList(textVal: MutableState<TextFieldValue>) {
val context = LocalContext.current
val countries = getListOfCountries()
var filteredCountries: ArrayList<String>
LazyColumn(
modifier = Modifier.fillMaxWidth()
) {
val searchText = textVal.value.text
filteredCountries = if (searchText.isEmpty()) {
countries
} else {
val resultList = ArrayList<String>()
for (country in countries) {
if (country.lowercase(Locale.getDefault()).contains(searchText.lowercase(Locale.getDefault()))) {
resultList.add(country)
}
}
resultList
}
items(filteredCountries) { filteredCountries ->
CountryListItem(
countryText = filteredCountries,
onItemClick = { selectedCountry ->
Toast.makeText(context, selectedCountry, Toast.LENGTH_SHORT).show()
}
)
}
}
}
@Composable
fun CountryListItem(
countryText: String,
onItemClick: (String) -> Unit
) {
Row(
modifier = Modifier
.clickable {
onItemClick(countryText)
}
.background(Color.White)
.height(60.dp)
.fillMaxWidth()
.padding(5.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = countryText,
fontSize = 16.sp,
color = Color.Black,
modifier = Modifier.padding(start = 10.dp)
)
}
}
@Composable
fun getListOfCountries(): ArrayList<String> {
val isoCountryCodes = Locale.getISOCountries()
val countryListWithEmojis = ArrayList<String>()
for (countryCode in isoCountryCodes) {
val locale = Locale("", countryCode)
val countryName = locale.displayCountry
val flagOffset = 0x1F1E6
val asciiOffset = 0x41
val firstChar = Character.codePointAt(countryCode, 0) - asciiOffset + flagOffset
val secondChar = Character.codePointAt(countryCode, 1) - asciiOffset + flagOffset
val flag = (String(Character.toChars(firstChar)) + String(Character.toChars(secondChar)))
countryListWithEmojis.add("$countryName (${locale.country}) $flag")
}
return countryListWithEmojis
}
| 0 | Kotlin | 2 | 5 | 991bcf257f584f090fe8f23507376549e491f0bc | 6,932 | Jetpack-Compose-CountryList-and-Auto-Complete-Search | Apache License 2.0 |
cli/src/main/kotlin/org/rewedigital/konversation/generator/dialogflow/QuickReply.kt | rewe-digital | 171,288,628 | false | null | package org.rewedigital.konversation.generator.dialogflow
import org.rewedigital.konversation.generator.NodeExporter
import org.rewedigital.konversation.generator.Printer
data class QuickReply(
val lang: String,
val replies: List<String>
) : NodeExporter {
override fun prettyPrinted(printer: Printer) {
printer("""
{
"type": 2,
"lang": "$lang",
"replies": [""")
printer(replies.joinToString(separator = ",", postfix = "\n") { "\n \"${it.escape()}\"" })
printer(" ]\n }")
}
override fun minified(printer: Printer) {
printer("""{"type":2,"lang":"$lang","replies":[""")
printer(replies.joinToString(separator = ",", postfix = "]}") { "\"${it.escape()}\"" })
}
private fun String.escape() =
replace("\\", "\\\\")
.replace("\r", "\\r")
.replace("\n", "\\n")
.replace("\"", "\\")
} | 3 | Kotlin | 1 | 15 | 01398570426b16b512f6e03cc4b0a67b1cbac9cf | 957 | Konversation | MIT License |
app/src/main/java/com/pimenta/bestv/feature/workdetail/domain/IsFavoriteUseCase.kt | Vij4yk | 222,473,642 | true | {"Kotlin": 381718} | /*
* Copyright (C) 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.pimenta.bestv.feature.workdetail.domain
import com.pimenta.bestv.common.presentation.model.WorkType
import com.pimenta.bestv.common.presentation.model.WorkViewModel
import com.pimenta.bestv.data.MediaRepository
import javax.inject.Inject
/**
* Created by marcus on 18-04-2019.
*/
class IsFavoriteUseCase @Inject constructor(
private val mediaRepository: MediaRepository
) {
operator fun invoke(workViewModel: WorkViewModel) =
when (workViewModel.type) {
WorkType.MOVIE -> mediaRepository.isFavoriteMovie(workViewModel.id)
WorkType.TV_SHOW -> mediaRepository.isFavoriteTvShow(workViewModel.id)
}
} | 0 | null | 0 | 1 | c843d997a801389f929b9a1fd754047ae1b348a0 | 1,262 | BesTV | Apache License 2.0 |
corecomponent/core/src/main/java/com/komeyama/simple/weather/core/extentions/Fragment.kt | Komeyama | 272,177,961 | false | null | package com.komeyama.simple.weather.core.extentions
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
/*
todo
*/
inline fun <reified T : ViewModel> Fragment.assistedViewModels(
crossinline body: () -> T
): Lazy<T> {
return viewModels {
object : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return body() as T
}
}
}
}
/*
todo
*/
inline fun <reified T : ViewModel> Fragment.assistedActivityViewModels(
crossinline body: () -> T
): Lazy<T> {
return activityViewModels {
object : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return body() as T
}
}
}
} | 0 | Kotlin | 0 | 0 | d08c80a62b3b26a4b17583ebbd58361fc52f01ff | 1,060 | simple-weather-forecast | MIT License |
coil-network/src/commonMain/kotlin/coil3/network/CacheResponse.kt | coil-kt | 201,684,760 | false | null | package coil3.network
import coil3.network.internal.CACHE_CONTROL
import coil3.network.internal.CONTENT_TYPE
import coil3.network.internal.append
import io.ktor.client.statement.HttpResponse
import io.ktor.http.Headers
import io.ktor.http.headers
import okio.BufferedSink
import okio.BufferedSource
/** Holds the response metadata for an image in the disk cache. */
class CacheResponse {
val cacheControl: String? get() = responseHeaders[CACHE_CONTROL]
val contentType: String? get() = responseHeaders[CONTENT_TYPE]
val sentRequestAtMillis: Long
val receivedResponseAtMillis: Long
val responseHeaders: Headers
constructor(source: BufferedSource) {
this.sentRequestAtMillis = source.readUtf8LineStrict().toLong()
this.receivedResponseAtMillis = source.readUtf8LineStrict().toLong()
this.responseHeaders = headers {
val responseHeadersLineCount = source.readUtf8LineStrict().toInt()
for (i in 0 until responseHeadersLineCount) {
append(source.readUtf8LineStrict())
}
}
}
constructor(response: HttpResponse, headers: Headers = response.headers) {
this.sentRequestAtMillis = response.requestTime.timestamp
this.receivedResponseAtMillis = response.responseTime.timestamp
this.responseHeaders = headers
}
fun writeTo(sink: BufferedSink) {
sink.writeDecimalLong(sentRequestAtMillis).writeByte('\n'.code)
sink.writeDecimalLong(receivedResponseAtMillis).writeByte('\n'.code)
val responseHeaders = responseHeaders.entries()
val responseHeadersLineCount = responseHeaders.sumOf { it.value.size }.toLong()
sink.writeDecimalLong(responseHeadersLineCount).writeByte('\n'.code)
for (header in responseHeaders) {
for (value in header.value) {
sink.writeUtf8(header.key)
.writeUtf8(":")
.writeUtf8(value)
.writeByte('\n'.code)
}
}
}
}
| 42 | null | 626 | 9,954 | 9b3f851b2763b4c72a3863f8273b8346487b363b | 2,031 | coil | Apache License 2.0 |
src/main/kotlin/kr/nagaza/nagazaserver/domain/exception/CafeException.kt | NAGAZA-Team | 706,076,040 | false | {"Kotlin": 115663, "Shell": 637} | package kr.nagaza.nagazaserver.domain.exception
class CafeNotFoundException : DomainException(ErrorCode.CAFE_NOT_FOUND)
class CafeRoomNotFoundException : DomainException(ErrorCode.CAFE_ROOM_NOT_FOUND)
| 0 | Kotlin | 1 | 1 | 331acd205503767bd55495fa7b1fd394f8962361 | 203 | NAGAZA-Server | MIT License |
covpass-sdk/src/main/java/de/rki/covpass/sdk/revocation/RevocationLocalListRepository.kt | Digitaler-Impfnachweis | 376,239,258 | false | null | /*
* (C) Copyright IBM Deutschland GmbH 2021
* (C) Copyright IBM Corp. 2021
*/
package de.rki.covpass.sdk.revocation
import COSE.OneKey
import COSE.Sign1Message
import com.ensody.reactivestate.MutableValueFlow
import com.ensody.reactivestate.SuspendMutableValueFlow
import com.upokecenter.cbor.CBORObject
import de.rki.covpass.sdk.dependencies.defaultJson
import de.rki.covpass.sdk.revocation.RevocationLocalListRepository.Companion.UPDATE_INTERVAL_HOURS
import de.rki.covpass.sdk.revocation.database.RevocationByteOneLocal
import de.rki.covpass.sdk.revocation.database.RevocationByteTwoLocal
import de.rki.covpass.sdk.revocation.database.RevocationDatabase
import de.rki.covpass.sdk.revocation.database.RevocationIndexLocal
import de.rki.covpass.sdk.revocation.database.RevocationKidLocal
import de.rki.covpass.sdk.storage.CborSharedPrefsStore
import de.rki.covpass.sdk.storage.DscRepository.Companion.NO_UPDATE_YET
import de.rki.covpass.sdk.utils.isNetworkError
import de.rki.covpass.sdk.utils.parallelMap
import de.rki.covpass.sdk.utils.toHex
import de.rki.covpass.sdk.utils.toRFC1123OrEmpty
import io.ktor.client.HttpClient
import io.ktor.client.call.receive
import io.ktor.client.features.defaultRequest
import io.ktor.client.features.json.JsonFeature
import io.ktor.client.features.json.serializer.KotlinxSerializer
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.host
import io.ktor.client.statement.HttpResponse
import io.ktor.http.HttpStatusCode
import java.security.PublicKey
import java.time.Instant
import java.time.temporal.ChronoUnit
public class RevocationLocalListRepository(
httpClient: HttpClient,
host: String,
store: CborSharedPrefsStore,
private val database: RevocationDatabase,
private val revocationListPublicKey: PublicKey,
) {
private val client = httpClient.config {
defaultRequest {
this.host = host
}
install(JsonFeature) {
serializer = KotlinxSerializer(defaultJson)
}
}
public val revocationListUpdateIsOn: SuspendMutableValueFlow<Boolean> =
store.getData("revocation_list_update_is_on", false)
public val lastRevocationUpdateFinish: SuspendMutableValueFlow<Instant> =
store.getData("last_revocation_update", NO_UPDATE_YET)
private val lastRevocationUpdateStart: SuspendMutableValueFlow<Instant> =
store.getData("last_revocation_update_start", NO_UPDATE_YET)
private val lastRevocationUpdatedTable: SuspendMutableValueFlow<RevocationListUpdateTable> =
store.getData("last_revocation_update_TABLE", RevocationListUpdateTable.COMPLETED)
public val revocationListUpdateCanceled: MutableValueFlow<Boolean> =
MutableValueFlow(false)
public suspend fun getSavedKidList(): List<RevocationKidLocal> =
database.revocationKidDao().getAll()
private suspend fun getSavedIndexList(): List<RevocationIndexLocal> =
database.revocationIndexDao().getAll()
public suspend fun getSavedIndex(
kid: ByteArray,
hashType: Byte,
): Map<Byte, RevocationIndexEntry> =
database.revocationIndexDao().getIndex(kid, hashType).index
private suspend fun getSavedByteOneList(): List<RevocationByteOneLocal> =
database.revocationByteOneDao().getAll()
public suspend fun getSavedByteOneChunk(
kid: ByteArray,
hashType: Byte,
byte1: Byte,
): List<ByteArray> =
database.revocationByteOneDao().getByteOneChunks(kid, hashType, byte1)?.chunks
?: emptyList()
private suspend fun getSavedByteTwoList(): List<RevocationByteTwoLocal> =
database.revocationByteTwoDao().getAll()
public suspend fun getSavedByteTwoChunk(
kid: ByteArray,
hashType: Byte,
byte1: Byte,
byte2: Byte,
): List<ByteArray> =
database.revocationByteTwoDao().getByteTwoChunks(kid, hashType, byte1, byte2)?.chunks
?: emptyList()
public suspend fun update() {
if (!revocationListUpdateIsOn.value) return
if (lastRevocationUpdateFinish.value.isBeforeUpdateInterval()) {
updateRevocationList()
}
}
public suspend fun deleteAll() {
database.revocationKidDao().deleteAll()
database.revocationIndexDao().deleteAll()
database.revocationByteOneDao().deleteAll()
database.revocationByteTwoDao().deleteAll()
resetUpdateFinish()
}
private suspend fun resetUpdateFinish() {
lastRevocationUpdateFinish.set(NO_UPDATE_YET)
}
private suspend fun updateRevocationList() {
if (isUpdateResetNeeded()) {
lastRevocationUpdatedTable.set(RevocationListUpdateTable.COMPLETED)
}
updateLastStartRevocationValidation(Instant.now())
do {
if (revocationListUpdateCanceled.value) {
break
}
when (lastRevocationUpdatedTable.value) {
RevocationListUpdateTable.COMPLETED -> {
// Update kidlist
updateKidList()
lastRevocationUpdatedTable.set(
RevocationListUpdateTable.KID_LIST,
)
}
RevocationListUpdateTable.KID_LIST -> {
// update index
updateIndex()
lastRevocationUpdatedTable.set(
RevocationListUpdateTable.INDEX,
)
}
RevocationListUpdateTable.INDEX -> {
// update byte one
updateByteOne()
if (!revocationListUpdateCanceled.value) {
lastRevocationUpdatedTable.set(
RevocationListUpdateTable.BYTE_ONE,
)
}
}
RevocationListUpdateTable.BYTE_ONE -> {
// update byte two
updateByteTwo()
if (!revocationListUpdateCanceled.value) {
lastRevocationUpdatedTable.set(
RevocationListUpdateTable.BYTE_TWO,
)
}
}
RevocationListUpdateTable.BYTE_TWO -> {
updateLastRevocationValidation(
lastRevocationUpdateStart.value,
)
lastRevocationUpdatedTable.set(
RevocationListUpdateTable.COMPLETED,
)
}
}
} while (lastRevocationUpdatedTable.value != RevocationListUpdateTable.COMPLETED)
}
private fun isUpdateResetNeeded(): Boolean =
lastRevocationUpdateStart.value.isAfter(
lastRevocationUpdateFinish.value,
) && lastRevocationUpdateStart.value.isBeforeUpdateInterval()
private suspend fun updateByteOne() {
val oldByteOneList = getSavedByteOneList()
val indexList = getSavedIndexList()
indexList.forEach {
val filteredOldByteOneList = oldByteOneList.filter { byteOneLocal ->
byteOneLocal.kid.contentEquals(it.kid) && byteOneLocal.hashVariant == it.hashVariant
}
deleteOldByteOneList(filteredOldByteOneList, it)
it.index.toList().parallelMap { (byteOne, revocationIndexEntry) ->
updateByteOne(revocationIndexEntry, it, byteOne)
}
if (revocationListUpdateCanceled.value) {
return
}
}
}
private suspend fun updateByteTwo() {
val oldByteTwoList = getSavedByteTwoList()
val indexList = getSavedIndexList()
indexList.forEach {
val filteredOldByteTwoList = oldByteTwoList.filter { byteTwoLocal ->
byteTwoLocal.kid.contentEquals(it.kid) && byteTwoLocal.hashVariant == it.hashVariant
}
deleteOldByteTwoList(filteredOldByteTwoList, it)
it.index.toList().parallelMap { (byteOne, revocationIndexEntry) ->
revocationIndexEntry.byte2?.forEach { byte2Entry ->
updateByteTwoLogic(
byte2Entry,
it,
byteOne,
)
}
}
if (revocationListUpdateCanceled.value) {
return
}
}
}
/**
* Update the [lastRevocationUpdateFinish].
*/
private suspend fun updateLastRevocationValidation(instant: Instant) {
lastRevocationUpdateFinish.set(instant)
}
/**
* Update the [lastRevocationUpdateStart].
*/
private suspend fun updateLastStartRevocationValidation(instant: Instant) {
lastRevocationUpdateStart.set(instant)
}
private suspend fun updateKidList() {
val newKidListObject = getKidList(
lastRevocationUpdateFinish.value,
)
if (newKidListObject.wasModifiedSince) {
val oldKidListObject = database.revocationKidDao().getAll()
val removedKidList = oldKidListObject.filter { oldElement ->
!newKidListObject.kidList.map { it.kid }.contains(oldElement.kid)
}
database.revocationKidDao().replaceAll(
newKidListObject.kidList.map {
RevocationKidLocal(
it.kid,
it.hashVariants,
)
},
)
// remove deleted kid from other tables
removedKidList.forEach {
database.revocationIndexDao().deleteAllFromKid(it.kid)
database.revocationByteOneDao().deleteAllFromKid(it.kid)
database.revocationByteTwoDao().deleteAllFromKid(it.kid)
}
}
}
private suspend fun updateIndex() {
val oldIndexList = database.revocationIndexDao().getAll()
val kidList = database.revocationKidDao().getAll()
kidList.forEach { revocationKidLocal ->
val filteredOldIndexList =
oldIndexList.filter { it.kid.contentEquals(revocationKidLocal.kid) }
filteredOldIndexList.forEach {
if (revocationKidLocal.hashVariants[it.hashVariant] == null) {
database.revocationIndexDao().deleteElement(it.kid, it.hashVariant)
database.revocationByteOneDao()
.deleteAllFromKidAndHashVariant(it.kid, it.hashVariant)
database.revocationByteTwoDao()
.deleteAllFromKidAndHashVariant(it.kid, it.hashVariant)
}
}
revocationKidLocal.hashVariants.forEach { (hashType, _) ->
val index =
getIndex(revocationKidLocal.kid, hashType, lastRevocationUpdateFinish.value)
if (index.wasModifiedSince) {
database.revocationIndexDao().insertIndex(
RevocationIndexLocal(
revocationKidLocal.kid,
hashType,
index.indexList,
),
)
}
}
}
}
private suspend fun updateByteOne(
revocationIndexEntry: RevocationIndexEntry,
revocationIndexLocal: RevocationIndexLocal,
byteOne: Byte,
) {
if (
Instant.ofEpochSecond(revocationIndexEntry.timestamp ?: 0)
.isAfter(lastRevocationUpdateFinish.value) &&
lastRevocationUpdateFinish.value.epochSecond >=
(
database.revocationByteOneDao().getByteOneChunks(
revocationIndexLocal.kid,
revocationIndexLocal.hashVariant,
byteOne,
)?.timestamp ?: 0
)
) {
val byte1ChunkList = getByteOneChunk(
revocationIndexLocal.kid,
revocationIndexLocal.hashVariant,
byteOne,
lastRevocationUpdateFinish.value,
)
database.revocationByteOneDao().insertByteOne(
RevocationByteOneLocal(
revocationIndexLocal.kid,
revocationIndexLocal.hashVariant,
byteOne,
byte1ChunkList.chunkList,
lastRevocationUpdateStart.value.epochSecond,
),
)
}
}
private suspend fun updateByteTwoLogic(
byte2Entry: Map.Entry<Byte, RevocationIndexByte2Entry>,
indexEntry: RevocationIndexLocal,
byteOne: Byte,
) {
if (
Instant.ofEpochSecond(byte2Entry.value.timestamp ?: 0)
.isAfter(lastRevocationUpdateFinish.value) &&
lastRevocationUpdateFinish.value.epochSecond >=
(
database.revocationByteTwoDao().getByteTwoChunks(
indexEntry.kid,
indexEntry.hashVariant,
byteOne,
byte2Entry.key,
)?.timestamp ?: 0
)
) {
val byte2ChunkList = getByteTwoChunk(
indexEntry.kid,
indexEntry.hashVariant,
byteOne,
byte2Entry.key,
lastRevocationUpdateFinish.value,
)
database.revocationByteTwoDao().insertByteTwo(
RevocationByteTwoLocal(
indexEntry.kid,
indexEntry.hashVariant,
byteOne,
byte2Entry.key,
byte2ChunkList.chunkList,
lastRevocationUpdateStart.value.epochSecond,
),
)
}
}
private suspend fun deleteOldByteOneList(
filteredOldByteOneList: List<RevocationByteOneLocal>,
revocationIndexLocal: RevocationIndexLocal,
) {
filteredOldByteOneList.forEach { byteOneLocal ->
if (revocationIndexLocal.index[byteOneLocal.byteOne] == null) {
database.revocationByteOneDao().deleteElement(
revocationIndexLocal.kid,
revocationIndexLocal.hashVariant,
byteOneLocal.byteOne,
)
database.revocationByteTwoDao().deleteAllFromKidAndHashVariantAndByteOne(
revocationIndexLocal.kid,
revocationIndexLocal.hashVariant,
byteOneLocal.byteOne,
)
}
}
}
private suspend fun deleteOldByteTwoList(
filteredOldByteTwoList: List<RevocationByteTwoLocal>,
revocationIndexLocal: RevocationIndexLocal,
) {
filteredOldByteTwoList.forEach { byteTwoLocal ->
if (revocationIndexLocal.index[byteTwoLocal.byteOne]?.byte2?.get(byteTwoLocal.byteTwo) == null) {
database.revocationByteTwoDao().deleteAllFromKidAndHashVariantAndByteOneAndByteTwo(
revocationIndexLocal.kid,
revocationIndexLocal.hashVariant,
byteTwoLocal.byteOne,
byteTwoLocal.byteTwo,
)
}
}
}
private suspend fun getKidList(lastUpdate: Instant): KidListObject {
val signedObject = getSigned("kid.lst", lastUpdate)
return KidListObject(
signedObject?.wasModifiedSince ?: false,
signedObject?.cborObject?.toKidList() ?: emptyList(),
)
}
private suspend fun getIndex(
kid: ByteArray,
hashType: Byte,
lastUpdate: Instant,
): IndexListObject {
val signedObject = getSigned("${kid.toHex()}${hashType.toHex()}/index.lst", lastUpdate)
return IndexListObject(
signedObject?.wasModifiedSince ?: false,
signedObject?.cborObject?.toIndexResponse() ?: emptyMap(),
)
}
private suspend fun getByteOneChunk(
kid: ByteArray,
hashType: Byte,
byte1: Byte,
lastUpdate: Instant,
): ChunkListObject {
val signedObject =
getSigned("${kid.toHex()}${hashType.toHex()}/${byte1.toHex()}/chunk.lst", lastUpdate)
return ChunkListObject(
wasModifiedSince = signedObject?.wasModifiedSince ?: false,
chunkList = signedObject?.cborObject?.toListOfByteArrays() ?: emptyList(),
)
}
private suspend fun getByteTwoChunk(
kid: ByteArray,
hashType: Byte,
byte1: Byte,
byte2: Byte,
lastUpdate: Instant,
): ChunkListObject {
val signedObject =
getSigned(
"${kid.toHex()}${hashType.toHex()}/${byte1.toHex()}/${byte2.toHex()}/chunk.lst",
lastUpdate,
)
return ChunkListObject(
wasModifiedSince = signedObject?.wasModifiedSince ?: false,
chunkList = signedObject?.cborObject?.toListOfByteArrays() ?: emptyList(),
)
}
private suspend fun getSigned(url: String, lastUpdate: Instant): SignedObject? {
return try {
val httpResponse: HttpResponse = client.get(url) {
header("If-Modified-Since", lastUpdate.toRFC1123OrEmpty())
}
val list: ByteArray = httpResponse.receive()
val sign1Message = Sign1Message.DecodeFromBytes(list) as Sign1Message
validateRevocationSignature(sign1Message)
SignedObject(
wasModifiedSince = httpResponse.status == HttpStatusCode.OK,
cborObject = CBORObject.DecodeFromBytes(sign1Message.GetContent()),
)
} catch (e: RevocationRemoteListRepository.RevocationListSignatureValidationFailedException) {
null
} catch (e: Throwable) {
if (isNetworkError(e)) {
null
} else {
throw e
}
}
}
private fun validateRevocationSignature(sign1Message: Sign1Message) {
if (!sign1Message.validate(OneKey(revocationListPublicKey, null))) {
throw RevocationRemoteListRepository.RevocationListSignatureValidationFailedException()
}
}
private data class SignedObject(
val wasModifiedSince: Boolean = false,
val cborObject: CBORObject?,
)
private data class ChunkListObject(
val wasModifiedSince: Boolean = false,
val chunkList: List<ByteArray>,
)
private data class IndexListObject(
val wasModifiedSince: Boolean = false,
val indexList: Map<Byte, RevocationIndexEntry>,
)
private data class KidListObject(
val wasModifiedSince: Boolean = false,
val kidList: List<RevocationKidEntry>,
)
public companion object {
public const val UPDATE_INTERVAL_HOURS: Long = 24
}
}
public fun Instant.isBeforeUpdateInterval(): Boolean {
return isBefore(
Instant.now().minus(UPDATE_INTERVAL_HOURS, ChronoUnit.HOURS),
)
}
public enum class RevocationListUpdateTable {
COMPLETED,
KID_LIST,
INDEX,
BYTE_ONE,
BYTE_TWO,
}
| 33 | null | 60 | 185 | 7301f1500dab4a686aa40341500667cf4cc54d1e | 19,347 | covpass-android | Apache License 2.0 |
shared/src/iosMain/kotlin/com/vasylt/composekmm/core/presentation/ContactsTheme.kt | VasylT | 734,461,368 | false | {"Kotlin": 59960, "Swift": 650} | package com.vasylt.composekmm.core.presentation
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import com.vasylt.composekmm.ui.theme.DarkColorScheme
import com.vasylt.composekmm.ui.theme.LightColorScheme
import com.vasylt.composekmm.ui.theme.Typography
@Composable
actual fun ContactsTheme(
darkTheme: Boolean,
dynamicColor: Boolean,
content: @Composable () -> Unit
) {
MaterialTheme(
colorScheme = if(darkTheme) DarkColorScheme else LightColorScheme,
typography = Typography,
content = content
)
} | 0 | Kotlin | 0 | 0 | b1313d5ed529aedf9819c45c316d118bf313c680 | 588 | KMMContacts | Apache License 2.0 |
src/commonMain/kotlin/com.github.ikovalyov.model/security/User.kt | ikovalyov | 355,338,939 | false | null | @file:UseSerializers(UuidSerializer::class)
package com.github.ikovalyov.model.security
import com.benasher44.uuid.Uuid
import com.benasher44.uuid.uuidFrom
import com.github.ikovalyov.model.markers.IEditable
import com.github.ikovalyov.model.serializer.UuidSerializer
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@ExperimentalSerializationApi
@Serializable
data class User(
override val id: Uuid,
val email: Email,
val loggedIn: Boolean,
val nickname: String,
val roles: List<Uuid>,
val password: Password
) : IEditable<User> {
override fun getMetadata(): List<IEditable.EditableMetadata<*, User>> {
return listOf(
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.Id,
readOnly = true,
serialize = { id.toString() },
deserialize = { uuidFrom(it) },
get = { id },
update = { copy(id = it) }
),
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.Email,
readOnly = false,
serialize = { it.value.value },
deserialize = { Email(ShortString(it)) },
get = { email },
update = { copy(email = it) }
),
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.Nickname,
readOnly = false,
serialize = { it },
deserialize = { it },
get = { nickname },
update = { copy(nickname = it) }
),
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.UserRoles,
readOnly = false,
serialize = { Json.encodeToString(ListSerializer(UuidSerializer), it) },
deserialize = { Json.decodeFromString(ListSerializer(UuidSerializer), it) },
get = { roles },
update = { copy(roles = it) }
),
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.Password,
readOnly = false,
serialize = { it.value.value },
deserialize = { Password(ShortString(it)) },
get = { password },
update = { copy(password = it) }
),
)
}
override fun serialize(): String {
return Json.encodeToString(this)
}
}
| 25 | null | 0 | 2 | 81830ed91f528043da381233bae4d31eaffdaccc | 2,687 | kotlin-blogpost-engine | MIT License |
data/model/src/main/java/com/ds/ciceksepeti/model/product/DynamicFilter.kt | developersancho | 371,180,136 | false | null | package com.ds.ciceksepeti.model.product
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class DynamicFilter(
@Json(name = "clearLink")
var clearLink: Any?,
@Json(name = "detailId")
var detailId: Int?,
@Json(name = "dropdownInfo")
var dropdownInfo: Any?,
@Json(name = "dropdownTitle")
var dropdownTitle: Any?,
@Json(name = "filterBehaviour")
var filterBehaviour: Int?,
@Json(name = "filterType")
var filterType: Int?,
@Json(name = "id")
var id: Int?,
@Json(name = "isMainCategory")
var isMainCategory: Boolean?,
@Json(name = "isReload")
var isReload: Boolean?,
@Json(name = "isRemovableDetail")
var isRemovableDetail: Boolean?,
@Json(name = "name")
var name: String?,
@Json(name = "sequence")
var sequence: Int?,
@Json(name = "urlTag")
var urlTag: Any?,
@Json(name = "values")
var values: List<Value> = emptyList()
) | 0 | Kotlin | 0 | 0 | 1ad877d404b6c6777db0d23b50d8b832b2a89d52 | 990 | CicekSepeti-Challenge | Apache License 2.0 |
app/src/main/java/kz/sozdik/translation/di/TranslateModule.kt | sozdik-kz | 290,830,901 | false | null | package kz.sozdik.translation.di
import dagger.Binds
import dagger.Module
import dagger.Provides
import kz.sozdik.translation.data.TranslateRestGateway
import kz.sozdik.translation.data.api.TranslationApi
import kz.sozdik.translation.domain.TranslateRemoteGateway
import retrofit2.Retrofit
@Module
abstract class TranslateModule {
@Binds
abstract fun bindTranslateRepository(repository: TranslateRestGateway): TranslateRemoteGateway
@Module
companion object {
@Provides
@JvmStatic
fun provideTranslationApi(retrofit: Retrofit): TranslationApi =
retrofit.create(TranslationApi::class.java)
}
} | 5 | Kotlin | 5 | 43 | cfbdffe47253c14ec75d0fba166d1077e028328c | 652 | sozdik-android | MIT License |
sdk/backend/src/main/kotlin/com/supertokens/sdk/recipes/accountlinking/responses/CheckCanLinkAccountsResponseDTO.kt | Appstractive | 656,572,792 | false | {"Kotlin": 415391, "Ruby": 2302} | package com.supertokens.sdk.recipes.accountlinking.responses
import com.supertokens.sdk.common.responses.BaseResponseDTO
import kotlinx.serialization.Serializable
@Serializable
data class CheckCanLinkAccountsResponseDTO(
override val status: String,
val accountsAlreadyLinked: Boolean,
): BaseResponseDTO
| 5 | Kotlin | 1 | 3 | e4d0ff3664034d1c4981a0a2cdf58c3a053da2a7 | 315 | supertokens-kt | Apache License 2.0 |
app/src/main/java/com/ozantopuz/dicetask/ui/detail/ReleaseAdapter.kt | ozantopuz | 436,359,167 | false | {"Kotlin": 65581} | package com.ozantopuz.dicetask.ui.detail
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.ozantopuz.dicetask.databinding.ItemReleaseBinding
import com.ozantopuz.dicetask.ui.entity.ReleaseViewItem
class ReleaseAdapter(
private var list: ArrayList<ReleaseViewItem> = arrayListOf()
) : RecyclerView.Adapter<ReleaseAdapter.ReleaseViewHolder>() {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ReleaseViewHolder {
val itemBinding =
ItemReleaseBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return ReleaseViewHolder(itemBinding)
}
override fun onBindViewHolder(holder: ReleaseViewHolder, position: Int) {
val item: ReleaseViewItem = list[position]
with(holder.binding) {
textViewTitle.text = item.title
textViewType.text = item.primaryType
textViewDate.text = item.firstReleaseDate
}
}
override fun getItemCount(): Int = list.size
@SuppressLint("NotifyDataSetChanged")
fun setList(list: List<ReleaseViewItem>? = null) {
if (list != null) this.list = ArrayList(list)
notifyDataSetChanged()
}
class ReleaseViewHolder(val binding: ItemReleaseBinding) :
RecyclerView.ViewHolder(binding.root)
} | 0 | Kotlin | 0 | 0 | 956ac995e222c2432416d3acbb9b863ca67261c4 | 1,482 | DiceTask | MIT License |
server/src/main/kotlin/org/javacs/kt/URIContentProvider.kt | fwcd | 135,159,301 | false | null | package org.javacs.kt
import java.net.URI
import java.net.URLDecoder
import java.nio.charset.StandardCharsets
import java.nio.file.Paths
import org.javacs.kt.externalsources.JarClassContentProvider
import org.javacs.kt.externalsources.toKlsURI
import org.javacs.kt.util.KotlinLSException
import org.javacs.kt.util.partitionAroundLast
/**
* Fetches the content of Kotlin files identified by a URI.
*/
class URIContentProvider(
val jarClassContentProvider: JarClassContentProvider
) {
fun contentOf(uri: URI): String = when (uri.scheme) {
"file" -> Paths.get(uri).toFile().readText()
"kls" -> uri.toKlsURI()?.let { jarClassContentProvider.contentOf(it).second }
?: throw KotlinLSException("Could not find ${uri}")
else -> throw KotlinLSException("Unrecognized scheme ${uri.scheme}")
}
}
| 118 | Kotlin | 117 | 874 | cfd1717b0a376e8b0ec42dd9b4d703c02e65578a | 837 | kotlin-language-server | MIT License |
src/commonTest/kotlin/com/soywiz/ktcc/preprocessor/MacroTest.kt | korlibs | 165,555,533 | false | null | package com.soywiz.ktcc.preprocessor
import kotlin.test.*
class MacroTest {
@Test fun test1a() = assertEquals(Macro("HELLO", listOf("WORLD"), null), Macro("HELLO=WORLD"))
@Test fun test1b() = assertEquals(Macro("HELLO", listOf("WORLD"), null), Macro("HELLO", "WORLD"))
@Test fun test2a() = assertEquals(Macro("HELLO", listOf("(", "WORLD", ")"), null), Macro("HELLO= (WORLD)"))
@Test fun test2b() = assertEquals(Macro("HELLO", listOf("(", "WORLD", ")"), null), Macro("HELLO", " (WORLD)"))
@Test fun test3a() = assertEquals(Macro("HELLO", listOf(), listOf("WORLD")), Macro("HELLO=(WORLD)"))
@Test fun test3b() = assertEquals(Macro("HELLO", listOf(), listOf("WORLD")), Macro("HELLO", "(WORLD)"))
@Test fun test4a() = assertEquals(Macro("HELLO", listOf("A", "+", "B"), listOf("A", "B")), Macro("HELLO=(A, B) A+B"))
@Test fun test4b() = assertEquals(Macro("HELLO", listOf("A", "+", "B"), listOf("A", "B")), Macro("HELLO", "(A, B) A+B"))
} | 1 | Kotlin | 5 | 63 | f3d1cace49f6a74e3aad71a2cdcc22b877d3c783 | 970 | ktcc | MIT License |
sphinx/screens/dashboard/dashboard/src/main/java/chat/sphinx/dashboard/ui/feed/play/FeedPlaySideEffect.kt | stakwork | 340,103,148 | false | {"Kotlin": 4008358, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453} | package chat.sphinx.dashboard.ui.feed.play
import android.content.Context
import io.matthewnelson.concept_views.sideeffect.SideEffect
sealed class FeedPlaySideEffect: SideEffect<Context>() {
} | 96 | Kotlin | 11 | 18 | 64eb5948ee1878cea6f375adc94ac173f25919fa | 195 | sphinx-kotlin | MIT License |
app/src/main/java/com/tuk/lightninggathering/HomeFragment.kt | FiveGuys-in-Oido | 644,228,044 | false | null | package com.tuk.lightninggathering
import android.annotation.SuppressLint
import android.content.Intent
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.firebase.FirebaseApp
import com.google.firebase.database.*
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [HomeFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class HomeFragment : Fragment() {
// TODO: Rename and change types of parameters
private lateinit var recyclerView: RecyclerView
private lateinit var postAdapter: PostAdapter
private lateinit var postList: MutableList<Post>
val meetingKeysList = ArrayList<String>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_home, container, false)
// RecyclerView 초기화
recyclerView = view.findViewById(R.id.showRecyclerView)
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = LinearLayoutManager(requireContext())
// 게시물 데이터 생성
postList = ArrayList()
FirebaseApp.initializeApp(requireContext())
val db = FirebaseDatabase.getInstance()
val query = db.getReference("meetings")
query.addListenerForSingleValueEvent(object : ValueEventListener {
@SuppressLint("NotifyDataSetChanged")
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (meetingSnapshot in dataSnapshot.children) {
val title = meetingSnapshot.child("title").getValue(String::class.java)
val date = meetingSnapshot.child("date").getValue(String::class.java)
val location = meetingSnapshot.child("location").getValue(String::class.java)
val curMemberCount = meetingSnapshot.child("memberKeys").getValue(object : GenericTypeIndicator<List<String>>() {})
val maxMemberCount = meetingSnapshot.child("maxMemberCount").getValue(Int::class.java)
val meetingKeys = meetingSnapshot.key
if (meetingKeys != null) {
meetingKeysList.add(meetingKeys)
}
val post = Post(title, date, location, curMemberCount,maxMemberCount)
postList.add(post)
}
postAdapter.notifyDataSetChanged() // 어댑터에 데이터 변경을 알림
}
override fun onCancelled(databaseError: DatabaseError) {
// Handle the error
}
})
// 어댑터 설정
postAdapter = PostAdapter(postList, requireContext(), meetingKeysList)
recyclerView.adapter = postAdapter
postAdapter.setOnItemClickListener { _, meetingKeys ->
val intent = Intent(requireContext(), GatheringDetailActivity::class.java)
intent.putExtra("meetingKeys", meetingKeys)
startActivity(intent)
}
return view
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
HomeFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | 11 | Kotlin | 0 | 0 | f357feaccc0ee53a9ca5f765868dbc5f30a54e5d | 4,173 | LightingGathering | MIT License |
app/src/main/java/com/anggitprayogo/kotlinmultiplatformproject/ui/main/MainActivityAdapter.kt | anggit97 | 245,429,786 | false | {"Objective-C": 92773, "Kotlin": 37267, "Swift": 6776} | package com.anggitprayogo.kotlinmultiplatformproject.ui.main
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import coil.api.load
import com.anggitprayogo.kotlinmultiplatformproject.R
import domain.model.Article
import kotlinx.android.synthetic.main.row_item_news.view.*
class MainActivityAdapter : RecyclerView.Adapter<MainActivityAdapter.ViewHolder>() {
private var newsList: MutableList<Article> = mutableListOf()
fun setItems(newsList: MutableList<Article>) {
this.newsList = newsList
notifyDataSetChanged()
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindView(article: Article) {
with(itemView) {
ivNews.load(article.urlToImage)
tvTitleNews.text = article.title
tvAuthorNews.text = article.author
}
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.row_item_news,
parent,
false
)
)
}
override fun getItemCount(): Int = newsList.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindView(newsList[position])
}
} | 0 | Objective-C | 1 | 0 | 7436e3e01fcd7a5a64f8536a785a40b151be94ea | 1,437 | Kotlin-Multi-Platform-News-App | MIT License |
app/src/main/java/com/ogamoga/developerslive/domain/model/Item.kt | ogamoga | 403,120,927 | false | {"Kotlin": 31703} | package com.ogamoga.developerslive.domain.model
data class Item(
val id: Int,
val url: String,
val description: String,
var hasPrevious: Boolean
)
| 0 | Kotlin | 0 | 0 | cfc73aa6fdcbc0009bcf6605ab964b316237a176 | 164 | DevelopersLife | MIT License |
ktor/src/jvmTest/kotlin/multiplatform/ktor/ServerTest.kt | juggernaut0 | 201,797,664 | false | {"Kotlin": 38536} | package multiplatform.ktor
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.serializer
import multiplatform.api.ApiRoute
import multiplatform.api.Method
import multiplatform.api.pathOf
import kotlin.test.Test
import kotlin.test.assertEquals
class ServerTest {
@Test
fun testServerExts() {
@Serializable
data class Req(val x: String)
val route = ApiRoute(Method.POST, pathOf(Unit.serializer(), "/test"), String.serializer(), Req.serializer())
testApplication {
install(StatusPages) {
installWebApplicationExceptionHandler()
}
routing {
handleApi(route) {
it.x.uppercase()
}
}
with(client.post {
url("/test")
//language=JSON
setBody("""{"x": "test"}""")
}) {
assertEquals(HttpStatusCode.OK, status)
assertEquals("\"TEST\"", bodyAsText())
}
with(client.post {
url("/test")
//language=JSON
setBody("""{"y": "test"}""")
}) {
assertEquals(HttpStatusCode.BadRequest, status)
}
}
}
@Test
fun params() {
@Serializable
data class Params(val path: String, val query: String)
val route = ApiRoute(Method.GET, pathOf(Params.serializer(), "/{path}?q={query}"), String.serializer())
testApplication {
install(StatusPages) {
installWebApplicationExceptionHandler()
}
routing {
handleApi(route) {
params.path + params.query
}
}
with(client.get {
method = HttpMethod.Get
url("/test?q=foo")
}) {
assertEquals(HttpStatusCode.OK, status)
assertEquals("\"testfoo\"", bodyAsText())
}
with(client.get {
method = HttpMethod.Get
url("/test")
}) {
assertEquals(HttpStatusCode.BadRequest, status)
}
}
}
} | 0 | Kotlin | 0 | 0 | f72cd96b34f4867869492795bc2b67c0071a1649 | 2,487 | multiplatform-utils | MIT License |
src/main/kotlin/it/heptartle/kbgg/api/bgg/HotApi.kt | serafo27 | 186,999,437 | false | null | package it.heptartle.kbgg.api.bgg
import it.heptartle.kbgg.domain.bgg.Items
import it.heptartle.kbgg.domain.bgg.Type
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface HotApi {
@GET("hot")
fun hot(@Query("type") type: Type? = null): Call<Items>
}
| 1 | Kotlin | 1 | 1 | 42f9b9301eb68ac6818a1655b68f1b5190d2d271 | 293 | kbgg | MIT License |
src/main/kotlin/com/github/l1an/yuillustration/core/illustration/Entry.kt | L1-An | 729,406,949 | false | {"Kotlin": 53248} | package com.github.l1an.yuillustration.core.illustration
import taboolib.library.configuration.ConfigurationSection
import taboolib.library.xseries.getItemStack
class Entry(val config: ConfigurationSection) {
val key = config.name
val category = config.getString("category", "default") ?: "default"
val show = config.getBoolean("show", true)
// 图标
val icon = config.getItemStack("icon") ?: error("Icon not found in $key")
val shiny = config.getBoolean("icon.shiny", false)
val customModelData = config.getInt("icon.custom-model-data", -1)
// 解锁条件,若不存在则自动解锁
val unlock = config.getConfigurationSection("unlock")
// 解锁奖励,若不存在则默认无奖励
val reward = config.getConfigurationSection("reward")
} | 0 | Kotlin | 0 | 1 | 1d8fbc493da7e2076ee3f264c35dc71baa80d13a | 736 | YuIllustration | Creative Commons Zero v1.0 Universal |
domain/src/test/java/app/sedici/tasks/domain/SetTaskIsCheckedByIdTest.kt | razvanred | 387,555,253 | false | {"Kotlin": 227488, "Shell": 379} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.sedici.tasks.domain
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import app.cash.turbine.test
import app.sedici.tasks.base.common.AppCoroutineDispatchers
import app.sedici.tasks.base.common.InvokeError
import app.sedici.tasks.base.common.InvokeStarted
import app.sedici.tasks.base.common.InvokeSuccess
import app.sedici.tasks.data.repository.TaskRepository
import app.sedici.tasks.model.NewTask
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import dagger.hilt.android.testing.HiltTestApplication
import io.mockk.coEvery
import io.mockk.spyk
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.runBlockingTest
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.ParameterizedRobolectricTestRunner
import org.robolectric.annotation.Config
import javax.inject.Inject
import kotlin.time.ExperimentalTime
@RunWith(ParameterizedRobolectricTestRunner::class)
@HiltAndroidTest
@Config(application = HiltTestApplication::class)
@OptIn(ExperimentalTime::class)
class SetTaskIsCheckedByIdTest(private val isChecked: Boolean) {
private val appDispatchers = AppCoroutineDispatchers(
main = TestCoroutineDispatcher(),
io = TestCoroutineDispatcher(),
computation = Dispatchers.Default
)
@get:Rule
val hiltRule by lazy { HiltAndroidRule(this) }
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()
private val testScope = TestCoroutineScope(context = appDispatchers.main)
@Inject
lateinit var taskRepository: TaskRepository
@Before
fun setup() {
hiltRule.inject()
}
@Test
fun invoke_checkSuccess() = testScope.runBlockingTest {
val id = taskRepository.saveNewTask(
newTask = NewTask(
title = "Get vaccinated",
description = "2nd dose",
expiresOn = null
)
)
val setTaskIsCheckedById = SetTaskIsCheckedById(
appDispatchers = appDispatchers,
taskRepository = taskRepository
)
setTaskIsCheckedById(id = id, isChecked = isChecked).test {
assertThat(awaitItem()).isEqualTo(InvokeStarted)
assertThat(awaitItem()).isEqualTo(InvokeSuccess)
awaitComplete()
}
assertThat(taskRepository.getByIdOrNull(id = id)?.isChecked).isEqualTo(isChecked)
}
@Test
fun invoke_withFailingRepository_checkReturnsInvokeError() = testScope.runBlockingTest {
val taskRepository: TaskRepository = spyk(taskRepository)
val taskId = taskRepository.saveNewTask(
newTask = NewTask(
title = "Go to the beach",
description = "Don't forget the sunscreen",
expiresOn = null
)
)
coEvery { taskRepository.setTaskIsCheckedById(isChecked = isChecked, id = taskId) }
.throws(RuntimeException("Stub!"))
val setTaskIsCheckedById = SetTaskIsCheckedById(
taskRepository = taskRepository,
appDispatchers = appDispatchers
)
setTaskIsCheckedById(id = taskId, isChecked = isChecked).test {
assertThat(awaitItem()).isEqualTo(InvokeStarted)
val result = awaitItem()
assertThat(result).isInstanceOf(InvokeError::class.java)
assertThat((result as InvokeError).throwable.message).isEqualTo("Stub!")
awaitComplete()
}
}
@After
fun cleanup() {
testScope.cleanupTestCoroutines()
}
companion object {
@JvmStatic
@ParameterizedRobolectricTestRunner.Parameters(name = "is_checked")
fun params() = listOf(true, false)
}
}
| 10 | Kotlin | 0 | 1 | 870a7ee1a36c19acec7401c0a6d011d368aa677d | 4,589 | tasks-android | Apache License 2.0 |
src/main/kotlin/com/learning/controllers/AbstractFactoryPatternController.kt | netodeolino | 187,368,096 | false | null | package com.learning.controllers
import com.learning.patterns.abstractfactory.CarroPopular
import com.learning.patterns.abstractfactory.CarroSedan
import com.learning.patterns.abstractfactory.FabricaFord
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/abstract-factory")
class AbstractFactoryPatternController {
@GetMapping
fun abstractFactory(): String {
var fabricaFord: FabricaFord = FabricaFord()
var carroPopular: CarroPopular = fabricaFord.criarCarroPopular()
carroPopular.info()
var carroSedan: CarroSedan = fabricaFord.criarCarroSedan()
carroSedan.info()
return "abstract factory"
}
} | 0 | Kotlin | 0 | 0 | 4050cfcaee6e2d966e5b8ae7a28b9e006af32ee6 | 826 | learn | MIT License |
sqllin-driver/src/jvmMain/kotlin/com/ctrip/sqllin/driver/AbstractJdbcDatabaseConnection.kt | ctripcorp | 570,015,389 | false | null | /*
* Copyright (C) 2023 Ctrip.com.
*
* 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.ctrip.sqllin.driver
import java.math.BigDecimal
import java.sql.PreparedStatement
import java.sql.Types
/**
* The super class for DatabaseConnection on JVM
* @author yaqiao
*/
internal abstract class AbstractJdbcDatabaseConnection : DatabaseConnection {
abstract fun createStatement(sql: String): PreparedStatement
protected fun bindParamsToSQL(sql: String, bindParams: Array<Any?>?): PreparedStatement = createStatement(sql).apply {
bindParams?.run {
require(isNotEmpty()) { "Empty bindArgs" }
forEachIndexed { index, any ->
val realIndex = index + 1
when (any) {
is String -> setString(realIndex, any)
is Long -> setLong(realIndex, any)
is Double -> setDouble(realIndex, any)
is ByteArray -> setBytes(realIndex, any)
null -> setNull(realIndex, Types.NULL)
is Int -> setInt(realIndex, any)
is Float -> setFloat(realIndex, any)
is Boolean -> setBoolean(realIndex, any)
is Char -> setString(realIndex, any.toString())
is Short -> setShort(realIndex, any)
is Byte -> setByte(realIndex, any)
is ULong -> setLong(realIndex, any.toLong())
is UInt -> setInt(realIndex, any.toInt())
is UShort -> setShort(realIndex, any.toShort())
is UByte -> setByte(realIndex, any.toByte())
is BigDecimal -> setBigDecimal(realIndex, any)
else -> throw IllegalArgumentException("No supported element type.")
}
}
}
}
} | 3 | null | 11 | 217 | 4872fddad7ad72f5f95e14ad831b3ebb7fc87d47 | 2,370 | SQLlin | Apache License 2.0 |
petsearch-shared/data/source/src/commonMain/kotlin/com/msa/petsearch/shared/data/source/animal/model/network/petinfo/PetContactAddressDTO.kt | msa1422 | 534,594,528 | false | {"Kotlin": 219948, "Swift": 46109, "Ruby": 2530} | package com.msa.petsearch.shared.data.source.animal.model.network.petinfo
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
internal data class PetContactAddressDTO(
@SerialName("address1") val address1: String?,
@SerialName("address2") val address2: String?,
@SerialName("city") val city: String?,
@SerialName("state") val state: String?,
@SerialName("postcode") val postcode: String?,
@SerialName("country") val country: String?
)
| 0 | Kotlin | 0 | 19 | 55519d0c845eedeaefdea5638c9db8f9f753d678 | 505 | KMM-Arch-PetSearch | MIT License |
src/commonMain/kotlin/uk/org/jurg/yakl/engine/utils/StringReader.kt | jurgc11 | 250,645,845 | false | null | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.org.jurg.yakl.engine.utils
import kotlin.math.min
class StringReader(private val str: String) : Reader {
private val length = str.length
private var next = 0
private val mark = 0
override fun read(buffer: CharArray, offset: Int, length: Int): Int {
if (offset < 0 || offset > buffer.size || length < 0 ||
offset + length > buffer.size || offset + length < 0
) {
throw IndexOutOfBoundsException()
} else if (length == 0) {
return 0
}
if (next >= this.length) return -1
val n = min(this.length - next, length)
copySubstring(str,next, next + n, buffer, offset)
next += n
return n
}
private fun copySubstring(src: String, srcBegin: Int, srcEnd: Int, buffer: CharArray, offset: Int) {
for (i in 0 until srcEnd-srcBegin) {
buffer[i+offset] = src[i+srcBegin]
}
}
override fun close() {
// No-op
}
}
| 2 | Kotlin | 0 | 3 | 5677967ab51f4bc6096bd6b953248f389898aa9d | 1,580 | yakl | Apache License 2.0 |
app/src/main/java/dev/esnault/bunpyro/data/service/sync/SyncService.kt | esnaultdev | 242,479,002 | false | null | package dev.esnault.bunpyro.data.service.sync
import android.database.SQLException
import dev.esnault.bunpyro.data.db.examplesentence.ExampleSentenceDao
import dev.esnault.bunpyro.data.db.examplesentence.ExampleSentenceDb
import dev.esnault.bunpyro.data.db.grammarpoint.GrammarPointDao
import dev.esnault.bunpyro.data.db.grammarpoint.GrammarPointDb
import dev.esnault.bunpyro.data.db.review.ReviewDao
import dev.esnault.bunpyro.data.db.review.ReviewDb
import dev.esnault.bunpyro.data.db.reviewhistory.ReviewHistoryDao
import dev.esnault.bunpyro.data.db.reviewhistory.ReviewHistoryDb
import dev.esnault.bunpyro.data.db.supplementallink.SupplementalLinkDao
import dev.esnault.bunpyro.data.db.supplementallink.SupplementalLinkDb
import dev.esnault.bunpyro.data.mapper.apitodb.ExampleSentenceMapper
import dev.esnault.bunpyro.data.mapper.apitodb.GrammarPointMapper
import dev.esnault.bunpyro.data.mapper.apitodb.SupplementalLinkMapper
import dev.esnault.bunpyro.data.mapper.apitodb.review.GhostReviewMapper
import dev.esnault.bunpyro.data.mapper.apitodb.review.NormalReviewMapper
import dev.esnault.bunpyro.data.mapper.apitodb.review.ReviewHistoryMapper
import dev.esnault.bunpyro.data.network.BunproVersionedApi
import dev.esnault.bunpyro.data.network.entities.ExampleSentence
import dev.esnault.bunpyro.data.network.entities.GrammarPoint
import dev.esnault.bunpyro.data.network.entities.review.ReviewsData
import dev.esnault.bunpyro.data.network.entities.SupplementalLink
import dev.esnault.bunpyro.data.network.responseRequest
import dev.esnault.bunpyro.data.repository.sync.ISyncRepository
import dev.esnault.bunpyro.data.utils.DataUpdate
import dev.esnault.bunpyro.data.utils.crashreport.ICrashReporter
import dev.esnault.bunpyro.data.utils.fromLocalIds
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import retrofit2.Response
class SyncService(
private val syncRepo: ISyncRepository,
private val versionedApi: BunproVersionedApi,
private val grammarPointDao: GrammarPointDao,
private val exampleSentenceDao: ExampleSentenceDao,
private val supplementalLinkDao: SupplementalLinkDao,
private val reviewDao: ReviewDao,
private val reviewHistoryDao: ReviewHistoryDao,
private val crashReporter: ICrashReporter
) : ISyncService {
private val syncEventChannel = ConflatedBroadcastChannel<SyncEvent>()
// region Global sync
override suspend fun getSyncEvent(): Flow<SyncEvent> {
return syncEventChannel.asFlow()
}
override suspend fun firstSync(): SyncResult {
if (syncRepo.getFirstSyncCompleted()) {
// The first sync has already been completed, nothing to do
return SyncResult.Success
}
return nextSync(SyncType.ALL)
}
override suspend fun nextSync(type: SyncType): SyncResult {
syncEventChannel.send(SyncEvent.IN_PROGRESS)
val result = performNextSync(type)
val resultEvent = when (result) {
is SyncResult.Success -> SyncEvent.SUCCESS
is SyncResult.Error -> SyncEvent.ERROR
}
syncEventChannel.send(resultEvent)
return result
}
private suspend fun performNextSync(type: SyncType): SyncResult {
if (type == SyncType.ALL) {
val grammarSyncResult = syncGrammarPoints()
if (grammarSyncResult !is SyncResult.Success) {
return grammarSyncResult
}
val examplesSyncResult = syncExampleSentences()
if (examplesSyncResult !is SyncResult.Success) {
return examplesSyncResult
}
val supplementalLinksResult = syncSupplementalLinks()
if (supplementalLinksResult !is SyncResult.Success) {
return supplementalLinksResult
}
}
val reviewsResult = syncReviews()
if (reviewsResult is SyncResult.Success) {
syncRepo.saveFirstSyncCompleted()
}
return reviewsResult
}
private suspend fun <T> syncApiEndpoint(
apiRequest: suspend () -> Response<T>,
onSuccess: suspend (T, Response<T>) -> SyncResult
): SyncResult {
return responseRequest(
request = apiRequest,
onSuccess = { body, response -> onSuccess(body!!, response) },
onNotModified = { SyncResult.Success },
onInvalidApiKey = {
// TODO disconnect the user, clear the DB and redirect to the api key screen
SyncResult.Error.Server
},
onServerError = { _, error ->
crashReporter.recordNonFatal(error)
SyncResult.Error.Server
},
onNetworkError = { SyncResult.Error.Network },
onUnknownError = { error ->
crashReporter.recordNonFatal(error)
SyncResult.Error.Unknown(error)
}
)
}
// endregion
// region Grammar points
private suspend fun syncGrammarPoints(): SyncResult {
val eTag = syncRepo.getGrammarPointsETag()
return syncApiEndpoint(
apiRequest = { versionedApi.getGrammarPoints(eTag) },
onSuccess = { data, response ->
val newEtag = response.headers()["etag"]
saveGrammarPoints(data.data, newEtag)
}
)
}
private suspend fun saveGrammarPoints(
grammarPoints: List<GrammarPoint>,
eTag: String?
): SyncResult {
return try {
val mapper = GrammarPointMapper()
val mappedPoints = mapper.mapNotNull(grammarPoints)
grammarPointDao.performDataUpdate { localIds ->
DataUpdate.fromLocalIds(localIds, mappedPoints, GrammarPointDb::id)
}
syncRepo.saveGrammarPointsETag(eTag)
SyncResult.Success
} catch (e: SQLException) {
SyncResult.Error.DB(e)
}
}
// endregion
// region Example sentences
private suspend fun syncExampleSentences(): SyncResult {
val eTag = syncRepo.getExampleSentencesETag()
return syncApiEndpoint(
apiRequest = { versionedApi.getExampleSentences(eTag) },
onSuccess = { data, response ->
val newEtag = response.headers()["etag"]
saveExampleSentences(data.data, newEtag)
}
)
}
private suspend fun saveExampleSentences(
exampleSentences: List<ExampleSentence>,
eTag: String?
): SyncResult {
return try {
val grammarPointIds = grammarPointDao.getAllIds()
val mapper = ExampleSentenceMapper()
val mappedSentences = exampleSentences
.let(mapper::mapNotNull)
// The API returns some example sentence that is not related to any grammar point
// Let's filter them so that we have a sane DB
.filter { grammarPointIds.contains(it.grammarId) }
exampleSentenceDao.performDataUpdate { localIds ->
DataUpdate.fromLocalIds(localIds, mappedSentences, ExampleSentenceDb::id)
}
syncRepo.saveExampleSentencesETag(eTag)
SyncResult.Success
} catch (e: SQLException) {
SyncResult.Error.DB(e)
}
}
// endregion
// region Supplemental links
private suspend fun syncSupplementalLinks(): SyncResult {
val eTag = syncRepo.getSupplementalLinksETag()
return syncApiEndpoint(
apiRequest = { versionedApi.getSupplementalLinks(eTag) },
onSuccess = { data, response ->
val newEtag = response.headers()["etag"]
saveSupplementalLinks(data.data, newEtag)
}
)
}
private suspend fun saveSupplementalLinks(
supplementalLinks: List<SupplementalLink>,
eTag: String?
): SyncResult {
return try {
val grammarPointIds = grammarPointDao.getAllIds()
val mapper = SupplementalLinkMapper()
val mappedLinks = supplementalLinks
.let(mapper::mapNotNull)
// The API returns some example sentence that is not related to any grammar point
// Let's filter them so that we have a sane DB
.filter { grammarPointIds.contains(it.grammarId) }
supplementalLinkDao.performDataUpdate { localIds ->
DataUpdate.fromLocalIds(localIds, mappedLinks, SupplementalLinkDb::id)
}
syncRepo.saveSupplementalLinksETag(eTag)
SyncResult.Success
} catch (e: SQLException) {
SyncResult.Error.DB(e)
}
}
// endregion
// region Reviews
override suspend fun syncReviews(): SyncResult {
val eTag = syncRepo.getReviewsETag()
return syncApiEndpoint(
apiRequest = { versionedApi.getAllReviews(eTag) },
onSuccess = { data, response ->
val newEtag = response.headers()["etag"]
saveReviews(data, newEtag)
}
)
}
private suspend fun saveReviews(
rawReviewsData: ReviewsData,
eTag: String?
): SyncResult {
return try {
val grammarPointIds = grammarPointDao.getAllIds()
val rawNormalReviews = rawReviewsData.reviews.orEmpty()
.filter { grammarPointIds.contains(it.grammarId) }
val rawGhostReviews = rawReviewsData.ghostReviews.orEmpty()
.filter { grammarPointIds.contains(it.grammarId) }
val normalReviewMapper = NormalReviewMapper()
val ghostReviewMapper = GhostReviewMapper()
val reviewHistoryMapper = ReviewHistoryMapper()
val mappedNormalReviews = normalReviewMapper.mapNotNull(rawNormalReviews)
val mappedGhostReviews = ghostReviewMapper.mapNotNull(rawGhostReviews)
val mappedReviews = mappedNormalReviews + mappedGhostReviews
reviewDao.performDataUpdate { localIds ->
DataUpdate.fromLocalIds(localIds, mappedReviews, ReviewDb::id)
}
val mappedNormalReviewsHistory =
reviewHistoryMapper.mapFromNormalReviews(rawNormalReviews)
val mappedGhostReviewsHistory =
reviewHistoryMapper.mapFromGhostReviews(rawGhostReviews)
val mappedReviewsHistory = mappedNormalReviewsHistory + mappedGhostReviewsHistory
reviewHistoryDao.performDataUpdate { localIds ->
DataUpdate.fromLocalIds(localIds, mappedReviewsHistory, ReviewHistoryDb::id)
}
syncRepo.saveReviewsETag(eTag)
SyncResult.Success
} catch (e: SQLException) {
SyncResult.Error.DB(e)
}
}
// endregion
}
| 2 | Kotlin | 1 | 9 | 89b3c7dad2c37c22648c26500016d6503d27019e | 10,930 | BunPyro | Intel Open Source License |
src/main/kotlin/de/jpx3/intavestorage/storage/FileStorage.kt | ventolotl | 474,118,187 | true | {"Kotlin": 16678} | package de.jpx3.intavestorage.storage
import org.bukkit.configuration.ConfigurationSection
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.util.UUID
import java.util.concurrent.TimeUnit
import java.util.function.Consumer
class FileStorage(config: ConfigurationSection) : ExpiringStorageGateway {
override fun requestStorage(id: UUID, consumer: Consumer<ByteBuffer>) {
val file = fileOf(id)
val bytes = FileInputStream(file).use(FileInputStream::readBytes)
consumer.accept(ByteBuffer.wrap(bytes))
}
override fun saveStorage(id: UUID, buffer: ByteBuffer) {
val file = fileOf(id)
FileOutputStream(file).use { it.write(buffer.array()) }
}
private fun fileOf(id: UUID): File {
val prefix = id.toString().substring(0, 2)
val file = File(cacheFile(), "$prefix/$id.storage")
try {
file.parentFile.mkdirs()
if (!file.exists() && !file.createNewFile()) {
error("Failed to create file ${file.absolutePath}")
}
} catch (e: Exception) {
throw IllegalStateException("Failed to create file ${file.absolutePath}", e)
}
return file
}
override fun clearEntriesOlderThan(value: Long, unit: TimeUnit) {
cacheFile()
.walkTopDown()
.filter { file -> file.isFile && file.name.endsWith(".storage") }
.filter { file -> System.currentTimeMillis() - file.lastModified() > unit.toMillis(value) }
.forEach(File::delete)
}
private fun cacheFile(): File {
val operatingSystem = System.getProperty("os.name").lowercase()
val filePath = if (operatingSystem.contains("win")) {
System.getenv("APPDATA") + "/Intave/Storage/"
} else {
System.getProperty("user.home") + "/.intave/storage/"
}
val workDirectory = File(filePath)
if (!workDirectory.exists()) {
workDirectory.mkdir()
}
return workDirectory
}
}
| 0 | null | 0 | 0 | 2d93053de8ba68655cdbd10ec6163339d3f923a8 | 2,099 | storage | Apache License 2.0 |
app-quality-insights/api/src/com/android/tools/idea/insights/IssueStats.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.insights
/**
* Ensures the minimum number of [StatsGroup]s and [DataPoint]s within a group if applicable.
*
* Given a number N, the resulting [IssueStats] will have at least top N values plus the "Other"
* value if applicable.
*/
const val MINIMUM_SUMMARY_GROUP_SIZE_TO_SHOW = 3
/**
* Ensures we show distributions if the given manufacturer/model/OS accounts for more than this
* percentage of the total.
*/
const val MINIMUM_PERCENTAGE_TO_SHOW = 10.0
private const val OTHER_GROUP = "Other"
/** Stats of an [Issue]. */
data class IssueStats<T : Number>(val topValue: String?, val groups: List<StatsGroup<T>>) {
fun isEmpty() = topValue == null && groups.isEmpty()
}
/** A named group of [DataPoint]s. */
data class StatsGroup<T : Number>(
val groupName: String,
val percentage: T,
val breakdown: List<DataPoint<T>>,
)
/** Represents a leaf named data point. */
data class DataPoint<T : Number>(val name: String, val percentage: T)
data class DetailedIssueStats(val deviceStats: IssueStats<Double>, val osStats: IssueStats<Double>)
fun <T : Number> T.percentOf(total: T): Double = ((this.toDouble() / total.toDouble()) * 100)
/**
* Returns the count of elements from [this] whose values are greater than [threshold], meanwhile
* [minElementCount] is ensured if not met.
*/
fun List<Double>.resolveElementCountBy(minElementCount: Int, threshold: Double): Int {
return indexOfFirst { it <= threshold }.coerceAtLeast(minElementCount)
}
/**
* Returns summarized distributions of Oses.
*
* Please ensure the input of the data points are sorted by [WithCount.count] in descending order.
*/
fun List<WithCount<OperatingSystemInfo>>.summarizeOsesFromRawDataPoints(
minGroupSize: Int,
minPercentage: Double,
): IssueStats<Double> {
if (isEmpty()) return IssueStats(null, emptyList())
val totalEvents = sumOf { it.count }
val topOs = first().value.displayName
val statsGroups = map {
StatsGroup(it.value.displayName, it.count.percentOf(totalEvents), emptyList())
}
val resolvedGroupSize =
statsGroups.map { it.percentage }.resolveElementCountBy(minGroupSize, minPercentage)
val others = statsGroups.drop(resolvedGroupSize)
return IssueStats(
topOs,
statsGroups.take(resolvedGroupSize) +
if (others.isEmpty()) listOf()
else
listOf(
StatsGroup(
OTHER_GROUP,
others.sumOf { it.percentage },
others
.map { DataPoint(it.groupName, it.percentage) }
.let { points ->
// Here we just show top N (minGroupSize) + "Other" in the sub "Other" group.
points.take(minGroupSize) +
if (minGroupSize >= points.size) listOf()
else
listOf(
DataPoint(OTHER_GROUP, points.drop(minGroupSize).sumOf { it.percentage })
)
},
)
),
)
}
/**
* Returns summarized distributions of devices.
*
* Please ensure the input of the data points are sorted by [WithCount.count] in descending order.
*/
fun List<WithCount<Device>>.summarizeDevicesFromRawDataPoints(
minGroupSize: Int,
minPercentage: Double,
): IssueStats<Double> {
if (isEmpty()) return IssueStats(null, emptyList())
val topDevice = first().value
val totalEvents = sumOf { it.count }
val statsGroups =
groupBy { it.value.manufacturer }
.map { (manufacturer, reports) ->
val groupEvents = reports.sumOf { it.count }
val totalDataPoints =
reports
.sortedByDescending { it.count }
.map { DataPoint(it.value.model.substringAfter("/"), it.count.percentOf(totalEvents)) }
val resolvedGroupSize =
totalDataPoints.map { it.percentage }.resolveElementCountBy(minGroupSize, minPercentage)
val topGroupSizePercentages =
totalDataPoints.take(resolvedGroupSize).sumOf { it.percentage }
StatsGroup(
manufacturer,
groupEvents.percentOf(totalEvents),
totalDataPoints.take(resolvedGroupSize) +
if (resolvedGroupSize >= totalDataPoints.size) listOf()
else
listOf(
DataPoint(OTHER_GROUP, groupEvents.percentOf(totalEvents) - topGroupSizePercentages)
),
)
}
.sortedByDescending { it.percentage }
val resolvedGroupSize =
statsGroups.map { it.percentage }.resolveElementCountBy(minGroupSize, minPercentage)
val others = statsGroups.drop(resolvedGroupSize)
return IssueStats(
topDevice.model,
statsGroups.take(resolvedGroupSize) +
if (others.isEmpty()) listOf()
else
listOf(
StatsGroup(
OTHER_GROUP,
others.sumOf { it.percentage },
others
.map { DataPoint(it.groupName, it.percentage) }
.let { points ->
// Here we just show top N (minGroupSize) + "Other" in the sub "Other" group.
points.take(minGroupSize) +
if (minGroupSize >= points.size) listOf()
else
listOf(
DataPoint(OTHER_GROUP, points.drop(minGroupSize).sumOf { it.percentage })
)
},
)
),
)
}
| 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 5,953 | android | Apache License 2.0 |
app/src/test/kotlin/no/nav/punsjbolle/journalpost/PunsjbarJournalpostClientTest.kt | navikt | 365,000,292 | false | {"Kotlin": 66816, "Dockerfile": 198} | package no.nav.punsjbolle.journalpost
import no.nav.punsjbolle.AktørId.Companion.somAktørId
import no.nav.punsjbolle.JournalpostId.Companion.somJournalpostId
import no.nav.punsjbolle.Søknadstype
import org.intellij.lang.annotations.Language
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.skyscreamer.jsonassert.JSONAssert
internal class PunsjbarJournalpostClientTest {
@Test
fun `mapper kopiert journalpost`() {
val kopiertJournalpost = KopiertJournalpost(
journalpostId = "22222222222".somJournalpostId(),
opprinneligJournalpostId = "11111111111".somJournalpostId(),
aktørId = "33333333333".somAktørId(),
søknadstype = Søknadstype.PleiepengerSyktBarn
)
val (key, value) = PunsjbarJournalpostClient.map(kopiertJournalpost)
assertEquals("22222222222",key)
@Language("JSON")
val forventetValue = """
{
"journalpostId": "22222222222",
"aktørId": "33333333333",
"ytelse": "PSB",
"type": "KOPI",
"opprinneligJournalpost": {
"journalpostId": "11111111111"
}
}
""".trimIndent()
JSONAssert.assertEquals(forventetValue, value, true)
}
@Test
fun `feiler ved overstyring av nøkkelfelt`() {
assertThrows<IllegalArgumentException> {
PunsjbarJournalpostClient.map(object : PunsjbarJournalpost {
override val journalpostId = "1111111111".somJournalpostId()
override val aktørId = "33333333333".somAktørId()
override val søknadstype = Søknadstype.PleiepengerSyktBarn
override val type = "TEST"
override val ekstraInfo = mapOf("journalpostId" to mapOf(
"foo" to "bar"
))
})
}
}
} | 0 | Kotlin | 0 | 0 | 350a62b0d9c0a47a2e176fd539bf5aa25238756d | 1,959 | k9-punsjbolle | MIT License |
NotificationsLog/app/src/main/java/com/altamirano/fabricio/notifications/adapters/SwipeItem.kt | vladymix | 314,492,133 | false | null | package com.altamirano.fabricio.notifications.adapters
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.altamirano.fabricio.notifications.R
abstract class SwipeItem(val ctx: Context) : ItemTouchHelper.Callback() {
val deleteDrawable: Drawable
val mBackground: ColorDrawable
val intrinsicWidth: Int
val intrinsicHeight: Int
val backgroundColor: Int
init {
mBackground = ColorDrawable()
backgroundColor = Color.parseColor("#b80f0a")
deleteDrawable = ContextCompat.getDrawable(this.ctx, R.drawable.ic_trash_delete)!!
deleteDrawable.setTint(Color.WHITE)
intrinsicWidth = deleteDrawable.intrinsicWidth
intrinsicHeight = deleteDrawable.intrinsicHeight
}
override fun getMovementFlags(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
): Int {
return makeMovementFlags(0, ItemTouchHelper.LEFT)
}
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return false
}
override fun onChildDraw(
c: Canvas,
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean
) {
val itemView = viewHolder.itemView
val itemHeight = itemView.height
Log.i("Swipe", "desplazamiento $dX")
val isCancelled = dX == 0f && !isCurrentlyActive
if (isCancelled) {
mBackground.setBounds(0, 0, 0, 0)
mBackground.draw(c)
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
return
}
mBackground.setColor(backgroundColor)
mBackground.setBounds(
itemView.right + dX.toInt(),
itemView.top,
itemView.right,
itemView.bottom
)
mBackground.draw(c)
val deleteIconTop: Int = itemView.top + (itemHeight - intrinsicHeight) / 2
val deleteIconMargin: Int = (itemHeight - intrinsicHeight) / 2
val deleteIconLeft = itemView.right - deleteIconMargin - intrinsicWidth
val deleteIconRight = itemView.right - deleteIconMargin
val deleteIconBottom = deleteIconTop + intrinsicHeight
if(dX< -136){
deleteDrawable.setBounds(deleteIconLeft, deleteIconTop, deleteIconRight, deleteIconBottom)
deleteDrawable.draw(c)
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
} | 0 | Kotlin | 0 | 0 | c963fb87e31b26ec0a0355b1721c6366004eed56 | 2,965 | notifications_log | Apache License 2.0 |
src/main/kotlin/no/skatteetaten/aurora/gobo/graphql/auroraconfig/AuroraConfig.kt | Skatteetaten | 135,263,220 | false | {"Kotlin": 729888, "HTML": 1433, "Shell": 426} | package no.skatteetaten.aurora.gobo.graphql.auroraconfig
import com.expediagroup.graphql.generator.annotations.GraphQLIgnore
import com.fasterxml.jackson.databind.JsonNode
import com.jayway.jsonpath.JsonPath
import graphql.schema.DataFetchingEnvironment
import no.skatteetaten.aurora.gobo.graphql.applicationdeployment.ApplicationDeploymentRef
import no.skatteetaten.aurora.gobo.graphql.loadValue
import no.skatteetaten.aurora.gobo.integration.boober.AuroraConfigFileType
import no.skatteetaten.aurora.gobo.security.checkValidUserToken
import no.skatteetaten.aurora.gobo.security.runBlockingWithTimeout
import java.util.concurrent.CompletableFuture
data class AuroraConfig(
val name: String,
val ref: String,
val resolvedRef: String,
val files: List<AuroraConfigFileResource>
) {
suspend fun files(
types: List<AuroraConfigFileType>? = null,
fileNames: List<String>? = null,
dfe: DataFetchingEnvironment
): List<AuroraConfigFileResource> {
dfe.checkValidUserToken()
return files.filter {
types == null || types.contains(it.type)
}.filter {
fileNames == null || fileNames.contains(it.name)
}
}
fun applicationDeploymentSpec(
applicationDeploymentRefs: List<ApplicationDeploymentRef>,
dfe: DataFetchingEnvironment
): CompletableFuture<List<ApplicationDeploymentSpec>> {
runBlockingWithTimeout { dfe.checkValidUserToken() } // TODO bør fikses med @PreAuthorize?
return dfe.loadValue(
AdSpecKey(
name,
ref,
applicationDeploymentRefs
)
)
}
fun applicationFiles(
applicationDeploymentRefs: List<ApplicationDeploymentRef>,
types: List<AuroraConfigFileType>? = null,
dfe: DataFetchingEnvironment
): CompletableFuture<List<ApplicationFilesResource>> {
runBlockingWithTimeout { dfe.checkValidUserToken() } // TODO bør fikses med @PreAuthorize?
return dfe.loadValue(
ApplicationFilesKey(
name,
ref,
types,
applicationDeploymentRefs
)
)
}
}
data class ApplicationDeploymentSpec(
@GraphQLIgnore
val rawJsonValueWithDefaults: JsonNode
) {
val cluster: String? = rawJsonValueWithDefaults.text("/cluster/value")
val envName: String? = rawJsonValueWithDefaults.text("/envName/value")
val environment = rawJsonValueWithDefaults.expression("\$.envName.sources[?(@.name=='folderName')].value")
val name: String? = rawJsonValueWithDefaults.text("/name/value")
val version: String? = rawJsonValueWithDefaults.text("/version/value")
val releaseTo = rawJsonValueWithDefaults.optionalText("/releaseTo/value")
val application: String? = rawJsonValueWithDefaults.text("/name/value")
val type: String? = rawJsonValueWithDefaults.text("/type/value")
val deployStrategy: String? = rawJsonValueWithDefaults.text("/deployStrategy/type/value")
val replicas = rawJsonValueWithDefaults.int("/replicas/value")
val paused = rawJsonValueWithDefaults.boolean("/pause/value")
val affiliation: String? = rawJsonValueWithDefaults.text("/affiliation/value")
private fun JsonNode.expression(path: String) =
runCatching { JsonPath.read<List<String>>(this.toString(), path).first() }.getOrNull()
private fun JsonNode.optionalText(path: String) = this.at(path)?.textValue()
private fun JsonNode.text(path: String) = this.at(path).textValue()
private fun JsonNode.boolean(path: String) = this.at(path).booleanValue()
private fun JsonNode.int(path: String) = this.at(path).intValue()
}
data class AuroraConfigFileResource(
val name: String,
val contents: String,
val type: AuroraConfigFileType,
val contentHash: String
)
data class NewAuroraConfigFileInput(
val auroraConfigName: String,
val auroraConfigReference: String? = null,
val fileName: String,
val contents: String
)
data class UpdateAuroraConfigFileInput(
val auroraConfigName: String,
val auroraConfigReference: String? = null,
val fileName: String,
val contents: String,
val existingHash: String
)
data class AuroraConfigFileValidationResponse(
val message: String? = null,
val success: Boolean,
val file: AuroraConfigFileResource? = null
)
data class ApplicationFilesResource(
val files: List<AuroraConfigFileResource>,
val application: String,
val environment: String,
)
| 0 | Kotlin | 0 | 3 | 9a28e1d711756479696672f139568fdeadb74ac1 | 4,539 | gobo | Apache License 2.0 |
app/src/main/java/com/lyc/gank/utils/IntentExt.kt | SirLYC | 93,046,345 | false | null | package com.lyc.gank.utils
import android.content.Intent
import com.lyc.data.resp.GankItem
/**
* Created by <NAME> on 2018/2/25.
*/
//GankItem
private const val KEY_ID = "KEY_ID"
private const val KEY_URL = "KEY_URL"
private const val KEY_IMAGE = "KEY_IMAGE"
private const val KEY_WHO = "KEY_WHO"
private const val KEY_TIME = "KEY_TIME"
private const val KEY_TYPE = "KEY_TYPE"
private const val KEY_DESC = "KEY_DESC"
fun Intent.putGankItem(gankItem: GankItem) =
putExtra(KEY_ID, gankItem.idOnServer)
.putExtra(KEY_URL, gankItem.url)
.putExtra(KEY_IMAGE, gankItem.imgUrl)
.putExtra(KEY_WHO, gankItem.author)
.putExtra(KEY_TIME, gankItem.publishTime)
.putExtra(KEY_TYPE, gankItem.type)
.putExtra(KEY_DESC, gankItem.title)
fun Intent.getGankItem(): GankItem? {
val id = getStringExtra(KEY_ID)
val url = getStringExtra(KEY_URL)
val image = getStringExtra(KEY_IMAGE)
val who = getStringExtra(KEY_WHO)
val time = getStringExtra(KEY_TIME)
val type = getStringExtra(KEY_TYPE)
val desc = getStringExtra(KEY_DESC)
if (id == null || url == null || who == null
|| time == null || type == null || desc == null)
return null
return GankItem(id, desc, time, type, url, who, null)
.apply { imgUrl = image }
} | 1 | Kotlin | 0 | 6 | f72e0079a84871da510012e8f4b8cb330f80d1a1 | 1,370 | Android-Gank-Share | Apache License 2.0 |
v9/src/androidTest/java/dev/romainguy/graphics/v9/PathResizerTest.kt | romainguy | 520,313,998 | false | {"Kotlin": 25671} | /*
* Copyright (C) 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.romainguy.graphics.v9
import android.graphics.Rect
import android.graphics.RectF
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PathResizerTest {
@Test
fun emptySlice() {
val slice = Slice(0.0f, 0.0f)
assertEquals(0.0f, slice.size)
}
@Test(expected = IllegalArgumentException::class)
fun startMustBeLessThanEnd() {
val slice = Slice(2.0f, 1.0f)
assertEquals(1.0f, slice.size)
}
@Test
fun sliceFromIntRect() {
val slices = Slices(Rect(0, 0, 4, 4))
assertEquals(1, slices.verticalSlices.size)
assertEquals(Slice(0.0f, 4.0f), slices.verticalSlices[0])
assertEquals(1, slices.horizontalSlices.size)
assertEquals(Slice(0.0f, 4.0f), slices.horizontalSlices[0])
}
@Test
fun sliceFromInt() {
val slices = Slices(0, 0, 4, 4)
assertEquals(1, slices.verticalSlices.size)
assertEquals(Slice(0.0f, 4.0f), slices.verticalSlices[0])
assertEquals(1, slices.horizontalSlices.size)
assertEquals(Slice(0.0f, 4.0f), slices.horizontalSlices[0])
}
@Test
fun sliceFromFloatRect() {
val slices = Slices(RectF(0.0f, 0.0f, 4.0f, 4.0f))
assertEquals(1, slices.verticalSlices.size)
assertEquals(Slice(0.0f, 4.0f), slices.verticalSlices[0])
assertEquals(1, slices.horizontalSlices.size)
assertEquals(Slice(0.0f, 4.0f), slices.horizontalSlices[0])
}
@Test
fun sliceFromFloat() {
val slices = Slices(0.0f, 0.0f, 4.0f, 4.0f)
assertEquals(1, slices.verticalSlices.size)
assertEquals(Slice(0.0f, 4.0f), slices.verticalSlices[0])
assertEquals(1, slices.horizontalSlices.size)
assertEquals(Slice(0.0f, 4.0f), slices.horizontalSlices[0])
}
@Test(expected = IllegalArgumentException::class)
fun emptyVerticalSlices() {
Slices(listOf(), listOf(Slice(0.0f, 1.0f)))
}
@Test(expected = IllegalArgumentException::class)
fun emptyHorizontalSlices() {
Slices(listOf(Slice(0.0f, 1.0f)), listOf())
}
@Test
fun slices() {
val slices = Slices(
listOf(Slice(0.0f, 1.0f), Slice(2.0f, 3.0f)),
listOf(Slice(0.0f, 1.0f), Slice(2.0f, 3.0f))
)
assertEquals(2, slices.verticalSlices.size)
assertEquals(2, slices.horizontalSlices.size)
}
@Test
fun filterEmptySlices() {
val slices = Slices(
listOf(Slice(0.0f, 0.0f), Slice(2.0f, 3.0f)),
listOf(Slice(0.0f, 0.0f), Slice(2.0f, 3.0f))
)
assertEquals(1, slices.verticalSlices.size)
assertEquals(1, slices.horizontalSlices.size)
}
// TODO: test path resizing
}
| 1 | Kotlin | 3 | 333 | 00bf8ad051bf4fb657559611e5ed46b233ea1ba2 | 3,447 | v9 | Apache License 2.0 |
kaff4-core/src/main/kotlin/net/navatwo/kaff4/streams/map_stream/IntervalTreeExtensions.kt | kaff4 | 555,850,412 | false | {"Kotlin": 419315, "Shell": 649} | package net.navatwo.kaff4.streams.map_stream
import com.github.nava2.interval_tree.IntervalTree
import net.navatwo.kaff4.yieldNotNull
import java.util.SortedSet
private fun Sequence<MapStreamEntry>.compressed(requireSort: Boolean): Sequence<MapStreamEntry> = sequence {
val sortedEntries = if (requireSort) [email protected]() else this@compressed
var previousEntry: MapStreamEntry? = null
for (mapStreamEntry in sortedEntries) {
if (previousEntry == null) {
previousEntry = mapStreamEntry
continue
}
previousEntry = if (previousEntry.canMerge(mapStreamEntry)) {
previousEntry.merge(mapStreamEntry)
} else {
yield(previousEntry)
mapStreamEntry
}
}
yieldNotNull(previousEntry)
}
internal fun IntervalTree<MapStreamEntry>.compressedSequence(): Sequence<MapStreamEntry> {
if (this.size <= 1) return this.asSequence()
return asSequence().compressed(requireSort = false)
}
internal fun SortedSet<MapStreamEntry>.compressedSequence(): Sequence<MapStreamEntry> {
return asSequence().compressed(requireSort = false)
}
internal fun Iterator<MapStreamEntry>.compressedSequence(isSorted: Boolean): Sequence<MapStreamEntry> {
return asSequence().compressed(requireSort = !isSorted)
}
| 12 | Kotlin | 0 | 1 | 8cad41439e93d31548c12c6252cf12f293db147f | 1,254 | kaff4 | MIT License |
android/app/src/main/kotlin/com/dalpat/covid19_tracker/MainActivity.kt | dalpat98 | 265,201,234 | false | null | package Enter package name here
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 9 | 936a288669454bbaf8912d573059dc80803a9e38 | 128 | Covid-Tracker-App | Apache License 2.0 |
core/src/main/kotlin/net/insprill/mapdisplays/core/exception/EncodeException.kt | Insprill | 525,202,305 | false | null | package net.insprill.mapdisplays.core.exception
import java.io.IOException
class EncodeException(msg: String) : IOException(msg)
| 0 | Kotlin | 0 | 0 | ccb719808d2d5d3e3b1f4601c924f59c56276c8c | 131 | map-displays | Apache License 2.0 |
HTTPShortcuts/app/src/main/java/ch/rmy/android/http_shortcuts/utils/NotificationUtil.kt | staticStone | 136,870,061 | true | {"Kotlin": 435889, "Java": 57185} | package ch.rmy.android.http_shortcuts.utils
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import ch.rmy.android.http_shortcuts.R
object NotificationUtil {
const val PENDING_SHORTCUTS_NOTIFICATION_CHANNEL = "pending"
fun createChannels(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val name = context.getString(R.string.name_pending_shortcuts_channel)
val importance = NotificationManager.IMPORTANCE_MIN
val channel = NotificationChannel(PENDING_SHORTCUTS_NOTIFICATION_CHANNEL, name, importance)
notificationManager.createNotificationChannel(channel)
}
}
}
| 0 | Kotlin | 0 | 0 | 2570dc75da654c232ea8f778c65116132a447978 | 868 | HTTP-Shortcuts | MIT License |
Functional/Named and Default Argument/Contoh 4/src/App.kt | anangkur | 200,490,004 | false | null | // main function
fun main() {
val fullName = getFullName(first = "Dicoding")
print(fullName)
}
fun getFullName(first: String = "Kotlin", middle: String = " is ", last: String = "Awesome"): String {
return "$first $middle $last"
} | 0 | Kotlin | 1 | 0 | e2151c0a27075f47a1963f0c802ff6b834b3b849 | 242 | dicoding-basic-kotlin-submission | MIT License |
Functional/Named and Default Argument/Contoh 4/src/App.kt | anangkur | 200,490,004 | false | null | // main function
fun main() {
val fullName = getFullName(first = "Dicoding")
print(fullName)
}
fun getFullName(first: String = "Kotlin", middle: String = " is ", last: String = "Awesome"): String {
return "$first $middle $last"
} | 0 | Kotlin | 1 | 0 | e2151c0a27075f47a1963f0c802ff6b834b3b849 | 242 | dicoding-basic-kotlin-submission | MIT License |
core/util/src/main/java/dev/ryzhoov/util/ui/BaseDialogFragment.kt | v1aditech | 581,266,106 | false | {"Kotlin": 161157} | package dev.ryzhoov.util.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.viewbinding.ViewBinding
abstract class BaseDialogFragment<T : ViewBinding> : DialogFragment(), BindingInflater<T> {
private var _binding: T? = null
protected val binding: T get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = inflateBinding()
return binding.root
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
} | 0 | Kotlin | 0 | 0 | 5b0fc12bf74f19f765d99d5671b0f599bebd17a9 | 720 | napomnix | Apache License 2.0 |
app/src/main/java/android/example/homescout/ui/scan/ScanFragment.kt | lowguy98 | 671,297,165 | false | null | package android.example.homescout.ui.scan
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Intent
import android.content.res.AssetManager
import android.example.homescout.R
import android.example.homescout.databinding.FragmentScanBinding
import android.example.homescout.ui.intro.PermissionAppIntro
import android.example.homescout.utils.BluetoothAPILogger
import android.example.homescout.utils.Constants.SCAN_PERIOD
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import androidx.room.util.FileUtil
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import org.tensorflow.lite.Interpreter
import timber.log.Timber
import java.io.FileInputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.FileChannel
class ScanFragment : Fragment() {
// PROPERTIES
private var _binding: FragmentScanBinding? = null
private val binding get() = _binding!!
private val isBluetoothEnabled : Boolean
get() = bluetoothAdapter.isEnabled
private val scanResults = mutableListOf<ScanResult>()
private val classificationResults = mutableListOf<String>()
private var isScanning = false
set(value) {
field = value
if (value) {
binding.buttonScan.text = getString(R.string.scan_button_stop)
} else {
binding.buttonScan.text = getString(R.string.scan_button_scan)
}
}
// PROPERTIES lateinit
private lateinit var scanSettings: ScanSettings
private lateinit var tflite : Interpreter
private lateinit var tflitemodel : ByteBuffer
// PROPERTIES lazy
private val bluetoothAdapter: BluetoothAdapter by lazy {
val bluetoothManager = activity?.getSystemService(AppCompatActivity.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothManager.adapter
}
private val bleScanner by lazy {
bluetoothAdapter.bluetoothLeScanner
}
private val scanResultAdapter: ScanResultAdapter by lazy {
ScanResultAdapter(scanResults, classificationResults) { result ->
// User tapped on a scan result
with(result.device) {
Snackbar.make(binding.root, "Tapped on: $address", Snackbar.LENGTH_LONG).show()
}
}
}
// LIFECYCLE FUNCTIONS
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
setupViewModelAndBinding(inflater, container)
buildScanSettings()
setOnClickListenerForScanButton()
setupRecyclerView()
val assets = context?.assets ?: throw Exception("Context or assets is null")
try {
tflitemodel = setupModel(assets,"model.tflite")
tflite = Interpreter(tflitemodel)
}
catch(ex: Exception){ex.printStackTrace()
}
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
// FUNCTIONS USED IN onCreateView() (for code readability)
private fun setupViewModelAndBinding(inflater: LayoutInflater, container: ViewGroup?) {
_binding = FragmentScanBinding.inflate(inflater, container, false)
}
private fun buildScanSettings() {
scanSettings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build()
}
private fun setOnClickListenerForScanButton() {
binding.buttonScan.setOnClickListener {
if (!isBluetoothEnabled) {
MaterialAlertDialogBuilder(requireContext())
.setTitle("Enable Bluetooth required!")
.setMessage("Please turn on Bluetooth. Thanks.")
.setPositiveButton("Ok") { _, _ ->
// Respond to positive button press
val intentBluetooth = Intent().apply {
action = Settings.ACTION_BLUETOOTH_SETTINGS
}
requireContext().startActivity(intentBluetooth)
}
.show()
return@setOnClickListener
}
if (isScanning) {
stopBleScan()
} else {
startBLEScan()
}
}
}
private fun setupRecyclerView() {
binding.scanResultsRecyclerView.apply {
adapter = scanResultAdapter
layoutManager = LinearLayoutManager(
activity,
RecyclerView.VERTICAL,
false
)
isNestedScrollingEnabled = false
}
val animator = binding.scanResultsRecyclerView.itemAnimator
if (animator is SimpleItemAnimator) {
animator.supportsChangeAnimations = false
}
}
private fun setupModel(assetManager: AssetManager, modelPath: String): ByteBuffer {
val fileDescriptor = assetManager.openFd(modelPath)
val inputStream = FileInputStream(fileDescriptor.fileDescriptor)
val fileChannel = inputStream.channel
val startOffset = fileDescriptor.startOffset
val declaredLength = fileDescriptor.declaredLength
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength)
}
private fun checkIfBluetoothIsEnabled() {
binding.buttonScan.isEnabled = isBluetoothEnabled
if (!isBluetoothEnabled) {
MaterialAlertDialogBuilder(requireContext())
.setTitle("Bluetooth required!")
.setMessage("Please enable Bluetooth. Thanks")
.setPositiveButton("Ok") { _, _ ->
// Respond to positive button press
val intentBluetooth = Intent().apply {
action = Settings.ACTION_BLUETOOTH_SETTINGS
}
requireContext().startActivity(intentBluetooth)
}
.show()
}
}
// CALLBACKS
private val scanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
BluetoothAPILogger().logResults(result)
}
val scanRecord: ByteArray? = result.scanRecord?.bytes
val scanRecord_hex: String? = if (scanRecord != null) {
bytesToHex(scanRecord)
} else {
null
}
println(scanRecord_hex)
var inferResult = doInference(scanRecord_hex)
// this might needs to be changed as the device.address might change due to
// MAC randomization
// check if the current found result is already in the entire scanResult list
val indexQuery = scanResults.indexOfFirst { it.device.address == result.device.address }
// element not found returns -1
if (indexQuery != -1) { // A scan result already exists with the same address
scanResults[indexQuery] = result
classificationResults[indexQuery] = inferResult
scanResultAdapter.notifyItemChanged(indexQuery)
} else { // found new device
// with(result.device) {
// //Timber.i( address: $address")
// }
scanResults.add(result)
classificationResults.add(inferResult)
scanResultAdapter.notifyItemInserted(scanResults.size - 1)
}
}
override fun onScanFailed(errorCode: Int) {
Timber.i("onScanFailed: code $errorCode")
}
}
// PRIVATE FUNCTIONS
private fun startBLEScan() {
if (!isBluetoothEnabled) { checkIfBluetoothIsEnabled() }
scanResults.clear()
scanResultAdapter.notifyDataSetChanged()
// if (ActivityCompat.checkSelfPermission(
// requireContext(),
// Manifest.permission.BLUETOOTH_SCAN
// ) != PackageManager.PERMISSION_GRANTED
// ) {
// startActivity(Intent(requireContext(), PermissionAppIntro::class.java))
// return
// }
if (!XXPermissions.isGranted(requireContext(), Permission.BLUETOOTH_SCAN)){
startActivity(Intent(requireContext(), PermissionAppIntro::class.java))
return
}
val handler = Handler(Looper.getMainLooper())
handler.postDelayed({
isScanning = false
bleScanner.stopScan(scanCallback)
}, SCAN_PERIOD)
bleScanner.startScan(null, scanSettings, scanCallback)
isScanning = true
}
private fun stopBleScan() {
// if (ActivityCompat.checkSelfPermission(
// requireContext(),
// Manifest.permission.BLUETOOTH_SCAN
// ) != PackageManager.PERMISSION_GRANTED
// ) {
// startActivity(Intent(requireContext(), PermissionAppIntro::class.java))
// return
// }
if (!XXPermissions.isGranted(requireContext(), Permission.BLUETOOTH_SCAN)){
startActivity(Intent(requireContext(), PermissionAppIntro::class.java))
return
}
bleScanner.stopScan(scanCallback)
isScanning = false
}
//transfer scanRecords into hex format
private val hexArray = "0123456789ABCDEF".toCharArray()
private fun bytesToHex(bytes: ByteArray): String? {
val hexChars = CharArray(bytes.size * 2)
for (j in bytes.indices) {
val v = bytes[j].toInt() and 0xFF
hexChars[j * 2] = hexArray[v ushr 4]
hexChars[j * 2 + 1] = hexArray[v and 0x0F]
}
return String(hexChars)
}
private fun doInference(hex_stream: String?): String {
val features: List<Any>? = hex_stream?.let { featureExtraction(it) }
// convert the extracted features into the appropriate format
var inputData = ByteBuffer.allocateDirect(4 * 3) // assuming that there are 3 features and they are all floats
inputData.order(ByteOrder.nativeOrder()) // use the device's native byte order (either BIG_ENDIAN or LITTLE_ENDIAN)
// add the features to the ByteBuffer
val scaledFeatures = scaleFeatures(features!!)
scaledFeatures.forEach { feature ->
inputData.putFloat(feature) // 由于所有特征都是浮点数,可以直接使用putFloat
}
inputData.rewind()
var outputData = Array(1) { FloatArray(3) } // assuming the model outputs 3 floats
tflite.run(inputData, outputData)
// Find the label with the highest probability
val labels = listOf("health and fitness", "personal electronics", "tracker")
val maxIndex = outputData[0].indices.maxByOrNull { outputData[0][it] } ?: -1// Find the index of the maximum value
return if (maxIndex != -1) {
labels[maxIndex]
} else {
"Unknown"
}
}
private fun scaleFeatures(features: List<Any>): List<Float> {
// 这里是Python中获取的mean_和scale_的示例值
val mean = floatArrayOf(68.402435F, 2.7195122F, 0.5121951F)
val scale = floatArrayOf(20.386724F, 1.2569261F, 0.8729527F)
return features.mapIndexed { index, feature ->
when (feature) {
is Int -> ((feature - mean[index]) / scale[index]).toFloat()
is Float -> (feature - mean[index]) / scale[index]
else -> feature as Float // 如果有其他数据类型,按需处理
}
}
}
fun featureExtraction(raw: String): List<Any> {
var i = 0
var adCnt = 0
var manufacturerOrService = 0
var bluetoothSupported = 2
val typeList = mutableListOf<String>()
val adStruct = mutableMapOf<String, String>()
val adLenList = mutableListOf<Int>()
while (i < raw.length) {
val length = raw.substring(i, i + 2).toInt(16)
if (length == 0) break
val type = raw.substring(i + 2, i + 4)
val data = raw.substring(i + 4, i + length * 2 + 2)
adCnt += 1
typeList.add(type)
adStruct[type] = data
adLenList.add(length)
when (type) {
"16", "ff" -> manufacturerOrService = 1
"01" -> {
val binaryStr = Integer.toBinaryString(0x1a).padStart(8, '0')
bluetoothSupported = if (binaryStr[5] == '0') 1 else 0
}
}
i += length * 2 + 2
}
return listOf(i, adCnt, bluetoothSupported)
}
} | 0 | Kotlin | 0 | 0 | 3de3453fb61d630d79e00d7855e8dc2d25633ca9 | 13,536 | BLE-classifier | Apache License 2.0 |
src/main/kotlin/scene/SceneType.kt | markusmo3 | 246,157,113 | true | {"Kotlin": 102628, "ANTLR": 26463} | package scene
import com.intellij.openapi.fileTypes.LanguageFileType
import common.Icons
object SceneType : LanguageFileType(SceneLanguage) {
override fun getIcon() = Icons.SCENE_FILE
override fun getName() = "Scene"
override fun getDefaultExtension() = "tres"
override fun getDescription() = name
} | 0 | Kotlin | 0 | 0 | 140f3bea47e100b44f9c2ec76991fcc653ea0829 | 323 | intellij-gdscript | MIT License |
stream-chat-android-client/src/main/java/io/getstream/chat/android/client/api/ChatClientConfig.kt | GetStream | 177,873,527 | false | {"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229} | /*
* Copyright (c) 2014-2022 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getstream.chat.android.client.api
import io.getstream.chat.android.client.ChatClient
import io.getstream.chat.android.client.api.internal.DistinctChatApi
import io.getstream.chat.android.client.logger.ChatLoggerConfig
import io.getstream.chat.android.client.notifications.handler.NotificationConfig
/**
* A config to setup the [ChatClient] behavior.
*
* @param apiKey The API key of your Stream Chat app obtained from the
* [Stream Dashboard](https://dashboard.getstream.io/).
* @param httpUrl The base URL to be used by the client.
* @param cdnHttpUrl The base CDN URL to be used by the client.
* @param wssUrl The base WebSocket URL to be used by the client.
* @param warmUp Controls the connection warm-up behavior.
* @param loggerConfig A logging config to be used by the client.
* @param distinctApiCalls Controls whether [DistinctChatApi] is enabled or not.
* @param debugRequests Controls whether requests can be recorded or not.
* @param notificationConfig A notification config to be used by the client.
*/
@Suppress("LongParameterList")
public class ChatClientConfig @JvmOverloads constructor(
public val apiKey: String,
public var httpUrl: String,
public var cdnHttpUrl: String,
public var wssUrl: String,
public val warmUp: Boolean,
public val loggerConfig: ChatLoggerConfig,
public var distinctApiCalls: Boolean = true,
public val debugRequests: Boolean,
public val notificationConfig: NotificationConfig,
) {
public var isAnonymous: Boolean = false
}
| 24 | Kotlin | 273 | 1,451 | 8e46f46a68810d8086c48a88f0fff29faa2629eb | 2,154 | stream-chat-android | FSF All Permissive License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/medialive/CfnInputSecurityGroupPropsDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.medialive
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.medialive.CfnInputSecurityGroupProps
@Generated
public fun buildCfnInputSecurityGroupProps(initializer: @AwsCdkDsl
CfnInputSecurityGroupProps.Builder.() -> Unit): CfnInputSecurityGroupProps =
CfnInputSecurityGroupProps.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | b22e397ff37c5fce365a5430790e5d83f0dd5a64 | 456 | aws-cdk-kt | Apache License 2.0 |
app/src/main/java/com/rudione/tranquilhaven/viewmodel/ProfileViewModel.kt | Rudione | 579,201,331 | false | null | package com.rudione.tranquilhaven.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.rudione.tranquilhaven.data.model.User
import com.rudione.tranquilhaven.utils.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ProfileViewModel @Inject constructor(
private val firestore: FirebaseFirestore,
private val auth: FirebaseAuth
): ViewModel() {
private val _user = MutableStateFlow<Resource<User>>(Resource.Unspecified())
val user = _user.asStateFlow()
init {
getUser()
}
fun getUser() {
viewModelScope.launch {
_user.emit(Resource.Loading())
}
firestore.collection("user").document(auth.uid!!)
.addSnapshotListener { value, error ->
if (error != null) {
viewModelScope.launch {
_user.emit(Resource.Failure(error.message.toString()))
}
} else {
val user = value?.toObject(User::class.java)
viewModelScope.launch {
_user.emit(Resource.Success(user))
}
}
}
}
fun logout() {
auth.signOut()
}
} | 0 | Kotlin | 0 | 0 | 7b3eaf40f3617fbc9c83b7e6de52eb9fe84fbf52 | 1,532 | TranquilHaven | MIT License |
tulip/libtulip-persistence-api/src/commonMain/kotlin/com/tajmoti/libtulip/repository/HostedMovieRepository.kt | Tajmoti | 391,138,914 | false | null | package com.tajmoti.libtulip.repository
import com.tajmoti.libtulip.model.TulipMovie
import com.tajmoti.libtulip.model.key.MovieKey
interface HostedMovieRepository : RwRepository<TulipMovie.Hosted, MovieKey.Hosted>
| 6 | Kotlin | 0 | 0 | c653ebf97b1a43c505b1debb7aa636b06db1ff33 | 217 | Tulip | MIT License |
core/src/commonMain/kotlin/work/socialhub/kmastodon/internal/FollowsResourceImpl.kt | uakihir0 | 783,390,459 | false | {"Kotlin": 168825, "Ruby": 2191, "Shell": 2164, "Makefile": 319} | package work.socialhub.kmastodon.internal
import work.socialhub.khttpclient.HttpRequest
import work.socialhub.kmastodon.api.FollowsResource
import work.socialhub.kmastodon.api.request.follows.FollowsRemoteFollowRequest
import work.socialhub.kmastodon.api.response.Response
import work.socialhub.kmastodon.api.response.follows.FollowsRemoteFollowResponse
import work.socialhub.kmastodon.util.Headers
import work.socialhub.kmastodon.util.MediaType
class FollowsResourceImpl(
uri: String,
accessToken: String
) : AbstractAuthResourceImpl(uri, accessToken),
FollowsResource {
override fun remoteFollow(
request: FollowsRemoteFollowRequest
): Response<FollowsRemoteFollowResponse> = exec {
HttpRequest()
.url("${uri}/api/v1/follow_requests")
.header(Headers.AUTHORIZATION, bearerToken())
.accept(MediaType.JSON)
.pwn("uri", request.uri)
.post()
}
}
| 0 | Kotlin | 0 | 1 | cee156c1a8b272b424ca096217c277b6903d24cd | 947 | kmastodon | MIT License |
Common/src/main/java/ram/talia/hexal/api/nbt/HexalNBTHelper.kt | Talia-12 | 519,549,575 | false | null | package ram.talia.hexal.api.nbt
import at.petrak.hexcasting.api.spell.iota.Iota
import at.petrak.hexcasting.api.utils.asCompound
import at.petrak.hexcasting.api.utils.asInt
import at.petrak.hexcasting.common.lib.hex.HexIotaTypes
import net.minecraft.client.multiplayer.ClientLevel
import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.IntTag
import net.minecraft.nbt.ListTag
import net.minecraft.nbt.NbtUtils
import net.minecraft.nbt.Tag
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.Entity
import ram.talia.hexal.api.linkable.ILinkable
import ram.talia.hexal.api.linkable.LinkableRegistry
import java.util.*
fun ListTag.toIotaList(level: ServerLevel): MutableList<Iota> {
val out = ArrayList<Iota>()
for (patTag in this) {
val tag = patTag.asCompound
out.add(HexIotaTypes.deserialize(tag, level))
}
return out
}
@JvmName("toNbtListSpellDatum")
fun List<Iota>.toNbtList(): ListTag {
val patsTag = ListTag()
for (pat in this) {
patsTag.add(HexIotaTypes.serialize(pat))
}
return patsTag
}
inline fun <reified T : Entity> ListTag.toEntityList(level: ServerLevel): MutableList<T> {
val out = ArrayList<T>()
for (eTag in this) {
val uuid = NbtUtils.loadUUID(eTag)
val entity = level.getEntity(uuid)
if (entity != null && entity.isAlive && entity is T)
out.add(entity)
}
return out
}
@JvmName("toNbtListEntity")
fun List<Entity>.toNbtList(): ListTag {
val listTag = ListTag()
for (entity in this) {
listTag.add(NbtUtils.createUUID(entity.uuid))
}
return listTag
}
fun ListTag.toIntList(): MutableList<Int> {
val out = mutableListOf<Int>()
for (idTag in this) {
out.add(idTag.asInt)
}
return out
}
@JvmName("toNbtListInt")
fun List<Int>.toNbtList(): ListTag {
val listTag = ListTag()
this.forEach { listTag.add(IntTag.valueOf(it)) }
return listTag
}
@JvmName("toNbtListUUID")
fun List<UUID>.toNbtList(): ListTag {
val listTag = ListTag()
this.forEach { listTag.add(NbtUtils.createUUID(it)) }
return listTag
}
fun ListTag.toUUIDList(): MutableList<UUID> {
val uuids = mutableListOf<UUID>()
this.forEach { uuids.add(NbtUtils.loadUUID(it)) }
return uuids
}
@JvmName("toNbtListTag")
fun List<Tag>.toNbtList(): ListTag {
val listTag = ListTag()
this.forEach { listTag.add(it) }
return listTag
}
fun ListTag.toCompoundTagList(): MutableList<CompoundTag> {
val tags = mutableListOf<Tag>()
tags.addAll(this)
return tags.map { it as CompoundTag } as MutableList<CompoundTag>
}
@JvmName("toSyncTagILinkable")
fun List<ILinkable>.toSyncTag(): ListTag {
val listTag = ListTag()
this.forEach { listTag.add(LinkableRegistry.wrapSync(it)) }
return listTag
}
fun ListTag.toIRenderCentreMap(level: ClientLevel): Map<CompoundTag, ILinkable.IRenderCentre> {
val out = mutableMapOf<CompoundTag, ILinkable.IRenderCentre>()
this.forEach { centreTag ->
val centre = LinkableRegistry.fromSync(centreTag as CompoundTag, level)
if (centre != null) out[centreTag] = centre
}
return out
} | 17 | Kotlin | 9 | 9 | 56eddb1931f5da21695640052989ee024a8d78da | 2,993 | Hexal | MIT License |
AppCheck-ins/app/src/main/java/com/example/iram/check_ins/Util/Location.kt | IramML | 141,610,474 | false | null | package com.example.iram.check_ins.Util
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import com.example.iram.check_ins.Interfaces.locationListener
import com.example.iram.check_ins.Messages.Errors
import com.example.iram.check_ins.Messages.Message
import com.example.iram.check_ins.Messages.Messages
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
class Location(var activity: AppCompatActivity, locationListener: locationListener){
private val permissionFineLocation=android.Manifest.permission.ACCESS_FINE_LOCATION
private val permissionCoarseLocation=android.Manifest.permission.ACCESS_COARSE_LOCATION
private val REQUEST_CODE_LOCATION=100
private var fusedLocationClient:FusedLocationProviderClient?=null
private var locationRequest:LocationRequest?=null
private var callbabck:LocationCallback?=null
init {
fusedLocationClient= FusedLocationProviderClient(activity.applicationContext)
inicializeLocationRequest()
callbabck=object: LocationCallback(){
override fun onLocationResult(p0: LocationResult?) {
super.onLocationResult(p0)
locationListener.locationResponse(p0!!)
}
}
}
private fun inicializeLocationRequest() {
locationRequest= LocationRequest()
locationRequest?.interval=50000
locationRequest?.fastestInterval=5000
locationRequest?.priority=LocationRequest.PRIORITY_HIGH_ACCURACY
}
private fun validatePermissionsLocation():Boolean{
val fineLocationAvailable=ActivityCompat.checkSelfPermission(activity.applicationContext, permissionFineLocation)==PackageManager.PERMISSION_GRANTED
val coarseLocationAvailable=ActivityCompat.checkSelfPermission(activity.applicationContext, permissionCoarseLocation)==PackageManager.PERMISSION_GRANTED
return fineLocationAvailable && coarseLocationAvailable
}
private fun requestPermissions(){
val contextProvider=ActivityCompat.shouldShowRequestPermissionRationale(activity, permissionFineLocation)
if(contextProvider){
Message.message(activity.applicationContext, Messages.RATIONALE)
}
permissionRequest()
}
private fun permissionRequest(){
ActivityCompat.requestPermissions(activity, arrayOf(permissionFineLocation, permissionCoarseLocation), REQUEST_CODE_LOCATION)
}
fun onRequestPermissionsResult(requestCode:Int, permissions:Array<out String>, grantResults:IntArray){
when(requestCode){
REQUEST_CODE_LOCATION->{
if(grantResults.size>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
getLocation()
}else{
Message.messageError(activity.applicationContext, Errors.PERMISSION_DENIED)
}
}
}
}
fun stopUpdateLocation(){
this.fusedLocationClient?.removeLocationUpdates(callbabck)
}
fun inicializeLocation(){
if (validatePermissionsLocation()){
getLocation()
}else{
requestPermissions()
}
}
@SuppressLint("MissingPermission")
private fun getLocation() {
validatePermissionsLocation()
fusedLocationClient?.requestLocationUpdates(locationRequest, callbabck, null)
}
} | 0 | Kotlin | 0 | 0 | 511b10c4207402c0ddd99efde5e8689f07b07fd0 | 3,636 | CheckinsApp | MIT License |
AppCheck-ins/app/src/main/java/com/example/iram/check_ins/Util/Location.kt | IramML | 141,610,474 | false | null | package com.example.iram.check_ins.Util
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import com.example.iram.check_ins.Interfaces.locationListener
import com.example.iram.check_ins.Messages.Errors
import com.example.iram.check_ins.Messages.Message
import com.example.iram.check_ins.Messages.Messages
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
class Location(var activity: AppCompatActivity, locationListener: locationListener){
private val permissionFineLocation=android.Manifest.permission.ACCESS_FINE_LOCATION
private val permissionCoarseLocation=android.Manifest.permission.ACCESS_COARSE_LOCATION
private val REQUEST_CODE_LOCATION=100
private var fusedLocationClient:FusedLocationProviderClient?=null
private var locationRequest:LocationRequest?=null
private var callbabck:LocationCallback?=null
init {
fusedLocationClient= FusedLocationProviderClient(activity.applicationContext)
inicializeLocationRequest()
callbabck=object: LocationCallback(){
override fun onLocationResult(p0: LocationResult?) {
super.onLocationResult(p0)
locationListener.locationResponse(p0!!)
}
}
}
private fun inicializeLocationRequest() {
locationRequest= LocationRequest()
locationRequest?.interval=50000
locationRequest?.fastestInterval=5000
locationRequest?.priority=LocationRequest.PRIORITY_HIGH_ACCURACY
}
private fun validatePermissionsLocation():Boolean{
val fineLocationAvailable=ActivityCompat.checkSelfPermission(activity.applicationContext, permissionFineLocation)==PackageManager.PERMISSION_GRANTED
val coarseLocationAvailable=ActivityCompat.checkSelfPermission(activity.applicationContext, permissionCoarseLocation)==PackageManager.PERMISSION_GRANTED
return fineLocationAvailable && coarseLocationAvailable
}
private fun requestPermissions(){
val contextProvider=ActivityCompat.shouldShowRequestPermissionRationale(activity, permissionFineLocation)
if(contextProvider){
Message.message(activity.applicationContext, Messages.RATIONALE)
}
permissionRequest()
}
private fun permissionRequest(){
ActivityCompat.requestPermissions(activity, arrayOf(permissionFineLocation, permissionCoarseLocation), REQUEST_CODE_LOCATION)
}
fun onRequestPermissionsResult(requestCode:Int, permissions:Array<out String>, grantResults:IntArray){
when(requestCode){
REQUEST_CODE_LOCATION->{
if(grantResults.size>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
getLocation()
}else{
Message.messageError(activity.applicationContext, Errors.PERMISSION_DENIED)
}
}
}
}
fun stopUpdateLocation(){
this.fusedLocationClient?.removeLocationUpdates(callbabck)
}
fun inicializeLocation(){
if (validatePermissionsLocation()){
getLocation()
}else{
requestPermissions()
}
}
@SuppressLint("MissingPermission")
private fun getLocation() {
validatePermissionsLocation()
fusedLocationClient?.requestLocationUpdates(locationRequest, callbabck, null)
}
} | 0 | Kotlin | 0 | 0 | 511b10c4207402c0ddd99efde5e8689f07b07fd0 | 3,636 | CheckinsApp | MIT License |
data/src/main/java/com/example/data/db/AppDatabase.kt | Vishwajith-Shettigar | 800,866,827 | false | {"Kotlin": 203666} | package com.example.data.db
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.data.dao.UserDao
import com.example.data.entity.UserEntity
@Database(entities = [UserEntity::class], version = 1)
abstract class AppDatabase: RoomDatabase() {
abstract fun userDao(): UserDao
} | 30 | Kotlin | 49 | 17 | 553fd3b1fc6a8c3c26a944097326b051fbd8277f | 307 | NextGen | MIT License |
app/src/main/java/io/aethibo/rollback/features/add/AddProductIntent.kt | primepixel | 383,722,476 | false | null | package io.aethibo.rollback.features.add
import io.aethibo.domain.request.AddProductRequest
import io.aethibo.rollback.framework.mvibase.IIntent
sealed class AddProductIntent : IIntent {
object GetCategories : AddProductIntent()
data class AddProduct(val product: AddProductRequest) : AddProductIntent()
}
| 0 | Kotlin | 1 | 1 | f65162bb7ebb53828eb48b42c7a913e10ca66b9e | 316 | Rollback | Apache License 2.0 |
app/src/main/java/com/eveexite/coffeemaker/presentation/base/BaseFragment.kt | ivanph1017 | 126,720,616 | false | null | package com.eveexite.coffeemaker.presentation.base
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.eveexite.coffeemaker.presentation.ViewModelFactory
import dagger.android.support.DaggerFragment
import javax.inject.Inject
import kotlin.reflect.KClass
/**
* Created by Ivan on 29/01/2018.
*/
abstract class BaseFragment<T : ViewModel> : DaggerFragment() {
@Inject lateinit var viewModelFactory: ViewModelFactory
protected lateinit var viewModel: T
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
setHasOptionsMenu(true)
return inflater.inflate(getLayout(), container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(getViewModelClass().java)
}
protected abstract fun getLayout(): Int
protected abstract fun getViewModelClass(): KClass<T>
} | 0 | Kotlin | 0 | 3 | c8fb816df5ef9cd5ee9ec11602717747970c6738 | 1,176 | CoffeeMakerKotlin | MIT License |
app/src/main/java/com/zeynelerdi/fxratesample/MainApplication.kt | ZeynelErdiKarabulut | 314,023,724 | false | null | package com.zeynelerdi.fxratesample
import android.app.Application
import com.zeynelerdi.fxratesample.di.AppComponent
import com.zeynelerdi.fxratesample.di.AppModule
import com.zeynelerdi.fxratesample.di.DaggerAppComponent
import com.zeynelerdi.fxratesample.di.NetworkModule
import com.zeynelerdi.fxratesample.repo.network.NetoworkConfig
interface FxRatesApplication {
fun getAppComponent(): AppComponent
}
class MainApplication : Application(), FxRatesApplication {
override fun getAppComponent(): AppComponent {
return DaggerAppComponent.builder()
.networkModule(NetworkModule(NetoworkConfig.BASE_URL))
.appModule(AppModule())
.build()
}
}
| 0 | Kotlin | 0 | 0 | f8119b4207a41e2dad84b2fc031705b15c69cafd | 701 | CurrencyConverter | Apache License 2.0 |
common/src/test/kotlin/com/github/vatbub/matchmaking/common/serializationtests/SerializationTestSuperclass.kt | vatbub | 162,929,659 | false | null | /*-
* #%L
* matchmaking.common
* %%
* Copyright (C) 2016 - 2019 <NAME>
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.vatbub.matchmaking.common.serializationtests
import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.io.Input
import com.esotericsoftware.kryo.io.Output
import com.esotericsoftware.kryonet.Connection
import com.esotericsoftware.kryonet.Listener
import com.github.vatbub.matchmaking.common.fromJson
import com.github.vatbub.matchmaking.common.initializeMinLogRedirect
import com.github.vatbub.matchmaking.common.registerClasses
import com.github.vatbub.matchmaking.common.testing.kryo.KryoTestClient
import com.github.vatbub.matchmaking.common.testing.kryo.KryoTestServer
import com.github.vatbub.matchmaking.common.toJson
import com.github.vatbub.matchmaking.testutils.KotlinTestSuperclass
import org.awaitility.Awaitility.await
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.file.Path
import java.util.concurrent.TimeUnit
private var lastFileCounter = -1
internal val nextFileCounter: Int
get() {
lastFileCounter++
return lastFileCounter
}
internal val nextObjectFileName: String
get() = "$nextFileCounter.bin"
internal fun nextObjectPath(root: Path) = root.resolve(nextObjectFileName)
abstract class SerializationTestSuperclass<T : Any>(private val clazz: Class<T>) :
KotlinTestSuperclass<T>() {
private var kryoServer: KryoTestServer? = null
private var kryoClient: KryoTestClient? = null
@BeforeAll
fun redirectKryoLogs() {
initializeMinLogRedirect()
}
@AfterEach
fun stopKryo() {
kryoClient?.client?.stop()
kryoServer?.server?.stop()
}
@Test
fun serializationTest() {
val originalObject = newObjectUnderTest()
val json = originalObject.toJson(true)
val deserializedObject: T = fromJson(json, clazz)
Assertions.assertEquals(originalObject, deserializedObject)
}
@Test
fun kryoSerializationTest(@TempDir tempDir: Path) {
val kryo = Kryo()
kryo.registerClasses()
val originalObject = newObjectUnderTest()
val outputFile = nextObjectPath(tempDir).toFile()
Output(FileOutputStream(outputFile)).use {
kryo.writeObject(it, originalObject)
}
Input(FileInputStream(outputFile)).use {
val deserializedObject = kryo.readObject(it, clazz)
Assertions.assertEquals(originalObject, deserializedObject)
}
}
@Test
fun kryoNetSerializationTest() {
val originalObject1 = newObjectUnderTest()
val originalObject2 = newObjectUnderTest()
var listener1Called = false
var listener2Called = false
kryoServer = KryoTestServer(object : Listener {
override fun received(connection: Connection?, receivedObject: Any?) {
listener1Called = true
Assertions.assertEquals(originalObject1, receivedObject)
Assertions.assertEquals(originalObject1.hashCode(), receivedObject.hashCode())
connection?.sendTCP(originalObject2)
}
})
kryoClient = KryoTestClient(kryoTestServer = kryoServer!!, listener = object : Listener {
override fun received(connection: Connection?, receivedObject: Any?) {
listener2Called = true
Assertions.assertEquals(originalObject2, receivedObject)
}
})
kryoClient?.client?.sendTCP(originalObject1)
await().atMost(5, TimeUnit.SECONDS).until { listener1Called }
await().atMost(5, TimeUnit.SECONDS).until { listener2Called }
}
@Test
fun isClassRegisteredInKryo() {
val kryo = Kryo()
kryo.registerClasses()
kryo.isRegistrationRequired = true
Assertions.assertDoesNotThrow { kryo.getRegistration(clazz) }
}
}
| 11 | Kotlin | 5 | 32 | 7ece6b79c6ea15dcf636851a61fde6dc6615188d | 4,650 | matchmaking | Apache License 2.0 |
modular-portal-core/src/main/kotlin/dev/emirman/mp/core/service/stock/StockService.kt | emirhannaneli | 874,732,764 | false | {"Kotlin": 302519} | package dev.emirman.mp.core.service.stock
import dev.emirman.mp.core.dto.stock.create.CStock
import dev.emirman.mp.core.dto.stock.update.UStock
import dev.emirman.mp.core.mapper.stock.StockMapper
import dev.emirman.mp.core.model.stock.Stock
import dev.emirman.mp.core.spec.stock.StockSpec
import net.lubble.util.service.BaseService
import java.math.BigDecimal
interface StockService : BaseService<Stock, CStock, UStock, StockSpec>, StockMapper {
fun moveToBlocked(stock: Stock, amount: BigDecimal)
fun pullFromBlocked(stock: Stock, amount: BigDecimal)
} | 0 | Kotlin | 0 | 1 | b3fe543c02b95033e6cf2d12808968ec225f5259 | 564 | modular-portal | Apache License 2.0 |
src/main/java/net/bloople/allblockvariants/blocks/StainedGlassVerticalSlabBlock.kt | bloopletech | 517,354,828 | false | null | package net.bloople.allblockvariants.blocks
import net.minecraft.block.Stainable
import net.minecraft.util.DyeColor
class StainedGlassVerticalSlabBlock(private val dyeColor: DyeColor, settings: Settings)
: GlassVerticalSlabBlock(settings), Stainable {
override fun getColor(): DyeColor {
return dyeColor
}
} | 0 | Kotlin | 0 | 0 | 946f3176964fef5aa5c5424fa1a686942c34c224 | 330 | allblockvariants | MIT License |
ktfx-layouts/src/ktfx/layouts/scene/control/CheckMenuItem.kt | alilosoft | 182,138,993 | true | {"Kotlin": 364065, "HTML": 1385, "Java": 682} | @file:Suppress("PackageDirectoryMismatch", "NOTHING_TO_INLINE")
package ktfx.layouts
import javafx.scene.Node
import javafx.scene.control.CheckMenuItem
/** Creates a [CheckMenuItem]. */
fun checkMenuItem(
text: String? = null,
graphic: Node? = null,
init: ((@LayoutDslMarker CheckMenuItem).() -> Unit)? = null
): CheckMenuItem = CheckMenuItem(text, graphic).also { init?.invoke(it) }
/** Creates a [CheckMenuItem] and add it to this manager. */
inline fun MenuItemManager.checkMenuItem(
text: String? = null,
graphic: Node? = null,
noinline init: ((@LayoutDslMarker CheckMenuItem).() -> Unit)? = null
): CheckMenuItem = ktfx.layouts.checkMenuItem(text, graphic, init).add() | 0 | Kotlin | 0 | 0 | f499c9d7abddb270f1946c0e9ffb9072e45cd625 | 701 | ktfx | Apache License 2.0 |
app/src/main/java/com/example/mymovies/viewmodels/BaseViewModel.kt | PRADEEPERIYASAMY | 324,136,994 | false | null | package com.example.mymovies.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
abstract class BaseViewModel<Action> : ViewModel(), CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Job() + Dispatchers.IO
protected val mutableError = MutableLiveData<String>()
val error: LiveData<String>
get() = mutableError
protected val mutableSuccess = MutableLiveData<String>()
val success: LiveData<String>
get() = mutableSuccess
protected val mutableLoading = MutableLiveData<Boolean>()
val isLoading: LiveData<Boolean> get() = mutableLoading
abstract fun doAction(action: Action): Any
fun setSuccess(string: String) {
mutableSuccess.value = string
}
fun setError(string: String) {
mutableError.value = string
}
}
| 0 | Kotlin | 0 | 0 | 48a603b0e53c2c5c6781f77c27c9fe58e01e0f5d | 1,048 | MyMovies | MIT License |
http-api/src/test/kotlin/org/rmleme/starwarsapi/httpapi/controller/PostPlanetControllerTest.kt | rmleme | 607,449,661 | false | null | package org.rmleme.starwarsapi.httpapi.controller
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.shouldBe
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.server.testing.testApplication
import io.mockk.called
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import io.mockk.verify
import org.rmleme.starwarsapi.entities.CORUSCANT
import org.rmleme.starwarsapi.httpapi.controller.dto.request.PlanetRequest
import org.rmleme.starwarsapi.httpapi.extension.asJson
import org.rmleme.starwarsapi.httpapi.extension.defaultTestApplication
import org.rmleme.starwarsapi.usecases.service.PlanetService
import org.springframework.core.io.ClassPathResource
import java.util.Optional
class PostPlanetControllerTest : ShouldSpec({
isolationMode = IsolationMode.InstancePerTest
val service = mockk<PlanetService>()
should("return HTTP 400 when id is null") {
testApplication {
val client = defaultTestApplication(PLANETS_PATH) { postPlanet(service) }
client.post(PLANETS_PATH) {
contentType(ContentType.Application.Json)
setBody(
"""
{
"id": null
}
""".trimIndent()
)
}.apply {
status shouldBe HttpStatusCode.BadRequest
}
verify { service wasNot called }
}
}
should("save a planet and return HTTP 201") {
testApplication {
val client = defaultTestApplication(PLANETS_PATH) { postPlanet(service) }
val planet = CORUSCANT
val expected = ClassPathResource("/single-planet-response.json").file.readText()
coEvery { service.loadPlanetFromApi(9) } returns Optional.of(planet)
client.post(PLANETS_PATH) {
contentType(ContentType.Application.Json)
setBody(PlanetRequest(id = 9))
}.apply {
status shouldBe HttpStatusCode.Created
bodyAsText().asJson() shouldBe expected.asJson()
}
coVerify(exactly = 1) { service.loadPlanetFromApi(9) }
}
}
should("return HTTP 422 when planet does not exist in swapi") {
testApplication {
val client = defaultTestApplication(PLANETS_PATH) { postPlanet(service) }
coEvery { service.loadPlanetFromApi(9) } returns Optional.empty()
client.post(PLANETS_PATH) {
contentType(ContentType.Application.Json)
setBody(PlanetRequest(id = 9))
}.apply {
status shouldBe HttpStatusCode.UnprocessableEntity
}
coVerify(exactly = 1) { service.loadPlanetFromApi(9) }
}
}
})
| 0 | Kotlin | 0 | 0 | f69c8da1777e9fca8434b0f1df98d82e55dda14f | 3,032 | star-wars-api | Apache License 2.0 |
demo/plot/src/jvmBatikMain/kotlin/demo/plot/batik/plotConfig/ScaleLimitsContinuousBatik.kt | JetBrains | 176,771,727 | false | {"Kotlin": 7616680, "Python": 1299756, "Shell": 3453, "C": 3039, "JavaScript": 931, "Dockerfile": 94} | /*
* Copyright (c) 2020. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package demo.plot.batik.plotConfig
import demo.plot.common.model.plotConfig.ScaleLimitsContinuous
import demo.common.batik.demoUtils.PlotSpecsDemoWindowBatik
import java.awt.Dimension
fun main() {
with(ScaleLimitsContinuous()) {
PlotSpecsDemoWindowBatik(
"Scale limits (continuous)",
plotSpecList(),
2,
Dimension(500, 200)
).open()
}
} | 150 | Kotlin | 51 | 1,561 | c8db300544974ddd35a82a90072772b788600ac6 | 554 | lets-plot | MIT License |
app/src/main/java/com/rubikkube/composemovie/data/remote/DataSource.kt | Rubikkube | 403,575,668 | false | null | package com.rubikkube.composemovie.data.remote
data class DataSource<out T>(val status: Status, val data: T?, val message: String?) {
companion object {
fun <T> empty(): DataSource<T> {
return DataSource(Status.EMPTY, null, null)
}
fun <T> success(data: T?): DataSource<T> {
return DataSource(Status.SUCCESS, data, null)
}
fun <T> error(msg: String, data: T?): DataSource<T> {
return DataSource(Status.ERROR, data, msg)
}
fun <T> loading(data: T?): DataSource<T> {
return DataSource(Status.LOADING, data, null)
}
}
} | 0 | null | 2 | 16 | 3a034735f6f3717525cd6116f1fd4bc69a6cda64 | 642 | compose-movie | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.