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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
plugin/src/main/kotlin/ir/taher7/melodymine/database/Database.kt | Vallerian | 700,695,551 | false | {"Kotlin": 203245, "TypeScript": 151420, "CSS": 4018, "Shell": 2145, "JavaScript": 1577, "Dockerfile": 367} | package ir.taher7.melodymine.database
import com.cryptomorin.xseries.ReflectionUtils
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import ir.taher7.melodymine.MelodyMine
import ir.taher7.melodymine.models.MelodyPlayer
import ir.taher7.melodymine.storage.Messages
import ir.taher7.melodymine.storage.Settings
import ir.taher7.melodymine.utils.Utils
import org.bukkit.Bukkit
import org.bukkit.entity.Player
import org.bukkit.scheduler.BukkitRunnable
import java.sql.Connection
import java.sql.Statement
import java.util.function.Consumer
object Database {
lateinit var hikari: HikariDataSource
init {
try {
connect()
initialize()
} catch (ex: Exception) {
ex.printStackTrace()
}
}
private fun connect() {
try {
val config = HikariConfig()
config.setJdbcUrl("jdbc:mysql://${Settings.host}:${Settings.port}/${Settings.database}")
if (ReflectionUtils.supports(13)) {
config.driverClassName = "com.mysql.cj.jdbc.Driver"
} else {
config.driverClassName = "com.mysql.jdbc.Driver"
}
config.username = Settings.username
config.password = Settings.password
config.maximumPoolSize = 10
hikari = HikariDataSource(config)
MelodyMine.instance.logger.info(Messages.getMessage("success.database"))
} catch (ex: Exception) {
MelodyMine.instance.logger.severe(Messages.getMessage("errors.database"))
ex.printStackTrace()
}
}
private fun initialize() {
if (!::hikari.isInitialized) return
try {
val connection = createConnection() ?: return
val statement = connection.createStatement()
statement.execute("CREATE TABLE IF NOT EXISTS melodymine(id INTEGER AUTO_INCREMENT PRIMARY KEY ,uuid VARCHAR(36) UNIQUE ,name VARCHAR(36),socketID VARCHAR(36) UNIQUE ,verifyCode VARCHAR(36) UNIQUE ,server VARCHAR(36),serverIp VARCHAR(36),webIp VARCHAR(36),isActiveVoice BOOLEAN default FALSE,isMute BOOLEAN default FALSE,serverIsOnline BOOLEAN default FALSE, webIsOnline BOOLEAN default FALSE)")
closeConnection(connection)
} catch (ex: Exception) {
ex.printStackTrace()
}
}
private fun createConnection(): Connection? {
if (!::hikari.isInitialized) return null
return try {
hikari.getConnection()
} catch (e: Exception) {
e.printStackTrace()
null
}
}
private fun closeConnection(connection: Connection) {
if (!::hikari.isInitialized) return
try {
connection.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun initPlayer(player: Player, consumer: Consumer<MelodyPlayer>) {
if (!::hikari.isInitialized) return
object : BukkitRunnable() {
override fun run() {
try {
val connection = createConnection() ?: return
val statement = connection.prepareStatement(
"INSERT INTO melodymine(uuid,name,verifyCode,server,serverIsOnline) VALUES (?,?,?,?,?)",
Statement.RETURN_GENERATED_KEYS
)
val verifyCode = Utils.getVerifyCode()
statement.setString(1, player.player?.uniqueId.toString())
statement.setString(2, player.name)
statement.setString(3, verifyCode)
statement.setString(4, Settings.server)
statement.setBoolean(5, true)
statement.executeUpdate()
val generatedKeys = statement.generatedKeys
if (generatedKeys.next()) {
val id = generatedKeys.getLong(1)
val melodyPlayer = MelodyPlayer(
id = id.toInt(),
player = player.player,
uuid = player.player?.uniqueId.toString(),
name = player.name,
verifyCode = verifyCode,
server = Settings.server,
serverIsOnline = true,
)
consumer.accept(melodyPlayer)
}
closeConnection(connection)
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}.runTaskAsynchronously(MelodyMine.instance)
}
fun findPlayer(uuid: String, consumer: Consumer<MelodyPlayer?>) {
if (!::hikari.isInitialized) return
object : BukkitRunnable() {
override fun run() {
try {
val connection = createConnection() ?: return
val statement = connection.prepareStatement("SELECT * FROM melodymine WHERE uuid = ?")
statement.setString(1, uuid)
val result = statement.executeQuery()
if (result.next()) {
consumer.accept(
MelodyPlayer(
id = result.getInt("id"),
uuid = result.getString("uuid"),
name = result.getString("name"),
server = result.getString("server"),
socketID = result.getString("socketID"),
verifyCode = result.getString("verifyCode"),
serverIsOnline = result.getBoolean("serverIsOnline"),
webIsOnline = result.getBoolean("webIsOnline"),
isActiveVoice = result.getBoolean("isActiveVoice"),
isMute = result.getBoolean("isMute"),
)
)
} else {
consumer.accept(null)
}
closeConnection(connection)
} catch (ex: Exception) {
consumer.accept(null)
ex.printStackTrace()
}
}
}.runTaskAsynchronously(MelodyMine.instance)
}
fun updatePlayer(player: MelodyPlayer, leave: Boolean) {
if (!::hikari.isInitialized) return
object : BukkitRunnable() {
override fun run() {
try {
val connection = createConnection() ?: return
if (!leave) {
val statement = connection.prepareStatement(
"UPDATE melodymine SET verifyCode = ?,server = ?, serverIsOnline = ?,isMute = ? WHERE uuid = ? LIMIT 1"
)
statement.setString(1, player.verifyCode)
statement.setString(2, player.server)
statement.setBoolean(3, player.serverIsOnline)
statement.setBoolean(4, player.isMute)
statement.setString(5, player.uuid)
statement.executeUpdate()
} else {
val statement = connection.prepareStatement(
"UPDATE melodymine SET verifyCode = ?,server = ?, serverIsOnline = ?,isMute = ? WHERE uuid = ? AND server = ?"
)
statement.setString(1, player.verifyCode)
statement.setString(2, player.server)
statement.setBoolean(3, player.serverIsOnline)
statement.setBoolean(4, player.isMute)
statement.setString(5, player.uuid)
statement.setString(6, Settings.server)
statement.executeUpdate()
}
closeConnection(connection)
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}.runTaskAsynchronously(MelodyMine.instance)
}
fun resetDate() {
if (!::hikari.isInitialized) return
val connection = createConnection() ?: return
val statement = connection.prepareStatement(
"UPDATE melodymine SET serverIsOnline = ? WHERE serverIsOnline = ? AND server = ?"
)
statement.setBoolean(1, false)
statement.setBoolean(2, true)
statement.setString(3, Settings.server)
statement.executeUpdate()
closeConnection(connection)
}
fun updateSocketPlayer() {
object : BukkitRunnable() {
override fun run() {
try {
val connection = createConnection() ?: return
val uuidList = arrayListOf<String>()
Bukkit.getOnlinePlayers().forEach { player: Player ->
uuidList.add(player.uniqueId.toString())
}
if (uuidList.isNotEmpty()) {
val placeholders = uuidList.joinToString(separator = ",", prefix = "(", postfix = ")") { "?" }
val sql = "UPDATE melodymine SET serverIsOnline = ? WHERE uuid IN $placeholders"
val statement = connection.prepareStatement(sql)
statement.setBoolean(1, true)
uuidList.forEachIndexed { index, uuid ->
statement.setString(index + 2, uuid)
}
statement.executeUpdate()
}
closeConnection(connection)
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}.runTaskAsynchronously(MelodyMine.instance)
}
fun getVerifyCode(player: Player, consumer: Consumer<String>) {
object : BukkitRunnable() {
override fun run() {
try {
val connection = createConnection() ?: return
val statement = connection.prepareStatement(
"SELECT verifyCode FROM melodymine WHERE uuid = ?"
)
statement.setString(1, player.uniqueId.toString())
val result = statement.executeQuery()
if (result.next()) {
consumer.accept(result.getString("verifyCode"))
} else {
val verifyCode = Utils.getVerifyCode()
val statement = connection.prepareStatement(
"UPDATE melodymine SET verifyCode = ? WHERE uuid = ? "
)
statement.setString(1, verifyCode)
statement.setString(2, player.uniqueId.toString())
statement.executeUpdate()
consumer.accept(verifyCode)
}
closeConnection(connection)
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}.runTaskAsynchronously(MelodyMine.instance)
}
} | 6 | Kotlin | 9 | 34 | b3a133082180551341addd09f743a6605086eb62 | 11,431 | MelodyMine | Apache License 2.0 |
examples/android/src/main/java/io/github/g0dkar/qrcode/QRCodeListActivity.kt | g0dkar | 418,322,972 | false | null | package io.github.g0dkar.qrcode
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import io.github.g0dkar.qrcode.NewQRCodeActivity.Companion.QRCODE_DATA
import io.github.g0dkar.qrcode.extra.QRCodeListAdapter
import io.github.g0dkar.qrcode.extra.QRCodeListDatasource
class QRCodeListActivity : AppCompatActivity() {
private val listAdapter = QRCodeListAdapter {
val intent = Intent(this@QRCodeListActivity, QRCodeDetailActivity::class.java)
intent.putExtra(QRCodeDetailActivity.QRCODE_DATA, it.data)
intent.putExtra(QRCodeDetailActivity.QRCODE_TIMESTAMP, it.timestamp.toEpochSecond())
startActivity(intent)
}
private lateinit var recyclerView: RecyclerView
private lateinit var fab: View
private lateinit var newQRCodeActivity: ActivityResultLauncher<Intent>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fab = findViewById(R.id.fab)
recyclerView = findViewById(R.id.recycler_view)
QRCodeListDatasource.fromContext(this)
recyclerView.adapter = listAdapter
fab.setOnClickListener {
startNewQRCodeActivity()
}
newQRCodeActivity = registerForActivityResult(StartActivityForResult()) {
if (it.data != null) {
val result = it.resultCode
if (result == RESULT_OK) {
val qrCodeData = it.data?.getStringExtra(QRCODE_DATA)
if (qrCodeData != null) {
QRCodeListDatasource.add(qrCodeData)
} else {
Toast.makeText(
this@QRCodeListActivity,
R.string.new_qrcode_error,
Toast.LENGTH_LONG
).show()
}
} else {
Toast.makeText(
this@QRCodeListActivity,
R.string.new_qrcode_error,
Toast.LENGTH_LONG
).show()
}
}
}
}
override fun onResume() {
super.onResume()
QRCodeListDatasource.liveData.observe(this) {
if (it != null) {
listAdapter.submitList(it)
}
}
}
override fun onStop() {
super.onStop()
QRCodeListDatasource.liveData.removeObservers(this)
}
private fun startNewQRCodeActivity() {
val intent = Intent(this, NewQRCodeActivity::class.java)
newQRCodeActivity.launch(intent)
}
}
| 4 | null | 4 | 97 | 71f51478d99948899d18f7cbc5e0cb0cf59a46ba | 2,962 | qrcode-kotlin | MIT License |
pillarbox-player/src/main/java/ch/srgssr/pillarbox/player/tracker/MediaItemTrackerProvider.kt | SRGSSR | 519,157,987 | false | {"Kotlin": 660173, "Shell": 555} | /*
* Copyright (c) SRG SSR. All rights reserved.
* License information is available from the LICENSE file.
*/
package ch.srgssr.pillarbox.player.tracker
/**
* Tracker factory
*
* @constructor Create empty Tracker factory
*/
interface MediaItemTrackerProvider {
/**
* Get media item tracker factory
*
* @param trackerClass
* @return
*/
fun getMediaItemTrackerFactory(trackerClass: Class<*>): MediaItemTracker.Factory
}
| 16 | Kotlin | 0 | 9 | 7209750736a47157f22dd939a17750d649172f0a | 459 | pillarbox-android | MIT License |
pillarbox-player/src/main/java/ch/srgssr/pillarbox/player/tracker/MediaItemTrackerProvider.kt | SRGSSR | 519,157,987 | false | {"Kotlin": 660173, "Shell": 555} | /*
* Copyright (c) SRG SSR. All rights reserved.
* License information is available from the LICENSE file.
*/
package ch.srgssr.pillarbox.player.tracker
/**
* Tracker factory
*
* @constructor Create empty Tracker factory
*/
interface MediaItemTrackerProvider {
/**
* Get media item tracker factory
*
* @param trackerClass
* @return
*/
fun getMediaItemTrackerFactory(trackerClass: Class<*>): MediaItemTracker.Factory
}
| 16 | Kotlin | 0 | 9 | 7209750736a47157f22dd939a17750d649172f0a | 459 | pillarbox-android | MIT License |
app/src/main/java/com/plcoding/composepaging3caching/data/database/BeerDao.kt | diogosantos41 | 706,395,695 | false | {"Kotlin": 19426} | package com.dscoding.paging3caching.data.local
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Upsert
@Dao
interface BeerDao {
@Upsert
suspend fun upsertAll(beers: List<BeerEntity>)
@Query("SELECT * FROM BeerEntity")
fun pagingSource(): PagingSource<Int, BeerEntity>
@Query("DELETE FROM BeerEntity")
suspend fun clearAll()
} | 0 | Kotlin | 0 | 0 | 41e4b2f58fef284d2bd18d4d54cce760117d75c8 | 413 | paging3-cache-android | MIT License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/Tally1.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.Tally1: ImageVector
get() {
if (_tally1 != null) {
return _tally1!!
}
_tally1 = Builder(name = "Tally1", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(1.5f, 24.0f)
curveToRelative(-0.829f, 0.0f, -1.5f, -0.671f, -1.5f, -1.5f)
verticalLineTo(1.5f)
curveTo(0.0f, 0.671f, 0.671f, 0.0f, 1.5f, 0.0f)
reflectiveCurveToRelative(1.5f, 0.671f, 1.5f, 1.5f)
verticalLineToRelative(21.0f)
curveToRelative(0.0f, 0.829f, -0.671f, 1.5f, -1.5f, 1.5f)
close()
}
}
.build()
return _tally1!!
}
private var _tally1: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 1,624 | icons | MIT License |
app/src/main/java/com/msomodi/imageverse/view/common/PackageCard.kt | MarioSomodi | 602,268,671 | false | null | package com.msomodi.imageverse.view.common
import android.content.res.Configuration
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Card
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.MaterialTheme.typography
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.msomodi.imageverse.R
import com.msomodi.imageverse.model.packages.response.PackageResponse
import com.msomodi.imageverse.ui.theme.ImageverseTheme
@Composable
fun PackageCard(
modifier : Modifier = Modifier,
smallerCard : Boolean,
packageObj : PackageResponse,
onSelectPackage : (String) -> Unit,
selectedPackageId : String,
){
val selected : Boolean = selectedPackageId == packageObj.id
Card(
modifier = modifier
.width(IntrinsicSize.Max)
.border(width = 2.dp, shape = RoundedCornerShape(30.dp), color = if(selected) MaterialTheme.colors.primary else MaterialTheme.colors.background),
shape = RoundedCornerShape(30.dp),
elevation = 5.dp
) {
Column(
modifier = modifier
.width(IntrinsicSize.Max)
.padding(15.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = if(smallerCard) Arrangement.spacedBy(3.dp) else Arrangement.spacedBy(15.dp)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = if(smallerCard) Arrangement.spacedBy(3.dp) else Arrangement.spacedBy(15.dp)
) {
Text(
text = packageObj.name,
style = typography.h5
)
Text(
text = "EUR ${packageObj.price}",
fontSize = 35.sp,
fontWeight = FontWeight.SemiBold
)
Text(
text = stringResource(R.string.a_month),
style = typography.h5
)
}
Divider(
modifier = modifier
.clip(RoundedCornerShape(20.dp)),
color = MaterialTheme.colors.primary,
thickness = 2.dp
)
Column(
modifier = modifier
.width(IntrinsicSize.Max),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
Text(
text = "Upload images up to ${packageObj.uploadSizeLimit}MB",
style = typography.h5,
textAlign = TextAlign.Center
)
Text(
text = "Max daily upload is ${packageObj.dailyUploadLimit}MB",
style = typography.h5,
textAlign = TextAlign.Center
)
Text(
text = "${packageObj.dailyImageUploadLimit} images daily",
style = typography.h5,
textAlign = TextAlign.Center
)
}
Divider(
modifier = modifier
.clip(RoundedCornerShape(20.dp)),
color = MaterialTheme.colors.primary,
thickness = 2.dp
)
Button(
modifier = modifier
.fillMaxWidth(),
onClick = {onSelectPackage(packageObj.id)},
shape = RoundedCornerShape(15.dp),
enabled = !selected
) {
Text(text = stringResource(R.string.choose_this_package))
}
}
}
}
@Preview(showBackground = true)
@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PackageCardPreview(){
val packageObj = PackageResponse(
"1",
"Default",
9.99.toDouble(),
10,
10,
10
)
ImageverseTheme {
Surface(modifier = Modifier.fillMaxWidth()) {
PackageCard(packageObj = packageObj, onSelectPackage = {}, selectedPackageId = packageObj.id, smallerCard = false)
}
}
} | 0 | Kotlin | 0 | 0 | 57cac8c5b439b1ad52c18b6a67f477e743f5bf9e | 5,141 | Imageverse | MIT License |
app/src/main/java/com/github/drunlin/webappbox/model/WebappModel.kt | Mass-Reports | 349,377,938 | true | {"Kotlin": 172282, "HTML": 1409} | package com.github.drunlin.webappbox.model
import android.content.Context
import android.graphics.Bitmap
import com.github.drunlin.webappbox.R
import com.github.drunlin.webappbox.common.Callback
import com.github.drunlin.webappbox.common.getBitmap
import com.github.drunlin.webappbox.data.Policy
import com.github.drunlin.webappbox.data.Webapp
import javax.inject.Inject
open class WebappModel(protected val id: Long) {
@Inject lateinit var context: Context
val onUrlChange = Callback<(String) -> Unit>()
open val originalUrl = ""
open val webapp by lazy { Webapp(id, "", context.getBitmap(R.mipmap.ic_webapp), "", Policy.ASK) }
open fun setUrl(url: String) {
webapp.url = url
onUrlChange.invoke { it(url) }
}
open fun setLocationPolicy(policy: Policy) {
webapp.locationPolicy = policy
}
fun update(url: String, icon: Bitmap, name: String, locationPolicy: Policy) {
webapp.url = url
webapp.icon = icon
webapp.name = name
webapp.locationPolicy = locationPolicy
}
}
| 0 | null | 0 | 0 | 778b078dee694a6d1b74d40cd14de823a2a002d2 | 1,067 | webappbox | Apache License 2.0 |
quickhttp/src/main/java/org/quick/http/UploadingRequestBody.kt | SpringSmell | 200,751,390 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 20, "Kotlin": 25, "Java": 3} | package org.quick.http
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.Buffer
import okio.BufferedSink
import okio.Okio
import okio.source
import org.quick.async.Async
import org.quick.http.callback.OnUploadingListener
import java.io.File
/**
* 上传文件-请求体
*/
class UploadingRequestBody(var mediaType: MediaType, var key: String, var file: File, var onUploadingListener: OnUploadingListener<*>?) : RequestBody() {
override fun contentType(): MediaType? = mediaType
override fun contentLength(): Long = file.length()
override fun writeTo(sink: BufferedSink) {
val source = file.source()
val buffer = Buffer()
var redBytesCount: Long
var redBytesTotalCount = 0L
var lastTime = 0L
var tempTime: Long
var isDone = false
val byteCount = 2048L
redBytesCount = source.read(buffer, byteCount)
while (redBytesCount != -1L) {
redBytesTotalCount += redBytesCount
sink.write(buffer, redBytesCount)
redBytesCount = source.read(buffer, byteCount)
tempTime = System.currentTimeMillis() - lastTime
if (tempTime > 100L) {/*间隔80毫秒触发一次,否则队列阻塞*/
lastTime = System.currentTimeMillis()
if (!isDone) {/*完成后只触发一次*/
isDone = redBytesCount == -1L
Async.runOnUiThread { onUploadingListener?.onLoading(key, redBytesTotalCount, contentLength(), isDone) }
}
}
}
if (!isDone) Async.runOnUiThread { onUploadingListener?.onLoading(key, redBytesTotalCount, contentLength(), true) }
}
} | 1 | null | 1 | 1 | e0d58bf8cb2cd7057ffda72f0031dcca313beb20 | 1,648 | QuickHttpService | Apache License 2.0 |
compiler/testData/codegen/boxInline/nonLocalReturns/tryFinally/exceptionTable/throwInFinally.kt | JakeWharton | 99,388,807 | false | null | // FILE: 1.kt
package test
public inline fun <R> doCall(block: ()-> R, exception: (e: Exception)-> Unit, finallyBlock: ()-> R) : R {
try {
return block()
} catch (e: Exception) {
exception(e)
} finally {
return finallyBlock()
}
}
public inline fun <R> doCall2(block: ()-> R, exception: (e: Exception)-> Unit, finallyBlock: ()-> R) : R {
try {
return block()
} catch (e: Exception) {
exception(e)
} finally {
finallyBlock()
}
throw java.lang.RuntimeException("fail")
}
// FILE: 2.kt
import test.*
class Holder {
var value: String = ""
}
fun test0(h: Holder): String {
try {
val localResult = doCall (
{
h.value += "OK_NON_LOCAL"
return "OK_NON_LOCAL"
},
{
h.value += ", OK_EXCEPTION"
"OK_EXCEPTION"
},
{
h.value += ", OK_FINALLY"
throw java.lang.RuntimeException("FINALLY")
"OK_FINALLY"
})
return localResult;
} catch (e: RuntimeException) {
if (e.message != "FINALLY") {
return "FAIL in exception: " + e.message
} else {
return "CATCHED_EXCEPTION"
}
}
return "FAIL";
}
fun test1(h: Holder): String {
try {
val localResult = doCall (
{
h.value += "OK_LOCAL"
throw java.lang.RuntimeException("FAIL")
"OK_LOCAL"
},
{
h.value += ", OK_EXCEPTION"
"OK_EXCEPTION"
},
{
h.value += ", OK_FINALLY"
throw java.lang.RuntimeException("FINALLY")
"OK_FINALLY"
})
} catch (e: RuntimeException) {
if (e.message != "FINALLY") {
return "FAIL in exception: " + e.message
} else {
return "CATCHED_EXCEPTION"
}
}
return "FAIL";
}
fun test2(h: Holder): String {
val localResult = doCall (
{
h.value += "OK_LOCAL"
throw java.lang.RuntimeException()
"OK_LOCAL"
},
{
h.value += ", OK_EXCEPTION"
"OK_EXCEPTION"
},
{
h.value += ", OK_FINALLY"
"OK_FINALLY"
})
return localResult;
}
fun test3(h: Holder): String {
try {
val localResult = doCall (
{
h.value += "OK_LOCAL"
throw java.lang.RuntimeException("FAIL")
"OK_LOCAL"
},
{
h.value += ", OK_EXCEPTION"
throw java.lang.RuntimeException("FAIL_EX")
"OK_EXCEPTION"
},
{
h.value += ", OK_FINALLY"
throw java.lang.RuntimeException("FINALLY")
"OK_FINALLY"
})
} catch (e: RuntimeException) {
if (e.message != "FINALLY") {
return "FAIL in exception: " + e.message
} else {
return "CATCHED_EXCEPTION"
}
}
return "FAIL";
}
fun test4(h: Holder): String {
try {
val localResult = doCall2 (
{
h.value += "OK_LOCAL"
throw java.lang.RuntimeException("FAIL")
"OK_LOCAL"
},
{
h.value += ", OK_EXCEPTION"
throw java.lang.RuntimeException("EXCEPTION")
"OK_EXCEPTION"
},
{
h.value += ", OK_FINALLY"
"OK_FINALLY"
})
} catch (e: RuntimeException) {
if (e.message != "EXCEPTION") {
return "FAIL in exception: " + e.message
} else {
return "CATCHED_EXCEPTION"
}
}
return "FAIL";
}
fun box(): String {
var h = Holder()
val test0 = test0(h)
if (test0 != "CATCHED_EXCEPTION" || h.value != "OK_NON_LOCAL, OK_FINALLY") return "test0: ${test0}, holder: ${h.value}"
h = Holder()
val test1 = test1(h)
if (test1 != "CATCHED_EXCEPTION" || h.value != "OK_LOCAL, OK_EXCEPTION, OK_FINALLY") return "test1: ${test1}, holder: ${h.value}"
h = Holder()
val test2 = test2(h)
if (test2 != "OK_FINALLY" || h.value != "OK_LOCAL, OK_EXCEPTION, OK_FINALLY") return "test2: ${test2}, holder: ${h.value}"
h = Holder()
val test3 = test3(h)
if (test3 != "CATCHED_EXCEPTION" || h.value != "OK_LOCAL, OK_EXCEPTION, OK_FINALLY") return "test3: ${test3}, holder: ${h.value}"
h = Holder()
val test4 = test4(h)
if (test4 != "CATCHED_EXCEPTION" || h.value != "OK_LOCAL, OK_EXCEPTION, OK_FINALLY") return "test4: ${test4}, holder: ${h.value}"
return "OK"
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 5,114 | kotlin | Apache License 2.0 |
technocracy.foundation/src/main/kotlin/net/cydhra/technocracy/foundation/client/gui/multiblock/MultiblockSettingsTab.kt | notphinix | 229,493,759 | true | {"Kotlin": 789585} | package net.cydhra.technocracy.foundation.client.gui.multiblock
import net.cydhra.technocracy.foundation.client.gui.TCGui
import net.cydhra.technocracy.foundation.client.gui.TCTab
import net.cydhra.technocracy.foundation.model.tileentities.multiblock.TileEntityMultiBlockPart
import net.minecraft.util.ResourceLocation
class MultiblockSettingsTab(parent: TCGui, val controller: TileEntityMultiBlockPart<*>) : TCTab("Settings", parent, icon = ResourceLocation("technocracy.foundation", "textures/item/gear.png")) {
override fun init() {}
} | 0 | Kotlin | 0 | 0 | 71a044f54f813b0213b6ae1f0394f49324ac9c1c | 546 | Technocracy | MIT License |
Barlom-Foundation-JVM/src/main/kotlin/x/barlom/infrastructure/graphs/Platform.kt | martin-nordberg | 82,682,055 | false | null | //
// (C) Copyright 2019 <NAME>
// Apache 2.0 License
//
package /*jvm*/x.barlom.infrastructure.graphs
//---------------------------------------------------------------------------------------------------------------------
/** Returns the class name for the given object [instance]. */
internal fun getClassName(instance:Any) =
instance::class.simpleName
//---------------------------------------------------------------------------------------------------------------------
| 0 | Kotlin | 0 | 0 | 337b46f01f6eec6dfb3b86824c26f1c103e9d9a2 | 485 | ZZ-Barlom | Apache License 2.0 |
compiler/testData/codegen/box/callableReference/kt49526a.kt | JetBrains | 3,432,266 | false | null | // IGNORE_BACKEND: NATIVE
// IGNORE_BACKEND_FIR: JVM_IR
// FIR_STATUS: callable reference type approximation hack not implemented
fun <T> id(x: T): T = x
fun <T> intersect(x: T, y: T): T = x
interface I1
interface I2
class C1 : I1, I2 {
override fun toString() = "OK"
}
class C2 : I1, I2
fun box() =
intersect(C1(), C2())
.let(::id)
.toString()
| 125 | Kotlin | 4903 | 39,894 | 0ad440f112f353cd2c72aa0a0619f3db2e50a483 | 375 | kotlin | Apache License 2.0 |
app/src/main/java/com/d10ng/app/demo/pages/LocationStatusManagerScreen.kt | D10NGYANG | 378,832,800 | false | {"Kotlin": 207694} | package com.d10ng.app.demo.pages
import android.Manifest
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.d10ng.app.demo.utils.back
import com.d10ng.app.managers.PermissionManager
import com.d10ng.app.status.LocationStatusManager
import com.d10ng.compose.model.UiViewModelManager
import com.d10ng.compose.ui.AppColor
import com.d10ng.compose.ui.PageTransitions
import com.d10ng.compose.ui.base.Cell
import com.d10ng.compose.ui.base.CellGroup
import com.d10ng.compose.ui.navigation.NavBar
import com.d10ng.datelib.toDateStr
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.annotation.RootNavGraph
/**
* 定位状态管理
* @Author d10ng
* @Date 2024/1/8 16:54
*/
@RootNavGraph
@Destination(style = PageTransitions::class)
@Composable
fun LocationStatusManagerScreen() {
LaunchedEffect(Unit) {
if (PermissionManager.request(
arrayOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
)
)
) {
LocationStatusManager.start()
} else {
UiViewModelManager.showFailToast("权限不足")
}
}
DisposableEffect(Unit) {
onDispose {
LocationStatusManager.stop()
}
}
LocationStatusManagerScreenView()
}
@Composable
private fun LocationStatusManagerScreenView() {
Column(
modifier = Modifier
.fillMaxSize()
.background(AppColor.Neutral.bg)
.navigationBarsPadding()
) {
NavBar(title = "定位状态", onClickBack = { back() })
Column(
modifier = Modifier
.fillMaxSize()
.weight(1f)
.verticalScroll(rememberScrollState())
) {
val location by LocationStatusManager.statusFlow.collectAsState(null)
CellGroup(title = "定位信息", inset = true) {
Cell(title = "时间", value = location?.time?.toDateStr() ?: "--")
Cell(title = "经度", value = location?.longitude?.toString() ?: "--")
Cell(title = "纬度", value = location?.latitude?.toString() ?: "--")
Cell(title = "海拔", value = "${location?.altitude}米")
Cell(title = "速度", value = "${location?.speed}m/s")
Cell(title = "方向", value = "${location?.bearing}度")
Cell(title = "精度", value = "${location?.accuracy}米")
Cell(title = "提供者", value = location?.provider ?: "--")
}
}
}
}
@Preview
@Composable
private fun LocationStatusManagerScreenPreview() {
LocationStatusManagerScreenView()
} | 0 | Kotlin | 0 | 1 | 90db8ad73b882c0ac53de29c5b3058beee6ec57d | 3,269 | DLAppUtil | MIT License |
app/src/main/java/com/mob/lee/fastair/model/ImageCategory.kt | hongui | 123,892,735 | false | null | package com.mob.lee.fastair.model
import android.provider.MediaStore
import com.mob.lee.fastair.R
class ImageCategory(override val title : Int= R.string.category_picture) :Category(){
override fun uri() = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
} | 3 | Kotlin | 14 | 72 | 0526fe4bb1eff33c1278c1ac86f02785710817bd | 258 | FastAir | Apache License 2.0 |
testedrawingapp/app/src/main/java/com/example/testedrawingapp/MainActivity.kt | WendelEduardo | 603,006,092 | false | null | package com.example.testedrawingapp
import android.app.Dialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ImageButton
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.core.view.get
class MainActivity : AppCompatActivity() {
private var drawingView: DrawingView? = null
private var imageButtonCurrentPaint: ImageButton? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
drawingView = findViewById(R.id.drawing_view)
drawingView?.setSizeForBrush(10.toFloat())
val ibBrush: ImageButton = findViewById(R.id.ib_brush)
ibBrush.setOnClickListener {
showBrushSizeChooserDialog()
}
val linearLayoutPaintColors = findViewById<LinearLayout>(R.id.ll_paint_colors)
imageButtonCurrentPaint = linearLayoutPaintColors[1] as ImageButton
imageButtonCurrentPaint?.setImageDrawable(
ContextCompat.getDrawable(
this,
R.drawable.pallet_pressed
)
)
}
private fun showBrushSizeChooserDialog() {
val brushDialog = Dialog(this)
brushDialog.setContentView(R.layout.dialog_brush_size)
brushDialog.setTitle("Brush size :")
val smallBtn: ImageButton = brushDialog.findViewById(R.id.ib_small_brush)
smallBtn.setOnClickListener(View.OnClickListener {
drawingView?.setSizeForBrush(10.toFloat())
brushDialog.dismiss()
})
val mediumBtn: ImageButton = brushDialog.findViewById(R.id.ib_medium_brush)
mediumBtn.setOnClickListener(View.OnClickListener {
drawingView?.setSizeForBrush(20.toFloat())
brushDialog.dismiss()
})
val largeBtn: ImageButton = brushDialog.findViewById(R.id.ib_large_brush)
largeBtn.setOnClickListener(View.OnClickListener {
drawingView?.setSizeForBrush(30.toFloat())
brushDialog.dismiss()
})
brushDialog.show()
}
fun paintClicked(view: View) {
if (view !== imageButtonCurrentPaint) {
val imageButton = view as ImageButton
val colorTag = imageButton.tag.toString()
drawingView?.setColor(colorTag)
imageButton.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.pallet_pressed))
imageButtonCurrentPaint?.setImageDrawable(
ContextCompat.getDrawable(
this,
R.drawable.pallet_normal
)
)
imageButtonCurrentPaint = view
}
}
} | 0 | Kotlin | 0 | 1 | 7db6eb60b550dcc747279f27f576dc78a95ba109 | 2,763 | Android_kotlin_developer | MIT License |
app/src/main/java/com/mbah1/jephthah/fieldservicereporter/features/students/domain/use_case/UpdateStudent.kt | sproutjeph | 668,215,949 | false | null | package com.mbah1.jephthah.fieldservicereporter.features.students.domain.use_case
import com.mbah1.jephthah.fieldservicereporter.features.students.data.repository.StudentRepository
import com.mbah1.jephthah.fieldservicereporter.features.students.domain.model.StudentModel
class UpdateStudent(
private val studentRepository: StudentRepository
) {
suspend operator fun invoke(studentModel: StudentModel) {
studentRepository.updateStudent(studentModel)
}
} | 0 | Kotlin | 0 | 0 | 446e0755a8a8d942421498553ed6c29aa9326252 | 475 | Field-Service-Reporter | MIT License |
presentation/src/main/java/com/ezzy/presentation/home/components/FeaturedItem.kt | EzekielWachira | 742,792,801 | false | {"Kotlin": 231925} | package com.ezzy.presentation.home.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.ezzy.data.domain.model.Property
import com.ezzy.data.utils.property
import com.ezzy.designsystem.components.CustomPadding
import com.ezzy.designsystem.theme.TripitacaTheme
import com.ezzy.designsystem.utils.DpDimensions
import com.ezzy.presentation.R
import com.ezzy.presentation.home.model.Listing
import com.ezzy.presentation.home.model.listings
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun FeaturedItem(
modifier: Modifier = Modifier,
listing: Property,
onClick: (Property) -> Unit = {}
) {
Surface(
modifier = modifier.width(220.dp),
onClick = { onClick(listing) },
color = MaterialTheme.colorScheme.onSurface,
shape = RoundedCornerShape(DpDimensions.Small),
border = BorderStroke(width = 1.dp, color = MaterialTheme.colorScheme.surface)
) {
Column(
modifier = Modifier
.padding(DpDimensions.Small)
) {
Box(
modifier = Modifier.width(200.dp)
) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(listing.photos[0])
.placeholder(R.drawable.placeholder)
.crossfade(true)
.build(),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.clip(RoundedCornerShape(DpDimensions.Small))
.height(DpDimensions.Dp150)
.fillMaxWidth()
)
CustomChip(
label = "Apartment", modifier = Modifier
.align(Alignment.BottomEnd)
)
}
CustomPadding(
verticalPadding = DpDimensions.Normal,
horizontalPadding = DpDimensions.Small
) {
Text(
text = listing.name,
color = MaterialTheme.colorScheme.inversePrimary,
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.Center,
maxLines = 1,
modifier = Modifier.basicMarquee()
)
Spacer(modifier = Modifier.height(DpDimensions.Small))
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(DpDimensions.Small)
) {
Icon(
painter = painterResource(id = R.drawable.pin), contentDescription = null,
modifier = Modifier.size(DpDimensions.Normal),
tint = MaterialTheme.colorScheme.inversePrimary
)
Text(
text = listing.smart_location,
color = MaterialTheme.colorScheme.inversePrimary,
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center
)
}
Spacer(modifier = Modifier.height(DpDimensions.Small))
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = stringResource(
R.string.currency,
listing.price.toFloat()
),
color = MaterialTheme.colorScheme.onPrimary,
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.Center
)
Text(
text = "/night",
color = MaterialTheme.colorScheme.inversePrimary,
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center
)
}
}
}
}
}
@Composable
fun CustomChip(
modifier: Modifier = Modifier,
label: String,
) {
CustomPadding(verticalPadding = DpDimensions.Small, horizontalPadding = DpDimensions.Small,
modifier = modifier) {
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.background.copy(alpha = 0.7f),
border = BorderStroke(width = 1.dp, color = MaterialTheme.colorScheme.outline)
) {
Row(modifier = Modifier.padding(DpDimensions.Small)) {
Text(
text = label,
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onPrimary,
)
}
}
}
}
@Preview
@Composable
fun FeaturedItemPreview() {
TripitacaTheme {
FeaturedItem(modifier = Modifier, property)
}
} | 0 | Kotlin | 0 | 0 | 4021ffb25fdb7aa82c57bae5de02379c319b19fe | 6,517 | Tripitaca | MIT License |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/filled/ArrowBigLeftLines.kt | walter-juan | 868,046,028 | false | null | package com.woowla.compose.icon.collections.tabler.tabler.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.FilledGroup
public val FilledGroup.ArrowBigLeftLines: ImageVector
get() {
if (_arrowBigLeftLines != null) {
return _arrowBigLeftLines!!
}
_arrowBigLeftLines = Builder(name = "ArrowBigLeftLines", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(9.586f, 4.0f)
lineToRelative(-6.586f, 6.586f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 0.0f, 2.828f)
lineToRelative(6.586f, 6.586f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.18f, 0.434f)
lineToRelative(0.145f, -0.068f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 1.089f, -1.78f)
verticalLineToRelative(-2.586f)
horizontalLineToRelative(2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, -1.0f)
verticalLineToRelative(-6.0f)
lineToRelative(-0.007f, -0.117f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -0.993f, -0.883f)
lineToRelative(-2.0f, -0.001f)
verticalLineToRelative(-2.585f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, -3.414f, -1.414f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0f, 8.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.993f, 0.883f)
lineToRelative(0.007f, 0.117f)
verticalLineToRelative(6.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.993f, 0.117f)
lineToRelative(-0.007f, -0.117f)
verticalLineToRelative(-6.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.0f, 8.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.993f, 0.883f)
lineToRelative(0.007f, 0.117f)
verticalLineToRelative(6.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.993f, 0.117f)
lineToRelative(-0.007f, -0.117f)
verticalLineToRelative(-6.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f)
close()
}
}
.build()
return _arrowBigLeftLines!!
}
private var _arrowBigLeftLines: ImageVector? = null
| 0 | null | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 3,863 | compose-icon-collections | MIT License |
web-regresjonstest/src/test/kotlin/no/nav/su/se/bakover/web/komponenttest/Komponenttest.kt | navikt | 227,366,088 | false | null | package no.nav.su.se.bakover.web.komponenttest
import io.getunleash.FakeUnleash
import io.getunleash.Unleash
import io.ktor.server.application.Application
import io.ktor.server.testing.ApplicationTestBuilder
import io.ktor.server.testing.testApplication
import no.nav.su.se.bakover.client.Clients
import no.nav.su.se.bakover.common.infrastructure.config.ApplicationConfig
import no.nav.su.se.bakover.domain.DatabaseRepos
import no.nav.su.se.bakover.domain.satser.SatsFactoryForSupplerendeStønad
import no.nav.su.se.bakover.test.applicationConfig
import no.nav.su.se.bakover.test.fixedClock
import no.nav.su.se.bakover.test.persistence.dbMetricsStub
import no.nav.su.se.bakover.test.persistence.withMigratedDb
import no.nav.su.se.bakover.test.satsFactoryTest
import no.nav.su.se.bakover.web.Consumers
import no.nav.su.se.bakover.web.SharedRegressionTestData
import no.nav.su.se.bakover.web.TestClientsBuilder
import no.nav.su.se.bakover.web.services.AccessCheckProxy
import no.nav.su.se.bakover.web.services.ServiceBuilder
import no.nav.su.se.bakover.web.services.Services
import no.nav.su.se.bakover.web.services.tilbakekreving.TilbakekrevingConsumer
import no.nav.su.se.bakover.web.services.utbetaling.kvittering.UtbetalingKvitteringConsumer
import no.nav.su.se.bakover.web.susebakover
import org.mockito.kotlin.mock
import java.time.Clock
import java.time.LocalDate
import javax.sql.DataSource
class AppComponents private constructor(
val clock: Clock,
val applicationConfig: ApplicationConfig,
val databaseRepos: DatabaseRepos,
val clients: Clients,
val unleash: Unleash,
val services: Services,
val accessCheckProxy: AccessCheckProxy,
val consumers: Consumers,
) {
companion object {
fun instance(
clock: Clock,
applicationConfig: ApplicationConfig,
dataSource: DataSource,
repoBuilder: (dataSource: DataSource, clock: Clock, satsFactory: SatsFactoryForSupplerendeStønad) -> DatabaseRepos,
clientBuilder: (databaseRepos: DatabaseRepos, clock: Clock) -> Clients,
serviceBuilder: (databaseRepos: DatabaseRepos, clients: Clients, clock: Clock, satsFactory: SatsFactoryForSupplerendeStønad, unleash: Unleash) -> Services,
): AppComponents {
val databaseRepos = repoBuilder(dataSource, clock, satsFactoryTest)
val clients = clientBuilder(databaseRepos, clock)
val unleash = FakeUnleash().apply { enableAll() }
val services: Services = serviceBuilder(databaseRepos, clients, clock, satsFactoryTest, unleash)
val accessCheckProxy = AccessCheckProxy(
personRepo = databaseRepos.person,
services = services,
)
val consumers = Consumers(
tilbakekrevingConsumer = TilbakekrevingConsumer(
tilbakekrevingService = services.tilbakekrevingService,
revurderingService = services.revurdering,
clock = clock,
),
utbetalingKvitteringConsumer = UtbetalingKvitteringConsumer(
utbetalingService = services.utbetaling,
ferdigstillVedtakService = services.ferdigstillVedtak,
clock = clock,
),
)
return AppComponents(
clock = clock,
databaseRepos = databaseRepos,
clients = clients,
unleash = unleash,
services = services,
accessCheckProxy = accessCheckProxy,
consumers = consumers,
applicationConfig = applicationConfig,
)
}
}
}
internal fun withKomptestApplication(
clock: Clock = fixedClock,
applicationConfig: ApplicationConfig = applicationConfig(),
repoBuilder: (dataSource: DataSource, clock: Clock, satsFactory: SatsFactoryForSupplerendeStønad) -> DatabaseRepos = { dataSource, klokke, satsFactory ->
SharedRegressionTestData.databaseRepos(
dataSource = dataSource,
clock = klokke,
satsFactory = satsFactory, // TODO uheldig at vi ikke kan overstyre denne med satsFactory.gjeldende(LocalDate.now(clock))
)
},
clientsBuilder: (databaseRepos: DatabaseRepos, clock: Clock) -> Clients = { databaseRepos, klokke ->
TestClientsBuilder(
clock = klokke,
databaseRepos = databaseRepos,
).build(applicationConfig)
},
serviceBuilder: (databaseRepos: DatabaseRepos, clients: Clients, clock: Clock, satsFactory: SatsFactoryForSupplerendeStønad, unleash: Unleash) -> Services = { databaseRepos, clients, klokke, satsFactory, unleash ->
ServiceBuilder.build(
databaseRepos = databaseRepos,
clients = clients,
behandlingMetrics = mock(),
søknadMetrics = mock(),
clock = klokke,
unleash = unleash,
satsFactory = satsFactory.gjeldende(LocalDate.now(klokke)),
applicationConfig = applicationConfig,
dbMetrics = dbMetricsStub,
)
},
test: ApplicationTestBuilder.(appComponents: AppComponents) -> Unit,
) {
withMigratedDb { dataSource ->
testApplication(
appComponents = AppComponents.instance(
clock = clock,
dataSource = dataSource,
repoBuilder = repoBuilder,
clientBuilder = clientsBuilder,
serviceBuilder = serviceBuilder,
applicationConfig = applicationConfig,
),
test = test,
)
}
}
fun Application.testSusebakover(appComponents: AppComponents) {
return susebakover(
clock = appComponents.clock,
applicationConfig = appComponents.applicationConfig,
unleash = appComponents.unleash,
databaseRepos = appComponents.databaseRepos,
clients = appComponents.clients,
services = appComponents.services,
accessCheckProxy = appComponents.accessCheckProxy,
)
}
fun testApplication(
appComponents: AppComponents,
test: ApplicationTestBuilder.(appComponents: AppComponents) -> Unit,
) {
testApplication {
application {
testSusebakover(appComponents)
}
test(appComponents)
}
}
| 1 | Kotlin | 0 | 1 | d7157394e11b5b3c714a420a96211abb0a53ea45 | 6,362 | su-se-bakover | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/model/request/WaitingListApplicationUpdateRequest.kt | ministryofjustice | 533,838,017 | false | {"Kotlin": 3661116, "Shell": 9529, "Dockerfile": 1478} | package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.model.request
import com.fasterxml.jackson.annotation.JsonFormat
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.validation.constraints.AssertTrue
import jakarta.validation.constraints.Size
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.WaitingListStatus
import java.time.LocalDate
@Schema(
description =
"""
Describes a single waiting list application to be updated.
""",
)
data class WaitingListApplicationUpdateRequest(
@Schema(
description = """
The updated past or present date on which the waiting list application was requested.
Note this cannot be after the date the waiting list application was first made.
""",
example = "2023-06-23",
)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
val applicationDate: LocalDate? = null,
@Schema(
description = "The updated person who made the request",
example = "<NAME>",
)
@field:Size(max = 100, message = "Requested by must not exceed {max} characters")
val requestedBy: String? = null,
@Schema(
description = "The updated comments related to the waiting list request",
example = "The prisoner has specifically requested to attend this activity",
)
@field:Size(max = 500, message = "Comments must not exceed {max} characters")
val comments: String? = null,
@Schema(
description = "The updated status of the application. Only PENDING, APPROVED or DECLINED are allowed when updating.",
example = "PENDING",
)
val status: WaitingListStatus? = null,
) {
@AssertTrue(message = "Requested by cannot be empty or blank")
private fun isRequestedBy() = requestedBy == null || requestedBy.isNotBlank()
@AssertTrue(message = "Application date cannot be in the future")
private fun isApplicationDate() = applicationDate == null || applicationDate <= LocalDate.now()
@AssertTrue(message = "Only PENDING, APPROVED or DECLINED are allowed for status")
private fun isStatus() =
status == null || listOf(WaitingListStatus.PENDING, WaitingListStatus.APPROVED, WaitingListStatus.DECLINED).contains(status)
}
| 10 | Kotlin | 0 | 1 | e8963f0ff3cba7eb2c9ace94b245cc08bfa9bfce | 2,185 | hmpps-activities-management-api | MIT License |
app/src/main/java/com/brightsolutions_knottracker/FavouriteList.kt | Mxttk | 729,033,334 | false | {"Kotlin": 142266} | @file:Suppress("unused", "unused", "unused", "unused", "unused", "unused", "unused", "unused",
"unused", "unused", "unused", "unused", "unused", "unused", "unused", "unused", "unused",
"unused", "unused", "unused", "unused"
)
package com.brightsolutions_knottracker
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.database.*
@Suppress("UNUSED_PARAMETER", "unused")
class FavouriteList : AppCompatActivity() {
private lateinit var recyclerFavKnots : RecyclerView
private lateinit var databaseReference: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_favourite_list)
recyclerFavKnots = findViewById(R.id.recyclerViewFavKnots)
recyclerFavKnots.layoutManager = LinearLayoutManager(this)
recyclerFavKnots.setHasFixedSize(true)
//init db
databaseReference = FirebaseDatabase.getInstance().reference
// grabbing user favourites list
val userReferenceKnots = databaseReference.child("userdata")
.child("productionUsers")
.child(User.userName.toString())
.child("myKnots")
val favoritesMap = mutableMapOf<String, KnotData>()
recyclerFavKnots.adapter = MyAdapter(context = this@FavouriteList,favoritesMap)
userReferenceKnots.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (snapshotUser in snapshot.children) {
for (snap in snapshotUser.children){
val knotData = snap.getValue(KnotData::class.java) as KnotData
when (knotData.isFavourite){
true -> {
favoritesMap[snap.key.toString()] = knotData // add knot item to map
}
else -> {
// do nothing
}
}
}
}
recyclerFavKnots.adapter = MyAdapter(context = this@FavouriteList,favoritesMap)
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(this@FavouriteList, "Data retrieval cancelled", Toast.LENGTH_SHORT).show()
}
})
}
fun closeWindow(view: View) {
finish()
}
} | 0 | Kotlin | 0 | 0 | 414878a5d663d6deb6ceb41086671f0e8c357eec | 2,677 | KnotTracker | MIT License |
test/src/me/anno/tests/utils/SpiderWalk.kt | AntonioNoack | 456,513,348 | false | null | package me.anno.tests.utils
import me.anno.Time
import me.anno.ecs.Component
import me.anno.ecs.Entity
import me.anno.ecs.components.light.DirectionalLight
import me.anno.ecs.components.light.sky.Skybox
import me.anno.ecs.components.mesh.Mesh
import me.anno.ecs.components.mesh.MeshComponent
import me.anno.ecs.components.mesh.material.Material
import me.anno.ecs.systems.OnUpdate
import me.anno.ecs.systems.Updatable
import me.anno.engine.OfficialExtensions
import me.anno.engine.raycast.RayQuery
import me.anno.engine.raycast.Raycast
import me.anno.engine.ui.control.DraggingControls
import me.anno.engine.ui.render.SceneView.Companion.testSceneWithUI
import me.anno.gpu.CullMode
import me.anno.input.Key
import me.anno.io.files.Reference.getReference
import me.anno.maths.Maths.clamp
import me.anno.maths.Maths.dtTo01
import me.anno.maths.Maths.length
import me.anno.maths.Maths.max
import me.anno.maths.Maths.mix
import me.anno.maths.Maths.sq
import me.anno.mesh.Shapes.flatCube
import me.anno.recast.NavMesh
import me.anno.recast.NavMeshAgent
import me.anno.utils.Color.black
import me.anno.utils.types.Booleans.hasFlag
import org.joml.Matrix4x3d
import org.joml.Vector3d
import org.joml.Vector3f
import org.joml.Vector4d
import org.recast4j.detour.DefaultQueryFilter
import org.recast4j.detour.NavMeshQuery
import org.recast4j.detour.crowd.Crowd
import org.recast4j.detour.crowd.CrowdConfig
import java.util.Random
import kotlin.math.PI
import kotlin.math.asin
import kotlin.math.atan2
import kotlin.math.min
/**
* eight-legged spider, which walks
* - terrain
* - path finding on it
* - legs using IK
* - find new targets in groups of 4 legs
* - move body with terrain
* */
fun main() {
OfficialExtensions.initForTests()
val scene = Entity("Scene")
val terrain = Entity("Terrain", scene)
terrain.add(MeshComponent(getReference("res://meshes/NavMesh.fbx")))
terrain.setScale(2.5)
val navMesh1 = NavMesh()
scene.add(navMesh1)
val sunE = Entity("Sun", scene).setScale(100.0)
val sun = DirectionalLight()
sun.shadowMapCascades = 1
sun.autoUpdate = 2
sun.color.set(2.5f, 1.7f, 1.3f)
sunE.add(sun)
val sky = Skybox()
sky.applyOntoSun(sunE, sun, 20f)
scene.add(sky)
navMesh1.cellSize = 2f
navMesh1.cellHeight = 5f
navMesh1.agentHeight = 1f
navMesh1.agentRadius = 1.5f
navMesh1.agentMaxClimb = 10f
navMesh1.collisionMask = 1
val meshData = navMesh1.build()!!
navMesh1.data = meshData
val navMesh = org.recast4j.detour.NavMesh(meshData, navMesh1.maxVerticesPerPoly, 0)
if (false) scene.add(MeshComponent(navMesh1.toMesh(Mesh())!!.apply {
makeLineMesh(true)
material = Material().apply {
cullMode = CullMode.BOTH
diffuseBase.set(0.2f, 1f, 0.2f, 0.5f)
}.ref
positions!!.apply {
for (i in indices step 3) {
this[i + 1] += 0.03f
}
}
}.ref)).apply {
collisionBits = 0
}
val query = NavMeshQuery(navMesh)
val filter = DefaultQueryFilter()
val config = CrowdConfig(navMesh1.agentRadius)
val crowd = Crowd(config, navMesh)
val baseY = 40.0
val spider = Entity("Spider", scene)
spider.setPosition(0.0, baseY, 0.0)
val xs = listOf(-1, +1)
val black1 = Material.diffuse(0x070707 or black)
val white = Material()
val gray = Material.diffuse(0x333333 or black)
val gray2 = Material.diffuse(0x171717 or black)
fun add(target: Entity, offset: Vector3f, scale: Vector3f, material: Material) {
target.add(MeshComponent(flatCube.linear(offset, scale).front, material))
}
add(spider, Vector3f(0f, 0.2f, -0.1f), Vector3f(1.0f, 0.6f, 1.5f), gray)
add(spider, Vector3f(0f, 0.2f, +2.8f), Vector3f(1.4f, 1.0f, 1.4f), gray)
for (x in xs) {
// teeth
add(spider, Vector3f(x * 0.4f, -0.4f, -1.68f), Vector3f(0.12f, 0.5f, 0.12f), white)
// eyes
add(spider, Vector3f(x * 0.3f, +0.6f, -1.68f), Vector3f(0.08f), black1)
}
val legDimensions = listOf(
Vector3f(1f, 0.20f, 0.20f),
Vector3f(1f, 0.18f, 0.18f),
Vector3f(1f, 0.16f, 0.16f),
Vector3f(0.4f, 0.12f, 0.12f),
)
// create 8 legs
val upperLegMesh = flatCube.linear(Vector3f(-0.9f, 0f, 0f), legDimensions[0]).front
val middleLegMesh = flatCube.linear(Vector3f(-0.9f, 0f, 0f), legDimensions[1]).front
val lowerLegMesh = flatCube.linear(Vector3f(-0.9f, 0f, 0f), legDimensions[2]).front
val footMesh = flatCube.linear(Vector3f(-0.3f, 0f, 0f), legDimensions[3]).front
fun calc(alpha: Double, delta: Vector3d, c: Double): Pair<Double, Double> {
val len = delta.length()
val gamma = 2.0 * asin(min(len / (2 * c), 1.0))
val a2 = alpha + PI / 2
val x1 = (PI - gamma) / 2
val z1 = atan2(delta.x, delta.y)
val beta = PI - x1 - z1 - a2
return beta to (PI - gamma)
}
// know the spider's transform in the future to plan steps
val stepFrequency = 3.0
val futureTransform = Matrix4x3d()
val predictionDeltaTime = 0.5 / stepFrequency
val agent = object : NavMeshAgent(
meshData, navMesh, query, filter, Random(1234),
navMesh1, crowd, 1, 10f, 300f
), Updatable {
val velocity = Vector3d(1.0, 0.0, 0.0)
val lastPos = Vector3d()
val angleDictator = Vector3d(0.0, 1.0, 0.0)
override fun update(instances: Collection<Component>) {
crowd.update(Time.deltaTime.toFloat(), null)
// move spider along path to target
// find proper position
val start = Vector3d(crowdAgent.currentPosition).add(0.0, 10.0, 0.0)
val query0 =
RayQuery(start, Vector3d(0.0, -1.0, 0.0), 40.0, Raycast.TRIANGLE_FRONT, -1, false, setOf(spider))
val hit = Raycast.raycastClosestHit(
scene, query0
)
spider.position = (if (hit) query0.result.positionWS else Vector3d(crowdAgent.currentPosition))
.add(0.0, 1.0, 0.0)
if (hit) {
val newAngle = query0.result.shadingNormalWS.normalize()
angleDictator.lerp(newAngle, dtTo01(5.0 * Time.deltaTime))
}
if (velocity.lengthSquared() < 1e-16) velocity.set(1.0, 0.0, 0.0)
if (angleDictator.lengthSquared() < 1e-16) angleDictator.set(0.0, 1.0, 0.0)
val rotY = -atan2(velocity.z, velocity.x) - PI / 2
val rotX = atan2(velocity.y, length(velocity.x, velocity.z))
val tmp = Vector3d(angleDictator).rotateY(-rotY)
val rotZ = -atan2(tmp.x, angleDictator.y)
val currPos = spider.position
if (lastPos.distanceSquared(currPos) > 1e-8) {
val velocity1 = Vector3d(currPos).sub(lastPos).div(Time.deltaTime)
velocity.lerp(Vector3d(velocity1), dtTo01(5.0 * Time.deltaTime))
lastPos.set(currPos)
}
spider.setRotation(rotX, rotY, rotZ)
futureTransform.identity()
.setTranslation(spider.position + velocity * predictionDeltaTime)
.rotateZ(rotZ)
.rotateX(rotX)
.rotateY(rotY)
}
}
spider.add(agent)
// animate body with legs
for (x in xs) {
for (z in 0 until 4) {
val zf = z - 1.5
val upperLeg = Entity(spider)
upperLeg.add(MeshComponent(upperLegMesh, gray2))
upperLeg.setPosition(x * 0.9, 0.0, zf * 0.5)
val middleLeg = Entity(upperLeg)
middleLeg.add(MeshComponent(middleLegMesh, gray2))
middleLeg.setPosition(-1.8, 0.0, 0.0)
val lowerLeg = Entity(middleLeg)
lowerLeg.add(MeshComponent(lowerLegMesh, gray2))
lowerLeg.setPosition(-1.8, 0.0, 0.0)
val foot = Entity(lowerLeg)
foot.add(MeshComponent(footMesh, black1))
foot.setPosition(-1.8, 0.0, 0.0)
class Leg : Component(), OnUpdate {
val zero = Vector3d(x * 3.0, -0.5, zf)
val target = Vector3d()
val lastTarget = Vector3d()
var timeAccu = if ((z + (x + 1) / 2).hasFlag(1)) 1.0 else 1.5
val angles = Vector4d()
var isWalking = false
override fun onUpdate() {
val step = Time.deltaTime * stepFrequency
timeAccu += step
if (timeAccu > 1.0) {
timeAccu -= 1.0
// find new target to step on
// use raycast to find floor's y
futureTransform.transformPosition(zero, target)
val up = 5.0
val len = 10.0
val query1 = RayQuery(
Vector3d(0.0, up, 0.0).add(target), Vector3d(0.0, -1.0, 0.0), len,
-1, -1, false, setOf(spider)
)
if (Raycast.raycastClosestHit(scene, query1)) {
val footThickness = legDimensions.last().y
target.y += up - query1.result.distance - footThickness
}
isWalking = lastTarget.distanceSquared(target) > 1e-2 * sq(step)
lastTarget.set(target)
}
val dtMix = dtTo01(5.0 * step)
// convert target into "spiderBody" space
val toLocal = spider.transform.globalTransform.invert(Matrix4x3d())
val localTarget = toLocal.transformPosition(target, Vector3d())
// add stepping up at the start of each step
if (isWalking) localTarget.y += max(1.0 - 10.0 * timeAccu, 0.0)
val upperLegPos = toLocal.transformPosition(upperLeg.transform.globalPosition, Vector3d())
val distance0 = length(upperLegPos.x - localTarget.x, upperLegPos.z - localTarget.z)
val distance = min(distance0 / (3 * 1.8), 1.0)
val downwards = (upperLegPos.y - localTarget.y) / distance0 * .5
val alpha = -clamp(
mix(
mix(1.57, -0.2, downwards), // close
mix(0.7, -0.5, downwards), // far away
distance
), -1.0, PI / 2
)
val rotY = -x * atan2(
upperLeg.position.z - localTarget.z,
-x * (upperLeg.position.x - localTarget.x)
)
val rotY1 = clamp(-rotY, -1.2, 1.2) + (if (x > 0) PI else 0.0)
angles.x = mix(angles.x, alpha, dtMix)
angles.y = mix(angles.y, rotY1, dtMix)
upperLeg.setRotation(0.0, angles.y, angles.x)
upperLeg.validateTransform()
middleLeg.validateTransform()
val middleLegPos = toLocal.transformPosition(middleLeg.transform.globalPosition, Vector3d())
val delta = Vector3d(middleLegPos).sub(localTarget).rotateY(rotY) // z-component is 0
delta.x *= -x
val (beta, gamma) = calc(alpha, delta, 1.8)
val beta1 = max(beta, 0.0)
val gamma1 = max(gamma, 0.0)
angles.z = mix(angles.z, beta1, dtMix)
angles.w = mix(angles.w, gamma1, dtMix)
middleLeg.setRotation(0.0, 0.0, angles.z)
lowerLeg.setRotation(0.0, 0.0, angles.w)
foot.setRotation(0.0, 0.0, -(angles.x + angles.z + angles.w))
}
}
upperLeg.add(Leg())
}
}
testSceneWithUI("Spider IK", scene) {
it.editControls = object : DraggingControls(it.renderView) {
override fun onMouseClicked(x: Float, y: Float, button: Key, long: Boolean) {
if (button == Key.BUTTON_LEFT) {
val ci = it.renderView
val query0 = RayQuery(
ci.cameraPosition, ci.getMouseRayDirection(), 1e3,
-1, -1, false, setOf(spider)
)
if (Raycast.raycastClosestHit(scene, query0)) {
val pt0 = Vector3f(query0.result.positionWS)
val poly = query.findNearestPoly(pt0, Vector3f(1e3f), filter).result
val pos = poly?.nearestPos
if (poly != null && pos != null) {
agent.crowdAgent.setTarget(poly.nearestRef, pos)
}
}
}
}
}
}
} | 0 | null | 3 | 24 | 013af4d92e0f89a83958008fbe1d1fdd9a10e992 | 12,997 | RemsEngine | Apache License 2.0 |
sdk/src/test/java/com/microsoft/did/sdk/util/Base64Test.kt | sbolotovms | 337,989,562 | true | {"Kotlin": 572132} | package com.microsoft.did.sdk.util
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class Base64Test {
/* @see https://tools.ietf.org/html/rfc4648#section-10
*/
private val base64TestPairs = listOf(
Pair("", ""),
Pair("f", "Zg=="),
Pair("fo", "Zm8="),
Pair("foo", "Zm9v"),
Pair("foob", "Zm9vYg=="),
Pair("fooba", "Zm9vYmE="),
Pair("foobar", "Zm9vYmFy")
)
private val base64UrlTestPairs = listOf(
Pair("", ""),
Pair("f", "Zg"),
Pair("fo", "Zm8"),
Pair("foo", "Zm9v"),
Pair("foob", "Zm9vYg"),
Pair("fooba", "Zm9vYmE"),
Pair("foobar", "Zm9vYmFy")
)
@Test
fun `rfc base64 encode vectors`() {
base64TestPairs.forEach {
val suppliedInput = it.first.map { character -> character.toByte() }.toByteArray()
val actualEncodedOutput = Base64.encode(suppliedInput)
val expectedEncodedOutput = it.second
assertThat(actualEncodedOutput).isEqualTo(expectedEncodedOutput)
}
}
@Test
fun `rfc base64 decode vectors`() {
base64TestPairs.forEach {
val expectedDecodedOutput = it.first.map { character -> character.toByte() }.toByteArray()
val suppliedInput = it.second
val actualDecodedOutput = Base64.decode(suppliedInput)
assertEqualsByteArray(expectedDecodedOutput, actualDecodedOutput)
}
}
@Test
fun `rfc base64url encode vectors`() {
base64UrlTestPairs.forEach {
val suppliedInput = it.first.map { character -> character.toByte() }.toByteArray()
val actualEncodedOutput = Base64Url.encode(suppliedInput)
val expectedEncodedOutput = it.second
assertThat(actualEncodedOutput).isEqualTo(expectedEncodedOutput)
}
}
@Test
fun `rfc base64url decode vectors`() {
base64UrlTestPairs.forEach {
val expectedDecodedOutput = it.first.map { character -> character.toByte() }.toByteArray()
val suppliedInput = it.second
val actualDecodedOutput = Base64Url.decode(suppliedInput)
assertEqualsByteArray(expectedDecodedOutput, actualDecodedOutput)
}
}
@Test
fun `twos compliment url`() {
val suppliedInput = ByteArray(3)
// CAFE41
// 1100 1010 1111 1110 0100 0001
// ^ ^ ^ ^
// 50 47 57 1
// y v 5 B
suppliedInput[0] = 0xCA.toByte()
suppliedInput[1] = 0xFE.toByte()
suppliedInput[2] = 0x41.toByte()
val expectedOutput = "yv5B"
val actualOutput = Base64Url.encode(suppliedInput)
assertThat(actualOutput).isEqualTo(expectedOutput)
val suppliedInputString = "1234"
// 1(53) 2(54) 3(55) 4(56)
// v v v v
// 11010111 01101101 11111000
// 215 109 248
val expectedOutputByteArray = ByteArray(3)
expectedOutputByteArray[0] = 0xD7.toByte()
expectedOutputByteArray[1] = 0x6D.toByte()
expectedOutputByteArray[2] = 0xF8.toByte()
val actualOutputByteArray = Base64Url.decode(suppliedInputString)
assertEqualsByteArray(expectedOutputByteArray, actualOutputByteArray)
}
private fun assertEqualsByteArray(expected: ByteArray, actual: ByteArray) {
assertThat(expected.size).isEqualTo(actual.size)
expected.forEachIndexed { index, byte ->
assertThat(byte).isEqualTo(actual[index])
}
}
} | 0 | null | 0 | 0 | b91adc0494fe3a7c8881f09e9fa90dd635aa3c05 | 3,621 | VerifiableCredential-SDK-Android | MIT License |
app/src/main/java/com/muratozturk/mova/ui/home/now_playing_movies/NowPlayingMoviesViewModel.kt | muratozturk5 | 587,507,400 | false | null | package com.hoangtien2k3.themoviedb.ui.home.now_playing_movies
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.hoangtien2k3.themoviedb.domain.model.MovieUI
import com.hoangtien2k3.themoviedb.domain.use_case.home.GetNowPlayingMoviesUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class NowPlayingMoviesViewModel @Inject constructor(private val getNowPlayingMoviesUseCase: GetNowPlayingMoviesUseCase) :
ViewModel() {
private val _nowPlayingMovies =
MutableStateFlow<PagingData<MovieUI>>(PagingData.empty())
val nowPlayingMovies
get() = _nowPlayingMovies.asStateFlow()
init {
getNowPlayingMovies()
}
private fun getNowPlayingMovies() = viewModelScope.launch {
getNowPlayingMoviesUseCase().cachedIn(viewModelScope).collectLatest {
_nowPlayingMovies.emit(it)
}
}
} | 1 | Kotlin | 13 | 96 | 280ced4d70d4e2f9e7c4549b5c919cc7cd821146 | 1,173 | Mova | MIT License |
features/currencyexchange/domain/src/commonMain/kotlin/com/mindera/kmpexample/currencyexchange/domain/datasource/remote/CurrencyExchangeRemoteSource.kt | Mindera | 767,105,015 | false | {"Kotlin": 89862, "Swift": 422} | package com.mindera.kmpexample.currencyexchange.domain.datasource.remote
import com.mindera.kmpexample.currencyexchange.domain.model.CurrencyExchangeResponseItem
interface CurrencyExchangeRemoteSource {
suspend fun getCurrencyExchange(endpoint: String): List<CurrencyExchangeResponseItem>
}
| 0 | Kotlin | 0 | 1 | 1c24d2aeade48da855424296ca036e6c1da1c1b3 | 299 | Android-KMP-Template | Apache License 2.0 |
features/currencyexchange/domain/src/commonMain/kotlin/com/mindera/kmpexample/currencyexchange/domain/datasource/remote/CurrencyExchangeRemoteSource.kt | Mindera | 767,105,015 | false | {"Kotlin": 89862, "Swift": 422} | package com.mindera.kmpexample.currencyexchange.domain.datasource.remote
import com.mindera.kmpexample.currencyexchange.domain.model.CurrencyExchangeResponseItem
interface CurrencyExchangeRemoteSource {
suspend fun getCurrencyExchange(endpoint: String): List<CurrencyExchangeResponseItem>
}
| 0 | Kotlin | 0 | 1 | 1c24d2aeade48da855424296ca036e6c1da1c1b3 | 299 | Android-KMP-Template | Apache License 2.0 |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/covidcertificate/validation/core/DccValidator.kt | corona-warn-app | 268,027,139 | false | null | package de.rki.coronawarnapp.covidcertificate.validation.core
import androidx.annotation.VisibleForTesting
import de.rki.coronawarnapp.covidcertificate.common.certificate.DccData
import de.rki.coronawarnapp.covidcertificate.common.certificate.DccJsonSchemaValidator
import de.rki.coronawarnapp.covidcertificate.common.certificate.DccV1
import de.rki.coronawarnapp.covidcertificate.signature.core.DscSignatureValidator
import de.rki.coronawarnapp.covidcertificate.validation.core.business.BusinessValidator
import de.rki.coronawarnapp.util.TimeStamper
import de.rki.coronawarnapp.util.toLocalDateTimeUtc
import timber.log.Timber
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.Date
import javax.inject.Inject
class DccValidator @Inject constructor(
private val businessValidator: BusinessValidator,
private val dccJsonSchemaValidator: DccJsonSchemaValidator,
private val dscSignatureValidator: DscSignatureValidator,
private val timeStamper: TimeStamper,
) {
/**
* Validates DCC against the rules of the country of arrival and issuer country
*/
suspend fun validateDcc(
userInput: ValidationUserInput,
certificate: DccData<out DccV1.MetaData>,
): DccValidation {
Timber.tag(TAG).v("validateDcc(country=%s)", userInput.arrivalCountry)
val signatureCheckPassed = isSignatureValid(
certificate,
Date.from(
userInput.arrivalDateTime.atZone(ZoneId.systemDefault()).toInstant()
)
)
val expirationCheckPassed = certificate.expiresAfter(userInput.arrivalDateTime)
val jsonSchemaCheckPassed = dccJsonSchemaValidator.isValid(certificate.certificateJson).isValid
val businessValidation = businessValidator.validate(
userInput.arrivalCountry,
userInput.arrivalDateTime,
certificate
)
return DccValidation(
userInput = userInput,
validatedAt = timeStamper.nowUTC,
signatureCheckPassed = signatureCheckPassed,
expirationCheckPassed = expirationCheckPassed,
jsonSchemaCheckPassed = jsonSchemaCheckPassed,
acceptanceRules = businessValidation.acceptanceRules,
invalidationRules = businessValidation.invalidationRules
)
}
private suspend fun isSignatureValid(dccData: DccData<out DccV1.MetaData>, date: Date): Boolean = try {
dscSignatureValidator.validateSignature(dccData, date = date)
true
} catch (e: Exception) {
Timber.tag(TAG).d(e)
false
}
companion object {
private const val TAG = "DccValidator"
}
}
@VisibleForTesting
internal fun DccData<*>.expiresAfter(referenceDate: LocalDateTime): Boolean {
return header.expiresAt.toLocalDateTimeUtc() > referenceDate
}
| 6 | null | 504 | 2,486 | 7b0eee8d53a090ee0ca585c6a90c4cec570e51d6 | 2,850 | cwa-app-android | Apache License 2.0 |
payments-core/src/test/java/com/stripe/android/model/MandateDataParamsTest.kt | stripe | 6,926,049 | false | null | package com.stripe.android.model
import kotlin.test.Test
import kotlin.test.assertEquals
class MandateDataParamsTest {
@Test
fun toParamMap_shouldCreateExpectedObject() {
val expectedParams = mapOf(
"customer_acceptance" to mapOf(
"type" to "online",
"online" to mapOf(
"ip_address" to "127.0.0.1",
"user_agent" to "my_user_agent"
)
)
)
assertEquals(
expectedParams,
MandateDataParamsFixtures.DEFAULT.toParamMap()
)
}
@Test
fun toParamMap_whenInferFromClient_shouldCreateExpectedObject() {
val actualParams = MandateDataParams(
MandateDataParams.Type.Online.DEFAULT
).toParamMap()
val expectedParams = mapOf(
"customer_acceptance" to mapOf(
"type" to "online",
"online" to mapOf(
"infer_from_client" to true
)
)
)
assertEquals(expectedParams, actualParams)
}
}
| 64 | Kotlin | 522 | 935 | bec4fc5f45b5401a98a310f7ebe5d383693936ea | 1,104 | stripe-android | MIT License |
chart_server/src/main/kotlin/io/madrona/njord/layers/Istzne.kt | manimaul | 213,533,249 | false | {"Kotlin": 271638, "TypeScript": 66411, "CSS": 23739, "Python": 8161, "PLpgSQL": 5036, "HTML": 3275, "Shell": 3043, "Dockerfile": 2008} | package io.madrona.njord.layers
import io.madrona.njord.model.*
/**
* Geometry Primitives: Area
*
* Object: Inshore traffic zone
*
* Acronym: ISTZNE
*
* Code: 68
*/
class Istzne : Layerable() {
private val lineColor = Color.TRFCD
override fun preTileEncode(feature: ChartFeature) {
feature.lineColor(lineColor)
}
override fun layers(options: LayerableOptions) = sequenceOf(
lineLayerWithColor(theme = options.theme, color = lineColor, style = LineStyle.DashLine, width = 1f),
)
}
| 17 | Kotlin | 3 | 8 | 7d9604d7b285601d64301e604a92f9d283f57c18 | 527 | njord | Apache License 2.0 |
compose-ide-plugin/src/com/android/tools/compose/debug/ComposePositionManagerFactory.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.compose.debug
import com.intellij.debugger.PositionManager
import com.intellij.debugger.PositionManagerFactory
import com.intellij.debugger.engine.DebugProcess
import org.jetbrains.kotlin.idea.debugger.KotlinPositionManager
class ComposePositionManagerFactory : PositionManagerFactory() {
override fun createPositionManager(process: DebugProcess): PositionManager {
return ComposePositionManager(process, KotlinPositionManager(process))
}
}
| 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 1,097 | android | Apache License 2.0 |
modules/data/src/main/kotlin/arc/data/source/local/db/DbService.kt | jimlyas | 530,131,916 | false | {"Kotlin": 70556} | package arc.data.source.local.db
/**
* [DbService] defines data source coming from local database
* @author jimlyas
* 0.1.0 0.1.0
*
* Copyright © 2022-2023 jimlyas. All rights reserved.
*/
interface DbService | 1 | Kotlin | 0 | 2 | dbe93edffddb44853a5120d757996486d542f8ab | 215 | arc | MIT License |
simplified-books-controller/src/main/java/org/nypl/simplified/books/controller/ProfileCreationTask.kt | jonathangreen | 292,624,474 | true | {"Gradle": 90, "Shell": 9, "INI": 88, "Text": 2, "Ignore List": 2, "Batchfile": 1, "Markdown": 90, "EditorConfig": 1, "YAML": 1, "XML": 329, "Kotlin": 620, "Java Properties": 1, "JSON": 46, "Java": 280, "CSS": 1, "HTML": 1, "JavaScript": 2} | package org.nypl.simplified.books.controller
import com.io7m.jfunctional.Option
import io.reactivex.subjects.Subject
import org.nypl.simplified.accounts.api.AccountProviderType
import org.nypl.simplified.profiles.api.ProfileCreationEvent
import org.nypl.simplified.profiles.api.ProfileCreationEvent.ProfileCreationFailed
import org.nypl.simplified.profiles.api.ProfileCreationEvent.ProfileCreationFailed.ErrorCode.ERROR_DISPLAY_NAME_ALREADY_USED
import org.nypl.simplified.profiles.api.ProfileCreationEvent.ProfileCreationFailed.ErrorCode.ERROR_GENERAL
import org.nypl.simplified.profiles.api.ProfileCreationEvent.ProfileCreationSucceeded
import org.nypl.simplified.profiles.api.ProfileDescription
import org.nypl.simplified.profiles.api.ProfileEvent
import org.nypl.simplified.profiles.api.ProfilesDatabaseType
import java.util.concurrent.Callable
class ProfileCreationTask(
private val profiles: ProfilesDatabaseType,
private val profileEvents: Subject<ProfileEvent>,
private val accountProvider: AccountProviderType,
private val description: ProfileDescription
) : Callable<ProfileCreationEvent> {
private fun execute(): ProfileCreationEvent {
val displayName = this.description.displayName
if (this.profiles.findProfileWithDisplayName(displayName).isSome) {
return ProfileCreationFailed.of(displayName, ERROR_DISPLAY_NAME_ALREADY_USED, Option.none())
}
return try {
val profile = this.profiles.createProfile(this.accountProvider, displayName)
profile.setDescription(this.description)
ProfileCreationSucceeded.of(displayName, profile.id)
} catch (e: Exception) {
ProfileCreationFailed.of(displayName, ERROR_GENERAL, Option.some(e))
}
}
@Throws(Exception::class)
override fun call(): ProfileCreationEvent {
val event = this.execute()
this.profileEvents.onNext(event)
return event
}
}
| 0 | Kotlin | 0 | 0 | d832b391188c86858158ef702f308c6b507ddb61 | 1,875 | Simplified-Android-Core | Apache License 2.0 |
app/src/androidTest/java/com/appttude/h_mal/atlas_weather/data/network/interceptors/MockingNetworkInterceptor.kt | hmalik144 | 163,556,459 | false | {"Kotlin": 275988, "Ruby": 3065} | package com.appttude.h_mal.atlas_weather.data.network.interceptors
import androidx.test.espresso.idling.CountingIdlingResource
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
class MockingNetworkInterceptor(
private val idlingResource: CountingIdlingResource
) : Interceptor {
private var feedMap: MutableMap<String, Pair<String, Int>> = mutableMapOf()
override fun intercept(chain: Interceptor.Chain): Response {
idlingResource.increment()
val original = chain.request()
val originalHttpUrl = original.url.toString()
feedMap[feedMap.keys.first { originalHttpUrl.contains(it) }]?.let { responsePair ->
val code = responsePair.second
val jsonBody = responsePair.first
val body = jsonBody.toResponseBody("application/json".toMediaType())
val chainResponseBuilder = Response.Builder()
.code(code)
.protocol(Protocol.HTTP_1_1)
.request(original)
.message("OK")
.body(body)
idlingResource.decrement()
return chainResponseBuilder.build()
}
idlingResource.decrement()
return chain.proceed(original)
}
fun addUrlStub(url: String, data: String, code: Int = 200) = feedMap.put(url, Pair(data, code))
fun removeUrlStub(url: String) = feedMap.remove(url)
} | 4 | Kotlin | 0 | 0 | a82ce7f8626bd20f66d080c4242ac2b871450d80 | 1,513 | Weather-apps | MIT License |
src/test/kotlin/unibz/cs/semint/kprime/domain/db/DatabaseToStringTest.kt | kprime-dev | 722,929,885 | false | {"Kotlin": 383495, "XSLT": 1078, "HTML": 372, "Makefile": 218} | package unibz.cs.semint.kprime.domain.db
import org.junit.Ignore
import org.junit.Test
import unibz.cs.semint.kprime.domain.dql.Mapping
import unibz.cs.semint.kprime.usecase.common.UnSQLizeSelectUseCase
import kotlin.test.assertEquals
class DatabaseToStringTest {
@Test
fun test_print_db_one_table() {
// given
val db = Database()
db.schema.addTable("person:name,surname")
// when
val result = db.toString()
//
assertEquals("""
Table(name='person', id='t1', view='', condition='', parent=null, columns=[name, surname], catalog=null, schema=null, source=null)
""".trimIndent(),result)
}
@Test
fun test_print_db_one_table_with_one_functional_dependenncy() {
// given
val db = Database()
db.schema.addTable("person:name,surname")
db.schema.addFunctional("person:name-->surname")
// when
val result = db.toString()
//R
assertEquals("""
Table(name='person', id='t1', view='', condition='', parent=null, columns=[name, surname], catalog=null, schema=null, source=null)
FUNCTIONAL person:name --> person:surname ;
""".trimIndent(),result)
}
@Test
@Ignore
fun test_print_db_one_table_one_mapping() {
// given
val db = Database()
db.schema.addTable("person:name,surname")
db.mappings = mutableListOf()
db.mappings.apply { this?.add( Mapping.fromQuery(
UnSQLizeSelectUseCase().fromsql("query2","""
SELECT *
FROM alias
""".trimIndent()))
)
}
// when
val result = db.toString()
// then
assertEquals("""
""".trimIndent(),result)
}
} | 0 | Kotlin | 0 | 0 | 34ceb56e3da8b2e64329c7655d50f40400487f25 | 1,807 | kprime-arm | MIT License |
python/src/com/jetbrains/python/statistics/PyPackageUsagesCollector.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.statistics
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.jetbrains.python.extensions.getSdk
import com.jetbrains.python.packaging.PyPIPackageCache
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.packaging.management.PythonPackageManager
import com.jetbrains.python.sdk.PythonSdkAdditionalData
import com.jetbrains.python.sdk.PythonSdkUtil
/**
* Reports usages of packages and versions
*/
internal class PyPackageVersionUsagesCollector : ProjectUsagesCollector() {
override fun getMetrics(project: Project) = getPackages(project) + getInstalledPackages(project)
override fun requiresReadAccess(): Boolean = true
override fun getGroup(): EventLogGroup = GROUP
private val GROUP = EventLogGroup("python.packages", 6)
//full list is stored in metadata, see FUS-1218 for more details
private val PYTHON_PACKAGE_INSTALLED = registerPythonSpecificEvent(GROUP,
"python_package_installed",
PACKAGE_FIELD,
PACKAGE_VERSION_FIELD)
private val PYTHON_PACKAGE_INSTALLED_IN_SDK = GROUP.registerVarargEvent("python_packages_installed_in_sdk",
EXECUTION_TYPE,
INTERPRETER_TYPE,
PACKAGE_FIELD,
PACKAGE_VERSION_FIELD)
private fun getPackages(project: Project): Set<MetricEvent> {
val result = HashSet<MetricEvent>()
val pypiPackages = PyPIPackageCache.getInstance()
for (module in project.modules) {
val sdk = module.getSdk() ?: continue
if (!PythonSdkUtil.isPythonSdk(sdk)) continue
val usageData = getPythonSpecificInfo(sdk)
PyPackageManager.getInstance(sdk).getRequirements(module).orEmpty()
.filter { pypiPackages.containsPackage(it.name) }
.forEach { req ->
ProgressManager.checkCanceled()
val version = req.versionSpecs.firstOrNull()?.version?.trim() ?: "unknown"
val data = ArrayList(usageData) // Not to calculate interpreter on each call
data.add(PACKAGE_FIELD.with(req.name))
data.add(PACKAGE_VERSION_FIELD.with(version))
result.add(PYTHON_PACKAGE_INSTALLED.metric(data))
}
}
return result
}
private fun getInstalledPackages(project: Project): Set<MetricEvent> {
val result = HashSet<MetricEvent>()
val pypiPackages = PyPIPackageCache.getInstance()
for (module in project.modules) {
val sdk = module.getSdk() ?: continue
if (!PythonSdkUtil.isPythonSdk(sdk)) continue
if (sdk.sdkAdditionalData !is PythonSdkAdditionalData) continue
val executionType = sdk.executionType
val interpreterType = sdk.interpreterType
PythonPackageManager.forSdk(project, sdk).installedPackages
.filter { pypiPackages.containsPackage(it.name) }
.forEach { pythonPackage ->
val version = pythonPackage.version
val data = buildList {
add(PACKAGE_FIELD.with(pythonPackage.name))
add(PACKAGE_VERSION_FIELD.with(version))
add(EXECUTION_TYPE.with(executionType.value))
add(INTERPRETER_TYPE.with(interpreterType.value))
}
result.add(PYTHON_PACKAGE_INSTALLED_IN_SDK.metric(data))
}
}
return result
}
}
val PACKAGE_FIELD = EventFields.StringValidatedByEnum("package", "python_packages")
val PACKAGE_VERSION_FIELD = EventFields.StringValidatedByRegexpReference("package_version", "version")
| 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 4,300 | intellij-community | Apache License 2.0 |
src/main/kotlin/no/nav/pensjon/opptjening/omsorgsopptjening/bestem/pensjonsopptjening/vilkarsvurdering/lover/FullOmsorgForBarnUnder6.kt | navikt | 593,529,397 | false | null | package no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.vilkarsvurdering.lover
import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.omsorgsarbeid.model.getAntallUtbetalingMoneder
import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.vilkarsvurdering.lover.grunnlag.GrunnlagOmsorgForBarnUnder6
import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.vilkarsvurdering.vilkar.Utfall
import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.vilkarsvurdering.vilkar.Vilkar
import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.vilkarsvurdering.vilkar.VilkarsInformasjon
/**
* For barn fra 1 til og med 5 år må omsorgsyter minst ha 6 måneder med omsorgsarbeid for barnet
*
* For barn som ikke har fylt ett år kreves ikke 6 måneder for å oppnå omsorgsopptjening
*
* Barn som ikke har fylt ett år og er født i desember vil ikke ha utbetalt barnetrygd og har ikke omsorgsarbeid for året.
* De har alikevel rett til full omsorgsopptjening det første året.
* Det betyr at vi må sjekke om omsorgsyter har fått barnetrygd i året etter for å vite om omsorgsyter har rett til omsorgsopptjening
*
*/
class FullOmsorgForBarnUnder6 : Vilkar<GrunnlagOmsorgForBarnUnder6>(
vilkarsInformasjon = VilkarsInformasjon(
beskrivelse = "Medlemmet har minst halve året hatt den daglige omsorgen for et barn",
begrunnesleForAvslag = "Medlemmet har ikke et halve år med daglig omsorgen for et barn",
begrunnelseForInnvilgelse = "Medlemmet har et halve år med daglig omsorgen for et barn",
),
utfallsFunksjon = `Minst 6 moneder omsorg for barn under 6 ar`,
) {
companion object {
private val `Minst 6 moneder omsorg for barn under 6 ar` = fun(grunnlag: GrunnlagOmsorgForBarnUnder6) =
grunnlag.run {
if(utfallPersonVilkarsvurdering == Utfall.AVSLAG){
Utfall.AVSLAG
}
else if (seksMonederOmsorg(ar = omsorgsAr) && alderMottaker(mellom = 0..5)) {
Utfall.INVILGET
} else if(fodtIOmsorgsAr(omsorgsAr, grunnlag.omsorgsmottaker.fodselsAr)) {
Utfall.INVILGET
}
else {
Utfall.AVSLAG
}
}
private fun fodtIOmsorgsAr(omsorgsAr: Int, fodselsAr: Int): Boolean =
omsorgsAr == fodselsAr
private fun GrunnlagOmsorgForBarnUnder6.mottakerDoedeI(ar: Int) =
omsorgsmottaker.doedsdato?.let { it.year == ar } ?: false
private fun GrunnlagOmsorgForBarnUnder6.seksMonederOmsorg(ar: Int) =
omsorgsArbeid100Prosent.getAntallUtbetalingMoneder(ar) >= 6
private fun GrunnlagOmsorgForBarnUnder6.enMonedOmsorg(ar: Int) =
omsorgsArbeid100Prosent.getAntallUtbetalingMoneder(ar) >= 1
private fun GrunnlagOmsorgForBarnUnder6.alderMottaker(mellom: IntRange) =
(omsorgsAr - omsorgsmottaker.fodselsAr) in mellom
}
}
| 0 | Kotlin | 0 | 0 | a2a81018aba974f996ca1486d1fc6a216530dadb | 3,063 | omsorgsopptjening-bestem-pensjonsopptjening | MIT License |
module_home/src/main/kotlin/com/crow/module_home/ui/viewmodel/HomeViewModel.kt | crowforkotlin | 610,636,509 | false | null | package com.crow.module_home.ui.viewmodel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.crow.base.app.app
import com.crow.base.ui.viewmodel.mvi.BaseMviViewModel
import com.crow.module_home.R
import com.crow.module_home.model.entity.HomeHeader
import com.crow.module_home.model.intent.HomeIntent
import com.crow.module_home.model.resp.homepage.Banner
import com.crow.module_home.model.resp.search.comic_reuslt.SearchComicResult
import com.crow.module_home.model.resp.search.novel_result.SearchNovelResult
import com.crow.module_home.model.source.ComicSearchDataSource
import com.crow.module_home.model.source.NovelSearchDataSource
import com.crow.module_home.network.HomeRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
/*************************
* @Machine: RedmiBook Pro 15 Win11
* @Path: module_home/src/main/kotlin/com/crow/module_home/view
* @Time: 2023/3/6 0:11
* @Author: CrowForKotlin
* @Description: HomeViewModel
* @formatter:on
**************************/
class HomeViewModel(private val repository: HomeRepository) : BaseMviViewModel<HomeIntent>() {
private val mNewHomeDatas: MutableList<Any> = mutableListOf()
private val mBanners: MutableList<Banner> = mutableListOf()
private var mRefreshStartIndex = 3
var mComicSearchFlowPage : Flow<PagingData<SearchComicResult>>? = null
var mNovelSearchFlowPage : Flow<PagingData<SearchNovelResult>>? = null
/**
* ● 获取主页Banner 快照
*
* ● 2023-09-17 01:06:15 周日 上午
*/
fun getSnapshotBanner() = mBanners.toMutableList()
/**
* ● 获取主页数据 快照
*
* ● 2023-09-17 01:06:32 周日 上午
*/
fun getSnapshotHomeData() = mNewHomeDatas.toMutableList()
/** ● 获取主页 (返回数据量很多)*/
private fun getHomePage(intent: HomeIntent.GetHomePage) {
flowResult(intent, repository.getHomePage()) { value ->
mBanners.clear()
mNewHomeDatas.clear()
mBanners.addAll(value.mResults.mBanners.filter { banner -> banner.mType <= 2 }.toMutableList())
mNewHomeDatas.add(HomeHeader(R.drawable.home_ic_recommed_24dp, app.getString(R.string.home_recommend_comic)))
mNewHomeDatas.addAll(value.mResults.mRecComicsResult.mResult.toMutableList())
mNewHomeDatas.add(Unit)
mNewHomeDatas.add(HomeHeader(R.drawable.home_ic_new_24dp, app.getString(R.string.home_hot_comic)))
mNewHomeDatas.addAll(value.mResults.mHotComics.toMutableList())
mNewHomeDatas.add(HomeHeader(R.drawable.home_ic_new_24dp, app.getString(R.string.home_new_comic)))
mNewHomeDatas.addAll(value.mResults.mNewComics.toMutableList())
mNewHomeDatas.add(HomeHeader(R.drawable.home_ic_finish_24dp, app.getString(R.string.home_commit_finish)))
mNewHomeDatas.addAll(value.mResults.mFinishComicDatas.mResult.toMutableList())
mNewHomeDatas.add(HomeHeader(R.drawable.home_ic_finish_24dp, app.getString(R.string.home_topic_comic)))
value.mResults.mTopics.mResult.forEach { mNewHomeDatas.add(it) }
intent.copy(homePageData = value)
}
}
// 通过刷新的方式 获取推荐
private fun getRecPageByRefresh(intent: HomeIntent.GetRecPageByRefresh) {
flowResult(intent, repository.getRecPageByRefresh(3, mRefreshStartIndex)) { value ->
mNewHomeDatas[1] = value.mResults.mResult[0]
mNewHomeDatas[2] = value.mResults.mResult[1]
mNewHomeDatas[3] = value.mResults.mResult[2]
mRefreshStartIndex += 3
intent.copy(recPageData = value)
}
}
private fun doSearchComic(intent: HomeIntent.SearchComic) {
mComicSearchFlowPage = Pager(
config = PagingConfig(
pageSize = 20,
initialLoadSize = 20,
enablePlaceholders = true,
),
pagingSourceFactory = {
ComicSearchDataSource { position, pagesize ->
flowResult(repository.doSearchComic(intent.keyword, intent.type, position, pagesize), intent) { value -> intent.copy(searchComicResp = value.mResults) }.mResults
}
}
).flow.flowOn(Dispatchers.IO).cachedIn(viewModelScope)
}
private fun doSearchNovel(intent: HomeIntent.SearchNovel) {
mNovelSearchFlowPage = Pager(
config = PagingConfig(
pageSize = 20,
initialLoadSize = 20,
enablePlaceholders = true,
),
pagingSourceFactory = {
NovelSearchDataSource { position, pagesize ->
flowResult(repository.doSearchNovel(intent.keyword, intent.type, position, pagesize), intent) { value -> intent.copy(searchNovelResp = value.mResults) }.mResults
}
}
).flow.flowOn(Dispatchers.IO).cachedIn(viewModelScope)
}
override fun dispatcher(intent: HomeIntent) {
when (intent) {
is HomeIntent.GetHomePage -> getHomePage(intent)
is HomeIntent.GetRecPageByRefresh -> getRecPageByRefresh(intent)
is HomeIntent.SearchComic -> doSearchComic(intent)
is HomeIntent.SearchNovel -> doSearchNovel(intent)
}
}
} | 8 | null | 5 | 335 | 76105c20001ec1f51b2801c5cb084e6d45b819af | 5,400 | CopyMangaX | Apache License 2.0 |
AnnZone-Android/app/src/main/java/cn/anline/annzone/bean/BlogDataItem.kt | jiankian | 120,399,839 | false | null | package cn.anline.annzone.bean
import com.google.gson.annotations.SerializedName
data class BlogDataItem(var summary: String = "",
var uid: Int = 0,
@SerializedName("update_time")
val updateTime: Long = 0,
@SerializedName("create_time")
var createTime: Long = 0,
@SerializedName("http_info")
val httpInfo: String = "",
val ip: String = "",
val id: Int = 0,
var title: String = "",
val ua: String = "",
val content: String = "",
val url: String = "") | 25 | null | 69 | 210 | 2e9246d0e83e6e6b7bb7bcbb74ca12f114e25a13 | 755 | AnnZone | MIT License |
kotlin-mui-icons/src/main/generated/mui/icons/material/AllInbox.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/AllInbox")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val AllInbox: SvgIconComponent
| 10 | Kotlin | 5 | 983 | 7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35 | 198 | kotlin-wrappers | Apache License 2.0 |
api/app/src/test/kotlin/packit/unit/model/PacketTest.kt | mrc-ide | 599,186,390 | false | {"Kotlin": 266103, "TypeScript": 240236, "Shell": 8735, "JavaScript": 2023, "CSS": 1626, "Dockerfile": 1112, "HTML": 904} | package packit.unit.model
import packit.model.Packet
import packit.model.toBasicDto
import packit.model.toDto
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class PacketTest
{
@Test
fun `toDto returns correct PacketDto for given Packet`()
{
val packet = Packet("id1", "name1", "displayName1", emptyMap(), true, 1.0, 2.0, 3.0)
val packetDto = packet.toDto()
assertEquals("id1", packetDto.id)
assertEquals("name1", packetDto.name)
assertEquals("displayName1", packetDto.displayName)
assertTrue(packetDto.parameters.isEmpty())
assertTrue(packetDto.published)
assertEquals(1.0, packetDto.importTime)
assertEquals(2.0, packetDto.startTime)
assertEquals(3.0, packetDto.endTime)
}
@Test
fun `toDto returns correct PacketDto for Packet with non-empty parameters`()
{
val parameters = mapOf("param1" to "value1")
val packet = Packet("id1", "name1", "displayName1", parameters, true, 1.0, 2.0, 3.0)
val packetDto = packet.toDto()
assertEquals(parameters, packetDto.parameters)
}
@Test
fun `toBasicDto returns correct BasicPacketDto for given Packet`()
{
val packet = Packet("id1", "name1", "displayName1", emptyMap(), true, 1.0, 2.0, 3.0)
val basicPacketDto = packet.toBasicDto()
assertEquals("id1", basicPacketDto.id)
assertEquals("name1", basicPacketDto.name)
}
}
| 4 | Kotlin | 0 | 0 | da475d0f85c3f886989caa42a18005974c8086b0 | 1,491 | packit | MIT License |
mylibrary1/src/main/java/me/hacket/mylibrary1/MyLib1InitTask.kt | hacket | 557,921,055 | false | null | package me.hacket.mylibrary1
import android.app.Application
import android.content.res.Configuration
import android.os.SystemClock
import me.hacket.appinit.annotation.AppInitTask
import me.hacket.appinit.api.AppInit
import me.hacket.appinit.api.IAppInitTask
import me.hacket.appinit.api.utils.Consts
@AppInitTask(
id = "myLib1",
background = true,
// process = [AppInitTask.PROCESS_NOT_MAIN],
priority = AppInitTask.PRIORITY_HIGH,
dependencies = []
)
class MyLib1InitTask : IAppInitTask {
override fun onCreate(application: Application) {
AppInit.logger().info(Consts.TAG, "myLib1 execute start, sleep 4000L.")
SystemClock.sleep(4000L)
AppInit.logger().info(Consts.TAG, "myLib1 execute end.")
}
override fun onConfigurationChanged(application: Application, newConfig: Configuration) {
super.onConfigurationChanged(application, newConfig)
AppInit.logger().debug(Consts.TAG, "myLib1 onConfigurationChanged:$newConfig")
}
} | 0 | Kotlin | 4 | 41 | 5ef8f147b4d1598e1486a5f19a7104e1b2a36b5d | 998 | AppInit | Apache License 2.0 |
codebase/android/core/alarmkitimpl/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/alarmkitimpl/AlarmReceiver.kt | Abhimanyu14 | 429,663,688 | false | null | package com.makeappssimple.abhimanyu.financemanager.android.core.alarmkitimpl
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.makeappssimple.abhimanyu.financemanager.android.core.logger.MyLogger
import com.makeappssimple.abhimanyu.financemanager.android.core.notificationkit.NotificationKit
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
public class AlarmReceiver : BroadcastReceiver() {
@Inject
public lateinit var myLogger: MyLogger
@Inject
public lateinit var notificationKit: NotificationKit
override fun onReceive(
context: Context,
intent: Intent?,
) {
myLogger.logInfo(
message = "Alarm received : ${System.currentTimeMillis()}",
)
notificationKit.scheduleNotification()
}
}
| 11 | null | 0 | 3 | 7e080a68bc038bd64d2d406b75a49e8f1ea2a791 | 876 | finance-manager | Apache License 2.0 |
src/main/kotlin/me/fzzyhmstrs/amethyst_imbuement/modifier/ModifierPredicates.kt | fzzyhmstrs | 461,338,617 | false | {"Kotlin": 1677469, "Java": 105566} | package me.fzzyhmstrs.amethyst_imbuement.modifier
import me.fzzyhmstrs.amethyst_core.registry.RegisterTag
import me.fzzyhmstrs.amethyst_core.scepter_util.SpellType
import me.fzzyhmstrs.amethyst_core.scepter_util.augments.AugmentHelper
import me.fzzyhmstrs.amethyst_core.scepter_util.augments.SlashAugment
import me.fzzyhmstrs.amethyst_core.scepter_util.augments.SummonEntityAugment
import me.fzzyhmstrs.fzzy_core.coding_util.FzzyPort
import net.minecraft.enchantment.Enchantment
import net.minecraft.registry.tag.TagKey
import net.minecraft.util.Identifier
import java.util.function.Predicate
object ModifierPredicates {
/*private val FIRE_AUGMENTS: TagKey<Enchantment> = TagKey.of(RegistryKeys.ENCHANTMENT, Identifier(AC.MOD_ID,"fire_augments"))
private val ICE_AUGMENTS: TagKey<Enchantment> = TagKey.of(RegistryKeys.ENCHANTMENT, Identifier(AC.MOD_ID,"ice_augments"))
private val LIGHTNING_AUGMENTS: TagKey<Enchantment> = TagKey.of(RegistryKeys.ENCHANTMENT, Identifier(AC.MOD_ID,"lightning_augments"))
private val ELEMENTAL_AUGMENTS: TagKey<Enchantment> = TagKey.of(RegistryKeys.ENCHANTMENT, Identifier(AC.MOD_ID,"elemental_augments"))
private val HEALER_AUGMENTS: TagKey<Enchantment> = TagKey.of(RegistryKeys.ENCHANTMENT, Identifier(AC.MOD_ID,"healer_augments"))
private val BUILDER_AUGMENTS: TagKey<Enchantment> = TagKey.of(RegistryKeys.ENCHANTMENT, Identifier(AC.MOD_ID,"builder_augments"))
private val TRAVELER_AUGMENTS: TagKey<Enchantment> = TagKey.of(RegistryKeys.ENCHANTMENT, Identifier(AC.MOD_ID,"traveler_augments"))
private val BOLT_AUGMENTS: TagKey<Enchantment> = TagKey.of(RegistryKeys.ENCHANTMENT, Identifier(AC.MOD_ID,"bolt_augments"))*/
val FURIOUS_PREDICATE = Predicate {id: Identifier -> AugmentHelper.getAugmentType(id.toString()) == SpellType.FURY}
val WITTY_PREDICATE = Predicate {id: Identifier -> AugmentHelper.getAugmentType(id.toString()) == SpellType.WIT}
val GRACEFUL_PREDICATE = Predicate {id: Identifier -> AugmentHelper.getAugmentType(id.toString()) == SpellType.GRACE}
val BLADE_PREDICATE = Predicate {id: Identifier -> FzzyPort.ENCHANTMENT.get(id) is SlashAugment}
val ICE_PREDICATE = Predicate {id: Identifier -> isInTag(id, RegisterTag.ICE_AUGMENTS)}
val ELEMENTAL_PREDICATE = Predicate {id: Identifier -> isInTag(id, RegisterTag.ELEMENTAL_AUGMENTS)}
val HEALERS_PREDICATE = Predicate {id: Identifier -> isInTag(id, RegisterTag.HEALER_AUGMENTS)}
val HEALERS_PACT_PREDICATE = Predicate {id: Identifier -> !isInTag(id, RegisterTag.HEALER_AUGMENTS)}
val DANGER_PACT_PREDICATE = Predicate {id: Identifier -> AugmentHelper.getAugmentType(id.toString()) != SpellType.FURY}
val FIRE_PREDICATE = Predicate {id: Identifier -> isInTag(id, RegisterTag.FIRE_AUGMENTS)}
val LIGHTNING_PREDICATE = Predicate {id: Identifier -> isInTag(id, RegisterTag.LIGHTNING_AUGMENTS)}
val SUMMONERS_PREDICATE = Predicate {id: Identifier -> FzzyPort.ENCHANTMENT.get(id) is SummonEntityAugment}
val BUILDERS_PREDICATE = Predicate {id: Identifier -> isInTag(id, RegisterTag.BUILDER_AUGMENTS)}
val TRAVELER_PREDICATE = Predicate {id: Identifier -> isInTag(id, RegisterTag.TRAVELER_AUGMENTS)}
val BOLT_PREDICATE = Predicate {id: Identifier -> isInTag(id, RegisterTag.BOLT_AUGMENTS)}
val SOUL_PREDICATE = Predicate {id: Identifier -> isInTag(id, RegisterTag.SOUL_AUGMENTS)}
private fun isInTag(id: Identifier,tag: TagKey<Enchantment>): Boolean{
val augment = FzzyPort.ENCHANTMENT.get(id)?:return false
return FzzyPort.ENCHANTMENT.registry().getEntry(augment).isIn(tag)
}
}
| 9 | Kotlin | 8 | 4 | 7e51e5528c9495d818a3ae1c586d7cb6d5f5ece0 | 3,599 | ai | MIT License |
python/src/com/jetbrains/python/configuration/UnsupportedPythonInterpreterConfigurable.kt | ingokegel | 72,937,917 | true | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.configuration
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.dsl.builder.panel
import org.jetbrains.annotations.ApiStatus
/**
* This configurable does not contain any information. It is used when Python interpreter's additional data is not recognized and, thus,
* cannot be properly edited.
*/
@ApiStatus.Internal
internal class UnsupportedPythonInterpreterConfigurable(sdk: Sdk) : BoundConfigurable(sdk.name) {
override fun createPanel(): DialogPanel = panel {}
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 739 | intellij-community | Apache License 2.0 |
src/main/java/ru/hollowhorizon/hc/client/models/internal/Transformation.kt | HollowHorizon | 450,852,365 | false | null | /*
* MIT License
*
* Copyright (c) 2024 HollowHorizon
*
* 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 ru.hollowhorizon.hc.client.models.gltf
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import org.joml.Matrix3f
import org.joml.Matrix4f
import org.joml.Quaternionf
import org.joml.Vector3f
import kotlin.math.abs
@Serializable
data class Transformation(
var translationX: Float,
var translationY: Float,
var translationZ: Float,
var rotationX: Float,
var rotationY: Float,
var rotationZ: Float,
var rotationW: Float,
var scaleX: Float,
var scaleY: Float,
var scaleZ: Float,
var hasTranslation: Boolean = true,
var hasRotation: Boolean = true,
var hasScale: Boolean = true,
var weights: List<Float> = ArrayList(),
@Transient
private val matrix: Matrix4f = Matrix4f(),
) {
val translation: Vector3f get() = Vector3f(translationX, translationY, translationZ)
val rotation: Quaternionf get() = Quaternionf(rotationX, rotationY, rotationZ, rotationW)
val scale: Vector3f get() = Vector3f(scaleX, scaleY, scaleZ)
fun add(transform: Transformation, simpleRot: Boolean = false) {
if (transform.hasTranslation) {
translationX += transform.translationX
translationY += transform.translationY
translationZ += transform.translationZ
}
if (transform.hasRotation) {
val res = rotation
if (!simpleRot) res.mulLeft(transform.rotation)
else res.mul(transform.rotation)
rotationX = res.x()
rotationY = res.y()
rotationZ = res.z()
rotationW = res.w()
}
if (transform.hasScale) {
scaleX *= transform.scaleX
scaleY *= transform.scaleY
scaleZ *= transform.scaleZ
}
if (transform.weights.isNotEmpty()) {
weights = transform.weights
}
hasTranslation = transform.hasTranslation
hasRotation = transform.hasRotation
hasScale = transform.hasScale
}
fun Quaternionf.mulLeft(q: Quaternionf) {
set(
q.w() * x() + q.x() * w() + q.y() * z() - q.z() * y(),
q.w() * y() - q.x() * z() + q.y() * w() + q.z() * x(),
q.w() * z() + q.x() * y() - q.y() * x() + q.z() * w(),
q.w() * w() - q.x() * x() - q.y() * y() - q.z() * z()
)
}
fun sub(transform: Transformation) {
if (transform.hasTranslation) {
translationX = transform.translationX - translationX
translationY = transform.translationY - translationY
translationZ = transform.translationZ - translationZ
}
if (transform.hasRotation) {
val res = transform.rotation
res.mul(rotation.invert())
rotationX = res.x()
rotationY = res.y()
rotationZ = res.z()
rotationW = res.w()
}
if (transform.hasScale) {
scaleX = transform.scaleX / scaleX
scaleY = transform.scaleY / scaleY
scaleZ = transform.scaleZ / scaleZ
}
if (transform.weights.isNotEmpty()) {
weights = transform.weights
}
hasTranslation = transform.hasTranslation
hasRotation = transform.hasRotation
hasScale = transform.hasScale
}
fun mul(factor: Float): Transformation {
translationX *= factor
translationY *= factor
translationZ *= factor
val q = Quaternionf(0f, 0f, 0f, 1f).lerp(rotation, factor)
rotationX = q?.x() ?: rotationX
rotationY = q?.y() ?: rotationY
rotationZ = q?.z() ?: rotationZ
rotationW = q?.w() ?: rotationW
scaleX = scaleX * factor + 1f * (1f - factor)
scaleY = scaleY * factor + 1f * (1f - factor)
scaleZ = scaleZ * factor + 1f * (1f - factor)
return this
}
fun setTranslation(array: Vector3f?) {
if (array == null) return
translationX = array.x()
translationY = array.y()
translationZ = array.z()
}
fun addRotation(array: Quaternionf) {
val res = rotation
//Рубрика: угадай сколько часов потребовалось, чтобы понять, что нужно использовать этот метод
res.mulLeft(array)
rotationX = res.x()
rotationY = res.y()
rotationZ = res.z()
rotationW = res.w()
}
fun addRotationRight(array: Quaternionf) {
val res = rotation
res.mul(array)
rotationX = res.x()
rotationY = res.y()
rotationZ = res.z()
rotationW = res.w()
}
fun setRotation(array: Quaternionf?) {
if (array == null) return
rotationX = array.x()
rotationY = array.y()
rotationZ = array.z()
rotationW = array.w()
}
fun setScale(array: Vector3f?) {
if (array == null) return
scaleX = array.x()
scaleY = array.y()
scaleZ = array.z()
}
fun set(transformation: Transformation) {
if (transformation.hasTranslation) {
translationX = transformation.translationX
translationY = transformation.translationY
translationZ = transformation.translationZ
}
if (transformation.hasRotation) {
rotationX = transformation.rotationX
rotationY = transformation.rotationY
rotationZ = transformation.rotationZ
rotationW = transformation.rotationW
}
if (transformation.hasScale) {
scaleX = transformation.scaleX
scaleY = transformation.scaleY
scaleZ = transformation.scaleZ
}
if (transformation.weights.isNotEmpty()) {
weights = transformation.weights
}
}
@JvmOverloads
constructor(
translation: Vector3f? = Vector3f(),
rotation: Quaternionf? = Quaternionf(0.0f, 0.0f, 0.0f, 1.0f),
scale: Vector3f? = Vector3f(1.0f, 1.0f, 1.0f),
matrix: Matrix4f = Matrix4f(),
weights: List<Float> = ArrayList(),
) : this(
translation?.x() ?: 0f, translation?.y() ?: 0f, translation?.z() ?: 0f,
rotation?.x() ?: 0f, rotation?.y() ?: 0f, rotation?.z() ?: 0f, rotation?.w() ?: 1f,
scale?.x() ?: 1f, scale?.y() ?: 1f, scale?.z() ?: 1f,
translation != null, rotation != null, scale != null,
weights, matrix
)
fun getMatrix(): Matrix4f {
return Matrix4f()
.translate(translation)
.rotate(rotation.normalize())
.scale(scale)
.mul(matrix)
}
fun getNormalMatrix(): Matrix3f {
return Matrix3f()
.rotate(rotation.normalize())
.scale(scale)
}
fun setLocal(node: GltfTree.Node, animPose: Transformation) = set(node.fromLocal(animPose))
override fun equals(other: Any?): Boolean {
if (other is Transformation) {
if (hasTranslation) {
if (translationX != other.translationX) return false
if (translationY != other.translationY) return false
if (translationZ != other.translationZ) return false
}
if (hasRotation) {
if (abs(rotationY - other.rotationY) > 0.1) return false
if (abs(rotationZ - other.rotationZ) > 0.1) return false
if (abs(rotationX - other.rotationX) > 0.1) return false
if (abs(rotationW - other.rotationW) > 0.1) return false
}
if (hasScale) {
if (scaleX != other.scaleX) return false
if (scaleY != other.scaleY) return false
if (scaleZ != other.scaleZ) return false
}
return true
} else return super.equals(other)
}
companion object {
fun lerp(first: Transformation?, second: Transformation?, step: Float): Transformation? {
if (first == null) return second?.mul(step)
if (second == null) return first.apply { mul(1f - step) }
val tF = if (first.hasTranslation) first.translation else null
val tS = if (second.hasTranslation) second.translation else null
val rF = if (first.hasRotation) first.rotation else null
val rS = if (second.hasRotation) second.rotation else null
val sF = if (first.hasScale) first.scale else null
val sS = if (second.hasScale) second.scale else null
return Transformation(
tF.lerp(tS, step),
rF.lerp(rS, step),
sF.lerp(sS, step)
)
}
}
}
private fun Vector3f?.lerp(other: Vector3f?, factor: Float): Vector3f? {
if (this == null) return other?.mul(factor)
if (other == null) return this.mul(1f - factor)
return this.lerp(other, factor)
}
private fun Quaternionf?.lerp(other: Quaternionf?, factor: Float): Quaternionf? {
return when {
this == null && other == null -> null
this == null -> Quaternionf().slerp(other, factor)
other == null -> Quaternionf().slerp(this, 1f - factor)
else -> Quaternionf(this).slerp(other, factor)
}
} | 1 | null | 4 | 20 | 7e0c4510a0e5d2d3540aff428871b7ecc642c898 | 10,307 | HollowCore | MIT License |
app/src/androidTest/kotlin/com/moonpi/swiftnotes/test/BaseRunner.kt | AlexHurray | 130,821,769 | false | {"Java Properties": 3, "Gradle": 3, "Shell": 2, "Markdown": 1, "Git Attributes": 1, "Batchfile": 2, "Text": 1, "Ignore List": 2, "XML": 30, "Proguard": 1, "Kotlin": 7, "Java": 9} | package com.moonpi.swiftnotes.test
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.support.test.InstrumentationRegistry
import android.support.test.InstrumentationRegistry.getInstrumentation
import android.support.test.espresso.matcher.ViewMatchers.assertThat
import android.support.test.uiautomator.By
import android.support.test.uiautomator.UiDevice
import android.support.test.uiautomator.Until
import android.util.Log
import org.hamcrest.CoreMatchers.notNullValue
import org.junit.Before
import org.junit.BeforeClass
import java.io.File
open class BaseRunner {
val mDevice: UiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
val TARGET_PACKAGE: String = InstrumentationRegistry.getTargetContext().getPackageName()
val WAIT_TIMEOUT: Long = 5000
val LAUNCH_TIMEOUT: Long = 5000
companion object {
@BeforeClass @JvmStatic
fun clear() {
val cache = getInstrumentation().getTargetContext().getCacheDir()
File(cache.getParent()).deleteRecursively()
File("sdcard/allure-results").deleteRecursively()
}
}
@Before
fun setUp(){
mDevice.pressHome()
val launcherPackage: String = getLauncherPackageName()
assertThat(launcherPackage, notNullValue())
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT)
val context: Context = InstrumentationRegistry.getContext()
val intent: Intent = context.getPackageManager().getLaunchIntentForPackage(TARGET_PACKAGE)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
context.startActivity(intent)
mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), LAUNCH_TIMEOUT)
//File("sdcard/allure-results").deleteRecursively()
}
private fun getLauncherPackageName(): String {
// Create launcher Intent
val intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_HOME)
// Use PackageManager to get the launcher package name
val pm = InstrumentationRegistry.getContext().packageManager
val resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)
return resolveInfo.activityInfo.packageName
}
}
| 1 | null | 1 | 1 | 04d1c8ab43baeffe9b02bad841849dfac8a1afde | 2,365 | Swiftnotes | Apache License 2.0 |
app/src/_test/java/com/lhwdev/selfTestMacro/MainPreview.kt | lhwdev | 289,257,684 | false | null | package com.lhwdev.selfTestMacro
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.tooling.preview.Preview
import com.lhwdev.selfTestMacro.api.*
import com.lhwdev.selfTestMacro.model.MainRepository
import com.lhwdev.selfTestMacro.model.MainRepositoryImpl
import com.lhwdev.selfTestMacro.model.Status
// TODO: this crashes
@Composable
fun PreviewStubState(statusBar: Boolean = false, content: @Composable () -> Unit) {
PreviewBase(statusBar = statusBar) {
val pref = remember {
val sharedPreferences = buildSharedPreference {}
val state = PreferenceState(PreferenceHolder(sharedPreferences))
state.apply {
isDebugEnabled = true
firstState = 1
val userA = DbUser(
id = 0,
user = User(name = "홍길동", userCode = "D01234567", token = User.Token("userA")),
instituteName = "어느고등학교",
instituteType = InstituteType.school,
userGroupId = 10
)
val userB = DbUser(
id = 1,
user = User(name = "김철수", userCode = "D01234568", token = User.Token("userB")),
instituteName = "어느고등학교",
instituteType = InstituteType.school,
userGroupId = 11
)
val userGroupA = DbUserGroup(
id = 10,
userIds = listOf(0),
usersIdentifier = UsersIdentifier(
mainUserName = "홍길동",
token = UsersIdToken("groupA"),
isStudent = true,
agreement = true
),
instituteType = InstituteType.school,
institute = InstituteInfo(
name = "어느고등학교",
code = "schoolA",
address = "서울시 대충 광화문 1번",
requestUrlBody = "https://stubhcs.example.org"
)
)
val userGroupB = DbUserGroup(
id = 11,
userIds = listOf(1),
usersIdentifier = UsersIdentifier(
mainUserName = "김철수",
token = UsersIdToken("groupB"),
isStudent = true,
agreement = true
),
instituteType = InstituteType.school,
institute = InstituteInfo(
name = "어느고등학교",
code = "schoolA",
address = "서울시 대충 광화문 1번",
requestUrlBody = "https://stubhcs.example.org"
)
)
val testGroupA = DbTestGroup(
target = DbTestTarget.Group(name = "그룹 1", userIds = listOf(0, 1)),
schedule = DbTestSchedule.None,
excludeWeekend = true
)
db.users = DbUsers(
users = mapOf(0 to userA, 1 to userB),
maxId = 1
)
db.userGroups = DbUserGroups(
groups = mapOf(
10 to userGroupA,
11 to userGroupB
),
maxId = 11
)
db.testGroups = DbTestGroups(
groups = listOf(testGroupA),
maxGroupGeneratedNameIndex = 1
)
}
state
}
CompositionLocalProvider(
LocalPreference provides pref
) {
content()
}
}
}
@Preview
@Composable
fun MainPreview(): Unit = PreviewStubState {
Main()
}
| 2 | null | 7 | 50 | 06ada78bb235a170f74c9a3f06dc9b5ea99e0a8d | 2,870 | covid-selftest-macro | Apache License 2.0 |
app/src/main/java/com/example/racetracker/ui/TimerManager.kt | BMukhtar | 721,394,131 | false | {"Kotlin": 25391} | package com.example.racetracker.ui
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
class TimerManager(private val scope: CoroutineScope) {
private var timerJob: Job? = null
private var startTime: Long = 0
private var duration: Long = 0
private val _timerState = MutableStateFlow(TimerState())
val timerState = _timerState.asStateFlow()
fun startTimer(startedAtMillis: Long, durationMillis: Long, currentTimeProvider: () -> Long ) {
startTime = startedAtMillis
duration = durationMillis
timerJob = scope.launch {
while (isActive) {
val currentTime = currentTimeProvider()
val timeLeft = startTime + duration - currentTime
if (timeLeft > 0) {
_timerState.value = TimerState(visible = true, timeMillis = timeLeft)
delay(1000)
} else {
_timerState.value = TimerState(visible = false, timeMillis = 0)
break
}
}
}
}
fun confirm() {
timerJob?.cancel()
_timerState.value = TimerState(visible = false, timeMillis = 0)
}
fun reject() {
_timerState.value = _timerState.value.copy(visible = false)
}
fun cancelReject() {
_timerState.value = _timerState.value.copy(visible = true)
}
fun reloadScreen(startedAtMillis: Long, durationMillis: Long) {
if (startedAtMillis != null) {
startTimer(startedAtMillis, durationMillis) {
System.currentTimeMillis()
}
} else {
_timerState.value = TimerState(visible = false, timeMillis = 0)
}
}
data class TimerState(val visible: Boolean = false, val timeMillis: Long = 0)
}
| 0 | Kotlin | 0 | 0 | aefebd7812f0fa2f2a1a96ab1347f0fcf1c6d022 | 1,864 | timermanager | Apache License 2.0 |
knear-sdk/src/main/java/com/knear/android/provider/ViewAccessKeyChangesAllRequestParams.kt | near | 514,329,257 | false | null | package com.knear.android.provider
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
class ViewAccessKeyChangesAllRequestParams (
@SerializedName("method")
private val method: String,
@SerializedName("params")
private val params: Any,
@SerializedName("id")
private val currentId: Int
){
@SerializedName("jsonrpc")
private var jsonRpc: String = "2.0"
override fun toString(): String {
val gsonBuilder = GsonBuilder()
val gson = gsonBuilder.create()
return gson.toJson(this)
}
}
| 5 | null | 3 | 20 | 42a2bbeed12257c310a96a4af1ffedda2ea719f1 | 580 | near-api-kotlin | MIT License |
increase-kotlin-core/src/main/kotlin/com/increase/api/models/IntrafiAccountEnrollmentCreateParams.kt | Increase | 614,596,742 | false | null | // File generated from our OpenAPI spec by Stainless.
package com.increase.api.models
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonAnySetter
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.increase.api.core.ExcludeMissing
import com.increase.api.core.JsonValue
import com.increase.api.core.NoAutoDetect
import com.increase.api.core.toUnmodifiable
import com.increase.api.models.*
import java.util.Objects
class IntrafiAccountEnrollmentCreateParams
constructor(
private val accountId: String,
private val emailAddress: String,
private val additionalQueryParams: Map<String, List<String>>,
private val additionalHeaders: Map<String, List<String>>,
private val additionalBodyProperties: Map<String, JsonValue>,
) {
fun accountId(): String = accountId
fun emailAddress(): String = emailAddress
@JvmSynthetic
internal fun getBody(): IntrafiAccountEnrollmentCreateBody {
return IntrafiAccountEnrollmentCreateBody(
accountId,
emailAddress,
additionalBodyProperties,
)
}
@JvmSynthetic internal fun getQueryParams(): Map<String, List<String>> = additionalQueryParams
@JvmSynthetic internal fun getHeaders(): Map<String, List<String>> = additionalHeaders
@JsonDeserialize(builder = IntrafiAccountEnrollmentCreateBody.Builder::class)
@NoAutoDetect
class IntrafiAccountEnrollmentCreateBody
internal constructor(
private val accountId: String?,
private val emailAddress: String?,
private val additionalProperties: Map<String, JsonValue>,
) {
/** The identifier for the account to be added to IntraFi. */
@JsonProperty("account_id") fun accountId(): String? = accountId
/** The contact email for the account owner, to be shared with IntraFi. */
@JsonProperty("email_address") fun emailAddress(): String? = emailAddress
@JsonAnyGetter
@ExcludeMissing
fun _additionalProperties(): Map<String, JsonValue> = additionalProperties
fun toBuilder() = Builder().from(this)
companion object {
@JvmStatic fun builder() = Builder()
}
class Builder {
private var accountId: String? = null
private var emailAddress: String? = null
private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(
intrafiAccountEnrollmentCreateBody: IntrafiAccountEnrollmentCreateBody
) = apply {
this.accountId = intrafiAccountEnrollmentCreateBody.accountId
this.emailAddress = intrafiAccountEnrollmentCreateBody.emailAddress
additionalProperties(intrafiAccountEnrollmentCreateBody.additionalProperties)
}
/** The identifier for the account to be added to IntraFi. */
@JsonProperty("account_id")
fun accountId(accountId: String) = apply { this.accountId = accountId }
/** The contact email for the account owner, to be shared with IntraFi. */
@JsonProperty("email_address")
fun emailAddress(emailAddress: String) = apply { this.emailAddress = emailAddress }
fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.clear()
this.additionalProperties.putAll(additionalProperties)
}
@JsonAnySetter
fun putAdditionalProperty(key: String, value: JsonValue) = apply {
this.additionalProperties.put(key, value)
}
fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.putAll(additionalProperties)
}
fun build(): IntrafiAccountEnrollmentCreateBody =
IntrafiAccountEnrollmentCreateBody(
checkNotNull(accountId) { "`accountId` is required but was not set" },
checkNotNull(emailAddress) { "`emailAddress` is required but was not set" },
additionalProperties.toUnmodifiable(),
)
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is IntrafiAccountEnrollmentCreateBody &&
this.accountId == other.accountId &&
this.emailAddress == other.emailAddress &&
this.additionalProperties == other.additionalProperties
}
private var hashCode: Int = 0
override fun hashCode(): Int {
if (hashCode == 0) {
hashCode =
Objects.hash(
accountId,
emailAddress,
additionalProperties,
)
}
return hashCode
}
override fun toString() =
"IntrafiAccountEnrollmentCreateBody{accountId=$accountId, emailAddress=$emailAddress, additionalProperties=$additionalProperties}"
}
fun _additionalQueryParams(): Map<String, List<String>> = additionalQueryParams
fun _additionalHeaders(): Map<String, List<String>> = additionalHeaders
fun _additionalBodyProperties(): Map<String, JsonValue> = additionalBodyProperties
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is IntrafiAccountEnrollmentCreateParams &&
this.accountId == other.accountId &&
this.emailAddress == other.emailAddress &&
this.additionalQueryParams == other.additionalQueryParams &&
this.additionalHeaders == other.additionalHeaders &&
this.additionalBodyProperties == other.additionalBodyProperties
}
override fun hashCode(): Int {
return Objects.hash(
accountId,
emailAddress,
additionalQueryParams,
additionalHeaders,
additionalBodyProperties,
)
}
override fun toString() =
"IntrafiAccountEnrollmentCreateParams{accountId=$accountId, emailAddress=$emailAddress, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}"
fun toBuilder() = Builder().from(this)
companion object {
@JvmStatic fun builder() = Builder()
}
@NoAutoDetect
class Builder {
private var accountId: String? = null
private var emailAddress: String? = null
private var additionalQueryParams: MutableMap<String, MutableList<String>> = mutableMapOf()
private var additionalHeaders: MutableMap<String, MutableList<String>> = mutableMapOf()
private var additionalBodyProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(
intrafiAccountEnrollmentCreateParams: IntrafiAccountEnrollmentCreateParams
) = apply {
this.accountId = intrafiAccountEnrollmentCreateParams.accountId
this.emailAddress = intrafiAccountEnrollmentCreateParams.emailAddress
additionalQueryParams(intrafiAccountEnrollmentCreateParams.additionalQueryParams)
additionalHeaders(intrafiAccountEnrollmentCreateParams.additionalHeaders)
additionalBodyProperties(intrafiAccountEnrollmentCreateParams.additionalBodyProperties)
}
/** The identifier for the account to be added to IntraFi. */
fun accountId(accountId: String) = apply { this.accountId = accountId }
/** The contact email for the account owner, to be shared with IntraFi. */
fun emailAddress(emailAddress: String) = apply { this.emailAddress = emailAddress }
fun additionalQueryParams(additionalQueryParams: Map<String, List<String>>) = apply {
this.additionalQueryParams.clear()
putAllQueryParams(additionalQueryParams)
}
fun putQueryParam(name: String, value: String) = apply {
this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value)
}
fun putQueryParams(name: String, values: Iterable<String>) = apply {
this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values)
}
fun putAllQueryParams(additionalQueryParams: Map<String, Iterable<String>>) = apply {
additionalQueryParams.forEach(this::putQueryParams)
}
fun removeQueryParam(name: String) = apply {
this.additionalQueryParams.put(name, mutableListOf())
}
fun additionalHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply {
this.additionalHeaders.clear()
putAllHeaders(additionalHeaders)
}
fun putHeader(name: String, value: String) = apply {
this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value)
}
fun putHeaders(name: String, values: Iterable<String>) = apply {
this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values)
}
fun putAllHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply {
additionalHeaders.forEach(this::putHeaders)
}
fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) }
fun additionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply {
this.additionalBodyProperties.clear()
this.additionalBodyProperties.putAll(additionalBodyProperties)
}
fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply {
this.additionalBodyProperties.put(key, value)
}
fun putAllAdditionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) =
apply {
this.additionalBodyProperties.putAll(additionalBodyProperties)
}
fun build(): IntrafiAccountEnrollmentCreateParams =
IntrafiAccountEnrollmentCreateParams(
checkNotNull(accountId) { "`accountId` is required but was not set" },
checkNotNull(emailAddress) { "`emailAddress` is required but was not set" },
additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(),
additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(),
additionalBodyProperties.toUnmodifiable(),
)
}
}
| 1 | null | 0 | 5 | dc1361d08cb41ff45817c2e7638f53356f15cf8e | 10,787 | increase-kotlin | Apache License 2.0 |
ObjectOrientedParadigm/Exercise-1/Rectangle.kt | Johanx22x | 674,064,501 | false | {"Kotlin": 19851, "Go": 18444, "F#": 13580, "Prolog": 4760, "Rust": 4512, "Makefile": 822} | class Rectangle(width: Int, height: Int, center: Point) : DrawableObject {
private var width: Int = width
get() = field
set(value) { field = value }
private var height: Int = height
get() = field
set(value) { field = value }
private var center: Point = center
get() = field
set(value) { field = value }
override fun draw(): String {
return "Rectangle(width=$width, height=$height, center=" + center.draw() + ")"
}
}
| 0 | Kotlin | 0 | 1 | 17ef99cfb4e12803a15615f235bfd3d0961ec373 | 493 | ProgrammingLanguages | MIT License |
year2019/src/main/kotlin/net/olegg/aoc/year2019/day23/Day23.kt | 0legg | 110,665,187 | false | null | package net.olegg.aoc.year2019.day23
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.parseLongs
import net.olegg.aoc.year2019.DayOf2019
import net.olegg.aoc.year2019.Intcode
/**
* See [Year 2019, Day 23](https://adventofcode.com/2019/day/23)
*/
object Day23 : DayOf2019(23) {
override fun first(): Any? {
val program = data
.parseLongs(",")
.toLongArray()
return runBlocking {
val inputs = List(50) { Channel<Long>(Channel.UNLIMITED) }
val outputs = List(50) { Channel<Long>(Channel.UNLIMITED) }
repeat(50) {
inputs[it].send(it.toLong())
launch(Dispatchers.Default) {
val intcode = Intcode(program.copyOf())
intcode.eval(inputs[it], outputs[it])
}
}
while (true) {
outputs.forEach { output ->
output.tryReceive().getOrNull()?.let { dst ->
val x = output.receive()
val y = output.receive()
if (dst == 255L) {
return@runBlocking y
} else {
inputs[dst.toInt()].send(x)
inputs[dst.toInt()].send(y)
}
}
}
inputs
.filter { it.isEmpty }
.forEach { it.send(-1L) }
}
}
}
override fun second(): Any? {
val program = data
.parseLongs(",")
.toLongArray()
return runBlocking {
val inputs = List(50) { Channel<Long>(Channel.UNLIMITED) }
val outputs = List(50) { Channel<Long>(Channel.UNLIMITED) }
val nat = Channel<Long>(Channel.UNLIMITED)
repeat(50) {
inputs[it].send(it.toLong())
launch(Dispatchers.Default) {
val intcode = Intcode(program.copyOf())
intcode.eval(inputs[it], outputs[it])
}
}
val natYs = mutableListOf<Long>()
while (true) {
outputs.forEach { output ->
output.tryReceive().getOrNull()?.let { dst ->
val x = output.receive()
val y = output.receive()
if (dst == 255L) {
nat.send(x)
nat.send(y)
} else {
inputs[dst.toInt()].send(x)
inputs[dst.toInt()].send(y)
}
}
}
val empty = inputs.count { it.isEmpty }
if (empty == 50) {
val natValues = generateSequence { nat.tryReceive().getOrNull() }.toList()
if (natValues.isNotEmpty()) {
val (x, y) = natValues.takeLast(2)
inputs[0].send(x)
inputs[0].send(y)
if (natYs.isNotEmpty() && natYs.last() == y) {
return@runBlocking y
} else {
natYs += y
}
} else {
inputs
.filter { it.isEmpty }
.forEach { it.send(-1L) }
}
} else {
inputs
.filter { it.isEmpty }
.forEach { it.send(-1L) }
}
}
}
}
}
fun main() = SomeDay.mainify(Day23)
| 0 | null | 1 | 8 | 3006775fc2d1da3b12303029b9f35d2793c912df | 3,148 | adventofcode | MIT License |
src/test/kotlin/org/wit/lucre/models/VaultModelTest.kt | kingsleyzissou | 306,965,292 | false | null | package org.wit.lucre.models
import com.aventrix.jnanoid.jnanoid.NanoIdUtils
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class VaultModelTest {
private val id: String = NanoIdUtils.randomNanoId()
private lateinit var vault: Vault
private final val EXPECTED_ID: String = id
private final val EXPECTED_NAME: String = "HSBC"
private final val EXPECTED_DESCRIPTION: String = "GBP Account"
private final val EXPECTED_CURRENCY: String = "£"
@BeforeEach
internal fun setup() {
vault = Vault(
"HSBC",
"GBP Account",
"£",
id
)
}
@Test
fun getName() {
assertEquals(EXPECTED_NAME, vault.name)
}
@Test
fun setName() {
val newName = "AIB"
vault.name = newName
assertEquals(newName, vault.name)
}
@Test
fun getDescription() {
assertEquals(EXPECTED_DESCRIPTION, vault.description)
}
@Test
fun setDescription() {
val newDescription = "Euro account"
vault.description = newDescription
assertEquals(newDescription, vault.description)
}
@Test
fun getCurrency() {
assertEquals(EXPECTED_CURRENCY, vault.currency)
}
@Test
fun setCurrency() {
val newCurrency = "€"
vault.currency = newCurrency
assertEquals(newCurrency, vault.currency)
}
@Test
fun getId() {
assertEquals(EXPECTED_ID, vault.id)
}
@Test
fun setId() {
val newId = NanoIdUtils.randomNanoId()
vault.id = newId
assertEquals(newId, vault.id)
}
}
| 0 | Kotlin | 0 | 0 | e6026e326a26a319fa82c3248f3d8bf89a4073fe | 1,713 | lucre-desktop | Apache License 2.0 |
core/src/nativeMain/kotlin/pw/binom/charset/Charsets.kt | caffeine-mgn | 182,165,415 | false | {"C": 13079003, "Kotlin": 1913743, "C++": 200, "Shell": 88} | package pw.binom.charset
actual object Charsets {
actual fun get(name: String): Charset = IconvCharset(name)
actual val UTF8: Charset
get() = get("utf-8")
} | 7 | C | 2 | 59 | 580ff27a233a1384273ef15ea6c63028dc41dc01 | 174 | pw.binom.io | Apache License 2.0 |
shared/src/commonTest/kotlin/io/github/jelinekma/pragueopendatakotlinlib/v2/TestSortedWasteStationsClient.kt | martinjelinek | 763,563,087 | false | {"Kotlin": 230955} | package cz.vse.jelinekma.pragueopendatakotlinlib.v2
import cz.vse.golemiokotlinlib.v2.client.WasteCollectionClient
import cz.vse.golemiokotlinlib.common.entity.responsedata.WasteStationAccessibility
import cz.vse.jelinekma.pragueopendatakotlinlib.TestClient
import cz.vse.jelinekma.pragueopendatakotlinlib.dummyData.ApiKeyLocal
import kotlinx.coroutines.test.runTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertTrue
class TestSortedWasteStationsClient : TestClient() {
private lateinit var client: WasteCollectionClient
private val id = "1"
private val ksnkoId = "15288"
@BeforeTest
fun setUp() {
client = WasteCollectionClient(ApiKeyLocal.API_KEY)
}
@Test
fun testAllWasteStations() = runTest {
val data = client.getSortedWasteStations(
latlng,
null,
null,
WasteStationAccessibility.ACCESSIBLE,
limit,
null,
false,
id,
ksnkoId
)
assertTrue { data.isNotEmpty() }
}
@Test
fun testGetSortedWasteStationsPickDays() = runTest {
val testData = client.getSortedWasteStationsPickDays(
ksnkoId,
ksnkoId
)
assertTrue { testData.isNotEmpty() }
}
} | 0 | Kotlin | 0 | 2 | b49495579ed1de62068fcccd8393357f2b386701 | 1,315 | golemiokotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/Nqueens.kt | ashtanko | 203,993,092 | false | null | /*
* Copyright 2020 Oleksii Shtanko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens
* attack each other.
* Given an integer n, return all distinct solutions to the n-queens puzzle.
* Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a
* queen and an empty space respectively.
*/
fun Int.solveNQueens(): List<List<String>> {
val chess = Array(this) { CharArray(this) }
for (i in 0 until this) {
for (j in 0 until this) {
chess[i][j] = '.'
}
}
val res: MutableList<List<String>> = ArrayList()
solve(res, chess, 0)
return res
}
@Throws(IllegalStateException::class)
fun Array<out Pair<Int, Char>>.assertLocations(size: Int, abc: CharArray) {
if (this.isEmpty()) return
if (!this.map { it.first }.none { it > size }) {
throw IllegalStateException("Column cannot be more that $size x $size board")
}
if (this.map { it.second }.none { abc.contains(it) }) {
throw IllegalStateException(
"Wrong row - should be one of this: ${abc.toList().joinToString()}",
)
}
}
private const val BOARD_MAX_SIZE = 8
/**
* Max 8x8.
*/
fun Int.genBoard(vararg locations: Pair<Int, Char>): String {
if (this > BOARD_MAX_SIZE) throw IllegalStateException("Board size cannot be more than 8x8")
val abc = charArrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
val empty = "|_|"
val filled = "|#|"
val unique = locations.toSet().toTypedArray()
unique.assertLocations(this, abc)
val trueLocations = unique.map {
it.first - 1 to abc.indexOf(it.second.lowercaseChar())
}
val board = Array(this) { IntArray(this) { 0 } }
for (loc in trueLocations) {
board.reversedArray()[loc.first][loc.second] = 1
}
val sb = StringBuilder()
for (i in board.reversedArray().indices) {
sb.append("${this - i} ")
for (b in board[i]) {
if (b == 0) sb.append(empty) else sb.append(filled)
}
sb.append("\n")
}
for (j in 0 until this) {
sb.append(" ${abc[j]}")
}
sb.append("\n")
return sb.toString()
}
private fun solve(
res: MutableList<List<String>>,
chess: Array<CharArray>,
row: Int,
) {
if (row == chess.size) {
res.add(construct(chess))
return
}
for (col in chess.indices) {
if (valid(chess, row, col)) {
chess[row][col] = 'Q'
solve(res, chess, row + 1)
chess[row][col] = '.'
}
}
}
private fun valid(chess: Array<CharArray>, row: Int, col: Int): Boolean {
for (i in 0 until row) {
if (chess[i][col] == 'Q') {
return false
}
}
run {
var i = row - 1
var j = col + 1
while (i >= 0 && j < chess.size) {
if (chess[i][j] == 'Q') {
return false
}
i--
j++
}
}
var i = row - 1
var j = col - 1
while (i >= 0 && j >= 0) {
if (chess[i][j] == 'Q') {
return false
}
i--
j--
}
return true
}
private fun construct(chess: Array<CharArray>): List<String> {
val path: MutableList<String> = ArrayList()
for (chars in chess) {
path.add(String(chars))
}
return path
}
| 6 | null | 0 | 19 | c6e2befdce892e9f2caf1d98f54dc1dd9b2c89ba | 4,011 | kotlab | Apache License 2.0 |
src/main/kotlin/com/ragin/bdd/cucumber/matcher/ValidDateContextMatcher.kt | Ragin-LundF | 278,038,006 | false | {"Kotlin": 107188, "Gherkin": 75853, "Java": 43890} | package com.ragin.bdd.cucumber.matcher
import com.ragin.bdd.cucumber.core.ScenarioStateContext
import com.ragin.bdd.cucumber.datetimeformat.BddCucumberDateTimeFormat
import com.ragin.bdd.cucumber.utils.DateUtils
import net.javacrumbs.jsonunit.core.ParametrizedMatcher
import org.hamcrest.BaseMatcher
import org.hamcrest.Description
import org.springframework.stereotype.Component
import java.time.format.DateTimeFormatter
@Component
class ValidDateContextMatcher(private val dateTimeFormatCollection: Collection<BddCucumberDateTimeFormat>) : BaseMatcher<Any>(), ParametrizedMatcher {
private var parameter: String? = null
override fun matches(actual: Any): Boolean {
val parameterFromContext = ScenarioStateContext.scenarioContextMap[parameter]
val jsonDate = DateUtils.transformToLocalDateTime(actual, dateTimeFormatCollection);
if (jsonDate != null) {
return jsonDate.toLocalDate().format(DateTimeFormatter.ISO_LOCAL_DATE).equals(parameterFromContext)
}
return false
}
override fun describeTo(description: Description) {
description.appendText("The actual date is not equal to the parameter [$parameter]")
}
override fun describeMismatch(item: Any, description: Description) {
description
.appendText("BDD Context value was [")
.appendValue(ScenarioStateContext.scenarioContextMap[parameter])
.appendText("].")
.appendText(" JSON Value was [")
.appendValue(item)
.appendText("].")
}
override fun setParameter(parameter: String) {
this.parameter = parameter
}
} | 2 | Kotlin | 2 | 6 | e1c0f516bdb50e31bdbeaed00cc9f7a5f121f77f | 1,676 | bbd-cucumber-gherkin-lib | MIT License |
bot/src/main/kotlin/bot/utils/DataRetriever.kt | tedsiebear | 271,154,042 | true | {"Kotlin": 55369, "SQLPL": 848} | package bot.utils
import com.github.scribejava.apis.YahooApi20
import com.github.scribejava.core.builder.ServiceBuilder
import com.github.scribejava.core.model.OAuth2AccessToken
import com.github.scribejava.core.model.OAuthConstants
import com.github.scribejava.core.model.OAuthRequest
import com.github.scribejava.core.model.Verb
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.parser.Parser
import shared.EnvVariables
import shared.Postgres
object DataRetriever {
private const val SCOREBOARD = "/scoreboard"
private const val STANDINGS = "/standings"
private const val TRANSACTIONS = "/transactions"
private val BASE_URL =
"https://fantasysports.yahooapis.com/fantasy/v2/league/${EnvVariables.YahooGameKey.variable}.l.${EnvVariables.YahooLeagueId.variable}"
private val oauthService = ServiceBuilder(EnvVariables.YahooClientId.variable)
.apiSecret(EnvVariables.YahooClientSecret.variable)
.callback(OAuthConstants.OOB)
.build(YahooApi20.instance())
private var currentToken: Pair<Long, OAuth2AccessToken>? = null
/**
* Checks to see whether or not a token is expired.
*
* @param retrieved when the token was initially retrieved
* @param expiresIn when the token expires
* @return if the token is expired
*/
private fun isTokenExpired(retrieved: Long, expiresIn: Int): Boolean {
val timeElapsed = ((System.currentTimeMillis() - retrieved) / 1000)
return timeElapsed >= expiresIn
}
/**
* Refreshes an expired token.
*/
private fun refreshExpiredToken() {
currentToken?.let {
if (isTokenExpired(it.first, it.second.expiresIn)) {
val refreshToken = oauthService.refreshAccessToken(it.second.refreshToken)
currentToken = Pair(System.currentTimeMillis(), refreshToken)
Postgres.saveTokenData(refreshToken)
}
}
}
fun authenticate() {
while (true) {
currentToken = Postgres.latestTokenData
if (currentToken == null) { // This will run only if there is no data in the database
println("There is currently no token data in the database. Please authenticate with Yahoo.")
} else {
return
}
Thread.sleep(5000)
}
}
private fun grabData(url: String): Document {
refreshExpiredToken()
println("Grabbing Data...")
val request = OAuthRequest(Verb.GET, url)
oauthService.signRequest(currentToken?.second, request)
val response = oauthService.execute(request)
println("Data grabbed.")
return Jsoup.parse(response.body, "", Parser.xmlParser())
}
fun getTransactions(): Document {
return grabData(BASE_URL + TRANSACTIONS)
}
fun getStandings(): Document {
return grabData(BASE_URL + STANDINGS)
}
fun getTeamsData(): Document {
return grabData(BASE_URL + SCOREBOARD)
}
}
| 0 | Kotlin | 0 | 0 | c46ddd1647db27953058583c7b430b847877d169 | 3,041 | yahoo-fantasy-bot | MIT License |
core/src/main/java/contacts/core/entities/custom/AbstractCustomDataOperation.kt | vestrel00 | 223,332,584 | false | {"Kotlin": 1616347, "Shell": 635} | package contacts.core.entities.custom
import contacts.core.AbstractCustomDataField
import contacts.core.entities.CustomDataEntity
import contacts.core.entities.MimeType
import contacts.core.entities.operation.AbstractDataOperation
/**
* Base type of all custom [AbstractDataOperation]s.
*/
abstract class AbstractCustomDataOperation
<F : AbstractCustomDataField, E : CustomDataEntity>(
callerIsSyncAdapter: Boolean,
isProfile: Boolean,
includeFields: Set<F>?
) : AbstractDataOperation<F, E>(
callerIsSyncAdapter = callerIsSyncAdapter,
isProfile = isProfile,
includeFields = includeFields
) {
// Override this to cast type from MimeType to MimeType.Custom
abstract override val mimeType: MimeType.Custom
/**
* Sets the custom [data] values into the operation via the provided [setValue] function.
*/
protected abstract fun setCustomData(
data: E, setValue: (field: F, value: Any?) -> Unit
)
/*
* Invokes the abstract setCustomData function, which uses the type of
* AbstractCustomDataField in the setValue function instead of DataField. This
* enforces consumers to use their custom data field instead of API fields.
*/
final override fun setValuesFromData(data: E, setValue: (field: F, value: Any?) -> Unit) {
setCustomData(data, setValue)
}
/**
* Creates instances of [AbstractCustomDataOperation].
*/
interface Factory<F : AbstractCustomDataField, E : CustomDataEntity> {
/**
* Creates instances of [AbstractCustomDataOperation].
*
* ## Include fields
*
* Insert and update operations will do nothing (no-op) for data whose corresponding field
* is not specified in [includeFields]. If [includeFields] is...
*
* - null, then the included field checks are disabled. This means that any non-blank data
* will be processed. This is a more optimal, recommended way of including all fields.
* - not null but empty, then data will be skipped (no-op).
*/
fun create(
callerIsSyncAdapter: Boolean,
isProfile: Boolean,
includeFields: Set<F>?
): AbstractCustomDataOperation<F, E>
}
} | 26 | Kotlin | 35 | 573 | 383594d2708296f2fbc6ea1f10b117d3acd1f46a | 2,269 | contacts-android | Apache License 2.0 |
app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadProvider.kt | CarlosEsco | 182,704,531 | false | null | package eu.kanade.tachiyomi.data.download
import android.content.Context
import androidx.core.net.toUri
import androidx.core.text.isDigitsOnly
import com.elvishew.xlog.XLog
import com.hippo.unifile.UniFile
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.model.isMergedChapter
import eu.kanade.tachiyomi.util.lang.isUUID
import eu.kanade.tachiyomi.util.storage.DiskUtil
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
/**
* This class is used to provide the directories where the downloads should be saved.
* It uses the following path scheme: /<root downloads dir>/<source name>/<manga>/<chapter>
*
* @param context the application context.
*/
class DownloadProvider(private val context: Context) {
/**
* Preferences helper.
*/
private val preferences: PreferencesHelper by injectLazy()
private val source = Injekt.get<SourceManager>().getMangadex()
fun downloadsDir(): UniFile = preferences.downloadsDirectory().get().let {
val dir = UniFile.fromUri(context, it.toUri())
DiskUtil.createNoMediaFile(dir, context)
dir
}
/**
* Returns the download directory for a manga. For internal use only.
*
* @param manga the manga to query.
* @param source the source of the manga.
*/
@Synchronized
internal fun getMangaDir(manga: Manga): UniFile {
try {
val mangaDirName = getMangaDirName(manga)
val sourceDirName = getSourceDirName()
XLog.d("creating directory for $sourceDirName : $mangaDirName")
return downloadsDir().createDirectory(sourceDirName)
.createDirectory(mangaDirName)
} catch (e: Exception) {
XLog.e("error getting download folder for ${manga.title}", e)
throw Exception(context.getString(R.string.invalid_download_location))
}
}
/**
* Returns the download directory for a source if it exists.
*
* @param source the source to query.
*/
fun findSourceDir(): UniFile? {
return downloadsDir().findFile(getSourceDirName(), true)
}
/**
* Returns the download directory for a manga if it exists.
*
* @param manga the manga to query.
* @param source the source of the manga.
*/
fun findMangaDir(manga: Manga): UniFile? {
val sourceDir = findSourceDir()
return sourceDir?.findFile(getMangaDirName(manga), true)
}
/**
* Returns the download directory for a chapter if it exists.
*
* @param chapter the chapter to query.
* @param manga the manga of the chapter.
* @param source the source of the chapter.
*/
fun findChapterDir(chapter: Chapter, manga: Manga): UniFile? {
val mangaDir = findMangaDir(manga)
return getValidChapterDirNames(chapter).asSequence()
.mapNotNull { mangaDir?.findFile(it, true) ?: mangaDir?.findFile("$it.cbz", true) }
.firstOrNull()
}
/**
* Returns a list of downloaded directories for the chapters that exist.
*
* @param chapters the chapters to query.
* @param manga the manga of the chapter.
* @param source the source of the chapter.
*/
fun findChapterDirs(chapters: List<Chapter>, manga: Manga): List<UniFile> {
val mangaDir = findMangaDir(manga) ?: return emptyList()
val idHashSet = chapters.map { it.mangadex_chapter_id }.toHashSet()
val oldIdHashSet = chapters.mapNotNull { it.old_mangadex_id }.toHashSet()
val chapterNameHashSet = chapters.map { it.name }.toHashSet()
val scanalatorNameHashSet = chapters.map { getJ2kChapterName(it) }.toHashSet()
val scanalatorCbzNameHashSet = chapters.map { "${getChapterDirName(it)}.cbz" }.toHashSet()
return mangaDir.listFiles()!!.asList().filter { file ->
file.name?.let { fileName ->
val mangadexId = fileName.substringAfterLast(" - ", "")
// legacy dex id
if (mangadexId.isNotEmpty() && mangadexId.isUUID()) {
return@filter idHashSet.contains(mangadexId)
} else if (mangadexId.isNotEmpty() && mangadexId.isDigitsOnly()) {
return@filter oldIdHashSet.contains(mangadexId)
} else {
if (scanalatorNameHashSet.contains(fileName)) {
return@filter true
}
if (scanalatorCbzNameHashSet.contains(fileName)) {
return@filter true
}
val afterScanlatorCheck = fileName.substringAfter("_")
return@filter chapterNameHashSet.contains(fileName) || chapterNameHashSet.contains(
afterScanlatorCheck,
)
}
}
return@filter false
}
}
/**
* Returns a list of all files in manga directory
*
* @param chapters the chapters to query.
* @param manga the manga of the chapter.
* @param source the source of the chapter.
*/
fun findUnmatchedChapterDirs(
chapters: List<Chapter>,
manga: Manga,
): List<UniFile> {
val mangaDir = findMangaDir(manga) ?: return emptyList()
val idHashSet = chapters.map { it.mangadex_chapter_id }.toHashSet()
val chapterNameHashSet = chapters.map { it.name }.toHashSet()
val scanalatorNameHashSet = chapters.map { getJ2kChapterName(it) }.toHashSet()
val scanalatorCbzNameHashSet = chapters.map { "${getChapterDirName(it)}.cbz" }.toHashSet()
return mangaDir.listFiles()!!.asList().filter { file ->
file.name?.let { fileName ->
if (fileName.endsWith(Downloader.TMP_DIR_SUFFIX)) {
return@filter true
}
val mangadexId = fileName.substringAfterLast("- ", "")
if (mangadexId.isNotEmpty() && (mangadexId.isDigitsOnly() || mangadexId.isUUID())) {
return@filter !idHashSet.contains(mangadexId)
} else {
if (scanalatorNameHashSet.contains(fileName)) {
return@filter false
}
if (scanalatorCbzNameHashSet.contains(fileName)) {
return@filter false
}
val afterScanlatorCheck = fileName.substringAfter("_")
return@filter !chapterNameHashSet.contains(fileName) && !chapterNameHashSet.contains(
afterScanlatorCheck,
)
}
}
// everything else is considered true
return@filter true
}
}
fun renameMangaFolder(from: String, to: String) {
val sourceDir = findSourceDir()
val mangaDir = sourceDir?.findFile(DiskUtil.buildValidFilename(from))
mangaDir?.renameTo(to)
}
/**
* Returns a list of downloaded directories for the chapters that exist.
*
* @param chapters the chapters to query.
* @param manga the manga of the chapter.
* @param source the source of the chapter.
*/
fun findTempChapterDirs(chapters: List<Chapter>, manga: Manga): List<UniFile> {
val mangaDir = findMangaDir(manga) ?: return emptyList()
return chapters.mapNotNull { mangaDir.findFile("${getChapterDirName(it)}${Downloader.TMP_DIR_SUFFIX}") }
}
/**
* Returns the download directory name for a source always english to not break with other forks or current neko
*
* @param source the source to query.
*/
fun getSourceDirName(): String {
return "$source (EN)"
}
/**
* Returns the download directory name for a manga.
*
* @param manga the manga to query.
*/
fun getMangaDirName(manga: Manga): String {
return DiskUtil.buildValidFilename(manga.title)
}
/**
* Returns the chapter directory name for a chapter.
*
* @param chapter the chapter to query.
*/
fun getChapterDirName(chapter: Chapter, useNewId: Boolean = true): String {
if (chapter.isMergedChapter()) {
return getJ2kChapterName(chapter)
} else {
if (useNewId.not() && chapter.old_mangadex_id == null) {
return ""
}
val chapterId = if (useNewId) chapter.mangadex_chapter_id else chapter.old_mangadex_id
return DiskUtil.buildValidFilename(chapter.name, " - $chapterId")
}
}
fun getJ2kChapterName(chapter: Chapter): String {
return DiskUtil.buildValidFilename(
if (chapter.scanlator != null) "${chapter.scanlator}_${chapter.name}"
else chapter.name,
)
}
/**
* Returns valid downloaded chapter directory names.
*
* @param chapter the chapter to query.
*/
fun getValidChapterDirNames(chapter: Chapter): List<String> {
return listOf(
getChapterDirName(chapter, true),
// chater names from j2k
getJ2kChapterName(chapter),
// legacy manga id
getChapterDirName(chapter, false),
// Legacy chapter directory name used in v0.8.4 and before
DiskUtil.buildValidFilename(chapter.name),
).filter { it.isNotEmpty() }
}
}
| 94 | null | 98 | 934 | 317243499e4131d3c3ee3604d81f8b69067414a4 | 9,657 | Neko | Apache License 2.0 |
kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/gcePersistentDisk.kt | MaTriXy | 129,299,660 | true | {"Kotlin": 237663} | // GENERATED
package com.fkorotkov.kubernetes
import io.fabric8.kubernetes.api.model.GCEPersistentDiskVolumeSource
import io.fabric8.kubernetes.api.model.PersistentVolumeSpec
import io.fabric8.kubernetes.api.model.Volume
fun PersistentVolumeSpec.`gcePersistentDisk`(block: GCEPersistentDiskVolumeSource.() -> Unit = {}) {
if(this.`gcePersistentDisk` == null) {
this.`gcePersistentDisk` = GCEPersistentDiskVolumeSource()
}
this.`gcePersistentDisk`.block()
}
fun Volume.`gcePersistentDisk`(block: GCEPersistentDiskVolumeSource.() -> Unit = {}) {
if(this.`gcePersistentDisk` == null) {
this.`gcePersistentDisk` = GCEPersistentDiskVolumeSource()
}
this.`gcePersistentDisk`.block()
}
| 0 | Kotlin | 0 | 0 | 6446f7995b9fdf012ba72b380fe7b5ebe11649e2 | 709 | k8s-kotlin-dsl | MIT License |
HKBusETA/app/src/main/java/com/loohp/hkbuseta/FavActivity.kt | LOOHP | 686,756,915 | false | {"Kotlin": 193468, "Java": 136916} | package com.loohp.hkbuseta
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.ButtonDefaults
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import com.loohp.hkbuseta.compose.AdvanceButton
import com.loohp.hkbuseta.shared.Registry
import com.loohp.hkbuseta.shared.Shared
import com.loohp.hkbuseta.theme.HKBusETATheme
import com.loohp.hkbuseta.utils.StringUtils
import kotlinx.coroutines.delay
import java.util.Timer
import java.util.TimerTask
class FavActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Shared.setDefaultExceptionHandler(this)
setContent {
FavElements(this)
}
}
override fun onStart() {
super.onStart()
Shared.setSelfAsCurrentActivity(this)
}
override fun onDestroy() {
super.onDestroy()
if (isFinishing) {
Shared.removeSelfFromCurrentActivity(this)
}
}
}
@Composable
fun FavElements(instance: FavActivity) {
HKBusETATheme {
Column(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colors.background),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
) {
Shared.MainTime()
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(20.dp, 0.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
FavTitle(instance)
Spacer(modifier = Modifier.size(StringUtils.scaledSize(10, instance).dp))
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
FavButton(1, instance)
Spacer(modifier = Modifier.size(StringUtils.scaledSize(10, instance).dp))
FavButton(2, instance)
Spacer(modifier = Modifier.size(StringUtils.scaledSize(10, instance).dp))
FavButton(3, instance)
Spacer(modifier = Modifier.size(StringUtils.scaledSize(10, instance).dp))
FavButton(4, instance)
}
Spacer(modifier = Modifier.size(StringUtils.scaledSize(10, instance).dp))
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
FavButton(5, instance)
Spacer(modifier = Modifier.size(StringUtils.scaledSize(10, instance).dp))
FavButton(6, instance)
Spacer(modifier = Modifier.size(StringUtils.scaledSize(10, instance).dp))
FavButton(7, instance)
Spacer(modifier = Modifier.size(StringUtils.scaledSize(10, instance).dp))
FavButton(8, instance)
}
Spacer(modifier = Modifier.size(StringUtils.scaledSize(10, instance).dp))
FavDescription(instance)
}
}
}
@Composable
fun FavTitle(instance: FavActivity) {
Text(
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
color = MaterialTheme.colors.primary,
fontSize = TextUnit(StringUtils.scaledSize(17F, instance), TextUnitType.Sp),
text = if (Shared.language == "en") "Favourite Routes" else "最喜愛路線"
)
}
@Composable
fun FavDescription(instance: FavActivity) {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp, 0.dp),
textAlign = TextAlign.Center,
color = MaterialTheme.colors.primary,
fontSize = TextUnit(StringUtils.scaledSize(11F, instance), TextUnitType.Sp),
text = if (Shared.language == "en") "These routes will display in their corresponding indexed Tile" else "這些路線將顯示在其相應數字的資訊方塊中"
)
}
@Composable
fun FavButton(favoriteIndex: Int, instance: FavActivity) {
val hasFavouriteStopRoute = remember { mutableStateOf(Shared.favoriteRouteStops[favoriteIndex] != null) }
val deleteState = remember { mutableStateOf(false) }
LaunchedEffect (Unit) {
while (true) {
delay(500)
val newState = Shared.favoriteRouteStops[favoriteIndex] != null
if (newState != hasFavouriteStopRoute.value) {
hasFavouriteStopRoute.value = newState
}
}
}
FavButtonInternal(favoriteIndex, hasFavouriteStopRoute, deleteState, instance)
}
@Composable
fun FavButtonInternal(favoriteIndex: Int, hasFavouriteStopRoute: MutableState<Boolean>, deleteState: MutableState<Boolean>, instance: FavActivity) {
val haptic = LocalHapticFeedback.current
AdvanceButton(
onClick = {
if (deleteState.value) {
if (Registry.getInstance(instance).hasFavouriteRouteStop(favoriteIndex)) {
Registry.getInstance(instance).clearFavouriteRouteStop(favoriteIndex, instance)
Toast.makeText(instance, if (Shared.language == "en") "Cleared Route Stop ETA ".plus(favoriteIndex).plus(" Tile") else "已清除資訊方塊路線巴士站預計到達時間".plus(favoriteIndex), Toast.LENGTH_SHORT).show()
}
val newState = Shared.favoriteRouteStops[favoriteIndex] != null
if (newState != hasFavouriteStopRoute.value) {
hasFavouriteStopRoute.value = newState
}
deleteState.value = false
} else {
val favouriteStopRoute = Shared.favoriteRouteStops[favoriteIndex]
if (favouriteStopRoute != null) {
val stopId = favouriteStopRoute.optString("stopId")
val co = favouriteStopRoute.optString("co")
val index = favouriteStopRoute.optInt("index")
val stop = favouriteStopRoute.optJSONObject("stop")!!
val route = favouriteStopRoute.optJSONObject("route")!!
val intent = Intent(instance, EtaActivity::class.java)
intent.putExtra("stopId", stopId)
intent.putExtra("co", co)
intent.putExtra("index", index)
intent.putExtra("stop", stop.toString())
intent.putExtra("route", route.toString())
instance.startActivity(intent)
}
}
},
onLongClick = {
if (!deleteState.value) {
deleteState.value = true
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
Timer().schedule(object : TimerTask() {
override fun run() {
if (deleteState.value) {
deleteState.value = false
}
}
}, 5000)
val favouriteStopRoute = Shared.favoriteRouteStops[favoriteIndex]
if (favouriteStopRoute != null) {
val index = favouriteStopRoute.optInt("index")
val stop = favouriteStopRoute.optJSONObject("stop")!!
val stopName = stop.optJSONObject("name")!!
val route = favouriteStopRoute.optJSONObject("route")!!
val destName = route.optJSONObject("dest")!!
val text = if (Shared.language == "en") {
route.optString("route").plus(" To ").plus(StringUtils.capitalize(destName.optString("en"))).plus("\n")
.plus(index).plus(". ").plus(StringUtils.capitalize(stopName.optString("en")))
} else {
route.optString("route").plus(" 往").plus(StringUtils.capitalize(destName.optString("zh"))).plus("\n")
.plus(index).plus(". ").plus(StringUtils.capitalize(stopName.optString("zh")))
}
instance.runOnUiThread {
Toast.makeText(instance, text, Toast.LENGTH_LONG).show()
}
}
}
},
modifier = Modifier
.width(StringUtils.scaledSize(35, instance).dp)
.height(StringUtils.scaledSize(35, instance).dp),
colors = ButtonDefaults.buttonColors(
backgroundColor = if (deleteState.value) Color(0xFF633A3A) else MaterialTheme.colors.secondary,
contentColor = if (deleteState.value) Color(0xFFFF0000) else if (hasFavouriteStopRoute.value) Color(0xFFFFFF00) else Color(0xFF444444),
),
enabled = hasFavouriteStopRoute.value,
content = {
if (deleteState.value) {
Icon(
modifier = Modifier.size(StringUtils.scaledSize(21, instance).dp),
imageVector = Icons.Filled.Clear,
tint = Color(0xFFFF0000),
contentDescription = if (Shared.language == "en") "Clear Route Stop ETA ".plus(favoriteIndex).plus(" Tile") else "清除資訊方塊路線巴士站預計到達時間".plus(favoriteIndex)
)
} else {
Text(
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontSize = TextUnit(StringUtils.scaledSize(17F, instance), TextUnitType.Sp),
color = if (hasFavouriteStopRoute.value) Color(0xFFFFFF00) else Color(0xFF444444),
text = favoriteIndex.toString()
)
}
}
)
} | 0 | Kotlin | 0 | 0 | e512f805796587879bb35b04377cdcc6f766d678 | 11,130 | HK-Bus-ETA-WearOS | MIT License |
app/src/main/java/com/farmerbb/notepad/models/Entities.kt | farmerbb | 17,308,977 | false | null | /* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tglt.notepad.models
import androidx.room.*
import java.util.*
@Entity
data class NoteContents(
@PrimaryKey(autoGenerate = true)
val contentsId: Long = 0,
val text: String = "",
val isDraft: Boolean = false
)
@Entity
data class NoteMetadata(
@PrimaryKey(autoGenerate = true)
val metadataId: Long = 0,
val title: String = "",
val date: Date = Date()
)
@Entity(
primaryKeys = ["metadataId", "contentsId"],
indices = [Index("contentsId")]
)
data class CrossRef(
val metadataId: Long = 0,
val contentsId: Long = 0
)
data class Note(
@Embedded val metadata: NoteMetadata = NoteMetadata(),
@Relation(
parentColumn = "metadataId",
entityColumn = "contentsId",
associateBy = Junction(CrossRef::class)
)
val contents: NoteContents = NoteContents()
) | 49 | null | 80 | 205 | 8ee72a5c9559500707792ddb8fd6acbce1080018 | 1,432 | Notepad | Apache License 2.0 |
app/src/main/java/com/example/pettyplanet/di/MainModule.kt | shankarpriyank | 443,486,579 | false | {"Kotlin": 41528} | package com.example.pettyplanet.di
import android.app.Application
import android.content.Context
import androidx.room.Room
import com.example.pettyplanet.database.SavedPostsDatabase
import com.example.pettyplanet.repository.PostRepositoryImpl
import com.example.pettyplanet.repository.PostsRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object MainModule {
@Singleton
@Provides
fun provideUserID(@ApplicationContext context: Context): String {
val preferences =
context.getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
return preferences.getString("text", "")!!
}
@Provides
@Singleton
fun providePostDatabase(app: Application): SavedPostsDatabase {
return Room.databaseBuilder(
app,
SavedPostsDatabase::class.java,
SavedPostsDatabase.DATABASE_NAME
)
.fallbackToDestructiveMigration()
.build()
}
@Provides
@Singleton
fun providePostRepository(db: SavedPostsDatabase): PostsRepository {
return PostRepositoryImpl(db.savedPostDao)
}
}
| 0 | Kotlin | 1 | 2 | bc069a841264c306833c1c7b64286b52942ae0eb | 1,334 | PettyPlanet | Freetype Project License |
app/src/main/java/org/teslasoft/assistant/ui/PromptViewActivity.kt | AndraxDev | 608,789,494 | false | null | /**************************************************************************
* Copyright (c) 2023-2024 Dmytro Ostapenko. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**************************************************************************/
package org.teslasoft.assistant.ui.activities
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.Configuration
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.content.res.AppCompatResources
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.fragment.app.FragmentActivity
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.elevation.SurfaceColors
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.teslasoft.assistant.Api
import org.teslasoft.assistant.Config
import org.teslasoft.assistant.R
import org.teslasoft.assistant.preferences.Preferences
import org.teslasoft.assistant.ui.assistant.AssistantActivity
import org.teslasoft.core.api.network.RequestNetwork
import java.net.MalformedURLException
import java.net.URL
class PromptViewActivity : FragmentActivity(), SwipeRefreshLayout.OnRefreshListener {
private var activityTitle: TextView? = null
private var content: ConstraintLayout? = null
private var progressBar: ProgressBar? = null
private var noInternetLayout: ConstraintLayout? = null
private var btnReconnect: MaterialButton? = null
private var btnShowDetails: MaterialButton? = null
private var promptBy: TextView? = null
private var promptText: EditText? = null
private var textCat: TextView? = null
private var refreshPage: SwipeRefreshLayout? = null
private var requestNetwork: RequestNetwork? = null
private var btnCopy: MaterialButton? = null
private var btnLike: MaterialButton? = null
private var btnTry: MaterialButton? = null
private var btnFlag: ImageButton? = null
private var promptBg: ConstraintLayout? = null
private var promptActions: ConstraintLayout? = null
private var id = ""
private var title = ""
private var networkError = ""
private var likeState = false
private var settings: SharedPreferences? = null
private var promptFor: String? = null
private var btnBack: ImageButton? = null
private var root: ConstraintLayout? = null
private val dataListener: RequestNetwork.RequestListener = object : RequestNetwork.RequestListener {
override fun onResponse(tag: String, message: String) {
noInternetLayout?.visibility = View.GONE
progressBar?.visibility = View.GONE
content?.visibility = View.VISIBLE
try {
val map: HashMap<String, String> = Gson().fromJson(
message, TypeToken.getParameterized(HashMap::class.java, String::class.java, String::class.java).type
)
promptText?.setText(map["prompt"])
promptBy?.text = "By " + map["author"]
btnLike?.text = map["likes"]
promptFor = map["type"]
textCat?.text = when (map["category"]) {
"development" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_development))
"music" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_music))
"art" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_art))
"culture" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_culture))
"business" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_business))
"gaming" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_gaming))
"education" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_education))
"history" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_history))
"health" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_health))
"food" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_food))
"tourism" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_tourism))
"productivity" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_productivity))
"tools" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_tools))
"entertainment" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_entertainment))
"sport" -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_sport))
else -> String.format(resources.getString(R.string.cat), resources.getString(R.string.cat_uncat))
}
networkError = ""
} catch (e: Exception) {
networkError = e.printStackTrace().toString()
}
}
override fun onErrorResponse(tag: String, message: String) {
networkError = message
noInternetLayout?.visibility = View.VISIBLE
progressBar?.visibility = View.GONE
content?.visibility = View.GONE
}
}
private val likeListener: RequestNetwork.RequestListener = object : RequestNetwork.RequestListener {
override fun onResponse(tag: String, message: String) {
btnLike?.isEnabled = true
likeState = true
settings?.edit()?.putBoolean(id, true)?.apply()
btnLike?.setIconResource(R.drawable.ic_like)
loadData()
}
override fun onErrorResponse(tag: String, message: String) {
btnLike?.isEnabled = true
Toast.makeText(this@PromptViewActivity, getString(R.string.label_sorry_action_failed), Toast.LENGTH_SHORT).show()
}
}
private val dislikeListener: RequestNetwork.RequestListener = object : RequestNetwork.RequestListener {
override fun onResponse(tag: String, message: String) {
btnLike?.isEnabled = true
likeState = false
settings?.edit()?.putBoolean(id, false)?.apply()
btnLike?.setIconResource(R.drawable.ic_like_outline)
loadData()
}
override fun onErrorResponse(tag: String, message: String) {
btnLike?.isEnabled = true
Toast.makeText(this@PromptViewActivity, getString(R.string.label_sorry_action_failed), Toast.LENGTH_SHORT).show()
}
}
override fun onResume() {
super.onResume()
reloadAmoled()
// Reset preferences singleton
Preferences.getPreferences(this, "")
}
private fun reloadAmoled() {
if (isDarkThemeEnabled() && Preferences.getPreferences(this, "").getAmoledPitchBlack()) {
if (android.os.Build.VERSION.SDK_INT <= 34) {
window.navigationBarColor = ResourcesCompat.getColor(resources, R.color.amoled_window_background, theme)
window.statusBarColor = ResourcesCompat.getColor(resources, R.color.amoled_accent_50, theme)
}
window.setBackgroundDrawableResource(R.color.amoled_window_background)
root?.setBackgroundColor(ResourcesCompat.getColor(resources, R.color.amoled_window_background, theme))
activityTitle?.setBackgroundColor(ResourcesCompat.getColor(resources, R.color.amoled_accent_50, theme))
promptBg?.setBackgroundResource(R.drawable.btn_accent_24_amoled)
promptActions?.setBackgroundResource(R.drawable.btn_accent_24_amoled)
btnBack?.background = getDarkAccentDrawable(
AppCompatResources.getDrawable(
this,
R.drawable.btn_accent_tonal_v4_amoled
)!!, this
)
btnFlag?.background = getDarkAccentDrawable(
AppCompatResources.getDrawable(
this,
R.drawable.btn_accent_tonal_v4_amoled
)!!, this
)
} else {
if (android.os.Build.VERSION.SDK_INT <= 34) {
window.navigationBarColor = SurfaceColors.SURFACE_0.getColor(this)
window.statusBarColor = SurfaceColors.SURFACE_4.getColor(this)
}
window.setBackgroundDrawableResource(R.color.window_background)
root?.setBackgroundColor(SurfaceColors.SURFACE_0.getColor(this))
activityTitle?.setBackgroundColor(SurfaceColors.SURFACE_4.getColor(this))
promptBg?.background = getDarkDrawable(
AppCompatResources.getDrawable(
this,
R.drawable.btn_accent_24
)!!
)
promptActions?.background = getDarkDrawable(
AppCompatResources.getDrawable(
this,
R.drawable.btn_accent_24
)!!
)
btnBack?.background = getDarkAccentDrawable(
AppCompatResources.getDrawable(
this,
R.drawable.btn_accent_tonal_v4
)!!, this
)
btnFlag?.background = getDarkAccentDrawable(
AppCompatResources.getDrawable(
this,
R.drawable.btn_accent_tonal_v4
)!!, this
)
}
}
private fun getDarkDrawable(drawable: Drawable) : Drawable {
DrawableCompat.setTint(DrawableCompat.wrap(drawable), SurfaceColors.SURFACE_2.getColor(this))
return drawable
}
private fun isDarkThemeEnabled(): Boolean {
return when (resources.configuration.uiMode and
Configuration.UI_MODE_NIGHT_MASK) {
Configuration.UI_MODE_NIGHT_YES -> true
Configuration.UI_MODE_NIGHT_NO -> false
Configuration.UI_MODE_NIGHT_UNDEFINED -> false
else -> false
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val extras: Bundle? = intent.extras
if (extras == null) {
checkForURI()
} else {
id = extras.getString("id", "")
title = extras.getString("title", "")
[email protected](extras.getString("title", ""))
if (id == "" || title == "") {
checkForURI()
} else {
allowLaunch()
}
}
}
private fun checkForURI() {
val uri = intent.data
try {
val url = URL(uri?.scheme, uri?.host, uri?.path)
val paths = url.path.split("/")
id = paths[paths.size - 1]
allowLaunch()
} catch (e: MalformedURLException) {
Toast.makeText(this, "Invalid URL", Toast.LENGTH_SHORT).show()
finish()
}
}
private fun allowLaunch() {
setContentView(R.layout.activity_view_prompt)
if (android.os.Build.VERSION.SDK_INT <= 34) {
window.statusBarColor = SurfaceColors.SURFACE_4.getColor(this)
}
initUI()
Thread {
runOnUiThread {
initLogic()
}
}.start()
}
private fun initUI() {
activityTitle = findViewById(R.id.activity_view_title)
content = findViewById(R.id.view_content)
progressBar = findViewById(R.id.progress_bar_view)
noInternetLayout = findViewById(R.id.no_internet)
btnReconnect = findViewById(R.id.btn_reconnect)
btnShowDetails = findViewById(R.id.btn_show_details)
promptBy = findViewById(R.id.prompt_by)
promptText = findViewById(R.id.prompt_text)
refreshPage = findViewById(R.id.refresh_page)
btnFlag = findViewById(R.id.btn_flag)
btnCopy = findViewById(R.id.btn_copy)
btnLike = findViewById(R.id.btn_like)
btnTry = findViewById(R.id.btn_try)
textCat = findViewById(R.id.text_cat)
btnBack = findViewById(R.id.btn_back)
root = findViewById(R.id.root)
promptBg = findViewById(R.id.prompt_bg)
promptActions = findViewById(R.id.prompt_actions)
noInternetLayout?.visibility = View.GONE
progressBar?.visibility = View.VISIBLE
content?.visibility = View.GONE
reloadAmoled()
}
private fun initLogic() {
activityTitle?.isSelected = true
btnFlag?.background = getDarkAccentDrawable(
AppCompatResources.getDrawable(
this,
R.drawable.btn_accent_tonal_v4
)!!, this
)
btnBack?.background = getDarkAccentDrawable(
AppCompatResources.getDrawable(
this,
R.drawable.btn_accent_tonal_v4
)!!, this
)
btnFlag?.setImageResource(R.drawable.ic_flag)
btnBack?.setOnClickListener {
finish()
}
settings = getSharedPreferences("likes", MODE_PRIVATE)
likeState = settings?.getBoolean(id, false) == true
refreshPage?.setColorSchemeResources(R.color.accent_900)
refreshPage?.setProgressBackgroundColorSchemeColor(
SurfaceColors.SURFACE_2.getColor(this)
)
refreshPage?.setSize(SwipeRefreshLayout.LARGE)
refreshPage?.setOnRefreshListener(this)
if (likeState) {
btnLike?.setIconResource(R.drawable.ic_like)
} else {
btnLike?.setIconResource(R.drawable.ic_like_outline)
}
btnCopy?.setOnClickListener {
val clipboard: ClipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("prompt", promptText?.text.toString())
clipboard.setPrimaryClip(clip)
Toast.makeText(this, getString(R.string.label_copy), Toast.LENGTH_SHORT).show()
}
btnLike?.setOnClickListener {
if (likeState) {
requestNetwork?.startRequestNetwork("GET", "${Config.API_ENDPOINT}/dislike.php?api_key=${Api.TESLASOFT_API_KEY}&id=$id", "A", dislikeListener)
} else {
requestNetwork?.startRequestNetwork("GET", "${Config.API_ENDPOINT}/like.php?api_key=${Api.TESLASOFT_API_KEY}&id=$id", "A", likeListener)
}
btnLike?.isEnabled = false
}
btnTry?.setOnClickListener {
if (promptFor == "GPT") {
val i = Intent(
this,
AssistantActivity::class.java
).setAction(Intent.ACTION_VIEW)
i.putExtra("prompt", promptText?.text.toString())
startActivity(i)
} else {
val i = Intent(
this,
AssistantActivity::class.java
).setAction(Intent.ACTION_VIEW)
i.putExtra("prompt", "/imagine " + promptText?.text.toString())
i.putExtra("FORCE_SLASH_COMMANDS_ENABLED", true)
startActivity(i)
}
}
btnFlag?.setOnClickListener {
val i = Intent(this, ReportAbuseActivity::class.java).setAction(Intent.ACTION_VIEW)
i.putExtra("id", id)
startActivity(i)
}
requestNetwork = RequestNetwork(this)
activityTitle?.text = title
btnReconnect?.setOnClickListener { loadData() }
btnShowDetails?.setOnClickListener {
MaterialAlertDialogBuilder(this, R.style.App_MaterialAlertDialog)
.setTitle(R.string.label_error_details)
.setMessage(networkError)
.setPositiveButton(R.string.btn_close) { _, _ -> }
.show()
}
loadData()
}
private fun getDarkAccentDrawable(drawable: Drawable, context: Context) : Drawable {
DrawableCompat.setTint(DrawableCompat.wrap(drawable), getSurfaceColor(context))
return drawable
}
private fun getSurfaceColor(context: Context) : Int {
return if (isDarkThemeEnabled() && Preferences.getPreferences(context, "").getAmoledPitchBlack()) {
ResourcesCompat.getColor(context.resources, R.color.amoled_accent_50, context.theme)
} else {
SurfaceColors.SURFACE_4.getColor(context)
}
}
override fun onRefresh() {
refreshPage?.isRefreshing = false
loadData()
}
private fun loadData() {
noInternetLayout?.visibility = View.GONE
progressBar?.visibility = View.VISIBLE
content?.visibility = View.GONE
requestNetwork?.startRequestNetwork("GET", "${Config.API_ENDPOINT}/prompt.php?api_key=${Api.TESLASOFT_API_KEY}&id=$id", "A", dataListener)
}
}
| 9 | null | 57 | 98 | 50401c8e55ecc0560b818779ec2b10fa36241166 | 18,279 | speak-gpt | Apache License 2.0 |
app/src/main/java/com/bluesound/nsd/ServiceDescription.kt | jpelgrim | 728,270,633 | false | {"Kotlin": 14482} | package com.bluesound.nsd
class ServiceDescription(val name: String, val address: String, val port: Int) {
override fun toString(): String {
return "ServiceDescription(name='$name', address='$address', port=$port)"
}
}
| 0 | Kotlin | 0 | 0 | e3ddc40640306d74150269395fff9c1a34d100cb | 236 | NSD | Apache License 2.0 |
core/src/ru/icarumbas/bagel/view/renderer/systems/ViewportSystem.kt | Rami-Majdoub | 229,632,097 | false | {"Kotlin": 167745, "C++": 1658, "GLSL": 1323, "Java": 1271} | package ru.icarumbas.bagel.view.renderer.systems
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.systems.IteratingSystem
import com.badlogic.gdx.utils.viewport.Viewport
import ru.icarumbas.bagel.engine.components.other.PlayerComponent
import ru.icarumbas.bagel.engine.components.physics.BodyComponent
import ru.icarumbas.bagel.engine.world.RoomWorld
import ru.icarumbas.bagel.utils.body
import ru.icarumbas.bagel.view.renderer.components.SizeComponent
class ViewportSystem(
private val view: Viewport,
private val rm: RoomWorld
) : IteratingSystem(Family.all(PlayerComponent::class.java, BodyComponent::class.java, SizeComponent::class.java).get()) {
override fun processEntity(entity: Entity, deltaTime: Float) {
moveCamera(body[entity].body.position.x, body[entity].body.position.y)
}
private fun moveCamera(posX: Float, posY: Float) {
with (view) {
camera.position.x = posX
camera.position.y = posY
if (camera.position.y - worldHeight / 2f < 0)
camera.position.y = worldHeight / 2f
if (camera.position.x - worldWidth / 2f < 0)
camera.position.x = worldWidth / 2f
if (camera.position.x + worldWidth / 2f > rm.getRoomWidth())
camera.position.x = rm.getRoomWidth() - worldWidth / 2f
if (camera.position.y + worldHeight / 2f > rm.getRoomHeight())
camera.position.y = rm.getRoomHeight() - worldHeight / 2f
camera.update()
}
}
} | 0 | null | 1 | 0 | 71b24a8e2f70669679250719c24d7e8bedd5de28 | 1,601 | bagel | Apache License 2.0 |
src/main/kotlin/view/TopBarView.kt | kirilenkobm | 668,817,148 | false | null | package view
import Constants
import state.*
import util.IconManager
import view.popupwindows.SettingsDialog
import java.awt.*
import javax.swing.*
/**
* Class representing the top bar view of the application.
*
* This class is responsible for creating and managing the top bar of the application,
* which includes navigation buttons, the address bar, the file filter, and settings button.
*
* The left panel contains the navigation buttons, the address bar, and the file filter.
* The right panel contains the view mode buttons and the settings button.
*
* The class implements the `SettingsObserver` interface.
*/
class TopBarView(private val frame: JFrame) : SettingsObserver {
private val topBar = JSplitPane()
private val leftPanel = JPanel()
private val rightPanel = JPanel(FlowLayout(FlowLayout.RIGHT))
private val addressBarView = AddressBarView()
private var settingsDialog: SettingsDialog? = null
private val filterPanel = FilterPanel()
init {
configurePanel()
Settings.addObserver(this)
}
private fun configurePanel() {
leftPanel.layout = BoxLayout(leftPanel, BoxLayout.X_AXIS)
addNavigationButtons()
addAddressBarAndFilter()
addRightPanelButtons()
applyThemeColors()
topBar.leftComponent = leftPanel
topBar.rightComponent = rightPanel
topBar.resizeWeight = 0.7
}
private fun addNavigationButtons() {
val navigationButtons = arrayOf(
Pair(IconManager.backArrowIcon) { AppState.goBack() },
Pair(IconManager.forwardArrowIcon) { AppState.goForward() },
Pair(IconManager.homeIcon) { AppState.goHome() },
Pair(IconManager.upArrowIcon) { AppState.goUp() }
)
navigationButtons.forEach {
val (icon, action) = it
leftPanel.add(createButton(icon, Settings.buttonSize, action))
}
leftPanel.add(Box.createHorizontalStrut(20)) // add 100px of space
}
private fun setupAddressBarPanel(): JPanel {
val addressBarPanel = addressBarView.getPanel()
addressBarPanel.maximumSize = Dimension(
addressBarPanel.maximumSize.width,
addressBarPanel.preferredSize.height
)
addressBarPanel.preferredSize = Dimension(400, addressBarPanel.preferredSize.height)
addressBarPanel.minimumSize = Dimension(400, addressBarPanel.preferredSize.height)
return addressBarPanel
}
private fun setupFilterView(addressBarHeight: Int): JPanel {
val filterView = filterPanel.getPanel()
filterView.preferredSize = Dimension(filterView.preferredSize.width, addressBarHeight)
filterView.minimumSize = Dimension(filterView.minimumSize.width, addressBarHeight)
filterView.maximumSize = Dimension(filterView.maximumSize.width, addressBarHeight)
return filterView
}
private fun addAddressBarAndFilter() {
val addressBarPanel = setupAddressBarPanel()
val filterLabel = JLabel(" /*. ").apply {
foreground = if (Settings.colorTheme == ColorTheme.LIGHT) Color.BLACK else Color.WHITE
font = Font("Arial", Font.PLAIN, 14)
}
val filterView = setupFilterView(addressBarPanel.preferredSize.height)
leftPanel.add(addressBarPanel)
leftPanel.add(filterLabel)
leftPanel.add(filterView)
}
private fun addRightPanelButtons() {
val viewModeGroup = ButtonGroup()
val tableButton = createToggleButton(IconManager.tocIcon, Settings.buttonSize) {
Settings.updateViewMode(ViewMode.TABLE)
}.apply {
isSelected = Settings.viewMode == ViewMode.TABLE
}
val iconButton = createToggleButton(IconManager.viewModuleIcon, Settings.buttonSize) {
Settings.updateViewMode(ViewMode.GRID)
}.apply {
isSelected = Settings.viewMode == ViewMode.GRID
}
viewModeGroup.add(tableButton)
viewModeGroup.add(iconButton)
val settingsButton = createButton(IconManager.settingsIcon, Settings.buttonSize) {
if (settingsDialog?.isVisible != true) // to ensure only one settings view is shown
{
settingsDialog = SettingsDialog().apply {
// to locate it in the middle of the main view, not in the
// top left corner of the screen
setLocationRelativeTo(frame)
isVisible = true
}
}
}
rightPanel.add(tableButton)
rightPanel.add(iconButton)
rightPanel.add(Box.createHorizontalStrut(20)) // add 100px of space
rightPanel.add(settingsButton)
}
private fun applyThemeColors() {
if (Settings.colorTheme == ColorTheme.DARK) {
leftPanel.background = Color.DARK_GRAY
rightPanel.background = Color.DARK_GRAY
topBar.background = Color.DARK_GRAY
} else {
leftPanel.background = Constants.DEFAULT_SWING_BACKGROUND_COLOR
rightPanel.background = Constants.DEFAULT_SWING_BACKGROUND_COLOR
topBar.background = Constants.DEFAULT_SWING_BACKGROUND_COLOR
}
}
// Buttons are almost the same, to avoid code duplication
// I created an abstract button
private fun <T : AbstractButton> createButtonWithIcon(
button: T,
iconArg: ImageIcon,
size: Int,
action: () -> Unit
): T {
val resizedIcon = ImageIcon(iconArg.image.getScaledInstance(size, size, Image.SCALE_SMOOTH))
return button.apply {
icon = resizedIcon
isContentAreaFilled = false // make the button transparent
isBorderPainted = false // remove the border
isFocusPainted = false // remove the focus highlight
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
addActionListener {
action()
}
}
}
private fun createButton(icon: ImageIcon, size: Int, action: () -> Unit) =
createButtonWithIcon(JButton(), icon, size, action)
private fun createToggleButton(icon: ImageIcon, size: Int, action: () -> Unit) =
createButtonWithIcon(JToggleButton(), icon, size, action)
fun getPanel(): JSplitPane {
return topBar
}
// not applicable here
override fun onShowHiddenFilesChanged(newShowHiddenFiles: Boolean) { }
// not applicable here
override fun onViewModeChanged(newViewMode: ViewMode) { }
private fun refreshUIComponents() {
leftPanel.revalidate()
leftPanel.repaint()
rightPanel.revalidate()
rightPanel.repaint()
}
override fun onColorThemeChanged(newColorTheme: ColorTheme) {
// remove all components and recreate the panel
leftPanel.removeAll()
rightPanel.removeAll()
configurePanel()
// update subviews
addressBarView.updateView()
filterPanel.updateView()
refreshUIComponents()
}
override fun onLanguageChanged(newLanguage: Language) { }
}
| 0 | Kotlin | 0 | 0 | 28f2648fefe1662dfe607d47d170a4beb46ccd3a | 7,149 | DirExplorer | Apache License 2.0 |
reaktive/src/commonTest/kotlin/com/badoo/reaktive/observable/ObservableToObservableTests.kt | badoo | 174,194,386 | false | null | package com.badoo.reaktive.observable
import com.badoo.reaktive.base.SourceTests
import com.badoo.reaktive.base.SourceTestsImpl
import com.badoo.reaktive.test.base.assertDisposed
import com.badoo.reaktive.test.observable.TestObservable
import com.badoo.reaktive.test.observable.assertComplete
import com.badoo.reaktive.test.observable.test
import kotlin.test.Ignore
import kotlin.test.Test
interface ObservableToObservableTests : SourceTests {
@Test
fun completes_WHEN_upstream_is_completed()
@Test
fun disposes_downstream_disposable_WHEN_upstream_completed()
}
@Ignore
class ObservableToObservableTestsImpl(
transform: Observable<*>.() -> Observable<*>
) : ObservableToObservableTests, SourceTests by SourceTestsImpl(TestObservable<Nothing>(), { transform().test() }) {
private val upstream = TestObservable<Nothing>()
private val observer = upstream.transform().test()
override fun completes_WHEN_upstream_is_completed() {
upstream.onComplete()
observer.assertComplete()
}
override fun disposes_downstream_disposable_WHEN_upstream_completed() {
upstream.onComplete()
observer.assertDisposed()
}
}
| 8 | null | 58 | 956 | c712c70be2493956e7057f0f30199994571b3670 | 1,185 | Reaktive | Apache License 2.0 |
svverif/01-arbiter/src/main/kotlin/ArbiterInterface.kt | frwang96 | 416,809,961 | false | null | /*
* SPDX-License-Identifier: Apache-2.0
*/
@file:Verik
import io.verik.core.*
class ArbiterInterface(
@In var clk: Boolean
) : ModuleInterface() {
var grant: Ubit<`2`> = nc()
var request: Ubit<`2`> = nc()
var reset: Boolean = nc()
@Make
val cb = ArbiterClockingBlock(posedge(clk), request, grant)
@Make
val test_port = ArbiterTestPort(cb, reset)
@Make
val dut_port = ArbiterDutPort(request, reset, clk, grant)
class ArbiterClockingBlock(
override val event: Event,
@Out var request: Ubit<`2`>,
@In var grant: Ubit<`2`>
) : ClockingBlock()
class ArbiterTestPort(
val cb: ArbiterClockingBlock,
@Out var reset: Boolean
) : ModulePort()
class ArbiterDutPort(
@In var request: Ubit<`2`>,
@In var reset: Boolean,
@In var clk: Boolean,
@Out var grant: Ubit<`2`>
) : ModulePort()
}
| 0 | Kotlin | 1 | 5 | 9a0f5f79b824e69a33dc4f9717d3b9e3ed103180 | 923 | verik-examples | Apache License 2.0 |
src/main/java/zd/zero/waifu/motivator/plugin/personality/Wendi.kt | anazari96 | 308,873,487 | true | {"Kotlin": 195582, "Java": 60287, "CSS": 538, "HTML": 283, "Shell": 80} | package zd.zero.waifu.motivator.plugin.personality
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.util.messages.MessageBusConnection
import zd.zero.waifu.motivator.plugin.motivation.event.MotivationEvent
import zd.zero.waifu.motivator.plugin.motivation.event.MotivationEventListener
import zd.zero.waifu.motivator.plugin.motivation.event.MotivationEvents
import zd.zero.waifu.motivator.plugin.personality.core.IdlePersonalityCore
import zd.zero.waifu.motivator.plugin.personality.core.ResetCore
import zd.zero.waifu.motivator.plugin.personality.core.TaskPersonalityCore
import zd.zero.waifu.motivator.plugin.personality.core.emotions.EMOTIONAL_MUTATION_TOPIC
import zd.zero.waifu.motivator.plugin.personality.core.emotions.EMOTION_TOPIC
import zd.zero.waifu.motivator.plugin.personality.core.emotions.EmotionCore
import zd.zero.waifu.motivator.plugin.personality.core.emotions.EmotionalMutationAction
import zd.zero.waifu.motivator.plugin.personality.core.emotions.EmotionalMutationActionListener
import zd.zero.waifu.motivator.plugin.personality.core.emotions.EmotionalMutationType
import zd.zero.waifu.motivator.plugin.personality.core.emotions.Mood
import zd.zero.waifu.motivator.plugin.settings.PluginSettingsListener
import zd.zero.waifu.motivator.plugin.settings.WaifuMotivatorPluginState
import zd.zero.waifu.motivator.plugin.tools.AlarmDebouncer
import zd.zero.waifu.motivator.plugin.tools.toOptional
import java.util.Optional
// Waifu
// Emotion
// Notification
// Determination
// Interface
// %%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%% , , #@@@@&%%%%%%%%%%%%
// %%%%%%%%%%@@@@@@@@@@@& / @@@@%%%%%%%%
// %%%%%%%@@&%* . /%%%@@%%%%%
// %%%%%@%%%% %%%%%@%%%
// %%%@%%%% %%%%%@%
// %%%%%%% %%%%%%
// %%%%%. . ,%%%%
// %%%% %%%
// %%% @@@@@@@/&. @@@@@@@@@. %%
// %% .@@# @@ @@ # .@@ %%
// %. @# %% % @ , %, (%% @@ %%
// %. %@ #%%%%%%%%%%%% %%%%%%%%%%%%% @ %%
// %* # %%%%%%%%%%%%%%% %%%%%%%%%%%%%%%% & %%
// %# %%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%% @ %%
// %% %%%%%%%%%%%%%%%%%%( %%%%%%%%%%%%%%%%%% *%%
// %% . #%%%%%%%%%%%%%%%%%/ %%%%%%%%%%%%%%%%%% / #%%
// %% @ %%%%%%%%%%%%%%%%% ,%%%%%%%%%%%%%%%% %%%
// %%* %%%%%%%%%%%%%%% %%%%%%%%%%%%%% %%%
// %%% %%%%%%%%%%. .%%%%%%%%/ #%%%
// %%% %%%%
// %%%( ........ ..........%%%%
// %%%% .......... ...... %%%%%
// %%%%% /%%%%%
// %%%%%* ,(((*****************((( %%%%%%
// %%%%%%. (((********************/( %%%%%%%
// %%%%%%%/ (**********************( ,%%%%%%%%
// %%%%%%%%%% (*****...............** /%%%%%%%%%%%
// %%%%%%%%%%%%%% (.................. *%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%. ,/,........ %%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%* #%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%.. ....,%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%....... .........(%%%%%%%%%%%%%%%%%%%%%%%%%
object Wendi : Disposable, EmotionalMutationActionListener {
private lateinit var messageBusConnection: MessageBusConnection
private lateinit var emotionCore: EmotionCore
private val taskPersonalityCore = TaskPersonalityCore()
private val idlePersonalityCore = IdlePersonalityCore()
private val resetCore = ResetCore()
private const val DEBOUNCE_INTERVAL = 80
private val singleEventDebouncer = AlarmDebouncer<MotivationEvent>(DEBOUNCE_INTERVAL)
private val idleEventDebouncer = AlarmDebouncer<MotivationEvent>(DEBOUNCE_INTERVAL)
fun initialize() {
if (this::messageBusConnection.isInitialized.not()) {
messageBusConnection = ApplicationManager.getApplication().messageBus.connect()
emotionCore = EmotionCore(WaifuMotivatorPluginState.getPluginState())
messageBusConnection.subscribe(
PluginSettingsListener.PLUGIN_SETTINGS_TOPIC,
PluginSettingsListener { newPluginState -> [email protected] = emotionCore.updateConfig(newPluginState) }
)
messageBusConnection.subscribe(EMOTIONAL_MUTATION_TOPIC, this)
messageBusConnection.subscribe(
MotivationEventListener.TOPIC,
MotivationEventListener { motivationEvent ->
when (motivationEvent.type) {
MotivationEvents.IDLE ->
idleEventDebouncer.debounceAndBuffer(motivationEvent) {
consumeEvents(it)
}
else -> singleEventDebouncer.debounce {
consumeEvent(motivationEvent)
}
}
}
)
}
}
val currentMood: Optional<Mood>
get() = if (this::emotionCore.isInitialized) emotionCore.currentMood.toOptional()
else Optional.empty()
private fun consumeEvents(bufferedMotivationEvents: List<MotivationEvent>) {
val emotionalState = emotionCore.deriveMood(bufferedMotivationEvents.first())
bufferedMotivationEvents.forEach { motivationEvent -> reactToEvent(motivationEvent, emotionalState) }
}
private fun consumeEvent(motivationEvent: MotivationEvent) {
val currentMood = emotionCore.deriveMood(motivationEvent)
reactToEvent(motivationEvent, currentMood)
publishMood(currentMood)
}
override fun onAction(emotionalMutationAction: EmotionalMutationAction) {
val mutatedMood = emotionCore.mutateMood(emotionalMutationAction)
reactToMutation(emotionalMutationAction)
publishMood(mutatedMood)
}
private fun reactToMutation(
emotionalMutationAction: EmotionalMutationAction
) {
if (emotionalMutationAction.type == EmotionalMutationType.RESET)
resetCore.processMutationEvent(emotionalMutationAction)
}
private fun publishMood(currentMood: Mood) {
ApplicationManager.getApplication().messageBus
.syncPublisher(EMOTION_TOPIC)
.onDerivedMood(currentMood)
}
private fun reactToEvent(motivationEvent: MotivationEvent, emotionalState: Mood) {
when (motivationEvent.type) {
MotivationEvents.TEST,
MotivationEvents.TASK -> taskPersonalityCore.processMotivationEvent(motivationEvent, emotionalState)
MotivationEvents.IDLE -> idlePersonalityCore.processMotivationEvent(motivationEvent, emotionalState)
else -> {
}
}
}
override fun dispose() {
if (this::messageBusConnection.isInitialized) {
messageBusConnection.dispose()
singleEventDebouncer.dispose()
idleEventDebouncer.dispose()
}
}
}
| 0 | Kotlin | 0 | 0 | 55db302c1e0bc47e9893370a1c36dff98de61207 | 8,247 | waifu-motivator-plugin | MIT License |
build-logic/convention/src/main/kotlin/com/yugyd/buildlogic/convention/buildtype/BuildTypeAndroidApplicationPlugin.kt | Yugyd | 685,349,849 | false | {"Kotlin": 869405, "FreeMarker": 22968, "Fluent": 18} | /*
* Copyright 2024 Roman Likhachev
*
* 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.yugyd.buildlogic.convention.buildtype
import com.android.build.api.dsl.ApplicationExtension
import com.android.build.api.variant.ApplicationAndroidComponentsExtension
import com.yugyd.buildlogic.convention.core.ANDROID_APPLICATION_ALIAS
import com.yugyd.buildlogic.convention.core.checkPlugin
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
class BuildTypeAndroidApplicationPlugin : Plugin<Project> {
companion object {
private val ACTIVE_PRODUCT_FLAVOR_VARIANTS = arrayOf("debug", "staging", "release")
}
override fun apply(target: Project) {
with(target) {
checkPlugin(ANDROID_APPLICATION_ALIAS)
extensions.configure<ApplicationExtension> {
configureBuildTypes()
disableUnusedProductFlavorVariants()
}
}
}
private fun Project.disableUnusedProductFlavorVariants() {
// https://developer.android.com/build/build-variants#filter-variants
extensions.configure<ApplicationAndroidComponentsExtension> {
beforeVariants { variantBuilder ->
if (!ACTIVE_PRODUCT_FLAVOR_VARIANTS.contains(variantBuilder.name)) {
variantBuilder.enable = false
}
}
}
}
}
| 0 | Kotlin | 1 | 8 | e803def7e9acbd6648c67751a7d3e3a32a6fcf9f | 1,958 | quiz-platform | Apache License 2.0 |
feature/scrobble/src/main/java/com/mataku/scrobscrob/scrobble/ui/molecule/TrackAlbum.kt | mataku | 99,928,377 | false | null | package com.mataku.scrobscrob.scrobble.ui.molecule
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.mataku.scrobscrob.core.entity.TrackAlbumInfo
import com.mataku.scrobscrob.core.entity.imageUrl
import com.mataku.scrobscrob.scrobble.R
import com.mataku.scrobscrob.ui_common.SunsetTextStyle
import com.mataku.scrobscrob.ui_common.style.SunsetThemePreview
@Composable
fun TrackAlbum(
album: TrackAlbumInfo
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
Text(
text = stringResource(id = R.string.label_track_album),
style = SunsetTextStyle.h7
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
) {
val imageUrl = album.imageList.imageUrl()
val height = 80.dp
AsyncImage(
model = imageUrl ?: R.drawable.no_image,
contentDescription = "Album artwork",
modifier = Modifier
.size(height)
)
Spacer(modifier = Modifier.width(16.dp))
Column(
modifier = Modifier
.wrapContentWidth()
.height(height),
verticalArrangement = Arrangement.Center
) {
Text(
text = album.title,
modifier = Modifier.wrapContentSize(),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = SunsetTextStyle.body1.copy(
fontWeight = FontWeight.Bold
)
)
Spacer(modifier = Modifier.size(4.dp))
Text(
text = album.artist,
modifier = Modifier.wrapContentSize(),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = SunsetTextStyle.body2
)
}
}
}
}
@Preview(showBackground = true)
@Composable
private fun TrackAlbumPreview() {
SunsetThemePreview() {
Surface {
TrackAlbum(
album = TrackAlbumInfo(
artist = "Perfume",
title = "セラミックガール",
imageList = emptyList(),
)
)
}
}
}
| 2 | Kotlin | 1 | 5 | 2041f94c43365caaef5389dd07a613a4f1c3b34b | 2,967 | SunsetScrob | Apache License 2.0 |
core/src/main/kotlin/com/gdgchicagowest/windycitydevcon/features/sessiondetail/SessionDetailMvp.kt | rharter | 67,167,893 | false | null | package com.gdgchicagowest.windycitydevcon.features.sessiondetail
import com.gdgchicagowest.windycitydevcon.features.shared.Mvp
import com.gdgchicagowest.windycitydevcon.model.Session
import com.gdgchicagowest.windycitydevcon.model.Speaker
interface SessionDetailMvp {
interface View : Mvp.View {
fun showSessionDetail(session: Session)
fun showSpeakerInfo(speakers: Set<Speaker>)
}
interface Presenter : Mvp.Presenter<View> {
fun setSessionId(sessionId: String)
}
}
| 0 | Kotlin | 2 | 11 | ce1ca4ad4f3b696311325c896b9dc7888fb8d111 | 511 | windy-city-devcon-android | Apache License 2.0 |
src/rider/test/kotlin/com/jetbrains/rider/plugins/unreal/test/cases/integrationTests/UnrealLinkBase.kt | JetBrains | 163,069,146 | false | {"C++": 336883, "Kotlin": 167528, "C#": 118215, "Batchfile": 7961, "C": 4329} | @file:Suppress("JUnitTestCaseWithNoTests")
package com.jetbrains.rider.plugins.unreal.test.cases.integrationTests
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.fire
import com.jetbrains.rdclient.util.idea.waitAndPump
import com.jetbrains.rider.plugins.unreal.model.frontendBackend.ForceInstall
import com.jetbrains.rider.plugins.unreal.model.frontendBackend.InstallPluginDescription
import com.jetbrains.rider.plugins.unreal.model.frontendBackend.PluginInstallLocation
import com.jetbrains.rider.plugins.unreal.model.frontendBackend.rdRiderModel
import com.jetbrains.rider.projectView.solution
import com.jetbrains.rider.test.scriptingApi.waitPumping
import com.jetbrains.rider.test.unreal.UnrealTestLevelProject
import org.testng.annotations.AfterMethod
import java.time.Duration
open class UnrealLinkBase: UnrealTestLevelProject() {
@AfterMethod
override fun unrealCleanup() {
deleteRiderLink()
super.unrealCleanup()
}
protected fun installRiderLink(place: PluginInstallLocation, timeout: Duration = Duration.ofSeconds(240)) {
logger.info("Installing RiderLink in ${place.name}")
var riderLinkInstalled = false
project.solution.rdRiderModel.installPluginFinished.advise(Lifetime.Eternal) { riderLinkInstalled = true }
project.solution.rdRiderModel.installEditorPlugin.fire(
InstallPluginDescription(place, ForceInstall.Yes)
)
waitAndPump(timeout, { riderLinkInstalled }, { "RiderLink has not been installed" })
}
protected fun deleteRiderLink() {
project.solution.rdRiderModel.deletePlugin.fire()
waitPumping(Duration.ofSeconds(5))
}
} | 43 | C++ | 23 | 128 | 15c38f04f14f8a10abd6521da726ce831b76b1c5 | 1,643 | UnrealLink | Apache License 2.0 |
mobile-ui/src/main/java/org/buffer/android/boilerplate/ui/browse/BrowseAdapter.kt | bufferapp | 114,655,619 | false | null | package org.buffer.android.boilerplate.ui.browse
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import org.buffer.android.boilerplate.ui.R
import org.buffer.android.boilerplate.ui.model.BufferooViewModel
import javax.inject.Inject
class BrowseAdapter @Inject constructor(): RecyclerView.Adapter<BrowseAdapter.ViewHolder>() {
var bufferoos: List<BufferooViewModel> = arrayListOf()
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val bufferoo = bufferoos[position]
holder.nameText.text = bufferoo.name
holder.titleText.text = bufferoo.title
Glide.with(holder.itemView.context)
.load(bufferoo.avatar)
.apply(RequestOptions.circleCropTransform())
.into(holder.avatarImage)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater
.from(parent.context)
.inflate(R.layout.item_bufferoo, parent, false)
return ViewHolder(itemView)
}
override fun getItemCount(): Int {
return bufferoos.size
}
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var avatarImage: ImageView
var nameText: TextView
var titleText: TextView
init {
avatarImage = view.findViewById(R.id.image_avatar)
nameText = view.findViewById(R.id.text_name)
titleText = view.findViewById(R.id.text_title)
}
}
} | 9 | null | 53 | 981 | 0f20a7bc6fa7fca5a0c2453aeb2bf2ef29214f7d | 1,748 | android-clean-architecture-mvi-boilerplate | MIT License |
parser/src/main/kotlin/gay/pizza/pork/parser/ParserBase.kt | GayPizzaSpecifications | 680,636,847 | false | {"Kotlin": 357342} | package gay.pizza.pork.parser
import gay.pizza.pork.ast.gen.Node
import gay.pizza.pork.ast.gen.NodeParser
import gay.pizza.pork.ast.gen.NodeType
import gay.pizza.pork.tokenizer.*
abstract class ParserBase(source: TokenSource, val attribution: NodeAttribution) : NodeParser {
val source: TokenSource = if (source is ParserAwareTokenSource) {
source
} else {
LazySkippingTokenSource(source, TokenType.ParserIgnoredTypes)
}
@Suppress("NOTHING_TO_INLINE")
protected inline fun <T: Node> produce(type: NodeType, noinline block: () -> T): T =
attribution.produce(type, block)
@Suppress("NOTHING_TO_INLINE")
protected inline fun <T: Node> expect(type: NodeType, vararg tokenTypes: TokenType, noinline block: (Token) -> T): T =
produce(type) {
block(expect(*tokenTypes))
}
protected fun <T> collect(
peeking: TokenType,
consuming: TokenType? = null,
read: () -> T
): List<T> {
val items = mutableListOf<T>()
while (!peek(peeking)) {
val item = read()
if (consuming != null) {
if (!peek(peeking)) {
expect(consuming)
}
}
items.add(item)
}
return items
}
protected fun <T> oneAndContinuedBy(separator: TokenType, read: () -> T): List<T> {
val items = mutableListOf<T>()
items.add(read())
while (peek(separator)) {
expect(separator)
items.add(read())
}
return items
}
protected fun peek(vararg types: TokenType): Boolean {
val token = peek()
return types.contains(token.type)
}
protected fun next(type: TokenType): Boolean {
return if (peek(type)) {
expect(type)
true
} else false
}
protected fun expect(vararg types: TokenType): Token {
val token = next()
if (!types.contains(token.type)) {
expectedTokenError(token, *types)
}
return token
}
protected fun <T: Node> expect(vararg types: TokenType, consume: (Token) -> T): T =
consume(expect(*types))
protected fun expectedTokenError(token: Token, vararg types: TokenType): Nothing {
throw ExpectedTokenError(token, token.sourceIndex, *types)
}
protected fun next(): Token {
val token = source.next()
attribution.push(token)
return token
}
protected fun peek(): Token = source.peek()
protected fun peek(ahead: Int): TokenType = source.peekTypeAhead(ahead)
protected fun peek(ahead: Int, vararg types: TokenType): Boolean = types.contains(source.peekTypeAhead(ahead))
}
| 0 | Kotlin | 1 | 0 | 9338b01b4832f838bda54cedb54893a13f37f418 | 2,478 | pork | MIT License |
app/src/main/java/com/mundocrativo/javier/solosonido/model/QueueObj.kt | Javierenrique00 | 293,379,415 | false | null | package com.mundocrativo.javier.solosonido.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class QueueObj(
@PrimaryKey(autoGenerate = true) val id:Long,
val queueName:String
) | 0 | Kotlin | 0 | 0 | 108eeba060b720d6809b152759e73ef72a99c3c8 | 217 | grabwaves | Apache License 2.0 |
collaboration-suite-phone-ui/src/main/java/com/kaleyra/collaboration_suite_phone_ui/drawables/AnimatedRedBorderDrawable.kt | Bandyer | 337,367,845 | false | null | /*
* Copyright 2021-2022 Bandyer @ https://www.bandyer.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bandyer.sdk_design.drawables
import android.graphics.*
import android.graphics.Paint.ANTI_ALIAS_FLAG
import android.graphics.Paint.Style.STROKE
import android.graphics.PathDashPathEffect.Style.ROTATE
import android.graphics.drawable.Drawable
import android.util.Property
/**
* @suppress
* Red Bordered rectangle drawable animated
* @property width Int
* @property height Int
* @property linePaint Paint
* @property length Float
* @property dotPaint Paint
* @property rectPath Path
* @property pathDot Path
* @property initialPhase Float
* @constructor
*/
class AnimatedRedBorderDrawable(borderSize: Float, val width: Int, val height: Int) : Drawable() {
var dotProgress = 0f
set(value) {
field = value.coerceIn(0f, 1f)
callback?.invalidateDrawable(this)
}
private val linePaint = Paint(ANTI_ALIAS_FLAG).apply {
style = STROKE
strokeWidth = borderSize
color = Color.RED
}
private val length by lazy {
val pathMeasure = PathMeasure()
pathMeasure.setPath(rectPath, false)
pathMeasure.length
}
private val dotPaint = Paint(ANTI_ALIAS_FLAG).apply {
style = STROKE
strokeWidth = borderSize
shader = LinearGradient(0f, 0f, 0f, height.toFloat(), Color.RED, Color.parseColor("#8B0000"), Shader.TileMode.CLAMP)
}
private val rectPath = Path().apply {
val rect = RectF(0f, 0f, width.toFloat(), height.toFloat())
addRect(rect, Path.Direction.CW)
}
private val pathDot = Path().apply {
val rect = RectF(0f, 0f, length, borderSize)
addRect(rect, Path.Direction.CW)
}
private val initialPhase by lazy(LazyThreadSafetyMode.NONE) {
(1f - (1f / (2 * 1))) * length
}
override fun draw(canvas: Canvas) {
canvas.drawPath(rectPath, linePaint)
val phase = initialPhase + dotProgress * length * 1
dotPaint.pathEffect = PathDashPathEffect(pathDot, length, phase, ROTATE)
canvas.drawPath(rectPath, dotPaint)
}
override fun setAlpha(alpha: Int) {
linePaint.alpha = alpha
dotPaint.alpha = alpha
}
override fun getOpacity() = PixelFormat.TRANSLUCENT
override fun setColorFilter(colorFilter: ColorFilter?) {
linePaint.colorFilter = colorFilter
dotPaint.colorFilter = colorFilter
}
override fun getIntrinsicWidth() = width
override fun getIntrinsicHeight() = height
object DOT_PROGRESS : Property<AnimatedRedBorderDrawable, Float>(Float::class.java, "dotProgress") {
override fun set(drawable: AnimatedRedBorderDrawable, dotProgress: Float) {
drawable.dotProgress = dotProgress
}
override fun get(drawable: AnimatedRedBorderDrawable) = drawable.dotProgress
}
} | 1 | null | 1 | 2 | 25aba4362ef436a7ed6cdecbcdcee94be6239bf9 | 3,457 | Bandyer-Android-Design | Apache License 2.0 |
data/src/main/kotlin/team/mobileb/opgg/data/mapper/UtilsMapper.kt | OPGG-HACKTHON | 391,351,999 | false | null | package team.mobileb.opgg.data.mapper
import team.mobileb.opgg.data.model.PositionInfoResponse
import team.mobileb.opgg.data.model.PositionResultResponse
import team.mobileb.opgg.domain.model.PositionInfo
import team.mobileb.opgg.domain.model.PositionResult
private fun positionResultResponseToDomain(response: PositionResultResponse) = PositionResult(
code = response.code,
name = response.name
)
fun PositionInfoResponse.toDomain() = PositionInfo(
code = code,
message = message,
result = result.map(::positionResultResponseToDomain),
responseTime = responseTime
)
| 0 | Kotlin | 1 | 23 | 26036b3a9e38b3e2e127746dcda733b108138e61 | 594 | mobile-b-android | MIT License |
remote-messaging/remote-messaging-api/src/main/java/com/duckduckgo/remote/messaging/api/MessageActionMapperPlugin.kt | duckduckgo | 78,869,127 | false | {"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784} | /*
* Copyright (c) 2023 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.remote.messaging.api
interface MessageActionMapperPlugin {
fun evaluate(jsonMessageAction: JsonMessageAction): Action?
}
data class JsonMessageAction(
val type: String,
val value: String,
val additionalParameters: Map<String, String>?,
)
sealed class JsonActionType(val jsonValue: String) {
object URL : JsonActionType("url")
object PLAYSTORE : JsonActionType("playstore")
object DEFAULT_BROWSER : JsonActionType("defaultBrowser")
object DISMISS : JsonActionType("dismiss")
object APP_TP_ONBOARDING : JsonActionType("atpOnboarding")
object SHARE : JsonActionType("share")
}
| 67 | Kotlin | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 1,239 | Android | Apache License 2.0 |
src/main/kotlin/com/johngachihi/assignment/soap2/models/Student.kt | johnGachihi | 315,207,408 | false | null | package com.johngachihi.assignment.soap2.models
import javax.persistence.*
@Entity
data class Student(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
val id: Int?,
val name: String,
val email: String,
val phoneNumber: String,
val address: String,
val entryPoints: String
) | 0 | Kotlin | 0 | 0 | be6ba8173eef0181a845676b7aec429b7af7a615 | 311 | DistObjs-SoapProducer | Apache License 2.0 |
app/src/main/java/com/cmgapps/android/curriculumvitae/ui/info/InfoSheet.kt | chrimaeon | 349,755,471 | false | null | /*
* Copyright (c) 2021. <NAME> <<EMAIL>>
*
* 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.cmgapps.android.curriculumvitae.ui.info
import android.net.Uri
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.content.pm.PackageInfoCompat
import com.cmgapps.android.curriculumvitae.R
import com.cmgapps.android.curriculumvitae.components.WebViewDialog
import com.cmgapps.android.curriculumvitae.util.ThemedPreview
import com.cmgapps.common.curriculumvitae.CopyRightText
import com.google.accompanist.insets.LocalWindowInsets
import com.google.accompanist.insets.rememberInsetsPaddingValues
@Composable
fun InfoSheet(
modifier: Modifier = Modifier,
onOpenWebsite: (Uri) -> Unit
) {
var ossDialogOpen by remember { mutableStateOf(false) }
var oflDialogOpen by remember { mutableStateOf(false) }
val strokeColor = MaterialTheme.colors.onSurface
Column(
modifier
.fillMaxWidth()
.drawBehind {
val length = 16.dp.toPx()
val paddingTop = 14.dp.toPx()
drawLine(
strokeColor,
Offset(size.width / 2 - length, paddingTop),
Offset(size.width / 2 + length, paddingTop),
strokeWidth = 4.dp.toPx(),
cap = StrokeCap.Round,
alpha = 0.2f
)
}
.padding(
rememberInsetsPaddingValues(
insets = LocalWindowInsets.current.navigationBars,
additionalTop = 24.dp,
additionalEnd = 24.dp,
additionalBottom = 24.dp
)
)
) {
Text(
text = stringResource(id = R.string.app_name),
style = MaterialTheme.typography.h5,
modifier = Modifier.padding(start = 24.dp),
)
val context = LocalContext.current
with(context.packageManager.getPackageInfo(context.packageName, 0)) {
Text(
text = stringResource(
id = R.string.version,
versionName,
PackageInfoCompat.getLongVersionCode(this)
),
modifier = Modifier.padding(start = 24.dp),
)
}
Spacer(Modifier.height(24.dp))
Text(
text = CopyRightText,
modifier = Modifier.padding(start = 24.dp),
)
val uri = Uri.parse(stringResource(id = R.string.info_cmgapps_href))
InfoTextButton(
text = stringResource(id = R.string.info_cmgapps_link),
onClick = { onOpenWebsite(uri) },
)
InfoTextButton(
text = stringResource(id = R.string.info_oss_licenses),
onClick = { ossDialogOpen = true }
)
InfoTextButton(
text = stringResource(id = R.string.info_open_font_licenses),
onClick = { oflDialogOpen = true }
)
InfoTextButton(
text = stringResource(id = R.string.project_on_github),
onClick = {
onOpenWebsite(
Uri.parse("https://github.com/chrimaeon/curriculumvitae")
)
}
)
}
if (ossDialogOpen) {
WebViewDialog(
url = "licenses.html".asAssetFileUrl(),
onDismissRequest = { ossDialogOpen = false }
)
}
if (oflDialogOpen) {
WebViewDialog(
url = "ofl-licenses.html".asAssetFileUrl(),
onDismissRequest = { oflDialogOpen = false },
)
}
}
private fun String.asAssetFileUrl() = "file:///android_asset/$this"
@Composable
private fun InfoTextButton(
text: String,
onClick: () -> Unit,
) {
TextButton(
modifier = Modifier.padding(start = 16.dp),
colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colors.primaryVariant),
onClick = onClick,
) {
Text(text)
}
}
@Preview()
@Composable()
fun PreviewInfoSheet() {
ThemedPreview {
InfoSheet(onOpenWebsite = {})
}
}
| 1 | Kotlin | 2 | 4 | 86f5d9bf772f409e69248fe47289c32bf6a28ec8 | 5,595 | curriculumvitae | Apache License 2.0 |
app/src/main/java/at/opnote/ui/base/BaseFragment.kt | fly8899 | 456,671,546 | false | null | package at.opnote.ui.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.doOnAttach
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import at.opnote.analytics.OpAnalytics
import at.opnote.util.extensions.applyNavigationBarMarginConsuming
import at.opnote.util.extensions.hideKeyboard
import at.opnote.util.extensions.reactToImeConsuming
import javax.inject.Inject
abstract class BaseFragment<VB : ViewBinding> : Fragment() {
private var _binding: VB? = null
val binding: VB
get() = _binding!!
@Inject
lateinit var opAnalytics: OpAnalytics
abstract fun setViewBinding(
inflater: LayoutInflater,
container: ViewGroup?
): VB
open val reactToIme: Boolean = true
open val applyNavigationInsetsPadding = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) return
opAnalytics.trackScreenCreation(this)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = setViewBinding(inflater, container)
if (applyNavigationInsetsPadding) {
binding.root.doOnAttach {
it.applyNavigationBarMarginConsuming()
}
}
if (reactToIme) {
binding.root.doOnAttach {
it.reactToImeConsuming()
}
}
return _binding!!.root
}
override fun onPause() {
super.onPause()
hideKeyboard()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
fun trackContent(action: String) {
opAnalytics.trackContent(action)
}
} | 0 | Kotlin | 0 | 0 | a5997cb2031ea57f6a16c4ab8cd203e51838c0ce | 1,885 | OpNote | Apache License 2.0 |
features/todo/src/main/java/com/hrudhaykanth116/todo/ui/components/TodoListItemUI.kt | hrudhaykanth116 | 300,963,083 | false | {"Kotlin": 456464} | package com.hrudhaykanth116.todo.ui.components
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.hrudhaykanth116.core.common.resources.Dimens
import com.hrudhaykanth116.core.common.utils.compose.MyPreview
import com.hrudhaykanth116.core.data.models.toUIText
import com.hrudhaykanth116.core.ui.components.AppCard
import com.hrudhaykanth116.core.ui.components.AppClickableIcon
import com.hrudhaykanth116.core.ui.components.AppText
import com.hrudhaykanth116.core.ui.components.CenteredColumn
import com.hrudhaykanth116.core.ui.components.AppCircularImage
import com.hrudhaykanth116.core.ui.models.ImageHolder
import com.hrudhaykanth116.core.ui.models.toImageHolder
import com.hrudhaykanth116.todo.R
import com.hrudhaykanth116.todo.ui.models.ToDoTaskUIState
import com.hrudhaykanth116.todo.ui.models.TodoUIModel
import com.hrudhaykanth116.core.R as CoreR
@Composable
fun TodoListItemUI(
toDoTaskUIState: ToDoTaskUIState,
modifier: Modifier = Modifier,
onRemoveClicked: () -> Unit = {}
) {
// TODO: May be this could be hoisted. Savable because, state retained on scroll or more.
var isExpanded by rememberSaveable {
mutableStateOf(false)
}
val height by animateDpAsState(
if (isExpanded) 120.dp else 60.dp,
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
)
AppCard(
// modifier = Modifier.fillMaxWidth().height(80.dp).padding(8.dp),
modifier = modifier
// .height(
// height.coerceAtLeast(60.dp) // Makes sure at least 60dp is set.
// )
.fillMaxWidth()
// .animateContentSize(
// animationSpec = tween(100)
// )
// .padding(8.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(Dimens.DEFAULT_PADDING)
) {
if (toDoTaskUIState.showCategoryIcon) {
// Category image.
AppCircularImage(
image = CoreR.drawable.profile_icon.toImageHolder()
)
}
Column(
modifier = Modifier.weight(1f)
) {
AppText(
uiText = toDoTaskUIState.data.title.text.toUIText(),
maxLines = if (isExpanded) Int.MAX_VALUE else 2,
style = MaterialTheme.typography.bodyLarge,
overflow = if (isExpanded) TextOverflow.Visible else TextOverflow.Ellipsis,
)
if(isExpanded){
Spacer(modifier = Modifier.height(4.dp))
AppText(
uiText = toDoTaskUIState.data.description.text.toUIText(),
// TODO: Modify according to final ui
maxLines = if (isExpanded) Int.MAX_VALUE else 3,
overflow = if (isExpanded) TextOverflow.Visible else TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodyMedium,
)
}
}
Spacer(modifier = Modifier.width(8.dp))
AppClickableIcon(
imageHolder = ImageHolder.LocalDrawableResource(
if(isExpanded) CoreR.drawable.ic_collapse_arrow else CoreR.drawable.ic_expand_arrow
),
contentDescriptionUIText = "Expand".toUIText(),
onClick = {
isExpanded = !isExpanded
}
)
AppClickableIcon(
imageHolder = ImageHolder.LocalDrawableResource(
CoreR.drawable.ic_delete
),
contentDescriptionUIText = "Delete".toUIText(),
onClick = onRemoveClicked
)
}
}
}
@MyPreview
@Composable
fun TodoListItemUIPreview() {
CenteredColumn {
TodoListItemUI(
toDoTaskUIState = ToDoTaskUIState(
TodoUIModel(
"1",
TextFieldValue("Title"),
TextFieldValue("Description"),
)
),
modifier = Modifier
.height(80.dp)
.padding(horizontal = 10.dp),
)
// Spacer(modifier = Modifier.height(20.dp))
TodoListItemUI(
toDoTaskUIState = ToDoTaskUIState(
TodoUIModel(
"1",
TextFieldValue("Title"),
TextFieldValue("Description"),
)
),
modifier = Modifier
.height(80.dp)
.padding(horizontal = 10.dp),
)
}
} | 0 | Kotlin | 0 | 0 | 964a07bdcdaf5405c76c44823a4814cf800287ab | 5,656 | MAFET | MIT License |
ledger/src/main/kotlin/org/knowledger/ledger/storage/adapters/BlockStorageAdapter.kt | fakecoinbase | 282,563,487 | false | null | package org.knowledger.ledger.storage.adapters
import org.knowledger.ledger.crypto.Hash
import org.knowledger.ledger.database.ManagedSession
import org.knowledger.ledger.database.StorageElement
import org.knowledger.ledger.database.adapters.SchemaProvider
import org.knowledger.ledger.results.Outcome
import org.knowledger.ledger.results.deadCode
import org.knowledger.ledger.service.results.LoadFailure
import org.knowledger.ledger.storage.Block
import org.knowledger.ledger.storage.block.BlockImpl
import org.knowledger.ledger.storage.block.SABlockStorageAdapter
import org.knowledger.ledger.storage.block.SUBlockStorageAdapter
import org.knowledger.ledger.storage.block.StorageAwareBlock
internal class BlockStorageAdapter(
private val suBlockStorageAdapter: SUBlockStorageAdapter,
private val saBlockStorageAdapter: SABlockStorageAdapter
) : LedgerStorageAdapter<Block>,
SchemaProvider by suBlockStorageAdapter {
override fun store(
toStore: Block,
session: ManagedSession
): StorageElement =
when (toStore) {
is StorageAwareBlock ->
saBlockStorageAdapter.store(toStore, session)
is BlockImpl ->
suBlockStorageAdapter.store(toStore, session)
else -> deadCode()
}
override fun load(
ledgerHash: Hash, element: StorageElement
): Outcome<Block, LoadFailure> =
saBlockStorageAdapter.load(ledgerHash, element)
} | 0 | Kotlin | 0 | 0 | 8bc64987e1ab4d26663064da06393de6befc30ae | 1,459 | SeriyinslashKnowLedger | MIT License |
plugins/git-features-trainer/src/git4idea/ift/lesson/GitProjectHistoryLesson.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.ift.lesson
import com.intellij.diff.tools.util.SimpleDiffPanel
import com.intellij.ide.dnd.aware.DnDAwareTree
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.vcs.changes.VcsEditorTabFilesManager
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.SearchTextField
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.tree.TreeUtil
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.ui.filter.BranchFilterPopupComponent
import com.intellij.vcs.log.ui.filter.UserFilterPopupComponent
import com.intellij.vcs.log.ui.frame.MainFrame
import com.intellij.vcs.log.ui.frame.VcsLogCommitDetailsListPanel
import com.intellij.vcs.log.ui.table.GraphTableModel
import com.intellij.vcs.log.ui.table.VcsLogGraphTable
import git4idea.ift.GitLessonsBundle
import git4idea.ift.GitLessonsUtil.checkoutBranch
import git4idea.ift.GitLessonsUtil.highlightLatestCommitsFromBranch
import git4idea.ift.GitLessonsUtil.highlightSubsequentCommitsInGitLog
import git4idea.ift.GitLessonsUtil.resetGitLogWindow
import git4idea.ift.GitLessonsUtil.showWarningIfGitWindowClosed
import git4idea.ui.branch.dashboard.CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY
import git4idea.ui.branch.dashboard.SHOW_GIT_BRANCHES_LOG_PROPERTY
import training.dsl.*
import training.ui.LearningUiHighlightingManager
import java.awt.Rectangle
class GitProjectHistoryLesson : GitLesson("Git.ProjectHistory", GitLessonsBundle.message("git.project.history.lesson.name")) {
override val existedFile = "git/sphinx_cat.yml"
private val branchName = "feature"
private val textToFind = "sphinx"
private var showGitBranchesBackup: Boolean? = null
override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true)
override val lessonContent: LessonContext.() -> Unit = {
checkoutBranch("feature")
task("ActivateVersionControlToolWindow") {
text(GitLessonsBundle.message("git.project.history.open.git.window", action(it)))
stateCheck {
val toolWindowManager = ToolWindowManager.getInstance(project)
toolWindowManager.getToolWindow(ToolWindowId.VCS)?.isVisible == true
}
}
resetGitLogWindow()
prepareRuntimeTask l@{
val property = SHOW_GIT_BRANCHES_LOG_PROPERTY
val logUiProperties = VcsProjectLog.getInstance(project).mainLogUi?.properties ?: return@l
showGitBranchesBackup = logUiProperties[property]
logUiProperties[property] = true
}
task {
highlightLatestCommitsFromBranch(branchName)
}
task {
text(GitLessonsBundle.message("git.project.history.commits.tree.explanation"))
proceedLink()
}
task {
var selectionCleared = false
// todo: return highlighting of full tree node when IFT-234 will be resolved
triggerByPartOfComponent(highlightBorder = false) l@{ tree: DnDAwareTree ->
val path = TreeUtil.treePathTraverser(tree).find { it.getPathComponent(it.pathCount - 1).toString() == "HEAD_NODE" }
?: return@l null
val rect = tree.getPathBounds(path) ?: return@l null
Rectangle(rect.x, rect.y, rect.width, 0).also {
if (!selectionCleared) {
tree.clearSelection()
selectionCleared = true
}
}
}
}
task {
val logUiProperties = VcsProjectLog.getInstance(project).mainLogUi?.properties
val choice = if (logUiProperties == null || !logUiProperties[CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY]) 1 else 0
text(GitLessonsBundle.message("git.project.history.apply.branch.filter", choice))
text(GitLessonsBundle.message("git.project.history.click.head.tooltip", choice),
LearningBalloonConfig(Balloon.Position.above, 250))
triggerByUiComponentAndHighlight(false, false) { ui: BranchFilterPopupComponent ->
ui.currentText?.contains("HEAD") == true
}
showWarningIfGitWindowClosed()
}
task {
triggerByUiComponentAndHighlight { _: UserFilterPopupComponent -> true }
}
val meFilterText = VcsLogBundle.message("vcs.log.user.filter.me")
task {
text(GitLessonsBundle.message("git.project.history.apply.user.filter"))
text(GitLessonsBundle.message("git.project.history.click.filter.tooltip"),
LearningBalloonConfig(Balloon.Position.above, 0))
triggerByListItemAndHighlight { item ->
item.toString().contains(meFilterText)
}
showWarningIfGitWindowClosed()
}
task {
text(GitLessonsBundle.message("git.project.history.select.me", strong(meFilterText)))
triggerByUiComponentAndHighlight(false, false) { ui: UserFilterPopupComponent ->
ui.currentText?.contains(meFilterText) == true
}
restoreByUi(delayMillis = defaultRestoreDelay)
}
task {
text(GitLessonsBundle.message("git.project.history.apply.message.filter", code(textToFind), LessonUtil.rawEnter()))
triggerByUiComponentAndHighlight { ui: SearchTextField ->
(UIUtil.getParentOfType(MainFrame::class.java, ui) != null).also {
if (it) IdeFocusManager.getInstance(project).requestFocus(ui, true)
}
}
triggerByUiComponentAndHighlight(false, false) l@{ ui: VcsLogGraphTable ->
val model = ui.model as? GraphTableModel ?: return@l false
model.rowCount > 0 && model.getCommitMetadata(0).fullMessage.contains(textToFind)
}
showWarningIfGitWindowClosed()
}
task {
text(GitLessonsBundle.message("git.project.history.select.commit"))
highlightSubsequentCommitsInGitLog(0)
triggerByUiComponentAndHighlight(false, false) { ui: VcsLogGraphTable ->
ui.selectedRow == 0
}
restoreState {
val vcsLogUi = VcsProjectLog.getInstance(project).mainLogUi ?: return@restoreState false
vcsLogUi.filterUi.textFilterComponent.text == ""
}
showWarningIfGitWindowClosed()
}
// todo Find out why it's hard to collapse highlighted commit details
task {
text(GitLessonsBundle.message("git.project.history.commit.details.explanation"))
proceedLink()
triggerByUiComponentAndHighlight(highlightInside = false, usePulsation = true) { _: VcsLogCommitDetailsListPanel -> true }
}
task {
before {
LearningUiHighlightingManager.clearHighlights()
}
text(GitLessonsBundle.message("git.project.history.click.changed.file"))
triggerByFoundPathAndHighlight(highlightInside = true) { _, path ->
path.getPathComponent(path.pathCount - 1).toString().contains(".yml")
}
triggerByUiComponentAndHighlight(false, false) { _: SimpleDiffPanel -> true }
showWarningIfGitWindowClosed()
}
if (VcsEditorTabFilesManager.getInstance().shouldOpenInNewWindow) {
task("EditorEscape") {
text(GitLessonsBundle.message("git.project.history.close.diff", action(it)))
stateCheck { previous.ui?.isShowing != true }
}
}
text(GitLessonsBundle.message("git.project.history.invitation.to.commit.lesson"))
}
override fun onLessonEnd(project: Project, lessonPassed: Boolean) {
if (showGitBranchesBackup != null) {
val logUiProperties = VcsProjectLog.getInstance(project).mainLogUi?.properties ?: error("Failed to get MainVcsLogUiProperties")
logUiProperties[SHOW_GIT_BRANCHES_LOG_PROPERTY] = showGitBranchesBackup!!
}
}
} | 191 | null | 4372 | 13,319 | 4d19d247824d8005662f7bd0c03f88ae81d5364b | 7,740 | intellij-community | Apache License 2.0 |
app/src/main/java/com/kuneosu/mintoners/data/model/Match.kt | Kuneosu | 823,904,157 | false | {"Kotlin": 235754} | package com.kuneosu.mintoners.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import java.util.Date
@Entity(tableName = "matches")
@TypeConverters(Converters::class)
data class Match(
@PrimaryKey(autoGenerate = true) var matchNumber: Int = 0,
val matchName: String,
val matchDate: Date,
val matchPoint: String,
val matchCount: Int,
val matchType: String,
var matchPlayers: List<Player>,
var matchList: List<Game>,
var matchState: Int = 0
)
| 0 | Kotlin | 0 | 0 | 3a290dcc803aa1d5ce1ad300c7cb3789280b1c74 | 538 | Mintoners | MIT License |
skellig-test-step-processing-http/src/main/kotlin/org/skellig/teststep/processor/http/HttpRequestFactory.kt | skellig-framework | 263,021,995 | false | {"Kotlin": 1283314, "CSS": 525991, "Java": 270216, "FreeMarker": 66859, "HTML": 11313, "ANTLR": 6165} | package org.skellig.teststep.processor.http
import okhttp3.Credentials
import okhttp3.FormBody
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.skellig.teststep.processor.http.model.HttpMethodName
import org.skellig.teststep.processor.http.model.HttpRequestDetails
/**
* Class representing an HTTP request factory creating okhttp3 [Request] objects from [HttpRequestDetails].
*
* @property baseUrl The base URL for the requests.
*/
class HttpRequestFactory(private val baseUrl: String?) {
fun createRequest(httpRequestDetails: HttpRequestDetails): Request {
val builder = Request.Builder()
.url(createUrl(httpRequestDetails))
.method(httpRequestDetails.verb.toString(), getRequestBody(httpRequestDetails))
if (httpRequestDetails.formParams.isNotEmpty()) {
val formBody = FormBody.Builder()
httpRequestDetails.formParams.forEach { formBody.add(it.key, it.value ?: "") }
builder.post(formBody.build())
}
httpRequestDetails.username?.let {
builder.header("Authorization", Credentials.basic(httpRequestDetails.username, httpRequestDetails.password ?: ""))
}
httpRequestDetails.headers.forEach { builder.header(it.key, it.value ?: "") }
return builder.build()
}
private fun getRequestBody(httpRequestDetails: HttpRequestDetails): RequestBody? {
val mediaType = (httpRequestDetails.headers["Content-Type"] ?: "application/json").toMediaType()
val requestBody = httpRequestDetails.body?.toRequestBody(mediaType)
return if (httpRequestDetails.verb == HttpMethodName.POST) requestBody ?: "".toRequestBody(mediaType)
else requestBody
}
private fun createUrl(httpRequest: HttpRequestDetails): String {
val urlBuilder = (baseUrl + httpRequest.url).toHttpUrl().newBuilder()
return if (httpRequest.queryParams.isEmpty()) {
urlBuilder.build().toString()
} else {
httpRequest.queryParams.entries.forEach { urlBuilder.addQueryParameter(it.key, it.value) }
return urlBuilder.build().toString()
}
}
} | 8 | Kotlin | 0 | 3 | ed375268b0e444f1928f22f4ac27603e9d1fb66b | 2,300 | skellig-core | Apache License 2.0 |
sub_seminar002_example/app/src/main/java/com/sopt_nyh/sub_seminar002_example/adapter/MyFragmentSPAdapter.kt | Younanee | 151,179,124 | false | null | package com.sopt_nyh.sub_seminar002_example.adapter
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import com.sopt_nyh.sub_seminar002_example.MainFragment
import com.sopt_nyh.sub_seminar002_example.MapFragment
import com.sopt_nyh.sub_seminar002_example.MyPageFragment
class MyFragmentSPAdapter(fm : FragmentManager, val fCount : Int) : FragmentStatePagerAdapter(fm) {
override fun getItem(position: Int): Fragment? {
when(position){
0 -> return MainFragment()
1 -> {
val mapFragment : Fragment = MapFragment()
return mapFragment
}
2 -> return MyPageFragment()
else -> return null
}
}
override fun getCount(): Int = fCount
} | 0 | Kotlin | 0 | 0 | 813bf94da45f30389b9e9ff921154366048b1c21 | 840 | do_it_sopt_android_part | MIT License |
src/main/kotlin/world/cepi/kstom/Manager.kt | arslanarm | 334,777,044 | true | {"Kotlin": 59937} | package world.cepi.kstom
import net.minestom.server.MinecraftServer
import net.minestom.server.UpdateManager
import net.minestom.server.advancements.AdvancementManager
import net.minestom.server.adventure.bossbar.BossBarManager
import net.minestom.server.command.CommandManager
import net.minestom.server.data.DataManager
import net.minestom.server.event.GlobalEventHandler
import net.minestom.server.exception.ExceptionManager
import net.minestom.server.extensions.ExtensionManager
import net.minestom.server.gamedata.loottables.LootTableManager
import net.minestom.server.gamedata.tags.TagManager
import net.minestom.server.instance.InstanceManager
import net.minestom.server.instance.block.BlockManager
import net.minestom.server.listener.manager.PacketListenerManager
import net.minestom.server.monitoring.BenchmarkManager
import net.minestom.server.network.ConnectionManager
import net.minestom.server.recipe.RecipeManager
import net.minestom.server.scoreboard.TeamManager
import net.minestom.server.storage.StorageManager
import net.minestom.server.timer.SchedulerManager
import net.minestom.server.world.biomes.BiomeManager
/**
* Shorthand utilities for MinecraftServer
*/
public object Manager {
public val command: CommandManager
get() = MinecraftServer.getCommandManager()
public val block: BlockManager
get() = MinecraftServer.getBlockManager()
public val instance: InstanceManager
get() = MinecraftServer.getInstanceManager()
public val advancement: AdvancementManager
get() = MinecraftServer.getAdvancementManager()
public val packetListener: PacketListenerManager
get() = MinecraftServer.getPacketListenerManager()
public val recipe: RecipeManager
get() = MinecraftServer.getRecipeManager()
public val benchmark: BenchmarkManager
get() = MinecraftServer.getBenchmarkManager()
public val biome: BiomeManager
get() = MinecraftServer.getBiomeManager()
public val bossBar: BossBarManager
get() = MinecraftServer.getBossBarManager()
public val connection: ConnectionManager
get() = MinecraftServer.getConnectionManager()
public val data: DataManager
get() = MinecraftServer.getDataManager()
public val storage: StorageManager
get() = MinecraftServer.getStorageManager()
public val tag: TagManager
get() = MinecraftServer.getTagManager()
public val team: TeamManager
get() = MinecraftServer.getTeamManager()
public val update: UpdateManager
get() = MinecraftServer.getUpdateManager()
public val exception: ExceptionManager
get() = MinecraftServer.getExceptionManager()
public val lootTable: LootTableManager
get() = MinecraftServer.getLootTableManager()
public val extension: ExtensionManager
get() = MinecraftServer.getExtensionManager()
public val scheduler: SchedulerManager
get() = MinecraftServer.getSchedulerManager()
public val globalEvent: GlobalEventHandler
get() = MinecraftServer.getGlobalEventHandler()
} | 0 | Kotlin | 0 | 0 | d4ec51735991b5bc0a02bc1230f7316384a7eb1b | 3,089 | KStom | MIT License |
sqllin-dsl/src/commonMain/kotlin/com/ctrip/sqllin/dsl/sql/clause/HavingClause.kt | ctripcorp | 570,015,389 | false | null | /*
* Copyright (C) 2022 Ctrip.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ctrip.sqllin.dsl.sql.clause
import com.ctrip.sqllin.dsl.sql.statement.GroupBySelectStatement
import com.ctrip.sqllin.dsl.sql.statement.HavingSelectStatement
/**
* SQL 'HAVING' clause by select statement
* @author yaqiao
*/
internal class HavingClause<T>(val selectCondition: SelectCondition) : ConditionClause<T>(selectCondition) {
override val clauseName: String = "HAVING"
}
public infix fun <T> GroupBySelectStatement<T>.HAVING(condition: SelectCondition): HavingSelectStatement<T> =
appendToHaving(HavingClause(condition)).also {
container changeLastStatement it
} | 3 | null | 4 | 217 | 4872fddad7ad72f5f95e14ad831b3ebb7fc87d47 | 1,208 | SQLlin | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/Socks.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.Socks: ImageVector
get() {
if (_socks != null) {
return _socks!!
}
_socks = Builder(name = "Socks", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(11.998f, 4.0f)
curveToRelative(0.0f, -1.068f, 0.415f, -2.073f, 1.171f, -2.828f)
reflectiveCurveToRelative(1.761f, -1.172f, 2.829f, -1.172f)
horizontalLineToRelative(4.0f)
curveToRelative(2.204f, 0.0f, 3.999f, 1.793f, 4.0f, 3.999f)
horizontalLineToRelative(0.0f)
reflectiveCurveToRelative(-12.0f, 0.001f, -12.0f, 0.001f)
close()
moveTo(11.998f, 6.0f)
verticalLineToRelative(3.724f)
curveToRelative(0.001f, 0.251f, -0.091f, 0.491f, -0.26f, 0.675f)
lineToRelative(-3.344f, 3.667f)
curveToRelative(-2.109f, 2.636f, -1.796f, 6.469f, 0.696f, 8.544f)
curveToRelative(1.077f, 0.896f, 2.439f, 1.39f, 3.837f, 1.39f)
curveToRelative(1.835f, 0.0f, 3.544f, -0.821f, 4.663f, -2.222f)
lineToRelative(4.212f, -4.861f)
curveToRelative(1.418f, -1.637f, 2.198f, -3.731f, 2.197f, -5.897f)
verticalLineToRelative(-5.021f)
horizontalLineToRelative(-12.001f)
close()
moveTo(9.997f, 4.0f)
curveToRelative(0.0f, -1.493f, 0.547f, -2.898f, 1.537f, -4.0f)
horizontalLineToRelative(-2.533f)
curveToRelative(-1.068f, 0.0f, -2.073f, 0.416f, -2.829f, 1.172f)
reflectiveCurveToRelative(-1.171f, 1.76f, -1.171f, 2.828f)
horizontalLineToRelative(4.996f)
close()
moveTo(6.832f, 12.816f)
lineToRelative(3.167f, -3.479f)
lineToRelative(-0.002f, -3.337f)
horizontalLineToRelative(-4.996f)
verticalLineToRelative(3.724f)
curveToRelative(0.001f, 0.251f, -0.091f, 0.491f, -0.26f, 0.675f)
lineToRelative(-3.344f, 3.667f)
curveToRelative(-2.109f, 2.636f, -1.796f, 6.469f, 0.696f, 8.544f)
curveToRelative(1.077f, 0.896f, 2.439f, 1.39f, 3.837f, 1.39f)
curveToRelative(0.517f, 0.0f, 1.021f, -0.072f, 1.508f, -0.197f)
curveToRelative(-2.974f, -2.828f, -3.281f, -7.644f, -0.606f, -10.987f)
close()
}
}
.build()
return _socks!!
}
private var _socks: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,473 | icons | MIT License |
src/main/kotlin/br/com/erivelton/rest/pix/chave/dto/resposta/DadosContaResposta.kt | eriveltonluiz | 387,615,008 | true | {"Kotlin": 35704, "Smarty": 2172, "Dockerfile": 156} | package br.com.erivelton.rest.pix.chave.dto.resposta
import br.com.erivelton.pix.DadosConta
import br.com.erivelton.rest.pix.chave.enums.TipoContaBcb
class DadosContaResposta (
dadosConta: DadosConta
){
val instituicao: String? = dadosConta.instituicao
val agencia: String = dadosConta.agencia
val numero: String = dadosConta.numero
val tipoConta: TipoContaBcb = TipoContaBcb.valueOf(dadosConta.tipoContaBcb.name)
} | 0 | Kotlin | 0 | 0 | c63d8eb9eeb4a533261fdbb52ac3d83cd1e205fc | 437 | orange-talents-05-template-pix-keymanager-rest | Apache License 2.0 |
src/main/java/com/example/navigation/dsl/NavigationDSLFragmentTwo.kt | vshpyrka | 754,325,488 | false | {"Kotlin": 182512} | package com.example.navigation.dsl
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.navigation.R
import com.example.navigation.applyWindowInsets
import com.example.navigation.databinding.FragmentNavigationDSLTwoBinding
import com.example.navigation.getLoremIpsum
class NavigationDSLFragmentTwo : Fragment(R.layout.fragment_navigation_d_s_l_two) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val argument = arguments?.getString(nav_graph.args.id) ?: ""
val binding = FragmentNavigationDSLTwoBinding.bind(view)
binding.root.applyWindowInsets()
val text = "DSL Destination ARG - $argument"
binding.title.text = text
binding.button.setOnClickListener {
findNavController().navigate(
nav_graph.nested_graph
)
}
binding.text.text = getLoremIpsum()
}
}
| 0 | Kotlin | 0 | 0 | bf0d3e6ca9c31116a5ebb77576dc01b62c896e13 | 1,055 | android-navigation-example | Apache License 2.0 |
core/src/main/java/com/kurt/example/rickandmorty/core/di/CharactersModule.kt | kuuuurt | 199,823,122 | false | null | package com.kurt.example.rickandmorty.core.di
import com.kurt.example.rickandmorty.core.data.characters.CharactersRemoteSource
import com.kurt.example.rickandmorty.core.data.characters.CharactersRepositoryImpl
import com.kurt.example.rickandmorty.core.domain.repositories.CharactersRepository
import com.kurt.example.rickandmorty.core.framework.characters.remote.CharactersRemoteSourceImpl
import dagger.Binds
import dagger.Module
/**
* Copyright 2019, Kurt Renzo Acosta, All rights reserved.
*
* @author Kurt Renzo Acosta
* @since 08/05/2019
*/
@Module
abstract class CharactersModule {
@Binds
abstract fun provideCharactersRepository(charactersRepositoryImpl: CharactersRepositoryImpl): CharactersRepository
@Binds
abstract fun provideCharactersRemoteSource(charactersRemoteSourceImpl: CharactersRemoteSourceImpl): CharactersRemoteSource
} | 0 | Kotlin | 19 | 105 | 44bcf5bfe4646959c0bd0940a2d0881aa163ed3a | 865 | rick-and-morty-app | Apache License 2.0 |
storage/room/src/main/kotlin/dev/atick/storage/room/data/models/FallIncident.kt | atick-faisal | 609,303,624 | false | {"Kotlin": 207223} | package dev.atick.storage.room.data.models
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.*
@Entity(tableName = "falls")
data class FallIncident(
@ColumnInfo(name = "victim_name") val victimName: String,
@ColumnInfo(name = "high_risk") val highRisk: Boolean = false,
@ColumnInfo(name = "read_by_user") val readByUser: Boolean = false,
@PrimaryKey val timestamp: Long = Date().time
)
| 2 | Kotlin | 1 | 1 | 206235367c909b72d4339e686a1137f59f18d712 | 463 | Safety-Android | Apache License 2.0 |
platform/platform-impl/src/com/intellij/openapi/application/impl/BaseExpirableExecutorMixinImpl.kt | ingokegel | 72,937,917 | true | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.application.impl
import com.intellij.openapi.application.constraints.ConstrainedExecution
import com.intellij.openapi.application.constraints.ExpirableConstrainedExecution
import com.intellij.openapi.application.constraints.Expiration
import org.jetbrains.concurrency.CancellablePromise
import java.util.concurrent.Callable
import java.util.concurrent.Executor
import java.util.function.BooleanSupplier
internal abstract class BaseExpirableExecutorMixinImpl<E : BaseExpirableExecutorMixinImpl<E>>
protected constructor(constraints: Array<ConstrainedExecution.ContextConstraint>,
cancellationConditions: Array<BooleanSupplier>,
expirableHandles: Set<Expiration>,
private val executor: Executor)
: ConstrainedExecution<E>,
ExpirableConstrainedExecution<E>(constraints, cancellationConditions, expirableHandles) {
constructor (executor: Executor) : this(emptyArray(), emptyArray(), emptySet(), executor)
override fun scheduleWithinConstraints(runnable: Runnable, condition: BooleanSupplier?) {
executor.execute(kotlinx.coroutines.Runnable {
super.scheduleWithinConstraints(runnable, condition)
})
}
fun execute(command: Runnable): Unit = asExecutor().execute(command)
fun submit(task: Runnable): CancellablePromise<*> = asExecutor().submit(task)
fun <T : Any?> submit(task: Callable<T>): CancellablePromise<T> = asExecutor().submit(task)
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,617 | intellij-community | Apache License 2.0 |
vuejs-tests/src/org/jetbrains/vuejs/lang/VueTestModules.kt | wuxianqiang | 508,329,768 | false | {"Kotlin": 1447881, "Vue": 237479, "TypeScript": 106023, "JavaScript": 93869, "HTML": 17163, "Assembly": 12226, "Lex": 11227, "Java": 2846, "Shell": 1917, "Pug": 338} | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.vuejs.lang
import com.intellij.javascript.nodejs.library.NodeModulesDirectoryManager
import com.intellij.lang.javascript.buildTools.npm.PackageJsonUtil
import com.intellij.openapi.project.Project
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
fun createPackageJsonWithVueDependency(fixture: CodeInsightTestFixture,
additionalDependencies: String = "") {
fixture.configureByText(PackageJsonUtil.FILE_NAME, """
{
"name": "test",
"version": "0.0.1",
"dependencies": {
"vue": "2.5.3" ${if (additionalDependencies.isBlank()) "" else ", $additionalDependencies"}
}
}
""".trimIndent())
}
fun CodeInsightTestFixture.configureVueDependencies(vararg modules: VueTestModule) {
createPackageJsonWithVueDependency(
this, modules.asSequence()
.filter { it.folder != "vue" }
.flatMap { it.packageNames.asSequence() }
.joinToString { "\"${it}\": \"*\"" })
for (module in modules) {
tempDirFixture.copyAll("${getVueTestDataPath()}/modules/${module.folder}/node_modules", "node_modules")
}
forceReloadProjectRoots(project)
}
internal fun forceReloadProjectRoots(project: Project) {
// TODO - this shouldn't be needed, something's wrong with how roots are set within tests - check RootIndex#myRootInfos
NodeModulesDirectoryManager.getInstance(project).requestLibrariesUpdate()
}
enum class VueTestModule(val folder: String, vararg packageNames: String) {
BOOTSTRAP_VUE_2_0_0_RC_11("bootstrap-vue"),
BUEFY_0_6_2("buefy"),
COMPOSITION_API_0_4_0("composition-api/0.4.0", "@vue/composition-api"),
COMPOSITION_API_1_0_0("composition-api/1.0.0", "@vue/composition-api"),
ELEMENT_UI_2_0_5("element-ui"),
ELEMENT_PLUS_2_1_11_NO_WEB_TYPES("element-plus/2.1.11-no-web-types", "element-plus"),
HEADLESS_UI_1_4_1("headlessui", "@headlessui/vue"),
IVIEW_2_8_0("iview/2.8.0", "iview"),
IVIEW_3_5_4("iview/3.5.4", "iview"),
MINT_UI_2_2_3("mint-ui"),
NAIVE_UI_2_19_11_NO_WEB_TYPES("naive-ui/2.19.11-no-web-types", "naive-ui"),
NAIVE_UI_2_19_11("naive-ui/2.19.11", "naive-ui"),
// This version contains updated Web-Types and volar.d.ts included from index.d.ts
NAIVE_UI_2_33_2_PATCHED("naive-ui/2.33.2-patched", "naive-ui"),
NUXT_2_8_1("nuxt/2.8.1", "nuxt"),
NUXT_2_9_2("nuxt/2.9.2", "nuxt", "@nuxt/types"),
NUXT_2_13_2("nuxt/2.13.2", "nuxt", "@nuxt/types"),
NUXT_2_15_6("nuxt/2.15.6", "nuxt", "@nuxt/types"),
PRIMEVUE_3_8_2("primevue/3.8.2", "primevue"),
PINIA_2_0_22("pinia/2.0.22", "pinia", "vue-demi"),
QUASAR_2_6_5("quasar/2.6.5", "quasar"),
SHARDS_VUE_1_0_5("shards-vue", "@shards/vue"),
VUE_2_5_3("vue/2.5.3", "vue"),
VUE_2_6_10("vue/2.6.10", "vue"),
VUE_3_0_0("vue/3.0.0", "vue"),
VUE_3_1_0("vue/3.1.0", "vue"),
VUE_3_2_2("vue/3.2.2", "vue"),
VUELIDATE_0_7_13("vuelidate", "@types/vuelidate", "vuelidate"),
VUETIFY_0_17_2("vuetify/0.17.2", "vuetify"),
VUETIFY_1_2_10("vuetify/1.2.10", "vuetify"),
VUETIFY_1_3_7("vuetify/1.3.7", "vuetify"),
VUEUSE_9_3_0("vueuse/9.3.0", "@vueuse/core"),
VUEX_3_1_0("vuex/3.1.0", "vuex"),
VUEX_4_0_0("vuex/4.0.0", "vuex");
val packageNames: List<String>
init {
if (packageNames.isEmpty()) {
this.packageNames = listOf(folder)
}
else {
this.packageNames = packageNames.toList()
}
}
}
| 2 | Kotlin | 0 | 4 | e069e8b340ab04780ac13eab375d900f21bc7613 | 3,473 | intellij-plugin-mpx | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.