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/top/niunaijun/blackboxa/util/LoadingUtil.kt | black-binary | 371,578,211 | true | null | package top.niunaijun.blackboxa.util
import android.view.KeyEvent
import androidx.fragment.app.FragmentManager
import com.roger.catloadinglibrary.CatLoadingView
import top.niunaijun.blackboxa.R
/**
*
* @Description:
* @Author: wukaicheng
* @CreateDate: 2021/4/30 23:04
*/
object LoadingUtil {
fun showLoading(loadingView: CatLoadingView, fragmentManager: FragmentManager) {
if (!loadingView.isAdded) {
loadingView.setBackgroundColor(R.color.primary)
loadingView.show(fragmentManager, "")
fragmentManager.executePendingTransactions()
loadingView.setClickCancelAble(false)
loadingView.dialog?.setOnKeyListener { _, keyCode, _ ->
if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE) {
return@setOnKeyListener true
}
false
}
}
}
} | 0 | Java | 14 | 22 | 34c2622c4b2ce3ba77edfce0396f2e5b8698cb72 | 921 | BlackBox | Apache License 2.0 |
app/src/main/java/me/aravi/notes/beans/Notes.kt | mimosalab | 477,773,864 | false | null | package me.aravi.notes.beans
import androidx.room.Entity
import androidx.room.PrimaryKey
import me.aravi.notes.ui.theme.*
@Entity(tableName = "notes")
data class Notes(
val title: String,
val content: String,
val timestamp: Long,
val color: Int,
@PrimaryKey val id: Int? = null
) {
companion object {
val easyNotesColors =
listOf(LightPink, LightYellow, LightBlue, LightGreen, DarkYellow, RedYellow)
}
}
class InvalidNoteException(message: String) : Exception(message) | 0 | Kotlin | 0 | 2 | b1c6fa714d1387d7887bffbfa567d156232fbd2f | 519 | notes-composeui-android | Apache License 2.0 |
Projeto_ToolCoin/ToolCoin/app/src/main/java/com/jairolopes/toolcoin/ProjectionActivity.kt | JairoLopes | 546,181,328 | false | null | package com.jairolopes.toolcoin
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.jairolopes.toolcoin.databinding.ActivityProjectionBinding
class ProjectionActivity : AppCompatActivity(){
private lateinit var binding:ActivityProjectionBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityProjectionBinding.inflate(layoutInflater)
supportActionBar?.hide()
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.buttonProjectionPROJECTION.setOnClickListener{
if (validate()){
val price = binding.editPricePROJECTION.text.toString().toFloat()
val investment = binding.editInvestmentPROJECTION.text.toString().toFloat()
val projection = binding.editProjectionPROJECTION.text.toString().toFloat()
val supply = investment/price
val profit = ((projection - price) * supply)
val percentValue = ((projection - price) / price) * 100
val patrimony = (profit + investment)
binding.textResultPercentPROJECTION.text = "%.2f".format(percentValue) + "%"
binding.textResultSupplyPROJECTION.text = "%.2f".format(supply)
binding.textResultProfitPROJECTION.text = "$ %.2f".format(profit)
binding.textResultPatrimonyPROJECTION.text = "$ %.2f".format(patrimony)
}else{
Toast.makeText(this, "Preencha todos os campos!", Toast.LENGTH_SHORT).show()
}
}
binding.buttonClearPROJECTION.setOnClickListener{
binding.editPricePROJECTION.text.clear()
binding.editInvestmentPROJECTION.text.clear()
binding.editProjectionPROJECTION.text.clear()
binding.textResultPercentPROJECTION.text = "00.00%"
binding.textResultSupplyPROJECTION.text = "00.00"
binding.textResultProfitPROJECTION.text = "$ 00.00"
binding.textResultPatrimonyPROJECTION.text = "$ 00.00"
}
}
private fun validate():Boolean{
return (binding.editPricePROJECTION.text.toString() != "" &&
binding.editInvestmentPROJECTION.text.toString() != "" &&
binding.editProjectionPROJECTION.text.toString() != ""
)
}
} | 0 | Kotlin | 0 | 1 | 359996b17460c364d414aa06cd6059ab3be490c4 | 2,432 | Android_Nativo | MIT License |
modules/core/data/src/commonMain/kotlin/org/real/flickfusion/repo/SearchRepoImpl.kt | FrankieShao | 815,291,399 | false | {"Kotlin": 411322, "Swift": 657} | package org.real.flickfusion.repo
import org.real.flickfusion.remote.SearchGateway
/**
* @author <NAME>
* @created 20/07/2024
* Description:
*/
class SearchRepoImpl(private val gateway: SearchGateway): SearchRepo {
override fun search(key: String) = gateway.search(key)
} | 0 | Kotlin | 0 | 15 | 0312115d65abf9b44776c6159ad1d7d0b4bb035a | 280 | FlickFusion | MIT License |
src/test/kotlin/com/epam/brn/webclient/GitHubApiClientTest.kt | Brain-up | 216,092,521 | false | {"Kotlin": 1057933, "Handlebars": 512629, "TypeScript": 401203, "JavaScript": 168755, "HTML": 45401, "CSS": 30742, "SCSS": 27412, "RAML": 22982, "Makefile": 545, "Shell": 405, "Dockerfile": 185} | package com.epam.brn.webclient
import com.epam.brn.webclient.config.GitHubApiClientConfig
import com.epam.brn.dto.github.GitHubContributorDto
import com.epam.brn.dto.github.GitHubUserDto
import com.epam.brn.webclient.property.GitHubApiClientProperty
import io.mockk.junit5.MockKExtension
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertAll
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.web.reactive.function.client.WebClient
@ExtendWith(MockKExtension::class)
internal class GitHubApiClientTest {
private lateinit var client: GitHubApiClient
private lateinit var server: MockWebServer
private lateinit var gitHubApiClientProperty: GitHubApiClientProperty
private lateinit var gitHubApiClientConfig: GitHubApiClientConfig
@BeforeEach
fun setup() {
server = MockWebServer()
server.start()
val baseRoot = "/"
val rootUrl = server.url(baseRoot).toString()
gitHubApiClientProperty = GitHubApiClientProperty(
"token",
"type",
GitHubApiClientProperty.GitHubApiUrl(
rootUrl,
GitHubApiClientProperty.GitHubApiUrl.GitHubApiPath(
"/contributors",
"/users"
)
),
16777216,
false,
15000,
30000
)
gitHubApiClientConfig = GitHubApiClientConfig(gitHubApiClientProperty)
client = GitHubApiClient(gitHubApiClientProperty, gitHubApiClientConfig.gitHubApiWebClient(WebClient.builder()))
}
@AfterEach
fun afterAll() {
server.shutdown()
}
@Test
fun getContributorsWhenOKShouldReturnContributors() {
val contributor = GitHubContributorDto(
login = "lifeart",
id = 1360552,
gravatarId = "",
avatarUrl = "https://avatars.githubusercontent.com/u/1360552?v=4",
url = "https://api.github.com/users/lifeart",
type = "User",
siteAdmin = false,
contributions = 312
)
server.enqueue(
MockResponse().setResponseCode(200)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(readResourceAsString("contributors.json"))
)
server.enqueue(
MockResponse().setResponseCode(200)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(readResourceAsString("contributors-2.json"))
)
val contributors = client.getGitHubContributors("Brain-Up", "brn", 50)
assertAll(
{ assertThat(contributors).isNotEmpty },
{ assertThat(contributors.size).isEqualTo(56) },
{ assertThat(contributors[0]).isInstanceOf(GitHubContributorDto::class.java) },
{ assertThat(contributors[0]).isEqualTo(contributor) },
)
}
@ParameterizedTest
@ValueSource(ints = [401, 403, 404, 500])
fun getContributorsWhenHttpErrorThenShouldReturnEmptyContributors(statusCode: Int) {
server.enqueue(
MockResponse().setResponseCode(statusCode)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(readResourceAsString("http-error.json"))
)
val contributors = client.getGitHubContributors("Brain-Up", "brn", 50)
assertAll(
{ assertThat(contributors).isEmpty() }
)
}
@Test
fun getUserWhenOKShouldReturnGotHubUserInfo() {
val expectedUser = GitHubUserDto(
id = 7206824,
login = "test-user",
avatarUrl = "https://avatars.githubusercontent.com/u/test-user?v=4",
gravatarId = "",
name = "<NAME>",
company = "Company",
location = "Location",
email = "<EMAIL>",
bio = "Fullstack Developer",
)
server.enqueue(
MockResponse().setResponseCode(200)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(readResourceAsString("user.json"))
)
val user = client.getGitHubUser("test-user")
assertAll(
{ assertThat(user).isNotNull },
{ assertThat(user).isInstanceOf(GitHubUserDto::class.java) },
{ assertThat(user).isEqualTo(expectedUser) },
)
}
@ParameterizedTest
@ValueSource(ints = [404, 500])
fun getUserWhenHttpErrorThenShouldReturnNull(statusCode: Int) {
server.enqueue(
MockResponse().setResponseCode(statusCode)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(readResourceAsString("http-error.json"))
)
val user = client.getGitHubUser("test-user")
assertAll(
{ assertThat(user).isNull() }
)
}
private fun readResourceAsString(fileName: String) =
this::class.java.getResource("/inputData/githubapi/$fileName").readText()
}
| 114 | Kotlin | 26 | 61 | 310cfcae2b9780740554396271444388258ce8da | 5,544 | brn | Creative Commons Zero v1.0 Universal |
modules/aql/arrow-query-language/src/main/kotlin/arrow/aql/Prelude.kt | Krishan14sharma | 183,217,828 | true | {"Kotlin": 2391225, "CSS": 152663, "JavaScript": 67900, "HTML": 23177, "Java": 4465, "Shell": 3043, "Ruby": 1598} | package arrow.aql
import arrow.Kind
typealias Source<F, A> = Kind<F, A>
typealias Selection<A, Z> = A.() -> Z | 0 | Kotlin | 0 | 1 | 2b26976e1a8fbf29b7a3786074d56612440692a8 | 111 | arrow | Apache License 2.0 |
app/src/main/java/com/xgimi/filemanager/FileManagerApplication.kt | LuffyJoker | 289,462,606 | false | null | package com.xgimi.filemanager
import android.app.Application
import android.graphics.Color
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.Utils
import com.xgimi.collectionsdk.DataReporter.register
import com.xgimi.collectionsdk.DataReporter.resourceManager
import com.xgimi.filemanager.enums.FileCategory
import com.xgimi.filemanager.utils.FileCategoryUtil
import com.xgimi.filemanager.utils.ScreenAdapterUtils
import com.xgimi.filemanager.utils.ThreadManager
import com.xgimi.gimiskin.sdk.SkinEngine.initEngine
import com.xgimi.view.cell.GlobalConfig
import java.io.File
/**
* author : joker.peng
* e-mail : [email protected]
* date : 2020/8/6 16:47
* desc :
*/
class FileManagerApplication : Application() {
private val types = arrayOf(
"folder",
"video",
"audio",
"picture",
"doc",
"apk",
"theme",
"doc",
"zip",
"custom",
"other",
"favorite"
)
companion object {
@Suppress("unused")
private const val TAG = "CommonApp"
private var INSTANCE: FileManagerApplication? = null
fun getInstance(): FileManagerApplication {
return INSTANCE!!
}
}
override fun onCreate() {
super.onCreate()
// GlobalConfig.SHOW_BORDER = Color.RED
// GlobalConfig.SHOW_CONTENT = Color.BLUE
INSTANCE = this
initEngine(this)
Utils.init(this)
ScreenAdapterUtils.register(
this,
960f,
ScreenAdapterUtils.MATCH_BASE_WIDTH,
ScreenAdapterUtils.MATCH_UNIT_DP
)
//初始化数据采集
register(this)
}
fun reportFileCevent(path: String) {
ThreadManager.execute(Runnable {
try {
if (StringUtils.isEmpty(path)) {
return@Runnable
}
val src: String = when {
path.startsWith("http") -> {
"dlna"
}
path.startsWith("/mnt/samba") -> {
"samba"
}
else -> {
"usb"
}
}
val file = File(path)
if (file != null && file.exists()) {
val category: Int
category = if (file.isDirectory) {
FileCategory.Folder.ordinal
} else {
FileCategoryUtil.getTypeByNameOrPath(path)
}
var type: String = types[category]
if (path.toLowerCase().endsWith(".zip")) {
type = "zip"
} else if (path.toLowerCase().endsWith(".rar")) {
type = "rar"
} else if (path.toLowerCase().endsWith(".iso")) {
type = "iso"
}
val lastIndex = file.name.lastIndexOf('.')
var extension: String? = null
if (lastIndex > 0) {
extension = file.name.substring(lastIndex)
}
val fileName = file.name.substring(0, lastIndex) //todo 越界异常
resourceManager
.fileCEvent(
src,
type,
if (NetworkUtils.isAvailable()) 1 else -1,
fileName,
extension,
null
)
}
} catch (e: Exception) {
e.printStackTrace()
}
})
}
} | 1 | null | 1 | 1 | b6e06b7f4d587ab2439fd01b6238f7d1ef1a994c | 3,855 | CellFileManager | Apache License 2.0 |
app/src/main/java/com/allen/weather/ui/pages/hourlyweather/WeatherHourlyActivity.kt | 53365252 | 656,552,050 | false | null | package com.allen.weather.ui.pages.hourlyweather
import android.os.Bundle
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.allen.weather.R
import com.allen.weather.app.base.BaseActivity
import com.allen.weather.di.ui.bindComponent
import com.allen.weather.ui.common.recyclerview.DividerDecoration
import com.allen.weather.ui.common.recyclerview.RecyclerViewAdapter
import com.allen.weather.ui.viewdata.WeatherHourlyViewData
import kotlinx.android.synthetic.main.activity_weather_hourly.*
import javax.inject.Inject
class WeatherHourlyActivity : BaseActivity<WeatherHourlyViewModel>() {
@Inject
lateinit var adapter: RecyclerViewAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_weather_hourly)
this.bindComponent()
viewModel = ViewModelProviders.of(this, viewModelFactory).get(WeatherHourlyViewModel::class.java)
bindViewToModel()
bindModelToView()
}
override fun onResume() {
super.onResume()
viewModel.start(intent)
}
private fun bindModelToView() {
viewModel.listViewData.observe(this, {
adapter.setAdapterItems(it)
})
}
private fun bindViewToModel() {
adapter.register(
WeatherHourlyViewData::class.java,
WeatherHourlyViewBinder()
)
recycler_view.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recycler_view.adapter = adapter
recycler_view.addItemDecoration(DividerDecoration(this))
recycler_view.itemAnimator = null
}
} | 0 | Kotlin | 0 | 0 | da3ed5ae77db720a7da9bce52a5e3e22e0942488 | 1,713 | libtest | Apache License 2.0 |
src/test/kotlin/io/ashdavies/rx/rxtasks/TaskTest.kt | ashdavies | 78,042,187 | false | {"Kotlin": 11325, "Shell": 831, "Java": 545} | package io.ashdavies.rx.rxtasks
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockito_kotlin.mock
import org.junit.Test
import java.util.concurrent.CancellationException
internal class TaskTest {
@Test
fun `should get required task result`() {
val result = Tasks
.forResult(42)
.asRequired()
assertThat(result).isEqualTo(42)
}
@Test(expected = IllegalStateException::class)
fun `should throw illegal state exception for empty required result`() {
Tasks
.forResult<Int>(null)
.asRequired()
}
@Test
fun `should get task result`() {
val result = Tasks
.forResult(42)
.asResult()
assertThat(result).isEqualTo(42)
}
@Test
fun `should get nullable task result`() {
val result = Tasks
.forResult<Int>(null)
.asResult()
assertThat(result).isNull()
}
@Test(expected = RuntimeException::class)
fun `should throw task exception`() {
Tasks
.forException<Int>(RuntimeException())
.asResult()
}
@Test(expected = CancellationException::class)
fun `should throw cancellation exception on cancelled task`() {
Tasks
.forCanceled<Int>()
.asResult()
}
@Test(expected = IllegalStateException::class)
fun `should throw illegal state exception on incomplete task`() {
mock<Task<Int>>()
.asResult()
}
}
| 4 | Kotlin | 15 | 65 | 7eb18e313b5253065de4022c8f6707ac30127877 | 1,482 | rx-tasks | Apache License 2.0 |
app/src/main/java/me/hexile/odexpatcher/art/ArtPatcher.kt | giacomoferretti | 293,629,531 | false | null | package me.hexile.odexpatcher.art
import me.hexile.odexpatcher.ktx.readBytes
import me.hexile.odexpatcher.ktx.toHexString
import java.io.File
import java.io.RandomAccessFile
interface ArtInfo {
val version: String
val dexFileCount: Int
val dexChecksumOffset: Long
val headerSize: Long
//val headerFields: Int
fun parseChecksum(pos: Long, checksums: ArrayList<Pair<Long, ByteArray>>): Long
//fun getHeaderSize(): Long
}
abstract class ArtPatcher(private val file: File) {
protected abstract fun checkIfValid(raf: RandomAccessFile)
protected abstract fun parseHeader(raf: RandomAccessFile): ArtInfo
var header: ArtInfo
private val _checksums: ArrayList<Pair<Long, ByteArray>>
val checksums: List<Pair<Long, ByteArray>>
get() = _checksums.toList()
init {
RandomAccessFile(file, "r").use { raf ->
checkIfValid(raf)
header = parseHeader(raf)
_checksums = parseChecksums()
}
}
fun patch(checksums: ArrayList<ByteArray>) {
if (checksums.isEmpty()) {
throw IllegalArgumentException("Cannot be empty")
} else if (checksums.size != this._checksums.size) {
throw IllegalArgumentException("Must be same size ${checksums.size} != ${this._checksums.size}")
}
RandomAccessFile(file, "rw").use { raf ->
this._checksums.asSequence().withIndex().iterator().forEach {
println("PATCHING ${it.index}")
val source = raf.readBytes(it.value.first, 4)
val sourceCache = it.value.second
val new = checksums[it.index]
println(" -> ${source.toHexString()} = ${new.toHexString()} [${sourceCache.toHexString()}]")
raf.seek(it.value.first)
raf.write(checksums[it.index]) // java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
}
}
}
private fun parseChecksums(): ArrayList<Pair<Long, ByteArray>> {
val checksums = ArrayList<Pair<Long, ByteArray>>()
var cursor = header.dexChecksumOffset
for (i in 0 until header.dexFileCount) {
cursor = header.parseChecksum(cursor, checksums)
}
return checksums
}
protected fun toStringContents(): String {
val checksumsString = checksums.iterator().let {
if (!it.hasNext()) {
"{}"
} else {
var result = "{"
while (true) {
val entry = it.next()
result += "${entry.first}=${entry.second.toHexString()}"
if (!it.hasNext()) break
result += ", "
}
"$result}"
}
}
return "file=$file, header=$header, checksums=$checksumsString)"
}
override fun toString(): String {
return "ArtPatcher(${toStringContents()})"
}
} | 10 | Kotlin | 10 | 48 | 2cbf4fbf3a7ecaf64c1c795767ef97d75bf22340 | 2,966 | odex-patcher | Apache License 2.0 |
core/src/com/sergey/spacegame/common/util/CombinedIterator.kt | SergeySave | 88,623,560 | false | {"Java": 243814, "Kotlin": 180384, "Lua": 12948, "GLSL": 696, "Shell": 88} | package com.sergey.spacegame.common.util
/**
* An iterator that acts as a combination of other iterators
*
* @param E - the type of object returned by this iterator
*
* @author sergeys
*
* @constructor Creates a new CombinedIterator from a set of iterators
*
* @param iterators - an array of iterators
*/
class CombinedIterator<out E>(vararg iterators: Iterator<E>) : Iterator<E> {
private var iters: Array<out Iterator<E>> = iterators
private var index = 0
override fun hasNext(): Boolean {
while (true) {
if (index >= iters.size) return false
if (iters[index].hasNext()) return true
++index
}
}
override fun next(): E {
return iters[index].next()
}
}
| 1 | Java | 1 | 2 | b3a73ac904e379cfc038fa04e5f8042855398c66 | 763 | SpaceGame | MIT License |
feature/welcome/src/commonMain/kotlin/com/cdcoding/welcome/presentation/WelcomeIntent.kt | Christophe-DC | 822,562,468 | false | {"Kotlin": 728291, "Ruby": 4739, "Swift": 617} | package com.cdcoding.welcome.presentation
sealed interface WelcomeIntent {
object OnCreateNewWallet : WelcomeIntent
object OnImportWallet : WelcomeIntent
} | 0 | Kotlin | 0 | 0 | bc7c3eb161ee18db83402ded314e2e0b72196974 | 164 | secureWallet | Apache License 2.0 |
app/src/main/java/in/surajsau/jisho/domain/facenet/SaveFaceEmbedding.kt | surajsau | 434,128,847 | false | {"Kotlin": 212448} | package `in`.surajsau.jisho.domain.facenet
import `in`.surajsau.jisho.data.FileProvider
import `in`.surajsau.jisho.data.facenet.FaceRecognitionProvider
import javax.inject.Inject
class SaveFaceEmbedding @Inject constructor(
private val fileProvider: FileProvider,
private val faceRecognitionProvider: FaceRecognitionProvider,
) {
suspend fun invoke(faceName: String, faceFileName: String) {
val bitmap = fileProvider.fetchCachedBitmap(fileName = faceFileName)
val embeddings = faceRecognitionProvider.generateEmbedding(bitmap)
faceRecognitionProvider.saveEmbedding(faceName = faceName, embedding = embeddings)
}
} | 2 | Kotlin | 5 | 15 | 66ca1373067c57257e7d26f9b922d2d0915b0f4a | 657 | ML-Android | Apache License 2.0 |
app/src/main/java/datanapps/androidutility/utils/kotlin/DNAAppUtils.kt | datanapps | 165,179,466 | false | null | package datanapps.androidutility.utils.kotlin
import datanapps.androidutility.BuildConfig
/*
*
* Yogendra
* 11/01/2019
*
* */
object DNAAppUtils {
/*
* This included because, sonar raise create bug each class should have constructor
* */
/*
* Application Version name
* */
val appVersionName: String
get() = BuildConfig.VERSION_NAME
/*
* Application Version Code
* */
val appVersionCode: Int
get() = BuildConfig.VERSION_CODE
/*
*
* Application package name and id both are same
* */
val applicationId: String
get() = BuildConfig.APPLICATION_ID
/*
*
* Application package name
* */
val applicationPackageName: String
get() = applicationId
/*
*
* Application build type
* */
val buildType: String
get() = BuildConfig.BUILD_TYPE
/*
*
* Application build type
* */
val isDebug: Boolean
get() = BuildConfig.DEBUG
}
| 0 | null | 2 | 14 | 2160d3d7ba0227953c17957e2073cdcb3cdd14b4 | 1,087 | AndroidUtility | Apache License 2.0 |
wanpu/src/main/java/com/allever/lib/ad/wanpu/WanpuMainActivity.kt | devallever | 220,405,258 | false | {"Java": 122044, "Kotlin": 107945} | package com.allever.lib.ad.wanpu
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import com.allever.lib.ad.ADType
import com.allever.lib.ad.AdHelper
import com.allever.lib.common.app.App
import com.allever.lib.common.app.BaseActivity
class WanpuMainActivity: BaseActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_wanpu_main)
AdHelper.init(this, WanPuAdHelper, "")
val bannerAd = AdHelper.createAd(ADType.BANNER)
val bannerContainer = findViewById<LinearLayout>(R.id.bannerContainer)
bannerAd?.loadAndShow("", bannerContainer, null)
findViewById<View>(R.id.btnBanner).setOnClickListener(this)
findViewById<View>(R.id.btnInsert).setOnClickListener(this)
mHandler.postDelayed({
AdHelper.createInsertAd()?.load("", null, null)
}, 2000)
}
override fun onClick(view: View?) {
when(view?.id) {
R.id.btnInsert -> {
val insertAd = AdHelper.createAd(ADType.INSERT)
insertAd?.loadAndShow("", null, null)
}
R.id.btnBanner -> {
val bannerAd = AdHelper.createAd(ADType.BANNER)
val bannerContainer = findViewById<LinearLayout>(R.id.bannerContainer)
bannerContainer?.removeAllViews()
bannerAd?.loadAndShow("", bannerContainer, null)
}
}
}
override fun onDestroy() {
super.onDestroy()
AdHelper.destroy(this)
}
} | 1 | null | 1 | 1 | fe3e144df62174c1d8c7b36f42d808b5053fc11d | 1,637 | AndroidAdLibs | Apache License 2.0 |
dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/Methods.kt | kevinwang19810108 | 91,427,537 | true | {"INI": 10, "Gradle": 19, "Shell": 1, "EditorConfig": 1, "Markdown": 3, "Proguard": 5, "Text": 1, "Ignore List": 6, "Git Config": 1, "Kotlin": 131, "Java": 209, "XML": 16, "SQL": 1, "Java Properties": 1} | package com.raizlabs.android.dbflow.processor.definition
import com.grosner.kpoet.*
import com.raizlabs.android.dbflow.processor.ClassNames
import com.raizlabs.android.dbflow.processor.definition.column.wrapperCommaIfBaseModel
import com.raizlabs.android.dbflow.processor.utils.ModelUtils
import com.raizlabs.android.dbflow.processor.utils.`override fun`
import com.raizlabs.android.dbflow.processor.utils.codeBlock
import com.raizlabs.android.dbflow.processor.utils.isNullOrEmpty
import com.raizlabs.android.dbflow.sql.QueryBuilder
import com.squareup.javapoet.*
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import javax.lang.model.element.Modifier
/**
* Description:
*/
interface MethodDefinition {
val methodSpec: MethodSpec?
}
/**
* Description:
*
* @author <NAME> (fuzz)
*/
/**
* Description: Writes the bind to content values method in the ModelDAO.
*/
class BindToContentValuesMethod(private val baseTableDefinition: BaseTableDefinition,
private val isInsert: Boolean,
private val implementsContentValuesListener: Boolean) : MethodDefinition {
override val methodSpec: MethodSpec?
get() {
val methodBuilder = MethodSpec.methodBuilder(if (isInsert) "bindToInsertValues" else "bindToContentValues")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addParameter(ClassNames.CONTENT_VALUES, PARAM_CONTENT_VALUES)
.addParameter(baseTableDefinition.parameterClassName, ModelUtils.variable)
.returns(TypeName.VOID)
var retMethodBuilder: MethodSpec.Builder? = methodBuilder
if (isInsert) {
baseTableDefinition.columnDefinitions.forEach {
if (!it.isPrimaryKeyAutoIncrement && !it.isRowId) {
methodBuilder.addCode(it.contentValuesStatement)
}
}
if (implementsContentValuesListener) {
methodBuilder.addStatement("\$L.onBindTo\$LValues(\$L)",
ModelUtils.variable, if (isInsert) "Insert" else "Content", PARAM_CONTENT_VALUES)
}
} else {
if (baseTableDefinition.hasAutoIncrement || baseTableDefinition.hasRowID) {
val autoIncrement = baseTableDefinition.autoIncrementColumn
autoIncrement?.let {
methodBuilder.addCode(autoIncrement.contentValuesStatement)
}
} else if (!implementsContentValuesListener) {
retMethodBuilder = null
}
methodBuilder.addStatement("bindToInsertValues(\$L, \$L)", PARAM_CONTENT_VALUES, ModelUtils.variable)
if (implementsContentValuesListener) {
methodBuilder.addStatement("\$L.onBindTo\$LValues(\$L)",
ModelUtils.variable, if (isInsert) "Insert" else "Content", PARAM_CONTENT_VALUES)
}
}
return retMethodBuilder?.build()
}
companion object {
val PARAM_CONTENT_VALUES = "values"
}
}
/**
* Description:
*/
class BindToStatementMethod(private val tableDefinition: TableDefinition, private val isInsert: Boolean) : MethodDefinition {
override val methodSpec: MethodSpec?
get() {
val methodBuilder = MethodSpec.methodBuilder(if (isInsert) "bindToInsertStatement" else "bindToStatement")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addParameter(ClassNames.DATABASE_STATEMENT, PARAM_STATEMENT)
.addParameter(tableDefinition.parameterClassName,
ModelUtils.variable).returns(TypeName.VOID)
// write the reference method
if (isInsert) {
methodBuilder.addParameter(TypeName.INT, PARAM_START)
val realCount = AtomicInteger(1)
tableDefinition.columnDefinitions.forEach {
if (!it.isPrimaryKeyAutoIncrement && !it.isRowId) {
methodBuilder.addCode(it.getSQLiteStatementMethod(realCount))
realCount.incrementAndGet()
}
}
if (tableDefinition.implementsSqlStatementListener) {
methodBuilder.addStatement("${ModelUtils.variable}.onBindTo\$LStatement($PARAM_STATEMENT)",
if (isInsert) "Insert" else "")
}
} else {
var start = 0
if (tableDefinition.hasAutoIncrement || tableDefinition.hasRowID) {
val autoIncrement = tableDefinition.autoIncrementColumn
autoIncrement?.let {
methodBuilder.addStatement("int start = 0")
methodBuilder.addCode(it.getSQLiteStatementMethod(AtomicInteger(++start)))
}
methodBuilder.addStatement("bindToInsertStatement($PARAM_STATEMENT, ${ModelUtils.variable}, $start)")
} else if (tableDefinition.implementsSqlStatementListener) {
methodBuilder.addStatement("bindToInsertStatement($PARAM_STATEMENT, ${ModelUtils.variable}, $start)")
methodBuilder.addStatement("${ModelUtils.variable}.onBindTo\$LStatement($PARAM_STATEMENT)",
if (isInsert) "Insert" else "")
} else {
// don't generate method
return null
}
}
return methodBuilder.build()
}
companion object {
val PARAM_STATEMENT = "statement"
val PARAM_START = "start"
}
}
/**
* Description:
*/
class CreationQueryMethod(private val tableDefinition: TableDefinition) : MethodDefinition {
override val methodSpec: MethodSpec
get() = `override fun`(String::class, "getCreationQuery") {
modifiers(public, final)
val foreignSize = tableDefinition.foreignKeyDefinitions.size
val creationBuilder = codeBlock {
add("CREATE TABLE IF NOT EXISTS ${QueryBuilder.quote(tableDefinition.tableName)}(")
add(tableDefinition.columnDefinitions.joinToString { it.creationName.toString() })
tableDefinition.uniqueGroupsDefinitions.forEach {
if (!it.columnDefinitionList.isEmpty()) add(it.creationName)
}
if (!tableDefinition.hasAutoIncrement) {
val primarySize = tableDefinition.primaryColumnDefinitions.size
if (primarySize > 0) {
add(", PRIMARY KEY(${tableDefinition.primaryColumnDefinitions.joinToString { it.primaryKeyName.toString() }})")
if (!tableDefinition.primaryKeyConflictActionName.isNullOrEmpty()) {
add(" ON CONFLICT ${tableDefinition.primaryKeyConflictActionName}")
}
}
}
if (foreignSize == 0) {
add(")")
}
this
}
val codeBuilder = CodeBlock.builder()
.add("return ${creationBuilder.toString().S}")
val foreignKeyBlocks = ArrayList<CodeBlock>()
val tableNameBlocks = ArrayList<CodeBlock>()
val referenceKeyBlocks = ArrayList<CodeBlock>()
for (i in 0..foreignSize - 1) {
val foreignKeyBuilder = CodeBlock.builder()
val referenceBuilder = CodeBlock.builder()
val fk = tableDefinition.foreignKeyDefinitions[i]
foreignKeyBlocks.add(foreignKeyBuilder.apply {
add(", FOREIGN KEY(")
add(fk._foreignKeyReferenceDefinitionList.joinToString { QueryBuilder.quote(it.columnName) })
add(") REFERENCES ")
}.build())
tableNameBlocks.add(codeBlock { add("\$T.getTableName(\$T.class)", ClassNames.FLOW_MANAGER, fk.referencedTableClassName) })
referenceKeyBlocks.add(referenceBuilder.apply {
add("(")
add(fk._foreignKeyReferenceDefinitionList.joinToString { QueryBuilder.quote(it.foreignColumnName) })
add(") ON UPDATE ${fk.onUpdate.name.replace("_", " ")} ON DELETE ${fk.onDelete.name.replace("_", " ")}")
if (fk.deferred) {
add(" DEFERRABLE INITIALLY DEFERRED")
}
}.build())
}
if (foreignSize > 0) {
for (i in 0..foreignSize - 1) {
codeBuilder.add("+ ${foreignKeyBlocks[i].S} + ${tableNameBlocks[i]} + ${referenceKeyBlocks[i].S}")
}
codeBuilder.add(" + ${");".S};\n")
} else {
codeBuilder.add(";\n")
}
addCode(codeBuilder.build())
}
}
/**
* Description: Writes out the custom type converter fields.
*/
class CustomTypeConverterPropertyMethod(private val baseTableDefinition: BaseTableDefinition)
: TypeAdder, CodeAdder {
override fun addToType(typeBuilder: TypeSpec.Builder) {
val customTypeConverters = baseTableDefinition.associatedTypeConverters.keys
customTypeConverters.forEach {
typeBuilder.`private final field`(it, "typeConverter${it.simpleName()}") { `=`("new \$T()", it) }
}
val globalTypeConverters = baseTableDefinition.globalTypeConverters.keys
globalTypeConverters.forEach {
typeBuilder.`private final field`(it, "global_typeConverter${it.simpleName()}")
}
}
override fun addCode(code: CodeBlock.Builder): CodeBlock.Builder {
// Constructor code
val globalTypeConverters = baseTableDefinition.globalTypeConverters.keys
globalTypeConverters.forEach {
val def = baseTableDefinition.globalTypeConverters[it]
val firstDef = def?.get(0)
firstDef?.typeConverterElementNames?.forEach { elementName ->
code.statement("global_typeConverter${it.simpleName()} " +
"= (\$T) holder.getTypeConverterForClass(\$T.class)", it, elementName)
}
}
return code
}
}
/**
* Description:
*/
class ExistenceMethod(private val tableDefinition: BaseTableDefinition) : MethodDefinition {
override val methodSpec
get() = `override fun`(TypeName.BOOLEAN, "exists",
param(tableDefinition.parameterClassName!!, ModelUtils.variable),
param(ClassNames.DATABASE_WRAPPER, "wrapper")) {
modifiers(public, final)
code {
// only quick check if enabled.
var primaryColumn = tableDefinition.autoIncrementColumn
if (primaryColumn == null) {
primaryColumn = tableDefinition.primaryColumnDefinitions[0]
}
primaryColumn.appendExistenceMethod(this)
this
}
}
}
/**
* Description:
*/
class InsertStatementQueryMethod(private val tableDefinition: TableDefinition, private val isInsert: Boolean) : MethodDefinition {
override val methodSpec: MethodSpec?
get() {
if (isInsert && !tableDefinition.hasAutoIncrement) {
return null // dont write method here because we reuse the compiled statement query method
}
return `override fun`(String::class,
if (isInsert) "getInsertStatementQuery" else "getCompiledStatementQuery") {
modifiers(public, final)
val isSingleAutoincrement = tableDefinition.hasAutoIncrement
&& tableDefinition.columnDefinitions.size == 1 && isInsert
`return`(codeBlock {
add("INSERT ")
if (!tableDefinition.insertConflictActionName.isEmpty()) {
add("OR ${tableDefinition.insertConflictActionName} ")
}
add("INTO ${QueryBuilder.quote(tableDefinition.tableName)}(")
tableDefinition.columnDefinitions.filter {
!it.isPrimaryKeyAutoIncrement && !it.isRowId || !isInsert || isSingleAutoincrement
}.forEachIndexed { index, columnDefinition ->
if (index > 0) add(",")
add(columnDefinition.insertStatementColumnName)
}
add(") VALUES (")
tableDefinition.columnDefinitions.filter { !it.isPrimaryKeyAutoIncrement && !it.isRowId || !isInsert }
.forEachIndexed { index, columnDefinition ->
if (index > 0) add(",")
add(columnDefinition.insertStatementValuesString)
}
if (isSingleAutoincrement) add("NULL")
add(")")
}.S)
}
}
}
/**
* Description:
*/
class LoadFromCursorMethod(private val baseTableDefinition: BaseTableDefinition) : MethodDefinition {
override val methodSpec: MethodSpec
get() = `override fun`(TypeName.VOID, "loadFromCursor",
param(ClassNames.FLOW_CURSOR, PARAM_CURSOR),
param(baseTableDefinition.parameterClassName!!, ModelUtils.variable)) {
modifiers(public, final)
val index = AtomicInteger(0)
val nameAllocator = NameAllocator() // unique names
baseTableDefinition.columnDefinitions.forEach {
addCode(it.getLoadFromCursorMethod(true, index, nameAllocator))
index.incrementAndGet()
}
if (baseTableDefinition is TableDefinition) {
val foundDef = baseTableDefinition.oneToManyDefinitions.find { it.hasWrapper }
foundDef?.let { foundDef.writeWrapperStatement(this) }
code {
baseTableDefinition.oneToManyDefinitions
.filter { it.isLoad }
.forEach { it.writeLoad(this) }
this
}
}
if (baseTableDefinition is TableDefinition && baseTableDefinition.implementsLoadFromCursorListener) {
statement("${ModelUtils.variable}.onLoadFromCursor($PARAM_CURSOR)")
}
this
}
companion object {
val PARAM_CURSOR = "cursor"
}
}
/**
* Description:
*/
class OneToManyDeleteMethod(private val tableDefinition: TableDefinition,
private val useWrapper: Boolean) : MethodDefinition {
override val methodSpec: MethodSpec?
get() {
val shouldWrite = tableDefinition.oneToManyDefinitions.any { it.isDelete }
if (shouldWrite || tableDefinition.cachingEnabled) {
return `override fun`(TypeName.BOOLEAN, "delete",
param(tableDefinition.elementClassName!!, ModelUtils.variable)) {
modifiers(public, final)
if (useWrapper) {
addParameter(ClassNames.DATABASE_WRAPPER, ModelUtils.wrapper)
}
if (tableDefinition.cachingEnabled) {
statement("getModelCache().removeModel(getCachingId(${ModelUtils.variable}))")
}
statement("boolean successful = super.delete(${ModelUtils.variable}${wrapperCommaIfBaseModel(useWrapper)})")
if (!useWrapper) {
val foundDef = tableDefinition.oneToManyDefinitions.find { it.hasWrapper }
foundDef?.let { foundDef.writeWrapperStatement(this) }
}
tableDefinition.oneToManyDefinitions.forEach { it.writeDelete(this, useWrapper) }
`return`("successful")
}
}
return null
}
}
/**
* Description: Overrides the save, update, and insert methods if the [com.raizlabs.android.dbflow.annotation.OneToMany.Method.SAVE] is used.
*/
class OneToManySaveMethod(private val tableDefinition: TableDefinition,
private val methodName: String,
private val useWrapper: Boolean) : MethodDefinition {
override val methodSpec: MethodSpec?
get() {
if (!tableDefinition.oneToManyDefinitions.isEmpty() || tableDefinition.cachingEnabled) {
var retType = TypeName.BOOLEAN
var retStatement = "successful"
when (methodName) {
METHOD_INSERT -> {
retType = ClassName.LONG
retStatement = "rowId"
}
}
return `override fun`(retType, methodName,
param(tableDefinition.elementClassName!!, ModelUtils.variable)) {
modifiers(public, final)
if (useWrapper) {
addParameter(ClassNames.DATABASE_WRAPPER, ModelUtils.wrapper)
}
code {
if (methodName == METHOD_INSERT) {
add("long rowId = ")
} else if (methodName == METHOD_UPDATE || methodName == METHOD_SAVE) {
add("boolean successful = ")
}
statement("super.$methodName(${ModelUtils.variable}${wrapperCommaIfBaseModel(useWrapper)})")
if (tableDefinition.cachingEnabled) {
statement("getModelCache().addModel(getCachingId(${ModelUtils.variable}), ${ModelUtils.variable})")
}
this
}
// need wrapper access if we have wrapper param here.
if (!useWrapper) {
val foundDef = tableDefinition.oneToManyDefinitions.find { it.hasWrapper }
foundDef?.let { foundDef.writeWrapperStatement(this) }
}
for (oneToManyDefinition in tableDefinition.oneToManyDefinitions) {
when (methodName) {
METHOD_SAVE -> oneToManyDefinition.writeSave(this, useWrapper)
METHOD_UPDATE -> oneToManyDefinition.writeUpdate(this, useWrapper)
METHOD_INSERT -> oneToManyDefinition.writeInsert(this, useWrapper)
}
}
`return`(retStatement)
}
} else {
return null
}
}
companion object {
val METHOD_SAVE = "save"
val METHOD_UPDATE = "update"
val METHOD_INSERT = "insert"
}
}
/**
* Description: Creates a method that builds a clause of ConditionGroup that represents its primary keys. Useful
* for updates or deletes.
*/
class PrimaryConditionMethod(private val tableDefinition: BaseTableDefinition) : MethodDefinition {
override val methodSpec: MethodSpec?
get() = `override fun`(ClassNames.OPERATOR_GROUP, "getPrimaryConditionClause",
param(tableDefinition.parameterClassName!!, ModelUtils.variable)) {
modifiers(public, final)
code {
statement("\$T clause = \$T.clause()", ClassNames.OPERATOR_GROUP, ClassNames.OPERATOR_GROUP)
tableDefinition.primaryColumnDefinitions.forEach {
val codeBuilder = CodeBlock.builder()
it.appendPropertyComparisonAccessStatement(codeBuilder)
add(codeBuilder.build())
}
this
}
`return`("clause")
}
}
| 0 | Java | 0 | 0 | 8bec1a5e3e6a04168271ab91fdc5d94c7a24c7fd | 20,141 | DBFlow | MIT License |
lib/src/main/java/com/mobilabsolutions/stash/core/exceptions/base/AuthenticationException.kt | mobilabsolutions | 152,575,999 | false | null | /*
* Copyright © MobiLab Solutions GmbH
*/
package com.mobilabsolutions.stash.core.exceptions.base
class AuthenticationException(
override val message: String = "Authentication Failed",
override val code: Int? = null,
override val errorTitle: String? = null,
override val originalException: Throwable? = null
) : BasePaymentException(message, errorTitle, code, originalException)
| 1 | Kotlin | 1 | 2 | 9a1a5b978e7edc0a29b3360e4018eb9aabb9b27a | 400 | stash-sdk-android | Apache License 2.0 |
app/src/main/java/com/jimipurple/himichat/models/FriendRequest.kt | Gladozzz | 213,230,372 | false | null | package com.jimipurple.himichat.models
class FriendRequest(
val id : String,
val nickname : String,
val realName : String,
val avatar : String,
received : Boolean
) {
val isReceived = received
val isSent = !received
}
| 0 | Kotlin | 0 | 2 | 8ff8368322050c38ce301121e839e5629491c996 | 248 | HimiChat | MIT License |
src/main/kotlin/com/github/oowekyala/ijcc/lang/psi/JccNodeExtensions.kt | oowekyala | 160,946,520 | false | {"Kotlin": 636577, "HTML": 12321, "Lex": 10654, "Shell": 1940, "Just": 101} | package com.github.oowekyala.ijcc.lang.psi
import com.github.oowekyala.ijcc.lang.model.AccessModifier
/*
Miscellaneous semantic extensions for jcc nodes.
*/
val JccJavaAccessModifier.modelConstant: AccessModifier
get() = when (text) {
"" -> AccessModifier.PACKAGE_LOCAL
"public" -> AccessModifier.PUBLIC
"protected" -> AccessModifier.PROTECTED
"private" -> AccessModifier.PRIVATE
else -> throw IllegalStateException()
}
| 11 | Kotlin | 6 | 44 | c514083a161db56537d2473e42f2a1d4bf57eee1 | 499 | intellij-javacc | MIT License |
src/test/kotlin/uk/gov/justice/digital/hmpps/manageoffencesapi/entity/OffenceTest.kt | ministryofjustice | 460,455,417 | false | null | package uk.gov.justice.digital.hmpps.manageoffencesapi.entity
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import uk.gov.justice.digital.hmpps.manageoffencesapi.enum.SdrsCache.OFFENCES_A
import java.time.LocalDate
import java.time.LocalDateTime
class OffenceTest {
@Test
fun `Check statute and homeOfficeStatsCode with minimum data`() {
val of = BASE_OFFENCE.copy(sdrsCache = OFFENCES_A, code = "A1234")
assertThat(of.statuteCode).isEqualTo("A123")
assertThat(of.homeOfficeStatsCode).isNull()
}
@Test
fun `Check homeOfficeStatsCode with no subcategory`() {
val of = BASE_OFFENCE.copy(sdrsCache = OFFENCES_A, code = "A1234", category = 12)
assertThat(of.homeOfficeStatsCode).isEqualTo("012/")
}
@Test
fun `Check homeOfficeStatsCode with no category`() {
val of = BASE_OFFENCE.copy(sdrsCache = OFFENCES_A, code = "A1234", subCategory = 5)
assertThat(of.homeOfficeStatsCode).isEqualTo("/05")
}
@Test
fun `Check homeOfficeStatsCode with both category and sub-category`() {
val of = BASE_OFFENCE.copy(sdrsCache = OFFENCES_A, code = "A1234", category = 12, subCategory = 5)
assertThat(of.homeOfficeStatsCode).isEqualTo("012/05")
}
companion object {
private val BASE_OFFENCE = Offence(
code = "AABB011",
changedDate = LocalDateTime.now(),
revisionId = 1,
startDate = LocalDate.now(),
sdrsCache = OFFENCES_A,
)
}
}
| 0 | Kotlin | 0 | 0 | d3b2b1d073de6ef6697bcb11342fc78a6c5245f6 | 1,455 | hmpps-manage-offences-api | MIT License |
src/main/kotlin/ink/ptms/chemdah/core/quest/objective/marriagemaster/MMarriageHug.kt | TabooLib | 338,114,548 | false | null | package ink.ptms.chemdah.core.quest.objective.marriagemaster
import at.pcgamingfreaks.MarriageMaster.Bukkit.API.Events.HugEvent
import ink.ptms.chemdah.core.quest.objective.Dependency
import ink.ptms.chemdah.core.quest.objective.ObjectiveCountableI
@Dependency("MarriageMaster")
object MMarriageHug : ObjectiveCountableI<HugEvent>() {
override val name = "marriage hug"
override val event = HugEvent::class
init {
handler {
player.playerOnline
}
addSimpleCondition("position") {
toPosition().inside(it.player.playerOnline!!.location)
}
}
} | 1 | Kotlin | 16 | 24 | b0a711100f55498b6a0495043cb8ef736257f7be | 615 | Chemdah | MIT License |
mesh-exam/feature/discover/src/main/java/io/flaterlab/meshexam/presentation/discover/ui/info/ExamInfoLauncher.kt | chorobaev | 434,863,301 | false | {"Kotlin": 467494, "Java": 1951} | package io.flaterlab.meshexam.presentation.discover.ui.info
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
internal data class ExamInfoLauncher(
val examId: String,
val examName: String,
val examDurationInMin: Int,
val examHostName: String,
) : Parcelable | 0 | Kotlin | 0 | 2 | 364c4fcb70a461fc02d2a5ef2590ad5f8975aab5 | 301 | mesh-exam | MIT License |
solar/src/main/java/com/chiksmedina/solar/outline/businessstatistic/CourseDown.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.outline.businessstatistic
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.outline.BusinessStatisticGroup
val BusinessStatisticGroup.CourseDown: ImageVector
get() {
if (_courseDown != null) {
return _courseDown!!
}
_courseDown = Builder(
name = "CourseDown", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(1.4686f, 6.4708f)
curveTo(1.7609f, 6.1773f, 2.2357f, 6.1763f, 2.5292f, 6.4686f)
lineTo(6.4479f, 10.3708f)
curveTo(6.9617f, 10.8825f, 7.2948f, 11.2119f, 7.5722f, 11.4228f)
curveTo(7.8323f, 11.6205f, 7.954f, 11.6426f, 8.0345f, 11.6426f)
curveTo(8.1151f, 11.6427f, 8.2367f, 11.6206f, 8.497f, 11.4231f)
curveTo(8.7746f, 11.2125f, 9.1079f, 10.8833f, 9.6221f, 10.372f)
lineTo(9.8963f, 10.0993f)
curveTo(10.3651f, 9.633f, 10.7693f, 9.2312f, 11.1363f, 8.9526f)
curveTo(11.5297f, 8.654f, 11.9668f, 8.4281f, 12.505f, 8.428f)
curveTo(13.0432f, 8.428f, 13.4805f, 8.6538f, 13.8739f, 8.9523f)
curveTo(14.241f, 9.2308f, 14.6452f, 9.6326f, 15.1142f, 10.0987f)
lineTo(21.25f, 16.1971f)
verticalLineTo(12.4542f)
curveTo(21.25f, 12.04f, 21.5858f, 11.7042f, 22.0f, 11.7042f)
curveTo(22.4142f, 11.7042f, 22.75f, 12.04f, 22.75f, 12.4542f)
verticalLineTo(18.0f)
curveTo(22.75f, 18.4142f, 22.4142f, 18.75f, 22.0f, 18.75f)
horizontalLineTo(16.4179f)
curveTo(16.0037f, 18.75f, 15.6679f, 18.4142f, 15.6679f, 18.0f)
curveTo(15.6679f, 17.5858f, 16.0037f, 17.25f, 16.4179f, 17.25f)
horizontalLineTo(20.1815f)
lineTo(14.0917f, 11.1973f)
curveTo(13.5778f, 10.6866f, 13.2447f, 10.3577f, 12.9674f, 10.1473f)
curveTo(12.7073f, 9.9501f, 12.5858f, 9.928f, 12.5052f, 9.928f)
curveTo(12.4247f, 9.928f, 12.3031f, 9.9501f, 12.0431f, 10.1474f)
curveTo(11.7658f, 10.3579f, 11.4328f, 10.6868f, 10.9191f, 11.1976f)
lineTo(10.6448f, 11.4704f)
curveTo(10.1755f, 11.937f, 9.7711f, 12.3393f, 9.4038f, 12.618f)
curveTo(9.0101f, 12.9168f, 8.5726f, 13.1428f, 8.034f, 13.1426f)
curveTo(7.4954f, 13.1424f, 7.0581f, 12.9161f, 6.6645f, 12.617f)
curveTo(6.2975f, 12.338f, 5.8933f, 11.9355f, 5.4244f, 11.4685f)
curveTo(5.4128f, 11.4569f, 5.4012f, 11.4453f, 5.3895f, 11.4337f)
lineTo(1.4708f, 7.5314f)
curveTo(1.1773f, 7.2392f, 1.1763f, 6.7643f, 1.4686f, 6.4708f)
close()
}
}
.build()
return _courseDown!!
}
private var _courseDown: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 3,703 | SolarIconSetAndroid | MIT License |
engine/src/main/kotlin/io/rsbox/engine/game/model/entity/Player.kt | Rune-Status | 204,377,839 | false | null | package io.rsbox.engine.game.model.entity
import io.rsbox.api.event.EventManager
import io.rsbox.api.event.impl.PlayerLoadEvent
import io.rsbox.engine.Engine
import io.rsbox.engine.game.model.Appearance
import io.rsbox.engine.game.model.World
import io.rsbox.engine.game.model.block.PlayerBlockType
import io.rsbox.engine.game.model.interf.InterfaceManager
import io.rsbox.engine.net.Session
import io.rsbox.engine.net.game.Message
import io.rsbox.engine.net.game.impl.message.RegionRebuildMessage
/**
* @author <NAME>
*/
class Player(override val engine: Engine, override val world: World) : LivingEntity(), io.rsbox.api.entity.Player {
lateinit var session: Session
/**
* Player Data
*/
override lateinit var username: String
override lateinit var passwordHash: String
override lateinit var uuid: String
override lateinit var displayName: String
override var privilege: Int = 0
override var banned: Boolean = false
override var initiated = false
var lastIndex = -1
/**
* Global indexes
* GPI is arrays of entities which holds the data used to calculate what players are needed
* to be drawn on the client.
*/
val gpiLocalPlayers = arrayOfNulls<Player>(2048)
val gpiLocalIndexes = IntArray(2048)
var gpiLocalCount = 0
val gpiExternalIndexes = IntArray(2048)
var gpiExternalCount = 0
val gpiInactivityFlags = IntArray(2048)
val gpiTileHashMultipliers = IntArray(2048)
val isOnline: Boolean get() = index > 0
/**
* The interface manager.
* Handles all actions available for interface interaction for this player.
*/
override val interfaces = InterfaceManager(this)
override fun _interfaces(): io.rsbox.api.interf.InterfaceManager {
return interfaces
}
var appearance: Appearance = Appearance.DEFAULT
fun register() {
world.register(this)
}
fun login() {
// Setup initial GPI data.
gpiLocalPlayers[index] = this
gpiLocalIndexes[gpiLocalCount++] = index
for(i in 1 until 2048) {
if(i == index) continue
gpiExternalIndexes[gpiExternalCount++] = i
gpiTileHashMultipliers[i] = if(i < world.players.capacity) world.players[i]?.tile?.asTileHashMultiplier ?: 0 else 0
}
val tiles = IntArray(gpiTileHashMultipliers.size) { gpiTileHashMultipliers[it] }
write(RegionRebuildMessage(tile, engine.xteaKeyService, index, tiles))
initiated = true
this.addBlock(PlayerBlockType.APPEARANCE)
/**
* Trigger PlayerLoadEvent.
*/
EventManager.trigger(PlayerLoadEvent(this), {})
}
fun addBlock(block: PlayerBlockType) {
val bit = block.bit
blockState.addBit(bit)
}
fun hasBlock(block: PlayerBlockType): Boolean {
val bit = block.bit
return blockState.hasBit(bit)
}
fun prePulse() {
}
fun pulse() {
this.session.pulse()
}
fun postPulse() {
}
/**
* Network related functions
*/
fun write(message: Message) {
session.write(message)
}
fun flush() {
session.flush()
}
fun close() {
session.close()
}
companion object {
const val NORMAL_RENDER_DISTANCE = 15
const val LARGE_RENDER_DISTANCE = 127
}
} | 0 | Kotlin | 1 | 1 | 5a30213d4528554c7b544cecc145465294f292eb | 3,394 | rsbox-rsbox | MIT License |
shared/domain/trailers/api/src/commonMain/kotlin/com.thomaskioko/tvmaniac.shared.domain.trailers.api/TrailerCache.kt | c0de-wizard | 361,393,353 | false | null | package com.thomaskioko.tvmaniac.shared.domain.trailers.api
import com.thomaskioko.tvmaniac.core.db.Trailers
import kotlinx.coroutines.flow.Flow
interface TrailerCache {
fun insert(trailer: Trailers)
fun insert(trailerList: List<Trailers>)
fun getTrailersByShowId(showId: Int): Flow<List<Trailers>>
}
| 3 | Kotlin | 8 | 81 | 9df7429257c4cff0346734392c89b8017b90bd45 | 319 | tv-maniac | Apache License 2.0 |
src/main/kotlin/vkk/vk10/structs/PipelineColorBlendAttachmentState.kt | kotlin-graphics | 132,931,904 | false | null | package vkk.vk10.structs
import glm_.i
import kool.Ptr
import org.lwjgl.system.MemoryStack
import org.lwjgl.vulkan.VkPipelineColorBlendAttachmentState.*
import vkk.VkBlendFactor
import vkk.VkBlendOp
import vkk.VkColorComponentFlags
/**
* Structure specifying a pipeline color blend attachment state.
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>If the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#features-dualSrcBlend">dual source blending</a> feature is not enabled, {@code srcColorBlendFactor} <b>must</b> not be {@link VK10#VK_BLEND_FACTOR_SRC1_COLOR BLEND_FACTOR_SRC1_COLOR}, {@link VK10#VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR BLEND_FACTOR_ONE_MINUS_SRC1_COLOR}, {@link VK10#VK_BLEND_FACTOR_SRC1_ALPHA BLEND_FACTOR_SRC1_ALPHA}, or {@link VK10#VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA}</li>
* <li>If the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#features-dualSrcBlend">dual source blending</a> feature is not enabled, {@code dstColorBlendFactor} <b>must</b> not be {@link VK10#VK_BLEND_FACTOR_SRC1_COLOR BLEND_FACTOR_SRC1_COLOR}, {@link VK10#VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR BLEND_FACTOR_ONE_MINUS_SRC1_COLOR}, {@link VK10#VK_BLEND_FACTOR_SRC1_ALPHA BLEND_FACTOR_SRC1_ALPHA}, or {@link VK10#VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA}</li>
* <li>If the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#features-dualSrcBlend">dual source blending</a> feature is not enabled, {@code srcAlphaBlendFactor} <b>must</b> not be {@link VK10#VK_BLEND_FACTOR_SRC1_COLOR BLEND_FACTOR_SRC1_COLOR}, {@link VK10#VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR BLEND_FACTOR_ONE_MINUS_SRC1_COLOR}, {@link VK10#VK_BLEND_FACTOR_SRC1_ALPHA BLEND_FACTOR_SRC1_ALPHA}, or {@link VK10#VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA}</li>
* <li>If the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#features-dualSrcBlend">dual source blending</a> feature is not enabled, {@code dstAlphaBlendFactor} <b>must</b> not be {@link VK10#VK_BLEND_FACTOR_SRC1_COLOR BLEND_FACTOR_SRC1_COLOR}, {@link VK10#VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR BLEND_FACTOR_ONE_MINUS_SRC1_COLOR}, {@link VK10#VK_BLEND_FACTOR_SRC1_ALPHA BLEND_FACTOR_SRC1_ALPHA}, or {@link VK10#VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA}</li>
* <li>If either of {@code colorBlendOp} or {@code alphaBlendOp} is an <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#framebuffer-blend-advanced">advanced blend operation</a>, then {@code colorBlendOp} <b>must</b> equal {@code alphaBlendOp}</li>
* <li>If {@link VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT}{@code ::advancedBlendIndependentBlend} is {@link VK10#VK_FALSE FALSE} and {@code colorBlendOp} is an <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#framebuffer-blend-advanced">advanced blend operation</a>, then {@code colorBlendOp} <b>must</b> be the same for all attachments.</li>
* <li>If {@link VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT}{@code ::advancedBlendIndependentBlend} is {@link VK10#VK_FALSE FALSE} and {@code alphaBlendOp} is an <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#framebuffer-blend-advanced">advanced blend operation</a>, then {@code alphaBlendOp} <b>must</b> be the same for all attachments.</li>
* <li>If {@link VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT}{@code ::advancedBlendAllOperations} is {@link VK10#VK_FALSE FALSE}, then {@code colorBlendOp} <b>must</b> not be {@link EXTBlendOperationAdvanced#VK_BLEND_OP_ZERO_EXT BLEND_OP_ZERO_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_SRC_EXT BLEND_OP_SRC_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_DST_EXT BLEND_OP_DST_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_SRC_OVER_EXT BLEND_OP_SRC_OVER_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_DST_OVER_EXT BLEND_OP_DST_OVER_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_SRC_IN_EXT BLEND_OP_SRC_IN_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_DST_IN_EXT BLEND_OP_DST_IN_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_SRC_OUT_EXT BLEND_OP_SRC_OUT_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_DST_OUT_EXT BLEND_OP_DST_OUT_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_SRC_ATOP_EXT BLEND_OP_SRC_ATOP_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_DST_ATOP_EXT BLEND_OP_DST_ATOP_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_XOR_EXT BLEND_OP_XOR_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_INVERT_EXT BLEND_OP_INVERT_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_INVERT_RGB_EXT BLEND_OP_INVERT_RGB_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_LINEARDODGE_EXT BLEND_OP_LINEARDODGE_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_LINEARBURN_EXT BLEND_OP_LINEARBURN_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_VIVIDLIGHT_EXT BLEND_OP_VIVIDLIGHT_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_LINEARLIGHT_EXT BLEND_OP_LINEARLIGHT_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_PINLIGHT_EXT BLEND_OP_PINLIGHT_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_HARDMIX_EXT BLEND_OP_HARDMIX_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_PLUS_EXT BLEND_OP_PLUS_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_PLUS_CLAMPED_EXT BLEND_OP_PLUS_CLAMPED_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_PLUS_CLAMPED_ALPHA_EXT BLEND_OP_PLUS_CLAMPED_ALPHA_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_PLUS_DARKER_EXT BLEND_OP_PLUS_DARKER_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_MINUS_EXT BLEND_OP_MINUS_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_MINUS_CLAMPED_EXT BLEND_OP_MINUS_CLAMPED_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_CONTRAST_EXT BLEND_OP_CONTRAST_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_INVERT_OVG_EXT BLEND_OP_INVERT_OVG_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_RED_EXT BLEND_OP_RED_EXT}, {@link EXTBlendOperationAdvanced#VK_BLEND_OP_GREEN_EXT BLEND_OP_GREEN_EXT}, or {@link EXTBlendOperationAdvanced#VK_BLEND_OP_BLUE_EXT BLEND_OP_BLUE_EXT}</li>
* <li>If {@code colorBlendOp} or {@code alphaBlendOp} is an <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#framebuffer-blend-advanced">advanced blend operation</a>, then {@link VkSubpassDescription}{@code ::colorAttachmentCount} of the subpass this pipeline is compiled against <b>must</b> be less than or equal to {@link VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT}::advancedBlendMaxColorAttachments</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code srcColorBlendFactor} <b>must</b> be a valid {@code VkBlendFactor} value</li>
* <li>{@code dstColorBlendFactor} <b>must</b> be a valid {@code VkBlendFactor} value</li>
* <li>{@code colorBlendOp} <b>must</b> be a valid {@code VkBlendOp} value</li>
* <li>{@code srcAlphaBlendFactor} <b>must</b> be a valid {@code VkBlendFactor} value</li>
* <li>{@code dstAlphaBlendFactor} <b>must</b> be a valid {@code VkBlendFactor} value</li>
* <li>{@code alphaBlendOp} <b>must</b> be a valid {@code VkBlendOp} value</li>
* <li>{@code colorWriteMask} <b>must</b> be a valid combination of {@code VkColorComponentFlagBits} values</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkPipelineColorBlendStateCreateInfo}</p>
*
* <h3>Member documentation</h3>
*
* <ul>
* <li>{@code blendEnable} – controls whether blending is enabled for the corresponding color attachment. If blending is not enabled, the source fragment’s color for that attachment is passed through unmodified.</li>
* <li>{@code srcColorBlendFactor} – selects which blend factor is used to determine the source factors <code>(S<sub>r</sub>,S<sub>g</sub>,S<sub>b</sub>)</code>.</li>
* <li>{@code dstColorBlendFactor} – selects which blend factor is used to determine the destination factors <code>(D<sub>r</sub>,D<sub>g</sub>,D<sub>b</sub>)</code>.</li>
* <li>{@code colorBlendOp} – selects which blend operation is used to calculate the RGB values to write to the color attachment.</li>
* <li>{@code srcAlphaBlendFactor} – selects which blend factor is used to determine the source factor <code>S<sub>a</sub></code>.</li>
* <li>{@code dstAlphaBlendFactor} – selects which blend factor is used to determine the destination factor <code>D<sub>a</sub></code>.</li>
* <li>{@code alphaBlendOp} – selects which blend operation is use to calculate the alpha values to write to the color attachment.</li>
* <li>{@code colorWriteMask} – a bitmask of {@code VkColorComponentFlagBits} specifying which of the R, G, B, and/or A components are enabled for writing, as described for the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#framebuffer-color-write-mask">Color Write Mask</a>.</li>
* </ul>
*
* <h3>Layout</h3>
*
* <pre><code>
* struct VkPipelineColorBlendAttachmentState {
* VkBool32 blendEnable;
* VkBlendFactor srcColorBlendFactor;
* VkBlendFactor dstColorBlendFactor;
* VkBlendOp colorBlendOp;
* VkBlendFactor srcAlphaBlendFactor;
* VkBlendFactor dstAlphaBlendFactor;
* VkBlendOp alphaBlendOp;
* VkColorComponentFlags colorWriteMask;
* }</code></pre>
*/
class PipelineColorBlendAttachmentState(
var blendEnable: Boolean = false,
var srcColorBlendFactor: VkBlendFactor = VkBlendFactor.ZERO,
var dstColorBlendFactor: VkBlendFactor = VkBlendFactor.ZERO,
var colorBlendOp: VkBlendOp = VkBlendOp.ADD,
var srcAlphaBlendFactor: VkBlendFactor = VkBlendFactor.ZERO,
var dstAlphaBlendFactor: VkBlendFactor = VkBlendFactor.ZERO,
var alphaBlendOp: VkBlendOp = VkBlendOp.ADD,
var colorWriteMask: VkColorComponentFlags = 0
) {
infix fun write(ptr: Ptr) {
nblendEnable(ptr, blendEnable.i)
nsrcColorBlendFactor(ptr, srcColorBlendFactor.i)
ndstColorBlendFactor(ptr, dstColorBlendFactor.i)
ncolorBlendOp(ptr, colorBlendOp.i)
nsrcAlphaBlendFactor(ptr, srcAlphaBlendFactor.i)
ndstAlphaBlendFactor(ptr, dstAlphaBlendFactor.i)
nalphaBlendOp(ptr, alphaBlendOp.i)
ncolorWriteMask(ptr, colorWriteMask)
}
}
infix fun Array<PipelineColorBlendAttachmentState>.write(stack: MemoryStack): Ptr {
val natives = stack.ncalloc(ALIGNOF, size, SIZEOF)
for (i in indices)
this[i].write(natives + SIZEOF * i)
return natives
} | 2 | null | 7 | 96 | 3ae299c509d6c1fa75acd957083a827859cd7097 | 10,721 | vkk | Apache License 2.0 |
app/src/main/java/com/alexiscrack3/spinny/api/ServicesModule.kt | alexiscrack3 | 267,722,677 | false | null | package com.alexiscrack3.spinny.api
import org.koin.dsl.module
var servicesModule = module {
factory {
AuthTokenInterceptor(
securePreferences = get()
)
}
single {
ServicesFactory(
authTokenInterceptor = get<AuthTokenInterceptor>()
)
}
}
| 0 | Kotlin | 1 | 0 | c1e2b7e55fed56a227a6c90432e898489ae47cbf | 312 | spinny-android | MIT License |
app/src/main/java/com/example/hiltdatabindingdemo/di/CustomBindingComponent.kt | nuhkoca | 340,691,411 | false | {"Kotlin": 3862} | package com.example.hiltdatabindingdemo.di
import dagger.hilt.DefineComponent
import dagger.hilt.components.SingletonComponent
@BindingScoped
@DefineComponent(parent = SingletonComponent::class)
interface CustomBindingComponent
| 4 | Kotlin | 2 | 19 | 1dc9b49e6827fb8d832511b57407ed5d0fa990e5 | 230 | HiltDataBindingSample | Apache License 2.0 |
Application/app/src/main/java/com/demo/code/SelectionScreen.kt | devrath | 293,422,796 | false | null | package com.demo.code
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.demo.code.rxbasics.activities.RxBasicsActivity
import com.demo.code.demos.fromapi.activities.SampleOperatorsActivity
import kotlinx.android.synthetic.main.activity_selection_screen.*
import kotlinx.android.synthetic.main.content_main_selection.*
class SelectionScreen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_selection_screen)
rxFundamentalsId.setOnClickListener {
Intent(this, RxBasicsActivity::class.java).apply { startActivity(this) }
}
demoOneId.setOnClickListener {
Intent(this, SampleOperatorsActivity::class.java).apply { startActivity(this) }
}
}
} | 0 | Kotlin | 0 | 0 | 47b6f81b45a8d85c7b96a731403afbe2814605f2 | 881 | fuzzy-reactive-kotlin | Apache License 2.0 |
src/main/kotlin/com/wutsi/flutter/sdui/WidgetAware.kt | wutsi | 415,658,640 | false | null | package com.wutsi.flutter.sdui
interface WidgetAware {
fun toWidget(): Widget
}
| 1 | Kotlin | 1 | 2 | 0e39b6120b9cb6e8acf35c5d4d86cf95e75ebfae | 85 | sdui-kotlin | MIT License |
foundation/network/public/src/main/kotlin/ru/pixnews/foundation/network/inject/AppOkhttpModule.kt | illarionov | 305,333,284 | false | null | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.pixnews.foundation.network.inject
import android.content.Context
import com.squareup.anvil.annotations.ContributesTo
import dagger.Module
import dagger.Provides
import dagger.Reusable
import okhttp3.Cache
import okhttp3.OkHttpClient
import ru.pixnews.foundation.appconfig.NetworkConfig
import ru.pixnews.foundation.di.base.qualifiers.ApplicationContext
import ru.pixnews.foundation.di.base.scopes.AppScope
import ru.pixnews.foundation.di.base.scopes.SingleIn
import ru.pixnews.foundation.network.OkHttpClientProvider
import ru.pixnews.foundation.network.RootOkHttpClientProvider
import ru.pixnews.library.android.utils.precondition.checkNotMainThread
import java.io.File
import javax.inject.Qualifier
private const val OKHTTP_CACHE_SUBDIR = "okhttp"
@ContributesTo(AppScope::class)
@Module
public object AppOkhttpModule {
@Reusable
@Provides
internal fun provideAppOkHttpProvider(
@AppOkHttpClient appClient: dagger.Lazy<@JvmSuppressWildcards OkHttpClient>,
): OkHttpClientProvider {
return object : OkHttpClientProvider {
override fun get(): OkHttpClient = appClient.get()
}
}
@AppOkHttpClient
@Provides
@SingleIn(AppScope::class)
internal fun provideAppHttpClient(
rootOkHttpClientProvider: RootOkHttpClientProvider,
cache: Cache,
): OkHttpClient {
checkNotMainThread()
return rootOkHttpClientProvider.get().newBuilder()
.cache(cache)
.build()
}
@Provides
@SingleIn(AppScope::class)
internal fun provideCache(
networkConfig: NetworkConfig,
@ApplicationContext context: Context,
): Cache {
checkNotMainThread()
@Suppress("MagicNumber")
return Cache(
File(context.cacheDir, OKHTTP_CACHE_SUBDIR),
networkConfig.cacheSizeMbytes.toLong() * 1_000_000L,
)
}
@Qualifier
internal annotation class AppOkHttpClient
}
| 0 | Kotlin | 0 | 2 | d806ee06019389c78546d946f1c20d096afc7c6e | 2,551 | Pixnews | Apache License 2.0 |
tien-common/src/main/java/com/underwood/idgenerator/IDGenerator.kt | tianqiyu119 | 149,065,966 | false | null | package com.underwood.idgenerator
import com.underwood.config.TConfig
/**
* 基于Twitter的Snowflake算法实现
*
* <br>
* SnowFlake的结构如下(每部分用-分开):<br>
* <br>
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
* <br>
* 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
* <br>
* 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
* 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
* <br>
* 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
* <br>
* 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
* <br>
* <br>
* 加起来刚好64位,为一个Long型。<br>
* SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
*
* @author underwood/[email protected]
*/
//TODO: 增加基因法生成器
object IDGenerator {
/** 起始时间戳,用于用当前时间戳减去这个时间戳,算出偏移量 */
private const val startTime = 1519740777809L
/** workerId占用的位数5(表示只允许workId的范围为:0-1023) */
private const val workerIdBits = 5L
/** dataCenterId占用的位数:5 */
private const val dataCenterIdBits = 5L
/** 序列号占用的位数:12(表示只允许workId的范围为:0-4095) */
private const val sequenceBits = 12L
/** workerId可以使用的最大数值:31 */
private const val maxWorkerId = -1L xor (-1L shl workerIdBits.toInt())
/** dataCenterId可以使用的最大数值:31 */
private const val maxDataCenterId = -1L xor (-1L shl dataCenterIdBits.toInt())
private const val workerIdShift = sequenceBits
private const val dataCenterIdShift = sequenceBits + workerIdBits
private const val timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits
/** 用mask防止溢出:位与运算保证计算的结果范围始终是 0-4095 */
private const val sequenceMask = -1L xor (-1L shl sequenceBits.toInt())
private var workerId: Long = 0L
private var dataCenterId: Long = 0L
private var sequence = 0L
private var lastTimestamp = -1L
private var isClock = false
private val lock = Object()
@Synchronized fun nextId(): Long {
if (workerId == 0L && dataCenterId == 0L) {
init()
}
var timestamp = timeGen()
if (timestamp < lastTimestamp) {
val offset = lastTimestamp - timestamp
if (offset <= 5) {
try {
lock.wait(offset shl 1)
timestamp = timeGen()
if (timestamp < lastTimestamp) {
throw RuntimeException("Clock moved backwards. Refusing to generate id for $offset milliseconds")
}
} catch (e: Exception) {
throw RuntimeException(e)
}
} else {
throw RuntimeException("Clock moved backwards. Refusing to generate id for $offset milliseconds")
}
}
// 解决跨毫秒生成ID序列号始终为偶数的缺陷:如果是同一时间生成的,则进行毫秒内序列
if (lastTimestamp == timestamp) {
// 通过位与运算保证计算的结果范围始终是 0-4095
sequence = sequence + 1 and sequenceMask
if (sequence == 0L) {
timestamp = tilNextMillis(lastTimestamp)
}
} else {
// 时间戳改变,毫秒内序列重置
sequence = 0L
}
lastTimestamp = timestamp
/*
* 1.左移运算是为了将数值移动到对应的段(41、5、5,12那段因为本来就在最右,因此不用左移)
* 2.然后对每个左移后的值(la、lb、lc、sequence)做位或运算,是为了把各个短的数据合并起来,合并成一个二进制数
* 3.最后转换成10进制,就是最终生成的id
*/
return timestamp - startTime shl timestampLeftShift.toInt() or
(dataCenterId shl dataCenterIdShift.toInt()) or
(workerId shl workerIdShift.toInt()) or
sequence
}
private fun init() {
val config = TConfig.instance()
workerId = config.getLong("workerId", 24L)
dataCenterId = config.getLong("dataCenterId", 24L)
isClock = config.getBoolean("isClock", false)
if (workerId > maxWorkerId || workerId < 0) {
throw IllegalArgumentException("worker Id can't be greater than $maxWorkerId or less than 0")
}
if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
throw IllegalArgumentException("dataCenter Id can't be greater than $maxDataCenterId or less than 0")
}
}
private fun timeGen(): Long {
return if (isClock) SystemClock.now() else System.currentTimeMillis()
}
/**
* 保证返回的毫秒数在参数之后(阻塞到下一个毫秒,直到获得新的时间戳)
*
* @param lastTimestamp
* @return
*/
private fun tilNextMillis(lastTimestamp: Long): Long {
var timestamp = timeGen()
while (timestamp <= lastTimestamp) {
timestamp = timeGen()
}
return timestamp
}
} | 0 | Kotlin | 0 | 0 | 75fddd6c8beec89675ea58913a43b6191a84983f | 4,723 | tien | MIT License |
674-longest-continuous-increasing-subsequence/674-longest-continuous-increasing-subsequence.kt | javadev | 601,623,109 | false | {"Kotlin": 549966, "Java": 511} | class Solution {
fun findLengthOfLCIS(nums: IntArray): Int {
var ans = 1
var count = 1
for (i in 0 until nums.size - 1) {
if (nums[i] < nums[i + 1]) {
count++
} else {
ans = max(count, ans)
count = 1
}
}
return max(ans, count)
}
private fun max(n1: Int, n2: Int): Int {
return Math.max(n1, n2)
}
}
| 0 | Kotlin | 0 | 0 | 55c7493692d92e83ef541dcf6ae2e8db8d906409 | 447 | leethub | MIT License |
ktfx-commons/tests/src/ktfx/collections/ObservableCollectionsMapTest.kt | hendraanggrian | 102,934,147 | false | null | package ktfx.collections
import javafx.collections.ObservableMap
import com.hendraanggrian.ktfx.test.BaseMapTest
class ObservableCollectionsMapTest : BaseMapTest<ObservableMap<String, Any?>>() {
override fun empty() = emptyObservableMap<String, Any?>()
override fun of() = observableMapOf<String, Any?>()
override fun of(value: String) = observableMapOf<String, Any?>(value to null)
override fun of(vararg values: String) = observableMapOf<String, Any?>(*values.map { it to null }.toTypedArray())
override fun mutableOf() = mutableObservableMapOf<String, Any?>()
override fun mutableOf(vararg values: String) =
mutableObservableMapOf<String, Any?>(*values.map { it to null }.toTypedArray())
override fun Map<String, Any?>.to() = toObservableMap()
override fun Map<String, Any?>.toMutable() = toMutableObservableMap()
}
| 1 | Kotlin | 2 | 15 | ea4243fb75edb70d6710e7488fa08834084f6169 | 863 | ktfx | Apache License 2.0 |
censowalletintegration/src/main/java/co/censo/walletintegration/CensoWalletIntegration.kt | Censo-Inc | 739,015,899 | false | {"Kotlin": 36631} | package co.censo.walletintegration
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
class CensoWalletIntegration: ContentProvider() {
val apiUrl = "https://api.censo.co"
val apiVersion = "v1"
val linkScheme = "censo-main"
val linkVersion = "v1"
private var appName: String = "UNKNOWN"
fun initiate(onFinished: (Boolean) -> Unit): Session {
return Session(
name = appName, apiUrl = apiUrl, apiVersion = apiVersion,
linkScheme = linkScheme, linkVersion = linkVersion, onFinished = onFinished
)
}
override fun onCreate(): Boolean {
appName = context?.applicationInfo?.name ?: "UNKNOWN"
return true
}
override fun query(
p0: Uri,
p1: Array<out String>?,
p2: String?,
p3: Array<out String>?,
p4: String?
): Cursor? {
return null
}
override fun getType(p0: Uri): String? {
return null
}
override fun insert(p0: Uri, p1: ContentValues?): Uri? {
return null
}
override fun delete(p0: Uri, p1: String?, p2: Array<out String>?): Int {
return 0
}
override fun update(p0: Uri, p1: ContentValues?, p2: String?, p3: Array<out String>?): Int {
return 0
}
} | 0 | Kotlin | 0 | 0 | 0323c0211b13ab081eb33c4a6db4ac0f0223157d | 1,347 | censo-wallet-integration-android | MIT License |
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/history/HistoryBlock.kt | JetBrains | 1,459,486 | false | {"Kotlin": 5959132, "Java": 211095, "ANTLR": 84686, "HTML": 2184} | /*
* Copyright 2003-2023 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.history
import com.maddyhome.idea.vim.api.globalOptions
import com.maddyhome.idea.vim.api.injector
class HistoryBlock {
private val entries: MutableList<HistoryEntry> = ArrayList()
private var counter = 0
fun addEntry(text: String) {
for (i in entries.indices) {
val entry = entries[i]
if (text == entry.entry) {
entries.removeAt(i)
break
}
}
entries.add(HistoryEntry(++counter, text))
if (entries.size > maxLength()) {
entries.removeAt(0)
}
}
fun getEntries(): List<HistoryEntry> {
return entries
}
companion object {
private fun maxLength() = injector.globalOptions().history
}
}
| 6 | Kotlin | 749 | 9,241 | 66b01b0b0d48ffec7b0148465b85e43dfbc908d3 | 911 | ideavim | MIT License |
multiplatform-settings/src/macosX64Test/kotlin/com/russhwolf/settings/KeychainSettingsTest.kt | russhwolf | 132,682,692 | false | null | /*
* Copyright 2021 Russell Wolf
*
* 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.russhwolf.settings
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.alloc
import kotlinx.cinterop.ptr
import kotlinx.cinterop.value
import platform.CoreFoundation.CFTypeRefVar
import platform.CoreFoundation.kCFBooleanTrue
import platform.Foundation.CFBridgingRelease
import platform.Foundation.NSData
import platform.Foundation.NSString
import platform.Foundation.NSUTF8StringEncoding
import platform.Foundation.create
import platform.Security.SecItemCopyMatching
import platform.Security.kSecAttrAccount
import platform.Security.kSecAttrService
import platform.Security.kSecClass
import platform.Security.kSecClassGenericPassword
import platform.Security.kSecMatchLimit
import platform.Security.kSecMatchLimitOne
import platform.Security.kSecReturnData
import kotlin.test.Test
import kotlin.test.assertEquals
// TODO figure out how to get this running on ios, watchos, and tvos simulators
@ExperimentalSettingsImplementation
@OptIn(ExperimentalForeignApi::class)
class KeychainSettingsTest : BaseSettingsTest(
platformFactory = object : Settings.Factory {
override fun create(name: String?): Settings = KeychainSettings(name ?: "com.russhwolf.settings.test")
},
hasListeners = false
) {
@Test
fun constructor_application() {
val settings = KeychainSettings("com.russhwolf.settings.test")
settings -= "key"
settings["key"] = "value"
val value = try {
cfRetain("key", "com.russhwolf.settings.test") { cfKey, cfService ->
val cfValue = alloc<CFTypeRefVar>()
val query = cfDictionaryOf(
kSecClass to kSecClassGenericPassword,
kSecAttrAccount to cfKey,
kSecReturnData to kCFBooleanTrue,
kSecMatchLimit to kSecMatchLimitOne,
kSecAttrService to cfService
)
val status = SecItemCopyMatching(query, cfValue.ptr)
assertEquals(0, status)
val nsData = CFBridgingRelease(cfValue.value) as NSData
NSString.create(nsData, NSUTF8StringEncoding)?.toKString()
}
} finally {
settings -= "key"
}
assertEquals("value", value)
}
@Test
fun keys_no_name() {
val settings = KeychainSettings()
// Ensure this doesn't throw
settings.keys
}
}
| 35 | Kotlin | 66 | 996 | 405cbcd95f7429ef5252cd2d3d0fae9458bcbc61 | 3,023 | multiplatform-settings | Apache License 2.0 |
kotlin-electron/src/jsMain/generated/electron/renderer/CertificateTrustDialogOptions.kt | JetBrains | 93,250,841 | false | {"Kotlin": 12159121, "JavaScript": 330528} | // Generated by Karakum - do not modify it manually!
package electron.renderer
typealias CertificateTrustDialogOptions = electron.core.CertificateTrustDialogOptions
| 40 | Kotlin | 165 | 1,319 | a8a1947d73e3ed26426f1e27b641bff427dfd6a0 | 169 | kotlin-wrappers | Apache License 2.0 |
src/en/nineanime/src/eu/kanade/tachiyomi/animeextension/en/nineanime/AniwaveFilters.kt | almightyhak | 817,607,446 | false | {"Kotlin": 4066862} | package eu.kanade.tachiyomi.animeextension.en.nineanime
import eu.kanade.tachiyomi.animesource.model.AnimeFilter
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
object NineAnimeFilters {
open class QueryPartFilter(
displayName: String,
val vals: Array<Pair<String, String>>,
) : AnimeFilter.Select<String>(
displayName,
vals.map { it.first }.toTypedArray(),
) {
fun toQueryPart() = vals[state].second
}
open class CheckBoxFilterList(name: String, values: List<CheckBox>) : AnimeFilter.Group<AnimeFilter.CheckBox>(name, values)
private class CheckBoxVal(name: String, state: Boolean = false) : AnimeFilter.CheckBox(name, state)
private inline fun <reified R> AnimeFilterList.asQueryPart(): String {
return this.filterIsInstance<R>().joinToString("") {
(it as QueryPartFilter).toQueryPart()
}
}
private inline fun <reified R> AnimeFilterList.getFirst(): R {
return this.filterIsInstance<R>().first()
}
private inline fun <reified R> AnimeFilterList.parseCheckbox(
options: Array<Pair<String, String>>,
name: String,
): String {
return (this.getFirst<R>() as CheckBoxFilterList).state
.mapNotNull { checkbox ->
if (checkbox.state) {
options.find { it.first == checkbox.name }!!.second
} else {
null
}
}.joinToString("&$name[]=").let {
if (it.isBlank()) {
""
} else {
"&$name[]=$it"
}
}
}
class SortFilter : QueryPartFilter("Sort order", NineAnimeFiltersData.sort)
class GenreFilter : CheckBoxFilterList(
"Genre",
NineAnimeFiltersData.genre.map { CheckBoxVal(it.first, false) },
)
class CountryFilter : CheckBoxFilterList(
"Country",
NineAnimeFiltersData.country.map { CheckBoxVal(it.first, false) },
)
class SeasonFilter : CheckBoxFilterList(
"Season",
NineAnimeFiltersData.season.map { CheckBoxVal(it.first, false) },
)
class YearFilter : CheckBoxFilterList(
"Year",
NineAnimeFiltersData.year.map { CheckBoxVal(it.first, false) },
)
class TypeFilter : CheckBoxFilterList(
"Type",
NineAnimeFiltersData.type.map { CheckBoxVal(it.first, false) },
)
class StatusFilter : CheckBoxFilterList(
"Status",
NineAnimeFiltersData.status.map { CheckBoxVal(it.first, false) },
)
class LanguageFilter : CheckBoxFilterList(
"Language",
NineAnimeFiltersData.language.map { CheckBoxVal(it.first, false) },
)
class RatingFilter : CheckBoxFilterList(
"Rating",
NineAnimeFiltersData.rating.map { CheckBoxVal(it.first, false) },
)
val filterList = AnimeFilterList(
SortFilter(),
AnimeFilter.Separator(),
GenreFilter(),
CountryFilter(),
SeasonFilter(),
YearFilter(),
TypeFilter(),
StatusFilter(),
LanguageFilter(),
RatingFilter(),
)
data class FilterSearchParams(
val sort: String = "",
val genre: String = "",
val country: String = "",
val season: String = "",
val year: String = "",
val type: String = "",
val status: String = "",
val language: String = "",
val rating: String = "",
)
internal fun getSearchParameters(filters: AnimeFilterList): FilterSearchParams {
if (filters.isEmpty()) return FilterSearchParams()
return FilterSearchParams(
filters.asQueryPart<SortFilter>(),
filters.parseCheckbox<GenreFilter>(NineAnimeFiltersData.genre, "genre"),
filters.parseCheckbox<CountryFilter>(NineAnimeFiltersData.country, "country"),
filters.parseCheckbox<SeasonFilter>(NineAnimeFiltersData.season, "season"),
filters.parseCheckbox<YearFilter>(NineAnimeFiltersData.year, "year"),
filters.parseCheckbox<TypeFilter>(NineAnimeFiltersData.type, "type"),
filters.parseCheckbox<StatusFilter>(NineAnimeFiltersData.status, "status"),
filters.parseCheckbox<LanguageFilter>(NineAnimeFiltersData.language, "language"),
filters.parseCheckbox<RatingFilter>(NineAnimeFiltersData.rating, "rating"),
)
}
private object NineAnimeFiltersData {
val sort = arrayOf(
Pair("Most relevance", "most_relevance"),
Pair("Recently updated", "recently_updated"),
Pair("Recently added", "recently_added"),
Pair("Release date", "release_date"),
Pair("Trending", "trending"),
Pair("Name A-Z", "title_az"),
Pair("Scores", "scores"),
Pair("MAL scores", "mal_scores"),
Pair("Most watched", "most_watched"),
Pair("Most favourited", "most_favourited"),
Pair("Number of episodes", "number_of_episodes"),
)
val genre = arrayOf(
Pair("Action", "1"),
Pair("Adventure", "2"),
Pair("Avant Garde", "2262888"),
Pair("Boys Love", "2262603"),
Pair("Comedy", "4"),
Pair("Demons", "4424081"),
Pair("Drama", "7"),
Pair("Ecchi", "8"),
Pair("Fantasy", "9"),
Pair("Girls Love", "2263743"),
Pair("Gourmet", "2263289"),
Pair("Harem", "11"),
Pair("Horror", "14"),
Pair("Isekai", "3457284"),
Pair("Iyashikei", "4398552"),
Pair("Josei", "15"),
Pair("Kids", "16"),
Pair("Magic", "4424082"),
Pair("Mahou Shoujo", "3457321"),
Pair("Martial Arts", "18"),
Pair("Mecha", "19"),
Pair("Military", "20"),
Pair("Music", "21"),
Pair("Mystery", "22"),
Pair("Parody", "23"),
Pair("Psychological", "25"),
Pair("Reverse Harem", "4398403"),
Pair("Romance", "26"),
Pair("School", "28"),
Pair("Sci-Fi", "29"),
Pair("Seinen", "30"),
Pair("Shoujo", "31"),
Pair("Shounen", "33"),
Pair("Slice of Life", "35"),
Pair("Space", "36"),
Pair("Sports", "37"),
Pair("Super Power", "38"),
Pair("Supernatural", "39"),
Pair("Suspense", "2262590"),
Pair("Thriller", "40"),
Pair("Vampire", "41"),
)
val country = arrayOf(
Pair("China", "120823"),
Pair("Japan", "120822"),
)
val season = arrayOf(
Pair("Fall", "fall"),
Pair("Summer", "summer"),
Pair("Spring", "spring"),
Pair("Winter", "winter"),
Pair("Unknown", "unknown"),
)
val year = arrayOf(
Pair("2023", "2023"),
Pair("2022", "2022"),
Pair("2021", "2021"),
Pair("2020", "2020"),
Pair("2019", "2019"),
Pair("2018", "2018"),
Pair("2017", "2017"),
Pair("2016", "2016"),
Pair("2015", "2015"),
Pair("2014", "2014"),
Pair("2013", "2013"),
Pair("2012", "2012"),
Pair("2011", "2011"),
Pair("2010", "2010"),
Pair("2009", "2009"),
Pair("2008", "2008"),
Pair("2007", "2007"),
Pair("2006", "2006"),
Pair("2005", "2005"),
Pair("2004", "2004"),
Pair("2003", "2003"),
Pair("2000s", "2000s"),
Pair("1990s", "1990s"),
Pair("1980s", "1980s"),
Pair("1970s", "1970s"),
Pair("1960s", "1960s"),
Pair("1950s", "1950s"),
Pair("1940s", "1940s"),
Pair("1930s", "1930s"),
Pair("1920s", "1920s"),
Pair("1910s", "1910s"),
)
val type = arrayOf(
Pair("Movie", "movie"),
Pair("TV", "tv"),
Pair("OVA", "ova"),
Pair("ONA", "ona"),
Pair("Special", "special"),
Pair("Music", "music"),
)
val status = arrayOf(
Pair("Not Yet Aired", "info"),
Pair("Releasing", "releasing"),
Pair("Completed", "completed"),
)
val language = arrayOf(
Pair("Sub and Dub", "subdub"),
Pair("Sub", "sub"),
Pair("Dub", "dub"),
)
val rating = arrayOf(
Pair("G - All Ages", "g"),
Pair("PG - Children", "pg"),
Pair("PG 13 - Teens 13 and Older", "pg_13"),
Pair("R - 17+, Violence & Profanity", "r"),
Pair("R+ - Profanity & Mild Nudity", "r+"),
Pair("Rx - Hentai", "rx"),
)
}
}
| 55 | Kotlin | 28 | 93 | 507dddff536702999357b17577edc48353eab5ad | 9,004 | aniyomi-extensions | Apache License 2.0 |
app/src/main/java/com/semaphoreci/demo/network/remotedatasource/RepoRemoteDataSource.kt | semaphoreci-demos | 278,655,843 | false | null | package com.semaphoreci.demo.network.remotedatasource
import com.haroldadmin.cnradapter.NetworkResponse
import com.semaphoreci.demo.network.errors.ServerError
import com.semaphoreci.demo.network.models.Repo
import retrofit2.http.GET
interface RepoRemoteDataSource {
@GET("/orgs/semaphoreci-demos/repos")
suspend fun getSemaphoreRepos(): NetworkResponse<List<Repo>, ServerError>
}
| 1 | Kotlin | 188 | 5 | 5effee0468b3853fb97c12148fd14dae8119edcd | 390 | semaphore-demo-android | MIT License |
app/src/main/java/com/ice/ktuice/repositories/yearGradesResponseRepository/YearGradesRepository.kt | Andrius-B | 118,811,243 | false | null | package com.ice.ktuice.repositories.yearGradesResponseRepository
import com.ice.ktuice.models.YearGradesCollectionModel
/**
* Created by Andrius on 2/19/2018.
* This repository is mainly for use in the YearGradesService, which should be the user-facing facade
*/
interface YearGradesRepository {
fun getByStudCode(studCode: String): YearGradesCollectionModel?
fun createOrUpdate(yearGradesModel: YearGradesCollectionModel)
fun setUpdating(yearGradesModel: YearGradesCollectionModel, isUpdating: Boolean)
} | 1 | null | 1 | 5 | 7d9a9a03792c62de168211cc6107507f9c3d82f0 | 524 | KTU-ice | MIT License |
app/src/main/java/org/bonal/birthdaycard/presentation/component/PlaceHolderImage.kt | obonal | 333,988,099 | false | null | package org.bonal.birthdaycard.presentation.component
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import org.bonal.birthdaycard.R
@Composable
fun PlaceHolderImage(
modifier: Modifier,
@DrawableRes vectorIconRes: Int = R.drawable.ic_launcher_foreground,
contentDescription: String? = null,
tintColor: Color = MaterialTheme.colors.primary) {
Image(
modifier = modifier,
contentDescription = contentDescription,
painter = painterResource(id = vectorIconRes),
contentScale = ContentScale.Crop,
colorFilter = ColorFilter.tint(tintColor)
)
} | 1 | Kotlin | 0 | 1 | 60c82e0ce7d44b365e88f076d29ff6392154c41d | 947 | BirthdayCard | Apache License 2.0 |
src/main/kotlin/demo/api/Message.kt | crafting-demo | 481,831,557 | false | {"Kotlin": 5797} | package demo.api
data class RequestMessage(
var callTime: String,
var target: String,
var message: String,
var key: String?,
var value: String?,
)
data class ResponseMessage(
var receivedTime: String,
var returnTime: String,
var message: String,
)
| 0 | Kotlin | 0 | 0 | 5ab0c4b32fc6c19aab29eb5b6412e3a2eab4ea24 | 314 | backend-kotlin-spring | MIT License |
src/main/java/com/sup/dev/java_pc/sql/SqlQueryInsert.kt | ZeonXX | 381,989,125 | false | null | package com.sup.dev.java_pc.sql
class SqlQueryInsert(private val table: String) : SqlQuery() {
private val columns = ArrayList<String>()
private val values = ArrayList<String>()
constructor(table: String, vararg columns: String) : this(table){
columns(*columns)
}
fun put(column: String, value: Any): SqlQueryInsert {
columns.add(column)
values.add(value.toString())
return this
}
fun columns(vararg column: String): SqlQueryInsert {
for(i in column) columns.add(i)
return this
}
fun put(vararg value: Any): SqlQueryInsert {
for(i in value) values.add(i.toString())
return this
}
fun putValues(vararg value: Any): SqlQueryInsert {
for(i in value) put("?").value(i)
return this
}
fun putValue(column: String, value: Any): SqlQueryInsert {
return put(column, "?").value(value)
}
override fun value(v: Any): SqlQueryInsert {
return super.value(v) as SqlQueryInsert
}
override fun createQuery(): String {
var sql = Sql.INSERT + table + "("
for (i in columns.indices) {
if (i != 0) sql += ","
sql += columns[i]
}
sql += ") " + Sql.VALUES +"("
var xx = 0
while (xx < values.size){
if(xx != 0) sql += "),("
for (i in columns.indices) {
if (i != 0) sql += ","
sql += values[xx++]
}
}
sql += ")"
return sql
}
}
| 1 | Kotlin | 1 | 0 | f5eb0e74619c2bbc046c4cf3586d3e18c3e5df56 | 1,548 | DevSupJavaPc | Apache License 2.0 |
android/buildSrc/src/main/kotlin/tornaco/project/android/thanox/Aidl.kt | Tornaco | 228,014,878 | false | null | package tornaco.project.android.thanox
import org.gradle.api.Project
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.the
import java.io.File
fun Project.addAidlTask() {
tasks.register("idlGen") {
group = "idl"
doLast {
val projectPrebuiltAndroidSdkDir = File(rootProject.projectDir, "android_sdk")
val javaSrcDirs = project.the<SourceSetContainer>()["main"].java.srcDirs
println("aidlTask, javaSrcDirs: $javaSrcDirs")
println("aidl executable file: ${aidl()}, is it exists? ${File(aidl()).exists()}")
javaSrcDirs.forEach { srcDir ->
val tree = fileTree(srcDir)
tree.forEach { file ->
if (file.name.endsWith(".aidl")) {
val aidlPath = file.path
exec {
commandLine(
aidl(),
"-I$srcDir",
"-p$projectPrebuiltAndroidSdkDir/framework.aidl",
"-p$projectPrebuiltAndroidSdkDir/thanos.aidl",
aidlPath
)
}
}
}
}
}
}
tasks.named("compileJava") {
dependsOn("idlGen")
}
tasks.named("build") {
dependsOn("idlGen")
}
}
private fun Project.aidl() = buildTools("aidl") | 250 | null | 31 | 584 | 5d731c28e249cfd453c68de7af1f826e18b4ae69 | 1,530 | Thanox | Apache License 2.0 |
kafkistry-service-logic/src/main/kotlin/com/infobip/kafkistry/service/topic/inspectors/TopicUnevenPartitionProducingInspector.kt | infobip | 456,885,171 | false | {"Kotlin": 2628950, "FreeMarker": 812501, "JavaScript": 297269, "CSS": 7204} | package com.infobip.kafkistry.service.topic.inspectors
import com.infobip.kafkistry.kafka.Partition
import com.infobip.kafkistry.service.NamedTypeCauseDescription
import com.infobip.kafkistry.service.Placeholder
import com.infobip.kafkistry.service.StatusLevel
import com.infobip.kafkistry.service.topic.*
import com.infobip.kafkistry.service.topic.offsets.PartitionRate
import com.infobip.kafkistry.service.topic.offsets.TopicOffsetsService
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Configuration
import org.springframework.stereotype.Component
val UNEVEN_TRAFFIC_RATE = TopicInspectionResultType(
name = "UNEVEN_TRAFFIC_RATE",
level = StatusLevel.IGNORE,
category = IssueCategory.RUNTIME_ISSUE,
doc = "Topic has uneven produce rate across different partitions",
)
@Configuration
@ConfigurationProperties("app.topic-inspection.uneven-partition-rate")
class TopicUnevenPartitionProducingInspectorProperties {
var ignoreInternal = true
var only15MinWindow = false
var acceptableMaxMinRatio = 5.0
var thresholdMinMsgRate = 50.0
}
data class UnevenPartitionRates(
val lowRate: Map<Partition, Double>,
val highRate: Map<Partition, Double>,
)
@Component
class TopicUnevenPartitionProducingInspector(
private val properties: TopicUnevenPartitionProducingInspectorProperties,
private val topicOffsetsService: TopicOffsetsService,
) : TopicExternalInspector {
override fun inspectTopic(ctx: TopicInspectCtx, outputCallback: TopicExternalInspectCallback) {
if (properties.ignoreInternal && ctx.existingTopic?.internal == true) {
return
}
val topicOffsets = ctx.cache { topicOffsetsService.topicOffsets(clusterRef.identifier, topicName) }
?.takeIf { !it.empty }
?: return
val rates = topicOffsets.partitionMessageRate
.mapNotNull { (partition, rates) -> rates.rate()?.let { partition to it } }
.toMap()
if (rates.size < 2) {
return
}
val maxRate = rates.maxByOrNull { it.value } ?: return
val minRate = rates.minByOrNull { it.value } ?: return
val violated = with(properties) {
minRate.value * acceptableMaxMinRatio < maxRate.value && maxRate.value >= thresholdMinMsgRate
}
if (violated) {
outputCallback.addDescribedStatusType(
NamedTypeCauseDescription(
type = UNEVEN_TRAFFIC_RATE,
message = "Min rate partition %MIN_PARTITION% (rate: %MIN_RATE%) is too low comparing to " +
"max rate partition %MAX_PARTITION% (rate: %MAX_RATE%)",
placeholders = mapOf(
"MIN_PARTITION" to Placeholder("partition", minRate.key),
"MIN_RATE" to Placeholder("min.msg.rate", minRate.value),
"MAX_PARTITION" to Placeholder("partition", maxRate.key),
"MAX_RATE" to Placeholder("max.msg.rate", maxRate.value),
),
)
)
val lowRates = mutableMapOf<Partition, Double>()
val highRates = mutableMapOf<Partition, Double>()
rates.forEach { (partition, rate) ->
val lowRate = rate < maxRate.value / properties.acceptableMaxMinRatio
val highRate = rate > minRate.value * properties.acceptableMaxMinRatio
if (lowRate && !highRate) lowRates[partition] = rate
if (highRate && !lowRate) highRates[partition] = rate
}
outputCallback.setExternalInfo(UnevenPartitionRates(lowRates, highRates))
}
}
fun PartitionRate.rate() = if (properties.only15MinWindow) {
upTo15MinRate
} else {
upTo24HRate ?: upTo15MinRate
}
}
| 1 | Kotlin | 6 | 42 | 62403993a76fdf60b4cae3a87c5be0abe4fb3a88 | 3,900 | kafkistry | Apache License 2.0 |
server/src/main/kotlin/org/tod87et/roomkn/server/models/reservations/MultipleReservationResult.kt | spbu-math-cs | 698,579,800 | false | {"Kotlin": 162233, "JavaScript": 143389, "CSS": 11387, "HTML": 1871, "Dockerfile": 1208, "Shell": 483} | package org.tod87et.roomkn.server.models.reservations
import kotlinx.serialization.Serializable
@Serializable
data class MultipleReservationResult(val success: List<Reservation>, val failure: List<FailedReservation>)
| 55 | Kotlin | 0 | 3 | f323ac4c4072414d15d5b65547fd84ed576d840f | 219 | roomkn | Apache License 2.0 |
server/src/jvmMain/kotlin/mqtt/server/Sample.kt | thebehera | 171,056,445 | false | null | package mqtt.server
import java.math.BigInteger
actual data class SampleNativeClass actual constructor(actual val x: Int) {
actual fun twoPlusTwo(): Int = (BigInteger("2") + BigInteger("2")).toInt()
} | 2 | Kotlin | 1 | 32 | 2f2d176ca1d042f928fba3a9c49f4bc5ff39495f | 206 | mqtt | Apache License 2.0 |
mbcarkit/src/test/java/com/daimler/mbcarkit/business/model/vehicle/ChargingTimeTypeTest.kt | Daimler | 199,815,262 | false | null | package com.daimler.mbcarkit.business.model.vehicle
import org.assertj.core.api.SoftAssertions
import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(SoftAssertionsExtension::class)
class ChargingTimeTypeTest {
@Test
fun testCorrectEnumPositionsOfChargingTimeType(softly: SoftAssertions) {
val states = ChargingTimeType.values()
softly.assertThat(states[0]).isEqualTo(ChargingTimeType.ABSOLUTE_TIME)
softly.assertThat(states[1]).isEqualTo(ChargingTimeType.RELATIVE_TIME)
softly.assertThat(states[2]).isEqualTo(ChargingTimeType.UNKNOWN)
}
}
| 1 | null | 8 | 15 | 3721af583408721b9cd5cf89dd7b99256e9d7dda | 694 | MBSDK-Mobile-Android | MIT License |
botlin/src/main/kotlin/info/mizoguche/botlin/feature/cron/Cron.kt | mizoguche | 101,714,038 | false | null | package info.mizoguche.botlin.feature.cron
import com.google.gson.Gson
import info.mizoguche.botlin.BotMessageRequest
import info.mizoguche.botlin.engine.BotEngineId
import info.mizoguche.botlin.feature.BotFeature
import info.mizoguche.botlin.feature.BotFeatureContext
import info.mizoguche.botlin.feature.BotFeatureFactory
import info.mizoguche.botlin.feature.BotFeatureId
import info.mizoguche.botlin.feature.command.BotMessageCommand
import java.util.regex.Matcher
import java.util.regex.Pattern
data class Schedule(
val id: Int,
private val engineId: String,
private val channelId: String,
val cron: String,
private val command: String
) {
override fun toString(): String {
return "${id.toString().padStart(4, ' ')}: \"$cron\" $command"
}
fun start(context: BotFeatureContext) {
val com = BotMessageCommand(BotEngineId(engineId), channelId, command)
context.pipelineOf<BotMessageCommand>().execute(com)
}
}
data class Schedules(val schedules: MutableList<Schedule>) {
override fun toString(): String {
if (schedules.count() == 0) {
return "```\nNo schedules.\n```"
}
return "```\n${schedules.joinToString("\n")}\n```"
}
}
private val addCommandPattern = Pattern.compile("""add "(.+? .+? .+? .+? .+?)" ([\s\S]+)""")
private val removeCommandPattern = Pattern.compile("""remove (\d+?)""")
private fun BotFeatureContext.post(engineId: BotEngineId, channelId: String, message: String) {
val request = BotMessageRequest(engineId, channelId, message)
pipelineOf<BotMessageRequest>().execute(request)
}
class Cron(configuration: Configuration) : BotFeature {
override val requiredFeatures: Set<BotFeatureId>
get() = setOf(BotFeatureId("MessageCommand"))
private val scheduler = configuration.scheduler
private val gson = Gson()
override val id: BotFeatureId
get() = BotFeatureId("Cron")
override fun install(context: BotFeatureContext) {
context.pipelineOf<BotMessageCommand>().intercept {
if (it.command != "cron") {
return@intercept
}
if (it.args == "list") {
val schedules = currentSchedules(context)
context.post(it.engineId, it.channelId, schedules.toString())
return@intercept
}
val matcherAdd = addCommandPattern.matcher(it.args)
if (matcherAdd.matches()) {
add(context, matcherAdd, it)
return@intercept
}
val matcherRemove = removeCommandPattern.matcher(it.args)
if (matcherRemove.matches()) {
remove(context, matcherRemove, it)
return@intercept
}
context.post(
it.engineId,
it.channelId,
"error: invalid args: ${it.args}. confirm cron tab."
)
}
val schedules = currentSchedules(context)
schedules.schedules.forEach { schedule ->
scheduler.start(schedule) { schedule.start(context) }
}
}
private fun currentSchedules(context: BotFeatureContext): Schedules {
val schedulesJson = context.get()
return gson.fromJson(schedulesJson, Schedules::class.java) ?: Schedules(mutableListOf())
}
private fun storeSchedules(context: BotFeatureContext, schedules: Schedules) {
val json = gson.toJson(schedules)
context.set(json)
}
private fun add(context: BotFeatureContext, matcher: Matcher, command: BotMessageCommand) {
val cron = matcher.group(1)
val content = matcher.group(2)
val schedule = Schedule(
scheduler.createScheduleId(),
command.engineId.value,
command.channelId,
cron,
content
)
val schedules = currentSchedules(context)
schedules.schedules.add(schedule)
storeSchedules(context, schedules)
scheduler.start(schedule) { schedule.start(context) }
context.post(
command.engineId, command.channelId, """
|Created schedule.
|
|Current schedules:
|$schedules
""".trimMargin()
)
}
private fun remove(context: BotFeatureContext, matcher: Matcher, command: BotMessageCommand) {
val scheduleId = matcher.group(1).toInt()
val schedules = currentSchedules(context)
schedules.schedules.removeIf { it.id == scheduleId }
storeSchedules(context, schedules)
if (scheduler.isStarted(scheduleId)) {
scheduler.stop(scheduleId)
context.post(
command.engineId, command.channelId, """
|Removed schedule.
|
|Current schedules:
|$schedules
""".trimMargin()
)
} else {
context.post(
command.engineId, command.channelId, """
|Schedule not found.
|
|Current schedules:
|$schedules
""".trimMargin()
)
}
}
class Configuration {
var scheduler: CronScheduler = CronforjScheduler()
}
companion object Factory : BotFeatureFactory<Configuration> {
override fun create(configure: Configuration.() -> Unit): Cron {
val conf = Configuration().apply(configure)
return Cron(conf)
}
}
}
| 3 | null | 1 | 20 | 090df77d40aaa7463fffad506936c81d13456e17 | 5,623 | botlin | MIT License |
app/src/main/java/com/hironytic/kiretan0a/view/util/PublisherExt.kt | hironytic | 119,700,704 | false | null | //
// PublisherExt.kt
// Kiretan0A
//
// Copyright (c) 2018 <NAME> <<EMAIL>>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
package com.hironytic.kiretan0a.view.util
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.LiveDataReactiveStreams
import org.reactivestreams.Publisher
fun <T> Publisher<T>.toLiveData() =
LiveDataReactiveStreams.fromPublisher(this) as LiveData<T>
| 0 | Kotlin | 0 | 0 | ea104be9495aa9ddddbbc2c8af162db9d925cf6b | 1,433 | Kiretan0A | MIT License |
kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io/kotest/engine/tags/domain.kt | kotest | 47,071,082 | false | null | package io.kotest.engine.tags
data class Token(val lexeme: String, val type: TokenType)
enum class TokenType {
ExclamationMark, Pipe, Ampersand, Identifier, OpenParen, CloseParen
}
| 5 | null | 648 | 4,435 | 2ce83d0f79e189c90e2d7bb3d16bd4f75dec9c2f | 186 | kotest | Apache License 2.0 |
api/src/main/java/android/davoh/api/responses/HttpError.kt | DDavoH | 498,986,092 | false | {"Kotlin": 31054} | package android.davoh.api.responses
data class HttpError (
val error:String,
val code:Int
) | 0 | Kotlin | 0 | 0 | d2fa5db9712d03675df0c87dae209eac78bb1a8c | 100 | BlogyApp-Android | Apache License 2.0 |
app/src/debug/java/com/kishorebabu/android/commitstrip/CommitStripDebugApplication.kt | KishoreBabuIN | 105,754,517 | false | null | package com.kishorebabu.android.commitstrip
import com.facebook.stetho.Stetho
import com.squareup.leakcanary.LeakCanary
import timber.log.Timber
/**
* Created by kishore on 05/10/17.
*/
class CommitStripDebugApplication : CommitStripApplication() {
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
Stetho.initializeWithDefaults(this)
LeakCanary.install(this)
}
} | 1 | Kotlin | 0 | 0 | dc243aff8ac5a6d8dacdcda04ca8d99359757ef3 | 434 | CommitStripAndroid | The Unlicense |
app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/vpn/feature/AppTpPrivacyFeaturePluginTest.kt | duckduckgo | 78,869,127 | false | {"Kotlin": 10143711, "HTML": 63669, "Ruby": 14445, "JavaScript": 8385, "C++": 1813, "CMake": 1286, "Shell": 784} | /*
* Copyright (c) 2022 DuckDuckGo
*
* 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.duckduckgo.mobile.android.vpn.feature
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.internal.verification.VerificationModeFactory.times
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
class AppTpPrivacyFeaturePluginTest {
private lateinit var featurePlugin: AppTpPrivacyFeaturePlugin
private val context = InstrumentationRegistry.getInstrumentation().targetContext
private val plugins: HashSet<AppTpSettingPlugin> = hashSetOf<AppTpSettingPlugin>()
private val moshi: Moshi = Moshi.Builder().add(JSONObjectAdapter()).build()
private val configAdapter: JsonAdapter<JsonAppTpFeatureConfig> = moshi.adapter(JsonAppTpFeatureConfig::class.java)
private val settingAdapter: JsonAdapter<SimpleSettingJsonModel> = moshi.adapter(SimpleSettingJsonModel::class.java)
private val testSettings = HashMap<String, JSONObject?>()
private val testSetting = SimpleSettingJsonModel("enabled")
private val testSettingName = "test"
private val testConfig = JsonAppTpFeatureConfig("enabled", null, testSettings, "2a58bdb505a789fcefe2bc24fb9ead16")
private val mockPlugin: AppTpSettingPlugin = mock()
@Before
fun setup() {
whenever(mockPlugin.settingName).thenReturn(SettingName { testSettingName })
plugins.add(mockPlugin)
featurePlugin = AppTpPrivacyFeaturePlugin(plugins, context)
testSettings[testSettingName] = JSONObject(settingAdapter.toJson(testSetting))
}
@Test
fun whenNoNameReturnsFalse() {
assertFalse(featurePlugin.store("", ""))
}
@Test
fun whenNoJSONReturnsFalse() {
assertFalse(featurePlugin.store(AppTpFeatureName.AppTrackerProtection.value, ""))
}
@Test
fun whenPluginNameNotMatchingDontStore() {
whenever(mockPlugin.settingName).thenReturn(SettingName { "unmatched" })
assertTrue(featurePlugin.store(AppTpFeatureName.AppTrackerProtection.value, configAdapter.toJson(testConfig)))
verify(mockPlugin, never()).store(any(), any())
}
@Test
fun whenHashIsTheSameSkipStore() {
assertTrue(featurePlugin.store(AppTpFeatureName.AppTrackerProtection.value, configAdapter.toJson(testConfig)))
assertTrue(featurePlugin.store(AppTpFeatureName.AppTrackerProtection.value, configAdapter.toJson(testConfig)))
verify(mockPlugin, times(1)).store(mockPlugin.settingName, settingAdapter.toJson(testSetting))
}
@Test
fun whenHashChangesStore() {
assertTrue(featurePlugin.store(AppTpFeatureName.AppTrackerProtection.value, configAdapter.toJson(testConfig)))
val testConfig2 = JsonAppTpFeatureConfig("enabled", null, testSettings, "b123f6ba3f75a565f14b2350e9c2751c")
assertTrue(featurePlugin.store(AppTpFeatureName.AppTrackerProtection.value, configAdapter.toJson(testConfig2)))
verify(mockPlugin, times(2)).store(mockPlugin.settingName, settingAdapter.toJson(testSetting))
}
@Test
fun whenHashMissingAlwaysStore() {
assertTrue(featurePlugin.store(AppTpFeatureName.AppTrackerProtection.value, configAdapter.toJson(testConfig)))
val testConfig2 = JsonAppTpFeatureConfig("enabled", null, testSettings, null)
assertTrue(featurePlugin.store(AppTpFeatureName.AppTrackerProtection.value, configAdapter.toJson(testConfig2)))
assertTrue(featurePlugin.store(AppTpFeatureName.AppTrackerProtection.value, configAdapter.toJson(testConfig2)))
verify(mockPlugin, times(3)).store(mockPlugin.settingName, settingAdapter.toJson(testSetting))
}
private data class SimpleSettingJsonModel(val state: String)
}
| 54 | Kotlin | 865 | 3,285 | 4146b2f0cdc079d719ff58118ef86644f8cb8542 | 4,703 | Android | Apache License 2.0 |
src/main/kotlin/utils/Util.kt | Polishevskyi | 858,925,187 | false | {"Kotlin": 27803} | package utils
import io.appium.java_client.AppiumDriver
import io.appium.java_client.android.AndroidDriver
import org.openqa.selenium.By
import org.openqa.selenium.Point
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.PointerInput
import org.openqa.selenium.interactions.Sequence
import java.time.Duration
class ElementNotFoundException(message: String) : Exception(message)
object Util {
private const val DEFAULT_RETRIES_COUNT = 3
private const val DEFAULT_DELAY_BEFORE_ACTION = 1
private const val DEFAULT_DELAY_AFTER_ACTION = 0
private const val DEFAULT_DISTANCE = 0.1
private fun getCenterOfElement(element: WebElement?): Point {
element?.let {
val size = element.size
val start = Point(element.location.x, element.location.y)
val end = Point(element.location.x + size.width, element.location.y + size.height)
return Point((start.x + end.x) / 2, (start.y + end.y) / 2)
} ?: throw ElementNotFoundException("Element is null")
}
fun clickInCenterOfElement(driver: AppiumDriver, element: WebElement) {
val input = PointerInput(PointerInput.Kind.TOUCH, "finger1")
val middle = getCenterOfElement(element)
val actions = Sequence(input, 0)
actions.addAction(
input.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), middle.x, middle.y)
)
actions.addAction(input.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
actions.addAction(input.createPointerUp(PointerInput.MouseButton.LEFT.asArg()))
driver.perform(listOf(actions))
}
fun clickByCoordinates(driver: AppiumDriver, point: Point): Boolean {
val input = PointerInput(PointerInput.Kind.TOUCH, "finger1")
val seq = Sequence(input, 0)
seq.addAction(
input.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), point.x, point.y)
)
seq.addAction(input.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
seq.addAction(input.createPointerUp(PointerInput.MouseButton.LEFT.asArg()))
driver.perform(listOf(seq))
return true
}
fun waitAndClick(
driver: AppiumDriver,
element: WebElement?,
delayBeforeClick: Int = DEFAULT_DELAY_BEFORE_ACTION,
delayAfterClick: Int = DEFAULT_DELAY_AFTER_ACTION,
withException: Boolean = true
): Boolean {
var isClickSuccess = false
try {
element?.let {
Thread.sleep(delayBeforeClick.toLong() * 1000)
it.click()
isClickSuccess = true
Thread.sleep(delayAfterClick.toLong() * 1000)
}
} catch (ex: Exception) {
}
return if (!isClickSuccess && withException) {
throw ElementNotFoundException("Cannot click on element")
} else {
isClickSuccess
}
}
fun waitAndSendKeys(
driver: AppiumDriver,
element: WebElement?,
text: String,
delayBefore: Int = DEFAULT_DELAY_BEFORE_ACTION,
delayAfter: Int = DEFAULT_DELAY_AFTER_ACTION,
withException: Boolean = true
): Boolean {
Thread.sleep(delayBefore.toLong() * 1000)
element?.sendKeys(text)
if (driver is AndroidDriver) driver.hideKeyboard()
Thread.sleep(delayAfter.toLong() * 1000)
return if (element == null) {
if (withException) {
throw ElementNotFoundException("Cannot send text, element is null")
}
false
} else {
element.isDisplayed
}
}
fun swipe(driver: AppiumDriver, direction: SwipeDirection, distance: Double = DEFAULT_DISTANCE) {
if (distance < 0 || distance > 1) error("Scroll distance must be between 0 and 1")
val screenWidth = driver.manage().window().size.width
val screenHeight = driver.manage().window().size.height
val midPoint = Point((screenWidth * 0.5).toInt(), (screenHeight * 0.5).toInt())
val pointsForSwipe = when (direction) {
SwipeDirection.FINGER_TO_UP -> Pair(
Point(midPoint.x, (midPoint.y + (screenHeight * distance)).toInt()),
midPoint
)
SwipeDirection.FINGER_TO_DOWN -> Pair(
midPoint,
Point(midPoint.x, (midPoint.y + (screenHeight * distance)).toInt())
)
SwipeDirection.FINGER_TO_RIGHT -> Pair(
Point(midPoint.x - (screenWidth * distance).toInt(), midPoint.y),
midPoint
)
SwipeDirection.FINGER_TO_LEFT -> Pair(
midPoint,
Point(midPoint.x - (screenWidth * distance).toInt(), midPoint.y)
)
}
swipeByPoints(driver, pointsForSwipe.first, pointsForSwipe.second)
}
fun swipeByPoints(driver: AppiumDriver, start: Point, end: Point, duration: Duration = Duration.ofMillis(1000)) {
val input = PointerInput(PointerInput.Kind.TOUCH, "finger1")
val swipe = Sequence(input, 0)
swipe.addAction(input.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), start.x, start.y))
swipe.addAction(input.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))
swipe.addAction(input.createPointerMove(duration, PointerInput.Origin.viewport(), end.x, end.y))
swipe.addAction(input.createPointerUp(PointerInput.MouseButton.LEFT.asArg()))
driver.perform(listOf(swipe))
}
fun waitForVisibilityOfElementBy(
driver: AppiumDriver,
by: By,
retriesCount: Int = DEFAULT_RETRIES_COUNT,
withException: Boolean = true
): Boolean {
var isVisible = false
for (attempt in 0..retriesCount) {
try {
val element = driver.findElement(by)
isVisible = element.isDisplayed
if (isVisible) break
} catch (ex: Exception) {
Thread.sleep(1000)
}
}
return if (!isVisible && withException) {
throw ElementNotFoundException("Element is not visible")
} else {
isVisible
}
}
fun waitUntilElementGone(
driver: AppiumDriver,
by: By,
retriesCount: Int = DEFAULT_RETRIES_COUNT,
withException: Boolean = false
): Boolean {
var isDisplayed = true
for (attempt in 0..retriesCount) {
try {
val element = driver.findElement(by)
isDisplayed = element.isDisplayed
if (!isDisplayed) break
} catch (ex: Exception) {
isDisplayed = false
break
}
Thread.sleep(1000)
}
return if (withException && isDisplayed) {
throw ElementNotFoundException("Element is still visible after retries")
} else {
!isDisplayed
}
}
enum class SwipeDirection {
FINGER_TO_UP, FINGER_TO_DOWN, FINGER_TO_RIGHT, FINGER_TO_LEFT
}
}
| 0 | Kotlin | 0 | 0 | b4d10fc1e3bf4b43d42585b48b674b113393d5d8 | 7,161 | kotlin_mobile_polishevskyi_automatization | MIT License |
sting/src/androidTest/java/com/sys1yagi/sting/test/AppModule3.kt | sys1yagi | 35,763,049 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 9, "Kotlin": 21, "Java": 1} | package com.sys1yagi.sting.test
import com.sys1yagi.sting.Provides
public class AppModule3 {
Provides
open public fun provideModel(): Model {
return Model("model2", 11)
}
}
| 5 | null | 1 | 1 | 2ae3c4cbd2bca32f7cf3f3036c8eb5b3fc857662 | 195 | sting | Apache License 2.0 |
src/main/kotlin/com/github/alexhandbybbc/trbintellijplugin/listeners/MyProjectManagerListener.kt | AlexHandbyBBC | 286,716,999 | false | null | package com.github.alexhandbybbc.trbintellijplugin.listeners
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
import com.github.alexhandbybbc.trbintellijplugin.services.MyProjectService
internal class MyProjectManagerListener : ProjectManagerListener {
override fun projectOpened(project: Project) {
project.getService(MyProjectService::class.java)
}
}
| 0 | Kotlin | 0 | 0 | 8775b5f3663664074fe4a638c7e1e5b33b8afdd1 | 426 | TRB-intellij-plugin | Apache License 2.0 |
DibaMovies/app/src/main/java/com/example/dibamovies/presentation/ui/favorite/FavoriteMoviesAdapter.kt | aliiimaher | 828,873,124 | false | {"Kotlin": 62964} | package com.example.dibamovies.presentation.ui.favorite
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.example.dibamovies.databinding.ItemMovieBinding
import com.example.dibamovies.domain.data.model.movie.MoviesResponse
class FavoriteMoviesAdapter(private val movies: List<MoviesResponse.Data>) :
RecyclerView.Adapter<FavoriteMoviesAdapter.MovieViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
val binding = ItemMovieBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MovieViewHolder(binding)
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
val movie = movies[position]
holder.bind(movie)
}
override fun getItemCount() = movies.size
class MovieViewHolder(private val binding: ItemMovieBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(movie: MoviesResponse.Data) {
binding.movieName.text = movie.title
if (movie.poster.isNotEmpty()) {
Glide.with(binding.moviePic.context)
.load(movie.poster)
.transition(DrawableTransitionOptions.withCrossFade(1000))
.into(binding.moviePic)
}
}
}
} | 0 | Kotlin | 0 | 0 | 862862025f68bac511cd5775e78ef849f4f88c09 | 1,485 | Diba-Movies-App | MIT License |
app/src/main/java/com/catp/imagesapitestapp/di/ApplicationContextModule.kt | runaloop | 315,918,945 | false | null | package com.catp.imagesapitestapp.di
import android.app.Application
import android.content.Context
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class ApplicationContextModule {
@Singleton
@Provides
fun context(app: Application): Context {
return app.applicationContext
}
} | 0 | Kotlin | 0 | 0 | 18474b6a2cccc4d5956e36c0447336ae76adb380 | 336 | ImagesApiTest | Apache License 2.0 |
feature/splash-screen/src/main/kotlin/com/flixclusive/feature/splashScreen/SplashScreen.kt | flixclusiveorg | 659,237,375 | false | {"Kotlin": 1904772, "Java": 18011} | package com.flixclusive.feature.splashScreen
import android.os.Build
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.graphics.ExperimentalAnimationGraphicsApi
import androidx.compose.animation.graphics.res.animatedVectorResource
import androidx.compose.animation.graphics.res.rememberAnimatedVectorPainter
import androidx.compose.animation.graphics.vector.AnimatedImageVector
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.max
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.flixclusive.core.network.util.Resource
import com.flixclusive.core.theme.FlixclusiveTheme
import com.flixclusive.core.ui.common.GradientCircularProgressIndicator
import com.flixclusive.core.ui.common.navigation.navigator.SplashScreenNavigator
import com.flixclusive.core.ui.common.util.ifElse
import com.flixclusive.core.ui.common.util.showToast
import com.flixclusive.data.configuration.UpdateStatus
import com.flixclusive.feature.splashScreen.component.ErrorDialog
import com.flixclusive.feature.splashScreen.component.PrivacyNotice
import com.flixclusive.feature.splashScreen.component.ProvidersDisclaimer
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale
import com.ramcosta.composedestinations.annotation.Destination
import kotlinx.coroutines.delay
import com.flixclusive.core.locale.R as LocaleR
import com.flixclusive.core.ui.common.R as UiCommonR
@OptIn(ExperimentalAnimationGraphicsApi::class, ExperimentalPermissionsApi::class)
@Destination
@Composable
internal fun SplashScreen(
navigator: SplashScreenNavigator
) {
val context = LocalContext.current
val viewModel: SplashScreenViewModel = hiltViewModel()
val appSettings by viewModel.appSettings.collectAsStateWithLifecycle()
val onBoardingPreferences by viewModel.onBoardingPreferences.collectAsStateWithLifecycle()
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val updateStatus by viewModel.appUpdateCheckerUseCase.updateStatus.collectAsStateWithLifecycle()
val configurationStatus by viewModel.configurationStatus.collectAsStateWithLifecycle()
var areAllPermissionsGranted by remember { mutableStateOf(context.hasAllPermissionGranted()) }
var isDoneAnimating by rememberSaveable { mutableStateOf(false) }
var showDisclaimer by rememberSaveable { mutableStateOf(false) }
val localDensity = LocalDensity.current
var disclaimerHeightDp by remember { mutableStateOf(0.dp) }
val image =
AnimatedImageVector.animatedVectorResource(id = UiCommonR.drawable.flixclusive_animated_tag)
var atEnd by rememberSaveable { mutableStateOf(false) }
// Override tv theme if we're on tv
FlixclusiveTheme {
val brushGradient = Brush.linearGradient(
colors = listOf(
MaterialTheme.colorScheme.primary,
MaterialTheme.colorScheme.tertiary,
)
)
Column(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 25.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
val paddingBottom by animateDpAsState(
targetValue = if (!onBoardingPreferences.isFirstTimeUserLaunch_) 30.dp else 50.dp,
label = ""
)
Box(
modifier = Modifier.padding(bottom = paddingBottom)
) {
Image(
painter = rememberAnimatedVectorPainter(image, atEnd),
contentDescription = stringResource(id = LocaleR.string.animated_tag_content_desc),
contentScale = ContentScale.Fit,
modifier = Modifier
.width(300.dp)
.graphicsLayer(alpha = 0.99f)
.drawWithCache {
onDrawWithContent {
drawContent()
drawRect(brushGradient, blendMode = BlendMode.SrcAtop)
}
}
)
}
AnimatedContent(
targetState = onBoardingPreferences.isFirstTimeUserLaunch_,
contentAlignment = Alignment.TopCenter,
label = ""
) { state ->
when {
state && isDoneAnimating -> {
Box(
contentAlignment = Alignment.TopCenter,
modifier = Modifier
.fillMaxWidth()
.heightIn(disclaimerHeightDp)
) {
AnimatedContent(
targetState = showDisclaimer,
contentAlignment = Alignment.TopCenter,
label = ""
) { stateDisclaimer ->
when(stateDisclaimer) {
false -> {
PrivacyNotice(
nextStep = {
viewModel.updateSettings(
appSettings.copy(
isSendingCrashLogsAutomatically = it
)
)
showDisclaimer = true
},
modifier = Modifier
.onGloballyPositioned {
val height = with(localDensity) { it.size.height.toDp() }
disclaimerHeightDp = max(height, disclaimerHeightDp)
}
)
}
true -> {
ProvidersDisclaimer(
understood = { _ ->
viewModel.updateOnBoardingPreferences {
it.copy(isFirstTimeUserLaunch_ = false)
}
}
)
}
}
}
}
}
isDoneAnimating -> {
Box(
contentAlignment = Alignment.TopCenter,
modifier = Modifier
.fillMaxWidth()
.ifElse(
condition = disclaimerHeightDp > 0.dp,
ifTrueModifier = Modifier.height(disclaimerHeightDp)
)
) {
GradientCircularProgressIndicator(
colors = listOf(
MaterialTheme.colorScheme.primary,
MaterialTheme.colorScheme.tertiary,
),
modifier = Modifier
.animateEnterExit(
enter = scaleIn(),
exit = scaleOut(),
)
)
}
}
}
}
}
LaunchedEffect(isDoneAnimating) {
if (!isDoneAnimating) {
atEnd = true
delay(4000) // Wait for animated tag to finish
isDoneAnimating = true
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val notificationsPermissionState = rememberPermissionState(
android.Manifest.permission.POST_NOTIFICATIONS
)
val textToShow = if (notificationsPermissionState.status.shouldShowRationale) {
stringResource(LocaleR.string.notification_persist_request_message)
} else {
stringResource(LocaleR.string.notification_request_message)
}
if (!notificationsPermissionState.status.isGranted) {
ErrorDialog(
title = stringResource(LocaleR.string.splash_notice_permissions_header),
description = textToShow,
dismissButtonLabel = stringResource(LocaleR.string.allow),
onDismiss = notificationsPermissionState::launchPermissionRequest
)
}
if (notificationsPermissionState.status.isGranted && !areAllPermissionsGranted) {
isDoneAnimating = false // Repeat animation.
areAllPermissionsGranted = true
}
} else areAllPermissionsGranted = true
if (areAllPermissionsGranted && isDoneAnimating && !onBoardingPreferences.isFirstTimeUserLaunch_) {
if (updateStatus is UpdateStatus.Outdated && appSettings.isUsingAutoUpdateAppFeature) {
navigator.openUpdateScreen(
newVersion = viewModel.appUpdateCheckerUseCase.newVersion!!,
updateInfo = viewModel.appUpdateCheckerUseCase.updateInfo,
updateUrl = viewModel.appUpdateCheckerUseCase.updateUrl!!,
isComingFromSplashScreen = true,
)
} else if (
((updateStatus is UpdateStatus.Error) && appSettings.isUsingAutoUpdateAppFeature)
|| configurationStatus is Resource.Failure
) {
val (title, errorMessage) = if (updateStatus is UpdateStatus.Error)
stringResource(LocaleR.string.failed_to_get_app_updates) to updateStatus.errorMessage
else stringResource(LocaleR.string.something_went_wrong) to (configurationStatus as Resource.Failure).error
ErrorDialog(
title = title,
description = errorMessage!!.asString(),
dismissButtonLabel = stringResource(LocaleR.string.close_label),
onDismiss = navigator::openHomeScreen
)
} else if (
(((updateStatus is UpdateStatus.UpToDate) && appSettings.isUsingAutoUpdateAppFeature)
|| configurationStatus is Resource.Success)
&& uiState is SplashScreenUiState.Okay
) {
if (updateStatus is UpdateStatus.Error) {
LocalContext.current
.showToast(
message = """
${stringResource(LocaleR.string.failed_to_get_app_updates)}: ${updateStatus.errorMessage?.asString()}
""".trimIndent()
)
}
navigator.openHomeScreen()
}
}
}
} | 26 | Kotlin | 29 | 362 | f488f6d1b2de3ec0737a8437ce1c981bc2f55c31 | 13,267 | Flixclusive | MIT License |
tilgangskontroll/src/test/kotlin/no/nav/amt/tiltak/tilgangskontroll/tiltaksansvarlig_tilgang/TiltaksansvarligGjennomforingTilgangControllerTest.kt | navikt | 393,356,849 | false | null | package no.nav.amt.tiltak.tilgangskontroll.tiltaksansvarlig_tilgang
import no.nav.amt.tiltak.common.auth.AuthService
import no.nav.amt.tiltak.core.domain.nav_ansatt.NavAnsatt
import no.nav.amt.tiltak.core.port.NavAnsattService
import no.nav.amt.tiltak.core.port.TiltaksansvarligTilgangService
import no.nav.amt.tiltak.test.mock_oauth_server.MockOAuthServer
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import java.util.*
@ActiveProfiles("test")
@WebMvcTest(controllers = [TiltaksansvarligGjennomforingTilgangController::class])
class TiltaksansvarligGjennomforingTilgangControllerTest {
companion object : MockOAuthServer() {
@AfterAll
@JvmStatic
fun cleanup() {
shutdownMockServer()
}
}
@Autowired
private lateinit var mockMvc: MockMvc
@MockBean
private lateinit var authService: AuthService
@MockBean
private lateinit var navAnsattService: NavAnsattService
@MockBean
private lateinit var tiltaksansvarligTilgangService: TiltaksansvarligTilgangService
@Test
fun `giTilgangTilGjennomforing() - skal returnere 401 hvis token mangler`() {
val response = mockMvc.perform(
MockMvcRequestBuilders.post("/api/tiltaksansvarlig/gjennomforing-tilgang?gjennomforingId=${UUID.randomUUID()}")
).andReturn().response
assertEquals(401, response.status)
}
@Test
fun `giTilgangTilGjennomforing() - skal returnere 200 og gi tilgang til gjennomføring`() {
val gjennomforingId = UUID.randomUUID()
val navAnsattIdent = "Z1234"
val navAnsattId = UUID.randomUUID()
Mockito.`when`(authService.hentNavIdentTilInnloggetBruker())
.thenReturn(navAnsattIdent)
Mockito.`when`(navAnsattService.getNavAnsatt(navAnsattIdent))
.thenReturn(NavAnsatt(
navAnsattId,
navAnsattIdent,
"",
"",
""
))
val response = mockMvc.perform(
MockMvcRequestBuilders.post("/api/tiltaksansvarlig/gjennomforing-tilgang?gjennomforingId=$gjennomforingId")
.header("Authorization", "Bearer ${azureAdToken()}")
).andReturn().response
assertEquals(200, response.status)
verify(tiltaksansvarligTilgangService, times(1)).giTilgangTilGjennomforing(navAnsattId, gjennomforingId)
}
@Test
fun `stopTilgangTilGjennomforing() - skal returnere 401 hvis token mangler`() {
val response = mockMvc.perform(
MockMvcRequestBuilders.patch("/api/tiltaksansvarlig/gjennomforing-tilgang/stop?gjennomforingId=${UUID.randomUUID()}")
).andReturn().response
assertEquals(401, response.status)
}
@Test
fun `stopTilgangTilGjennomforing() - skal returnere 200 og stoppe tilgang til gjennomføring`() {
val gjennomforingId = UUID.randomUUID()
val navAnsattIdent = "Z1234"
val navAnsattId = UUID.randomUUID()
Mockito.`when`(authService.hentNavIdentTilInnloggetBruker())
.thenReturn(navAnsattIdent)
Mockito.`when`(navAnsattService.getNavAnsatt(navAnsattIdent))
.thenReturn(NavAnsatt(
navAnsattId,
navAnsattIdent,
"",
"",
""
))
val response = mockMvc.perform(
MockMvcRequestBuilders.patch("/api/tiltaksansvarlig/gjennomforing-tilgang/stop?gjennomforingId=$gjennomforingId")
.header("Authorization", "Bearer ${azureAdToken()}")
).andReturn().response
assertEquals(200, response.status)
verify(tiltaksansvarligTilgangService, times(1)).stopTilgangTilGjennomforing(navAnsattId, gjennomforingId)
}
}
| 4 | Kotlin | 2 | 3 | fd7fda363d9aeb793b269a5fdd6072a93e904c96 | 3,841 | amt-tiltak | MIT License |
year2020/day02/part1/src/test/kotlin/com/curtislb/adventofcode/year2020/day02/part1/Year2020Day02Part1Test.kt | curtislb | 226,797,689 | false | null | package com.curtislb.adventofcode.year2020.day02.part1
import java.nio.file.Paths
import kotlin.test.assertEquals
import org.junit.jupiter.api.Test
/**
* Tests the solution to the puzzle for 2020, day 2, part 1.
*/
class Year2020Day02Part1Test {
@Test
fun testSolutionWithRealInput() {
assertEquals(458, solve())
}
@Test
fun testSolutionWithTestInput() {
val solution = solve(inputPath = Paths.get("..", "input", "test_input.txt"))
assertEquals(2, solution)
}
}
| 0 | Kotlin | 1 | 1 | 029323b694e6376f31aec57260bef376fd4a5309 | 515 | AdventOfCode | MIT License |
android/src/main/java/com/reactnativedengage/DengageRNCoordinator.kt | dengage-tech | 348,966,381 | false | {"Swift": 32734, "Kotlin": 24486, "Java": 18363, "TypeScript": 12169, "Objective-C": 6250, "JavaScript": 1472, "Ruby": 1386, "C": 103} | package com.reactnativedengage
import android.content.Context
import com.dengage.sdk.DengageManager
import com.facebook.react.ReactInstanceManager
import com.facebook.react.bridge.ReactContext
class DengageRNCoordinator private constructor() {
var reactInstanceManager: ReactInstanceManager? = null
var dengageManager: DengageManager? = null
var isSuccessfullyInitialized = false
private set
fun injectReactInstanceManager(reactInstanceManager: ReactInstanceManager) {
if (this.reactInstanceManager != null) {
// TODO: throw error. can only initialize once.
}
this.reactInstanceManager = reactInstanceManager
this.reactInstanceManager!!.addReactInstanceEventListener(
object : ReactInstanceManager.ReactInstanceEventListener {
override fun onReactContextInitialized(context: ReactContext) {
reactInstanceManager.removeReactInstanceEventListener(this)
isSuccessfullyInitialized = true
}
})
}
fun setupDengage (logStatus: Boolean, firebaseKey: String?, huaweiKey: String?, context: Context) {
if (firebaseKey == null && huaweiKey == null) {
throw Error("Both firebase key and huawei key can't be null at the same time.");
}
when {
huaweiKey == null -> {
dengageManager = DengageManager.getInstance(context)
.setLogStatus(logStatus)
.setFirebaseIntegrationKey(firebaseKey)
.init()
}
firebaseKey == null -> {
dengageManager = DengageManager.getInstance(context)
.setLogStatus(logStatus)
.setHuaweiIntegrationKey(huaweiKey)
.init()
}
else -> {
dengageManager = DengageManager.getInstance(context)
.setLogStatus(logStatus)
.setHuaweiIntegrationKey(huaweiKey)
.setFirebaseIntegrationKey(firebaseKey)
.init()
}
}
}
companion object {
var sharedInstance = DengageRNCoordinator()
}
}
| 5 | Swift | 3 | 2 | 29d8c03a8d48b8b5428f1f687435b85d8263a73d | 2,000 | dengage-react-sdk | MIT License |
app/src/main/java/com/imashnake/animite/data/Resource.kt | imashnake0 | 461,101,703 | false | null | package com.imashnake.animite.data
import com.apollographql.apollo3.ApolloCall
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.exception.ApolloCompositeException
import com.apollographql.apollo3.exception.ApolloNetworkException
import com.apollographql.apollo3.exception.CacheMissException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
sealed class Resource<T>(
open val data: T?,
open val message: String? = null
) {
data class Success<T>(override val data: T) : Resource<T>(data)
data class Error<T>(override val message: String?, override val data: T? = null) : Resource<T?>(data, message)
class Loading<T> : Resource<T>(null)
companion object {
fun <T> success(data: T): Resource<T> {
return Success(data)
}
fun <T> error(msg: String, data: T? = null): Resource<T?> {
return Error(msg, data)
}
fun <T> loading(): Resource<T> {
return Loading()
}
/**
* Parses an [ApolloCall] into a [Resource] by checking its data & errors
* As well as catching non-HTTP exceptions like no hostname for no connection & cache miss for cache-only requests
*
* TODO: Should require a mapper rather than a higher order lambda to provide access to the [ApolloResponse.data]
*/
fun <T : Operation.Data, R> Flow<ApolloResponse<T>>.asResource(mapper: (T) -> R): Flow<Resource<R?>> {
return map { response ->
if (response.data != null) {
success<R?>(mapper(response.dataAssertNoErrors))
} else if (response.hasErrors()) {
error(response.errors!!.joinToString { it.toString() })
} else {
noDataError()
}
}.catch { e ->
if (e is ApolloCompositeException) {
val (first, second) = e.suppressedExceptions
if (first is ApolloNetworkException || first is CacheMissException) {
return@catch emit(networkError())
} else if (second is ApolloNetworkException || second is CacheMissException) {
return@catch emit(networkError())
}
}
return@catch emit(defaultError())
}
}
private fun <T> networkError() = error<T>("Network error, please check your connection and try again.")
private fun <T> defaultError() = error<T>("Unknown error occurred, please try again later.")
private fun <T> noDataError() = error<T>("Unknown error occurred, no data or errors received.")
}
}
| 5 | Kotlin | 7 | 41 | 5eed56fd52957622647f66aa92ae87cb95523ed1 | 2,829 | Animite | Apache License 2.0 |
app/src/main/java/com/softcross/onepiece/presentation/favorite/FavoritesFragment.kt | ErenMlg | 731,047,216 | false | {"Kotlin": 160094} | package com.softcross.onepiece.presentation.favorite
import androidx.fragment.app.viewModels
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.navigation.fragment.findNavController
import com.softcross.onepiece.R
import com.softcross.onepiece.core.common.delegate.viewBinding
import com.softcross.onepiece.core.common.extension.gone
import com.softcross.onepiece.core.common.extension.visible
import com.softcross.onepiece.databinding.FragmentFavoritesBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class FavoritesFragment : Fragment(R.layout.fragment_favorites) {
private val viewModel: FavoritesViewModel by viewModels()
private val binding: FragmentFavoritesBinding by viewBinding(FragmentFavoritesBinding::bind)
private val adapter = FavoritesAdapter().apply {
setOnDeleteFavoriteClickListener {
viewModel.deleteFavoriteItem(it)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
observeUI()
binding.viewToolbarFavorites.setTitle("Favorites")
binding.viewToolbarFavorites.setOnClickListener {
findNavController().navigate(R.id.favorites_to_characters)
}
}
private fun observeUI() {
viewModel.favoritesScreenUiState.observe(viewLifecycleOwner) { favoritesUiState ->
when (favoritesUiState) {
is FavoritesUiState.Error -> {
handleError(favoritesUiState.errorMessage)
}
is FavoritesUiState.Loading -> {
contentVisible(false)
}
is FavoritesUiState.Success -> {
handleSuccess(favoritesUiState.data)
}
}
}
}
private fun handleSuccess(favoriteList: List<FavoritesUiItem>) {
adapter.updateFavoriteList(favoriteList)
binding.rvFavorites.adapter = adapter
contentVisible(true)
}
private fun contentVisible(isVisible: Boolean) {
with(binding) {
viewErrorLayoutFavorites.gone()
viewLoadingFavorites.isVisible = !isVisible
rvFavorites.isVisible = isVisible
}
}
private fun handleError(errorMessage: String) {
with(binding) {
viewErrorLayoutFavorites.visible()
viewLoadingFavorites.gone()
rvFavorites.gone()
viewErrorLayoutFavorites.setRetryOnClick { viewModel.getAllFavorites() }
viewErrorLayoutFavorites.setErrorMessage(errorMessage)
}
}
} | 0 | Kotlin | 0 | 0 | b55ae20e7d5a74c12ec2557eff844cd7297f8da0 | 2,776 | OnePieceAndroid | Apache License 2.0 |
Yum-Client/app/src/main/java/com/anbui/yum/presentation/sign_up/SignUpViewModel.kt | AnBuiii | 608,489,464 | false | null | package com.anbui.yum.presentation.sign_up
import androidx.compose.runtime.mutableStateOf
import com.anbui.yum.common.ext.isValidEmail
import com.anbui.yum.common.ext.isValidPassword
import com.anbui.yum.common.ext.passwordMatches
import com.anbui.yum.common.snackbar.SnackbarManager
import com.anbui.yum.presentation.YumViewModel
import com.anbui.yum.R.string as AppText
class SignUpViewModel(
) : YumViewModel() {
val uiState = mutableStateOf(SignUpUiState())
private val email
get() = uiState.value.email
private val password
get() = uiState.value.password
private val repeatPassword
get() = uiState.value.repeatPassword
fun onEmailChange(newValue: String) {
uiState.value = uiState.value.copy(email = newValue)
}
fun onPasswordChange(newValue: String) {
uiState.value = uiState.value.copy(password = newValue)
}
fun onRepeatPasswordChange(newValue: String) {
uiState.value = uiState.value.copy(repeatPassword = newValue)
}
fun onSignUp(openAndPopUp: (String, String) -> Unit) {
if (!email.isValidEmail()) {
SnackbarManager.showMessage(AppText.email_error)
}
if (!password.isValidPassword()) {
SnackbarManager.showMessage(AppText.password_error)
}
if (!password.passwordMatches(repeatPassword)) {
SnackbarManager.showMessage(AppText.password_match_error)
}
// launchCatching {
// accountService.linkAccount(email, password)
// openAndPopUp(FEED_SCREEN, SIGNUP_SCREEN)
// }
}
}
| 0 | Kotlin | 0 | 3 | 94a9344aeb57403214315191304b81d15d584863 | 1,612 | Yum | MIT License |
sample/src/main/java/nu/dropud/bundr/feature/main/video/VideoFragmentView.kt | Bundedaterne | 129,445,865 | false | null | package nu.dropud.bundr.feature.main.video
import nu.dropud.bundr.feature.base.MvpView
interface VideoFragmentView : MvpView {
val remoteUuid: String?
fun connectTo(uuid: String)
fun showCamViews()
fun showStartRouletteView()
fun disconnect()
fun attachService()
fun showErrorWhileChoosingRandom()
fun showNoOneAvailable()
fun showLookingForPartnerMessage()
fun showOtherPartyFinished()
fun showConnectedMsg()
fun showWillTryToRestartMsg()
fun wasDisconnectedByOther()
} | 2 | Kotlin | 2 | 0 | bad0ae3b772e56c1571bda1feb5836d067be15e2 | 525 | Bundr | Apache License 2.0 |
app/src/main/java/com/mrspd/letschat/fragments/one_to_one_chat/ChatViewModelFactory.kt | satyamurti | 275,247,716 | false | null | package com.mrspd.letschat.fragments.one_to_one_chat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
class ChatViewModelFactory(
private val senderId: String?,
private val receiverId: String
) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(ChatViewModel::class.java)) {
return ChatViewModel(senderId, receiverId) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
| 1 | null | 30 | 80 | 62f0f0ae22b38d8c48c5c27800005039f2030987 | 579 | LetsChat | MIT License |
datatypes-jws/src/jvmMain/kotlin/at/asitplus/crypto/datatypes/jws/JcaExtensions.kt | a-sit-plus | 700,518,667 | false | {"Kotlin": 491122} | package at.asitplus.crypto.datatypes.jws
val JweEncryption.jcaName
get() = when (this) {
JweEncryption.A128GCM, JweEncryption.A192GCM, JweEncryption.A256GCM -> "AES/GCM/NoPadding"
JweEncryption.A128CBC_HS256, JweEncryption.A192CBC_HS384, JweEncryption.A256CBC_HS512 -> "AES/CBC/NoPadding"
}
val JweEncryption.jcaKeySpecName
get() = when (this) {
JweEncryption.A128GCM, JweEncryption.A192GCM, JweEncryption.A256GCM -> "AES"
JweEncryption.A128CBC_HS256, JweEncryption.A192CBC_HS384, JweEncryption.A256CBC_HS512 -> "AES"
}
val JweAlgorithm.jcaName:String?
get() = when (this) {
JweAlgorithm.ECDH_ES -> "ECDH"
JweAlgorithm.A128KW, JweAlgorithm.A192KW, JweAlgorithm.A256KW -> "AES"
JweAlgorithm.RSA_OAEP_256, JweAlgorithm.RSA_OAEP_384, JweAlgorithm.RSA_OAEP_512 -> "RSA/ECB/OAEPPadding"
is JweAlgorithm.UNKNOWN -> null
} | 8 | Kotlin | 1 | 12 | 2991e2fee40a461c76ecc0dc563065a37533980c | 906 | kmp-crypto | Apache License 2.0 |
app/src/main/java/com/ajdi/yassin/travelmantics/utils/FirebaseUtil.kt | YassinAJDI | 200,273,610 | false | null | package com.ajdi.yassin.travelmantics.utils
import com.google.firebase.database.FirebaseDatabase
/**
* @author <NAME>
* @since 8/4/2019.
*/
object FirebaseUtil {
val database = FirebaseDatabase.getInstance()
val dealsReference = database.getReference("travel_deals")
} | 0 | Kotlin | 0 | 1 | 5bbc2b52c38e5c2570e9c9247c1ea5b4b6b80355 | 282 | Travelmantics | MIT License |
app/src/main/java/com/davidfadare/notes/recycler/ColorAdapter.kt | offad | 414,578,202 | false | {"Kotlin": 306364, "Java": 137048} | package com.davidfadare.notes.recycler
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.recyclerview.widget.RecyclerView
import com.davidfadare.notes.R
class ColorAdapter(context: Context, vararg objects: String) : ArrayAdapter<String>(context, 0, objects) {
private val mColorsArray: Array<out String> = objects
override fun getView(position: Int, cView: View?, parent: ViewGroup): View {
val holder: ViewHolder
var convertView = cView
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.color_item, parent, false)
holder = ViewHolder(convertView)
convertView.tag = holder
} else {
holder = convertView.tag as ViewHolder
}
val drawable = holder.playButton.background as GradientDrawable
val color = Color.parseColor(mColorsArray[position])
drawable.setColor(color)
return convertView!!
}
class ViewHolder(convertView: View) : RecyclerView.ViewHolder(convertView) {
val playButton: View = convertView.findViewById(R.id.color_button)
}
}
| 0 | Kotlin | 0 | 1 | f072e801b3555a18709052a1e9f7dfff435d8535 | 1,331 | stylepad | MIT License |
providers/src/main/java/com/flixclusive/providers/models/common/SearchResultItem.kt | rhenwinch | 659,237,375 | false | {"Kotlin": 1156049} | package com.flixclusive.providers.models.common
data class SearchResultItem(
val id: String? = null,
val tmdbId: Int? = null,
val title: String? = null,
val url: String? = null,
val image: String? = null,
val releaseDate: String? = null,
val mediaType: MediaType? = null,
val seasons: Int? = null
)
| 9 | Kotlin | 7 | 96 | a90215b8c40ac0675cd217b38b842d2d57c90acc | 332 | Flixclusive | MIT License |
app/src/main/java/com/example/compose_clean_base/data/repository/CourseRepository.kt | samyoney | 783,208,332 | false | {"Kotlin": 136569} | package com.example.compose_clean_base.data.repository
import com.example.compose_clean_base.data.local.dao.CourseDao
import com.example.compose_clean_base.data.model.local.CourseEntity
import com.example.compose_clean_base.data.remote.service.CourseService
import javax.inject.Inject
class CourseRepository @Inject constructor(
private val service: CourseService,
private val courseDao: CourseDao,
) {
suspend fun fetchCourses() = service.fetch()
suspend fun insertListCourse(courseEntities: List<CourseEntity>) = courseDao.insert(courseEntities)
suspend fun getEnrollCourse() = courseDao.getClassEnroll()
} | 0 | Kotlin | 0 | 7 | 38ebae18cd04f7533f151885746f8b90cef0099a | 632 | compose_clean_base | MIT License |
kotlin-node/src/jsMain/generated/node/dns/resolveCname.suspend.kt | JetBrains | 93,250,841 | false | {"Kotlin": 13735517, "JavaScript": 331583} | // Generated by Karakum - do not modify it manually!
package node.dns
import js.promise.await
suspend fun resolveCname(hostname: String): js.array.ReadonlyArray<String> =
resolveCnameAsync(
hostname
).await()
| 36 | Kotlin | 165 | 1,299 | 0a7abd03f6f42e33c5434376ceedd15b6407ee43 | 229 | kotlin-wrappers | Apache License 2.0 |
logging-spring-boot-starter/src/main/kotlin/me/lura/logging/annotation/Log.kt | lura-framework | 435,202,723 | false | {"Kotlin": 15179, "Java": 5369, "Vue": 4679, "Shell": 2121, "JavaScript": 1795, "HTML": 313, "CSS": 181} | package me.lura.logging.annotation
annotation class Log(val value: String)
| 0 | Kotlin | 0 | 3 | 7790578bdd4100ba7887b9c39c90673282f7d160 | 76 | lura-framework | Apache License 2.0 |
src/main/kotlin/com/github/asvignesh/gcppubsub/listeners/MyProjectManagerListener.kt | asvignesh | 513,771,759 | false | null | package com.github.asvignesh.gcppubsub.listeners
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
import com.github.asvignesh.gcppubsub.services.MyProjectService
internal class MyProjectManagerListener : ProjectManagerListener {
override fun projectOpened(project: Project) {
project.service<MyProjectService>()
}
}
| 0 | Kotlin | 0 | 0 | 7735def837d0f345da100deea27cd532582165a4 | 436 | GCPPubSub | Apache License 2.0 |
android/src/main/kotlin/rekab/app/background_locator/pluggables/DisposePluggable.kt | rekabhq | 209,099,411 | false | {"Kotlin": 52608, "Dart": 30363, "Objective-C": 24131, "Ruby": 2080, "Swift": 986} | package rekab.app.background_locator.pluggables
import android.content.Context
import android.os.Handler
import io.flutter.plugin.common.MethodChannel
import rekab.app.background_locator.IsolateHolderService
import rekab.app.background_locator.Keys
import rekab.app.background_locator.PreferencesManager
class DisposePluggable : Pluggable {
override fun setCallback(context: Context, callbackHandle: Long) {
PreferencesManager.setCallbackHandle(context, Keys.DISPOSE_CALLBACK_HANDLE_KEY, callbackHandle)
}
override fun onServiceDispose(context: Context) {
(PreferencesManager.getCallbackHandle(context, Keys.DISPOSE_CALLBACK_HANDLE_KEY))?.let { disposeCallback ->
val backgroundChannel = MethodChannel(IsolateHolderService.backgroundEngine!!.dartExecutor.binaryMessenger,
Keys.BACKGROUND_CHANNEL_ID)
Handler(context.mainLooper)
.post {
backgroundChannel.invokeMethod(Keys.BCM_DISPOSE,
hashMapOf(Keys.ARG_DISPOSE_CALLBACK to disposeCallback))
}
}
}
} | 155 | Kotlin | 308 | 287 | 741dc82ad706cb1a6361a4f60b59a37b8254f142 | 1,132 | background_locator | MIT License |
app/src/main/java/com/tonyakitori/citrep/framework/utils/GeneralFunctions.kt | AntonioHReyes | 482,385,777 | false | {"Kotlin": 117199} | package com.tonyakitori.citrep.framework.utils
import androidx.fragment.app.Fragment
import com.karumi.dexter.Dexter
import com.karumi.dexter.MultiplePermissionsReport
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.multi.MultiplePermissionsListener
import java.text.SimpleDateFormat
import java.util.*
fun Fragment.checkPermissions(list: List<String>, callback: ((Boolean) -> Unit) = {}) {
Dexter.withActivity(this.requireActivity())
.withPermissions(list)
.withListener(object : MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
if (report?.grantedPermissionResponses?.size!! > 0) {
callback(true)
} else {
callback(false)
}
}
override fun onPermissionRationaleShouldBeShown(
permissions: MutableList<PermissionRequest>?,
token: PermissionToken?
) {
token?.continuePermissionRequest()
}
}).check()
}
fun Long.getFormattedDate(onlyDate: Boolean = true): String {
val messageTime = Calendar.getInstance()
messageTime.minimalDaysInFirstWeek = 4
messageTime.timeInMillis = this
val now = Calendar.getInstance()
val timeFormatString = "HH:mm"
val dateTimeFormatString = "dd/MM/yy"
val dateTodayFormatString = "dd/MM/yy"
val formatToday = SimpleDateFormat(dateTodayFormatString, Locale.getDefault())
return if (formatToday.format(now.timeInMillis) == formatToday.format(messageTime.timeInMillis)) {
if (onlyDate) {
"Hoy"
} else {
val format = SimpleDateFormat(timeFormatString, Locale.getDefault())
format.format(Date(messageTime.timeInMillis))
}
} else if (now.get(Calendar.DAY_OF_YEAR) - messageTime.get(Calendar.DAY_OF_YEAR) == 1 &&
now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)
) {
if (onlyDate) {
"Ayer"
} else {
val format = SimpleDateFormat(timeFormatString, Locale.getDefault())
format.format(Date(messageTime.timeInMillis))
}
} else if (now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)) {
if (onlyDate) {
val format = SimpleDateFormat(dateTimeFormatString, Locale.getDefault())
format.format(Date(messageTime.timeInMillis))
} else {
val format = SimpleDateFormat(timeFormatString, Locale.getDefault())
format.format(Date(messageTime.timeInMillis))
}
} else {
if (onlyDate) {
val format = SimpleDateFormat("dd/MM/yy", Locale.getDefault())
format.format(Date(messageTime.timeInMillis))
} else {
val format = SimpleDateFormat(timeFormatString, Locale.getDefault())
format.format(Date(messageTime.timeInMillis))
}
}
} | 0 | Kotlin | 0 | 5 | 0f53b259b0dff98de4bd1ee8d39efc624a00576e | 3,026 | CitRep-appwrite | MIT License |
VeterinarioApp/app/src/main/java/com/exucodeiro/veterinarioapp/Services/ProfissionalService.kt | Vitor-Xavier | 108,047,401 | false | null | package com.exucodeiro.veterinarioapp.Services
import com.exucodeiro.veterinarioapp.Models.Contato
import com.exucodeiro.veterinarioapp.Models.Profissional
import com.exucodeiro.veterinarioapp.Models.Servico
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.httpDelete
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.httpPost
import com.github.kittinunf.fuel.httpPut
class ProfissionalService {
init {
FuelManager.instance.basePath = BaseService.BASE_URL
FuelManager.instance.baseHeaders = mapOf("Content-Type" to "application/json")
}
fun getProfissionais(latitude: Double, longitude: Double) : List<Profissional> {
val profissionais: ArrayList<Profissional> = ArrayList()
val (_, _, result) = "Profissional/$latitude/$longitude/".httpGet().responseString()
val (data, error) = result
if (error == null) {
val mapper = jacksonObjectMapper()
profissionais.addAll(mapper.readValue<List<Profissional>>(data ?: ""))
}
return profissionais
}
fun getProfissional(profissionalId: Int) : Profissional? {
val (_, _, result) = "Profissional/$profissionalId".httpGet().responseString()
val (data, error) = result
val mapper = jacksonObjectMapper()
when (error == null) {
true -> return mapper.readValue(data ?: "")
false -> return null
}
}
fun postProfissional(profissional: Profissional) : Profissional? {
val mapper = jacksonObjectMapper()
val (_, _, result) = "Profissional".httpPost().body(mapper.writeValueAsString(profissional)).responseString()
val (data, error) = result
return if (error == null) mapper.readValue(data ?: "") else null
}
fun atualizaProfissional(profissional: Profissional) : Boolean {
val mapper = jacksonObjectMapper()
val str = mapper.writeValueAsString(profissional)
val (_, _, result) = "Profissional".httpPut().body(mapper.writeValueAsString(profissional)).responseString()
val (_, error) = result
return (error == null)
}
fun inativaProfissional(profissionalId: Int) : Boolean {
val (_, _, result) = "Profissional/$profissionalId".httpDelete().responseString()
val (_, error) = result
return (error == null)
}
fun setProfissionalOnline(profissionalId: Int, online: Boolean) : Boolean {
val (_, _, result) = "Profissional/$profissionalId/$online".httpPut().responseString()
val (_, error) = result
return (error == null)
}
fun adicionaServico(profissionalId: Int, servico: Servico) : Boolean {
val mapper = jacksonObjectMapper()
val (_, _, result) = "Profissional/Servico/$profissionalId".httpPost().body(mapper.writeValueAsString(servico)).responseString()
val (_, error) = result
return (error == null)
}
fun adicionaContato(profissionalId: Int, contato: Contato) : Boolean {
val mapper = jacksonObjectMapper()
val (_, _, result) = "Profissional/Contato/$profissionalId".httpPost().body(mapper.writeValueAsString(contato)).responseString()
val (_, error) = result
return (error == null)
}
} | 0 | Kotlin | 0 | 0 | be7c690ce4957ecc8f74917ff042ea598e797637 | 3,421 | VeterinarioApp | MIT License |
platform/platform-impl/src/com/intellij/ui/dsl/impl/CellBuilderImpl.kt | xieguanliang | 261,644,228 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.impl
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.dsl.CellBuilder
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import com.intellij.ui.layout.*
import com.intellij.util.SmartList
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
@ApiStatus.Experimental
internal class CellBuilderImpl<T : JComponent>(
private val dialogPanelConfig: DialogPanelConfig,
val component: T,
val viewComponent: JComponent = component) : CellBuilderBaseImpl<CellBuilder<T>>(dialogPanelConfig), CellBuilder<T> {
private var applyIfEnabled = false
override fun alignHorizontal(horizontalAlign: HorizontalAlign): CellBuilder<T> {
super.alignHorizontal(horizontalAlign)
return this
}
override fun alignVertical(verticalAlign: VerticalAlign): CellBuilder<T> {
super.alignVertical(verticalAlign)
return this
}
override fun comment(@NlsContexts.DetailedDescription comment: String, maxLineLength: Int): CellBuilder<T> {
super.comment(comment, maxLineLength)
return this
}
override fun rightLabelGap(): CellBuilder<T> {
super.rightLabelGap()
return this
}
override fun applyToComponent(task: T.() -> Unit): CellBuilder<T> {
component.task()
return this
}
override fun enabled(isEnabled: Boolean): CellBuilder<T> {
viewComponent.isEnabled = isEnabled
return this
}
override fun applyIfEnabled(): CellBuilder<T> {
applyIfEnabled = true
return this
}
override fun <V> bind(componentGet: (T) -> V, componentSet: (T, V) -> Unit, modelBinding: PropertyBinding<V>): CellBuilder<T> {
onApply { if (shouldSaveOnApply()) modelBinding.set(componentGet(component)) }
onReset { componentSet(component, modelBinding.get()) }
onIsModified { shouldSaveOnApply() && componentGet(component) != modelBinding.get() }
return this
}
private fun shouldSaveOnApply(): Boolean {
return !(applyIfEnabled && !viewComponent.isEnabled)
}
private fun onApply(callback: () -> Unit): CellBuilder<T> {
dialogPanelConfig.applyCallbacks.getOrPut(component) { SmartList() }.add(callback)
return this
}
private fun onReset(callback: () -> Unit): CellBuilder<T> {
dialogPanelConfig.resetCallbacks.getOrPut(component) { SmartList() }.add(callback)
return this
}
private fun onIsModified(callback: () -> Boolean): CellBuilder<T> {
dialogPanelConfig.isModifiedCallbacks.getOrPut(component) { SmartList() }.add(callback)
return this
}
} | 1 | null | 1 | 1 | d39c1b5060e799de1911c3a04a46bbd0669a7dd6 | 2,726 | intellij-community | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/sykmeldingstatus/kafka/producer/SykmeldingStatusKafkaProducer.kt | navikt | 238,714,111 | false | null | package no.nav.syfo.sykmeldingstatus.kafka.producer
import no.nav.syfo.log
import no.nav.syfo.model.sykmeldingstatus.KafkaMetadataDTO
import no.nav.syfo.model.sykmeldingstatus.SykmeldingStatusKafkaEventDTO
import no.nav.syfo.model.sykmeldingstatus.SykmeldingStatusKafkaMessageDTO
import org.apache.kafka.clients.producer.KafkaProducer
import org.apache.kafka.clients.producer.ProducerRecord
import java.time.OffsetDateTime
import java.time.ZoneOffset
class SykmeldingStatusKafkaProducer(private val kafkaProducer: KafkaProducer<String, SykmeldingStatusKafkaMessageDTO>, private val topicName: String) {
fun send(sykmeldingStatusKafkaEventDTO: SykmeldingStatusKafkaEventDTO, source: String, fnr: String) {
log.info("Skriver statusendring {} for sykmelding med id {} til topic på aiven", sykmeldingStatusKafkaEventDTO.statusEvent, sykmeldingStatusKafkaEventDTO.sykmeldingId)
val metadataDTO = KafkaMetadataDTO(sykmeldingId = sykmeldingStatusKafkaEventDTO.sykmeldingId, timestamp = OffsetDateTime.now(ZoneOffset.UTC), fnr = fnr, source = source)
val sykmeldingStatusKafkaMessageDTO = SykmeldingStatusKafkaMessageDTO(metadataDTO, sykmeldingStatusKafkaEventDTO)
try {
kafkaProducer.send(ProducerRecord(topicName, sykmeldingStatusKafkaMessageDTO.event.sykmeldingId, sykmeldingStatusKafkaMessageDTO)).get()
} catch (ex: Exception) {
log.error("Failed to send sykmeldingStatus to kafkatopic {}", metadataDTO.sykmeldingId)
throw ex
}
}
}
| 0 | Kotlin | 0 | 0 | c81f357d4bf0ba7383033dc3e2966a7e1e993454 | 1,523 | sykmeldinger-backend | MIT License |
soil-query-core/src/commonTest/kotlin/soil/query/core/ReplyTest.kt | soil-kt | 789,648,330 | false | {"Kotlin": 789346, "Makefile": 1014} | // Copyright 2024 Soil Contributors
// SPDX-License-Identifier: Apache-2.0
package soil.query.core
import soil.testing.UnitTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import kotlin.test.assertTrue
class ReplyTest : UnitTest() {
@Test
fun testNone() {
val reply = Reply.none<Int>()
assertTrue(reply.isNone)
assertFailsWith<IllegalStateException> { reply.getOrThrow() }
assertNull(reply.getOrNull())
assertEquals(0, reply.getOrElse { 0 })
assertEquals(0, reply.map { it + 1 }.getOrElse { 0 })
}
@Test
fun testSome() {
val reply = Reply.some(1)
assertTrue(!reply.isNone)
assertEquals(1, reply.getOrThrow())
assertEquals(1, reply.getOrNull())
assertEquals(1, reply.getOrElse { 0 })
assertEquals(2, reply.map { it + 1 }.getOrThrow())
}
@Test
fun testCompanion_combinePair() {
val reply1 = Reply.some(1)
val reply2 = Reply.some(2)
val reply3 = Reply.none<Int>()
assertEquals(3, Reply.combine(reply1, reply2) { a, b -> a + b }.getOrThrow())
assertTrue(Reply.combine(reply1, reply3) { a, b -> a + b }.isNone)
assertTrue(Reply.combine(reply2, reply3) { a, b -> a + b }.isNone)
assertTrue(Reply.combine(reply3, reply3) { a, b -> a + b }.isNone)
}
@Test
fun testCompanion_combineTriple() {
val reply1 = Reply.some(1)
val reply2 = Reply.some(2)
val reply3 = Reply.some(3)
val reply4 = Reply.none<Int>()
assertEquals(6, Reply.combine(reply1, reply2, reply3) { a, b, c -> a + b + c }.getOrThrow())
assertTrue(Reply.combine(reply1, reply2, reply4) { a, b, c -> a + b + c }.isNone)
assertTrue(Reply.combine(reply2, reply3, reply4) { a, b, c -> a + b + c }.isNone)
assertTrue(Reply.combine(reply4, reply4, reply4) { a, b, c -> a + b + c }.isNone)
}
}
| 0 | Kotlin | 1 | 109 | 25c3fdd81db98ea44afbaf2776421373ed2d3d05 | 1,989 | soil | Apache License 2.0 |
android/app/src/main/kotlin/com/example/flutter_todo_app/MainActivity.kt | mthinh | 450,280,241 | false | {"Dart": 7349, "HTML": 3944, "Swift": 404, "Kotlin": 133, "Objective-C": 38} | package com.example.flutter_todo_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | 1a70250561704ed1e9d18b592a90a8b94a8b573c | 133 | flutter_todo_app | MIT License |
p8e-api/src/main/kotlin/io/provenance/engine/config/P8eGRpcServerBuilderConfigurer.kt | provenance-io | 340,506,091 | false | null | package io.provenance.engine.config
import io.grpc.ServerBuilder
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder
import io.p8e.grpc.Constant
import io.p8e.util.ThreadPoolFactory
import org.lognet.springboot.grpc.GRpcServerBuilderConfigurer
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit.SECONDS
@Component
class P8eGRpcServerBuilderConfigurer: GRpcServerBuilderConfigurer() {
override fun configure(serverBuilder: ServerBuilder<*>) {
serverBuilder.maxInboundMessageSize(Constant.MAX_MESSAGE_SIZE)
.also {
val netty = (it as NettyServerBuilder)
.executor(ThreadPoolFactory.newFixedThreadPool(80, "grpc-server-%d"))
.permitKeepAliveTime(50, SECONDS)
.keepAliveTime(60, SECONDS)
.keepAliveTimeout(20, SECONDS)
.initialFlowControlWindow(NettyServerBuilder.DEFAULT_FLOW_CONTROL_WINDOW)
}
}
}
| 2 | Kotlin | 0 | 23 | d27b71e8ab95af104705b2e245b31a4fd6499a6d | 996 | p8e | Apache License 2.0 |
demo-common/src/jvmMain/kotlin/com/seanproctor/datatable/demo/Scrollbar.jvm.kt | sproctor | 638,790,475 | false | {"Kotlin": 67211} | package com.seanproctor.datatable.demo
import androidx.compose.foundation.HorizontalScrollbar
import androidx.compose.foundation.VerticalScrollbar
import androidx.compose.foundation.v2.ScrollbarAdapter
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import com.seanproctor.datatable.DataTableScrollState
import kotlin.math.roundToInt
@Composable
actual fun VerticalScrollbar(scrollState: DataTableScrollState, modifier: Modifier) {
VerticalScrollbar(
adapter = rememberScrollbarAdapter(scrollState),
modifier = modifier,
)
}
@Composable
actual fun HorizontalScrollbar(scrollState: DataTableScrollState, modifier: Modifier) {
HorizontalScrollbar(
adapter = rememberScrollbarAdapter(scrollState),
modifier = modifier,
)
}
@Composable
fun rememberScrollbarAdapter(scrollState: DataTableScrollState): ScrollbarAdapter {
return remember(scrollState) { DataTableScrollbarAdapter(scrollState) }
}
internal class DataTableScrollbarAdapter(
private val scrollState: DataTableScrollState
) : ScrollbarAdapter {
override val scrollOffset: Double get() = scrollState.offset.toDouble()
override suspend fun scrollTo(scrollOffset: Double) {
scrollState.scrollTo(scrollOffset.roundToInt())
}
override val contentSize: Double
// This isn't strictly correct, as the actual content can be smaller
// than the viewport when scrollState.maxValue is 0, but the scrollbar
// doesn't really care as long as contentSize <= viewportSize; it's
// just not showing itself
get() = scrollState.totalSize.toDouble()
override val viewportSize: Double
get() = scrollState.viewportSize.toDouble()
} | 3 | Kotlin | 13 | 101 | 3d8e1851cf822accd7a60767a4b0377822e5cf53 | 1,777 | compose-data-table | Apache License 2.0 |
pluto/src/main/java/com/mocklets/pluto/modules/settings/holders/SettingsEasyAccessPopupAppearanceHolder.kt | mocklets | 459,260,997 | false | null | package com.mocklets.pluto.modules.settings.holders
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import com.mocklets.pluto.R
import com.mocklets.pluto.core.extensions.canDrawOverlays
import com.mocklets.pluto.core.extensions.inflate
import com.mocklets.pluto.core.preferences.Preferences
import com.mocklets.pluto.core.ui.list.DiffAwareAdapter
import com.mocklets.pluto.core.ui.list.DiffAwareHolder
import com.mocklets.pluto.core.ui.list.ListItem
import com.mocklets.pluto.core.ui.setDebounceClickListener
import com.mocklets.pluto.databinding.PlutoItemSettingsEasyAccessAppearanceBinding
import com.mocklets.pluto.modules.settings.SettingsEasyAccessPopupAppearanceEntity
internal class SettingsEasyAccessPopupAppearanceHolder(
parent: ViewGroup,
listener: DiffAwareAdapter.OnActionListener
) : DiffAwareHolder(parent.inflate(R.layout.pluto___item_settings_easy_access_appearance), listener) {
private val binding = PlutoItemSettingsEasyAccessAppearanceBinding.bind(itemView)
private val title = binding.title
private val checkbox = binding.checkbox
private val disableOverlay = binding.disableOverlay
override fun onBind(item: ListItem) {
if (item is SettingsEasyAccessPopupAppearanceEntity) {
disableOverlay.visibility = if (itemView.context.canDrawOverlays()) GONE else VISIBLE
title.text = context.getString(
when (item.type) {
"mode" -> R.string.pluto___settings_easy_access_appearance_mode_title
"handed" -> R.string.pluto___settings_easy_access_appearance_handed_title
else -> error("unsupported appearance type")
}
)
checkbox.isSelected =
when (item.type) {
"mode" -> Preferences(context).isDarkAccessPopup
"handed" -> Preferences(context).isRightHandedAccessPopup
else -> error("unsupported appearance type")
}
if (itemView.context.canDrawOverlays()) {
itemView.setDebounceClickListener {
onAction("click")
}
}
}
}
}
| 0 | Kotlin | 2 | 8 | 87dc5a27272e0fc5c38e042fa95689a143ae5446 | 2,235 | pluto | Apache License 2.0 |
src/main/kotlin/com.franzmandl.fileadmin/security/Handler.kt | franzmandl | 570,884,978 | false | null | package com.franzmandl.fileadmin.security
import com.franzmandl.fileadmin.common.CommonUtil
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.authentication.AuthenticationFailureHandler
import org.springframework.security.web.authentication.AuthenticationSuccessHandler
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class Handler : AuthenticationFailureHandler, AuthenticationSuccessHandler, LogoutSuccessHandler {
private fun send(response: HttpServletResponse, message: String) {
response.contentType = CommonUtil.contentTypeTextPlainUtf8
response.writer.print(message)
}
override fun onAuthenticationFailure(
request: HttpServletRequest,
response: HttpServletResponse,
exception: AuthenticationException
) {
response.status = HttpServletResponse.SC_UNAUTHORIZED
send(response, "Wrong username or password.")
}
override fun onAuthenticationSuccess(
request: HttpServletRequest,
response: HttpServletResponse,
authentication: Authentication
) {
send(response, "Success!")
}
override fun onLogoutSuccess(
request: HttpServletRequest,
response: HttpServletResponse,
authentication: Authentication
) {
send(response, "Success!")
}
} | 0 | Kotlin | 0 | 0 | 9e7a3f2876688627b24a98a2fe58027b4d733ce2 | 1,538 | fileadmin-server | MIT License |
security/src/test/kotlin/com/kmdev/security/SecurityVerticleTest.kt | keuller | 148,202,291 | false | null | package com.kmdev.security
import io.reactivex.Single
import io.vertx.ext.unit.TestContext
import io.vertx.ext.unit.junit.VertxUnitRunner
import io.vertx.reactivex.core.RxHelper
import io.vertx.reactivex.core.Vertx
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
@RunWith(VertxUnitRunner::class)
class SecurityVerticleTest {
val vertx = Vertx.vertx()
var verticleId: String = ""
@Test
fun start(ctx: TestContext) {
val async = ctx.async()
RxHelper.deployVerticle(vertx, SecurityVerticle())
.doOnError(Throwable::printStackTrace)
.doOnSuccess { vid -> verticleId = vid }
.map { _ -> Single.just("") }
.delay(2, TimeUnit.SECONDS)
.doOnSuccess {
vertx.undeploy(verticleId)
async.complete()
}
.subscribe()
}
} | 0 | Kotlin | 2 | 5 | 88220b63dcadfc2c682b58b71ad7d24e5f95f302 | 942 | event-driven-platform | MIT License |
modules/wasm-binary/src/commonMain/kotlin/visitor/SourceMapSectionAdapter.kt | wasmium | 761,480,110 | false | {"Kotlin": 661510, "JavaScript": 203} | package org.wasmium.wasm.binary.visitor
public open class SourceMapSectionAdapter(protected val delegate: SourceMapSectionVisitor? = null) : SourceMapSectionVisitor {
override fun visitEnd(): Unit = delegate?.visitEnd() ?: Unit
}
| 0 | Kotlin | 0 | 3 | dc846f459f0bda1527cad253614df24bbdea012f | 236 | wasmium-wasm | Apache License 2.0 |
app/src/main/java/com/example/myweather/data/repositories/HourlyWeatherRepository.kt | iraklisangeloudis | 831,865,773 | false | {"Kotlin": 63641} | package com.example.myweather.data.repositories
import android.util.Log
import com.example.myweather.data.db.dao.HourlyWeatherDao
import com.example.myweather.data.db.entities.HourlyWeatherEntity
import com.example.myweather.data.network.responses.Hourly
interface HourlyWeatherRepository {
suspend fun insertHourlyWeather(hourly: Hourly, currentTime: String)
suspend fun getHourlyWeather(): List<HourlyWeatherEntity>
suspend fun clearHourlyWeather()
suspend fun logHourlyWeather()
}
class HourlyWeatherRepositoryImpl(private val hourlyWeatherDao: HourlyWeatherDao) : HourlyWeatherRepository {
override suspend fun insertHourlyWeather(hourly: Hourly, currentTime: String) {
try {
// Clear the old hourly weather data
clearHourlyWeather()
// Prepare and insert new hourly weather data for the next 24 hours
val entities = hourly.time.indices.map { i ->
HourlyWeatherEntity(
time = hourly.time[i],
temperature = hourly.temperature[i],
weatherCode = hourly.weatherCode[i],
isDay = hourly.isDay[i]
)
}.take(24)
hourlyWeatherDao.insertHourlyWeather(entities)
Log.d("HourlyWeatherRepo", "insertHourlyWeather: Insertion successful")
} catch (e: Exception) {
Log.e("HourlyWeatherRepo", "insertHourlyWeather: Insertion failed", e)
}
}
override suspend fun getHourlyWeather(): List<HourlyWeatherEntity> {
return try {
hourlyWeatherDao.getHourlyWeather()
} catch (e: Exception) {
Log.e("HourlyWeatherRepo", "getHourlyWeather: Retrieval failed", e)
emptyList()
}
}
override suspend fun clearHourlyWeather() {
try {
hourlyWeatherDao.clearHourlyWeather()
Log.d("HourlyWeatherRepo", "clearHourlyWeather: Clear successful")
} catch (e: Exception) {
Log.e("HourlyWeatherRepo", "clearHourlyWeather: Clear failed", e)
}
}
override suspend fun logHourlyWeather() {
try {
val hourlyWeatherList = getHourlyWeather()
if (hourlyWeatherList.isNotEmpty()) {
Log.d("HourlyWeatherLog", "Hourly Weather Data:")
hourlyWeatherList.forEach { hourlyWeather ->
Log.d("HourlyWeatherLog", "Time: ${hourlyWeather.time}")
Log.d("HourlyWeatherLog", "Temperature: ${hourlyWeather.temperature}")
Log.d("HourlyWeatherLog", "Weather Code: ${hourlyWeather.weatherCode}")
Log.d("HourlyWeatherLog", "Is Day: ${hourlyWeather.isDay}")
Log.d("HourlyWeatherLog", "----------------------")
}
} else {
Log.d("HourlyWeatherLog", "No hourly weather data available.")
}
} catch (e: Exception) {
Log.e("HourlyWeatherLog", "Error fetching hourly weather data", e)
}
}
} | 0 | Kotlin | 0 | 0 | 8554981d4fda8a22c21e4a0b950e639c7e9c4c09 | 3,068 | MyWeather | MIT License |
app/src/main/java/ru/olegivo/afs/common/android/BrowserScreen.kt | olegivo | 189,586,349 | false | null | /*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*
* This file is part of AFS.
*
* AFS is free software: you can redistribute it and/or modify
* it under the terms of the MIT License.
*
* AFS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* AFS.
*/
package ru.olegivo.afs.common.android
import android.content.Context
import android.content.Intent
import android.net.Uri
import ru.olegivo.afs.common.presentation.BrowserDestination
import ru.terrakok.cicerone.android.support.SupportAppScreen
class BrowserScreen(private val destination: BrowserDestination) : SupportAppScreen() {
override fun getActivityIntent(context: Context) =
Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(destination.url)
}
}
| 15 | Kotlin | 0 | 0 | c828167fc361ce32ddd2d4354f450dd052295de9 | 1,145 | AFS | MIT License |
src/main/kotlin/no/nav/pensjon/selvbetjening/fssgw/tech/web/WebClientPreparer.kt | navikt | 348,062,453 | false | null | package no.nav.pensjon.selvbetjening.fssgw.tech.web
import org.springframework.http.client.reactive.ReactorClientHttpConnector
import org.springframework.web.reactive.function.client.ExchangeStrategies
import org.springframework.web.reactive.function.client.WebClient
import reactor.netty.http.client.HttpClient
object WebClientPreparer {
private const val MAX_IN_MEMORY_SIZE = 10 * 1024 * 1024 // 10 MB
fun webClient(requiresProxy: Boolean, proxyUri: String) =
if (requiresProxy) proxyAwareWebClient(proxyUri)
else WebClient.create()
fun largeBufferWebClient(): WebClient {
val httpClient = HttpClient.create().wiretap(true)
val strategies = ExchangeStrategies.builder()
.codecs { it.defaultCodecs().maxInMemorySize(MAX_IN_MEMORY_SIZE) }
.build()
return WebClient.builder()
.clientConnector(ReactorClientHttpConnector(httpClient))
.exchangeStrategies(strategies).build()
}
private fun proxyAwareWebClient(proxyUri: String) =
WebClient.builder()
.clientConnector(WebClientProxyConfig.clientHttpConnector(proxyUri))
.build()
}
| 0 | Kotlin | 1 | 0 | a93aa7b5f92385bad4971bb122c944c10ed396d6 | 1,174 | pensjon-selvbetjening-fss-gateway | MIT License |
domain/src/main/java/com/example/domain/GetCharacterDetailsUseCase.kt | byronsanchez0 | 651,670,123 | false | null | package com.example.domain
import com.example.domain.details.model.Character
import javax.inject.Inject
class GetCharacterDetailsUseCase @Inject constructor(private val animeRepo: AnimeRepo) {
suspend operator fun invoke(id: Int): Character {
return animeRepo.getAnimeCharacters(id)
}
}
| 0 | Kotlin | 0 | 0 | b33306c562dc4702c8be6a639ad636ab3f656beb | 305 | AnimeCleanApp | MIT License |
app/src/main/java/com/github/dudgns0507/mvvm_cropo/ui/main/MainBundle.kt | dudgns0507 | 379,595,025 | false | null | package com.github.dudgns0507.mvvm_cropo.ui.main
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class MainBundle(
val t: String
) : Parcelable | 1 | Kotlin | 1 | 2 | c69453e3898271eba176975a8f5d1f2cc38386aa | 186 | MVVM-cropo | The Unlicense |
shell/src/main/java/com/stewemetal/takehometemplate/shell/navigation/model/Route.kt | stewemetal | 673,927,337 | false | {"Kotlin": 70954} | package com.stewemetal.takehometemplate.shell.navigation.model
import android.app.Activity
import android.content.DialogInterface
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
sealed interface Route
data class ScreenRoute(
val activityType: Class<out Activity>,
val fragmentType: Class<out Fragment>? = null,
val extras: Bundle? = null,
val activityTransition: ForwardBackTransitions? = null,
val fragmentTransition: ForwardBackTransitions? = null,
) : Route
data class BottomSheetRoute(
val sheetFragmentType: Class<out BottomSheetDialogFragment>,
val sheetContentType: Class<out Fragment>? = null,
val extras: Bundle? = null,
val contentTransition: ForwardBackTransitions? = null,
) : Route
data class DialogRoute(
val title: String? = null,
val message: String,
val positiveButtonText: String,
val positiveButtonClick: DialogInterface.OnClickListener,
val negativeButtonText: String? = null,
val negativeButtonClick: DialogInterface.OnClickListener? = null,
val neutralButtonText: String? = null,
val neutralButtonClick: DialogInterface.OnClickListener? = null,
val themeResId: Int? = null,
) : Route
| 7 | Kotlin | 0 | 0 | d6ba6bb847c20929e19631227b1bb308141b7b38 | 1,271 | android-takehometemplate-multimodule | Apache License 2.0 |
app/src/main/kotlin/net/primal/android/core/compose/feed/model/FeedPostsSyncStats.kt | PrimalHQ | 639,579,258 | false | {"Kotlin": 2739955} | package net.primal.android.core.compose.feed.model
import net.primal.android.attachments.domain.CdnImage
data class FeedPostsSyncStats(
val latestNoteIds: List<String> = emptyList(),
val latestAvatarCdnImages: List<CdnImage> = emptyList(),
)
| 79 | Kotlin | 15 | 124 | e95bbd03e3e6d57e5710449a9f968f42778fa1cd | 252 | primal-android-app | MIT License |
bank-vault-ui/src/main/kotlin/kspt/bank/views/client/CellChoiceView.kt | wndrws | 121,561,360 | false | {"Java": 141347, "Kotlin": 36862, "Batchfile": 280} | package kspt.bank.views.client
import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.collections.FXCollections
import javafx.geometry.Insets
import kspt.bank.ChoosableCellSize
import kspt.bank.controllers.CellApplicationController
import tornadofx.*
class CellChoiceView : View() {
private val model = ViewModel()
private val cellSizes = FXCollections.observableArrayList(*ChoosableCellSize.values())
private val selectedSize = model.bind { SimpleObjectProperty<ChoosableCellSize>() }
private val period = model.bind { SimpleIntegerProperty() }
private val cellApplicationController: CellApplicationController by inject()
override val root = vbox {
padding = Insets(20.0)
form {
fieldset("Выбор ячейки") {
field("Желаемый размер") {
combobox(selectedSize, cellSizes).required()
}
field("Период аренды (дней):") {
textfield(period).validator {
if (it.isNullOrBlank()) error("This field is required")
else if (it?.isInt() != true) error("Введите число")
else if (it.toInt() <= 0) error("Недопустимое число")
else null
}
}
}
}
anchorpane {
button("Отмена" ) {
anchorpaneConstraints { leftAnchor = 0 }
action {
find(CellChoiceView::class).replaceWith(ClientMainView::class, sizeToScene = true)
}
}
button("Дальше") {
anchorpaneConstraints { rightAnchor = 0 }
enableWhen(model.valid)
action {
cellApplicationController.processCellRequest(selectedSize.value, period.value.toInt())
}
}
}
}
} | 1 | null | 1 | 1 | b04b8cf29f91268eed3ad49c0bb54e92ff0b8b2c | 1,967 | bank-vault | MIT License |
http/common/src/main/kotlin/edu/byu/uapi/http/HttpEngineBase.kt | byu-oit | 130,911,554 | false | null | package edu.byu.uapi.http
import edu.byu.uapi.http.docs.DialectDocSource
import edu.byu.uapi.http.docs.DocSource
import edu.byu.uapi.http.docs.SwaggerViewerDocs
import edu.byu.uapi.http.json.JsonEngine
import edu.byu.uapi.model.UAPIModel
import edu.byu.uapi.model.dialect.UAPIDialect
import edu.byu.uapi.model.serialization.UAPISerializationFormat
import edu.byu.uapi.server.UAPIRuntime
import edu.byu.uapi.server.resources.list.ListResourceRuntime
import org.slf4j.LoggerFactory
abstract class HttpEngineBase<Server : Any, Config : HttpEngineConfig>(
val config: Config
) {
@Suppress("PrivatePropertyName")
private val LOG = LoggerFactory.getLogger(this.javaClass)
abstract fun startServer(config: Config): Server
private lateinit var _server: Server
val server: Server
get() = this._server
protected fun doInit() {
_server = startServer(config)
}
private fun checkInitialized() {
if (!this::_server.isInitialized) {
throw IllegalStateException(this::class.qualifiedName + " must call super.doInit() in its constructor.")
}
}
fun <UserContext : Any> register(
runtime: UAPIRuntime<UserContext>,
rootPath: String = ""
) {
checkInitialized()
val resources = runtime.resources().map {
when (it) {
is ListResourceRuntime<UserContext, *, *, *> -> HttpListResource(runtime, config, it)
}
}
val routes = resources.flatMap { it.routes }
registerRoutes(_server, config, routes, rootPath, runtime)
registerDocRoutes(_server, config, docRoutes(runtime.model), rootPath, runtime)
LOG.info("Finished registering routes for root path '/$rootPath'")
}
private fun docRoutes(model: UAPIModel): List<DocRoute> {
val rootPath: List<PathPart> = listOf(StaticPathPart("\$docs"))
return UAPIDialect.findAllDialects()
.flatMap { d -> UAPISerializationFormat.values().map { d to it } }
.map { DialectDocSource(model, it.first, it.second) }
.map { DocRoute(it, rootPath) } + DocRoute(SwaggerViewerDocs(model), rootPath)
}
abstract fun stop(server: Server)
abstract fun registerRoutes(
server: Server,
config: Config,
routes: List<HttpRoute>,
rootPath: String,
runtime: UAPIRuntime<*>
)
abstract fun registerDocRoutes(
server: Server,
config: Config,
docRoutes: List<DocRoute>,
rootPath: String,
runtime: UAPIRuntime<*>
)
}
data class DocRoute (
val path: List<PathPart>,
val source: DocSource
) {
constructor(source: DocSource, basePath: List<PathPart>): this(
basePath + StaticPathPart(source.name),
source
)
}
interface HttpEngineConfig {
val jsonEngine: JsonEngine<*, *>
}
| 16 | Kotlin | 0 | 0 | 1ca0e357a1b00cf11c1e1c9a1b00af4455d6d30c | 2,874 | kotlin-uapi | Apache License 2.0 |
src/main/kotlin/br/com/fabiofiorita/restapi/mapper/Mapper.kt | FabioFiorita | 626,425,405 | false | null | package br.com.fabiofiorita.restapi.mapper
interface Mapper<T, U> {
fun map(t: T): U
}
| 0 | Kotlin | 0 | 0 | 78a9c395cf1614164640e5c9e7d08042a3b2347a | 92 | Kotlin-REST-API | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.