path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/schibsted/elephant/android/ui/challenge/ChallengeFragment.kt | ElephantTeam | 267,237,784 | false | null | package com.schibsted.elephant.android.ui.challenge
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.navArgs
import com.schibsted.elephant.android.databinding.FragmentChallengeBinding
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.koin.androidx.viewmodel.ext.android.viewModel
class ChallengeFragment : Fragment() {
lateinit var binding: FragmentChallengeBinding
private val args: ChallengeFragmentArgs by navArgs()
private val challengeViewModel: ChallengeViewModel by viewModel()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentChallengeBinding.inflate(inflater)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
challengeViewModel.viewState
.onEach { render(it) }
.launchIn(viewLifecycleOwner.lifecycleScope)
challengeViewModel.requestChallenge(args.challengeId)
}
private fun render(state: ChallengeFragmentViewState) {
when(state) {
ChallengeFragmentViewState.Loading -> {
binding.progress.isVisible = true
binding.successGroup.isVisible = false
}
ChallengeFragmentViewState.Success -> {
binding.progress.isVisible = false
binding.successGroup.isVisible = true
}
ChallengeFragmentViewState.Error -> {
}
}
}
} | 5 | Kotlin | 0 | 0 | 628e195fb785efeef3471cec73b20bd88b9df6c5 | 1,828 | backend-android | Apache License 2.0 |
app/src/main/java/com/taqucinco/pokemon_sample/feature/database/DatabaseFactory.kt | taqucinco-com | 735,229,218 | false | {"Kotlin": 113444} | package com.taqucinco.pokemon_sample.feature.database
interface DatabaseFactory {
/**
* データベースを生成する
*
* @return データベース
*/
fun build(): AppDatabase
}
| 6 | Kotlin | 0 | 1 | c8e1ac968c331b832312ed36292855a097d54014 | 178 | pokemon_sample | Apache License 2.0 |
app/src/main/java/com/shevelev/wizard_camera/gallery_activity/di/GalleryActivityModuleChilds.kt | AndroidSourceTools | 339,484,028 | true | {"Kotlin": 259308, "GLSL": 32096, "Java": 3377} | package com.shevelev.wizard_camera.gallery_activity.di
import com.shevelev.wizard_camera.gallery_page.di.GalleryPageFragmentComponent
import dagger.Module
@Module(subcomponents = [
GalleryPageFragmentComponent::class
])
class GalleryActivityModuleChilds | 0 | null | 0 | 0 | 496cbc68749258d085734c6d0a724efa7a3b3d24 | 259 | WizardCamera | Apache License 2.0 |
custom-change-core/src/main/kotlin/momosetkn/liquibase/kotlin/change/custom/core/ChangeSetDslExtensions.kt | momosetkn | 844,062,460 | false | {"Kotlin": 499731, "Java": 178} | package momosetkn.liquibase.kotlin.change.custom.core
import liquibase.change.custom.CustomChange
import liquibase.change.custom.CustomChangeWrapper
import liquibase.change.custom.setCustomChange
import momosetkn.liquibase.kotlin.dsl.ChangeSetDsl
fun ChangeSetDsl.addCustomChange(change: CustomChange) {
val customChangeWrapper = this.changeSetSupport.createChange("customChange") as CustomChangeWrapper
customChangeWrapper.setCustomChange(change)
changeSetSupport.addChange(customChangeWrapper)
}
| 5 | Kotlin | 1 | 5 | d47b2dd7f585f3aa563e86ab52242e0b5d2ffaad | 512 | liquibase-kotlin | Apache License 2.0 |
src/main/kotlin/org/skellig/plugin/language/teststep/psi/SkelligTestStepParserDefinition.kt | skellig-framework | 309,154,374 | false | {"Kotlin": 219539, "Lex": 2218} | package org.skellig.plugin.language.teststep.psi
import com.intellij.lang.ASTNode
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import org.skellig.plugin.language.teststep.SkelligTestStepLexerAdapter
import org.skellig.plugin.language.teststep.SkelligTestStepParser
class SkelligTestStepParserDefinition : ParserDefinition {
private val file = IFileElementType(SkelligTestStepLanguage.INSTANCE)
override fun createLexer(project: Project?): Lexer {
return SkelligTestStepLexerAdapter()
}
override fun getCommentTokens(): TokenSet {
return COMMENTS
}
override fun getStringLiteralElements(): TokenSet {
return TokenSet.EMPTY
}
override fun createParser(project: Project?): PsiParser {
return SkelligTestStepParser()
}
override fun getFileNodeType(): IFileElementType {
return file
}
override fun createFile(viewProvider: FileViewProvider): PsiFile {
return SkelligTestStepFile(viewProvider)
}
override fun createElement(node: ASTNode?): PsiElement {
return SkelligTestStepTypes.Factory.createElement(node)
}
override fun spaceExistenceTypeBetweenTokens(left: ASTNode, right: ASTNode): ParserDefinition.SpaceRequirements {
// Line break between line comment and other elements
val leftElementType: IElementType = left.elementType
if (leftElementType === SkelligTestStepTypes.COMMENT) {
return ParserDefinition.SpaceRequirements.MUST_LINE_BREAK
}
return if (right.elementType === SkelligTestStepTypes.VALUE_ASSIGN) {
ParserDefinition.SpaceRequirements.MUST_LINE_BREAK
} else ParserDefinition.SpaceRequirements.MAY
}
}
private val WHITESPACE: TokenSet = TokenSet.create(TokenType.WHITE_SPACE)
private val COMMENTS: TokenSet = TokenSet.create(SkelligTestStepTypes.COMMENT) | 0 | Kotlin | 0 | 1 | 1f99c61d6c5deb44d684e98a413d9f991b9b2da7 | 2,250 | skellig-intellij-plugin | Apache License 2.0 |
libs/lib_security/src/main/java/com/bael/kirin/lib/security/constant/SchemeConstant.kt | ErickSumargo | 282,614,741 | false | null | package com.bael.kirin.lib.security.constant
/**
* Created by ErickSumargo on 01/06/20.
*/
const val SCHEME_AES: String = "AES"
| 0 | Kotlin | 4 | 20 | 2b3703036ce17d3e46c81bdf66986d83b4ac2517 | 132 | Kirin | MIT License |
tunneler/src/main/kotlin/com/salesforce/pomerium/CredentialStore.kt | salesforce | 653,799,146 | false | {"Kotlin": 60574} | package com.salesforce.pomerium
typealias CredentialKey = String
interface CredentialStore {
fun getToken(key: CredentialKey): String?
fun setToken(key: CredentialKey, jwt: String)
fun clearToken(key: CredentialKey)
} | 0 | Kotlin | 2 | 9 | 6efc8b1aa762c651d9a2912eb8507c0efe3d2969 | 231 | secure-pomerium-tunneler | Apache License 2.0 |
module_views/src/main/java/com/silencefly96/module_views/custom/LeftDeleteItemLayout.kt | silencefly96 | 383,359,654 | false | {"Kotlin": 661457, "Java": 143190, "Groovy": 7800} | @file:Suppress("unused")
package com.silencefly96.module_views.custom
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.Scroller
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import kotlin.math.abs
/**
* 左划删除控件
* 能在控件实现左滑吗?如何传入自定义的布局?
* 思路:
* 1、一个容器,左右两部分,左边外部导入,右边删除框 x 增加层级
* 2、在 View 右边追加一个删除款 x 需要在 View 内拦截事件
* 3、在 ConstraintLayout 内部添加一个删除框,左边对其 parent 右边
*
* @author silence
* @date 2022-09-27
*/
class LeftDeleteItemLayout : ConstraintLayout {
private val mDeleteView: View?
var mDeleteClickListener: OnClickListener? = null
set(value) {
field = value
mDeleteView?.setOnClickListener(value)
}
//流畅滑动
private var mScroller = Scroller(context)
//上次事件的横坐标
private var mLastX = -1f
private var mLastY = 0f
// 滑动模式,左滑模式(-1),初始化(0),上下模式(1)
private var mScrollMode = 0
//控制控件结束的runnable
// private val stopMoveRunnable: Runnable = Runnable { stopMove() }
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
super(context, attrs, defStyleAttr)
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) :
super(context, attrs, defStyleAttr, defStyleRes)
init {
//kotlin的初始化函数
mDeleteView = makeDeleteView(context)
addView(mDeleteView)
}
//创建删除框,设置好位置对齐自身最右边
private fun makeDeleteView(context: Context): View {
val deleteView = TextView(context)
//给当前控件一个id,用于删除控件约束
this.id = generateViewId()
//设置布局参数
deleteView.layoutParams = LayoutParams(
dp2px(context, 100f), 0
).apply {
//设置约束条件
leftToRight = id
topToTop = id
bottomToBottom = id
}
//设置其他参数
deleteView.text = "删除"
deleteView.gravity = Gravity.CENTER
deleteView.setTextColor(Color.WHITE)
deleteView.textSize = sp2px(context,13f).toFloat()
deleteView.setBackgroundColor(Color.RED)
//设置点击回调
deleteView.setOnClickListener(mDeleteClickListener)
return deleteView
}
//拦截事件
override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
when(event.action) {
//down事件记录x,不拦截,当move的时候才会用到
MotionEvent.ACTION_DOWN -> {
mLastX = event.x
// 对滑动冲突处理
mLastY = event.y
mScrollMode = 0
}
//拦截本控件内的移动事件
// 不能拦截,拦截会导致子控件onClick无法生效,onClick需要在ACTION_UP时触发
// MotionEvent.ACTION_MOVE -> return true
}
return super.onInterceptTouchEvent(event)
}
//处理事件
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when(event.action) {
MotionEvent.ACTION_DOWN -> {
// 防止滑出view范围收不到ACTION_MOVE事件
parent.requestDisallowInterceptTouchEvent(true)
return true
}
MotionEvent.ACTION_MOVE -> {
if (mScrollMode == 0) {
val deltaX = abs(event.x - mLastX)
val deltaY = abs(event.y - mLastY)
// 异常情况忽略了
if (deltaX == deltaY && deltaX == 0f) return super.onTouchEvent(event)
// 判断模式,进入左滑状态(-1),上下滑动(1)
mScrollMode = if (deltaX > deltaY) -1 else 1
}
// 左滑模式下交给当前控件处理
if (mScrollMode < 0) {
moveItem(event)
return true
}else {
// 这里不处理滑动事件,交个父控件(即RecyclerView)去处理
parent.requestDisallowInterceptTouchEvent(false)
return false
}
}
MotionEvent.ACTION_UP -> stopMove()
}
return super.onTouchEvent(event)
}
private fun moveItem(e: MotionEvent) {
Log.e("TAG", "moveItem: mLastX=$mLastX")
//如果没有收到down事件,不应该移动
if (mLastX == -1f) return
val dx = mLastX - e.x
//更新点击的横坐标
mLastX = e.x
//检查mItem移动后应该在[-deleteLength, 0]内
val deleteWidth = mDeleteView!!.width
if ((scrollX + dx) <= deleteWidth && (scrollX + dx) >= 0) {
//触发移动
scrollBy(dx.toInt(), 0)
}
// 菜的扣脚,ACTION_DOWN会接管整个事件序列,需要配合requestDisallowInterceptTouchEvent
//如果一段时间没有移动时间,mLastX还没被stopMove重置为-1,那就是移动到其他地方了
//设置200毫秒没有新事件就触发stopMove
// removeCallbacks(stopMoveRunnable)
// postDelayed(stopMoveRunnable, 200)
}
private fun stopMove() {
//如果移动过半了,应该判定左滑成功
val deleteWidth = mDeleteView!!.width
if (abs(scrollX) >= deleteWidth / 2f) {
//触发移动至完全展开
mScroller.startScroll(scrollX, 0, deleteWidth - scrollX, 0)
}else {
//如果移动没过半应该恢复状态,则恢复到原来状态
mScroller.startScroll(scrollX, 0, - scrollX, 0)
}
invalidate()
//清除状态
mLastX = -1f
}
//流畅地滑动
override fun computeScroll() {
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.currX, mScroller.currY)
postInvalidate()
}
}
//单位转换
@Suppress("SameParameterValue")
private fun dp2px(context: Context, dpVal: Float): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dpVal, context.resources
.displayMetrics
).toInt()
}
@Suppress("SameParameterValue")
private fun sp2px(context: Context, spVal: Float): Int {
val fontScale = context.resources.displayMetrics.scaledDensity
return (spVal * fontScale + 0.5f).toInt()
}
} | 0 | Kotlin | 2 | 7 | 716c03159ae773fe4a545642899573378c1651a9 | 6,294 | fundark | Apache License 2.0 |
src/test/kotlin/ParserTest.kt | booleworks | 497,876,711 | false | null | import com.booleworks.packagesolver.io.parse
import org.assertj.core.api.Assertions.assertThat
import kotlin.test.Test
internal class ParserTest {
@Test
fun testParser() {
val problem = parse("src/test/resources/small-test.cudf")
assertThat(problem.allPackages()).hasSize(9)
assertThat(problem.allPackageNames()).hasSize(6)
assertThat(problem.request.install).hasSize(1)
assertThat(problem.request.remove).isEmpty()
}
}
| 0 | Kotlin | 0 | 0 | e99b2e19599720866a0172b5c30047d37862343c | 475 | package-solving-poc | MIT License |
src/main/kotlin/org/hiatusuk/obsidian/web/utils/EncodeUtils.kt | poblish | 612,371,934 | false | null | package org.hiatusuk.obsidian.web.utils
import org.hiatusuk.obsidian.utils.StringUtils.replace
object EncodeUtils {
fun fixQueryEncoding(inUrl: String): String {
val qIdx = inUrl.indexOf('?')
if (qIdx < 0) {
return inUrl
}
val qStr = replace(replace(inUrl.substring(qIdx + 1), "+", "%20"), "\"", "%22")
return inUrl.substring(0, qIdx + 1) + qStr
}
}
| 0 | Kotlin | 0 | 0 | 67a62560c865de0fd751365b091bfb60b5f12f34 | 414 | obsidian | Apache License 2.0 |
pbtx-android-module/src/androidTest/java/com/pbtx/PbtxClientTest.kt | fixpayments | 454,709,009 | false | null | package com.pbtx
import android.util.Log
import androidx.test.runner.AndroidJUnit4
import com.pbtx.utils.PbtxUtils
import org.junit.*
import org.junit.rules.ExpectedException
import org.junit.runner.RunWith
import java.util.*
/**
* Test class for [ekisAndroidKeyStoreSignatureProvider]
*/
@RunWith(AndroidJUnit4::class)
class PbtxClientTest {
@Rule
@JvmField
val exceptionRule: ExpectedException = ExpectedException.none()
@Test
fun createAndDeleteKey() {
val initialKeyListSize = PbtxClient.listKeys().size
// Creating a new key
val keyName = randomKeyName()
val key = PbtxClient.createKey(keyName)
Log.d("EKisTest", "Key :: ${PbtxUtils.bytesToHexString(key)}")
Assert.assertNotNull(key)
// Check if the key present in the size
assert(PbtxClient.listKeys().size == initialKeyListSize + 1)
// Deleting key
PbtxClient.deleteKey(keyName)
// Check the store size after deleting the key
assert(PbtxClient.listKeys().size == initialKeyListSize)
}
@Test
fun listKeysTest() {
val initialKeyListSize = PbtxClient.listKeys().size
// Creating keys
val keyName1 = randomKeyName()
val keyName2 = randomKeyName()
PbtxClient.createKey(keyName1)
PbtxClient.createKey(keyName2)
// List of the keys present in the stores
val keyList = PbtxClient.listKeys()
keyList.forEach {
val publicKeyBytes = it.publicKey.keyBytes.toByteArray()
Log.d("EKisTest", "Key :: ${PbtxUtils.bytesToHexString(publicKeyBytes)}")
}
assert(keyList.size == initialKeyListSize + 2)
// Cleanup
PbtxClient.deleteKey(keyName1)
PbtxClient.deleteKey(keyName2)
assert(PbtxClient.listKeys().size == initialKeyListSize)
}
@Test
fun signDataTest() {
// Creating key
val keyName = randomKeyName()
PbtxClient.createKey(keyName)
// Signing data
val data = "0102030405060708090a0b0c0d0e0f"
val signature: ByteArray = PbtxClient.signData(
PbtxUtils.decodeHex(data),
keyName
)
Log.d("EKisTest", "Signature ${PbtxUtils.bytesToHexString(signature)}")
Assert.assertNotNull(signature)
// Cleanup
PbtxClient.deleteKey(keyName)
}
private fun randomKeyName(): String {
return "random" + UUID.randomUUID().toString()
}
} | 0 | Kotlin | 5 | 0 | f80a9fc19e539076197130c3d14143e0ae205ea5 | 2,490 | pbtx_android | Apache License 2.0 |
src/main/java/net/bloople/allblockvariants/Creator.kt | bloopletech | 517,354,828 | false | {"Kotlin": 949167, "Java": 2067} | package net.bloople.allblockvariants
import net.fabricmc.api.EnvType
import net.fabricmc.api.Environment
interface Creator {
fun createCommon()
@Environment(value= EnvType.CLIENT)
fun createClient(builder: ResourcePackBuilder)
fun createServer(builder: ResourcePackBuilder)
fun getBlockInfo(): BlockInfo?
} | 0 | Kotlin | 0 | 0 | 1e424795b6bc6a85d7a7c246cf36579d6f389fea | 328 | allblockvariants | MIT License |
FilmSearch/app/src/main/java/com/example/filmsearch/view/fragments/SelectionsFragment.kt | skripkalisa | 442,273,516 | false | null | package com.example.filmsearch.view.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.filmsearch.databinding.FragmentSelectionsBinding
import com.example.filmsearch.utils.AnimationHelper
class SelectionsFragment : Fragment() {
private lateinit var binding: FragmentSelectionsBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentSelectionsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
AnimationHelper.performFragmentCircularRevealAnimation(
binding.selectionsFragmentRoot,
requireActivity(),
4
)
}
} | 0 | Kotlin | 0 | 0 | 1ce519b6d07a0c5ab37f10f5fe3b9cddf03ac964 | 1,023 | SF_Android_proc | Apache License 2.0 |
src/test/kotlin/university/com/api/CartApiTest.kt | ShockJake | 840,829,722 | false | {"Kotlin": 129824, "Python": 4936, "Dockerfile": 1229, "Shell": 1129, "HTML": 122} | package university.com.api
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.put
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.testApplication
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.TestInstance
import university.com.api.ApiTestCommons.authenticateUser
import university.com.api.ApiTestCommons.setMockEngine
import university.com.data.model.Book
import university.com.plugins.configureRouting
import university.com.plugins.configureSecurity
import university.com.plugins.configureSerialization
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class CartApiTest {
private val objectMapper = jacksonObjectMapper()
private var token = ""
private val book = Book("TITLE", "AUTHOR", "DATE", "ID")
@BeforeAll
fun beforeAll() = testApplication {
setMockEngine()
application { configureSecurity(); configureRouting(); configureSerialization() }
token = authenticateUser(client)
}
@AfterAll
fun afterAll() {
ApiTestCommons.cleanup()
}
@BeforeTest
fun setUp() {
cleanCart()
}
@Test
fun shouldUpdateCart() = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
val expectedResult = listOf(book)
// when & then
addBookToCart(book)
getCartContents(expectedResult)
}
@Test
fun shouldRespondWithBadRequestIfEmptyDataProvided() = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
// when
val response = client.put("/cart") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
setBody("")
}
// then
assertEquals(HttpStatusCode.BadRequest, response.status)
}
@Test
fun shouldRespondWithBadRequestIfInvalidActionProvided() = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
// when
val response = client.put("/cart") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
setBody("""{"action": "TEST_ACTION"}""")
}
// then
assertEquals(HttpStatusCode.BadRequest, response.status)
}
@Test
fun shouldRespondWithBadRequestIfIncompleteDataProvided() = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
// when
val response = client.put("/cart") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
setBody("""{"action": "add"}""")
}
// then
assertEquals(HttpStatusCode.BadRequest, response.status)
}
@Test
fun shouldRespondWithBadRequestIfProvidedBookDataIsIncomplete() = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
// when
val response = client.put("/cart") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
setBody("""{"action": "add", "book": {}}""")
}
// then
assertEquals(HttpStatusCode.BadRequest, response.status)
}
@Test
fun shouldAddAndRemoveTheBookFromCart() = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
val removeRequestBody = """{ "action": "remove", "book": ${objectMapper.writeValueAsString(book)} }"""
val expectedResult = listOf<Book>()
// when
addBookToCart(book)
val removeResponse = client.put("/cart") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
setBody(removeRequestBody)
}
val getResponse = client.get("/cart") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
}
// then
assertEquals(HttpStatusCode.OK, getResponse.status)
assertEquals(HttpStatusCode.OK, removeResponse.status)
val responseBody = getResponse.bodyAsText()
assertNotNull(responseBody)
val actualResult = objectMapper.readValue<List<Book>>(responseBody)
assertEquals(expectedResult, actualResult)
}
@Test
fun shouldRespondWithBadRequestIfThereAreNoBooksToRemove() = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
val removeRequestBody = """{ "action": "remove", "book": ${objectMapper.writeValueAsString(book)} }"""
// when
val removeResponse = client.put("/cart") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
setBody(removeRequestBody)
}
// then
assertEquals(HttpStatusCode.BadRequest, removeResponse.status)
}
@Test
fun shouldCheckoutCart() = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
// when
addBookToCart(book)
val checkoutResponse = client.get("/cart/checkout") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
header(HttpHeaders.Accept, ContentType.Application.Json)
}
// then
assertEquals(HttpStatusCode.OK, checkoutResponse.status)
}
@Test
fun shouldRespondWithBadRequestIfNoBooksAreInCart() = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
// when
val checkoutResponse = client.get("/cart/checkout") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
header(HttpHeaders.Accept, ContentType.Application.Json)
}
// then
assertEquals(HttpStatusCode.BadRequest, checkoutResponse.status)
}
private fun cleanCart() = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
// when
val cleanResponse = client.delete("/cart") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
header(HttpHeaders.Accept, ContentType.Application.Json)
}
// then
assertEquals(HttpStatusCode.OK, cleanResponse.status)
}
private fun addBookToCart(book: Book) = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
val addRequestBody = """{ "action": "add", "book": ${objectMapper.writeValueAsString(book)} }"""
// when
val addResponse = client.put("/cart") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
setBody(addRequestBody)
}
// then
assertEquals(HttpStatusCode.OK, addResponse.status)
}
private fun getCartContents(expectedResult: List<Book>) = testApplication {
// given
application { configureSecurity(); configureRouting(); configureSerialization() }
// when
val getResponse = client.get("/cart") {
header(HttpHeaders.Accept, ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
header(HttpHeaders.Accept, ContentType.Application.Json)
}
// then
assertEquals(HttpStatusCode.OK, getResponse.status)
val responseBody = getResponse.bodyAsText()
assertNotNull(responseBody)
val actualResult = objectMapper.readValue<List<Book>>(responseBody)
assertEquals(expectedResult, actualResult)
}
}
| 0 | Kotlin | 0 | 0 | 92ca312ba364242aa8301e023bed99b3ff589cf7 | 9,477 | kotlin-library-backend | Apache License 2.0 |
elasticsearch/src/main/kotlin/io/qalipsis/plugins/elasticsearch/mget/ElasticsearchMultiGetStepSpecificationConverter.kt | qalipsis | 428,400,562 | false | null | /*
* Copyright 2022 AERIS IT Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.qalipsis.plugins.elasticsearch.mget
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode
import io.qalipsis.api.Executors
import io.qalipsis.api.annotations.StepConverter
import io.qalipsis.api.context.StepContext
import io.qalipsis.api.events.EventsLogger
import io.qalipsis.api.meters.CampaignMeterRegistry
import io.qalipsis.api.steps.StepSpecification
import io.qalipsis.api.steps.StepSpecificationConverter
import io.qalipsis.plugins.elasticsearch.AbstractElasticsearchQueryStepSpecificationConverter
import io.qalipsis.plugins.elasticsearch.query.ElasticsearchDocumentsQueryStep
import jakarta.inject.Named
import kotlin.coroutines.CoroutineContext
/**
* [StepSpecificationConverter] from [ElasticsearchMultiGetStepSpecification] to [ElasticsearchDocumentsQueryStep]
* to use the Multi Get API.
*
* @author Eric Jessé
*/
@StepConverter
internal class ElasticsearchMultiGetStepSpecificationConverter(
@Named(Executors.IO_EXECUTOR_NAME) ioCoroutineContext: CoroutineContext,
meterRegistry: CampaignMeterRegistry,
eventsLogger: EventsLogger
) : AbstractElasticsearchQueryStepSpecificationConverter<ElasticsearchMultiGetStepSpecificationImpl<*>>(
ioCoroutineContext,
meterRegistry,
eventsLogger
) {
override val endpoint = "_mget"
override val metricsQualifier = "mget"
override fun support(stepSpecification: StepSpecification<*, *, *>): Boolean {
return stepSpecification is ElasticsearchMultiGetStepSpecificationImpl
}
override fun buildQueryFactory(
spec: ElasticsearchMultiGetStepSpecificationImpl<*>,
jsonMapper: JsonMapper
): suspend (ctx: StepContext<*, *>, input: Any?) -> ObjectNode {
@Suppress("UNCHECKED_CAST")
val queryObjectBuilder =
spec.queryFactory as suspend MultiGetQueryBuilder.(ctx: StepContext<*, *>, input: Any?) -> Unit
return { context, input ->
jsonMapper.createObjectNode().also { rootNode ->
MultiGetQueryBuilderImpl().also { builder ->
builder.queryObjectBuilder(context, input)
}.toJson(rootNode)
}
}
}
@Suppress("UNCHECKED_CAST")
override fun buildDocumentsExtractor(
spec: ElasticsearchMultiGetStepSpecificationImpl<*>
): (JsonNode) -> List<ObjectNode> {
return if (spec.convertFullDocument) {
{ (it.get("docs") as ArrayNode?)?.toList() as List<ObjectNode>? ?: emptyList() }
} else {
{
(it.get("docs") as ArrayNode?)?.toList()?.filter { it.get("found").booleanValue() } as List<ObjectNode>?
?: emptyList()
}
}
}
}
| 0 | Kotlin | 0 | 0 | 652e09729f6e8703f319ec30196a6ecac14b41d6 | 3,449 | qalipsis-plugin-elasticsearch | Apache License 2.0 |
app/src/main/java/com/infusionsofgrandeur/lootraider/GameObjects/Platform.kt | ecrichlow | 448,751,860 | false | null | package com.infusionsofgrandeur.lootraider.GameObjects
import java.util.Date
import kotlin.math.abs
import kotlin.experimental.and
import android.widget.ImageView
import com.infusionsofgrandeur.lootraider.Managers.ConfigurationManager
import com.infusionsofgrandeur.lootraider.Managers.SpriteManager
import com.infusionsofgrandeur.lootraider.Managers.GameboardManager
import com.infusionsofgrandeur.lootraider.Managers.GameStateManager
class Platform(xPos: Int, yPos: Int, xTile: Int, yTile: Int, status: Motion, animationFrame: Int, var axis: TravelAxis, var speed: PlatformSpeed, var wait: PlatformWait) : Entity(xPos, yPos, xTile, yTile, status, animationFrame)
{
companion object
{
var startFrame: Int = -1
var endFrame: Int = -1
}
enum class TravelAxis
{
Horizontal,
Vertical
}
enum class PlatformSpeed
{
Slow,
Moderate,
Fast
}
enum class PlatformWait
{
Short,
Moderate,
Long
}
var timeDocked: Date?
var speedMultiplier = 0
var waitMultiplier = 0.0
var inLandingAndTakeoffZone = false
var takeoffDirection: Motion
init
{
timeDocked = Date()
takeoffDirection = status
speedMultiplier = when (speed)
{
PlatformSpeed.Slow -> ConfigurationManager.platformSpeedSlowMultiplier
PlatformSpeed.Moderate -> ConfigurationManager.platformSpeedModerateMultiplier
PlatformSpeed.Fast -> ConfigurationManager.platformSpeedFastMultiplier
}
waitMultiplier = when (wait)
{
PlatformWait.Short -> ConfigurationManager.platformWaitShortMultiplier
PlatformWait.Moderate -> ConfigurationManager.platformWaitModerateMultiplier
PlatformWait.Long -> ConfigurationManager.platformWaitLongMultiplier
}
}
fun runCycle(imageView: ImageView)
{
val currentLevel = GameboardManager.getGameboard(GameStateManager.getCurrentLevel() - 1)
val surroundingAttributes = getSurroundingAttributes()
val surroundingTiles = getSurroundingTiles()
val currentTileAttribute = if (currentLevel.attributeMap[yTile][xTile].size > 0) currentLevel.attributeMap[yTile][xTile][0] else 0
val xOffset = xPos - (xTile * GameStateManager.getTileWidth())
val yOffset = yPos - (yTile * GameStateManager.getTileHeight())
val isLeftBlocked = StasisField.isPositionBlocked(xTile - 1, yTile)
val isRightBlocked = StasisField.isPositionBlocked(xTile + 1, yTile)
val isDownBlocked = StasisField.isPositionBlocked(xTile, yTile + 1)
val deviceMultiplier = 1
if (timeDocked != null)
{
if ((Date().time - timeDocked!!.time) >= ConfigurationManager.platformDefaultWaitTime * 1000 * waitMultiplier)
{
val guards = GameStateManager.getGuards()
val player = GameStateManager.getPlayer()
timeDocked = null
status = takeoffDirection
takeoffDirection = Motion.Still
val playerPlatform = player.platformRiding.let()
{
if (it === this)
{
if (player.xPos != xPos)
{
player.xPos = xPos
}
}
}
for (nextGuard in guards)
{
val guardPlatform = nextGuard.platformRiding.let()
{
if (it === this)
{
if (nextGuard.xPos != xPos)
{
nextGuard.xPos = xPos
}
}
}
}
}
else
{
return
}
}
when (status)
{
Motion.PlatformLeft ->
{
if (xOffset == 0 && (!isPlatformTraversable(surroundingTiles.left, surroundingAttributes.left) || isLeftBlocked))
{
status = Motion.Still
takeoffDirection = Motion.PlatformRight
timeDocked = Date()
}
else if (xPos - ConfigurationManager.platformXAxisSteps * deviceMultiplier * speedMultiplier < xTile * GameStateManager.getTileWidth() && (!isPlatformTraversable(surroundingTiles.left, surroundingAttributes.left) || isLeftBlocked))
{
xPos = xTile * GameStateManager.getTileWidth()
status = Motion.Still
takeoffDirection = Motion.PlatformRight
timeDocked = Date()
}
else
{
xPos -= ConfigurationManager.platformXAxisSteps * deviceMultiplier * speedMultiplier
}
// Determine new tile position
if ((xTile > 0 && xPos <= ((xTile - 1) * GameStateManager.getTileWidth() + GameStateManager.getTileWidth() / 2)))
{
xTile -= 1
}
}
Motion.PlatformRight ->
{
if (xOffset == 0 && (!isPlatformTraversable(surroundingTiles.right, surroundingAttributes.right) || isRightBlocked))
{
status = Motion.Still
takeoffDirection = Motion.PlatformLeft
timeDocked = Date()
}
else if (xPos + ConfigurationManager.platformXAxisSteps * deviceMultiplier * speedMultiplier > xTile * GameStateManager.getTileWidth() && (!isPlatformTraversable(surroundingTiles.right, surroundingAttributes.right) || isRightBlocked))
{
xPos = xTile * GameStateManager.getTileWidth()
status = Motion.Still
takeoffDirection = Motion.PlatformLeft
timeDocked = Date()
}
else
{
xPos += ConfigurationManager.platformXAxisSteps * deviceMultiplier * speedMultiplier
}
// Determine new tile position
if (xTile < currentLevel.width - 1 && xPos >= (xTile * GameStateManager.getTileWidth() + GameStateManager.getTileWidth() / 2))
{
xTile += 1
}
}
Motion.PlatformUp ->
{
if (inLandingAndTakeoffZone && animationFrame == Platform.endFrame)
{
animationFrame -= ConfigurationManager.platformYAxisSteps * speedMultiplier
val image = SpriteManager.bitmapForSpriteNumber(animationFrame)
imageView.setImageBitmap(image)
}
else if (inLandingAndTakeoffZone && animationFrame > Platform.startFrame)
{
animationFrame -= ConfigurationManager.platformYAxisSteps * speedMultiplier
if (animationFrame < Platform.startFrame)
{
val diff = Platform.startFrame - animationFrame
animationFrame = Platform.startFrame
yPos -= diff
inLandingAndTakeoffZone = false
}
val image = SpriteManager.bitmapForSpriteNumber(animationFrame)
imageView.setImageBitmap(image)
}
else if (inLandingAndTakeoffZone && animationFrame == Platform.startFrame)
{
inLandingAndTakeoffZone = false
yPos -= ConfigurationManager.platformYAxisSteps * deviceMultiplier * speedMultiplier
}
else if (yOffset == 0 && isPlatformEndpoint(currentTileAttribute))
{
status = Motion.Still
takeoffDirection = Motion.PlatformDown
timeDocked = Date()
}
else if (yOffset == 0 && !isPlatformTraversable(surroundingTiles.up, surroundingAttributes.up))
{
status = Motion.Still
takeoffDirection = Motion.PlatformDown
timeDocked = Date()
}
else if (yPos - ConfigurationManager.platformYAxisSteps * deviceMultiplier * speedMultiplier < yTile * GameStateManager.getTileHeight() && !isPlatformTraversable(surroundingTiles.up, surroundingAttributes.up))
{
yPos = yTile * GameStateManager.getTileHeight()
status = Motion.Still
takeoffDirection = Motion.PlatformDown
timeDocked = Date()
}
else if (yPos - ConfigurationManager.platformYAxisSteps * deviceMultiplier * speedMultiplier < yTile * GameStateManager.getTileHeight() && isPlatformEndpoint(currentTileAttribute))
{
yPos = yTile * GameStateManager.getTileHeight()
status = Motion.Still
takeoffDirection = Motion.PlatformDown
timeDocked = Date()
}
else
{
yPos -= ConfigurationManager.platformYAxisSteps * deviceMultiplier * speedMultiplier
}
// Determine new tile position
if (yTile > 0 && yPos <= ((yTile - 1) * GameStateManager.getTileHeight() + GameStateManager.getTileHeight() / 2))
{
yTile -= 1
}
}
Motion.PlatformDown ->
{
if (inLandingAndTakeoffZone && animationFrame + (ConfigurationManager.platformYAxisSteps * speedMultiplier) >= Platform.endFrame)
{
status = Motion.Still
takeoffDirection = Motion.PlatformUp
timeDocked = Date()
animationFrame = Platform.endFrame
val image = SpriteManager.bitmapForSpriteNumber(animationFrame)
imageView.setImageBitmap(image)
}
else if (inLandingAndTakeoffZone)
{
animationFrame += ConfigurationManager.platformYAxisSteps * speedMultiplier
val image = SpriteManager.bitmapForSpriteNumber(animationFrame)
imageView.setImageBitmap(image)
}
else if (yOffset == 0 && (!isPlatformTraversable(surroundingTiles.down, surroundingAttributes.down) || isDownBlocked))
{
inLandingAndTakeoffZone = true
animationFrame = Platform.startFrame + 1
val image = SpriteManager.bitmapForSpriteNumber(animationFrame)
imageView.setImageBitmap(image)
}
// TODO: See if we ever enter this case
else if (yPos + ConfigurationManager.platformYAxisSteps * deviceMultiplier * speedMultiplier > yTile * GameStateManager.getTileHeight() && (!isPlatformTraversable(surroundingTiles.down, surroundingAttributes.down) || isDownBlocked))
{
yPos = yTile * GameStateManager.getTileHeight()
inLandingAndTakeoffZone = true
animationFrame = Platform.startFrame + 1
val image = SpriteManager.bitmapForSpriteNumber(animationFrame)
imageView.setImageBitmap(image)
}
else
{
yPos += ConfigurationManager.platformYAxisSteps * deviceMultiplier * speedMultiplier
}
// Determine new tile position
if (yTile < currentLevel.width - 1 && yPos >= (yTile * GameStateManager.getTileHeight() + GameStateManager.getTileHeight() / 2))
{
yTile += 1
}
}
}
imageView.left = xPos
imageView.top = yPos
}
fun isPlatformTraversable(tileNumber: Int, tileAttribute: Int): Boolean
{
if (tileNumber < 0)
{
return false
}
val tileSprite = SpriteManager.getSprite(tileNumber)
val spriteAttribute = tileSprite!!.header[0]
var traversable = false
// First, check the tile sprite's attributes
if (spriteAttribute and (ConfigurationManager.spriteHeaderTraversable) == ConfigurationManager.spriteHeaderTraversable && spriteAttribute and (ConfigurationManager.spriteHeaderFallthroughable) == ConfigurationManager.spriteHeaderFallthroughable)
{
traversable = true
}
else if ((spriteAttribute and (ConfigurationManager.spriteHeaderClimable) == ConfigurationManager.spriteHeaderClimable) || (spriteAttribute and (ConfigurationManager.spriteHeaderHangable) == ConfigurationManager.spriteHeaderHangable))
{
return false
}
else if (spriteAttribute == 0)
{
return false
}
// Then, check the attributes of the tiles position
if (tileAttribute and (ConfigurationManager.platformStoppableHeaderValue) == ConfigurationManager.platformStoppableHeaderValue)
{
return true
}
else if (tileAttribute == 0)
{
traversable = true
}
return traversable
}
fun isPlatformEndpoint(tileAttribute: Int): Boolean
{
if (tileAttribute and (ConfigurationManager.platformStoppableHeaderValue) == ConfigurationManager.platformStoppableHeaderValue)
{
return true
}
else
{
return false
}
}
fun getPlatformTopOffset(): Int
{
if (axis == TravelAxis.Horizontal)
{
return 0
}
else
{
return animationFrame - Platform.startFrame
}
}
} | 0 | Kotlin | 0 | 0 | aed17ddc1bf8bc8961be735cfa57f0a976a4a876 | 14,220 | LootRaiderAndroid_OS | Apache License 2.0 |
src/main/kotlin/no/nav/pensjon/kalkulator/avtale/PensjonsavtaleService.kt | navikt | 596,104,195 | false | null | package no.nav.pensjon.kalkulator.avtale
import no.nav.pensjon.kalkulator.avtale.api.dto.PensjonsavtaleSpecDto
import no.nav.pensjon.kalkulator.avtale.api.dto.UttaksperiodeSpecDto
import no.nav.pensjon.kalkulator.avtale.client.PensjonsavtaleClient
import no.nav.pensjon.kalkulator.avtale.client.np.PensjonsavtaleSpec
import no.nav.pensjon.kalkulator.avtale.client.np.Sivilstatus
import no.nav.pensjon.kalkulator.avtale.client.np.UttaksperiodeSpec
import no.nav.pensjon.kalkulator.tech.security.ingress.PidGetter
import no.nav.pensjon.kalkulator.tech.toggle.FeatureToggleService
import org.springframework.stereotype.Service
@Service
class PensjonsavtaleService(
private val avtaleClient: PensjonsavtaleClient,
private val pidGetter: PidGetter,
private val featureToggleService: FeatureToggleService
) {
fun fetchAvtaler(spec: PensjonsavtaleSpecDto): Pensjonsavtaler {
return if (featureToggleService.isEnabled("mock-norsk-pensjon"))
mockAvtaler(spec)
else
avtaleClient.fetchAvtaler(fromDto(spec))
}
private fun fromDto(dto: PensjonsavtaleSpecDto) =
PensjonsavtaleSpec(
pidGetter.pid(),
dto.aarligInntektFoerUttak,
dto.uttaksperioder.map(::fromUttaksperiodeSpecDto),
dto.antallInntektsaarEtterUttak,
dto.harAfp ?: false,
dto.harEpsPensjon ?: true,
dto.harEpsPensjonsgivendeInntektOver2G ?: true,
dto.antallAarIUtlandetEtter16 ?: 0,
dto.sivilstatus ?: Sivilstatus.GIFT,
dto.oenskesSimuleringAvFolketrygd ?: false
)
private fun fromUttaksperiodeSpecDto(dto: UttaksperiodeSpecDto) =
UttaksperiodeSpec(
Alder(dto.startAlder, dto.startMaaned),
Uttaksgrad.from(dto.grad),
dto.aarligInntekt
)
private companion object {
/**
* Temporary function for testing pensjonsavtaler with synthetic persons
* (per June 2023 Norsk Pensjon does not support synthetic persons)
*/
private fun mockAvtaler(spec: PensjonsavtaleSpecDto): Pensjonsavtaler {
val uttaksperiode = if (spec.uttaksperioder.isEmpty()) UttaksperiodeSpecDto(
67,
1,
100,
10000
) else spec.uttaksperioder[0]
val startAlder = uttaksperiode.startAlder
val someNumber = System.currentTimeMillis().toString().substring(7).toInt()
val startMaaned = someNumber % 12 + 1
val sluttMaaned = (someNumber + startAlder) % 12 + 1
return Pensjonsavtaler(
listOf(
Pensjonsavtale(
"PENSJONSKAPITALBEVIS",
AvtaleKategori.INDIVIDUELL_ORDNING,
startAlder,
startAlder + 10,
listOf(
Utbetalingsperiode(
Alder(startAlder, startMaaned),
Alder(startAlder + 10, sluttMaaned),
someNumber,
Uttaksgrad.from(uttaksperiode.grad)
)
)
)
), emptyList()
)
}
}
}
| 1 | Kotlin | 0 | 0 | a642602ae4997fb9d88f97464a85a6c3d9c33a89 | 3,357 | pensjonskalkulator-backend | MIT License |
Modulo_01_Estruturas_Basicas/M01A05VariaveisConstantes/src/M01A05VariaveisConstantes.kt | FilipeMGaspar | 465,803,176 | false | null | fun main(args: Array<String>) {
var nome:String = "Gustavo"
val idade:Short = 40 //val define como constante ou seja o valor não altera durante a execução do ´codigo
var peso:Float = 95.8F //Float termina com F
var numGrande:Long = 5_000_000L //Long termina co L
//idade = 41;
print("O seu nome é ")
print(nome)
print(", e tenho ")
print(idade)
print(" anos!")
/* Regras de nomeação das variaveis em KOTLIN
Começa com uma letra ou sublinhado
Maiúsculas e minúsculas fazem diferença
Só usa letras, números e sublinhado
Podemos utilizar acentos
Não pode conter espaço
Não pode ter símbolos (só sublinhado)
não pode ser uma palavra reservada
* */
} | 0 | Kotlin | 0 | 0 | 3c820bb3f069ccdd4a36324180bcb1c1d113cb83 | 742 | kotlin_Estudonauta | MIT License |
plugin/src/main/kotlin/ru/astrainteractive/telegrambridge/utils/Files.kt | Astra-Interactive | 584,452,095 | false | null | package ru.astrainteractive.telegrambridge.utils
import ru.astrainteractive.astralibs.file_manager.FileManager
/**
* All plugin files such as config.yml and other should only be stored here!
*/
object Files {
val configFile: FileManager = FileManager("config.yml")
} | 0 | Kotlin | 0 | 0 | 20de113860a51863fd77e88e8332601de8a9de9f | 275 | TelegramBridge | MIT License |
plugin/src/main/kotlin/ru/astrainteractive/telegrambridge/utils/Files.kt | Astra-Interactive | 584,452,095 | false | null | package ru.astrainteractive.telegrambridge.utils
import ru.astrainteractive.astralibs.file_manager.FileManager
/**
* All plugin files such as config.yml and other should only be stored here!
*/
object Files {
val configFile: FileManager = FileManager("config.yml")
} | 0 | Kotlin | 0 | 0 | 20de113860a51863fd77e88e8332601de8a9de9f | 275 | TelegramBridge | MIT License |
Application/app/src/main/java/com/demo/code/demos/fromapi/ui/operators/filterOperators/FilterOperatorFragment.kt | devrath | 293,422,796 | false | null | package com.demo.code.demos.fromapi.ui.operators.filterOperators
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.demo.code.demos.fromapi.utilities.Utils.getListOfTasks
import com.demo.code.databinding.FragmentOperatorFilterBinding
import com.demo.code.demos.fromapi.models.Task
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
class FilterOperatorFragment : Fragment() {
private val TAG = FilterOperatorFragment::class.java.simpleName
private var _binding: FragmentOperatorFilterBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentOperatorFilterBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
onClickListeners()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun onClickListeners() {
binding.floatingActionButton.setOnClickListener {
subscribeToObservable()
}
}
/**
* Create the observable
*/
private fun createObservable() : Observable<Task>{
return Observable.fromIterable(getListOfTasks())
.subscribeOn(Schedulers.io())
.filter { it.taskIsCompleted }
.observeOn(AndroidSchedulers.mainThread())
}
/**
* Subscribe to the observable
*/
private fun subscribeToObservable() {
createObservable().subscribe(object : Observer<Task>{
override fun onSubscribe(d: Disposable) {
Timber.tag(TAG).d("Subscribe Invoked")
}
override fun onNext(t: Task) {
Timber.tag(TAG).d("Value: %s", t)
}
override fun onError(e: Throwable) {
Timber.tag(TAG).e("ERROR: %s",e.message)
}
override fun onComplete() {
Timber.tag(TAG).d("Task is complete")
}
})
}
} | 0 | Kotlin | 0 | 0 | 47b6f81b45a8d85c7b96a731403afbe2814605f2 | 2,479 | fuzzy-reactive-kotlin | Apache License 2.0 |
columbiad-express-domain/src/test/kotlin/org/craftsrecords/columbiadexpress/domain/search/criteria/CriteriaShould.kt | ArjunDahal864 | 680,370,067 | false | null | package org.craftsrecords.columbiadexpress.domain.search.criteria
import org.assertj.core.api.Assertions.assertThatCode
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.craftsrecords.columbiadexpress.domain.EqualityShould
import org.craftsrecords.columbiadexpress.domain.spaceport.OnEarth
import org.craftsrecords.columbiadexpress.domain.spaceport.OnMoon
import org.craftsrecords.columbiadexpress.domain.spaceport.SpacePort
import org.junit.jupiter.api.Test
import java.time.LocalDateTime.now
class CriteriaShould(private val journey: Journey) : EqualityShould<Criteria> {
@Test
fun `create Criteria`() {
val journeys =
listOf(
journey,
inboundOf(journey) departingAt journey.departureSchedule.plusWeeks(1)
)
assertThatCode { Criteria(journeys) }.doesNotThrowAnyException()
}
@Test
fun `contain at least one journey`() {
assertThatThrownBy { Criteria(emptyList()) }
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage("Criteria must contain at least one journey")
}
@Test
fun `have only journeys ordered by departureSchedule`() {
val journeys =
listOf(
journey.copy(departureSchedule = now().plusWeeks(1)),
inboundOf(journey) departingAt now().plusDays(1)
)
assertThatThrownBy { Criteria(journeys) }
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage("Criteria must only have journeys ordered by departure schedule")
}
@Test
fun `have only connected journeys`(@OnEarth spacePortOnEarth: SpacePort, @OnMoon spacePortOnMoon: SpacePort) {
val journeys =
listOf(
Journey(spacePortOnEarth.id, now().plusDays(1), spacePortOnMoon.id),
Journey(spacePortOnEarth.id, now().plusWeeks(1), spacePortOnMoon.id)
)
assertThatThrownBy { Criteria(journeys) }
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage("Criteria must only have connected journeys")
}
@Test
fun `have at least 5 days between all journeys`(journey: Journey) {
val tooCloseJourney = inboundOf(journey).copy(departureSchedule = journey.departureSchedule)
assertThatThrownBy { Criteria(listOf(journey, tooCloseJourney)) }
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage("An elapse time of 5 days must be respected between journeys")
}
} | 0 | Kotlin | 0 | 0 | b06fcef38e8fa258184b91fe52e66100c518c1c1 | 2,568 | hyperlink_based_api | MIT License |
desktop/adapters/src/main/kotlin/com/soyle/stories/repositories/ProjectFileRepository.kt | Soyle-Productions | 239,407,827 | false | null | package com.soyle.stories.repositories
import com.soyle.stories.domain.project.Project
import com.soyle.stories.domain.validation.NonBlankString
import com.soyle.stories.stores.FileStore
import com.soyle.stories.workspace.repositories.FileRepository
import com.soyle.stories.workspace.repositories.ProjectRepository
import com.soyle.stories.workspace.valueobjects.ProjectFile
import java.io.File
class ProjectFileRepository(
private val fileStore: FileStore<ProjectFile>
) : ProjectRepository, com.soyle.stories.usecase.project.ProjectRepository, FileRepository {
private val fileSystem: Map<String, MutableSet<String>> = mapOf(
"directories" to mutableSetOf(),
"files" to mutableSetOf()
)
override suspend fun createFile(projectFile: ProjectFile) {
fileSystem.getValue("files").add(projectFile.location)
fileStore.createFile(projectFile.location, projectFile)
}
override suspend fun doesDirectoryExist(directory: String): Boolean {
return File(directory).run {
isDirectory && exists()
} || fileSystem.getValue("directories").contains(directory)
}
override suspend fun doesFileExist(filePath: String): Boolean {
return File(filePath).run {
isFile && exists()
} || fileSystem.getValue("files").contains(filePath)
}
override suspend fun addNewProject(project: Project) {}
override suspend fun getProjectAtLocation(location: String): Project? = fileStore.getFileAt(location)?.let {
Project(it.projectId, NonBlankString.create(it.projectName)!!)
}
} | 45 | Kotlin | 0 | 9 | 1a110536865250dcd8d29270d003315062f2b032 | 1,597 | soyle-stories | Apache License 2.0 |
app/src/main/java/kr/dagger/chat/base/BaseActivity.kt | 3dagger | 558,649,660 | false | null | package kr.dagger.chat.base
import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
abstract class BaseActivity<T : ViewDataBinding>(@LayoutRes private val layoutResId: Int) : AppCompatActivity() {
lateinit var binding: T
abstract fun initView(savedInstanceState: Bundle?)
abstract fun subscribeObservers()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, layoutResId)
initView(savedInstanceState)
subscribeObservers()
}
} | 0 | Kotlin | 0 | 0 | 6abb4412be4a99067e812fa2d23c89bcafdffb5b | 671 | Chatting | Apache License 2.0 |
src/main/kotlin/org/incoder/completion/androidsearch/GoogleMavenArtifactVersionSearcher.kt | RootCluster | 328,721,649 | true | {"Kotlin": 29227} | package org.incoder.completion.androidsearch
import org.incoder.completion.Client
import org.apache.http.util.TextUtils
import org.xml.sax.Attributes
import org.xml.sax.InputSource
import org.xml.sax.SAXException
import org.xml.sax.helpers.DefaultHandler
import java.util.*
import javax.xml.parsers.SAXParserFactory
object GoogleMavenArtifactVersionSearcher {
private var sArtifactVersionMap: MutableMap<String, List<ArtifactVersionBean>>? = null
fun searchArtifact(groupId: String): List<String>? {
if (sArtifactVersionMap == null || !sArtifactVersionMap!!.containsKey(groupId)) {
refreshIndexInfo(groupId)
}
if (sArtifactVersionMap == null) {
return null
}
if (sArtifactVersionMap!!.containsKey(groupId)) {
val list = ArrayList<String>()
val artifactVersionBeans = sArtifactVersionMap!![groupId]
if (artifactVersionBeans != null && artifactVersionBeans.isNotEmpty()) {
for (artifactVersionBean in artifactVersionBeans) {
list.add(artifactVersionBean.artifact!!)
}
}
return list
}
return null
}
fun searchVersion(groupId: String, artifactId: String): List<String>? {
if (sArtifactVersionMap == null || !sArtifactVersionMap!!.containsKey(groupId)) {
refreshIndexInfo(groupId)
}
if (sArtifactVersionMap == null) {
return null
}
if (sArtifactVersionMap!!.containsKey(groupId)) {
val artifactVersionBeans = sArtifactVersionMap!![groupId]
if (artifactVersionBeans != null && artifactVersionBeans.isNotEmpty()) {
val list = ArrayList<String>()
for (artifactVersionBean in artifactVersionBeans) {
if (artifactId == artifactVersionBean.artifact) {
for (version in artifactVersionBean.versions!!) {
list.add(version)
}
}
}
return list
}
}
return null
}
class ArtifactVersionBean {
var artifact: String? = null
var versions: MutableList<String>? = null
}
private fun refreshIndexInfo(groupId: String) {
try {
if (TextUtils.isEmpty(groupId)) {
return
}
val groupPath = groupId.replace("\\.".toRegex(), "/")
var result = Client.get("https://dl.google.com/dl/android/maven2/$groupPath/group-index.xml").trim { it <= ' ' }
if (TextUtils.isEmpty(result)) {
return
}
if (result.startsWith("<?xml")) {
val i = result.indexOf(">")
result = result.substring(i + 1)
}
println(result)
val saxParserFactory = SAXParserFactory.newInstance()
val xmlReader = saxParserFactory.newSAXParser().xmlReader
xmlReader.contentHandler = MyContentHandler(groupId)
xmlReader.parse(InputSource(result.reader()))
} catch (e: Exception) {
e.printStackTrace()
}
}
private class MyContentHandler(private val groupId: String) : DefaultHandler() {
private var artifactVersionBeanList: MutableList<ArtifactVersionBean>? = null
@Throws(SAXException::class)
override fun startDocument() {
super.startDocument()
if (sArtifactVersionMap == null) {
sArtifactVersionMap = HashMap()
}
}
@Throws(SAXException::class)
override fun startElement(uri: String?, localName: String?, qName: String?, attributes: Attributes?) {
super.startElement(uri, localName, qName, attributes)
if (this.groupId == qName) {
artifactVersionBeanList = ArrayList()
sArtifactVersionMap!![this.groupId] = artifactVersionBeanList!!
} else if (artifactVersionBeanList != null) {
val artifactVersionBean = ArtifactVersionBean()
artifactVersionBean.artifact = qName
val versions = attributes!!.getValue("versions")
if (!TextUtils.isEmpty(versions)) {
val split = versions.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (split.isNotEmpty()) {
artifactVersionBean.versions = ArrayList()
val list = Arrays.asList(*split)
list.reverse()
artifactVersionBean.versions!!.addAll(list)
}
}
artifactVersionBeanList!!.add(artifactVersionBean)
}
}
@Throws(SAXException::class)
override fun endDocument() {
super.endDocument()
}
}
}
| 0 | Kotlin | 0 | 0 | af069472dc0c2f1fdf354ce8e3c522647ba5dc14 | 4,959 | dependencies-completion | MIT License |
newm-server/src/main/kotlin/io/newm/server/features/collaboration/model/CollaboratorFilters.kt | projectNEWM | 447,979,150 | false | null | package io.newm.server.features.collaboration.model
import io.ktor.server.application.ApplicationCall
import io.newm.server.ktx.phrase
import io.newm.server.ktx.songIds
import io.newm.server.ktx.sortOrder
import org.jetbrains.exposed.sql.SortOrder
import java.util.UUID
data class CollaboratorFilters(
val sortOrder: SortOrder?,
val excludeMe: Boolean?,
val songIds: List<UUID>?,
val phrase: String?
)
val ApplicationCall.excludeMe: Boolean?
get() = parameters["excludeMe"]?.toBoolean()
val ApplicationCall.collaboratorFilters: CollaboratorFilters
get() = CollaboratorFilters(sortOrder, excludeMe, songIds, phrase)
| 2 | Kotlin | 3 | 7 | e76cf0d88f5b160722e32df9a84851c95e9a9fdc | 643 | newm-server | Apache License 2.0 |
mbmobilesdk/src/main/java/com/daimler/mbmobilesdk/vehicleassignment/AssignmentCodeViewModel.kt | rafalzawadzki | 208,997,288 | true | {"Kotlin": 1297852, "Groovy": 4489} | package com.daimler.mbmobilesdk.vehicleassignment
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.daimler.mbmobilesdk.R
import com.daimler.mbmobilesdk.utils.extensions.defaultErrorMessage
import com.daimler.mbmobilesdk.utils.extensions.ifValid
import com.daimler.mbmobilesdk.utils.extensions.re
import com.daimler.mbloggerkit.MBLoggerKit
import com.daimler.mbingresskit.MBIngressKit
import com.daimler.mbcarkit.MBCarKit
import com.daimler.mbcarkit.business.model.rif.Rifability
import com.daimler.mbnetworkkit.networking.HttpError
import com.daimler.mbnetworkkit.networking.RequestError
import com.daimler.mbnetworkkit.networking.ResponseError
import com.daimler.mbuikit.lifecycle.events.MutableLiveEvent
import com.daimler.mbuikit.lifecycle.events.MutableLiveUnitEvent
import com.daimler.mbuikit.utils.connectors.EditTextConnector
import com.daimler.mbuikit.utils.extensions.getString
class AssignmentCodeViewModel(app: Application) : AndroidViewModel(app) {
val vin = EditTextConnector { !it.isNullOrBlank() }
val validationCode = EditTextConnector { !it.isNullOrBlank() }
val progressVisible = MutableLiveData<Boolean>()
internal val codeGeneratedEvent = MutableLiveEvent<String>()
internal val invalidVinEvent = MutableLiveUnitEvent()
internal val alreadyAssignedEvent = MutableLiveUnitEvent()
internal val codeValidationEvent = MutableLiveEvent<String>()
internal val noRifSupportEvent = MutableLiveEvent<String>()
internal val legacyVehicleEvent = MutableLiveEvent<String>()
internal val errorEvent = MutableLiveEvent<String>()
private val isLoading: Boolean
get() = progressVisible.value == true
fun onGenerateCodeClicked() {
vin.ifValid {
generateCode(it)
}
}
fun onValidateCodeClicked() {
if (vin.isValid() && validationCode.isValid()) {
validateVac(vin.value!!, validationCode.value!!)
}
}
private fun generateCode(vin: String) {
if (isLoading) return
if (vin.length != VIN_LENGTH) {
errorEvent.sendEvent(String.format(
getString(R.string.assign_code_validation_length), VIN_LENGTH
))
return
}
validateVin(vin)
}
private fun validateVin(vin: String) {
onLoadingStarted()
MBIngressKit.refreshTokenIfRequired()
.onComplete { token ->
val jwt = token.jwtToken.plainToken
MBCarKit.assignmentService().assignVehicleByVin(jwt, vin)
.onComplete {
MBLoggerKit.d("Valid vin, rif = ${it.isRifable}")
notifyVinValidation(it, vin)
}.onFailure {
MBLoggerKit.re("Failed to assign vehicle.", it)
notifyVinValidationError(it)
}.onAlways { _, _, _ ->
onLoadingFinished()
}
}.onFailure {
MBLoggerKit.e("Failed to refresh token.", throwable = it)
onDefaultError(it)
onLoadingFinished()
}
}
private fun validateVac(vin: String, vac: String) {
if (isLoading) return
onLoadingStarted()
MBIngressKit.refreshTokenIfRequired()
.onComplete { token ->
val jwt = token.jwtToken.plainToken
MBCarKit.assignmentService().confirmVehicleAssignmentWithVac(jwt, vin, vac)
.onComplete {
MBLoggerKit.d("Assigned vehicle $vin.")
notifyVacValidation(vin)
}
.onFailure {
MBLoggerKit.re("Failed to assign vehicle.", it)
onDefaultError(it)
}
.onAlways { _, _, _ -> onLoadingFinished() }
}
.onFailure {
MBLoggerKit.e("Failed to refresh token.")
onLoadingFinished()
onDefaultError(it)
}
}
private fun notifyVinValidation(rifability: Rifability, vin: String) {
when {
rifability.isRifable -> codeGeneratedEvent.sendEvent(vin)
rifability.isConnectVehicle -> noRifSupportEvent.sendEvent(vin)
else -> legacyVehicleEvent.sendEvent(vin)
}
}
private fun notifyVinValidationError(error: ResponseError<out RequestError>?) {
when {
// 404 -> VIN not found
error?.requestError is HttpError.NotFound -> invalidVinEvent.sendEvent()
// 409 -> VIN already assigned
error?.requestError is HttpError.Conflict -> alreadyAssignedEvent.sendEvent()
else -> onDefaultError(error)
}
}
private fun notifyVacValidation(vin: String) {
codeValidationEvent.sendEvent(vin)
}
private fun onDefaultError(throwable: Throwable?) {
errorEvent.sendEvent(defaultErrorMessage(throwable))
}
private fun onDefaultError(error: ResponseError<out RequestError>?) {
errorEvent.sendEvent(defaultErrorMessage(error))
}
private fun onLoadingStarted() {
progressVisible.postValue(true)
}
private fun onLoadingFinished() {
progressVisible.postValue(false)
}
private companion object {
private const val VIN_LENGTH = 17
}
} | 0 | null | 0 | 0 | 1a924f70fbde5d731cdfde275e724e6343ee6ebe | 5,493 | MBSDK-Mobile-Android | MIT License |
core/usecases/src/main/kotlin/theme/addOppositionToValueWeb/OppositionAddedToValueWeb.kt | Soyle-Productions | 239,407,827 | false | null | package com.soyle.stories.usecase.theme.addOppositionToValueWeb
import java.util.*
open class OppositionAddedToValueWeb(
val themeId: UUID,
val valueWebId: UUID,
val oppositionValueId: UUID,
val oppositionValueName: String,
val needsName: Boolean
) | 45 | Kotlin | 0 | 9 | 1a110536865250dcd8d29270d003315062f2b032 | 270 | soyle-stories | Apache License 2.0 |
services/csm.cloud.project.api.timeseries/src/test/kotlin/com/bosch/pt/csm/cloud/projectmanagement/application/security/PatAuthenticationFilterTest.kt | boschglobal | 805,348,245 | false | {"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344} | /*
* ************************************************************************
*
* Copyright: <NAME> Power Tools GmbH, 2018 - 2023
*
* ************************************************************************
*/
package com.bosch.pt.csm.cloud.projectmanagement.application.security
import com.bosch.pt.csm.cloud.common.SmartSiteMockKTest
import com.bosch.pt.csm.cloud.projectmanagement.application.security.pat.authentication.PatAuthenticationEntryPoint
import com.bosch.pt.csm.cloud.projectmanagement.application.security.pat.authentication.PatAuthenticationFilter
import com.bosch.pt.csm.cloud.projectmanagement.application.security.pat.authentication.token.resolver.TokenResolver
import com.bosch.pt.csm.cloud.projectmanagement.application.security.pat.authentication.PatAuthenticationException
import com.bosch.pt.csm.cloud.projectmanagement.application.security.pat.authentication.token.model.PatErrors
import io.mockk.every
import io.mockk.impl.annotations.RelaxedMockK
import io.mockk.mockk
import io.mockk.verify
import io.mockk.verifySequence
import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.authentication.AuthenticationDetailsSource
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.AuthenticationManagerResolver
import org.springframework.security.authentication.LockedException
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolderStrategy
import org.springframework.security.core.context.SecurityContextImpl
import org.springframework.security.web.context.SecurityContextRepository
@SmartSiteMockKTest
class PatAuthenticationFilterTest {
@RelaxedMockK
private lateinit var authenticationManagerResolver:
AuthenticationManagerResolver<HttpServletRequest>
@RelaxedMockK private lateinit var securityContextHolderStrategy: SecurityContextHolderStrategy
@RelaxedMockK private lateinit var tokenResolver: TokenResolver
@RelaxedMockK private lateinit var entryPoint: PatAuthenticationEntryPoint
@RelaxedMockK private lateinit var securityContextRepository: SecurityContextRepository
@RelaxedMockK
private lateinit var authenticationDetailsSource:
AuthenticationDetailsSource<HttpServletRequest, *>
private val cut by lazy {
PatAuthenticationFilter(
authenticationManagerResolver,
securityContextHolderStrategy,
tokenResolver,
entryPoint,
securityContextRepository,
authenticationDetailsSource)
}
@Test
fun `handle error and do not process the request if the token cannot be resolved`() {
val request = MockHttpServletRequest()
val response = MockHttpServletResponse()
val filterChain = mockk<FilterChain>()
val expectedException =
PatAuthenticationException(PatErrors.invalidToken("Invalid basic authentication token"))
every { tokenResolver.resolve(any()) } throws expectedException
cut.doFilter(request, response, filterChain)
verify(exactly = 1) { entryPoint.commence(request, response, expectedException) }
verify(exactly = 0) { filterChain.doFilter(any(), any()) }
}
@Test
fun `do not apply the filter if no pat is provided`() {
val request = MockHttpServletRequest()
val response = MockHttpServletResponse()
val filterChain = mockk<FilterChain>(relaxed = true)
every { tokenResolver.resolve(any()) } returns null
cut.doFilter(request, response, filterChain)
verify(exactly = 1) { filterChain.doFilter(any(), any()) }
verify(exactly = 0) { entryPoint.commence(any(), any(), any()) }
}
@Test
fun `authentication failed because user is locked`() {
val request = MockHttpServletRequest()
val response = MockHttpServletResponse()
val filterChain = mockk<FilterChain>()
val authenticationManager = mockk<AuthenticationManager>()
every { tokenResolver.resolve(any()) } returns "token"
every { authenticationManagerResolver.resolve(any()) } returns authenticationManager
val expectedException = LockedException("Locked")
every { authenticationManager.authenticate(any()) } throws expectedException
cut.doFilter(request, response, filterChain)
verifySequence {
tokenResolver.resolve(request)
authenticationDetailsSource.buildDetails(request)
authenticationManagerResolver.resolve(request)
authenticationManager.authenticate(any())
securityContextHolderStrategy.clearContext()
entryPoint.commence(request, response, expectedException)
}
verify(exactly = 0) { filterChain.doFilter(any(), any()) }
}
@Test
fun `successful authentication`() {
val request = MockHttpServletRequest()
val response = MockHttpServletResponse()
val filterChain = mockk<FilterChain>(relaxed = true)
val authenticationManager = mockk<AuthenticationManager>()
val authentication = mockk<Authentication>()
val securityContext = SecurityContextImpl()
every { tokenResolver.resolve(any()) } returns "token"
every { authenticationManagerResolver.resolve(any()) } returns authenticationManager
every { authenticationManager.authenticate(any()) } returns authentication
every { securityContextHolderStrategy.createEmptyContext() } returns securityContext
cut.doFilter(request, response, filterChain)
verifySequence {
tokenResolver.resolve(request)
authenticationDetailsSource.buildDetails(request)
authenticationManagerResolver.resolve(request)
authenticationManager.authenticate(any())
securityContextHolderStrategy.createEmptyContext()
securityContextHolderStrategy.context = securityContext
securityContextRepository.saveContext(securityContext, request, response)
filterChain.doFilter(any(), any())
}
verify(exactly = 0) { entryPoint.commence(any(), any(), any()) }
assertThat(securityContext.authentication).isEqualTo(authentication)
}
}
| 0 | Kotlin | 3 | 9 | 9f3e7c4b53821bdfc876531727e21961d2a4513d | 6,240 | bosch-pt-refinemysite-backend | Apache License 2.0 |
app/src/main/kotlin/ru/khiraevmalik/theguardiannews/presentation/main/mvi/Action.kt | Hiraev | 278,637,711 | false | null | package ru.khiraevmalik.theguardiannews.presentation.main.mvi
import ru.khiraevmalik.theguardiannews.base.PagingStatus
import ru.khiraevmalik.theguardiannews.presentation.main.adapter.NewsItem
sealed class Action {
// Actions from user
sealed class User : Action() {
object SearchOpen : User()
object SearchClose : User()
object SearchClear : User()
class SearchQuery(val query: String) : User()
object FetchNews : User()
object FetchMore : User()
object Retry : User()
}
// Effects
sealed class Effect : Action() {
object SearchLoading : Effect()
class SearchError(val lastQuery: String) : Effect()
object SearchEmpty : Effect()
object SearchClose : Effect()
class SearchSuccess(val news: List<NewsItem>) : Effect()
object FetchLoading : Effect()
object FetchError : Effect()
class FetchSuccess(val news: List<NewsItem>, val pagingStatus: PagingStatus) : Effect()
}
}
| 0 | Kotlin | 0 | 0 | 19ce6605f1d8c33def4d0a70340c8e75bd4c9a20 | 1,021 | TheGuardianNews | Apache License 2.0 |
classes/src/myInterface.kt | Navachethan-Murugeppa | 287,685,049 | false | null | interface MyInterface {
fun hello() // function without implementation
fun greetings() = println("Hello there")//function with default implementation
} | 0 | Kotlin | 0 | 1 | 69410be5dada2e6a0032f31597242b5ed3ad6a26 | 161 | learn_kotlin | MIT License |
game/src/main/kotlin/gg/rsmod/game/message/handler/OpObj6Handler.kt | AlterRSPS | 421,831,790 | false | null | package gg.rsmod.game.message.handler
import gg.rsmod.game.message.MessageHandler
import gg.rsmod.game.message.impl.OpObj6Message
import gg.rsmod.game.model.ExamineEntityType
import gg.rsmod.game.model.World
import gg.rsmod.game.model.entity.Client
class OpObj6Handler : MessageHandler<OpObj6Message> {
override fun handle(client: Client, world: World, message: OpObj6Message) {
world.sendExamine(client, message.item, ExamineEntityType.ITEM)
}
} | 8 | Kotlin | 33 | 22 | 9de9acfd3be7353c0c749179b3a7be8aab49b53b | 465 | Alter | Apache License 2.0 |
app/src/main/java/rocks/crownstone/dev_app/MainActivity.kt | crownstone | 147,512,206 | false | null | package rocks.crownstone.dev_app
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import nl.komponents.kovenant.then
import nl.komponents.kovenant.unwrap
import rocks.crownstone.bluenet.scanparsing.ScannedDevice
import rocks.crownstone.bluenet.structs.*
import rocks.crownstone.bluenet.util.toUint8
import java.util.*
class MainActivity : AppCompatActivity() {
private val TAG = this.javaClass.simpleName
private val REQUEST_CODE_LOGIN = 1
val scanInterval = ScanMode.LOW_POWER
val deviceList = ArrayList<ScannedDevice>()
val deviceMap = HashMap<DeviceAddress, ScannedDevice>()
private lateinit var adapter: DeviceListAdapter
private lateinit var buttonRefresh: Button
private var lastUpdateTime: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.i(TAG, "onCreate")
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById(R.id.my_toolbar))
// Set the adapter
val listView = findViewById<RecyclerView>(R.id.list)
if (listView is RecyclerView) {
listView.layoutManager = LinearLayoutManager(this)
adapter = DeviceListAdapter(deviceList, ::onDeviceClick)
listView.adapter = adapter
// // See: https://stackoverflow.com/questions/45977011/example-of-when-should-we-use-run-let-apply-also-and-with-on-kotlin
// with(listView) {
// layoutManager = LinearLayoutManager(context)
// adapter = DeviceListAdapter(deviceList, ::onClick)
// }
// adapter = view.adapter as DeviceListAdapter
}
buttonRefresh = findViewById(R.id.buttonRefresh)
buttonRefresh.setOnClickListener {
MainApp.instance.bluenet.filterForCrownstones(true)
MainApp.instance.bluenet.filterForIbeacons(true)
MainApp.instance.bluenet.setScanInterval(scanInterval)
MainApp.instance.bluenet.startScanning()
deviceList.clear()
adapter.notifyDataSetChanged()
}
findViewById<Button>(R.id.buttonSort).setOnClickListener {
deviceList.sortByDescending { it.rssi }
adapter.notifyDataSetChanged()
}
MainApp.instance.bluenet.subscribe(BluenetEvent.SCAN_RESULT, { data -> onScannedDevice(data as ScannedDevice)})
// MainApp.instance.bluenet.subscribe(BluenetEvent.INITIALIZED, ::onBluenetInitialized)
// MainApp.instance.bluenet.subscribe(BluenetEvent.SCANNER_READY, ::onScannerReady)
Log.i(TAG, "init bluenet")
// MainApp.instance.bluenet.init(this)
MainApp.instance.bluenet.init(applicationContext)
.then {
Log.i(TAG, "run in foreground")
MainApp.instance.bluenet.runInForeground(MainApp.instance.NOTIFICATION_ID, MainApp.instance.getNotification())
}
.then {
Log.i(TAG, "make scanner ready")
MainApp.instance.bluenet.makeScannerReady(this)
}.unwrap()
.then {
MainApp.instance.bluenet.filterForIbeacons(true)
MainApp.instance.bluenet.filterForCrownstones(true)
Log.i(TAG, "start scanning")
MainApp.instance.bluenet.setScanInterval(scanInterval)
MainApp.instance.bluenet.startScanning()
}
.fail {
Log.w(TAG, "Failed: $it")
}
if (MainApp.instance.user.loadLogin(this)) {
MainApp.instance.sphere.getSpheres(MainApp.instance.user)
.success {
MainApp.instance.showResult("Logged in", this)
onLogin(0)
}
.fail {
MainApp.instance.showResult("Failed to log in", this)
}
}
// Always call onLogin, so the dev sphere settings are loaded.
onLogin(0)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
Log.i(TAG, "onCreateOptionsMenu")
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
Log.i(TAG, "onOptionsItemSelected")
if (item == null) { return false }
when (item.itemId) {
R.id.action_login -> {
val intent = Intent(this, LoginActivity::class.java)
this.startActivityForResult(intent, REQUEST_CODE_LOGIN)
return true
}
R.id.action_logout -> {
MainApp.instance.logout()
// MainApp.instance.showResult("Logged out", this)
MainApp.instance.quit()
// Can also use finishAffinity()
finishAndRemoveTask()
return true
}
R.id.action_test -> {
// val deviceListCopy = ArrayList<ScannedDevice>()
// deviceListCopy.addAll(deviceList)
// MainApp.instance.test(deviceListCopy, this)
val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
// this.startActivityForResult(intent, 456)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
this.baseContext.startActivity(intent)
return true
}
R.id.action_quit -> {
Log.i(TAG, "quit")
MainApp.instance.quit()
// Can also use finishAffinity()
finishAndRemoveTask()
return true
}
}
return super.onOptionsItemSelected(item)
}
fun onBluenetInitialized(data: Any) {
// Log.i(TAG, "onBluenetInitialized")
// MainApp.instance.bluenet.makeScannerReady(this)
// .success {
// Log.i(TAG, "start scanning")
// MainApp.instance.bluenet.startScanning()
// }
// .fail {
// Log.w(TAG, "unable to start scanning: $it")
// }
// MainApp.instance.bluenet.tryMakeScannerReady(this)
}
fun onScannerReady(data: Any) {
Log.i(TAG, "onScannerReady")
// MainApp.instance.bluenet.startScanning()
}
fun onLogin(resultCode: Int) {
Log.i(TAG, "onLogin result=$resultCode")
MainApp.instance.setSphereSettings()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Log.i(TAG, "onActivityResult $requestCode $resultCode")
if (MainApp.instance.bluenet.handleActivityResult(requestCode, resultCode, data)) {
return
}
if (requestCode == REQUEST_CODE_LOGIN) {
onLogin(resultCode)
return
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
Log.i(TAG, "onRequestPermissionsResult $requestCode")
if (MainApp.instance.bluenet.handlePermissionResult(requestCode, permissions, grantResults, this)) {
return
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
fun onScannedDevice(device: ScannedDevice) {
// if (!device.validated) {
// return
// }
if (device.serviceData == null) {
return
}
if (device.serviceData?.unique == false) {
return
}
Log.v(TAG, "Add or update $device")
// deviceMap[device.address] = device
var found = false
for (i in deviceList.indices) {
if (deviceList[i].address == device.address) {
deviceList[i] = device
adapter.notifyItemChanged(i, device)
found = true
break
}
}
if (!found) {
deviceList.add(device)
adapter.notifyItemInserted(deviceList.size-1)
}
// if (System.currentTimeMillis() > lastUpdateTime + GUI_UPDATE_INTERVAL_MS) {
// lastUpdateTime = System.currentTimeMillis()
// updateDeviceList()
// }
}
enum class DeviceOption {
Test,
Setup,
FactoryReset,
Reset,
PutInDfu,
HardwareVersion,
FirmwareVersion,
BootloaderVersion,
ResetCount,
UicrData,
Toggle,
}
private fun onDeviceClick(device: ScannedDevice, longClick: Boolean) {
rocks.crownstone.bluenet.util.Log.i(TAG, "onDeviceClick ${device.address}")
val activity = this ?: return
if (!longClick) {
val intent = Intent(this, ControlActivity::class.java)
intent.putExtra("deviceAddress", device.address)
MainApp.instance.selectedDevice = device
MainApp.instance.selectedDeviceServiceData = null
// Cache the latest service data of the selected device.
val serviceData = device.serviceData
if (device.validated && serviceData != null && !serviceData.flagExternalData) {
MainApp.instance.selectedDeviceServiceData = device.serviceData
}
this.startActivity(intent)
// this.startActivityForResult(intent, REQUEST_CODE_LOGIN)
return
}
val optionList = DeviceOption.values()
val optionNames = ArrayList<String>()
for (opt in optionList) {
optionNames.add(opt.name)
}
var optionInd = 0
MainApp.instance.selectOptionAlert(activity, "Select an option", optionNames)
.then {
optionInd = it
MainApp.instance.bluenet.connect(device.address)
}.unwrap()
.then {
when (optionList[optionInd]) {
DeviceOption.Test -> {
MainApp.instance.testOldFirmware(device, activity)
}
DeviceOption.Setup -> {
MainApp.instance.setup(device, activity)
}
DeviceOption.FactoryReset -> {
MainApp.instance.factoryReset(device, activity)
}
DeviceOption.Reset -> {
MainApp.instance.bluenet.control(device.address).reset()
}
DeviceOption.PutInDfu -> {
MainApp.instance.bluenet.control(device.address).goToDfu()
}
DeviceOption.HardwareVersion -> {
MainApp.instance.bluenet.deviceInfo(device.address).getHardwareVersion()
.success { MainApp.instance.showResult("hw: $it", activity) }
}
DeviceOption.FirmwareVersion -> {
MainApp.instance.bluenet.deviceInfo(device.address).getFirmwareVersion()
.success { MainApp.instance.showResult("fw: $it", activity) }
}
DeviceOption.BootloaderVersion -> {
MainApp.instance.bluenet.deviceInfo(device.address).getBootloaderVersion()
.success { MainApp.instance.showResult("bl: $it", activity) }
}
DeviceOption.ResetCount -> {
MainApp.instance.bluenet.state(device.address).getResetCount()
.success { MainApp.instance.showResult("resetCount: $it", activity) }
}
DeviceOption.UicrData -> {
MainApp.instance.bluenet.deviceInfo(device.address).getUicrData()
.success { MainApp.instance.showResult("uicr: $it", activity) }
}
DeviceOption.Toggle -> {
MainApp.instance.bluenet.control(device.address).toggleSwitch(255.toUint8())
}
}
}.unwrap()
.success {
MainApp.instance.showResult("Success", activity)
}
.fail {
rocks.crownstone.bluenet.util.Log.e(TAG, "failed: ${it.message}")
it.printStackTrace()
MainApp.instance.showResult("Failed: ${it.message}", activity)
}
.always { MainApp.instance.bluenet.disconnect(device.address) }
}
}
| 0 | Kotlin | 1 | 0 | c1c072c5976edaa1ea1762fecde3d20440599355 | 10,474 | bluenet-android-dev-app | Apache License 2.0 |
src/main/kotlin/com/sourcegraph/cody/agent/protocol/WorkspaceEditMetadata.kt | sourcegraph | 702,947,607 | false | {"Kotlin": 914689, "Java": 201176, "Shell": 4636, "TypeScript": 2153, "Nix": 1122, "JavaScript": 436, "HTML": 294} | package com.sourcegraph.cody.agent.protocol
data class WorkspaceEditMetadata(val isRefactoring: Boolean = false)
| 230 | Kotlin | 16 | 55 | 1eb25809c3e51b64f08e851c8da09778000540c6 | 114 | jetbrains | Apache License 2.0 |
src/main/kotlin/api/func/SetChatPhoto.kt | iseki0 | 195,287,997 | false | {"HTML": 520443, "Kotlin": 390011} | @file:Suppress("RemoveExplicitTypeArguments", "DuplicatedCode", "unused", "SpellCheckingInspection")
package api.func
import ApiContext
import api.*
import io.vertx.core.AsyncResult
import io.vertx.core.Future
/**
* Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns *True* on success.
* > Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.
*
* @param[chatId] Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
* @param[photo] New chat photo, uploaded using multipart/form-data
*/
fun ApiContext.setChatPhoto(
chatId: String,
photo: InputFile
): Future<SetChatPhotoResult> =
sendRequest<SetChatPhotoResult>("setChatPhoto", listOf(Pair("chat_id", chatId), Pair("photo", photo)))
fun ApiContext.setChatPhoto(
chatId: String,
photo: InputFile,
callback: (result: AsyncResult<SetChatPhotoResult>) -> Unit
): ApiContext = sendRequestCallback<SetChatPhotoResult>(
"setChatPhoto",
listOf(Pair("chat_id", chatId), Pair("photo", photo)),
callback
)
suspend fun ApiContext.setChatPhotoAwait(
chatId: String,
photo: InputFile
): SetChatPhotoResult =
sendRequestAwait<SetChatPhotoResult>("setChatPhoto", listOf(Pair("chat_id", chatId), Pair("photo", photo))) | 0 | HTML | 0 | 1 | 1d72031badfcb48f1093b18fafc175679e55fe1e | 1,512 | telebotKt | Do What The F*ck You Want To Public License |
module/data/src/main/kotlin/io/github/siyual_park/data/annotation/ConverterScope.kt | siyual-park | 403,557,925 | false | null | package io.github.siyual_park.data.annotation
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class ConverterScope(
val type: Type
) {
enum class Type {
MONGO,
R2DBC
}
}
| 5 | Kotlin | 0 | 18 | 17203e5b7630bb8279bf6c3cc0f7c4be11ab57ba | 234 | spring-webflux-multi-module-boilerplate | MIT License |
app/src/main/java/com/sunil/kotlincoroutneexample/ui/MainActivity.kt | sunil676 | 182,536,306 | false | null | package com.sunil.kotlincoroutneexample.ui
import android.os.Bundle
import com.sunil.kotlincoroutneexample.R
import com.sunil.kotlincoroutneexample.base.BaseActivity
import com.sunil.kotlincoroutneexample.viewModel.MainViewModel
import org.koin.android.architecture.ext.viewModel
class MainActivity : BaseActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
showMovieFragment()
}
private fun showMovieFragment() {
supportFragmentManager.beginTransaction()
.replace(R.id.container, MainFragment())
.commit()
}
} | 1 | Kotlin | 0 | 2 | 38700fbca2ee2144644377b938b4fa25d9741e7b | 674 | KotlinCoroutinKoinMvvm | Apache License 2.0 |
app/src/main/java/com/reodeveloper/marvelpay/data/room/RoomDataSource.kt | ReoDeveloper | 155,199,776 | false | null | package com.reodeveloper.marvelpay.data.room
import android.content.Context
import com.reodeveloper.common.DataSource
import com.reodeveloper.marvelpay.data.Specification
import com.reodeveloper.marvelpay.data.SpecificationBySelected
import com.reodeveloper.marvelpay.data.TwoWayMapper
import com.reodeveloper.marvelpay.domain.model.Contact
class RoomDataSource(context: Context, val mapper: TwoWayMapper<DbContact, Contact>) : DataSource<Contact> {
var database: MarvelDatabase = MarvelDatabase.getInstance(context)
override fun store(item: Contact) {
database.contactsDao().insert(mapper.reverseMap(item))
}
override fun store(items: List<Contact>) {
items.map { store(it) }
}
override fun getAll(): List<Contact> {
database.contactsDao().restorePreviousSelectedItems()
// We reset cached values, since we are asking for them now
return mapper.map(database.contactsDao().getAll().sortedBy { it.name })
}
override fun queryList(specification: Specification): List<Contact> {
return when (specification) {
is SpecificationBySelected -> {
mapper.map(database.contactsDao().querySelectedItems())
}
else -> emptyList()
}
}
override fun queryItem(specification: Specification): Contact {
throw NotImplementedError()
}
} | 0 | Kotlin | 0 | 0 | e2c22c7bc90a776b09d11e1fde94c7cea56c8a43 | 1,383 | Marvel-pay | Apache License 2.0 |
app/src/main/java/dev/yunzai/milibrary/viewmodels/SplashViewModel.kt | yunjaena | 373,853,053 | false | null | package dev.yunzai.milibrary.viewmodels
import dev.yunzai.milibrary.base.viewmodel.ViewModelBase
import dev.yunzai.milibrary.data.UserRepository
import dev.yunzai.milibrary.util.SingleLiveEvent
import dev.yunzai.milibrary.util.withThread
import io.reactivex.rxjava3.kotlin.addTo
class SplashViewModel(
private val userRepository: UserRepository
) : ViewModelBase() {
val isAutoLoginSuccessEvent = SingleLiveEvent<Boolean>()
fun checkAutoLogin() {
userRepository.refreshToken()
.withThread()
.subscribe({
isAutoLoginSuccessEvent.value = true
}, {
isAutoLoginSuccessEvent.value = false
}).addTo(compositeDisposable)
}
}
| 0 | Kotlin | 0 | 2 | 4c6774ff46c20eb53465ef64366a2ee0c90d2930 | 725 | MiliBrary_AOS | Apache License 2.0 |
comments-repo-cassandra/src/main/kotlin/com/crowdproj/comments/repo/cassandra/helpers/InstantHelper.kt | crowdproj | 508,567,511 | false | {"Kotlin": 219463, "Dockerfile": 364} | package com.crowdproj.comments.repo.cassandra.helpers
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
fun Clock.System.nowMillis() = Instant.fromEpochMilliseconds(now().toEpochMilliseconds())
| 0 | Kotlin | 2 | 1 | a7a53395d1ef7d2f655ff13c789ec76467781167 | 208 | crowdproj-comments | Apache License 2.0 |
ktor-server/src/main/kotlin/org/diploma/data/responses/RoommateProfile.kt | k-arabadzhiev | 515,181,907 | false | {"Kotlin": 309983} | package org.diploma.data.responses
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.diploma.data.user.City
import org.diploma.data.user.Interests
import org.diploma.data.user.Job
import org.diploma.data.user.School
@Serializable
data class RoommateProfile(
val id: String,
val name: String,
val photos: List<String>,
val age: Int,
val gender: Int,
@SerialName("display_budget")
val budget: Int,
val city: City,
@SerialName("has_room")
val hasRoom: Boolean,
val bio: String,
val job: Job,
val school: School,
@SerialName("user_interests")
val interests: List<Interests>,
@SerialName("last_activity_date")
val lastActivityDate: String
)
| 0 | Kotlin | 0 | 0 | e69e22d6aabffb3b4afe54cf9ef6a92007d5beb5 | 749 | Roommates | MIT License |
app/src/main/kotlin/de/ljz/questify/domain/repositories/QuestNotificationRepository.kt | LJZApps | 806,522,161 | false | {"Kotlin": 229922} | package de.ljz.questify.domain.repositories
import de.ljz.questify.domain.daos.QuestNotificationDao
import de.ljz.questify.domain.models.notifications.QuestNotificationEntity
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class QuestNotificationRepository @Inject constructor(
private val questNotificationDao: QuestNotificationDao
) : BaseRepository() {
suspend fun addQuestNotification(questNotifications: QuestNotificationEntity): Long {
return questNotificationDao.upsertQuestNotification(questNotifications)
}
} | 0 | Kotlin | 0 | 0 | dc04f195c507b4385b8df3cb034a410c253d6603 | 559 | Questify-Android | MIT License |
src/main/kotlin/dev/flavored/pistonlite/ByteBufferExt.kt | AppleFlavored | 793,831,625 | false | {"Kotlin": 9180} | package dev.flavored.pistonlite
import io.ktor.util.*
import java.nio.ByteBuffer
fun ByteBuffer.getString(): String {
val data = this.slice(position(), 64).decodeString().trimEnd()
position(position() + 64)
return data
}
fun ByteBuffer.putString(value: String) {
val data = value.padEnd(64).toByteArray()
put(data, 0, 64)
} | 0 | Kotlin | 0 | 1 | e24724cd5bdcf1c7aee858d85186d87bfab26d63 | 346 | pistonlite | MIT License |
app/src/main/java/com/worldcountries/model/country_detail/data/geo/Geography.kt | AhmetOcak | 699,314,809 | false | {"Kotlin": 99115} | package com.worldcountries.model.country_detail.data.geo
import com.google.gson.annotations.SerializedName
data class Geography(
@SerializedName("overview") val overview: String? = null,
@SerializedName("location") val location: String? = null,
@SerializedName("map_references") val mapReferences: String? = null,
@SerializedName("coastline") val coastline: Coastline? = Coastline(),
@SerializedName("climate") val climate: String? = null,
@SerializedName("terrain") val terrain: String? = null,
@SerializedName("population_distribution") val populationDistribution: String? = null
) | 0 | Kotlin | 0 | 0 | 6473ab8467d993d51c60443658cb405ff02a98c6 | 613 | WorldCountries | Apache License 2.0 |
typescript-kotlin/src/jsMain/kotlin/typescript/LogicalOperator.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6912722} | // Automatically generated - do not modify!
package typescript
sealed external interface LogicalOperator : SyntaxKind,
Union.LogicalOperator_ /* SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken */
| 0 | Kotlin | 7 | 31 | 79f2034ed9610e4416dfde5b70a0ff06f88210b5 | 214 | types-kotlin | Apache License 2.0 |
11_WebPageApp/Complete/WebPageApp/app/src/main/java/com/example/webpageapp/WebView.kt | emboss369 | 764,072,610 | false | {"Kotlin": 208338} | package com.example.webpageapp
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.viewinterop.AndroidView
@Composable
fun WebView(url: String) {
AndroidView(
factory = { context ->
android.webkit.WebView(context).apply {
webChromeClient = android.webkit.WebChromeClient()
webViewClient = android.webkit.WebViewClient()
settings.javaScriptEnabled = true
loadUrl(url)
}
}
)
}
@Preview
@Composable
fun WebViewPreview() {
WebView(url = "https://www.google.com/")
}
| 0 | Kotlin | 0 | 0 | f5097c08f483a5902c4d666712d0bdcc3bb434a8 | 592 | android-compose-book | The Unlicense |
shared/src/androidMain/kotlin/di/koinApp.android.kt | gleb-skobinsky | 634,563,581 | false | {"Kotlin": 173623, "Swift": 580, "HTML": 312, "Shell": 228, "Ruby": 101} | package di
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.startKoin
import org.koin.dsl.module
import presentation.SharedAppDataImpl
import presentation.conversation.ConversationViewModel
import presentation.drawer.DrawerViewModel
import presentation.login_screen.LoginViewModel
import presentation.profile.ProfileViewModel
actual fun startKoinApp() = startKoin {
modules(
module {
single { SharedAppDataImpl() }
single { DrawerViewModel(get()) }
viewModel { ConversationViewModel(get()) }
viewModel { LoginViewModel(get()) }
viewModel { ProfileViewModel(get()) }
}
)
} | 0 | Kotlin | 0 | 9 | 7bb13f8f074956978bd86806ec1e9c6cd65d306f | 686 | compose-connect | Apache License 2.0 |
app/src/main/java/johnnysc/github/forcepush/ui/chats/ChatsViewModel.kt | MAXCONTROLL | 618,882,645 | false | null | package johnnysc.github.forcepush.ui.chats
import androidx.lifecycle.viewModelScope
import johnnysc.github.forcepush.R
import johnnysc.github.forcepush.domain.chats.ChatDomain
import johnnysc.github.forcepush.domain.chats.ChatDomainMapper
import johnnysc.github.forcepush.domain.chats.ChatsInteractor
import johnnysc.github.forcepush.domain.chats.UserChatDomainMapper
import johnnysc.github.forcepush.ui.core.BaseViewModel
import johnnysc.github.forcepush.ui.main.NavigationCommunication
import johnnysc.github.forcepush.ui.main.NavigationUi
import johnnysc.github.forcepush.ui.search.Chat
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* @author Asatryan on 25.08.2021
*/
class ChatsViewModel(
communication: ChatsCommunication,
private val navigation: NavigationCommunication,
private val interactor: ChatsInteractor,
private val mapper: ChatDomainMapper<ChatUi>,
private val userMapper: UserChatDomainMapper<UserChatUi>,
private val dispatchersIO: CoroutineDispatcher = Dispatchers.IO,
private val dispatchersMain: CoroutineDispatcher = Dispatchers.Main,
) : BaseViewModel<ChatsCommunication, List<ChatUi>>(communication), Chat {
private val chatsMap: MutableMap<String, ChatUi> = mutableMapOf()
private val chatsRealtimeUpdateCallback = object : ChatsRealtimeUpdateCallback {
override fun updateChats(chats: List<ChatDomain>) {
viewModelScope.launch(dispatchersIO) {
chats.forEach { handleChat(it) }
val chatList = uiList()
withContext(dispatchersMain) { communication.map(chatList) }
}
}
}
private fun handleChat(chatDomain: ChatDomain) {
val chatUi: ChatUi = chatDomain.map(mapper)
if (!chatsMap.containsValue(chatUi)) chatUi.put(chatsMap)
}
private suspend fun uiList() = chatsMap.map { (userId, chatUi) ->
val userUi = interactor.userInfo(userId).map(userMapper)
chatUi.aggregatedWith(userUi)
}.sortedByDescending { it.sort() }
override fun startChatWith(userId: String) {
interactor.save(userId)
navigation.map(NavigationUi(R.id.chat_screen))
}
fun startGettingUpdates() {
interactor.startGettingUpdates(chatsRealtimeUpdateCallback)
}
fun stopGettingUpdates() {
interactor.stopGettingUpdates()
}
}
interface ChatsRealtimeUpdateCallback {
fun updateChats(chats: List<ChatDomain>)
object Empty : ChatsRealtimeUpdateCallback {
override fun updateChats(chats: List<ChatDomain>) = Unit
}
} | 0 | Kotlin | 0 | 0 | 6e953ea9602b93a3ecb9aaf582170b47108a0064 | 2,670 | ForcePush | MIT License |
godot-kotlin/src/nativeGen/kotlin/godot/VisualScriptBasicTypeConstant.kt | raniejade | 166,207,411 | false | null | // DO NOT EDIT, THIS FILE IS GENERATED FROM api.json
package godot
import gdnative.godot_method_bind
import gdnative.godot_string
import godot.core.Allocator
import godot.core.Godot
import godot.core.Variant
import godot.core.VariantArray
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.reflect.KCallable
import kotlinx.cinterop.BooleanVar
import kotlinx.cinterop.CFunction
import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.COpaquePointerVar
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.DoubleVar
import kotlinx.cinterop.IntVar
import kotlinx.cinterop.alloc
import kotlinx.cinterop.cstr
import kotlinx.cinterop.invoke
import kotlinx.cinterop.pointed
import kotlinx.cinterop.ptr
import kotlinx.cinterop.readValue
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.value
open class VisualScriptBasicTypeConstant(
@Suppress("UNUSED_PARAMETER")
__ignore: String?
) : VisualScriptNode(null) {
var basicType: Variant.Type
get() {
return getBasicType()
}
set(value) {
setBasicType(value.value)
}
var constant: String
get() {
return getBasicTypeConstant()
}
set(value) {
setBasicTypeConstant(value)
}
constructor() : this(null) {
if (Godot.shouldInitHandle()) {
_handle = __new()
}
}
fun getBasicType(): Variant.Type {
val self = this
return Allocator.allocationScope {
val _ret = alloc<IntVar>()
val _retPtr = _ret.ptr
__method_bind.getBasicType.call(self._handle, emptyList(), _retPtr)
Variant.Type.from(_ret.value)
}
}
fun getBasicTypeConstant(): String {
val self = this
return Allocator.allocationScope {
val _ret = alloc<godot_string>()
val _retPtr = _ret.ptr
checkNotNull(Godot.gdnative.godot_string_new)(_retPtr)
__method_bind.getBasicTypeConstant.call(self._handle, emptyList(), _retPtr)
_ret.toKStringAndDestroy()
}
}
fun setBasicType(name: Int) {
val self = this
return Allocator.allocationScope {
__method_bind.setBasicType.call(self._handle, listOf(name), null)
}
}
fun setBasicTypeConstant(name: String) {
val self = this
return Allocator.allocationScope {
__method_bind.setBasicTypeConstant.call(self._handle, listOf(name), null)
}
}
companion object {
internal fun __new(): COpaquePointer = Allocator.allocationScope {
val fnPtr =
checkNotNull(Godot.gdnative.godot_get_class_constructor)("VisualScriptBasicTypeConstant".cstr.ptr)
requireNotNull(fnPtr) { "No instance found for VisualScriptBasicTypeConstant" }
val fn = fnPtr.reinterpret<CFunction<() -> COpaquePointer>>()
fn()
}
/**
* Container for method_bind pointers for VisualScriptBasicTypeConstant
*/
private object __method_bind {
val getBasicType: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("VisualScriptBasicTypeConstant".cstr.ptr,
"get_basic_type".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_basic_type" }
}
val getBasicTypeConstant: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("VisualScriptBasicTypeConstant".cstr.ptr,
"get_basic_type_constant".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_basic_type_constant" }
}
val setBasicType: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("VisualScriptBasicTypeConstant".cstr.ptr,
"set_basic_type".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_basic_type" }
}
val setBasicTypeConstant: CPointer<godot_method_bind>
get() = Allocator.allocationScope {
val ptr =
checkNotNull(Godot.gdnative.godot_method_bind_get_method)("VisualScriptBasicTypeConstant".cstr.ptr,
"set_basic_type_constant".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_basic_type_constant" }
}}
}
}
| 12 | Kotlin | 4 | 51 | 5c1bb2a1f1d2187375bf50c0445b42c88f37989f | 4,342 | godot-kotlin | MIT License |
00-code(源代码)/src/com/hi/dhl/algorithms/leetcode/_707/kotlin/MyLinkedList1.kt | hi-dhl | 256,677,224 | false | null | package com.hi.dhl.algorithms.leetcode._707.kotlin
import com.hi.dhl.algorithms.model.ListNode
/**
* <pre>
* author: dhl
* date : 2020/8/13
* desc :
* </pre>
*/
class MyLinkedList1() {
/**
* 初始化
*/
var head: ListNode = ListNode(0)
var size: Int = 0
/**
* 获取指定位置的元素,找不到返回 -1
*/
fun get(index: Int): Int {
val k = index
if (k < 0 || k >= size) return -1
// 因为将伪头作为头结点,所以需要 +1 才是当前查找元素所在的结点
var cur: ListNode? = head
for (i in 0 until (k + 1)) cur = cur?.next
return cur?.`val` ?: -1
}
/**
* 在头部添加元素
*/
fun addAtHead(`val`: Int) {
addAtIndex(0, `val`)
}
/**
* 在尾部添加元素
*/
fun addAtTail(`val`: Int) {
addAtIndex(size, `val`)
}
/**
* 在指定位置插入元素
*/
fun addAtIndex(index: Int, `val`: Int) {
var k = index
if (k > size) return
if (k < 0) k = 0
// 因为有伪头结点存在,所以 i < index 找到的节点,一定是插入位置的前驱节点
var pre: ListNode? = head
for (i in 0 until k) pre = pre?.next
val node = ListNode(`val`)
node.next = pre?.next
pre?.next = node
size++
}
/**
* 删除指定位置的元素
*/
fun deleteAtIndex(index: Int) {
var k = index
if (k < 0 || k >= size) return
// 因为有伪头结点存在,所以 i < index 找到的节点,一定是插入位置的前驱节点
var pre: ListNode? = head
for (i in 0 until k) pre = pre?.next
pre?.next = pre?.next?.next
size--
}
} | 0 | Kotlin | 48 | 396 | b5e34ac9d1da60adcd9fad61da4ec82e2cefc044 | 1,526 | Leetcode-Solutions-with-Java-And-Kotlin | Apache License 2.0 |
app/src/main/java/com/gitsoft/thoughtpad/ui/settings/SettingsViewModel.kt | DenisGithuku | 366,343,331 | false | {"Kotlin": 65886} |
/*
* Copyright 2024 <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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitsoft.thoughtpad.ui.settings
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.gitsoft.thoughtpad.model.ThemeConfig
import com.gitsoft.thoughtpad.repository.UserPrefsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
data class SettingsUiState(
val selectedTheme: ThemeConfig = ThemeConfig.SYSTEM,
val isThemeDialogShown: Boolean = false,
val availableThemes: List<ThemeConfig> =
listOf(ThemeConfig.SYSTEM, ThemeConfig.LIGHT, ThemeConfig.DARK)
)
@HiltViewModel
class SettingsViewModel @Inject constructor(private val userPrefsRepository: UserPrefsRepository) :
ViewModel() {
private val _state = MutableStateFlow(SettingsUiState())
val state =
combine(_state, userPrefsRepository.userPreferencesFlow) { state, userPrefs ->
SettingsUiState(
selectedTheme = userPrefs.themeConfig,
isThemeDialogShown = state.isThemeDialogShown
)
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = SettingsUiState()
)
fun onToggleTheme(themeConfig: ThemeConfig) {
viewModelScope.launch { userPrefsRepository.updateThemeConfig(themeConfig) }
}
fun onToggleThemeDialog(isVisible: Boolean) {
_state.value = _state.value.copy(isThemeDialogShown = isVisible)
}
}
| 5 | Kotlin | 0 | 2 | fd18dbf9743c11f27fd254305ee82c2cad73364c | 2,291 | ThoughtPad | Apache License 2.0 |
app/src/main/java/com/fullrandomstudio/todosimply/ui/home/HomeScreen.kt | DamianWoroszyl | 653,764,648 | false | null | @file:OptIn(ExperimentalMaterial3Api::class)
package com.fullrandomstudio.todosimply.ui.home
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavDestination
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navOptions
import com.fullrandomstudio.designsystem.theme.TodoSimplyTheme
import com.fullrandomstudio.todosimply.ui.home.bottombar.HomeBottomBar
import com.fullrandomstudio.todosimply.ui.home.bottombar.HomeNavBarDestination
import com.fullrandomstudio.todosimply.ui.home.navigation.HOME_SCHEDULED_TASKS_ROUTE
import com.fullrandomstudio.todosimply.ui.home.navigation.homeScheduledTasks
import com.fullrandomstudio.todosimply.ui.home.navigation.navigateToHomeScheduledTasks
@Composable
fun HomeScreen(
modifier: Modifier = Modifier,
) {
val navController = rememberNavController()
val currentDestination: NavDestination? = navController
.currentBackStackEntryAsState().value?.destination
Scaffold(
modifier = modifier
.fillMaxSize(),
bottomBar = {
HomeBottomBar(
currentDestination = currentDestination,
onNavigateToDestination = { destination ->
// TODO: feature - when tapping selected destination reset state to top of the list/default tab selection
navigateToDestination(navController, destination)
}
)
}
) { paddingValues ->
NavHost(
navController = navController,
startDestination = HOME_SCHEDULED_TASKS_ROUTE,
modifier = Modifier.padding(paddingValues)
) {
homeScheduledTasks()
}
}
}
private fun navigateToDestination(
navController: NavHostController,
destination: HomeNavBarDestination
) {
val navOptions = navOptions {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
when (destination) {
HomeNavBarDestination.SCHEDULED_TASKS -> navController.navigateToHomeScheduledTasks(
navOptions
)
}
}
@Preview
@Composable
fun HomeScreenPreview() {
TodoSimplyTheme {
HomeScreen()
}
}
| 0 | Kotlin | 0 | 0 | 4bea1276c3ee0714002d195d94d02cf0491383d7 | 2,802 | todo-simply | Apache License 2.0 |
src/main/kotlin/com/coelho/noteskotlin/models/Note.kt | lucascoelhosilva | 190,426,012 | false | null | package com.coelho.noteskotlin.models
import com.fasterxml.jackson.annotation.JsonProperty
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
@Entity
data class Note(@Id
@GeneratedValue
@JsonProperty(value = "id", access = JsonProperty.Access.READ_ONLY)
val id: Long = 0L,
val title: String = "",
val description: String = "") | 0 | Kotlin | 0 | 0 | a0c2f37ffd35e3f497b2ba025735e71f566e06c9 | 457 | notesKotlin | MIT License |
src/main/kotlin/org/axonframework/intellij/ide/plugin/api/MessageCreator.kt | AxonFramework | 10,942,246 | false | {"Kotlin": 334756} | /*
* Copyright (c) 2022. Axon Framework
*
* 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.axonframework.intellij.ide.plugin.api
/**
* Represents an element that creates a message (payload).
*
* @see org.axonframework.intellij.ide.plugin.resolving.MessageCreationResolver
*/
interface MessageCreator : PsiElementWrapper {
/**
* The name of the payload being created. For deadlines, this is the deadlineName. For all other messages,
* it's the payload type.
*/
val payload: String
/**
* The parent handler that published the message. For example, if this MessageCreator represents an event
* created by a CommandHandler, the parentHandler will be that CommandHandler.
* The same applied for commands created by a SagaEventHandler, among others.
*/
val parentHandler: Handler?
}
| 22 | Kotlin | 20 | 34 | 46e26f26c83d14fb19b3873b66e5f2d5b540e736 | 1,370 | IdeaPlugin | Apache License 2.0 |
src/test/kotlin/com/yearsaday/qna/repository/QuestionAnswerMappingTest.kt | reavil01 | 411,887,886 | false | {"Kotlin": 37286, "JavaScript": 12733, "HTML": 1726, "CSS": 930} | package com.yearsaday.qna.repository
import com.yearsaday.qna.spring.entity.AnswerEntity
import com.yearsaday.qna.spring.entity.QuestionEntity
import com.yearsaday.qna.spring.repository.AnswerRepository
import com.yearsaday.qna.spring.repository.QuestionRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.test.context.web.WebAppConfiguration
import java.time.LocalDateTime
@WebAppConfiguration
@DataJpaTest
class QuestionAnswerMappingTest {
@Autowired
private lateinit var answerRepository: AnswerRepository
@Autowired
private lateinit var questionRepository: QuestionRepository
@BeforeEach
fun cleanUp() {
answerRepository.deleteAll()
questionRepository.deleteAll()
}
@Test
fun mappingTest() {
// given
val question = QuestionEntity(
0,
"질문1",
LocalDateTime.now().monthValue,
LocalDateTime.now().dayOfMonth
)
val answer = AnswerEntity(0, "답변1", question)
// when
val savedQuestion = questionRepository.save(question)
val savedAnswer = answerRepository.save(answer)
// then
assertThat(savedQuestion.id).isEqualTo(savedAnswer.question.id)
assertThat(savedQuestion.sentence).isEqualTo(savedAnswer.question.sentence)
}
@Test
fun mappingDeleteTest() {
// given
val question = QuestionEntity(
0,
"질문1",
LocalDateTime.now().monthValue,
LocalDateTime.now().dayOfMonth
)
val answer = AnswerEntity(0, "답변1", question)
questionRepository.save(question)
val savedAnswer = answerRepository.save(answer)
// when
answerRepository.delete(savedAnswer)
// then
assertThat(answerRepository.findAll().size).isEqualTo(0)
}
} | 0 | Kotlin | 0 | 0 | 694c38404839e387c4015635c9493c74a4c9e3b1 | 2,082 | qna-5years-a-day | Apache License 2.0 |
src/main/kotlin/com/deflatedpickle/mmf/util/ModelDisplay.kt | DeflatedPickle | 346,462,107 | false | null | /* Copyright (c) 2021 DeflatedPickle under the MIT license */
package com.deflatedpickle.mmf.util
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@ExperimentalSerializationApi
@Serializable
data class ModelDisplay(
val head: DisplayElement? = null,
val gui: DisplayElement? = null,
val ground: DisplayElement? = null,
val fixed: DisplayElement? = null,
val display: DisplayElement? = null,
@SerialName("firstperson_lefthand")
val firstPersonLeftHand: DisplayElement? = null,
@SerialName("firstperson_righthand")
val firstPersonRightHand: DisplayElement? = null,
@SerialName("thirdperson_lefthand")
val thirdPersonLeftHand: DisplayElement? = null,
@SerialName("thirdperson_righthand")
val thirdPersonRightHand: DisplayElement? = null,
@SerialName("__comment")
val comment: String = ""
)
| 0 | Kotlin | 0 | 0 | 908f416527c90e28041871cd281aae3be7668aa7 | 941 | mmf | MIT License |
Builders/String and map builders/src/Task.kt | iVieL | 258,301,450 | false | null | import java.util.HashMap
fun buildMap(map: HashMap<Int, String>.() -> Unit): HashMap<Int, String> {
val mapBuilder = HashMap<Int, String>()
mapBuilder.map()
return mapBuilder
}
fun usage(): Map<Int, String> {
return buildMap {
put(0, "0")
for (i in 1..10) {
put(i, "$i")
}
}
}
| 0 | Kotlin | 0 | 0 | 8d9cb9b46975f41c1462289e3546ed6a05e3c5d1 | 335 | kotlin-koans | MIT License |
app/src/main/java/com/example/saferdriving/dataclasses/BasicInfo.kt | 2rius | 750,328,069 | false | {"Kotlin": 79065} | package com.example.saferdriving.dataclasses
data class BasicInfo(
var age: Int? = null,
var drivingExperience: Int? = null,
var residenceCity: String? = null,
var job: String? = null
)
| 4 | Kotlin | 0 | 0 | d8f041e1babac63918b93b4b55ef3ec596f8bbe9 | 203 | safer-driving | MIT License |
platform/platform-impl/src/com/intellij/openapi/components/service.kt | SerCeMan | 39,251,104 | true | {"Text": 1972, "XML": 4051, "Ant Build System": 22, "Shell": 27, "Markdown": 7, "Ignore List": 19, "Git Attributes": 4, "Batchfile": 20, "Java": 47468, "Java Properties": 81, "HTML": 2353, "Groovy": 2144, "Kotlin": 133, "JavaScript": 37, "JFlex": 31, "XSLT": 109, "desktop": 2, "Python": 6462, "INI": 174, "C#": 32, "Smalltalk": 14, "Rich Text Format": 2, "JSON": 154, "CoffeeScript": 3, "CSS": 41, "J": 18, "Protocol Buffer": 2, "JAR Manifest": 6, "Gradle": 23, "E-mail": 18, "Roff": 38, "Roff Manpage": 1, "Gherkin": 4, "Diff": 12, "Maven POM": 1, "Checksums": 42, "Java Server Pages": 24, "C": 34, "AspectJ": 2, "Perl": 3, "HLSL": 2, "Erlang": 1, "Scala": 1, "Ruby": 2, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 9, "Microsoft Visual Studio Solution": 8, "C++": 18, "Objective-C": 9, "OpenStep Property List": 2, "NSIS": 15, "Vim Script": 1, "Emacs Lisp": 1, "Yacc": 1, "ActionScript": 1, "TeX": 4, "reStructuredText": 39, "Gettext Catalog": 125, "Jupyter Notebook": 4, "YAML": 1, "Regular Expression": 9} | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.openapi.components
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.project.Project
public inline fun <reified T: Any> service(): T? = ServiceManager.getService(javaClass<T>())
public inline fun <reified T: Any> Project.service(): T? = ServiceManager.getService(this, javaClass<T>())
public val ComponentManager.stateStore: IComponentStore
get() = getPicoContainer().getComponentInstance(javaClass<IComponentStore>()) as IComponentStore | 0 | Java | 0 | 0 | 060f2ac4c6c93e92cff266a60d67b972d09ab464 | 1,110 | intellij-community | Apache License 2.0 |
boxicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/boxicons/boxicons/solid/BxsMessageCheck.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.boxicons.boxicons.solid
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.boxicons.boxicons.SolidGroup
public val SolidGroup.BxsMessageCheck: ImageVector
get() {
if (_bxsMessageCheck != null) {
return _bxsMessageCheck!!
}
_bxsMessageCheck = Builder(name = "BxsMessageCheck", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(20.0f, 2.0f)
lineTo(4.0f, 2.0f)
curveToRelative(-1.103f, 0.0f, -2.0f, 0.894f, -2.0f, 1.992f)
verticalLineToRelative(12.016f)
curveTo(2.0f, 17.106f, 2.897f, 18.0f, 4.0f, 18.0f)
horizontalLineToRelative(3.0f)
verticalLineToRelative(4.0f)
lineToRelative(6.351f, -4.0f)
lineTo(20.0f, 18.0f)
curveToRelative(1.103f, 0.0f, 2.0f, -0.894f, 2.0f, -1.992f)
lineTo(22.0f, 3.992f)
arcTo(1.998f, 1.998f, 0.0f, false, false, 20.0f, 2.0f)
close()
moveTo(11.0f, 13.914f)
lineTo(7.293f, 10.207f)
lineTo(8.707f, 8.793f)
lineTo(11.0f, 11.086f)
lineToRelative(4.793f, -4.793f)
lineToRelative(1.414f, 1.414f)
lineTo(11.0f, 13.914f)
close()
}
}
.build()
return _bxsMessageCheck!!
}
private var _bxsMessageCheck: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 2,279 | compose-icon-collections | MIT License |
src/main/kotlin/academy/jairo/ktor/adapter/factory/DatabaseFactory.kt | jairosoares | 723,457,254 | false | {"Kotlin": 22728} | package academy.jairo.ktor.adapter.factory
import org.jetbrains.exposed.sql.Database
interface DatabaseFactory {
fun create(): Database
} | 0 | Kotlin | 0 | 0 | a339559d4957c193a7db16209f58b40dcc8272a4 | 143 | ktor-lab | MIT License |
app/src/main/java/com/cleanarch/features/wikientry/WikiEntryComponent.kt | nareshidiga | 507,351,310 | false | {"Kotlin": 28835} | package com.cleanarch.features.wikientry
import com.cleanarch.app.AppComponent
import com.cleanarch.features.wikientry.presentation.WikiEntryViewModel
import dagger.Component
/*
* Copyright (C) 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@WikiEntryScope
@Component(modules = [WikiEntryModule::class], dependencies = [AppComponent::class])
interface WikiEntryComponent {
fun inject(target: WikiEntryViewModel)
} | 0 | Kotlin | 0 | 5 | ee359def4acac4c347868000475648a611c38289 | 949 | Android-CleanArchitecture-Kotlin-Coroutines-Flow | Apache License 2.0 |
EarthGardener/app/src/main/java/team/gdsc/earthgardener/presentation/user/login/LoginActivity.kt | EarthGardener | 454,439,830 | false | {"Kotlin": 10400} | package team.gdsc.earthgardener.presentation.user.login
import android.content.ContentValues.TAG
import android.content.Intent
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.Observer
import com.kakao.sdk.auth.model.OAuthToken
import com.kakao.sdk.user.UserApiClient
import org.koin.androidx.viewmodel.ext.android.viewModel
import team.gdsc.earthgardener.R
import team.gdsc.earthgardener.data.model.request.signin.ReqSignInSuccessData
import team.gdsc.earthgardener.databinding.ActivityLoginBinding
import team.gdsc.earthgardener.presentation.main.MainActivity
import team.gdsc.earthgardener.presentation.base.BaseActivity
import team.gdsc.earthgardener.presentation.user.login.viewModel.SignInViewModel
import team.gdsc.earthgardener.presentation.user.signup.SignUpActivity
import java.util.regex.Pattern
class LoginActivity : BaseActivity<ActivityLoginBinding>(R.layout.activity_login) {
private val signInViewModel: SignInViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
btnLoginEvent()
navigateToSignUp()
observeSignIn()
btnKakaoLoginEvent()
checkKakaoLogin()
}
private fun btnLoginEvent(){
binding.btnLogin.setOnClickListener {
if(checkEmailPattern()){
val email = binding.etLoginEmail.text.toString().trim()
val pw = binding.etLoginPw.text.toString().trim()
showLoadingDialog(this)
// Post Login
signInViewModel.postSignIn(ReqSignInSuccessData(email, pw))
}else{
Toast.makeText(this, "이메일 형식에 맞추어 작성해주세요", Toast.LENGTH_SHORT).show()
}
}
}
private fun navigateToSignUp(){
binding.tvLoginSignUp.setOnClickListener {
startActivity(Intent(this, SignUpActivity::class.java))
}
}
private fun navigateToMain(){
startActivity(Intent(this, MainActivity::class.java))
finish()
}
private fun observeSignIn(){
signInViewModel.signInStatus.observe(this) {
dismissLoadingDialog()
if (it == 200) {
Toast.makeText(this, "로그인 성공", Toast.LENGTH_SHORT).show()
navigateToMain()
} else if (it == 401) {
Toast.makeText(this, "이메일 또는 비밀번호 오류", Toast.LENGTH_SHORT).show()
}
}
}
private fun checkEmailPattern(): Boolean {
val email = binding.etLoginEmail.text.toString().trim()
val emailValidation =
"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"
return Pattern.matches(emailValidation, email)
}
private fun btnKakaoLoginEvent(){
val callback: (OAuthToken?, Throwable?) -> Unit = { token, error ->
if(error != null){
Log.d("login", "정보 없음")
}else{
Log.d("login", "카카오톡 로그인에 성공")
UserApiClient.instance.me{ user, error ->
Log.d("id", user?.id.toString())
Log.d("nickname", user?.kakaoAccount?.profile?.nickname.toString())
Log.d("email", user?.kakaoAccount?.email.toString())
Log.d("image_url", user?.kakaoAccount?.profile?.profileImageUrl.toString())
}
// post 보내고 성공하면 아래 코드 실행
/*
Toast.makeText(this, "로그인 성공", Toast.LENGTH_SHORT).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
finish()
*/
}
}
binding.btnKakaoLogin.setOnClickListener {
if(UserApiClient.instance.isKakaoTalkLoginAvailable(this)){
UserApiClient.instance.loginWithKakaoTalk(this, callback = callback)
}else{
UserApiClient.instance.loginWithKakaoAccount(this, callback = callback)
}
/*
//회원 탈퇴 - 임시
UserApiClient.instance.unlink { error ->
if(error != null){
Toast.makeText(this, "회원 탈퇴 실패", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(this, "회원 탈퇴 성공", Toast.LENGTH_SHORT).show()
}
}
*/
}
}
private fun checkKakaoLogin(){
UserApiClient.instance.accessTokenInfo{ tokenInfo, error ->
if(error != null){
Toast.makeText(this, "로그인 정보 없음", Toast.LENGTH_SHORT).show()
}else if(tokenInfo != null){
// main으로 넘어가기
val intent = Intent(this, MainActivity::class.java)
startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
finish()
}
}
}
} | 20 | Kotlin | 0 | 1 | a06cbf7c45ea2181475a0fccd8c77f04cee58970 | 5,084 | EarthGardener-Android | MIT License |
android/app/src/main/kotlin/com/example/github_search_flutter_client_rxdart_example/MainActivity.kt | bizz84 | 261,154,385 | false | null | package com.example.github_search_flutter_client_rxdart_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 1 | Dart | 25 | 39 | fc6f098299da4982813389e0291b506e02838a9a | 160 | github_search_flutter_client_rxdart_example | MIT License |
paging/src/commonMain/kotlin/dev/icerock/moko/paging/LiveDataExt.kt | icerockdev | 241,032,010 | false | null | /*
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.paging
import dev.icerock.moko.mvvm.livedata.LiveData
import dev.icerock.moko.mvvm.livedata.map
import dev.icerock.moko.mvvm.livedata.mergeWith
fun <T> LiveData<List<T>>.withLoadingItem(
loading: LiveData<Boolean>,
itemFactory: () -> T
):
LiveData<List<T>> = mergeWith(loading) { items, nextPageLoading ->
if (nextPageLoading) {
items + itemFactory()
} else {
items
}
}
fun <T> LiveData<List<T>>.withReachEndNotifier(action: (Int) -> Unit):
LiveData<ReachEndNotifierList<T>> = map {
it.withReachEndNotifier(action)
}
| 3 | Kotlin | 4 | 14 | 1bdd5dbce25c270e4aac5bdd45b4c9e2582ca8f3 | 707 | moko-paging | Apache License 2.0 |
src/main/kotlin/io/slama/utils/command_permissions.kt | eKonis-src | 467,679,930 | true | {"Kotlin": 83429} | package io.slama.utils
import io.slama.core.BotConfiguration
import net.dv8tion.jda.api.entities.Member
fun Member.isAdmin(): Boolean =
BotConfiguration.guilds[guild.idLong]?.let { config ->
roles.map { it.idLong }.any { it == config.roles.adminRoleID }
} ?: false
fun Member.isManager(): Boolean =
isAdmin() || BotConfiguration.guilds[guild.idLong]?.let { config ->
roles.map { it.idLong }.any { it == config.roles.managerRoleID }
} ?: false
fun Member.isTeacher(): Boolean =
isManager() || BotConfiguration.guilds[guild.idLong]?.let { config ->
roles.map { it.idLong }.any { it == config.roles.teacherRoleID }
} ?: false
fun Member.isStudent(): Boolean =
BotConfiguration.guilds[guild.idLong]?.let { config ->
roles.map { it.idLong }.any { it == config.roles.studentRoleID }
} ?: false
| 0 | Kotlin | 0 | 0 | a0b293f20f175f36035778dba6f3eeb70946727d | 857 | UGE-Bot-1 | MIT License |
app/src/main/java/ru/maxim/unsplash/persistence/dao/UserDao.kt | maximborodkin | 406,747,572 | false | {"Kotlin": 242939} | package ru.maxim.unsplash.persistence.dao
import androidx.room.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.firstOrNull
import ru.maxim.unsplash.persistence.model.UserEntity
import ru.maxim.unsplash.persistence.model.UserEntity.UserContract
@Dao
abstract class UserDao {
@Query("SELECT * FROM ${UserContract.tableName}")
abstract fun getAll(): Flow<List<UserEntity>>
@Query(
"SELECT * FROM ${UserContract.tableName} WHERE ${UserContract.Columns.username}=:username"
)
abstract fun getByUsername(username: String): Flow<UserEntity?>
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract suspend fun insert(userEntity: UserEntity)
open suspend fun insertOrUpdate(userEntity: UserEntity) {
if (getByUsername(userEntity.username).catch { }.firstOrNull() != null) {
update(userEntity)
} else {
insert(userEntity)
}
}
@Update(entity = UserEntity::class)
abstract suspend fun update(userEntity: UserEntity)
@Delete
abstract suspend fun delete(userEntity: UserEntity)
} | 0 | Kotlin | 0 | 2 | 06a7d3fb24badae12d42d1a6c45666434ec34d73 | 1,143 | kts-android-unsplash | MIT License |
app/src/main/java/com/petzinger/magalu/network/GitHubApi.kt | PetzingerLucas | 860,656,363 | false | {"Kotlin": 31828} | package com.petzinger.magalu.network
import com.petzinger.magalu.model.pullrequest.PullRequest
import com.petzinger.magalu.model.repository.RepositoryResponse
import io.reactivex.rxjava3.core.Single
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface GitHubApi {
@GET("search/repositories")
fun getRepositories(
@Query("q") language: String,
@Query("sort") sort: String,
@Query("page") page: Int
): Single<RepositoryResponse>
@GET("repos/{owner}/{repo}/pulls")
fun getPullRequests(
@Path("owner") owner: String,
@Path("repo") repo: String
): Single<List<PullRequest>>
} | 0 | Kotlin | 0 | 0 | 37487dc60fee6ecea55f212f2c6abe416a7c84c6 | 675 | Teste-Magalu | MIT License |
kotlin-audio-pro/src/main/java/co/evergrace/kotlinaudiopro/players/components/MediaItemExt.kt | evergrace-co | 843,264,852 | false | {"Kotlin": 173698} | package co.evergrace.kotlinaudiopro.players.components
import co.evergrace.kotlinaudiopro.models.AudioItemHolder
import com.google.android.exoplayer2.MediaItem
fun MediaItem.getAudioItemHolder(): AudioItemHolder {
return localConfiguration!!.tag as AudioItemHolder
}
| 0 | Kotlin | 0 | 0 | 845f0d5e440c534cadafeb1dfa21a14d437bf0e4 | 273 | kotlin-audio-pro | Apache License 2.0 |
threejs/src/main/kotlin/three/helpers/GridHelper.kt | Pozo | 91,019,368 | false | null | @file:JsQualifier("THREE")
package three.helpers
import three.objects.Line
@JsName("GridHelper")
external class GridHelper : Line {
constructor(size: Int)
constructor(size: Int, divisions: Int)
constructor(size: Int, divisions: Int, colorCenterLine: Int)
constructor(size: Int, divisions: Int, colorCenterLine: Int, colorGrid: Int)
}
| 0 | Kotlin | 2 | 15 | a53df48f15f633deba31467e33aa798b453104fc | 355 | threejs-kotlin | MIT License |
kotlin-electron/src/jsMain/generated/electron/HidDeviceRemovedDetails.kt | JetBrains | 93,250,841 | false | {"Kotlin": 11411371, "JavaScript": 154302} | package electron
typealias HidDeviceRemovedDetails = electron.core.HidDeviceRemovedDetails
| 28 | Kotlin | 173 | 1,250 | 9e9dda28cf74f68b42a712c27f2e97d63af17628 | 93 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/com/developersancho/qnbmovie/di/AppModule.kt | developersancho | 275,271,253 | false | null | package com.developersancho.qnbmovie.di
import com.developersancho.local.di.localModule
import com.developersancho.manager.di.managerModule
import com.developersancho.qnbmovie.BuildConfig
import com.developersancho.remote.di.remoteModule
val appModule = listOf(
remoteModule(
baseUrl = BuildConfig.BASE_URL,
isDebug = BuildConfig.DEBUG
),
localModule(dbName = BuildConfig.DB_NAME),
viewModelModule,
managerModule
) | 0 | Kotlin | 0 | 5 | 043b0f3a5763fa6998384c06821122ddf6a72e5e | 452 | qnbmovie | Apache License 2.0 |
src/es/monarcamanga/src/eu/kanade/tachiyomi/extension/es/monarcamanga/Visormonarca.kt | komikku-app | 720,497,299 | false | {"Kotlin": 6775539, "JavaScript": 2160} | package eu.kanade.tachiyomi.extension.es.monarcamanga
import eu.kanade.tachiyomi.multisrc.madara.Madara
import java.text.SimpleDateFormat
import java.util.Locale
class Visormonarca : Madara(
"Visormonarca",
"https://visormonarca.com",
"es",
SimpleDateFormat("MMM d, yyy", Locale("es")),
) {
override val useNewChapterEndpoint = true
}
| 22 | Kotlin | 8 | 97 | 7fc1d11ee314376fe0daa87755a7590a03bc11c0 | 357 | komikku-extensions | Apache License 2.0 |
src/main/kotlin/bvanseg/kotlincommons/throwable/ThrowableExtentions.kt | AlexCouch | 281,023,717 | false | null | package bvanseg.kotlincommons.throwable
import java.io.PrintWriter
import java.io.StringWriter
/**
* Returns this [Throwable] as a String with the error and stack trace.
*
* @author bright_spark
* @since 2.2.5
*/
fun Throwable.printToString(): String = StringWriter().use { sw ->
PrintWriter(sw).use { pw ->
this.printStackTrace(pw)
sw.toString()
}
}
/**
* Returns this [Throwable] as an [ExceptionAnalysis] which provides a breakdown of the exception.
*
* @author bright_spark
* @since 2.2.5
*/
fun Throwable.analyse() = ExceptionAnalysis(this)
| 0 | Kotlin | 0 | 0 | aa619625e10cc1c0c8faaa16d12cf9e35a827d8e | 583 | KotlinCommons | MIT License |
app/src/androidTest/java/dev/m13d/somenet/timeline/TimelineScreenTest.kt | 3yebMB | 851,249,108 | false | {"Kotlin": 80851} | package dev.m13d.somenet.timeline
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import dev.m13d.somenet.MainActivity
import dev.m13d.somenet.domain.exceptions.BackendException
import dev.m13d.somenet.domain.exceptions.ConnectionUnavailableException
import dev.m13d.somenet.domain.post.InMemoryPostsCatalog
import dev.m13d.somenet.domain.post.OfflinePostCatalog
import dev.m13d.somenet.domain.post.Post
import dev.m13d.somenet.domain.post.PostsCatalog
import dev.m13d.somenet.domain.post.UnavailablePostCatalog
import kotlinx.coroutines.delay
import org.junit.After
import org.junit.Rule
import org.junit.Test
import org.koin.core.context.loadKoinModules
import org.koin.dsl.module
class TimelineScreenTest {
@get:Rule
val timelineTestRule = createAndroidComposeRule<MainActivity>()
@Test
fun showEmptyTimelineMessage() {
val email = "[email protected]"
val password = "p@S\$w0rd="
launchTimelineFor(email, password, timelineTestRule) {
// No operations
} verify {
emptyTimelineMessageIsShown()
}
}
@Test
fun showAvailablePosts() {
val email = "[email protected]"
val password = "B@rb24A89"
val post1 = Post("post1", "samanthaId", "This is Samantha's first post", 1L)
val post2 = Post("post2", "samanthaId", "This is Samantha's second post", 2L)
replacePostCatalogWith(InMemoryPostsCatalog(listOf(post1, post2)))
launchTimelineFor(email, password, timelineTestRule) {
} verify {
postsAreDisplayed(post1, post2)
}
}
@Test
fun openPostComposer() {
launchTimelineFor("[email protected]", "\\S0meP@sS1134", timelineTestRule) {
tapOnCreateNewPost()
} verify {
newPostComposerIsDisplayed()
}
}
@Test
fun showLoadingIndicator() {
replacePostCatalogWith(DelayingPostCatalog())
launchTimelineFor("[email protected]", "\\S0meP@sS1134", timelineTestRule) {
//no operations
} verify {
loadingIndicatorIsDisplayed()
}
}
@Test
fun showBackendError() {
replacePostCatalogWith(UnavailablePostCatalog())
launchTimelineFor("[email protected]", "\\S0meP@sS1134", timelineTestRule) {
//no operations
} verify {
backendErrorIsDisplayed()
}
}
@Test
fun showOfflineError() {
replacePostCatalogWith(OfflinePostCatalog())
launchTimelineFor("[email protected]", "\\S0meP@sS1134", timelineTestRule) {
//no operations
} verify {
offlineErrorIsDisplayed()
}
}
@After
fun tearDown() {
replacePostCatalogWith(InMemoryPostsCatalog())
}
private fun replacePostCatalogWith(postsCatalog: PostsCatalog) {
val replaceModule = module {
factory<PostsCatalog> { postsCatalog }
}
loadKoinModules(replaceModule)
}
class DelayingPostCatalog : PostsCatalog {
override suspend fun postsFor(userIds: List<String>): List<Post> {
delay(2000L)
return emptyList()
}
override suspend fun addPost(userId: String, postText: String): Post {
TODO("Not yet implemented")
}
}
}
| 1 | Kotlin | 0 | 0 | 1170d91ea7bac5d2483b7b735f904fda0dbe222c | 3,361 | Some-network | The Unlicense |
browser-kotlin/src/jsMain/kotlin/webrtc/RTCRtcpMuxPolicy.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6149909} | // Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package webrtc
// language=JavaScript
@JsName("""(/*union*/{require: 'require'}/*union*/)""")
sealed external interface RTCRtcpMuxPolicy {
companion object {
val require: RTCRtcpMuxPolicy
}
}
| 0 | Kotlin | 6 | 26 | 3fcfd2c61da8774151cf121596e656cc123b37db | 350 | types-kotlin | Apache License 2.0 |
kairo-sample/src/main/kotlin/kairoSample/entity/libraryCard/LibraryCardMapper.kt | hudson155 | 874,399,885 | false | {"Kotlin": 71596, "PLpgSQL": 159} | package kairoSample.entity.libraryCard
import com.google.inject.Inject
import kairo.id.KairoIdGenerator
internal class LibraryCardMapper @Inject constructor(
idGenerator: KairoIdGenerator.Factory,
) {
private val idGenerator: KairoIdGenerator = idGenerator.withPrefix("library_card")
internal fun map(model: LibraryCardModel): LibraryCardRep =
LibraryCardRep(
id = model.id,
libraryMemberId = model.libraryMemberId,
)
internal fun map(creator: LibraryCardRep.Creator): LibraryCardModel.Creator =
LibraryCardModel.Creator(
id = idGenerator.generate(),
libraryMemberId = creator.libraryMemberId,
)
}
| 0 | Kotlin | 0 | 1 | 074a487893faafacfd3e24e3e34b1e217ca9458c | 650 | kairo-sample | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/webrtc/RTCSdpType.kt | karakum-team | 393,199,102 | false | {"Kotlin": 7083457} | // Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package webrtc
// language=JavaScript
@JsName("""(/*union*/{answer: 'answer', offer: 'offer', pranswer: 'pranswer', rollback: 'rollback'}/*union*/)""")
sealed external interface RTCSdpType {
companion object {
val answer: RTCSdpType
val offer: RTCSdpType
val pranswer: RTCSdpType
val rollback: RTCSdpType
}
}
| 0 | Kotlin | 6 | 26 | 3ca49a8f44fc8b46e393ffe66fbd81f8b4943c18 | 491 | types-kotlin | Apache License 2.0 |
.teamcity/_self/release/buildTypes/BuildAndTestReleaseCandidate.kt | ValerieRobateau | 392,394,102 | true | {"C#": 747399, "TSQL": 710923, "Kotlin": 20317, "PLpgSQL": 7162, "PowerShell": 4859} | package _self.release.buildTypes
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.vcs
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.dotnetPublish
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.powerShell
object BuildAndTestReleaseCandidate : BuildType({
templates(_self.templates.BuildAndTestNetCoreApplication)
name = "Build and Test Release Candidate"
params {
param("BranchToBuild", "master")
}
triggers {
vcs {
id = "vcsTrigger"
enabled = false
branchFilter = "+:refs/heads/master"
}
}
}) | 0 | C# | 0 | 0 | f903f996f1c28fe00bf179f713cf1386590c5d05 | 680 | Ed-Fi-Analytics-Middle-Tier | Apache License 2.0 |
presentation-planner/src/main/java/com/jacekpietras/zoo/planner/viewmodel/PlannerViewModel.kt | JacekPietras | 334,416,736 | false | null | package com.jacekpietras.zoo.planner.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.map
import com.jacekpietras.zoo.core.dispatcher.launchInBackground
import com.jacekpietras.zoo.core.extensions.NullSafeMutableLiveData
import com.jacekpietras.zoo.core.extensions.reduceOnMain
import com.jacekpietras.zoo.domain.feature.planner.interactor.ObserveCurrentPlanUseCase
import com.jacekpietras.zoo.planner.mapper.PlannerStateMapper
import com.jacekpietras.zoo.planner.model.PlannerState
import com.jacekpietras.zoo.planner.model.PlannerViewState
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
internal class PlannerViewModel(
stateMapper: PlannerStateMapper,
observeCurrentPlanUseCase: ObserveCurrentPlanUseCase,
) : ViewModel() {
private val state = NullSafeMutableLiveData(PlannerState())
var viewState: LiveData<PlannerViewState> = state.map(stateMapper::from)
init {
launchInBackground {
observeCurrentPlanUseCase.run()
.onEach {
state.reduceOnMain {
copy(
plan = it.stages.map { it.animals.joinToString() }
)
}
}
.launchIn(this)
}
}
} | 0 | Kotlin | 0 | 1 | 07474546a9dbfc0263126b59933086b38d41b7e1 | 1,345 | ZOO | MIT License |
app/src/test/java/com/example/apodgallery/FavoriteApodTest.kt | jhonybguerra | 738,729,723 | false | {"Kotlin": 29687} | package com.example.apodgallery
import com.example.apodgallery.model.db.FavoriteApod
import com.example.apodgallery.model.network.ApodResponse
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class FavoriteApodTest {
@Test
fun `convert ApodResponse to FavoriteApod correctly`() {
val apodResponse = ApodResponse(
"Title",
"2023-01-01",
"Explanation test",
"https://example.com/image.jpg")
val expectedResponse = FavoriteApod(
title = "Title",
date = "2023-01-01",
explanation = "Explanation test",
url = "https://example.com/image.jpg")
val result = FavoriteApod.fromApodResponseToFavoriteApod(apodResponse)
assertEquals(expectedResponse, result)
}
} | 0 | Kotlin | 0 | 1 | 96e320c6e6406fa51625972409612157141d5346 | 957 | ApodGallery | Apache License 2.0 |
mongo-migration-stream-core/src/main/kotlin/pl/allegro/tech/mongomigrationstream/core/validation/MongoToolsValidator.kt | allegro | 551,426,608 | false | {"Kotlin": 226498} | package pl.allegro.tech.mongomigrationstream.core.validation
import io.github.oshai.kotlinlogging.KotlinLogging
import io.github.oshai.kotlinlogging.withLoggingContext
import pl.allegro.tech.mongomigrationstream.configuration.ApplicationProperties
import java.nio.file.Paths
import kotlin.io.path.exists
import kotlin.io.path.isExecutable
private val logger = KotlinLogging.logger { }
internal class MongoToolsValidator(private val applicationProperties: ApplicationProperties) : Validator {
private fun check(binary: String): Boolean {
withLoggingContext("binary" to binary) {
val binaryPath = Paths.get(applicationProperties.performerProperties.mongoToolsPath).resolve(binary)
return if (binaryPath.exists() && binaryPath.isExecutable()) {
logger.info { "$binary at $binaryPath exists and is executable" }
true
} else {
logger.error { "$binary at $binaryPath doesn't exist or isn't executable" }
false
}
}
}
override fun validate(): ValidationResult {
val mongoDump = check("mongodump")
val mongoRestore = check("mongorestore")
return if (mongoDump && mongoRestore) {
ValidationSuccess
} else {
ValidationFailure("MongoDB tools installation isn't working or doesn't exist")
}
}
}
| 11 | Kotlin | 3 | 33 | 296127bc8629d850ba064bfbd79f8e4178e49477 | 1,395 | mongo-migration-stream | Apache License 2.0 |
src/test/kotlin/me/benjozork/kson/parser/value/JsonNumberValueParserTest.kt | Benjozork | 156,921,876 | false | null | package me.benjozork.kson.parser.value
import me.benjozork.kson.parser.exception.IllegalJsonNumberTokenException
import me.benjozork.kson.parser.exception.IllegalJsonNumberValueException
import me.benjozork.kson.parser.JsonReader
import org.junit.Test
import org.junit.Assert.assertEquals
class JsonNumberValueParserTest {
@Test
fun intNumberTest() {
val shouldSucceed = mapOf (
"255" to 255,
"-21" to -21,
"0" to 0
)
shouldSucceed.forEach { source, actual ->
val result = JsonNumberValueParser.read(JsonReader(source))
assertEquals(actual, result)
assertEquals(Int::class, result::class)
}
}
@Test
fun doubleNumberTest() {
val shouldSucceed = mapOf (
"50.5" to 50.5,
"-2.29" to -2.29,
"0.0" to 0.0
)
shouldSucceed.forEach { source, actual ->
val result = JsonNumberValueParser.read(JsonReader(source))
assertEquals(actual, result)
assertEquals(Double::class, result::class)
}
}
@Test
fun exponentNumberTest() {
val shouldSucceed = mapOf (
"255e7" to 255e7,
"255E7" to 255e7,
"255e+7" to 255e7,
"255E+7" to 255e7,
"255e-7" to 255e-7,
"255E-7" to 255e-7
)
shouldSucceed.forEach { source, actual ->
val result = JsonNumberValueParser.read(JsonReader(source))
assertEquals(actual, result)
assertEquals(Double::class, result::class)
}
}
@Test
fun exponentDoubleNumberTest() {
val shouldSucceed = mapOf (
"255.25e7" to 255.25e7,
"255.56E7" to 255.56e7,
"255.75e+7" to 255.75e7,
"255.96E+7" to 255.96e7,
"255.13e-7" to 255.13e-7,
"255.01E-7" to 255.01e-7
)
shouldSucceed.forEach { source, actual ->
val result = JsonNumberValueParser.read(JsonReader(source))
assertEquals(actual, result)
assertEquals(Double::class, result::class)
}
}
@Test(expected = IllegalJsonNumberValueException::class)
fun numberFailDoesNotMatchRegexTest() {
val shouldFail = arrayOf("12ee.", "1+e", "0-", "1+", "e", "0E", "1e123", "e7", "E7", "e-7", "E-7")
shouldFail.forEach { JsonNumberValueParser.read(JsonReader(it)) }
}
@Test(expected = IllegalJsonNumberTokenException::class)
fun numberFailIllegalTokenTest() {
val shouldFail = arrayOf("12ae.", "e1nne", "0=", "1+", "e", "aE", "aaa")
shouldFail.forEach { JsonNumberValueParser.read(JsonReader(it)) }
}
} | 0 | Kotlin | 0 | 0 | 9b52b262e1bf1ca2663faaca34c86ac2f73b451a | 2,760 | kson | MIT License |
core/src/main/kotlin/gropius/dto/input/issue/RemoveAssignmentInput.kt | ccims | 487,996,394 | false | null | package gropius.dto.input.issue
import com.expediagroup.graphql.generator.annotations.GraphQLDescription
import com.expediagroup.graphql.generator.scalars.ID
import gropius.dto.input.common.Input
@GraphQLDescription("Input for the removeAssignment mutations")
class RemoveAssignmentInput(
@GraphQLDescription("The id of the Assignment to remove")
val assignment: ID
) : Input() | 2 | Kotlin | 1 | 0 | a0b0538d1960e920d53bc9dc2d7026dfea49d723 | 387 | gropius-backend | MIT License |
app/src/main/java/com/raion/furnitale/core/domain/usecase/search/SearchInteractor.kt | KylixEza | 349,910,754 | false | null | package com.raion.furnitale.core.domain.usecase.search
import com.raion.furnitale.core.data.Resource
import com.raion.furnitale.core.domain.model.Product
import com.raion.furnitale.core.domain.repository.IProductRepository
import kotlinx.coroutines.flow.Flow
class SearchInteractor(private val repository: IProductRepository): SearchUseCase {
override fun getSearchProducts(query: String): Flow<Resource<List<Product>>> {
return repository.getSearchProducts(query)
}
} | 0 | Kotlin | 1 | 1 | 014d82d8764c7c1002d166f435b7243508794fd3 | 486 | FurniTale | MIT License |
src/main/kotlin/possible_triangle/divide/crates/callbacks/CleanCallback.kt | PssbleTrngle | 275,110,821 | false | {"Kotlin": 272874, "TypeScript": 118166, "Java": 7745, "CSS": 6874, "HTML": 1620, "mcfunction": 1102, "Dockerfile": 856} | package possible_triangle.divide.crates.callbacks
import kotlinx.serialization.Serializable
import net.minecraft.core.BlockPos
import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.NbtUtils
import net.minecraft.server.MinecraftServer
import net.minecraft.world.entity.Entity
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.timers.TimerCallback
import net.minecraft.world.level.timers.TimerQueue
import possible_triangle.divide.Config
import possible_triangle.divide.crates.CrateEvents.UNBREAKABLE_TAG
import possible_triangle.divide.crates.CrateScheduler
import possible_triangle.divide.data.EventPos
import possible_triangle.divide.events.CallbackHandler
import possible_triangle.divide.logging.EventLogger
import java.util.*
class CleanCallback(val pos: BlockPos, val uuid: UUID) : TimerCallback<MinecraftServer> {
companion object : CallbackHandler<CleanCallback>("crate_cleanup", CleanCallback::class.java) {
@Serializable
private data class Event(val pos: EventPos)
private val LOGGER = EventLogger("loot_crate_cleaned", { Event.serializer() }) { isAdmin() }
override fun serialize(nbt: CompoundTag, callback: CleanCallback) {
nbt.put("pos", NbtUtils.writeBlockPos(callback.pos))
nbt.putUUID("uuid", callback.uuid)
}
override fun deserialize(nbt: CompoundTag): CleanCallback {
val pos = NbtUtils.readBlockPos(nbt.getCompound("pos"))
val uuid = nbt.getUUID("uuid")
return CleanCallback(pos, uuid)
}
fun cleanMarker(server: MinecraftServer, pos: BlockPos) {
CrateScheduler.markersAt(server, pos).forEach {
it.remove(Entity.RemovalReason.DISCARDED)
}
}
}
override fun handle(server: MinecraftServer, queue: TimerQueue<MinecraftServer>, time: Long) {
val crate = CrateScheduler.crateAt(server, pos, uuid = uuid) ?: return
LOGGER.log(server, Event(EventPos.of(pos)))
cleanMarker(server, pos)
crate.tileData.putBoolean(UNBREAKABLE_TAG, false)
if (Config.CONFIG.crate.cleanNonEmpty || crate.isEmpty) {
if (Config.CONFIG.crate.clearOnCleanup) crate.clearContent()
crate.level?.setBlock(
pos,
Blocks.AIR.defaultBlockState(),
2
)
}
}
} | 17 | Kotlin | 0 | 0 | e0cc0532307557d509f177ac9d80dc97e1353d72 | 2,402 | Divide | MIT License |
miaoandriod/src/main/java/com/a10miaomiao/miaoandriod/adapter/MiaoViewHolder.kt | Dwsy | 239,933,976 | true | {"Kotlin": 478153, "Java": 197271} | package com.a10miaomiao.miaoandriod.adapter
import android.support.v7.widget.RecyclerView
import android.view.View
/**
* Created by 10喵喵 on 2018/2/24.
*/
class MiaoViewHolder<T>(val parentView: View, val binding: Binding<T>? = null) : RecyclerView.ViewHolder(parentView) {
var index = 0
fun updateView(item: T) {
binding?.updateView(item, index)
}
class Binding<T>(val mAdapter: MiaoRecyclerViewAdapter<T>) {
var fns = ArrayList<(item: T, index: Int) -> Unit>()
fun bindIndexed(fn: ((item: T, index: Int) -> Unit)) {
fns.add(fn)
}
fun bind(fn: ((item: T) -> Unit)) {
bindIndexed { item, index -> fn(item) }
}
fun View.bindClick(fn: ((item: T, index: Int) -> Unit)) {
bindIndexed { item, index ->
this.setOnClickListener {
fn(item, index)
mAdapter.notifyDataSetChanged() //直接更新视图,省去每次都要手动更新
}
}
}
fun View.bindClick(fn: ((item: T) -> Unit)) {
bindClick { item, index -> fn(item) }
}
/**
* 更新视图
*/
fun updateView(item: T, index: Int) {
fns.forEach { it(item, index) }
}
}
} | 0 | null | 0 | 0 | 9ce5f4a6742591ba5ec0e6a071e12a833fd31810 | 1,271 | bilimiao2 | Apache License 2.0 |
app/src/main/java/com/elhady/movies/data/repository/MovieRepositoryImp.kt | islamelhady | 301,591,032 | false | {"Kotlin": 140014} | package com.elhady.movies.data.repository
import com.elhady.movies.data.Constant
import com.elhady.movies.data.local.AppConfiguration
import com.elhady.movies.data.local.database.daos.MovieDao
import com.elhady.movies.data.local.database.entity.movies.AdventureMovieEntity
import com.elhady.movies.data.local.database.entity.movies.MysteryMovieEntity
import com.elhady.movies.data.local.database.entity.movies.NowPlayingMovieEntity
import com.elhady.movies.data.local.database.entity.movies.PopularMovieEntity
import com.elhady.movies.data.local.database.entity.movies.TopRatedMovieEntity
import com.elhady.movies.data.local.database.entity.movies.TrendingMovieEntity
import com.elhady.movies.data.local.mappers.movies.TrendingMovieMapper
import com.elhady.movies.data.local.database.entity.movies.UpcomingMovieEntity
import com.elhady.movies.data.local.mappers.movies.AdventureMoviesMapper
import com.elhady.movies.data.local.mappers.movies.MysteryMoviesMapper
import com.elhady.movies.data.local.mappers.movies.NowPlayingMovieMapper
import com.elhady.movies.data.local.mappers.movies.UpcomingMovieMapper
import com.elhady.movies.data.remote.State
import com.elhady.movies.data.remote.response.BaseResponse
import com.elhady.movies.data.remote.response.PersonDto
import com.elhady.movies.data.remote.response.genre.GenreDto
import com.elhady.movies.data.remote.service.MovieService
import com.elhady.movies.data.local.mappers.movies.PopularMovieMapper
import com.elhady.movies.data.local.mappers.movies.TopRatedMovieMapper
import com.elhady.movies.utilities.Constants
import kotlinx.coroutines.flow.Flow
import java.util.Date
import javax.inject.Inject
class MovieRepositoryImp @Inject constructor(
private val movieService: MovieService,
private val popularMovieMapper: PopularMovieMapper,
private val movieDao: MovieDao,
private val appConfiguration: AppConfiguration,
private val trendingMovieMapper: TrendingMovieMapper,
private val upcomingMovieMapper: UpcomingMovieMapper,
private val nowPlayingMovieMapper: NowPlayingMovieMapper,
private val topRatedMovieMapper: TopRatedMovieMapper,
private val mysteryMoviesMapper: MysteryMoviesMapper,
private val adventureMoviesMapper: AdventureMoviesMapper
) :
MovieRepository, BaseRepository() {
/**
* Popular Movies
*/
override suspend fun getPopularMovies(): Flow<List<PopularMovieEntity>> {
refreshOneTimePerDay(
appConfiguration.getRequestDate(Constant.POPULAR_MOVIE_REQUEST_DATE_KEY),
::refreshPopularMovies
)
return movieDao.getPopularMovies()
}
private suspend fun refreshPopularMovies(currentDate: Date) {
val genre = getGenreMovies() ?: emptyList()
wrap(
{ movieService.getPopularMovies() },
{ list ->
list?.map {
popularMovieMapper.map(it, genre)
}
},
{
movieDao.insertPopularMovie(it)
appConfiguration.saveRequestDate(
Constant.POPULAR_MOVIE_REQUEST_DATE_KEY,
currentDate.time
)
}
)
}
/**
* Genre Movies
*/
override suspend fun getGenreMovies(): List<GenreDto>? {
return movieService.getGenreMovies().body()?.genres
}
/**
* Upcoming Movies
*/
override suspend fun getUpcomingMovies(): Flow<List<UpcomingMovieEntity>> {
refreshOneTimePerDay(
appConfiguration.getRequestDate(Constant.UPCOMING_MOVIE_REQUEST_DATE_KEY),
::refreshUpcomingMovies
)
return movieDao.getUpcomingMovies()
}
suspend fun refreshUpcomingMovies(currentDate: Date) {
wrap(
{ movieService.getUpcomingMovies() },
{ list ->
list?.map {
upcomingMovieMapper.map(it)
}
},
{
movieDao.deleteUpcomingMovies()
movieDao.insertUpcomingMovie(it)
appConfiguration.saveRequestDate(
Constant.UPCOMING_MOVIE_REQUEST_DATE_KEY,
currentDate.time
)
})
}
/**
* Top Rated Movies
*/
override suspend fun getTopRatedMovies(): Flow<List<TopRatedMovieEntity>> {
refreshOneTimePerDay(
appConfiguration.getRequestDate(Constant.TOP_RATED_MOVIE_REQUEST_DATE_KEY),
::refreshTopRatedMovies
)
return movieDao.getTopRatedMovies()
}
suspend fun refreshTopRatedMovies(currentDate: Date) {
wrap(
{ movieService.getTopRatedMovies() },
{ list ->
list?.map { topRatedMovieMapper.map(it) }
},
{
movieDao.deleteTopRatedMovies()
movieDao.insertTopRatedMovies(it)
appConfiguration.saveRequestDate(
Constant.TOP_RATED_MOVIE_REQUEST_DATE_KEY,
currentDate.time
)
}
)
}
/**
* Now Playing Movies
*/
override suspend fun getNowPlayingMovies(): Flow<List<NowPlayingMovieEntity>> {
refreshOneTimePerDay(
appConfiguration.getRequestDate(Constant.NOW_PLAYING_MOVIE_REQUEST_DATE_KEY),
::refreshNowPlayingMovies
)
return movieDao.getNowPlayingMovies()
}
private suspend fun refreshNowPlayingMovies(currentDate: Date) {
wrap(
{ movieService.getNowPlayingMovies() },
{ list ->
list?.map { nowPlayingMovieMapper.map(it) }
},
{
movieDao.deleteNowPlayingMovies()
movieDao.insertNowPlayingMovies(it)
appConfiguration.saveRequestDate(
Constant.NOW_PLAYING_MOVIE_REQUEST_DATE_KEY,
currentDate.time
)
}
)
}
override fun getTrendingPerson(): Flow<State<BaseResponse<PersonDto>>> {
return wrapWithFlow { movieService.getTrendingPerson() }
}
/**
* Trending Movies
*/
override suspend fun getTrendingMovie(): Flow<List<TrendingMovieEntity>> {
refreshOneTimePerDay(
appConfiguration.getRequestDate(Constant.TRENDING_MOVIE_REQUEST_DATE_KEY),
::refreshTrendingMovies
)
return movieDao.getAllTrendingMovies()
}
suspend fun refreshTrendingMovies(currentDate: Date) {
wrap(
{
movieService.getTrendingMovie()
},
{ list ->
list?.map {
trendingMovieMapper.map(it)
}
},
{
movieDao.deleteTrendingMovies()
movieDao.insertTrendingMovies(it)
appConfiguration.saveRequestDate(
Constant.TRENDING_MOVIE_REQUEST_DATE_KEY,
currentDate.time
)
}
)
}
/**
* Mystery Movies
*/
override suspend fun getMysteryMovies(): Flow<List<MysteryMovieEntity>> {
refreshOneTimePerDay(
appConfiguration.getRequestDate(Constant.MYSTERY_MOVIE_REQUEST_DATE_KEY),
::refreshMysteryMovies
)
return movieDao.getMysteryMovies()
}
suspend fun refreshMysteryMovies(currentDate: Date) {
wrap(
{ movieService.getMoviesListByGenre(genreID = Constants.MYSTERY_ID) },
{ list ->
list?.map {
mysteryMoviesMapper.map(it)
}
},
{
movieDao.deleteMysteryMovies()
movieDao.insertMysteryMovies(it)
appConfiguration.saveRequestDate(
Constant.MYSTERY_MOVIE_REQUEST_DATE_KEY,
currentDate.time
)
}
)
}
/**
* Adventure Movies
*/
override suspend fun getAdventureMovies(): Flow<List<AdventureMovieEntity>> {
refreshOneTimePerDay(
appConfiguration.getRequestDate(Constant.ADVENTURE_MOVIE_REQUEST_DATE_KEY),
::refreshAdventureMovies
)
return movieDao.getAdventureMovies()
}
suspend fun refreshAdventureMovies(currentDate: Date) {
wrap(
{ movieService.getMoviesListByGenre(genreID = Constants.ADVENTURE_ID) },
{ list ->
list?.map {
adventureMoviesMapper.map(it)
}
},
{
movieDao.deleteAdventureMovies()
movieDao.insertAdventureMovies(it)
appConfiguration.saveRequestDate(
Constant.ADVENTURE_MOVIE_REQUEST_DATE_KEY,
currentDate.time
)
}
)
}
} | 1 | Kotlin | 0 | 0 | 6974db17f9079acbc21aa269cc83f5c7f86b807f | 8,954 | movie-night-v2 | Apache License 2.0 |
plugin/src/main/kotlin/dev/anatolii/gradle/cpp/android/compiler/CppCompiler.kt | Anatolii | 207,176,940 | false | null | /*
* Copyright 2012 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 dev.anatolii.gradle.cpp.android.compiler
import dev.anatolii.gradle.cpp.android.CppLibraryAndroid
import org.gradle.internal.Transformers
import org.gradle.internal.operations.BuildOperationExecutor
import org.gradle.internal.work.WorkerLeaseService
import org.gradle.nativeplatform.internal.CompilerOutputFileNamingSchemeFactory
import org.gradle.nativeplatform.toolchain.internal.CommandLineToolContext
import org.gradle.nativeplatform.toolchain.internal.CommandLineToolInvocationWorker
import org.gradle.nativeplatform.toolchain.internal.compilespec.CppCompileSpec
internal class CppCompiler(
cppLibraryAndroid: CppLibraryAndroid,
buildOperationExecutor: BuildOperationExecutor,
compilerOutputFileNamingSchemeFactory: CompilerOutputFileNamingSchemeFactory,
commandLineToolInvocationWorker: CommandLineToolInvocationWorker,
invocationContext: CommandLineToolContext,
objectFileExtension: String,
useCommandFile: Boolean,
workerLeaseService: WorkerLeaseService
) : AndroidCompatibleNativeCompiler<CppCompileSpec>(
buildOperationExecutor,
compilerOutputFileNamingSchemeFactory,
commandLineToolInvocationWorker,
invocationContext,
CppCompileArgsTransformer(cppLibraryAndroid),
Transformers.noOpTransformer(),
objectFileExtension,
useCommandFile,
workerLeaseService
) {
private class CppCompileArgsTransformer(cppLibraryAndroid: CppLibraryAndroid)
: GccCompilerArgsTransformer<CppCompileSpec>(cppLibraryAndroid,"c++")
}
| 6 | Kotlin | 0 | 0 | c2af271e8221d28c2e28eea3a2c3fc6bee42fb5d | 2,194 | Android-CPP-ToolChain-for-Gradle | MIT License |
app/src/test/java/com/yoelglus/notes/domain/DeleteNoteTest.kt | yoelglus | 100,812,739 | false | null | package com.yoelglus.notes.domain
import com.yoelglus.notes.domain.gateways.NotesRepository
import org.junit.Test
import org.mockito.Mockito
import org.mockito.Mockito.mock
class DeleteNoteTest {
@Test
internal fun callsRepository() {
val notesRepository = mock(NotesRepository::class.java)
val deleteNote = DeleteNote(notesRepository)
val note = Note(1, "title", "text")
deleteNote.execute(note)
Mockito.verify(notesRepository).deleteNote(note)
}
} | 0 | Kotlin | 1 | 6 | be02d69f18ccae0db6e9fe646876608766c8c500 | 505 | notes | Apache License 2.0 |
app/src/main/java/com/stu71205/ca3_movie_booking_app/models/ElectronicViewModel.kt | jefferson-duarte | 772,087,092 | false | {"Kotlin": 80215} | package com.stu71205.ca3_movie_booking_app.models
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.stu71205.ca3_movie_booking_app.services.Electronics
import com.stu71205.ca3_movie_booking_app.services.ElectronicsService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class ElectronicViewModel : ViewModel() {
private val _electronics = MutableLiveData<List<Electronics>>()
val electronics: LiveData<List<Electronics>> = _electronics
fun fetchElectronics() {
viewModelScope.launch {
try {
val fetchedElectronics = withContext(Dispatchers.IO) {
val retrofit = Retrofit.Builder()
.baseUrl("https://fakestoreapi.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
val electronicsService = retrofit.create(ElectronicsService::class.java)
electronicsService.getElectronics()
}
_electronics.value = fetchedElectronics
} catch (e: Exception) {
Log.e("ElectronicViewModel", "Error to get electronics", e)
}
}
}
} | 0 | Kotlin | 0 | 1 | ebbc841e78ae9cb4b2bae206b9ed73a8b47bdd71 | 1,467 | 71205Project | Academic Free License v2.1 |
app/src/main/java/com/example/dobtominutes/MainActivity.kt | lakshmi-p15 | 445,700,530 | false | null | package com.example.dobtominutes
import android.app.DatePickerDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
private var tvSelectedDate: TextView? = null
private var tvAgeInMinutes: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnDatePicker: Button = findViewById(R.id.btnDatePicker)
tvSelectedDate = findViewById(R.id.tvSelectedDate)
tvAgeInMinutes = findViewById(R.id.tvAgeInMinutes)
btnDatePicker.setOnClickListener {
clickDatePicker()
}
}
private fun clickDatePicker() {
val myCalendar = Calendar.getInstance()
val year = myCalendar.get(Calendar.YEAR)
val month = myCalendar.get(Calendar.MONTH)
val day = myCalendar.get(Calendar.DAY_OF_MONTH)
val dpd = DatePickerDialog(
this,
{ _, selectedYear, selectedMonth, selectedDayOfMonth ->
//Displaying date selected in the application
val selectedDate = "$selectedDayOfMonth/ ${selectedMonth + 1}/$selectedYear"
tvSelectedDate?.text = selectedDate
// converting selected date into simple date format to calculate minutes
val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH)
val theDate = sdf.parse(selectedDate)
theDate?.let {
val selectedDateInMinutes = theDate.time / 60000
//finding current date
val currentDate = sdf.parse(sdf.format((System.currentTimeMillis())))
currentDate?.let {
val currentDateInMinutes = currentDate.time / 60000
// calculate no of minutes since the birth by using the difference between current date to selected date
val diffInMinutes = currentDateInMinutes - selectedDateInMinutes
tvAgeInMinutes?.text = diffInMinutes.toString()
}
}
},
year,
month,
day
)
dpd.datePicker.maxDate = System.currentTimeMillis() - 86400000
dpd.show()
}
} | 0 | Kotlin | 0 | 0 | d36674b71a027fbb3a15075a32234337b7c3b06b | 2,498 | DOB_To_Minutes | Apache License 2.0 |
web/src/jsMain/kotlin/ca/derekellis/reroute/stops/Stop.kt | dellisd | 440,373,187 | false | {"Kotlin": 89807, "JavaScript": 4456, "Dockerfile": 669, "HTML": 234} | package ca.derekellis.reroute.stops
import ca.derekellis.reroute.ui.Screen
data class Stop(val code: String) : Screen
| 0 | Kotlin | 0 | 10 | fb0e41e59374c1a34eb370b1202fb96c41589a95 | 120 | reroute | Apache License 2.0 |
src/main/kotlin/com/kryszak/gwatlin/api/story/GWBackstoryClient.kt | Kryszak | 214,791,260 | false | null | package com.kryszak.gwatlin.api.story
import com.kryszak.gwatlin.api.story.model.BackstoryAnswer
import com.kryszak.gwatlin.api.story.model.BackstoryQuestion
import com.kryszak.gwatlin.clients.backstory.BackstoryClient
/**
* Client for backstory endpoints
* @see com.kryszak.gwatlin.api.exception.ApiRequestException for errors
*/
class GWBackstoryClient {
private val backstoryClient: BackstoryClient = BackstoryClient()
/**
* Returns information about the Biography answers that are in the game
*/
fun getBackstoryAnswers(language: String = "en"): List<BackstoryAnswer> {
return backstoryClient.getBackstoryAnswers(language)
}
/**
* Returns information about the Biography questions that are in the game
*/
fun getBackstoryQuestions(language: String = "en"): List<BackstoryQuestion> {
return backstoryClient.getBackstoryQuestions(language)
}
}
| 0 | Kotlin | 0 | 1 | 03b79fda6b25bc0478144f03cd4df50eca7e21e6 | 918 | gwatlin | MIT License |
flank-scripts/src/main/kotlin/flank/scripts/cli/github/DeleteReleaseCommand.kt | Flank | 84,221,974 | false | {"Kotlin": 1748173, "Java": 101254, "Swift": 41229, "Shell": 10674, "Objective-C": 10006, "Dart": 9705, "HTML": 7235, "Gherkin": 4210, "TypeScript": 2717, "Ruby": 2272, "JavaScript": 1764, "SCSS": 1365, "Batchfile": 1183, "EJS": 1061, "Go": 159} | package flank.scripts.cli.github
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
import flank.scripts.ops.github.deleteOldRelease
object DeleteReleaseCommand : CliktCommand(
name = "delete_release",
help = "Delete old release on github"
) {
private val gitTag by option(help = "Git Tag").required()
override fun run() {
deleteOldRelease(gitTag)
}
}
| 64 | Kotlin | 115 | 676 | b40904b4e74a670cf72ee53dc666fc3a801e7a95 | 495 | flank | Apache License 2.0 |
services/hanke-service/src/test/kotlin/fi/hel/haitaton/hanke/logging/PermissionLoggingServiceTest.kt | City-of-Helsinki | 300,534,352 | false | {"Kotlin": 2023322, "Mustache": 89170, "Shell": 23444, "Batchfile": 5169, "PLpgSQL": 1115, "Dockerfile": 371} | package fi.hel.haitaton.hanke.logging
import assertk.all
import assertk.assertThat
import assertk.assertions.isNull
import assertk.assertions.prop
import fi.hel.haitaton.hanke.factory.PermissionFactory
import fi.hel.haitaton.hanke.permissions.Kayttooikeustaso
import fi.hel.haitaton.hanke.test.AuditLogEntryAsserts.hasObjectAfter
import fi.hel.haitaton.hanke.test.AuditLogEntryAsserts.hasObjectBefore
import fi.hel.haitaton.hanke.test.AuditLogEntryAsserts.hasObjectId
import fi.hel.haitaton.hanke.test.AuditLogEntryAsserts.hasObjectType
import fi.hel.haitaton.hanke.test.AuditLogEntryAsserts.hasUserActor
import fi.hel.haitaton.hanke.test.AuditLogEntryAsserts.isCreate
import fi.hel.haitaton.hanke.test.AuditLogEntryAsserts.isSuccess
import fi.hel.haitaton.hanke.test.AuditLogEntryAsserts.isUpdate
import io.mockk.called
import io.mockk.checkUnnecessaryStub
import io.mockk.clearAllMocks
import io.mockk.confirmVerified
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
class PermissionLoggingServiceTest {
private val userId = "test"
private val auditLogService: AuditLogService = mockk(relaxed = true)
private val loggingService = PermissionLoggingService(auditLogService)
@BeforeEach
fun clearMocks() {
clearAllMocks()
}
@AfterEach
fun cleanUp() {
checkUnnecessaryStub()
confirmVerified(auditLogService)
}
@Nested
inner class LogCreate {
@Test
fun `Creates audit log entry for created permission`() {
val permission =
PermissionFactory.create(kayttooikeustaso = Kayttooikeustaso.HANKEMUOKKAUS)
loggingService.logCreate(permission, userId)
verify {
auditLogService.create(
withArg { entry ->
assertThat(entry).all {
isCreate()
isSuccess()
hasUserActor(userId)
hasObjectId(PermissionFactory.PERMISSION_ID)
hasObjectType(ObjectType.PERMISSION)
prop(AuditLogEntry::objectBefore).isNull()
hasObjectAfter(permission)
}
}
)
}
}
}
@Nested
inner class LogUpdate {
@Test
fun `Creates audit log entry for updated permission`() {
val kayttooikeustasoBefore = Kayttooikeustaso.KATSELUOIKEUS
val permissionAfter =
PermissionFactory.create(kayttooikeustaso = Kayttooikeustaso.HANKEMUOKKAUS)
loggingService.logUpdate(kayttooikeustasoBefore, permissionAfter, userId)
verify {
auditLogService.create(
withArg { entry ->
assertThat(entry).all {
isUpdate()
isSuccess()
hasUserActor(userId)
hasObjectId(PermissionFactory.PERMISSION_ID)
hasObjectType(ObjectType.PERMISSION)
hasObjectBefore(
permissionAfter.copy(
kayttooikeustaso = Kayttooikeustaso.KATSELUOIKEUS
)
)
hasObjectAfter(permissionAfter)
}
}
)
}
}
@Test
fun `Doesn't create audit log entry if permission not updated`() {
val kayttooikeustasoBefore = PermissionFactory.KAYTTOOIKEUSTASO
val permissionAfter = PermissionFactory.create()
loggingService.logUpdate(kayttooikeustasoBefore, permissionAfter, userId)
verify { auditLogService wasNot called }
}
}
}
| 4 | Kotlin | 5 | 4 | c2c04891485439e52600f4b02710af5d4a547ac1 | 4,059 | haitaton-backend | MIT License |
src/test/kotlin/no/nav/personbruker/minesaker/api/saf/journalposter/objectmothers/HentJournalposterObjectMother.kt | navikt | 331,032,645 | false | null | package no.nav.personbruker.minesaker.api.saf.journalposter.objectmothers
import no.nav.dokument.saf.selvbetjening.generated.dto.HentJournalposter
import no.nav.personbruker.minesaker.api.saf.common.GraphQLError
import no.nav.personbruker.minesaker.api.saf.common.GraphQLResponse
import no.nav.personbruker.minesaker.api.saf.journalposter.HentJournalpostResultObjectMother
object HentJournalposterResultObjectMother {
fun giveMeOneResult(): GraphQLResponse<HentJournalposter.Result> {
val data = HentJournalpostResultObjectMother.giveMeHentJournalposterResult()
return GraphQLResponse(data)
}
fun giveMeResponseWithError(data: HentJournalposter.Result? = null): GraphQLResponse<HentJournalposter.Result> {
val error = GraphQLError("Feilet ved henting av data for bruker.")
return GraphQLResponse(data, listOf(error))
}
fun giveMeResponseWithDataAndError(): GraphQLResponse<HentJournalposter.Result> {
val data = HentJournalpostResultObjectMother.giveMeHentJournalposterResult()
return giveMeResponseWithError(data)
}
}
| 1 | Kotlin | 1 | 0 | 9483405e40b286e7b537a699ca3cf4eaca40ed0e | 1,098 | mine-saker-api | MIT License |
app/src/main/java/com/frc1678/pit_collection/ui/screens/CollectionScreen.kt | frc1678 | 803,040,142 | false | {"Kotlin": 52779} | // Copyright (c) 2022 FRC Team 1678: Citrus Circuits
package com.frc1678.pit_collection.ui.screens
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
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.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CameraAlt
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.LargeFloatingActionButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.frc1678.pit_collection.Constants
import com.frc1678.pit_collection.LocalEventKey
import com.frc1678.pit_collection.LocalPitData
import com.frc1678.pit_collection.MainActivityViewModel
import com.frc1678.pit_collection.MainNavGraph
import com.frc1678.pit_collection.data.datapointToHumanReadable
import com.frc1678.pit_collection.data.datapoints
import com.frc1678.pit_collection.data.drivetrainTypes
import com.frc1678.pit_collection.data.otherToHumanReadable
import com.frc1678.pit_collection.data.pictureTypes
import com.frc1678.pit_collection.ui.components.createImageFile
import com.frc1678.pit_collection.ui.components.pictureFolder
import com.frc1678.pit_collection.util.TopBar
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.double
import kotlinx.serialization.json.int
import java.io.File
/** Main screen for data collection **/
@OptIn(ExperimentalLayoutApi::class)
@MainNavGraph
@Destination
@Composable
fun CollectionScreen(
teamNumber: String, viewModel: MainActivityViewModel, navigator: DestinationsNavigator
) {
val actionBar = LocalEventKey.current + " Version: ${Constants.VERSION}"
Scaffold(
topBar = {
TopBar(
modifier = Modifier.padding(10.dp),
title = actionBar,
navigator = navigator,
true
)
}) { innerPadding ->
Column(
modifier = Modifier
.padding(10.dp)
.fillMaxSize()
) {
var pictureExpanded by remember { mutableStateOf(false) }
//Row with team number and camera button
Row(
modifier = Modifier
.fillMaxWidth()
.padding(innerPadding)
) {
Text(
text = teamNumber,
fontSize = 60.sp,
modifier = Modifier
.weight(2F)
.align(Alignment.CenterVertically)
)
val hasFullRobotPicture by remember {mutableStateOf(File("/$pictureFolder/" + teamNumber + "_full_robot.jpg").exists())}
val hasSidePicture by remember {mutableStateOf(File("/$pictureFolder/" + teamNumber + "_side.jpg").exists())}
LargeFloatingActionButton(shape = CircleShape,
modifier = Modifier
.weight(2F)
.align(Alignment.CenterVertically)
.padding(10.dp),
containerColor =
if (
hasFullRobotPicture &&
hasSidePicture
)
Color.Green
else if (
hasFullRobotPicture ||
hasSidePicture
)
Color.Cyan
else Color.LightGray,
onClick = { pictureExpanded = !pictureExpanded }) {
Icon(Icons.Filled.CameraAlt, "camera", modifier = Modifier.scale(3F, 3F))
PictureDropdown(teamNumber = teamNumber,
expanded = pictureExpanded,
onDismissRequest = { pictureExpanded = !pictureExpanded })
}
}
FlowRow(
maxItemsInEachRow = 2,
horizontalArrangement = Arrangement.Center,
verticalArrangement = Arrangement.Center
) {
val itemModifier = Modifier
.padding(4.dp)
.height(120.dp)
.weight(1f)
datapoints.toList().forEach { datapoint ->
DatapointCollection(
modifier = itemModifier,
teamNumber = teamNumber,
datapoint = datapoint.first,
) {
viewModel.updateData(teamNumber, datapoint.first, it)
}
}
}
}
}
}
/**Collection composable that will determine whether a popup or button will be shown **/
@Composable
fun DatapointCollection(
modifier: Modifier,
teamNumber: String,
datapoint: String,
setData: (JsonPrimitive) -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
if (datapoint == "drivetrain") {
Box {
Column(
modifier = Modifier
.align(Alignment.Center)
.background(
if (
LocalPitData.current[teamNumber]?.get("drivetrain")?.int != 0 &&
LocalPitData.current[teamNumber]?.get("drivetrain")?.int != null
)
Color.Green
else Color.LightGray
)
) {
DrivetrainDropdownInput(
modifier = modifier,
expanded = expanded,
drivetrainTypes = drivetrainTypes,
setData = { setData(it) },
onDismissRequest = { expanded = !expanded },
teamNumber = teamNumber,
)
}
}
} else if (datapoints[datapoint]!!.content.all { char -> char.isDigit() }) {
NumberDataInput(
modifier = modifier,
teamNumber = teamNumber,
datapoint = datapoint,
setData = setData
)
} else {
BooleanDataInput(modifier, teamNumber, datapoint, setData)
}
}
/**Button for boolean inputs **/
@Composable
fun BooleanDataInput(
modifier: Modifier,
teamNumber: String,
datapoint: String,
setData: (JsonPrimitive) -> Unit,
) {
val localPitData = LocalPitData.current
OutlinedCard(
modifier = modifier,
onClick = { setData(JsonPrimitive(!(localPitData[teamNumber]?.get(datapoint)?.boolean?: false))) },
colors = if (localPitData[teamNumber]?.get(datapoint)?.boolean == true) CardDefaults.outlinedCardColors(
Color.Green
) else CardDefaults.outlinedCardColors(
Color.LightGray
)
) {
Column(
modifier = Modifier
.fillMaxSize()
.wrapContentSize()
) {
Text(
if (localPitData[teamNumber]?.get(datapoint)?.boolean == true) datapointToHumanReadable[datapoint]!!.second
else datapointToHumanReadable[datapoint]!!.first, textAlign = TextAlign.Center
)
}
}
}
/** Composable for integer display. The value variable contains by default the value of the given datapoint.
* It is converted to a string in order to have it be set in the text field.
* The value of that string can always be changed, but the actual data is only set
* when the value can be converted to double without becoming null.
* If it is null after conversion, the isError variable will be set to true
* and the label text will turn red. In addition, the edited string will not be written to the data.*/
@Composable
fun NumberDataInput(
modifier: Modifier,
teamNumber: String,
datapoint: String,
setData: (JsonPrimitive) -> Unit,
) {
val localPitData = LocalPitData.current
OutlinedCard(
modifier = modifier,
colors = CardDefaults.outlinedCardColors(
if (
localPitData[teamNumber]?.get(datapoint)?.double != 0.0 &&
localPitData[teamNumber]?.get(datapoint)?.double != null
)
Color.Green
else Color.LightGray
)
) {
Column(
modifier = Modifier
.fillMaxSize()
.wrapContentSize()
) {
var value by rememberSaveable {
mutableStateOf((localPitData[teamNumber]?.get(datapoint)?.double?: 0).toString())
}
TextField(
value = value,
onValueChange = {
value = it
if (it.toDoubleOrNull() != null) {
setData(JsonPrimitive(it.toDouble()))
}
},
label = {
Text(text = otherToHumanReadable[datapoint]!!)
},
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.None,
keyboardType = KeyboardType.Number
),
isError = value.toDoubleOrNull() == null,
singleLine = true
)
}
}
}
/** Loop through drivetrainTypes, for each it will have text of the item be the key of the given drivetrainType.
* On click, it will set the given team's datapoint value, and then set it.
* selectedText keeps track of what the value of your datapoint is.
* It also determines what is being displayed in the text field, which shows which item is selected.
**/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DrivetrainDropdownInput(
modifier: Modifier,
expanded: Boolean,
drivetrainTypes: Map<String, JsonPrimitive>,
setData: (JsonPrimitive) -> Unit,
onDismissRequest: () -> Unit,
teamNumber: String,
) {
val localPitData = LocalPitData.current
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = { onDismissRequest() },
) {
TextField(modifier = modifier
.fillMaxSize()
.menuAnchor(),
value = otherToHumanReadable[drivetrainTypes.keys.toList()[localPitData[teamNumber]?.get(
"drivetrain"
)?.int ?: 0]]!!,
onValueChange = {},
readOnly = true,
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(
expanded = expanded
)
}
)
DropdownMenu(expanded = expanded, onDismissRequest = onDismissRequest) {
drivetrainTypes.forEach { item ->
DropdownMenuItem(
text = { Text(otherToHumanReadable[item.key]!!) },
trailingIcon = {
if (localPitData[teamNumber]?.get("drivetrain")?.int == (drivetrainTypes[item.key]?.int
?: 0)
) {
Icon(Icons.Default.Check, "")
}
},
onClick = {
setData(item.value)
onDismissRequest()
},
)
}
}
}
}
/** Dropdown menu with two items: full robot or side.
* For each one, clicking on the menu item will launch the camera activity, passing in a Uri file location.
* Launching from ActivityResultsContracts.Picture takes that Uri and saves the taken image to a designated file.
* That designated location is defined with createImageFile()
**/
@Composable
fun PictureDropdown(teamNumber: String, expanded: Boolean, onDismissRequest: () -> Unit) {
val takePictureLauncher =
rememberLauncherForActivityResult(contract = ActivityResultContracts.TakePicture()) {}
val pictureContext = LocalContext.current
DropdownMenu(expanded = expanded, onDismissRequest = onDismissRequest) {
pictureTypes.forEach { item ->
DropdownMenuItem(
text = { Text(otherToHumanReadable[item]!!) },
trailingIcon = {
if (File("/$pictureFolder/" + teamNumber + "_$item.jpg").exists()) {
Icon(Icons.Default.Check, "selected")
}
},
onClick = {
takePictureLauncher.launch(
createImageFile(
teamNumber = teamNumber,
pictureType = item,
context = pictureContext
)
)
onDismissRequest()
}
)
}
}
}
| 0 | Kotlin | 0 | 0 | c82bda768cff4e90b32752ebf3e8645206c11439 | 14,928 | pit-collection-2024-public | MIT License |
app/src/main/java/io/smileyjoe/applist/db/Db.kt | SmileyJoe | 139,638,793 | false | {"Kotlin": 109235, "Java": 8729} | package io.smileyjoe.applist.db
import android.app.Activity
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import io.smileyjoe.applist.BuildConfig
import io.smileyjoe.applist.R
import io.smileyjoe.applist.`object`.User
import io.smileyjoe.applist.util.Notify
/**
* Base db operations
*/
object Db {
/**
* Root key used for the app details
*/
private val DB_KEY_APP_DETAIL = if (BuildConfig.DEBUG) "app-debug" else "app"
/**
* Get the reference for the user
* </p>
* Db structure is <user_id>/DB_KEY_/items
*
* @param activity current activity used to show error
* todo: Should be a callback, shouldn't show the error
* @return [DatabaseReference] for the users node
*/
private fun getReference(activity: Activity): DatabaseReference? {
User.current?.let { user ->
return FirebaseDatabase.getInstance().reference.child(user.id)
} ?: run {
Notify.error(activity, R.string.error_not_signed_in)
return null
}
}
/**
* Get the reference for the user app details node
*
* @param activity current activity used to show error
* todo: Should be a callback, shouldn't show the error
* @return [DatabaseReference] for the user app details node
*/
fun getDetailReference(activity: Activity): DatabaseReference? {
getReference(activity)?.let { reference ->
return reference.child(DB_KEY_APP_DETAIL)
} ?: run {
return null
}
}
} | 0 | Kotlin | 0 | 0 | cd7cb13a42dd7813c713e99c27d1e0c800763cc2 | 1,600 | app_android_app_list | MIT License |
common/src/main/java/com/dugang/rely/common/extension/NetWork.kt | DuJerry | 174,309,767 | false | null | /*
* Copyright (c) 2017-2019 dugang
*
* 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.dugang.rely.common.extension
import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.net.NetworkCapabilities
import android.provider.Settings
/*
---------- 网络相关扩展函数 ----------
*/
/**
* 判断当前是否已有效连接
*/
val Context.netWorkConnected: Boolean
@TargetApi(28)
get() {
val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
?: return false
return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
/**
* 判断当前有效连接是蜂窝数据
*/
val Context.cellularConnected: Boolean
@TargetApi(28)
get() {
val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
?: return false
return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
}
/**
* 判断当前有效连接是WIFI
*/
val Context.wifiConnected: Boolean
@TargetApi(28)
get() {
val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
?: return false
return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
}
/**
* 判断/设置WIFI状态, get()-获取WIFI状态,set()-设置wifi状态
*/
var Context.isWifiEnable: Boolean
get() = wifiManager.isWifiEnabled
set(value) {
wifiManager.isWifiEnabled = value
}
/**
* 打开无线设置界面
*/
fun Context.openWirelessSettings() {
startActivity(Intent(Settings.ACTION_WIRELESS_SETTINGS).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
})
}
| 0 | Kotlin | 0 | 2 | ed1d40115fba3bfd6ae8de8a108b705613e4589f | 2,257 | Rely-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.