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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
function/FileFunctions.kt
|
cesards
| 252,885,439 | false | null |
/** Global File-related functions */
fun commonFileCleanupMessage(fileDeleted: Boolean) {
if (fileDeleted) {
println("${defaultVerboseIndentation}Done ✔️")
} else {
println("${defaultVerboseIndentation}Failed ❌")
}
}
fun File.getExtension(): String {
val fileName: String = getName()
return if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
fileName.substring(fileName.lastIndexOf(".") + 1)
} else {
""
}
}
fun File.removeSubfoldersMatching(matcher: (file: File) -> Boolean) {
//val matchingDirectories = filteredContent(recursively = recursively) {
val matchingDirectories = filteredContent(recursively = true) {
it.isDirectory && matcher(it)
}
matchingDirectories.deleteRecursively(verbose = true, wetRun = true)
// if (backup) {
// matchingDirectories.backupAndDeleteByRenaming()
// } else {
// matchingDirectories.deleteRecursively()
// }
}
fun File.filteredContent(recursively: Boolean, matcher: (File) -> Boolean): Sequence<File> =
listFiles()
.asSequence()
.flatMap {
when {
matcher(it) -> sequenceOf(it)
recursively && it.isDirectory -> {
it.filteredContent(recursively = true, matcher = matcher)
}
else -> sequenceOf()
}
}
fun Sequence<File>.deleteRecursively(verbose : Boolean = false, wetRun : Boolean = false) =
onEach { if (verbose) println("${defaultVerboseIndentation}Deleted: ${it.absolutePath}") }
.forEach { if (wetRun) it.deleteRecursively() }
| 5 |
Kotlin
|
0
| 0 |
1f5a95e3c86bd94e67974fa74c4ca5dbca6d0049
| 1,748 |
Don-Limpio
|
Apache License 2.0
|
moduleHttp/src/main/java/com/work/httplib/dn/kt/KTApiException.kt
|
Tiannuo
| 498,562,269 | false |
{"Kotlin": 218272, "Java": 43175}
|
package com.work.httplib.dn.kt
import android.net.ParseException
import com.google.gson.JsonParseException
import org.json.JSONException
import java.lang.Exception
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
/**
* 通用请求异常封装类
*/
class KTApiException(var code: String? = "-1", var errorMsg: String? = "null") : Exception() {
override fun toString(): String {
return "ApiException{" +
"code='" + code + '\'' +
", errorMsg='" + errorMsg + '\'' +
'}'
}
companion object {
private const val UNKNOWN_ERROR = -0x10
private const val PARSE_ERROR = -0x11
private const val NETWORK_ERROR = -0x12
/**
* Throwable --> ApiException
*
* @param e
* @return
*/
@JvmStatic
fun handleException(e: Throwable): KTApiException {
if (e is KTApiException) {
return e
}
val ex: KTApiException
return if (e is JsonParseException
|| e is JSONException
|| e is ParseException
) {
ex = KTApiException(PARSE_ERROR.toString(), "数据解析异常")
ex
} else if (e is ConnectException
|| e is UnknownHostException
|| e is SocketTimeoutException
) {
ex = KTApiException(NETWORK_ERROR.toString(), "网络请求异常")
ex
} else {
ex = KTApiException(UNKNOWN_ERROR.toString(), "其它异常:" + e.message)
e.printStackTrace()
ex
}
}
}
}
| 0 |
Kotlin
|
2
| 4 |
bf02c12830d80c6bcf7441c50c3f685d322fdf53
| 1,714 |
AndroidWork
|
Apache License 2.0
|
app/src/main/java/com/kuberam/android/component/CustomTopSection.kt
|
rohitjakhar
| 393,230,094 | false | null |
package com.kuberam.android.component
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.shape.ZeroCornerSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import coil.transform.CircleCropTransformation
import com.kuberam.android.data.model.ProfileDataModel
import com.kuberam.android.ui.theme.Typography
import com.kuberam.android.ui.viewmodel.MainViewModel
import com.kuberam.android.utils.NetworkResponse
import com.kuberam.android.utils.cardBackground
import com.kuberam.android.utils.textNormalColor
@Composable
fun CustomTopSection(
viewModel: MainViewModel
) {
viewModel.getUserDetails()
val userProfile = remember { mutableStateOf(ProfileDataModel()) }
val isDarkTheme =
produceState(initialValue = false, key1 = viewModel.darkTheme.value) {
value = viewModel.darkTheme.value
}
val currentCurrency = produceState(initialValue = "$", key1 = viewModel.currency.value) {
value = viewModel.currency.value
}
LaunchedEffect(viewModel.userProfileData.value) {
viewModel.getUserDetails()
when (viewModel.userProfileData.value) {
is NetworkResponse.Failure -> {
}
is NetworkResponse.Loading -> {
}
is NetworkResponse.Success -> {
userProfile.value = viewModel.userProfileData.value.data!!
}
}
}
Surface(
color = cardBackground(isDarkTheme.value),
modifier = Modifier.wrapContentHeight().fillMaxWidth()
.padding(bottom = 8.dp),
shape = RoundedCornerShape(16.dp).copy(
topStart = ZeroCornerSize,
topEnd = ZeroCornerSize
)
) {
Column(
Modifier.padding(
bottom = 8.dp,
top = 8.dp,
start = 16.dp,
end = 16.dp
).fillMaxWidth()
) {
Row {
Image(
painter = rememberImagePainter(
data =
userProfile.value.profileUrl,
builder = {
transformations(CircleCropTransformation())
},
),
contentDescription = null,
modifier = Modifier.padding(end = 16.dp)
)
Text(
text = "Hi \n${userProfile.value.name}",
style = Typography.h2,
color = textNormalColor(isDarkTheme.value)
)
}
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
) {
Text(
"Income: ${userProfile.value.totalIncome}${currentCurrency.value}",
style = MaterialTheme.typography.h2,
modifier = Modifier.padding(8.dp),
color = textNormalColor(isDarkTheme.value)
)
Text(
"Expense: ${userProfile.value.totalExpense}${currentCurrency.value}",
style = MaterialTheme.typography.h2,
modifier = Modifier.padding(8.dp),
color = textNormalColor(isDarkTheme.value)
)
}
}
}
}
| 3 |
Kotlin
|
6
| 37 |
dd1ff326b99dce0299f8a8dc0753734b489d319a
| 4,195 |
Kuberam
|
MIT License
|
_request-permission/request-permission-assertion/src/main/java/io/androidalatan/request/permission/assertions/MockPermissionExplanation.kt
|
android-alatan
| 466,507,427 | false | null |
package io.androidalatan.request.permission.assertions
import io.androidalatan.request.permission.api.PermissionExplanation
class MockPermissionExplanation : PermissionExplanation {
var showCount = 0
var callback: PermissionExplanation.OnConfirm? = null
override fun show(callback: PermissionExplanation.OnConfirm) {
showCount++
}
fun confirm() {
callback?.onConfirm()
}
}
| 3 |
Kotlin
|
5
| 56 |
35b0ec7a89f8254db0af1830ac1de8a7124c6f09
| 415 |
LifecycleComponents
|
MIT License
|
android/DartsScorecard/data/src/main/java/nl/entreco/data/db/DscDatabase.kt
|
Entreco
| 110,022,468 | false |
{"Markdown": 3, "Text": 3, "Ignore List": 10, "YAML": 2, "SVG": 35, "HTML": 1, "PHP": 1, "CSS": 1, "Gradle": 15, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 7, "Kotlin": 637, "XML": 222, "JSON": 2, "Java": 2}
|
package nl.entreco.data.db
import androidx.room.Database
import androidx.room.RoomDatabase
import nl.entreco.data.db.bot.BotDao
import nl.entreco.data.db.bot.BotTable
import nl.entreco.data.db.game.GameDao
import nl.entreco.data.db.game.GameTable
import nl.entreco.data.db.meta.MetaDao
import nl.entreco.data.db.meta.MetaTable
import nl.entreco.data.db.player.PlayerDao
import nl.entreco.data.db.player.PlayerTable
import nl.entreco.data.db.profile.ProfileDao
import nl.entreco.data.db.profile.ProfileTable
import nl.entreco.data.db.turn.TurnDao
import nl.entreco.data.db.turn.TurnTable
/**
* Created by Entreco on 12/12/2017.
*/
@Database(version = 3, exportSchema = false, entities = [
GameTable::class,
BotTable::class,
PlayerTable::class,
TurnTable::class,
MetaTable::class,
ProfileTable::class])
abstract class DscDatabase : RoomDatabase() {
abstract fun gameDao(): GameDao
abstract fun playerDao(): PlayerDao
abstract fun botDao(): BotDao
abstract fun turnDao(): TurnDao
abstract fun metaDao(): MetaDao
abstract fun profileDao(): ProfileDao
companion object {
const val name: String = "dsc_database"
}
}
| 4 | null |
1
| 1 |
a031a0eeadd0aa21cd587b5008364a16f890b264
| 1,178 |
Darts-Scorecard
|
Apache License 2.0
|
js/js.translator/testData/incremental/invalidation/updateExportsAndInlineImports/lib1/l1b.2.kt
|
JetBrains
| 3,432,266 | false |
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
inline fun fun2() = "fun2-2"
| 181 |
Kotlin
|
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 29 |
kotlin
|
Apache License 2.0
|
src/main/kotlin/com/kurtraschke/gtfsrtdump/TimestampFormatting.kt
|
exu1977
| 293,678,253 | true |
{"Kotlin": 36593}
|
package com.kurtraschke.gtfsrtdump
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.*
interface TimestampFormatter {
fun formatTimestamp(posixTimestamp: Long): String
}
@Suppress("unused")
enum class TimestampFormatting : TimestampFormatter {
POSIX {
override fun formatTimestamp(posixTimestamp: Long): String {
return when (posixTimestamp) {
0L -> ""
else -> posixTimestamp.toString()
}
}
},
ISO_8601_LOCAL {
override fun formatTimestamp(posixTimestamp: Long): String {
return when (posixTimestamp) {
0L -> ""
else -> DateTimeFormatter.ISO_LOCAL_DATE_TIME
.format(Instant.ofEpochSecond(posixTimestamp).atZone(TimeZone.getDefault().toZoneId()))
}
}
},
ISO_8601_UTC {
override fun formatTimestamp(posixTimestamp: Long): String {
return when (posixTimestamp) {
0L -> ""
else -> DateTimeFormatter.ISO_LOCAL_DATE_TIME
.withZone(ZoneId.of("UTC"))
.format(Instant.ofEpochSecond(posixTimestamp)) + "Z"
}
}
}
}
| 0 | null |
0
| 0 |
d72efe1923fe9cb1f41e1ee187a6954a91a27794
| 1,280 |
gtfs-rt-dump
|
Apache License 2.0
|
composeApp/src/commonMain/kotlin/com/ccc/resume/ui/contents/KeyValueListContent.kt
|
moonggae
| 845,905,986 | false |
{"Kotlin": 43422, "HTML": 1464, "CSS": 218}
|
package com.ccc.resume.ui.contents
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import com.ccc.resume.designsystem.getTextStyleFromString
import com.ccc.resume.ui.components.KeyValueList
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("key_value_list")
data class KeyValueListContent(
override val type: String = "key_value_list",
val value: List<KeyValueItem>,
@SerialName("vertical_padding")
val verticalPadding: Int = 8,
@SerialName("horizontal_padding")
val horizontalPadding: Int = 32,
@SerialName("key_style")
val keyStyle: String = "subtitle1",
@SerialName("value_style")
val valueStyle: String = "body2",
) : Content() {
override val composable: @Composable () -> Unit
get() = {
KeyValueList(
data = value.map { it.key to it.value },
verticalPaddingValues = verticalPadding.dp,
horizontalPaddingValues = horizontalPadding.dp,
keyStyle = getTextStyleFromString(keyStyle) ?: MaterialTheme.typography.subtitle1,
valueStyle = getTextStyleFromString(valueStyle) ?: MaterialTheme.typography.body2,
)
}
}
@Serializable
data class KeyValueItem(
val key: String,
val value: String
)
| 0 |
Kotlin
|
0
| 0 |
cfb1c8e3884fc4d17709a27c54503d7085431dd3
| 1,405 |
Resume-Wasm
|
Apache License 2.0
|
sample/sample-shared/src/commonMain/kotlin/de/jlnstrk/transit/sample/SampleProduct.kt
|
jlnstrk
| 229,599,180 | false |
{"Kotlin": 729374}
|
package de.jlnstrk.transit.sample
import de.jlnstrk.transit.common.model.Means
import de.jlnstrk.transit.common.model.ProductClass
sealed interface SampleProduct : ProductClass {
sealed interface RegionalTrain : SampleProduct {
override val base: Means get() = Means.TRAIN
sealed interface Local : RegionalTrain
sealed interface Express : RegionalTrain
}
// S-Bahn is a type of commuter rail used in most urban regions in Germany
sealed interface SBahn : SampleProduct {
override val base: Means get() = Means.TRAIN
interface Express : SBahn
}
interface ExpressBus : SampleProduct {
override val base: Means get() = Means.BUS
}
interface MetroBus : SampleProduct {
override val base: Means get() = Means.BUS
}
interface RegionalBus : SampleProduct {
override val base: Means get() = Means.BUS
}
}
| 0 |
Kotlin
|
0
| 0 |
9f700364f78ebc70b015876c34a37b36377f0d9c
| 914 |
transit
|
Apache License 2.0
|
app/src/main/java/m1k/kotik/negocards/data/canvas_qrc/canvas_view/canvas_tools/canvas_tools/CanvasPositionEditTool.kt
|
M1KoTiK
| 586,878,944 | false |
{"Kotlin": 307238}
|
package m1k.kotik.negocards.data.canvas_qrc.canvas_view.canvas_tools.canvas_tools
import android.content.Context
import android.graphics.*
import android.view.MotionEvent
import m1k.kotik.negocards.data.canvas_qrc.canvas_view.canvas_editors.CanvasEditor
import m1k.kotik.negocards.data.canvas_qrc.canvas_view.canvas_objects.ICanvasMeasurable
import m1k.kotik.negocards.data.canvas_qrc.canvas_view.canvas_objects.shapes.Rectangle
import m1k.kotik.negocards.data.canvas_qrc.canvas_view.canvas_tools.ICanvasTool
import m1k.kotik.negocards.data.canvas_qrc.canvas_view.canvas_tools.TouchProcessingCanvasTool
import m1k.kotik.negocards.data.canvas_qrc.old_govno.canvas_object_types.ShapeObject
import m1k.kotik.negocards.data.measure_utils.displacementByDelta
import m1k.kotik.negocards.data.measure_utils.isClickOnObject
class CanvasPositionEditTool(override val canvasEditor: CanvasEditor) :
TouchProcessingCanvasTool<ICanvasMeasurable>() {
override var x: Int = 0
override var y: Int = 0
override var width: Int = 0
override var height: Int = 0
private var _objectForEdit: MutableList<ICanvasMeasurable> = mutableListOf()
override var objectsForEdit: MutableList<ICanvasMeasurable>
get() = _objectForEdit
set(value) {
if(value.isNotEmpty()) {
_objectForEdit = value
updateToolMeasures()
}
}
private var initialObjectForEdit = mutableListOf<ICanvasMeasurable>()
private var startX: Int = 0
private var startY: Int = 0
// var isPressed = false
override val onClickDown: (x: Float, y: Float) -> Unit ={ eventX, eventY ->
startX = eventX.toInt()
startY = eventY.toInt()
initialObjectForEdit.clear()
initialObjectForEdit = objectsForEdit.map{obj ->
Rectangle().also { rc ->
rc.x = obj.x
rc.y = obj.y
rc.width = obj.width
rc.height = obj.height
}
}.toMutableList()
}
override val onMovingWhenPressed: (deltaX: Float, deltaY: Float, x: Float, y: Float) -> Unit = {
deltaX, deltaY, _, _ ->
for (i in 0 until initialObjectForEdit.count()){
val obj = initialObjectForEdit[i]
val displacementPoint = displacementByDelta(obj.x, obj.y, deltaX.toInt(), deltaY.toInt())
objectsForEdit[i].x = displacementPoint.x
objectsForEdit[i].y = displacementPoint.y
updateToolMeasures()
}
}
override fun draw(canvas: Canvas) {
if(objectsForEdit.isNotEmpty()) {
canvas.drawRoundRect(
x.toFloat() - 10,
y.toFloat() - 10,
x.toFloat() + width.toFloat() + 10,
y.toFloat() + height.toFloat() + 10,
5f,
5f,
Paint().also {
it.color = Color.parseColor("#181818")
it.style = Paint.Style.STROKE
it.strokeWidth = 4f
// it.pathEffect = DashPathEffect(floatArrayOf(50f, 10f), 0f)
})
}
}
private fun updateToolMeasures(){
val sortedByX = objectsForEdit.sortedBy { it.x }
val sortedByY = objectsForEdit.sortedBy { it.y }
val x = sortedByX.first().x
val y = sortedByY.first().y
val width = sortedByX.last().x + sortedByX.last().width - x
val height = sortedByX.last().y + sortedByX.last().height - y
this.x = x
this.y = y
this.width = width
this.height = height
}
override var onPositioning: (List<ICanvasMeasurable>) -> Point = {
Point()
}
}
| 0 |
Kotlin
|
0
| 1 |
b0289f8b81c200e31e201d8cebac73429bfaba31
| 3,705 |
Nego-Cards
|
Apache License 2.0
|
ohyeah/app/src/test/java/com/ewingsa/ohyeah/MainApplicationTest.kt
|
ewingsa
| 258,544,034 | false | null |
package com.ewingsa.ohyeah
import com.nhaarman.mockitokotlin2.mock
import dagger.android.DispatchingAndroidInjector
import org.junit.Assert.assertEquals
import org.junit.Test
class MainApplicationTest {
@Test
fun testAndroidInjector() {
val androidInjector: DispatchingAndroidInjector<Any> = mock()
val mainApplication = MainApplication()
mainApplication.androidInjector = androidInjector
assertEquals(androidInjector, mainApplication.androidInjector())
}
}
| 0 |
Kotlin
|
0
| 1 |
852fe9f32c01b87895c7e2a57d4d054d7356932c
| 507 |
ohyeah
|
Apache License 2.0
|
app/src/main/java/ir/magiccodes/weatherland/ui/feature/mainScreen/MainScreenPresenter.kt
|
MagicCodes01
| 639,393,068 | false | null |
package ir.magiccodes.weatherland.ui.feature.mainScreen
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import io.reactivex.SingleObserver
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers.io
import ir.magiccodes.weatherland.model.ApiService
import ir.magiccodes.weatherland.model.data.ForecastAdapterData
import ir.magiccodes.weatherland.model.data.WeatherData
import ir.magiccodes.weatherland.util.convertDateToDayOfWeek
import ir.magiccodes.weatherland.util.convertDateToHour
import ir.magiccodes.weatherland.util.getCurrentHour
class MainScreenPresenter(
private val apiService: ApiService
): MainScreenContract.Presenter {
var mainView: MainScreenContract.View? = null
lateinit var disposable: Disposable
lateinit var data: WeatherData
private var itemPosition: Int = 0
override fun onAttach(view: MainScreenContract.View) {
mainView = view
apiService.getWeather()
.subscribeOn(io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : SingleObserver<WeatherData>{
override fun onSubscribe(d: Disposable) {
disposable = d
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onSuccess(t: WeatherData) {
// set data to current weather
data = t
mainView!!.setCurrentWeather(data,itemPosition)
setHourlyForecastData(data)
// set detail data
mainView!!.showHourlyDetail(data,itemPosition)
}
override fun onError(e: Throwable) {
Log.v("RxjavaError", e.message!!)
}
})
}
override fun onDetach() {
mainView = null
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onHourlyForecastClicked() {
setHourlyForecastData(data)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onWeeklyForecastClicked() {
val dataWeeklyForecast = arrayListOf<ForecastAdapterData>()
data.forecast.forecastday.forEach {
dataWeeklyForecast.apply {
add(ForecastAdapterData(convertDateToDayOfWeek(it.date), it.day.condition.code, it.day.avgtempC.toInt().toString()))
}
}
mainView!!.showWeeklyForecast(dataWeeklyForecast)
}
override fun onWeatherItemClicked() {
TODO("Not yet implemented")
}
override fun onMapClicked() {
TODO("Not yet implemented")
}
override fun onAddWeatherClicked() {
TODO("Not yet implemented")
}
@RequiresApi(Build.VERSION_CODES.O)
fun setHourlyForecastData(data: WeatherData){
// set data to recycler hourly forecast
val forecastData = arrayListOf<ForecastAdapterData>()
data.forecast.forecastday[0].hour.forEach {
forecastData.apply {
add(ForecastAdapterData(convertDateToHour(it.time), it.condition.code, it.tempC.toInt().toString()))
}
}
// find current time item(weather)
forecastData.forEachIndexed { index, it ->
if (it.hourOrDate == getCurrentHour()){
it.hourOrDate = "Now"
//this is for find now item
itemPosition = index
}
}
mainView!!.showHourlyForecast(forecastData, itemPosition)
}
}
| 0 |
Kotlin
|
0
| 0 |
465906ecbb647a61860f98be518997d9a52d6c62
| 3,574 |
WeatherLand
|
MIT License
|
jb/src/main/kotlin/review/PullRequestChain.kt
|
TeamCodeStream
| 148,423,109 | false |
{"TypeScript": 7331579, "C#": 893431, "Kotlin": 530337, "JavaScript": 173494, "HTML": 164933, "Less": 148960, "Shell": 52216, "Java": 47033, "Python": 16745, "Lex": 2739, "CSS": 2364, "Ruby": 1764, "Dockerfile": 1382, "Roff": 131}
|
package com.codestream.review
import com.intellij.diff.chains.DiffRequestChainBase
import com.intellij.diff.chains.DiffRequestProducer
class PullRequestChain(val producers: List<PullRequestProducer>) : DiffRequestChainBase() {
override fun getRequests(): List<DiffRequestProducer> = producers
}
| 21 |
TypeScript
|
182
| 930 |
3989ca8f40ab33312f32887bf390262323676b5e
| 300 |
codestream
|
Apache License 2.0
|
app/src/main/java/com/william/easykt/data/DataRepo.kt
|
Seachal
| 357,416,143 | true |
{"Kotlin": 166552, "Java": 22100}
|
package com.william.easykt.data
import java.io.Serializable
/**
* @author William
* @date 2020/5/19 13:05
* Class Comment:业务数据返回模型
*/
// 通用的带有列表数据的实体
data class BaseListResponseBody<T>(
val curPage: Int,
val datas: List<T>,
val offset: Int,
val over: Boolean,
val pageCount: Int,
val size: Int,
val total: Int
)
//文章
data class ArticleResponseBody(
val curPage: Int,
var datas: MutableList<Article>,
val offset: Int,
val over: Boolean,
val pageCount: Int,
val size: Int,
val total: Int
)
//文章
data class Article(
val apkLink: String,
val audit: Int,
val author: String,
val chapterId: Int,
val chapterName: String,
var collect: Boolean,
val courseId: Int,
val desc: String,
val envelopePic: String,
val fresh: Boolean,
val id: Int,
val link: String,
val niceDate: String,
val niceShareDate: String,
val origin: String,
val prefix: String,
val projectLink: String,
val publishTime: Long,
val shareDate: String,
val shareUser: String,
val superChapterId: Int,
val superChapterName: String,
val tags: MutableList<Tag>,
val title: String,
val type: Int,
val userId: Int,
val visible: Int,
val zan: Int,
var top: String
)
data class Tag(
val name: String,
val url: String
)
//轮播图
data class Banner(
val desc: String,
val id: Int,
val imagePath: String,
val isVisible: Int,
val order: Int,
val title: String,
val type: Int,
val url: String
)
data class HotKey(
val id: Int,
val link: String,
val name: String,
val order: Int,
val visible: Int
)
//常用网站
data class Friend(
val icon: String,
val id: Int,
val link: String,
val name: String,
val order: Int,
val visible: Int
)
//知识体系
data class KnowledgeTreeBody(
val children: MutableList<Knowledge>,
val courseId: Int,
val id: Int,
val name: String,
val order: Int,
val parentChapterId: Int,
val visible: Int
) : Serializable
data class Knowledge(
val children: List<Any>,
val courseId: Int,
val id: Int,
val name: String,
val order: Int,
val parentChapterId: Int,
val visible: Int
) : Serializable
// 登录数据
data class LoginData(
val chapterTops: MutableList<String>,
val collectIds: MutableList<String>,
val email: String,
val icon: String,
val id: Int,
val password: String,
val token: String,
val type: Int,
val username: String
)
//收藏网站
data class CollectionWebsite(
val desc: String,
val icon: String,
val id: Int,
var link: String,
var name: String,
val order: Int,
val userId: Int,
val visible: Int
)
data class CollectionArticle(
val author: String,
val chapterId: Int,
val chapterName: String,
val courseId: Int,
val desc: String,
val envelopePic: String,
val id: Int,
val link: String,
val niceDate: String,
val origin: String,
val originId: Int,
val publishTime: Long,
val title: String,
val userId: Int,
val visible: Int,
val zan: Int
)
// 导航
data class NavigationBean(
val articles: MutableList<Article>,
val cid: Int,
val name: String
)
// 项目
data class ProjectTreeBean(
val children: List<Any>,
val courseId: Int,
val id: Int,
val name: String,
val order: Int,
val parentChapterId: Int,
val visible: Int
)
// 热门搜索
data class HotSearchBean(
val id: Int,
val link: String,
val name: String,
val order: Int,
val visible: Int
)
// TODO工具 类型
data class TodoTypeBean(
val type: Int,
val name: String,
var isSelected: Boolean
)
// TODO实体类
data class TodoBean(
val id: Int,
val completeDate: String,
val completeDateStr: String,
val content: String,
val date: Long,
val dateStr: String,
val status: Int,
val title: String,
val type: Int,
val userId: Int,
val priority: Int
) : Serializable
data class TodoListBean(
val date: Long,
val todoList: MutableList<TodoBean>
)
// 所有TODO,包括待办和已完成
data class AllTodoResponseBody(
val type: Int,
val doneList: MutableList<TodoListBean>,
val todoList: MutableList<TodoListBean>
)
data class TodoResponseBody(
val curPage: Int,
val datas: MutableList<TodoBean>,
val offset: Int,
val over: Boolean,
val pageCount: Int,
val size: Int,
val total: Int
)
// 公众号列表实体
data class WXChapterBean(
val children: MutableList<String>,
val courseId: Int,
val id: Int,
val name: String,
val order: Int,
val parentChapterId: Int,
val userControlSetTop: Boolean,
val visible: Int
)
// 用户个人信息
data class UserInfoBody(
val coinCount: Int, // 总积分
val rank: Int, // 当前排名
val userId: Int,
val username: String
)
// 个人积分实体
data class UserScoreBean(
val coinCount: Int,
val date: Long,
val desc: String,
val id: Int,
val reason: String,
val type: Int,
val userId: Int,
val userName: String
)
// 排行榜实体
data class CoinInfoBean(
val coinCount: Int,
val level: Int,
val rank: Int,
val userId: Int,
val username: String
)
// 我的分享
data class ShareResponseBody(
val coinInfo: CoinInfoBean,
val shareArticles: ArticleResponseBody
)
| 0 | null |
0
| 0 |
e4dc012c41c599055e62316e2055daad3177fb9c
| 5,333 |
EasyKotlin
|
Apache License 2.0
|
app/src/main/java/com/william/easykt/data/DataRepo.kt
|
Seachal
| 357,416,143 | true |
{"Kotlin": 166552, "Java": 22100}
|
package com.william.easykt.data
import java.io.Serializable
/**
* @author William
* @date 2020/5/19 13:05
* Class Comment:业务数据返回模型
*/
// 通用的带有列表数据的实体
data class BaseListResponseBody<T>(
val curPage: Int,
val datas: List<T>,
val offset: Int,
val over: Boolean,
val pageCount: Int,
val size: Int,
val total: Int
)
//文章
data class ArticleResponseBody(
val curPage: Int,
var datas: MutableList<Article>,
val offset: Int,
val over: Boolean,
val pageCount: Int,
val size: Int,
val total: Int
)
//文章
data class Article(
val apkLink: String,
val audit: Int,
val author: String,
val chapterId: Int,
val chapterName: String,
var collect: Boolean,
val courseId: Int,
val desc: String,
val envelopePic: String,
val fresh: Boolean,
val id: Int,
val link: String,
val niceDate: String,
val niceShareDate: String,
val origin: String,
val prefix: String,
val projectLink: String,
val publishTime: Long,
val shareDate: String,
val shareUser: String,
val superChapterId: Int,
val superChapterName: String,
val tags: MutableList<Tag>,
val title: String,
val type: Int,
val userId: Int,
val visible: Int,
val zan: Int,
var top: String
)
data class Tag(
val name: String,
val url: String
)
//轮播图
data class Banner(
val desc: String,
val id: Int,
val imagePath: String,
val isVisible: Int,
val order: Int,
val title: String,
val type: Int,
val url: String
)
data class HotKey(
val id: Int,
val link: String,
val name: String,
val order: Int,
val visible: Int
)
//常用网站
data class Friend(
val icon: String,
val id: Int,
val link: String,
val name: String,
val order: Int,
val visible: Int
)
//知识体系
data class KnowledgeTreeBody(
val children: MutableList<Knowledge>,
val courseId: Int,
val id: Int,
val name: String,
val order: Int,
val parentChapterId: Int,
val visible: Int
) : Serializable
data class Knowledge(
val children: List<Any>,
val courseId: Int,
val id: Int,
val name: String,
val order: Int,
val parentChapterId: Int,
val visible: Int
) : Serializable
// 登录数据
data class LoginData(
val chapterTops: MutableList<String>,
val collectIds: MutableList<String>,
val email: String,
val icon: String,
val id: Int,
val password: String,
val token: String,
val type: Int,
val username: String
)
//收藏网站
data class CollectionWebsite(
val desc: String,
val icon: String,
val id: Int,
var link: String,
var name: String,
val order: Int,
val userId: Int,
val visible: Int
)
data class CollectionArticle(
val author: String,
val chapterId: Int,
val chapterName: String,
val courseId: Int,
val desc: String,
val envelopePic: String,
val id: Int,
val link: String,
val niceDate: String,
val origin: String,
val originId: Int,
val publishTime: Long,
val title: String,
val userId: Int,
val visible: Int,
val zan: Int
)
// 导航
data class NavigationBean(
val articles: MutableList<Article>,
val cid: Int,
val name: String
)
// 项目
data class ProjectTreeBean(
val children: List<Any>,
val courseId: Int,
val id: Int,
val name: String,
val order: Int,
val parentChapterId: Int,
val visible: Int
)
// 热门搜索
data class HotSearchBean(
val id: Int,
val link: String,
val name: String,
val order: Int,
val visible: Int
)
// TODO工具 类型
data class TodoTypeBean(
val type: Int,
val name: String,
var isSelected: Boolean
)
// TODO实体类
data class TodoBean(
val id: Int,
val completeDate: String,
val completeDateStr: String,
val content: String,
val date: Long,
val dateStr: String,
val status: Int,
val title: String,
val type: Int,
val userId: Int,
val priority: Int
) : Serializable
data class TodoListBean(
val date: Long,
val todoList: MutableList<TodoBean>
)
// 所有TODO,包括待办和已完成
data class AllTodoResponseBody(
val type: Int,
val doneList: MutableList<TodoListBean>,
val todoList: MutableList<TodoListBean>
)
data class TodoResponseBody(
val curPage: Int,
val datas: MutableList<TodoBean>,
val offset: Int,
val over: Boolean,
val pageCount: Int,
val size: Int,
val total: Int
)
// 公众号列表实体
data class WXChapterBean(
val children: MutableList<String>,
val courseId: Int,
val id: Int,
val name: String,
val order: Int,
val parentChapterId: Int,
val userControlSetTop: Boolean,
val visible: Int
)
// 用户个人信息
data class UserInfoBody(
val coinCount: Int, // 总积分
val rank: Int, // 当前排名
val userId: Int,
val username: String
)
// 个人积分实体
data class UserScoreBean(
val coinCount: Int,
val date: Long,
val desc: String,
val id: Int,
val reason: String,
val type: Int,
val userId: Int,
val userName: String
)
// 排行榜实体
data class CoinInfoBean(
val coinCount: Int,
val level: Int,
val rank: Int,
val userId: Int,
val username: String
)
// 我的分享
data class ShareResponseBody(
val coinInfo: CoinInfoBean,
val shareArticles: ArticleResponseBody
)
| 0 | null |
0
| 0 |
e4dc012c41c599055e62316e2055daad3177fb9c
| 5,333 |
EasyKotlin
|
Apache License 2.0
|
src/main/resources/default_code/model/FrappeFilterSet.kt
|
klahap
| 805,279,827 | false |
{"Kotlin": 191881}
|
package default_code.model
import default_code.DocType
import default_code.DocTypeAbility
class FrappeFilterSet(
val filters: Set<FrappeFilter>,
) {
constructor(vararg filters: FrappeFilter) : this(filters.toSet())
fun serialize() = filters.joinToString(separator = ",", prefix = "[", postfix = "]") { it.serialize() }
class Builder<T> where T : DocType, T : DocTypeAbility.Query {
private val filters: MutableList<FrappeFilter> = mutableListOf()
fun add(value: FrappeFilter) = also {
val filterAlreadyExists = filters.any { it.fieldName == value.fieldName && it.operator == value.operator }
if (filterAlreadyExists)
throw Exception("filter '${value.operator.name}' already exists for field '${value.fieldName}'")
filters.add(value)
}
fun build() = FrappeFilterSet(filters = filters.toSet())
}
}
| 0 |
Kotlin
|
2
| 2 |
e3e5d3d4ea200bd7a8736c72e866d6d57ab43173
| 906 |
fraplin
|
MIT License
|
fuzzer/fuzzing_output/crashing_tests/verified/minimized/simpleFunAnnotation.kt-621474250.kt_minimized.kt
|
ItsLastDay
| 102,885,402 | false | null |
@Simple("OK")
fun box(): String {
return ((((((::box)) ?: ((::box)))!!.annotations.single() as Simple))).value
}
| 2 | null |
1
| 6 |
56f50fc307709443bb0c53972d0c239e709ce8f2
| 113 |
KotlinFuzzer
|
MIT License
|
src/test/kotlin/hm/binkley/shoppingcart/FakeTestDescriber.kt
|
binkley
| 838,932,873 | false |
{"Kotlin": 7642, "Shell": 211}
|
package hm.binkley.shoppingcart
internal class FakeTestDescriber : Describer {
override fun describe(item: ShoppingCartItem): String {
require(FLOOR_WAX_UPC == item.upc) {
"Unknown UPC for describing in tests: ${item.upc}"
}
return "FLOOR WAX"
}
}
| 0 |
Kotlin
|
0
| 0 |
f5acf08b43fbcb32d31ead292e0524f85f15d02e
| 293 |
kotlin-shopping-cart
|
Creative Commons Zero v1.0 Universal
|
plugins/space/src/main/kotlin/circlet/ui/CircletImageLoader.kt
|
sneha1702
| 278,616,856 | true | null |
package circlet.ui
import circlet.platform.api.*
import circlet.platform.api.oauth.*
import circlet.platform.client.*
import com.google.common.cache.*
import com.intellij.execution.process.*
import io.ktor.client.*
import io.ktor.client.request.*
import kotlinx.coroutines.*
import libraries.coroutines.extra.*
import runtime.*
import runtime.async.*
import java.awt.image.*
import java.io.*
import java.util.concurrent.*
import javax.imageio.*
class CircletImageLoader(
private val lifetime: Lifetime,
client: KCircletClient
) {
private val server: String = client.server.removeSuffix("/")
private val tokenSource: TokenSource = client.tokenSource
private val imagesEndpoint: String = "${server}/d"
private val imageCache: Cache<TID, Deferred<BufferedImage?>> = CacheBuilder.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.build<TID, Deferred<BufferedImage?>>()
private val coroutineDispatcher = ProcessIOExecutorService.INSTANCE.asCoroutineDispatcher()
suspend fun loadImageAsync(imageTID: TID): Deferred<BufferedImage?> {
return imageCache.get(imageTID) {
async(lifetime, coroutineDispatcher) {
backoff {
load(imageTID)
}
}
}
}
private suspend fun load(imageTID: TID): BufferedImage? {
val accessToken = tokenSource.token().accessToken
return HttpClient().use { client ->
val bytes = client.get<ByteArray>("$imagesEndpoint/$imageTID") {
header("Authorization", "Bearer $accessToken")
}
ImageIO.read(ByteArrayInputStream(bytes))
}
}
}
| 1 | null |
1
| 1 |
e98f7832f9a75dbdeac47da2ce1d737c2c241144
| 1,677 |
intellij-community
|
Apache License 2.0
|
feature/category/src/main/kotlin/com/naveenapps/expensemanager/feature/category/list/CategoryListAction.kt
|
nkuppan
| 536,435,007 | false |
{"Kotlin": 1018021}
|
package com.naveenapps.expensemanager.feature.category.list
import com.naveenapps.expensemanager.core.model.Category
sealed class CategoryListAction {
data object ClosePage : CategoryListAction()
data object Create : CategoryListAction()
data class Edit(val item: Category) : CategoryListAction()
data class ChangeCategory(val type: CategoryTabItems) : CategoryListAction()
}
| 4 |
Kotlin
|
15
| 94 |
5a5c790bea3f1ce4a720d7cffe6fe72a506507b7
| 397 |
expensemanager
|
Apache License 2.0
|
src/commonMain/kotlin/org/tix/feature/plan/domain/ticket/github/GithubPlanResult.kt
|
ncipollo
| 336,920,234 | false |
{"Kotlin": 601503}
|
package org.tix.feature.plan.domain.ticket.github
import org.tix.feature.plan.domain.ticket.PlanningOperation
import org.tix.feature.plan.domain.ticket.TicketPlanResult
data class GithubPlanResult(
override val id: String = "",
override val key: String = "",
override val tixId: String = "",
override val level: Int = 0,
override val description: String = "",
override val results: Map<String, String> = emptyMap(),
override val operation: PlanningOperation = PlanningOperation.CreateTicket,
override val startingLevel: Int = 0
) : TicketPlanResult
| 8 |
Kotlin
|
0
| 3 |
02f87c827c1159af055f5afc5481afd45c013703
| 582 |
tix-core
|
MIT License
|
core/src/main/java/com/endiar/movieverse/core/domain/model/FavoriteFilm.kt
|
nandrasaputra
| 220,730,565 | false | null |
package com.endiar.movieverse.core.domain.model
interface FavoriteFilm {
val id: Int
val title: String
val genre: String
val overview: String
val voteAverage: Double
val posterPath: String
}
| 0 |
Kotlin
|
3
| 3 |
897d2f1a4d320689866051dabcb616f7a869499a
| 215 |
Movieverse
|
Apache License 2.0
|
mobiuskt-test/src/commonMain/kotlin/matcher/SelfDescribingValue.kt
|
DrewCarlson
| 147,952,971 | false |
{"Kotlin": 361175}
|
package kt.mobius.test.matcher
internal class SelfDescribingValue<T>(private val value: T) : SelfDescribing {
override fun describeTo(description: Description) {
description.appendValue(value)
}
}
internal class SelfDescribingValueIterator<T>(private val values: Iterator<T>) : Iterator<SelfDescribing> {
override fun hasNext(): Boolean {
return values.hasNext()
}
override fun next(): SelfDescribing {
return SelfDescribingValue(values.next())
}
}
| 6 |
Kotlin
|
3
| 65 |
194d2c1bf2737b23f5683433bcdf3cbb40c19dae
| 501 |
mobius.kt
|
Apache License 2.0
|
android/src/main/kotlin/com/yfbx/scan/FlutterScanKitPlugin.kt
|
yfbx-repo
| 470,968,014 | false |
{"Objective-C": 17611, "Kotlin": 5308, "Dart": 3451, "Ruby": 2298, "Java": 151}
|
package com.yfbx.scan
import android.app.Activity
import android.content.Intent
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.platform.PlatformViewFactory
/** FlutterScanKitPlugin */
class FlutterScanKitPlugin : FlutterPlugin, ActivityAware {
private var mActivity: Activity? = null
private var mPluginBinding: FlutterPlugin.FlutterPluginBinding? = null
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
mPluginBinding = binding
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
mPluginBinding = null
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
mActivity = binding.activity
mPluginBinding?.let {
it.platformViewRegistry.registerViewFactory(
"ScanKitWidgetType", ScanKitViewFactory(it.binaryMessenger, binding)
)
}
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
onAttachedToActivity(binding)
}
override fun onDetachedFromActivityForConfigChanges() {
mActivity = null
}
override fun onDetachedFromActivity() {
mActivity = null
}
}
| 0 |
Objective-C
|
0
| 0 |
442523b2446d69c39fe2c70cf13a9e246d4e922b
| 1,655 |
flutter_scankit
|
MIT License
|
src/test/kotlin/dev/paulshields/assistantview/sourcefiles/AssistantViewFileTest.kt
|
Pkshields
| 228,929,505 | false | null |
package dev.paulshields.assistantview.sourcefiles
import com.intellij.openapi.fileTypes.FileType
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiFile
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import dev.paulshields.assistantview.testcommon.relaxedMock
import io.mockk.every
import org.apache.commons.lang.NotImplementedException
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.psi.KtFile
import org.junit.Test
class AssistantViewFileTest {
private val ktFile = relaxedMock<KtFile>().apply {
every { classes } returns emptyArray()
}
@Test
fun `test should return class list from kotlin file`() {
val psiClass = relaxedMock<PsiClass>()
every { ktFile.classes } returns arrayOf(psiClass)
val target = AssistantViewFile(ktFile)
val result = target.classes
assertThat(result.size, equalTo(1))
assertThat(result[0].underlyingPsiClass, equalTo(psiClass))
}
@Test
fun `test should handle empty class list on kotlin file`() {
val target = AssistantViewFile(ktFile)
val result = target.classes
assertThat(result.size, equalTo(0))
}
@Test(expected = NotImplementedException::class)
fun `test should throw exception when getting class list if psifile is not supported`() {
val unsupportedPsiFile = relaxedMock<PsiFile>()
val target = AssistantViewFile(unsupportedPsiFile)
val result = target.classes
}
@Test
fun `test should define first class in class list as main class`() {
val psiClass = relaxedMock<PsiClass>()
every { ktFile.classes } returns arrayOf(psiClass)
val target = AssistantViewFile(ktFile)
val result = target.mainClass
assertThat(result?.underlyingPsiClass, equalTo(psiClass))
}
@Test
fun `test should handle empty class list when defining main class`() {
val target = AssistantViewFile(ktFile)
val result = target.mainClass
assertThat(result, absent())
}
@Test
fun `test should provide file type`() {
val fileType: FileType = KotlinFileType.INSTANCE
every { ktFile.fileType } returns fileType
val target = AssistantViewFile(ktFile)
val result = target.fileType
assertThat(result, equalTo(fileType))
}
@Test
fun `test should have name`() {
every { ktFile.name } returns "GoodFileName"
val target = AssistantViewFile(ktFile)
val result = target.name
assertThat(result, equalTo(ktFile.name))
}
}
| 0 |
Kotlin
|
0
| 0 |
137d94d59ff4fbdd82f598fcdd25c1fa8c4b3be4
| 2,672 |
AssistantView
|
MIT License
|
util/namegeneration/src/test/kotlin/de/gleex/pltcmd/util/namegeneration/GeneratorsTest.kt
|
Baret
| 227,677,538 | false |
{"Kotlin": 771077}
|
package de.gleex.pltcmd.util.namegeneration
import de.gleex.kng.generators.nextAsString
import de.gleex.pltcmd.util.namegeneration.wordlists.bludgeoningWeapons
import de.gleex.pltcmd.util.namegeneration.wordlists.bluntTools
import io.kotest.core.spec.style.WordSpec
import io.kotest.inspectors.forAll
import io.kotest.matchers.collections.containExactly
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.endWith
class GeneratorsTest : WordSpec() {
init {
"The NATO Alphabet generator" should {
"generate 26 unique values" {
NatoAlphabetGenerator.nameCount shouldBe 26
NatoAlphabetGenerator.isAutoResetting shouldBe true
val generatedNames: List<String> = buildList {
repeat(26) {
add(NatoAlphabetGenerator.nextAsString())
}
}
generatedNames should containExactly("Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliet", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whiskey", "Xray", "Yankee", "Zulu")
NatoAlphabetGenerator.nextAsString() shouldBe "Alpha"
}
}
"The generator for blunt items" should {
"be auto-resetting" {
BluntToolAndWeaponNamesNumbered.isAutoResetting shouldBe true
}
val oneIterationPerNumberSize = bluntTools.size + bludgeoningWeapons.size
"contain 10 * $oneIterationPerNumberSize (number_of_wordlist_entries) names" {
BluntToolAndWeaponNamesNumbered.nameCount shouldBe (bluntTools.size + bludgeoningWeapons.size) * 10
}
"generate $oneIterationPerNumberSize '...-Zero' names first" {
val namesWithZero = buildList {
repeat(oneIterationPerNumberSize) {
add(BluntToolAndWeaponNamesNumbered.nextAsString())
}
}
namesWithZero.forAll { it should endWith("-Zero") }
val namesWithOne = buildList {
repeat(oneIterationPerNumberSize) {
add(BluntToolAndWeaponNamesNumbered.nextAsString())
}
}
namesWithOne.forAll { it should endWith("-One") }
}
}
}
}
| 47 |
Kotlin
|
0
| 4 |
d14f504f8e350f7bb54fe9ac819f54da7e1b8cff
| 2,483 |
pltcmd
|
MIT License
|
demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/set/DateSet.kt
|
WindSekirun
| 92,814,709 | false | null |
package pyxis.uzuki.live.richutilskt.demo.set
import android.content.Context
import pyxis.uzuki.live.richutilskt.demo.R
import pyxis.uzuki.live.richutilskt.demo.item.CategoryItem
import pyxis.uzuki.live.richutilskt.demo.item.ExecuteItem
import pyxis.uzuki.live.richutilskt.demo.item.generateExecuteItem
/**
* Created by pyxis on 06/11/2017.
*/
fun Context.getDateSet(): ArrayList<ExecuteItem> {
val list = arrayListOf<ExecuteItem>()
val asDateString = generateExecuteItem(CategoryItem.DATE, "asDateString",
getString(R.string.date_message_asdatestring_date),
"date?.asDateString()",
"RichUtils.asDateString(date);")
list.add(asDateString)
val asDateString2 = generateExecuteItem(CategoryItem.DATE, "asDateString",
getString(R.string.date_message_asdatestring_long),
"System.currentTimeMillis().asDateString()",
"RichUtils.asDateString(timestamp);")
list.add(asDateString2)
val parseDate = generateExecuteItem(CategoryItem.DATE, "parseDate",
getString(R.string.date_message_parsedate),
"\"2016-11-23 11:11:11\".parseDate()",
"RichUtils.parseDate(\"2016-11-23 11:11:11\")")
list.add(parseDate)
val toDateString = generateExecuteItem(CategoryItem.DATE, "toDateString",
getString(R.string.date_message_todatestring),
"\"2016-11-23 11:11:11\".toDateString(\"yyyy-MM-dd HH:mm:ss\", \"yyyy.mm.dd\")",
"RichUtils.toDateString(\"2016-11-23 11:11:11\", \"yyyy-Mm-dd HH:mm:ss\", \"yyyy.MM.dd\")")
list.add(toDateString)
return list
}
| 3 |
Kotlin
|
28
| 171 |
351b6be5c35f7e6864f49f202532a7dd21f2d1df
| 1,620 |
RichUtilsKt
|
Apache License 2.0
|
worldwind/src/jvmCommonMain/kotlin/earth/worldwind/layer/mbtiles/MBTiles.kt
|
WorldWindEarth
| 488,505,165 | false |
{"Kotlin": 2798182, "JavaScript": 459619, "HTML": 108987, "CSS": 8778}
|
package earth.worldwind.layer.mbtiles
import com.j256.ormlite.field.DataType
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable
import earth.worldwind.layer.mbtiles.MBTiles.Companion.TABLE_NAME
@DatabaseTable(tableName = TABLE_NAME)
class MBTiles {
@DatabaseField(columnName = ZOOM_LEVEL, dataType = DataType.INTEGER, uniqueCombo = true)
var zoomLevel = 0
@DatabaseField(columnName = TILE_COLUMN, dataType = DataType.INTEGER, uniqueCombo = true)
var tileColumn = 0
@DatabaseField(columnName = TILE_ROW, dataType = DataType.INTEGER, uniqueCombo = true)
var tileRow = 0
@DatabaseField(columnName = TILE_DATA, dataType = DataType.BYTE_ARRAY)
var tileData: ByteArray? = null
companion object {
const val TABLE_NAME = "tiles"
const val ZOOM_LEVEL = "zoom_level"
const val TILE_COLUMN = "tile_column"
const val TILE_ROW = "tile_row"
const val TILE_DATA = "tile_data"
}
}
| 22 |
Kotlin
|
12
| 98 |
b5ee69cdd30f6c6a90bf3bec638a3bc5bdb0fbc2
| 984 |
WorldWindKotlin
|
Apache License 2.0
|
src/main/kotlin/world/cepi/packer/PackerPlugin.kt
|
Project-Cepi
| 322,375,323 | false | null |
package world.cepi.packer
import com.google.inject.Inject
import com.velocitypowered.api.event.Subscribe
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent
import com.velocitypowered.api.plugin.Dependency
import com.velocitypowered.api.plugin.Plugin
import com.velocitypowered.api.proxy.ProxyServer
import org.slf4j.Logger
@Plugin(
id = "packer",
name = "Packer Plugin",
version = "0.1.0",
url = "https://cepi.world",
description = "Handles resourcepacks from an external URL",
authors = ["Cepi"],
dependencies = [Dependency(id = "votlin")]
)
class PackerPlugin @Inject constructor(private val server: ProxyServer, private val logger: Logger) {
@Subscribe
fun onProxyInitialization(@SuppressWarnings event: ProxyInitializeEvent) {
Companion.server = server
server.eventManager.register(this, EventListener)
PackerCommand.register(server)
logger.info("[Packer] has been enabled!")
}
companion object {
lateinit var server: ProxyServer
}
}
| 4 |
Kotlin
|
0
| 1 |
a11d72a08a8011a4a5770b19755330adde3afea4
| 1,041 |
Packer
|
MIT License
|
automation/code-generator/src/main/kotlin/io/github/typesafegithub/workflows/codegenerator/generation/ClassNaming.kt
|
typesafegithub
| 439,670,569 | false | null |
package io.github.typesafegithub.workflows.wrappergenerator.generation
import io.github.typesafegithub.workflows.actionsmetadata.model.ActionCoords
import java.util.Locale
fun ActionCoords.buildActionClassName(): String {
val versionString = version
.let { if (it.startsWith("v")) it else "v$it" }
.replaceFirstChar { it.titlecase(Locale.getDefault()) }
return "${name.toPascalCase()}$versionString"
}
| 28 | null |
19
| 363 |
3fdfa73ba9deb94943115d4cc1013020dafb6d90
| 428 |
github-workflows-kt
|
Apache License 2.0
|
kompack-base/src/jvmTest/kotlin/com/wunderbee/kompack/mpack/util/BufferSourceInputStreamTest.kt
|
dedee
| 621,699,131 | false | null |
package com.wunderbee.kompack.mpack.util
import java.io.ByteArrayInputStream
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class BufferSourceInputStreamTest {
@Test
fun pull() {
val ins = BufferSourceInputStream(ByteArrayInputStream(byteArrayOf(0, 1, 2, 3, 4, 5)))
assertEquals(0, ins.pullSByte())
assertEquals(1, ins.pullSByte())
assertEquals(2, ins.pullSByte())
assertEquals(3, ins.pullSByte())
assertEquals(4, ins.pullSByte())
assertEquals(5, ins.pullSByte())
assertFailsWith<Exception> { ins.pullSByte() }
}
@Test
fun pullAndPushBack() {
val ins = BufferSourceInputStream(ByteArrayInputStream(byteArrayOf(0, 1, 2, 3, 4, 5)))
assertEquals(0, ins.pullSByte())
ins.pushBack()
assertEquals(0, ins.pullSByte())
assertEquals(1, ins.pullSByte())
assertEquals(2, ins.pullSByte())
assertEquals(3, ins.pullSByte())
assertEquals(4, ins.pullSByte())
assertEquals(5, ins.pullSByte())
ins.pushBack()
assertEquals(5, ins.pullSByte())
assertFailsWith<Exception> { ins.pullSByte() }
}
@Test
fun pullAndPushBackTwice() {
val ins = BufferSourceInputStream(ByteArrayInputStream(byteArrayOf(0, 1, 2, 3, 4, 5)))
assertEquals(0, ins.pullSByte())
ins.pushBack()
assertFailsWith<AssertionError> { ins.pushBack() }
}
@Test
fun pullSigned() {
val ins = BufferSourceInputStream(ByteArrayInputStream(byteArrayOf(0, -1, -2, -3, -4, -5)))
assertEquals(0, ins.pullSByte())
assertEquals(-1, ins.pullSByte())
assertEquals(-2, ins.pullSByte())
assertEquals(-3, ins.pullSByte())
assertEquals(-4, ins.pullSByte())
assertEquals(-5, ins.pullSByte())
assertFailsWith<Exception> { ins.pullSByte() }
}
@Test
fun pullUSigned() {
val ins = BufferSourceInputStream(ByteArrayInputStream(byteArrayOf(0, -1, -2, -3, -4, -5)))
assertEquals(0, ins.pullUByte())
assertEquals(255, ins.pullUByte())
assertEquals(254, ins.pullUByte())
assertEquals(253, ins.pullUByte())
assertEquals(252, ins.pullUByte())
assertEquals(251, ins.pullUByte())
assertFailsWith<Exception> { ins.pullSByte() }
}
}
| 7 |
Kotlin
|
0
| 0 |
62ddc06864526bfcacdb2575b7eb91d576a684af
| 2,373 |
kompack
|
Apache License 2.0
|
src/main/kotlin/io/articulus/fhir/model/dstu3/Person.kt
|
Articulus-Tech
| 160,540,104 | false | null |
//
// Generated from FHIR Version 3.0.1.11917 on 2018-12-05T09:46:12.656
//
// 2018, Articulus
//
package io.articulus.fhir.model.dstu3
import kotlin.collections.List
/**
* A generic person record
*
* Demographics and administrative information about a person independent of a specific health-related context.
*/
open class Person() : DomainResource() {
/**
* This person's record is in active use
*/
var active: Boolean? = null
val address: List<Address> = mutableListOf<Address>()
/**
* The date on which the person was born
*/
var birthDate: String? = null
/**
* male | female | other | unknown
*/
var gender: String? = null
val identifier: List<Identifier> = mutableListOf<Identifier>()
val link: List<PersonLink> = mutableListOf<PersonLink>()
/**
* The organization that is the custodian of the person record
*/
var managingOrganization: Reference? = null
val name: List<HumanName> = mutableListOf<HumanName>()
/**
* Image of the person
*/
var photo: Attachment? = null
val telecom: List<ContactPoint> = mutableListOf<ContactPoint>()
}
/**
* Link to a resource that concerns the same actual person
*
* Link to a resource that concerns the same actual person.
*/
open class PersonLink() : BackboneElement() {
/**
* level1 | level2 | level3 | level4
*/
var assurance: String? = null
/**
* The resource to which this actual person is associated
*/
var target: Reference = Reference()
}
| 0 |
Kotlin
|
0
| 3 |
90b7b912048fc61ad3696497d1ceaf76459852cb
| 1,561 |
kotlin-fhir-model
|
Apache License 2.0
|
src/main/kotlin/com/github/kerubistan/kerub/services/AssignmentService.kt
|
kerubistan
| 19,528,622 | false | null |
package com.github.kerubistan.kerub.services
import com.github.kerubistan.kerub.model.controller.Assignment
import javax.ws.rs.Consumes
import javax.ws.rs.Path
import javax.ws.rs.PathParam
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
@Path("/controllers/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
interface AssignmentService {
@Path("{controller}/assignments")
fun listByController(
@PathParam("controller")
controller: String): List<Assignment>
}
| 109 |
Kotlin
|
4
| 14 |
99cb43c962da46df7a0beb75f2e0c839c6c50bda
| 510 |
kerub
|
Apache License 2.0
|
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/channels/TLAdminLogResults.kt
|
Miha-x64
| 436,587,061 | true |
{"Kotlin": 3919807, "Java": 75352}
|
package com.github.badoualy.telegram.tl.api.channels
import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID
import com.github.badoualy.telegram.tl.api.TLAbsChat
import com.github.badoualy.telegram.tl.api.TLAbsUser
import com.github.badoualy.telegram.tl.api.TLChannelAdminLogEvent
import com.github.badoualy.telegram.tl.core.TLObject
import com.github.badoualy.telegram.tl.core.TLObjectVector
import com.github.badoualy.telegram.tl.serialization.TLDeserializer
import com.github.badoualy.telegram.tl.serialization.TLSerializer
import java.io.IOException
/**
* channels.adminLogResults#ed8af74d
*
* @author <NAME> <EMAIL>
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
class TLAdminLogResults() : TLObject() {
var events: TLObjectVector<TLChannelAdminLogEvent> = TLObjectVector()
var chats: TLObjectVector<TLAbsChat> = TLObjectVector()
var users: TLObjectVector<TLAbsUser> = TLObjectVector()
private val _constructor: String = "channels.adminLogResults#ed8af74d"
override val constructorId: Int = CONSTRUCTOR_ID
constructor(
events: TLObjectVector<TLChannelAdminLogEvent>,
chats: TLObjectVector<TLAbsChat>,
users: TLObjectVector<TLAbsUser>
) : this() {
this.events = events
this.chats = chats
this.users = users
}
@Throws(IOException::class)
override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) {
writeTLVector(events)
writeTLVector(chats)
writeTLVector(users)
}
@Throws(IOException::class)
override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) {
events = readTLVector<TLChannelAdminLogEvent>()
chats = readTLVector<TLAbsChat>()
users = readTLVector<TLAbsUser>()
}
override fun computeSerializedSize(): Int {
var size = SIZE_CONSTRUCTOR_ID
size += events.computeSerializedSize()
size += chats.computeSerializedSize()
size += users.computeSerializedSize()
return size
}
override fun toString() = _constructor
override fun equals(other: Any?): Boolean {
if (other !is TLAdminLogResults) return false
if (other === this) return true
return events == other.events
&& chats == other.chats
&& users == other.users
}
companion object {
const val CONSTRUCTOR_ID: Int = 0xed8af74d.toInt()
}
}
| 1 |
Kotlin
|
2
| 3 |
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
| 2,523 |
kotlogram-resurrected
|
MIT License
|
src/main/kotlin/de/triplet/gradle/play/GeneratePlayResourcesTask.kt
|
jc48rho
| 135,592,332 | true |
{"Kotlin": 45368, "Groovy": 32289}
|
package de.triplet.gradle.play
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import java.io.File
open class GeneratePlayResourcesTask : DefaultTask() {
lateinit var outputFolder: File
@TaskAction
fun generate() {
inputs.files.files
.filter(File::exists)
.forEach { it.copyRecursively(outputFolder, true) }
}
}
| 0 |
Kotlin
|
0
| 0 |
910d5dd1af825d841f7e0f4326f6f3b278470bd3
| 396 |
gradle-play-publisher
|
MIT License
|
app-main/src/main/kotlin/com/github/fj/board/exception/client/post/CannotDeletePostException.kt
|
oen142
| 449,552,568 | true |
{"Kotlin": 584930, "Groovy": 179252, "Java": 88552, "Dart": 11943, "HTML": 1113, "Batchfile": 488, "Shell": 479, "Swift": 404, "Vim Snippet": 314, "Objective-C": 38}
|
/*
* spring-message-board-demo
* Refer to LICENCE.txt for licence details.
*/
package com.github.fj.board.exception.client.post
import com.github.fj.board.exception.GeneralHttpException
import org.springframework.http.HttpStatus
/**
* @author <NAME>(<EMAIL>)
* @since 03 - Aug - 2020
*/
class CannotDeletePostException(
override val message: String = "Cannot delete post in target board.",
override val cause: Throwable? = null
) : GeneralHttpException(HttpStatus.FORBIDDEN, message, cause) {
companion object {
val STATUS = HttpStatus.FORBIDDEN
}
}
| 0 | null |
0
| 0 |
9a3860f780a1c994fcc7f2bed1525a0d73a3fa64
| 582 |
spring-board-demo
|
Beerware License
|
native/objcexport-header-generator/impl/analysis-api/src/org/jetbrains/kotlin/objcexport/analysisApiUtils/isHashCode.kt
|
JetBrains
| 3,432,266 | false |
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.objcexport.analysisApiUtils
import org.jetbrains.kotlin.analysis.api.KaSession
import org.jetbrains.kotlin.analysis.api.symbols.KaCallableSymbol
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.StandardClassIds
private val hashCodeCallableId = CallableId(StandardClassIds.Any, Name.identifier("hashCode"))
internal fun KaSession.isHashCode(symbol: KaCallableSymbol): Boolean = symbol.callableId == hashCodeCallableId ||
symbol.allOverriddenSymbols.any { overriddenSymbol -> overriddenSymbol.callableId == hashCodeCallableId }
| 181 |
Kotlin
|
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 842 |
kotlin
|
Apache License 2.0
|
src/main/kotlin/org/kneelawk/kotlintest/proxy/KotlinTestProxyClient.kt
|
hepteract
| 131,376,476 | true |
{"Kotlin": 3867}
|
package org.kneelawk.kotlintest.proxy
/**
* Client proxy. Houses all functionality that only works on the client.
*/
class KotlinTestProxyClient : KotlinTestProxyCommon() {
}
| 0 |
Kotlin
|
0
| 0 |
6dae318b319360968834b14c596118eee00b8d79
| 179 |
KotlinTest
|
MIT License
|
sdk/src/main/java/tv/remo/android/controller/sdk/components/RemoBroadcaster.kt
|
NoahAndrews
| 324,432,149 | true |
{"Kotlin": 161601, "Java": 28273, "Python": 237}
|
package tv.remo.android.controller.sdk.components
import android.app.Activity
import android.content.Context
import android.content.Intent
import org.btelman.controlsdk.enums.ComponentStatus
import org.btelman.controlsdk.hardware.interfaces.DriverComponent
import org.btelman.controlsdk.hardware.interfaces.HardwareDriver
import java.nio.charset.Charset
/**
* Created by Brendon on 9/22/2019.
*/
@DriverComponent(
description = "Broadcasts controls to other apps that were given permission. Only supports ArduinoSendString",
requiresSetup = false
)
class RemoBroadcaster : HardwareDriver{
private lateinit var context: Context
override fun enable() {
}
override fun disable() {
sendToBroadcast("stop")
}
override fun getStatus(): ComponentStatus {
return ComponentStatus.STABLE
}
override fun initConnection(context: Context) {
this.context = context
}
override fun isConnected(): Boolean {
return true
}
override fun send(byteArray: ByteArray): Boolean {
sendToBroadcast(byteArray.toString(Charset.defaultCharset()))
return true
}
fun sendToBroadcast(data : String){
val intent = Intent("tv.remo.android.controller.sdk.socket.controls").apply {
putExtra("command", data)
}
context.sendBroadcast(intent)
}
override fun setupComponent(activity: Activity, force: Boolean): Int {
return -1
}
override fun usesCustomSetup(): Boolean {
return false
}
override fun clearSetup(context: Context) {
}
override fun getAutoReboot(): Boolean {
return false
}
override fun needsSetup(activity: Activity): Boolean {
return false
}
override fun receivedComponentSetupDetails(context: Context, intent: Intent?) {
}
}
| 0 | null |
0
| 0 |
3c511236dc7b8a6ad894cd798aebfe764597b9c7
| 1,852 |
controller-for-android
|
Apache License 2.0
|
app/src/main/java/com/oguzdogdu/wallieshd/presentation/search/SearchEvent.kt
|
oguzsout
| 616,912,430 | false | null |
package com.oguzdogdu.wallieshd.presentation.search
sealed class SearchEvent {
data class EnteredSearchQuery(
val query: String?,
val language: String?
) : SearchEvent()
data object GetAppLanguageValue : SearchEvent()
}
| 0 | null |
6
| 61 |
ddd410404ffd346e221fcd183226496411d8aa43
| 249 |
Wallies
|
MIT License
|
core/src/main/kotlin/finance/tegro/core/jackson/serializer/BigDecimalStringSerializer.kt
|
TegroTON
| 586,902,794 | false |
{"Kotlin": 227007}
|
package finance.tegro.core.jackson.serializer
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import java.math.BigDecimal
class BigDecimalStringSerializer : StdSerializer<BigDecimal>(BigDecimal::class.java) {
override fun serialize(value: BigDecimal, gen: JsonGenerator, provider: SerializerProvider?) {
gen.writeString(value.toString())
}
}
| 16 |
Kotlin
|
4
| 0 |
749b2877b2c886383898c70fae1d617bcc46755d
| 477 |
API-DEX-TON-Blockchain
|
MIT License
|
kotlin/services/keyspaces/src/main/kotlin/com/example/keyspace/HelloKeyspaces.kt
|
awsdocs
| 66,023,605 | false | null |
// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
// snippet-sourcedescription:[HelloKeyspaces.kt demonstrates how to display all current Amazon Keyspaces names and Amazon Resource Names (ARNs).]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Keyspaces]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.keyspace
import aws.sdk.kotlin.services.keyspaces.KeyspacesClient
import aws.sdk.kotlin.services.keyspaces.model.ListKeyspacesRequest
// snippet-start:[keyspace.kotlin.hello.main]
/**
Before running this Kotlin code example, set up your development environment, including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main() {
listKeyspaces()
}
suspend fun listKeyspaces() {
val keyspacesRequest = ListKeyspacesRequest {
maxResults = 10
}
KeyspacesClient { region = "us-east-1" }.use { keyClient ->
val response = keyClient.listKeyspaces(keyspacesRequest)
response.keyspaces?.forEach { keyspace ->
println("The name of the keyspace is ${keyspace.keyspaceName}")
}
}
}
// snippet-end:[keyspace.kotlin.hello.main]
| 248 | null |
5386
| 8,560 |
e6bb7238743b4c11cfa7bcfad882e049b6d450f4
| 1,359 |
aws-doc-sdk-examples
|
Apache License 2.0
|
app/src/androidTest/java/com/intact/testingapp/ui/activity/ActivityTestSuite.kt
|
DevAnuragGarg
| 263,376,735 | false | null |
package com.intact.testingapp.ui.activity
import org.junit.runner.RunWith
import org.junit.runners.Suite
/**
* To organize the execution of your instrumented unit tests, you can group a collection of test
* classes in a test suite class and run these tests together. Test suites can be nested; your test
* suite can group other test suites and run all their component test classes together.
*/
@RunWith(Suite::class)
@Suite.SuiteClasses(HomeActivityTest::class, DetailActivityTest::class)
class ActivityTestSuite
| 0 |
Kotlin
|
0
| 1 |
bdbe981b9787076e138f46f950ae98b9c8a96834
| 518 |
TestingApp
|
Apache License 2.0
|
src/commonMain/kotlin/baaahs/gl/render/RenderManager.kt
|
baaahs
| 174,897,412 | false | null |
package baaahs.gl.render
import baaahs.device.DeviceType
import baaahs.fixtures.Fixture
import baaahs.fixtures.RenderPlan
import baaahs.getBang
import baaahs.gl.GlContext
import baaahs.gl.glsl.FeedResolver
import baaahs.gl.glsl.GlslProgram
import baaahs.gl.patch.LinkedPatch
import baaahs.model.Model
import baaahs.util.Logger
class RenderManager(
private val model: Model,
private val createContext: () -> GlContext
) {
private val renderEngines = model.allEntities.map { it.deviceType }.distinct()
.associateWith { deviceType ->
val gl = createContext()
ModelRenderEngine(
gl, model, deviceType, resultDeliveryStrategy = pickResultDeliveryStrategy(gl)
)
}
fun getEngineFor(deviceType: DeviceType): ModelRenderEngine =
renderEngines.getBang(deviceType, "render engine")
suspend fun draw() {
// If there are multiple RenderEngines, let them parallelize the render step...
renderEngines.values.forEach { it.draw() }
// ... before transferring results back to CPU memory.
renderEngines.values.forEach { it.finish() }
}
fun addFixture(fixture: Fixture): FixtureRenderTarget {
return getEngineFor(fixture.deviceType).addFixture(fixture)
}
fun removeRenderTarget(renderTarget: FixtureRenderTarget) {
getEngineFor(renderTarget.fixture.deviceType).removeRenderTarget(renderTarget)
}
fun compile(deviceType: DeviceType, linkedPatch: LinkedPatch, feedResolver: FeedResolver): GlslProgram {
return getEngineFor(deviceType).compile(linkedPatch, feedResolver)
}
fun setRenderPlan(renderPlan: RenderPlan) {
renderEngines.forEach { (deviceType, engine) ->
val deviceTypeRenderPlan = renderPlan.deviceTypes[deviceType]
engine.setRenderPlan(deviceTypeRenderPlan)
if (deviceTypeRenderPlan == null) {
logger.debug { "No render plan for ${deviceType.title}" }
}
}
}
fun logStatus() {
renderEngines.values.forEach { it.logStatus() }
}
companion object {
private val logger = Logger<RenderManager>()
}
}
| 82 |
Kotlin
|
4
| 21 |
c434a734a751250566ccfbb6193c1af80cc03944
| 2,193 |
sparklemotion
|
MIT License
|
backdroplibrary/src/main/java/de/si/backdroplibrary/activity/ActivityEventHandling.kt
|
Str3l0k
| 186,306,967 | false | null |
package de.si.backdroplibrary.activity
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import androidx.core.animation.doOnStart
import androidx.core.graphics.luminance
import de.si.backdroplibrary.BackdropEvent
import de.si.backdroplibrary.children.CardBackdropFragment
import de.si.backdroplibrary.children.FullscreenBackdropFragment
import de.si.backdroplibrary.children.FullscreenRevealBackdropFragment
import de.si.backdroplibrary.components.toolbar.BackdropToolbarItem
import de.si.backdroplibrary.components.toolbar.BackdropToolbarMainButtonState
import kotlinx.android.synthetic.main.layout_main.*
import kotlinx.android.synthetic.main.layout_toolbar.*
import kotlinx.android.synthetic.main.layout_toolbar.view.*
internal fun BackdropActivity.onEvent(event: BackdropEvent): Boolean {
return when (event) {
// content events
is BackdropEvent.PrefetchBackdropContentView -> handlePrefetchBackdropContentEvent(event.layoutRes)
is BackdropEvent.ShowBackdropContentView -> handleShowBackdropContentEvent(event.layoutRes)
BackdropEvent.HideBackdropContentView -> handleHideBackdropContentEvent()
is BackdropEvent.BackdropContentNowVisible -> onBackdropContentVisible(event.view)
BackdropEvent.BackdropContentNowHidden -> onBackdropContentInvisible()
is BackdropEvent.ChangeBackdropColor -> fadeBackgroundColor(event.color)
// toolbar events
BackdropEvent.PrimaryActionTriggered -> onPrimaryActionClicked()
BackdropEvent.MoreActionTriggered -> onMoreActionClicked()
is BackdropEvent.ChangeToolbarItem -> handleToolbarItemChangedEvent(event.toolbarItem)
is BackdropEvent.StartActionMode -> handleToolbarActionModeStart(event.actionModeToolbarItem)
BackdropEvent.FinishActionMode -> handleToolbarActionModeFinish()
BackdropEvent.PrimaryActionInActionModeTriggered -> onPrimaryActionInActionModeClicked()
BackdropEvent.MoreActionInActionModeTriggered -> onMoreActionInActionModeClicked()
BackdropEvent.ActionModeFinished -> onToolbarActionModeFinished()
BackdropEvent.MenuActionTriggered -> onMenuActionClicked()
// card stack events
is BackdropEvent.AddTopCard -> handleAddTopCardEvent(event.fragment)
BackdropEvent.RemoveTopCard -> handleRemoveTopCardEvent()
// fullscreen
is BackdropEvent.ShowFullscreenFragment -> handleShowFullscreenFragmentEvent(event.fragment)
is BackdropEvent.RevealFullscreenFragment -> handleRevealFullscreenFragmentEvent(event.fragment)
BackdropEvent.HideFullscreenFragment -> handleHideFullscreenFragmentEvent()
}
}
//-----------------------------------------
// Backdrop content event handling
//-----------------------------------------
private fun BackdropActivity.handlePrefetchBackdropContentEvent(layoutResId: Int): Boolean {
backdropContent.preCacheContentView(layoutResId)
return true
}
private fun BackdropActivity.handleShowBackdropContentEvent(layoutResId: Int): Boolean {
backdropContent.showContentView(layoutResId) { contentView ->
backdropToolbar.disableActions()
backdropToolbar.showCloseButton()
backdropCardStack.disable()
animateBackdropOpening(contentView.height.toFloat())
}
return true
}
private fun BackdropActivity.handleHideBackdropContentEvent(): Boolean {
animateBackdropClosing()
backdropContent.hide()
backdropCardStack.enable()
backdropToolbar.enableActions()
when {
backdropToolbar.isInActionMode -> backdropToolbar.showCloseButton()
backdropCardStack.hasMoreThanOneEntry -> backdropToolbar.showBackButton()
else -> backdropToolbar.showMenuButton()
}
backdropViewModel.emit(BackdropEvent.BackdropContentNowHidden)
return true
}
//-----------------------------------------
// toolbar event handling
//-----------------------------------------
private fun BackdropActivity.handleToolbarItemChangedEvent(toolbarItem: BackdropToolbarItem): Boolean {
val mainButtonState: BackdropToolbarMainButtonState = if (backdropCardStack.hasMoreThanOneEntry) {
BackdropToolbarMainButtonState.BACK
} else {
baseCardFragment.menuButtonState
}
backdropToolbar.configure(toolbarItem, mainButtonState)
return true
}
private fun BackdropActivity.handleToolbarActionModeStart(toolbarItem: BackdropToolbarItem): Boolean {
backdropToolbar.startActionMode(toolbarItem)
return true
}
private fun BackdropActivity.handleToolbarActionModeFinish(): Boolean {
val menuRes: Int? = baseCardFragment.mainMenuRes
// TODO extract
val mainButtonState: BackdropToolbarMainButtonState = when {
backdropCardStack.hasMoreThanOneEntry -> BackdropToolbarMainButtonState.BACK
menuRes == null -> BackdropToolbarMainButtonState.NO_LAYOUT_ERROR
else -> baseCardFragment.menuButtonState
}
backdropToolbar.finishActionMode(mainButtonState)
return true
}
private fun BackdropActivity.fadeBackgroundColor(color: Int): Boolean {
val colorDrawable = layout_backdrop.background as? ColorDrawable ?: return true
val newTextColor = when {
color.luminance < 0.45 -> Color.WHITE
else -> Color.BLACK
}
val backgroundColorAnimator = ObjectAnimator.ofArgb(layout_backdrop, "backgroundColor", colorDrawable.color, color)
val textColorAnimator = ObjectAnimator.ofArgb(layout_backdrop_toolbar_titles.text_backdrop_toolbar_title.currentTextColor,
newTextColor)
textColorAnimator.addUpdateListener { animator ->
val colorValue: Int = animator.animatedValue as Int
backdropToolbar.setTintColor(colorValue)
}
AnimatorSet().apply {
playTogether(backgroundColorAnimator, textColorAnimator)
doOnStart { configureStatusBarAppearance(color) }
}.start()
return true
}
//-----------------------------------------
// card stack event handling
//-----------------------------------------
private fun BackdropActivity.handleAddTopCardEvent(cardFragment: CardBackdropFragment): Boolean {
backdropCardStack.push(cardFragment)
backdropToolbar.configure(cardFragment.toolbarItem, BackdropToolbarMainButtonState.BACK)
return true
}
private fun BackdropActivity.handleRemoveTopCardEvent(): Boolean {
backdropCardStack.pop()
val menuRes: Int? = baseCardFragment.mainMenuRes
val mainButtonState: BackdropToolbarMainButtonState = when {
backdropCardStack.hasMoreThanOneEntry -> BackdropToolbarMainButtonState.BACK
menuRes == null -> BackdropToolbarMainButtonState.NO_LAYOUT_ERROR
else -> baseCardFragment.menuButtonState
}
backdropToolbar.configure(backdropCardStack.topFragment.toolbarItem, mainButtonState)
return true
}
//-----------------------------------------
// fullscreen fragment event handling
//-----------------------------------------
private fun BackdropActivity.handleShowFullscreenFragmentEvent(fragment: FullscreenBackdropFragment): Boolean {
fullscreenDialogs.showFullscreenFragment(fragment)
return true
}
private fun BackdropActivity.handleHideFullscreenFragmentEvent(): Boolean {
fullscreenDialogs.hideFullscreenFragment()
return true
}
private fun BackdropActivity.handleRevealFullscreenFragmentEvent(fragment: FullscreenRevealBackdropFragment): Boolean {
fullscreenDialogs.revealFullscreen(fragment)
return true
}
| 2 | null |
1
| 1 |
6497c95cf23952e88b56b98fcb173a822284471e
| 7,741 |
Backdrop_Android
|
Apache License 2.0
|
data/src/main/java/com/sedsoftware/yaptalker/data/parsed/TopicPageParsed.kt
|
djkovrik
| 98,050,611 | false | null |
package com.sedsoftware.yaptalker.data.parsed
import pl.droidsonroids.jspoon.annotation.Selector
/**
* Class which represents parsed topic page in data layer.
*/
class TopicPageParsed {
@Selector(value = "h1.subpage > a.subtitle", defValue = "Unknown")
lateinit var topicTitle: String
@Selector(value = "td.bottommenu > font", defValue = "")
lateinit var isClosed: String
@Selector(value = "input[name~=auth_key]", attr = "outerHtml", regex = "value=\"([a-z0-9]+)\"", defValue = "")
lateinit var authKey: String
@Selector(value = "div.rating-value", regex = "([-\\d]+)", defValue = "0")
lateinit var topicRating: String
@Selector(value = "div[rel=rating] img[src$=rating-cell-minus.gif]", attr = "src", defValue = "")
lateinit var topicRatingPlusAvailable: String
@Selector(value = "div[rel=rating] img[src$=rating-cell-plus.gif]", attr = "src", defValue = "")
lateinit var topicRatingMinusAvailable: String
@Selector(value = "div[rel=rating] img[src$=rating-cell-plus-clicked.gif]", attr = "src", defValue = "")
lateinit var topicRatingPlusClicked: String
@Selector(value = "div[rel=rating] img[src$=rating-cell-minus-clicked.gif]", attr = "src", defValue = "")
lateinit var topicRatingMinusClicked: String
@Selector(
value = "div[rel=rating] a[onclick~=doRatePost]",
regex = "(?<=\\d{2}, )(\\d+)((?=, ))",
attr = "outerHtml",
defValue = "0"
)
lateinit var topicRatingTargetId: String
@Selector(value = "table.row3")
lateinit var navigation: TopicNavigationPanel
@Selector(value = "table[id~=p_row_\\d+]:has(.normalname)")
lateinit var posts: List<PostItemParsed>
}
| 0 |
Kotlin
|
4
| 9 |
465c34c3dc0dd0488b637073fddf6cd797e78613
| 1,695 |
YapTalker
|
Apache License 2.0
|
feature-governance-impl/src/main/java/io/novafoundation/nova/feature_governance_impl/data/repository/UnsupportedDelegationsRepository.kt
|
novasamatech
| 415,834,480 | false |
{"Kotlin": 7662708, "Java": 14723, "JavaScript": 425}
|
package io.novafoundation.nova.feature_governance_impl.data.repository
import io.novafoundation.nova.common.data.network.runtime.binding.BlockNumber
import io.novafoundation.nova.feature_governance_api.data.network.blockhain.model.Delegation
import io.novafoundation.nova.feature_governance_api.data.network.blockhain.model.ReferendumId
import io.novafoundation.nova.feature_governance_api.data.network.blockhain.model.TrackId
import io.novafoundation.nova.feature_governance_api.data.network.offchain.model.delegation.DelegateDetailedStats
import io.novafoundation.nova.feature_governance_api.data.network.offchain.model.delegation.DelegateMetadata
import io.novafoundation.nova.feature_governance_api.data.network.offchain.model.delegation.DelegateStats
import io.novafoundation.nova.feature_governance_api.data.network.offchain.model.vote.UserVote
import io.novafoundation.nova.feature_governance_api.data.repository.DelegationsRepository
import io.novafoundation.nova.feature_wallet_api.data.network.blockhain.types.Balance
import io.novafoundation.nova.runtime.extrinsic.multi.CallBuilder
import io.novafoundation.nova.runtime.multiNetwork.chain.model.Chain
import io.novafoundation.nova.runtime.multiNetwork.runtime.types.custom.vote.Conviction
import jp.co.soramitsu.fearless_utils.runtime.AccountId
class UnsupportedDelegationsRepository : DelegationsRepository {
override suspend fun isDelegationSupported(chain: Chain): Boolean {
return false
}
override suspend fun getDelegatesStats(recentVotesBlockThreshold: BlockNumber, chain: Chain): List<DelegateStats> {
return emptyList()
}
override suspend fun getDelegatesStatsByAccountIds(recentVotesBlockThreshold: BlockNumber, accountIds: List<AccountId>, chain: Chain): List<DelegateStats> {
return emptyList()
}
override suspend fun getDetailedDelegateStats(delegateAddress: String, recentVotesBlockThreshold: BlockNumber, chain: Chain): DelegateDetailedStats? {
return null
}
override suspend fun getDelegatesMetadata(chain: Chain): List<DelegateMetadata> {
return emptyList()
}
override suspend fun getDelegateMetadata(chain: Chain, delegate: AccountId): DelegateMetadata? {
return null
}
override suspend fun getDelegationsTo(delegate: AccountId, chain: Chain): List<Delegation> {
return emptyList()
}
override suspend fun allHistoricalVotesOf(user: AccountId, chain: Chain): Map<ReferendumId, UserVote>? {
return null
}
override suspend fun historicalVoteOf(user: AccountId, referendumId: ReferendumId, chain: Chain): UserVote? {
return null
}
override suspend fun directHistoricalVotesOf(
user: AccountId,
chain: Chain,
recentVotesBlockThreshold: BlockNumber?
): Map<ReferendumId, UserVote.Direct>? {
return null
}
override suspend fun CallBuilder.delegate(delegate: AccountId, trackId: TrackId, amount: Balance, conviction: Conviction) {
error("Unsupported")
}
override suspend fun CallBuilder.undelegate(trackId: TrackId) {
error("Unsupported")
}
}
| 14 |
Kotlin
|
5
| 9 |
66a5c0949aee03a5ebe870a1b0d5fa3ae929516f
| 3,148 |
nova-wallet-android
|
Apache License 2.0
|
app/src/test/java/io/github/drumber/kitsune/domain/mapper/LibraryEntryModificationMapperTest.kt
|
Drumber
| 406,471,554 | false |
{"Kotlin": 683035, "Ruby": 1828}
|
package io.github.drumber.kitsune.domain.mapper
import io.github.drumber.kitsune.utils.libraryEntryModification
import io.github.drumber.kitsune.utils.localLibraryEntryModification
import net.datafaker.Faker
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class LibraryEntryModificationMapperTest {
private val faker = Faker()
@Test
fun shouldMapLibraryEntryModificationToLocalLibraryEntryModification() {
// given
val libraryEntryModification = libraryEntryModification(faker)
// when
val localLibraryEntryModification = libraryEntryModification.toLocalLibraryEntryModification()
// then
assertThat(localLibraryEntryModification)
.usingRecursiveComparison()
.ignoringFields("state", "createTime")
.isEqualTo(libraryEntryModification)
}
@Test
fun shouldMapLocalLibraryEntryModificationToLibraryEntryModification() {
// given
val localLibraryEntryModification = localLibraryEntryModification(faker)
// when
val libraryEntryModification = localLibraryEntryModification.toLibraryEntryModification()
// then
assertThat(libraryEntryModification)
.usingRecursiveComparison()
.ignoringFields("state")
.isEqualTo(localLibraryEntryModification)
}
}
| 9 |
Kotlin
|
1
| 25 |
464cb3e4405dc33b5b7d495e372f369644f7814f
| 1,368 |
Kitsune
|
Apache License 2.0
|
loggenda/src/main/java/com/logg/loggenda/widget/Loggenda.kt
|
loggyourlife
| 147,519,494 | false | null |
package com.logg.loggenda.widget
import android.content.Context
import android.graphics.Typeface
import android.os.Handler
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.annotation.ColorInt
import androidx.core.view.ViewCompat
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.github.dewinjm.monthyearpicker.MonthYearPickerDialogFragment
import com.logg.loggenda.R
import com.logg.loggenda.adapter.MonthAdapter
import com.logg.loggenda.listener.BaseDayClickListener
import com.logg.loggenda.listener.BaseMonthChangeListener
import com.logg.loggenda.listener.BaseSnapBlockListener
import com.logg.loggenda.listener.OnCollapseListener
import com.logg.loggenda.model.EventItem
import com.logg.loggenda.util.*
import kotlinx.android.synthetic.main.layout_loggenda.view.*
import org.joda.time.LocalDate
import java.util.*
class Loggenda @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private var measuredViewHeight: Int = 0
private var monthAdapter: MonthAdapter? = null
private var selectedDay: LocalDate? = null
private var nowDate: LocalDate? = null
private var monthChangeListener: BaseMonthChangeListener? = null
private var previousMonthPosition: Int = -1
private var monthLayoutManager: MonthLayoutManager? = null
private var dayClickListener: BaseDayClickListener? = null
private var mSupportFragmentManager: FragmentManager? = null
private var snapHelper: SnapToBlock? = null
private var dayTypeFace: Typeface? = null
private var dayTextColor: Int = 0
private var dayTextSize: Float = 12f
private var onCollapseListener: OnCollapseListener? = null
init {
val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.layout_loggenda, this)
dayItemHeight = ViewUtils.calculateDayItemHeight(context, 40)
//setup()
}
fun setEvents(eventItems: MutableList<EventItem>?, position: Int) {
Handler().post {
monthAdapter?.getItem(position)!!.dayItems.forEach { dayItem ->
eventItems?.firstOrNull { it.date == dayItem.date }?.let {
dayItem.eventItem = it
}
}
monthAdapter?.notifyItemChanged(position)
monthLayoutManager?.setScrollEnabled(true)
}
}
fun setMonthChangeListener(monthChangeListener: BaseMonthChangeListener?) {
this.monthChangeListener = monthChangeListener
this.monthChangeListener?.onMonthChange(monthAdapter?.getItem(2)!!.monthDate, 2)
}
fun setDayClickListener(dayClickListener: BaseDayClickListener?) {
this.dayClickListener = dayClickListener
dayClickListener?.onDayClick(LocalDate(), 0, 0)
}
fun show(now: LocalDate, mSupportFragmentManager: FragmentManager?) {
nowDate = now
this.mSupportFragmentManager = mSupportFragmentManager
setup()
}
fun setNow(now: LocalDate) {
nowDate = now
monthAdapter?.setNow(now)
}
private fun setup() {
monthLayoutManager = MonthLayoutManager(context)
monthLayoutManager?.orientation = LinearLayoutManager.HORIZONTAL
recyclerView.layoutManager = monthLayoutManager
recyclerView.setHasFixedSize(true)
ViewCompat.setNestedScrollingEnabled(recyclerView, true)
snapHelper = SnapToBlock(1)
snapHelper?.attachToRecyclerView(recyclerView)
recyclerView.itemAnimator = null
monthAdapter = MonthAdapter(MonthUtils.generate3Month(nowDate!!, typeSelectedDateEnd), nowDate)
selectedDay?.let {
monthAdapter?.setSelectedDay(it)
}
recyclerView.adapter = monthAdapter
recyclerView.scrollToPosition(2)
snapHelper?.snappedPosition = 2
updateMonthName(2)
monthAdapter!!.dayClickListener = object : BaseDayClickListener() {
override fun onDayClick(day: LocalDate, monthPosition: Int, dayPosition: Int) {
super.onDayClick(day, monthPosition, dayPosition)
dayClickListener?.onDayClick(day, monthPosition, dayPosition)
selectedDay = day
}
}
ViewUtils.addDayNameViews(dayNameViewGroup, Locale.getDefault(), R.color.azure, dayTextSize)
snapHelper?.setSnapBlockCallback(object : BaseSnapBlockListener() {
override fun onBlockSnapped(snapPosition: Int) {
super.onBlockSnapped(snapPosition)
var snapPosition = snapPosition
if (snapPosition == 0) {
monthAdapter?.addMonth(MonthUtils.addMonth(monthAdapter?.getItem(snapPosition)!!.monthDate, true)!!, true)
snapPosition += 1
previousMonthPosition += 1
} else if (snapPosition == monthAdapter?.itemCount!! - 1 && monthAdapter?.getItem(snapPosition)!!.monthDate != LocalDate().dayOfMonth().withMinimumValue()) {
monthAdapter?.addMonth(MonthUtils.addMonth(monthAdapter?.getItem(snapPosition)!!.monthDate, false)!!, false)
snapPosition -= 1
previousMonthPosition -= 1
}
if (previousMonthPosition != snapPosition) {
previousMonthPosition = snapPosition
monthLayoutManager?.setScrollEnabled(false)
monthChangeListener?.onMonthChange(monthAdapter?.getItem(snapPosition)!!.monthDate, snapPosition)
}
snapHelper?.snappedPosition = snapPosition
monthAdapter?.notifyItemChanged(snapPosition)
updateMonthName(snapPosition)
refreshView()
}
})
btnNext?.setOnClickListener { view ->
monthAdapter?.getItem(snapHelper?.snappedPosition!!)?.let {
if (!it.monthDate.isEqual(nowDate?.dayOfMonth()?.withMinimumValue())) {
expand()
snapHelper?.snapToNext()
}
}
}
btnPrev?.setOnClickListener {
expand()
snapHelper?.snapToPrevious()
}
tvMonthName?.setOnClickListener {
showCalendar()
}
}
private fun showCalendar() {
// Use the calendar for create ranges
val calendar = GregorianCalendar.getInstance()
calendar.clear()
calendar.time = nowDate?.toDate()
val maxDate = calendar.timeInMillis // Get milliseconds of the modified date
val selectedMonth = calendar.get(Calendar.MONTH)
val selectedYear = calendar.get(Calendar.YEAR)
calendar.clear()
calendar.set(2010, 0, 1) // Set minimum date to show in dialog
val minDate = calendar.timeInMillis // Get milliseconds of the modified date
val dialogFragment = MonthYearPickerDialogFragment
.getInstance(selectedMonth, selectedYear, minDate, maxDate)
dialogFragment.setOnDateSetListener { year, month ->
val calendar = GregorianCalendar.getInstance()
calendar.clear()
calendar.time = nowDate?.toDate()
if (calendar.get(Calendar.MONTH) == month && calendar.get(Calendar.YEAR) == year) {
calendar.clear()
calendar.set(year, month, 1) // Set minimum date to show in dialog
updateCalendar(calendar, 2, typeSelectedDateEnd)
} else {
calendar.clear()
calendar.set(year, month, 1) // Set minimum date to show in dialog
updateCalendar(calendar, 1, typeSelectedDateCenter)
}
}
mSupportFragmentManager?.let {
dialogFragment.show(it, null)
}
}
fun isCollapsed(): Boolean {
return isCollapsed
}
private fun updateCalendar(calendar: Calendar, position: Int, type: Int) {
monthAdapter?.refreshData(MonthUtils.generate3Month(LocalDate.fromCalendarFields(calendar), type))
recyclerView.scrollToPosition(position)
snapHelper?.snappedPosition = position
this.monthChangeListener?.onMonthChange(monthAdapter?.getItem(position)!!.monthDate, position)
updateMonthName(position)
}
private fun updateMonthName(position: Int) {
tvMonthName.text = monthAdapter?.getItem(position)!!.monthDate.monthOfYear().getAsText(Locale.getDefault()) + ", " + monthAdapter?.getItem(position)!!.monthDate.year
}
fun setMonthScrollEnabled(isEnabled: Boolean) {
monthLayoutManager?.setScrollEnabled(isEnabled)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (measuredViewHeight == 0) {
val rowCount: Int = monthAdapter?.let { adapter ->
adapter.getItem(snapHelper!!.snappedPosition)?.dayItems?.let {
Math.ceil((it.size).toDouble() / 7).toInt()
} ?: run {
6
}
} ?: run {
6
}
layoutParams.height = (tvMonthName.measuredHeight + tvCalendarInfo.measuredHeight
+ dayNameViewGroup.measuredHeight + dayItemHeight * rowCount
+ rowCount * ViewUtils.convertDpToPixel(context, 4) + ViewUtils.convertDpToPixel(context, 4))
measuredViewHeight = layoutParams.height
isCollapsed = false
monthLayoutManager?.setScrollEnabled(true)
onCollapseListener?.onCollapse(isCollapsed)
}
}
fun collapse() {
if (!isCollapsed) {
isCollapsed = true
monthLayoutManager?.setScrollEnabled(false)
//recyclerView.isLayoutFrozen = true
ViewUtils.collapse(this, 0,
(tvMonthName.measuredHeight + tvCalendarInfo.measuredHeight
+ dayNameViewGroup.measuredHeight + dayItemHeight + ViewUtils.convertDpToPixel(context, 4)))
onCollapseListener?.onCollapse(isCollapsed)
}
}
fun expand() {
if (isCollapsed) {
isCollapsed = false
monthLayoutManager?.setScrollEnabled(true)
//recyclerView.isLayoutFrozen = false
//layoutParams.height = WRAP_CONTENT
ViewUtils.expand(this, 0, measuredViewHeight)
onCollapseListener?.onCollapse(isCollapsed)
}
}
fun setMonthNameTypeFace(typeface: Typeface) {
tvMonthName.typeface = typeface
}
fun setMonthNameTextColor(@ColorInt color: Int) {
tvMonthName.setTextColor(color)
}
fun setMonthNameTextSize(size: Float) {
tvMonthName.textSize = size
}
fun setDayNameTypeFace(typeface: Typeface) {
dayTypeFace = typeface
dayNameViewGroup.removeAllViews()
ViewUtils.addDayNameViews(dayNameViewGroup, Locale.getDefault(), if (dayTextColor != 0) dayTextColor else R.color.azure, dayTextSize, dayTypeFace)
}
fun setDayNameTextColor(@ColorInt color: Int) {
dayTextColor = color
dayNameViewGroup.removeAllViews()
ViewUtils.addDayNameViews(dayNameViewGroup, Locale.getDefault(), if (dayTextColor != 0) dayTextColor else R.color.azure, dayTextSize, dayTypeFace)
}
fun setDayNameTextSize(size: Float) {
dayTextSize = size
dayNameViewGroup.removeAllViews()
ViewUtils.addDayNameViews(dayNameViewGroup, Locale.getDefault(), if (dayTextColor != 0) dayTextColor else R.color.azure, dayTextSize, dayTypeFace)
}
fun setCalendarInfoText(info: String) {
tvCalendarInfo.text = info
}
fun setCalendarInfoTypeFace(typeface: Typeface) {
tvCalendarInfo.typeface = typeface
}
fun setCalendarInfoTextColor(@ColorInt color: Int) {
tvCalendarInfo.setTextColor(color)
}
fun setCalendarInfoTextSize(size: Float) {
tvCalendarInfo.textSize = size
}
fun setLoadingTint(@ColorInt color: Int) {
pbCalendar?.indeterminateDrawable?.setTint(color)
}
fun showLoading() {
pbCalendar.visibility = View.VISIBLE
tvCalendarInfo.visibility = View.INVISIBLE
}
fun refreshView() {
measuredViewHeight = 0
this.measure(measuredWidth, measuredHeight)
//invalidate()
//requestLayout()
}
fun setPreviousButtonTint(@ColorInt color: Int) {
btnPrev?.setColorFilter(color)
}
fun setNextButtonTint(@ColorInt color: Int) {
btnNext?.setColorFilter(color)
}
fun setPreviousButtonImageResource(resourceId: Int) {
btnPrev?.setImageResource(resourceId)
}
fun setNextButtonImageResource(resourceId: Int) {
btnNext?.setImageResource(resourceId)
}
fun closeLoading() {
pbCalendar.visibility = View.GONE
tvCalendarInfo.visibility = View.VISIBLE
}
companion object {
var dayItemHeight: Int = 0
var isCollapsed: Boolean = false
}
}
| 0 |
Kotlin
|
1
| 5 |
37a5497bd5ebe166987fb74d39f381d7b5d5eadf
| 13,295 |
loggenda
|
Apache License 2.0
|
src/main/kotlin/com/example/coreweb/domains/address/models/mappers/VillageMapper.kt
|
teambankrupt
| 292,072,114 | false |
{"Kotlin": 287703, "Java": 61650, "HTML": 22230}
|
package com.example.coreweb.domains.address.models.mappers
import com.example.coreweb.domains.address.models.dto.VillageDto
import com.example.coreweb.domains.address.models.entities.Village
import com.example.coreweb.domains.address.services.UnionService
import com.example.common.exceptions.notfound.NotFoundException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
@Component
class VillageMapper(@Autowired val unionService: UnionService) {
fun map(village: Village): VillageDto {
val dto = VillageDto()
dto.id = village.id
dto.nameEn = village.nameEn
dto.nameBn = village.nameBn
dto.unionId = village.union?.id
dto.createdAt = village.createdAt
dto.updatedAt = village.updatedAt
return dto
}
fun map(dto: VillageDto, village: Village?): Village {
var v = village;
if (v == null) v = Village();
v.nameEn = dto.nameEn
v.nameBn = dto.nameBn
v.union = dto.unionId?.let { this.unionService.find(it).orElseThrow { NotFoundException() } }
return v
}
}
| 3 |
Kotlin
|
0
| 2 |
e6613a4ac6cac29a67029d9073b53c1a2aa3767f
| 1,144 |
coreweb
|
Apache License 2.0
|
src/main/kotlin/com/example/coreweb/domains/address/models/mappers/VillageMapper.kt
|
teambankrupt
| 292,072,114 | false |
{"Kotlin": 287703, "Java": 61650, "HTML": 22230}
|
package com.example.coreweb.domains.address.models.mappers
import com.example.coreweb.domains.address.models.dto.VillageDto
import com.example.coreweb.domains.address.models.entities.Village
import com.example.coreweb.domains.address.services.UnionService
import com.example.common.exceptions.notfound.NotFoundException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
@Component
class VillageMapper(@Autowired val unionService: UnionService) {
fun map(village: Village): VillageDto {
val dto = VillageDto()
dto.id = village.id
dto.nameEn = village.nameEn
dto.nameBn = village.nameBn
dto.unionId = village.union?.id
dto.createdAt = village.createdAt
dto.updatedAt = village.updatedAt
return dto
}
fun map(dto: VillageDto, village: Village?): Village {
var v = village;
if (v == null) v = Village();
v.nameEn = dto.nameEn
v.nameBn = dto.nameBn
v.union = dto.unionId?.let { this.unionService.find(it).orElseThrow { NotFoundException() } }
return v
}
}
| 3 |
Kotlin
|
0
| 2 |
e6613a4ac6cac29a67029d9073b53c1a2aa3767f
| 1,144 |
coreweb
|
Apache License 2.0
|
src/main/kotlin/com/jordanbegian/apitemplate/routes/ProjectRoutesConfiguration.kt
|
jordan-begian
| 595,221,675 | false | null |
package com.jordanbegian.apitemplate.routes
import com.jordanbegian.apitemplate.handlers.ProjectHandlers
import org.springframework.boot.autoconfigure.web.WebProperties
import org.springframework.context.annotation.Bean
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.server.RouterFunction
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.router
@Component
class ProjectRoutesConfiguration {
@Bean
fun projectRoutes(projectHandlers: ProjectHandlers): RouterFunction<ServerResponse> {
return router {
POST("/submit", projectHandlers::submitRequest)
GET("/retrieve/all", projectHandlers::retrieveAll)
GET("/retrieve/{project-data-id}", projectHandlers::retrieveById)
}
}
}
| 13 |
Kotlin
|
0
| 0 |
8aa4d7a3f798ec6af84cf00aa67acef353768b88
| 864 |
api-template
|
Apache License 2.0
|
app/src/main/java/com/jizhe7550/kotlinapp/di/auth/AuthScope.kt
|
jizhe7550
| 239,940,383 | false | null |
package com.jizhe7550.kotlinapp.di.auth
import javax.inject.Scope
/**
* AuthScope is strictly for login and registration
*/
@Scope
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
annotation class AuthScope
| 0 |
Kotlin
|
0
| 0 |
2dcb890d36d29c88f449bb11ec6be74df36191a1
| 219 |
KoltinApp
|
Apache License 2.0
|
app/src/main/java/com/example/returnpals/composetools/dashboard/SelectAddress.kt
|
BC-CS481-Capstone
| 719,299,432 | false |
{"Kotlin": 271938, "Java": 64676}
|
package com.example.returnpals.composetools.dashboard
import DashboardMenuScaffold
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.NavGraph.Companion.findStartDestination
import com.example.returnpals.composetools.AddressItem
import com.example.returnpals.mainMenu.MenuRoutes
@Composable
fun SelectAddress(navController: NavController) {
DashboardMenuScaffold(navController = navController) {
SelectAddressContent(navController = navController)
}
}
@Composable
fun SelectAddressContent(navController: NavController) {
val customColor = Color(0xFFE1F6FF)
var selectedAddress by remember { mutableStateOf<AddressItem?>(null) }
LazyColumn(
modifier = Modifier
.fillMaxSize()
.background(customColor)
.padding(16.dp)
){
item { AddressHeader() }
item { AddressInfo() }
item {
AddressSelectionScreen(onAddressSelected = { address ->
selectedAddress = address
})
}
item {
Row {
Button(
onClick = {
// Handle click event
navController.navigate(MenuRoutes.PickupDetails) {
// Clear all the back stack up to the start destination and save state
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
// Avoid multiple copies of the same destination when reselecting the same item
launchSingleTop = true
// Restore state when navigating back to the composable
restoreState = true
}
},
enabled = selectedAddress != null,
modifier = Modifier.padding(16.dp)
) {
Text("Next")
}
}
}
}
}
@Composable
fun AddressHeader(){
Column {
Text(
text = "Pickup Details",
style = TextStyle(
color = Color.Black,
fontSize = 32.sp,
fontWeight = FontWeight.Normal,
)
)
Spacer(modifier = Modifier.height(32.dp))
Text(
text = "Select or add your pickup address",
style = TextStyle(
color = Color.Gray,
fontSize = 16.sp,
fontWeight = FontWeight.Normal,
)
)
}
Spacer(modifier = Modifier.height(88.dp))
}
@Composable
fun AddressInfo(){
Column (
){
Text(
text = "Your Addresses:",
style = TextStyle(
color = Color.Black,
fontSize = 14.sp,
fontWeight = FontWeight.Normal,
)
)
}
}
@Composable
fun AddressItemComposable(addressItem: AddressItem, isSelected: Boolean, onSelect: (AddressItem) -> Unit) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable { onSelect(addressItem) }
.padding(16.dp)
) {
// Circle selector
Canvas(modifier = Modifier.size(24.dp), onDraw = {
drawCircle(
color = if (isSelected) Color.Green else Color.Gray,
radius = size.minDimension / 3
)
})
Spacer(Modifier.width(16.dp))
// Address text
Text(text = addressItem.address, style = MaterialTheme.typography.body1)
}
}
@Composable
fun AddressSelectionScreen(onAddressSelected: (AddressItem?) -> Unit) {
val addresses = remember { mutableStateListOf(
AddressItem(1, "123 Your Address One"),
AddressItem(2, "456 Your Address Two")
// ... existing addresses
)}
var selectedAddress by remember { mutableStateOf<AddressItem?>(null) }
// Function to add a new address
val addNewAddress: (String) -> Unit = { newAddress: String ->
val newId = (addresses.maxOfOrNull { it.id } ?: 0) + 1
val newAddressItem = AddressItem(newId, newAddress)
addresses.add(newAddressItem)
selectedAddress = newAddressItem // Optionally auto-select the new address
onAddressSelected(newAddressItem) // Notify the parent composable
}
Column {
addresses.forEach { addressItem ->
AddressItemComposable(
addressItem = addressItem,
isSelected = addressItem == selectedAddress,
onSelect = {
selectedAddress = it
onAddressSelected(it)
}
)
}
AddAddress(onAddAddress = addNewAddress)
}
}
@Composable
fun AddAddress(onAddAddress: (String) -> Unit) {
val selectedBlue = Color(0xFF008BE7)
var text by remember { mutableStateOf("") }
Column(modifier = Modifier.padding(16.dp)) {
TextField(
value = text,
onValueChange = { text = it },
label = { Text("Enter new address") }
)
Button(
onClick = {
if (text.isNotBlank()) {
onAddAddress(text)
text = "" // Clear the text field
}
},
modifier = Modifier.padding(top = 8.dp),
shape = RoundedCornerShape(8.dp),
colors = ButtonDefaults.buttonColors(
backgroundColor = selectedBlue,
contentColor = Color.White
)
) {
Text("Add Address")
}
}
}
| 28 |
Kotlin
|
0
| 0 |
e857f854874211d11784260b4e2a19ffb7db8e13
| 7,296 |
ReturnPalsApp
|
MIT License
|
shared/src/main/java/sg/nphau/android/shared/ui/activities/SharedActivity.kt
|
nphausg
| 423,216,123 | false | null |
/*
* Created by nphau on 01/11/2021, 00:47
* Copyright (c) 2021 . All rights reserved.
* Last modified 01/11/2021, 00:39
*/
package sg.nphau.android.shared.ui.activities
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import sg.nphau.android.R
import sg.nphau.android.shared.common.extensions.toHTML
import sg.nphau.android.shared.common.extensions.longToast
import sg.nphau.android.shared.libs.CommonUtils
import sg.nphau.android.shared.libs.LocaleUtils
import sg.nphau.android.shared.libs.NetworkUtils
import sg.nphau.android.shared.ui.UIBehaviour
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
open class SharedActivity : FragmentActivity(), UIBehaviour {
// User for language setting
override fun attachBaseContext(newBase: Context?) {
LocaleUtils.self().setLocale(newBase)?.let {
super.attachBaseContext(it)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setUpBinding()
onSyncViews(savedInstanceState)
onSyncEvents()
onSyncData()
}
override fun onSyncViews(savedInstanceState: Bundle?) {
}
override fun onSyncEvents() {
}
override fun onSyncData() {
}
/**
* Used for setUp binding
*/
internal open fun setUpBinding() = Unit
override fun showError(message: String?) {
var messageNeedToBeShow = message ?: ""
if (message.isNullOrEmpty()) {
messageNeedToBeShow = if (NetworkUtils.isNetworkAvailable())
getString(R.string.common_error_unknown)
else
getString(R.string.common_error_connect)
}
longToast(messageNeedToBeShow.toHTML().toString())
}
override fun makeVibrator() = CommonUtils.makeVibrator(this)
override fun startActivity(intent: Intent?) {
try {
super.startActivity(intent)
overridePendingTransitionEnter()
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun startActivityForResult(intent: Intent, requestCode: Int) {
try {
super.startActivityForResult(intent, requestCode)
overridePendingTransitionEnter()
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun finish() {
super.finish()
overridePendingTransitionExit()
}
private fun overridePendingTransitionEnter() {
overridePendingTransition(R.anim.anim_slide_from_right, R.anim.anim_slide_to_left)
}
private fun overridePendingTransitionExit() {
overridePendingTransition(R.anim.anim_slide_from_left, R.anim.anim_slide_to_right)
}
open fun allowUserDismissKeyboardWhenClickOutSide() = false
override fun dispatchTouchEvent(motionEvent: MotionEvent?): Boolean {
if (allowUserDismissKeyboardWhenClickOutSide()) {
if (currentFocus != null)
(getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
}
return super.dispatchTouchEvent(motionEvent)
}
// region Coroutine
protected fun <T> on(flow: SharedFlow<T>, action: suspend (T) -> Unit) {
flow.flowWithLifecycle(lifecycle, Lifecycle.State.CREATED)
.onEach(action)
.launchIn(lifecycleScope)
}
protected fun launch(block: suspend CoroutineScope.() -> Unit) {
lifecycleScope.launch(Dispatchers.IO, CoroutineStart.DEFAULT, block)
}
protected fun launchWhenStarted(block: suspend CoroutineScope.() -> Unit) =
lifecycleScope.launchWhenStarted(block)
protected fun launchWhenResumed(block: suspend CoroutineScope.() -> Unit) =
lifecycleScope.launchWhenResumed(block)
protected fun launchWhenCreated(block: suspend CoroutineScope.() -> Unit) =
lifecycleScope.launchWhenCreated(block)
// endregion
}
| 0 |
Kotlin
|
0
| 0 |
7faa9b43846e613aea8d949215cfc88516d6265a
| 4,487 |
android.submodules
|
MIT License
|
octicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/octicons/octicons/ClockFill16.kt
|
walter-juan
| 868,046,028 | false |
{"Kotlin": 34345428}
|
package com.woowla.compose.icon.collections.octicons.octicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.octicons.Octicons
public val Octicons.ClockFill16: ImageVector
get() {
if (_clockFill16 != null) {
return _clockFill16!!
}
_clockFill16 = Builder(name = "ClockFill16", defaultWidth = 16.0.dp, defaultHeight =
16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(0.0f, 8.0f)
arcToRelative(8.0f, 8.0f, 0.0f, true, true, 16.0f, 0.0f)
arcTo(8.0f, 8.0f, 0.0f, false, true, 0.0f, 8.0f)
close()
moveTo(8.575f, 4.75f)
arcToRelative(0.825f, 0.825f, 0.0f, true, false, -1.65f, 0.0f)
verticalLineToRelative(3.5f)
curveToRelative(0.0f, 0.337f, 0.205f, 0.64f, 0.519f, 0.766f)
lineToRelative(2.5f, 1.0f)
arcToRelative(0.825f, 0.825f, 0.0f, false, false, 0.612f, -1.532f)
lineToRelative(-1.981f, -0.793f)
close()
}
}
.build()
return _clockFill16!!
}
private var _clockFill16: ImageVector? = null
| 0 |
Kotlin
|
0
| 3 |
eca6c73337093fbbfbb88546a88d4546482cfffc
| 1,905 |
compose-icon-collections
|
MIT License
|
src/main/kotlin/icu/windea/pls/model/elementInfo/ParadoxModifierInfo.kt
|
DragonKnightOfBreeze
| 328,104,626 | false |
{"Kotlin": 3413636, "Java": 165334, "Lex": 43133, "HTML": 23935, "Shell": 2742}
|
package icu.windea.pls.model.elementInfo
import com.intellij.openapi.project.*
import com.intellij.openapi.util.*
import com.intellij.psi.*
import icu.windea.pls.ep.modifier.*
import icu.windea.pls.lang.*
import icu.windea.pls.lang.psi.*
import icu.windea.pls.model.*
data class ParadoxModifierInfo(
override val name: String,
override val gameType: ParadoxGameType,
override val project: Project,
) : UserDataHolderBase(), ParadoxElementInfo {
val modificationTracker by lazy { support?.getModificationTracker(this) }
companion object {
val EMPTY = ParadoxModifierInfo("", ParadoxGameType.placeholder(), getDefaultProject())
}
}
fun ParadoxModifierInfo.toPsiElement(parent: PsiElement): ParadoxModifierElement {
return ParadoxModifierElement(parent, name, gameType, project).also { syncUserData(this, it) }
}
fun ParadoxModifierElement.toInfo(): ParadoxModifierInfo {
return ParadoxModifierInfo(name, gameType, project).also { syncUserData(this, it) }
}
//use optimized method rather than UserDataHolderBase.copyUserDataTo to reduce memory usage
@Suppress("UNCHECKED_CAST")
private fun syncUserData(from: UserDataHolder, to : UserDataHolder) {
ParadoxModifierSupport.Keys.keys.values.forEach {
val key = it as Key<Any>
to.putUserData(key, from.getUserData(key))
}
}
| 9 |
Kotlin
|
4
| 37 |
f7ce8f1df97e0cca675bbd23c99e3d0cfe743c3e
| 1,341 |
Paradox-Language-Support
|
MIT License
|
app/src/main/java/com/example/trytolie/multiplayer/game/GameData.kt
|
EFProject
| 774,363,215 | false |
{"Kotlin": 175887}
|
package com.example.trytolie.multiplayer.game
data class GameData(
var gameId: String = "-1",
var roomId: String = "-1",
val playerOneId: String = "",
val playerTwoId: String = "",
val gameState: GameStatus = GameStatus.DICE_PHASE,
val playerOneDice: Int = 2,
val playerTwoDice: Int = 2,
val currentTurn: Int = 1,
val currentPlayer: String? = "",
val winner: String? = "",
)
{
constructor() : this("-1", "-1", "", "", GameStatus.DICE_PHASE ,2,2,1,"","")
}
enum class GameStatus {
LIAR_PHASE, //handle the phase when a player decided to call liar other player or not
DICE_PHASE, //handle dice rolling phase
DECLARATION_PHASE, //handle dice declaration phase
}
| 0 |
Kotlin
|
0
| 0 |
486f2777276f2378713672dd3ddf93b11550725c
| 757 |
TryToLie-MACC
|
Apache License 2.0
|
src/main/java/com/mallowigi/icons/associations/Association.kt
|
arihant2math
| 397,433,446 | true |
{"Kotlin": 234710, "Java": 63374}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <NAME>Mallowigi" Boukhobza
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
*/
package com.mallowigi.icons.associations
import com.intellij.util.xmlb.annotations.Property
import com.mallowigi.models.FileInfo
import org.jetbrains.annotations.NonNls
import java.io.Serializable
/**
* Association
*
* @property name
* @property icon
* @property enabled
* @constructor Create empty Association
*/
abstract class Association internal constructor(
@field:Property @field:NonNls var name: String,
@field:Property var icon: String,
var enabled: Boolean = true
) : Serializable {
abstract var matcher: String
open val isEmpty: Boolean
get() = name.isEmpty() || icon.isEmpty()
/**
* Check whether the file matches the association
*
* @param file
* @return
*/
abstract fun matches(file: FileInfo): Boolean
/**
* Apply the association
*
* @param other
*/
open fun apply(other: Association) {
name = other.name
icon = other.icon
enabled = other.enabled
}
override fun toString(): String = "$name $matcher"
companion object {
private const val serialVersionUID: Long = -1L
}
}
| 0 | null |
0
| 0 |
cde61f2e10ca40b15a1b34982e077604e8d1d511
| 2,243 |
a-file-icon-idea
|
MIT License
|
android-beans/src/main/kotlin/rocks/frieler/android/beans/scopes/GenericScopedFactoryBean.kt
|
christopherfrieler
| 175,867,454 | false | null |
package rocks.frieler.android.beans.scopes
import rocks.frieler.android.beans.BeansProvider
import kotlin.reflect.KClass
/**
* Generic implementation for [ScopedFactoryBean].
*
* @author Christopher Frieler
*/
open class GenericScopedFactoryBean<T : Any>(
override val scope: String,
override val beanType: KClass<T>,
private val producer: BeansProvider.() -> T)
: ScopedFactoryBean<T> {
override fun produceBean(dependencies: BeansProvider): T {
return producer(dependencies)
}
}
| 1 | null |
1
| 2 |
658beaa8f50d5e8aff331c9ee680a32cb5efa845
| 532 |
android-beans
|
MIT License
|
mystique/src/main/java/co/upcurve/mystique/MystiqueItemPresenter.kt
|
rahulchowdhury
| 92,713,603 | false | null |
package co.upcurve.mystique
/**
* Every item or model presenter must extend this class and implement
* the given functions for Mystique and [mystify] to work as intended
*/
abstract class MystiqueItemPresenter : MystiqueItem {
/**
* Loads a data model to the presenter or item. This function
* has to be implemented and the supplied model has to be
* stored in the class extending [MystiqueItemPresenter]
*
* @param model The incoming data model to be stored
*/
abstract fun loadModel(model: Any)
/**
* Returns the loaded model (if any) from the item presenter.
* This function is usually used in the [MystiqueAdapter.removeItems]
* function to perform model wise comparison while removing an element
*
* @return The loaded model (if any)
*/
abstract fun getModel(): Any?
/**
* Any click listener (if supplied) has to be stored in the
* class extending [MystiqueItemPresenter] by implementing
* this function
*
* @param listener The click listener supplied at initialization
*/
abstract fun setListener(listener: Any?)
}
| 0 |
Kotlin
|
8
| 48 |
acd0bf7fadc808aecb920ea309f03490a7b09a75
| 1,141 |
Mystique
|
Apache License 2.0
|
app/src/main/java/com/kyagamy/step/fragments/CategoryFragament.kt
|
rovivi
| 262,239,890 | false |
{"Kotlin": 187381, "Java": 97322, "Lua": 26067}
|
package com.kyagamy.step.fragments
import android.media.MediaPlayer
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager
import com.kyagamy.step.views.MainActivity
import com.kyagamy.step.adapters.CategoryAdapter
import com.kyagamy.step.databinding.FragmentCategoryFragamentBinding
import com.kyagamy.step.room.entities.Category
import com.kyagamy.step.viewmodels.CategoryViewModel
import java.io.File
private const val POSITION = "position"
class CategoryFragament : Fragment() {
private var position = 0
private lateinit var categoryModel: CategoryViewModel
private lateinit var myDataSet: List<Category>
private val binding: FragmentCategoryFragamentBinding by lazy {
FragmentCategoryFragamentBinding.inflate(LayoutInflater.from(context), null, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
position = it.getInt(POSITION)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = binding.root
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Inflate the layout for this fragment
categoryModel = ViewModelProvider(this).get(CategoryViewModel::class.java)
val list = ArrayList<Category>()
val adapter = CategoryAdapter(list, this.requireContext())
binding.cycle.adapter = adapter
binding.cycle.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(pos: Int) {
// Check if this is the page you want.
myDataSet = adapter.myDataSet
position = pos
playSound()
}
}
)
categoryModel.allCategory.observe(viewLifecycleOwner) { words ->
words?.let { adapter.setSongs(it) }
}
val mainActivity = activity as MainActivity
binding.cycle.run {
setOnTouchListener(object : OnTouchListener {
var flage = 0
override fun onTouch(v: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> flage = 0
MotionEvent.ACTION_MOVE -> flage = 1
MotionEvent.ACTION_UP -> if (flage == 0) {
mainActivity.changeCategory(adapter.myDataSet[currentItem].name,currentItem)
}
}
return false
}
})
}
binding.button.setOnClickListener{
mainActivity.changeCategory(adapter.myDataSet[position].name,position)
}
}
override fun onResume() {
super.onResume()
try {
playSound()
} catch (_: Exception) {
}
}
fun playSound() {
if (myDataSet[position].music_category != null) {
try {
if (File(myDataSet[position].music_category.toString()).exists()) {
val mp = MediaPlayer()
mp.setDataSource(myDataSet[position].music_category)
mp.prepare()
mp.start()
}
} catch (_: Exception) {
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
18e200d2f7f58349455a35b819b921c32adab853
| 3,986 |
Stepdroid2
|
MIT License
|
app/src/main/java/com/p4indiafsm/features/stockAddCurrentStock/ShopAddCurrentStockList.kt
|
DebashisINT
| 600,987,989 | false |
{"Kotlin": 12277573, "Java": 971195}
|
package com.p4indiafsm.features.stockAddCurrentStock
class ShopAddCurrentStockList {
var product_id: String? = null
var product_stock_qty: String? = null
}
| 0 |
Kotlin
|
0
| 0 |
ffc013802161ca648cff7f95600d64a8ac6d8882
| 164 |
P4India
|
Apache License 2.0
|
rssreader/src/main/kotlin/dmitriykhalturin/rssreader/di/Injector.kt
|
DmitriyKhalturin
| 126,305,053 | false | null |
package dmitriykhalturin.rssreader.di
import android.app.Application
import android.support.v4.app.FragmentActivity
import dmitriykhalturin.rssreader.di.component.ApplicationComponent
import dmitriykhalturin.rssreader.di.component.DaggerApplicationComponent
import dmitriykhalturin.rssreader.di.component.DaggerPresenterComponent
import dmitriykhalturin.rssreader.di.module.ApplicationModule
import dmitriykhalturin.rssreader.di.module.PresenterModule
import dmitriykhalturin.rssreader.di.module.RepositoryModule
import dmitriykhalturin.rssreader.di.module.StateModule
/**
* Created by <NAME> <<EMAIL>></<EMAIL>>
* for saferide-android on 06.08.18 15:31.
*/
class Injector {
companion object {
@JvmStatic
private val sInstance = Injector()
@JvmStatic
private lateinit var sAppComponent: ApplicationComponent
@JvmStatic
fun getsInstance() = sInstance
}
fun buildAppComponent(application: Application) {
sAppComponent = DaggerApplicationComponent
.builder()
.applicationModule(ApplicationModule(application))
.repositoryModule(RepositoryModule())
.stateModule(StateModule())
.build() !!
}
fun getsApplicationComponent() = sAppComponent
fun getPresenterComponent(activity: FragmentActivity) = DaggerPresenterComponent
.builder()
.presenterModule(PresenterModule(activity))
.build() !!
}
| 0 |
Kotlin
|
0
| 1 |
40cd567246bb30ff7a5955c9be17fe9632a734a9
| 1,380 |
android-rss-reader
|
Apache License 2.0
|
tracker/src/main/java/com/ericafenyo/tracker/location/LocationUpdatesReceiver.kt
|
ericafenyo
| 309,510,894 | false | null |
/*
* The MIT License (MIT)
*
* Copyright (C) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.ericafenyo.tracker.location
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.ericafenyo.bikediary.logger.Logger
import com.ericafenyo.tracker.datastore.Record
import com.ericafenyo.tracker.datastore.RecordCache
import com.google.android.gms.location.LocationResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import timber.log.Timber
/**
* Receiver for broadcasts sent by [LocationUpdatesAction] through pending intent.
*/
class LocationUpdatesReceiver : BroadcastReceiver() {
private val tag = "LocationUpdatesReceiver"
override fun onReceive(context: Context, intent: Intent) {
Logger.debug(context, tag, "onReceive(context: $context, intent: $intent)")
Timber.d("Location updates: ${LocationResult.extractResult(intent)}")
val locations = if (LocationResult.hasResult(intent)) {
LocationResult.extractResult(intent).locations
} else {
null
}
// Skip if we don't have a location object
if (locations.isNullOrEmpty()) return
val location = locations.first().simplify()
runBlocking(Dispatchers.IO) {
RecordCache.getInstance(context).put(
Record.fromSimpleLocation(location)
)
}
}
}
| 10 |
Kotlin
|
0
| 0 |
3b9b5b9440270d102c04893d3903fb1d198c0883
| 2,415 |
bike-diary
|
MIT License
|
app/src/main/java/com/example/tonwallet/pages/SendDNS.kt
|
asnov
| 625,657,380 | false | null |
package com.example.tonwallet.pages
import android.content.res.Configuration
import android.util.Log
import androidx.compose.foundation.Image
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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Card
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
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.example.tonwallet.R
import com.example.tonwallet.Roboto
import com.example.tonwallet.ui.theme.TONWalletTheme
private const val TAG = "SendDNS"
@Composable
fun SendDNS(
modifier: Modifier = Modifier
) {
Log.v(TAG, "started")
Column(
modifier
.background(Color(0xFF31373E)),
Arrangement.Bottom,
Alignment.CenterHorizontally,
) {
Column(
Modifier
.background(
Color(0xFFFFFFFF), shape = RoundedCornerShape(
topStart = 10.dp,
topEnd = 10.dp,
bottomStart = 0.dp,
bottomEnd = 0.dp
)
)
.fillMaxWidth(),
Arrangement.Bottom,
)
{
Column(
modifier = Modifier
.padding(top = 16.dp, bottom = 12.dp, start = 20.dp, end = 16.dp)
)
{
Text(
stringResource(R.string.send_ton),
Modifier.padding(bottom = 12.dp),
color = Color.Black,
textAlign = TextAlign.Left,
fontSize = 20.sp,
lineHeight = 24.sp,
fontWeight = FontWeight.W500,
)
}
Column() {
Text(
stringResource(R.string.wallet_address_or_domain),
Modifier.padding(start = 20.dp),
color = Color(0xFF339CEC),
textAlign = TextAlign.Left,
fontSize = 15.sp,
lineHeight = 20.sp,
fontWeight = FontWeight.W500,
)
//down should be good working textfield acording to design
BasicTextField(value = "andrew.ton",
onValueChange = {},
Modifier
.fillMaxWidth()
.padding(start = 20.dp, top = 12.dp, bottom = 12.dp, end = 20.dp),
//.defaultMinSize(minHeight=64.dp),
textStyle = TextStyle(
color = Color(0xFF000000),
fontFamily = Roboto,
fontWeight = FontWeight.W400,
fontSize = 15.sp,
lineHeight = 20.sp,
textAlign = TextAlign.Left,
),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
singleLine = false,
minLines = 1,
cursorBrush = SolidColor(Color(0xFF339CEC)),
decorationBox = { innerTextField ->
Column(
) {
//this should be placeholder
// if (value.isEmpty()) {
// Text("Enter Wallet Address or Domain...")
// }
innerTextField()
Divider(
color = Color(0xFF339CEC),
modifier = Modifier
.padding(top = 12.dp)
.height(1.dp)
.fillMaxWidth()
)
}
}
)
Text(
stringResource(R.string.paste_wallet_address_dns),
Modifier.padding(top = 12.dp, start = 20.dp, bottom = 4.dp),
color = Color(0xFF757575),
textAlign = TextAlign.Left,
fontSize = 15.sp,
lineHeight = 20.sp,
fontWeight = FontWeight.W400,
)
}
Column(
Modifier.padding(top = 12.dp, start = 20.dp, end = 20.dp, bottom = 102.dp)
)
{
Row() {
Row(modifier.padding(end = 24.dp)) {
Image(
painterResource(R.drawable.icon_paste),
null,
Modifier
.height(20.dp)
.padding(end = 4.dp)
)
Text(
stringResource(R.string.paste),
color = Color(0xFF339CEC),
textAlign = TextAlign.Right,
fontSize = 15.sp,
lineHeight = 20.sp,
fontWeight = FontWeight.W400,
)
}
Row() {
Image(
painterResource(R.drawable.icon_scan2),
null,
Modifier
.height(20.dp)
.padding(end = 4.dp)
)
Text(
stringResource(R.string.scan),
color = Color(0xFF339CEC),
textAlign = TextAlign.Right,
fontSize = 15.sp,
lineHeight = 20.sp,
fontWeight = FontWeight.W400,
)
}
}
} // column with icons
Card(
Modifier
// .height(56.dp)
.fillMaxWidth()
.padding(8.dp),
elevation = 0.dp,
shape = RoundedCornerShape(
topStart = 6.dp,
topEnd = 6.dp,
bottomStart = 6.dp,
bottomEnd = 6.dp
),
backgroundColor = Color(0xEB2F373F),
contentColor = Color.White,
) {
Row(
Modifier.padding(10.dp),
// horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
)
{
Image(
painterResource(R.drawable.icon_invalid),
null,
Modifier
.size(32.dp),
Alignment.CenterStart,
)
Column(Modifier.padding(start = 10.dp)) {
Text(
stringResource(R.string.invalid_address),
Modifier,
color = Color.White,
textAlign = TextAlign.Left,
fontSize = 14.sp,
lineHeight = 18.sp,
fontWeight = FontWeight.W500,
)
Text(
stringResource(R.string.address_dnot_belong_ton),
Modifier,
color = Color.White,
textAlign = TextAlign.Left,
fontSize = 14.sp,
lineHeight = 18.sp,
fontWeight = FontWeight.W400,
)
}
}
}
}
} // column rounded top corners
} // main column
@Preview(
name = "Day Mode",
showSystemUi = true,
uiMode = Configuration.UI_MODE_NIGHT_NO,
)
@Composable
private fun DefaultPreview() {
TONWalletTheme {
SendDNS()
}
}
| 0 |
Kotlin
|
0
| 2 |
37d2ee916e3f2c769aa30fd048b97619ba435754
| 9,328 |
TONWallet
|
MIT License
|
lib/src/test/kotlin/com/programmerare/sweden_crs_transformations_4jvm/example/KotlinExample.kt
|
TomasJohansson
| 350,094,797 | false |
{"Scala": 42894, "Java": 32509, "Kotlin": 25114}
|
package com.programmerare.sweden_crs_transformations_4jvm.example
// This is NOT a "test" class with assertions, but it can be used for code examples
// e.g. verify that this code below works and then it can be paste into some example page at github
import com.programmerare.sweden_crs_transformations_4jvm.CrsCoordinate
import com.programmerare.sweden_crs_transformations_4jvm.CrsProjection
object KotlinExample {
@JvmStatic
fun main(args: Array<String>) {
val stockholmCentralStation_WGS84_latitude = 59.330231
val stockholmCentralStation_WGS84_longitude = 18.059196
val stockholmWGS84: CrsCoordinate = CrsCoordinate.createCoordinate(
CrsProjection.WGS84,
stockholmCentralStation_WGS84_latitude,
stockholmCentralStation_WGS84_longitude
)
val stockholmSweref99tm: CrsCoordinate =
stockholmWGS84.transform(CrsProjection.SWEREF_99_TM)
println("stockholmSweref99tm X: " + stockholmSweref99tm.longitudeX)
println("stockholmSweref99tm Y: " + stockholmSweref99tm.latitudeY)
println("stockholmSweref99tm 'toString': " + stockholmSweref99tm)
// Output from the above:
//stockholmSweref99tm X: 674032.357
//stockholmSweref99tm Y: 6580821.991
//stockholmSweref99tm 'toString': CrsCoordinate [ Y: 6580821.991 , X: 674032.357 , CRS: SWEREF_99_TM(EPSG:3006) ]
val allProjections: List<CrsProjection> = CrsProjection.getAllCrsProjections()
for (crsProjection in allProjections) {
println(stockholmWGS84.transform(crsProjection))
}
// Output from the above loop:
//CrsCoordinate [ Latitude: 59.330231 , Longitude: 18.059196 , CRS: WGS84(EPSG:4326) ]
//CrsCoordinate [ Y: 6580821.991 , X: 674032.357 , CRS: SWEREF_99_TM(EPSG:3006) ]
//CrsCoordinate [ Y: 6595151.116 , X: 494604.69 , CRS: SWEREF_99_12_00(EPSG:3007) ]
//CrsCoordinate [ Y: 6588340.147 , X: 409396.217 , CRS: SWEREF_99_13_30(EPSG:3008) ]
//CrsCoordinate [ Y: 6583455.373 , X: 324101.998 , CRS: SWEREF_99_15_00(EPSG:3009) ]
//CrsCoordinate [ Y: 6580494.921 , X: 238750.424 , CRS: SWEREF_99_16_30(EPSG:3010) ]
//CrsCoordinate [ Y: 6579457.649 , X: 153369.673 , CRS: SWEREF_99_18_00(EPSG:3011) ]
//CrsCoordinate [ Y: 6585657.12 , X: 366758.045 , CRS: SWEREF_99_14_15(EPSG:3012) ]
//CrsCoordinate [ Y: 6581734.696 , X: 281431.616 , CRS: SWEREF_99_15_45(EPSG:3013) ]
//CrsCoordinate [ Y: 6579735.93 , X: 196061.94 , CRS: SWEREF_99_17_15(EPSG:3014) ]
//CrsCoordinate [ Y: 6579660.051 , X: 110677.129 , CRS: SWEREF_99_18_45(EPSG:3015) ]
//CrsCoordinate [ Y: 6581507.028 , X: 25305.238 , CRS: SWEREF_99_20_15(EPSG:3016) ]
//CrsCoordinate [ Y: 6585277.577 , X: -60025.629 , CRS: SWEREF_99_21_45(EPSG:3017) ]
//CrsCoordinate [ Y: 6590973.148 , X: -145287.219 , CRS: SWEREF_99_23_15(EPSG:3018) ]
//CrsCoordinate [ Y: 6598325.639 , X: 1884004.1 , CRS: RT90_7_5_GON_V(EPSG:3019) ]
//CrsCoordinate [ Y: 6587493.237 , X: 1756244.287 , CRS: RT90_5_0_GON_V(EPSG:3020) ]
//CrsCoordinate [ Y: 6580994.18 , X: 1628293.886 , CRS: RT90_2_5_GON_V(EPSG:3021) ]
//CrsCoordinate [ Y: 6578822.84 , X: 1500248.374 , CRS: RT90_0_0_GON_V(EPSG:3022) ]
//CrsCoordinate [ Y: 6580977.349 , X: 1372202.721 , CRS: RT90_2_5_GON_O(EPSG:3023) ]
//CrsCoordinate [ Y: 6587459.595 , X: 1244251.702 , CRS: RT90_5_0_GON_O(EPSG:3024) ]
}
}
| 0 |
Scala
|
0
| 0 |
84f7f14f4619b341b94517c3a12d957d727f3dac
| 3,516 |
sweden_crs_transformations_4jvm
|
MIT License
|
rv-decoration/src/main/java/me/reezy/cosmo/rv/decoration/DividerDecoration.kt
|
czy1121
| 533,686,296 | false | null |
package me.reezy.cosmo.rv.decoration
import android.graphics.*
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.roundToInt
class DividerDecoration(
private val orientation: Int = RecyclerView.VERTICAL,
private val isLastVisible: Boolean = false,
private val isInside: Boolean = false
) : RecyclerView.ItemDecoration() {
private val paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var insetStart: Float = 0f
private var insetEnd: Float = 0f
fun stroke(size: Float = 1f, color: Int = Color.LTGRAY): DividerDecoration {
paint.strokeWidth = size
paint.color = color
return this
}
fun dash(dashWidth: Float, dashGap: Float = dashWidth): DividerDecoration {
paint.pathEffect = DashPathEffect(floatArrayOf(dashWidth, dashGap), 0f)
return this
}
fun inset(start: Float, end: Float = start): DividerDecoration {
insetStart = start
insetEnd = end
return this
}
private val bounds = Rect()
init {
paint.strokeJoin = Paint.Join.ROUND
paint.style = Paint.Style.STROKE
paint.color = Color.LTGRAY
paint.strokeWidth = 1f
}
override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (parent.layoutManager == null || parent.adapter == null) {
return
}
canvas.save()
for (i in 0 until parent.childCount) {
val child = parent.getChildAt(i)
val position = parent.getChildAdapterPosition(child)
val itemCount = parent.adapter!!.itemCount
if (!isLastVisible && position >= itemCount - 1) {
continue
}
parent.getDecoratedBoundsWithMargins(child, bounds)
if (orientation == RecyclerView.VERTICAL) {
val bottom = bounds.bottom + child.translationY
val top = bottom - paint.strokeWidth
canvas.drawLine(insetStart, top, parent.width - insetEnd, bottom, paint)
} else {
val right = bounds.right + child.translationX
val left = right - paint.strokeWidth
canvas.drawLine(left, insetStart, right, parent.height - insetEnd, paint)
}
}
canvas.restore()
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
if (isInside) {
outRect.set(0, 0, 0, 0)
return
}
if (orientation == RecyclerView.VERTICAL) {
outRect.set(0, 0, 0, paint.strokeWidth.roundToInt())
} else {
outRect.set(0, 0, paint.strokeWidth.roundToInt(), 0)
}
}
}
| 1 |
Kotlin
|
0
| 0 |
20f7f8693a737667398fe2f22339ed0ef61ff3ee
| 2,780 |
rv
|
Apache License 2.0
|
2023/Ktor/Node/src/main/kotlin/com/example/Application.kt
|
kyoya-p
| 253,926,918 | false |
{"Kotlin": 971926, "JavaScript": 86232, "HTML": 72159, "TypeScript": 63582, "Java": 30207, "C++": 29172, "CMake": 20891, "Dart": 14886, "Shell": 7841, "CSS": 6307, "Batchfile": 6227, "Dockerfile": 5012, "C": 3042, "Swift": 2246, "PowerShell": 234, "Objective-C": 78}
|
fun main() {
embeddedServer(CIO, port = 8080, host = "0.0.0.0", module = Application::module)
.start(wait = true)
}
fun Application.module() {
configureSerialization()
configureRouting()
}
| 16 |
Kotlin
|
1
| 2 |
19d03451e563a469214123d21a5b5cf93c9f307e
| 210 |
samples
|
Apache License 2.0
|
framework/core/src/commonTest/kotlin/dev/ahmedmourad/validation/core/TripleValidationsTests.kt
|
AhmedMourad0
| 294,846,260 | false | null |
package dev.ahmedmourad.validation.core
import dev.ahmedmourad.validation.core.utils.allFail
import dev.ahmedmourad.validation.core.utils.allMatch
import dev.ahmedmourad.validation.core.utils.constraint
import dev.ahmedmourad.validation.core.validations.*
import kotlin.test.Test
class TripleValidationsTests {
@Test
fun first_meansTheGivenValidationsMatchTheFirstElementOfTheTriple() {
constraint<Triple<Int, Unit, Unit>> {
first {
max(3)
}
}.allMatch(
Triple(-1, Unit, Unit),
Triple(1, Unit, Unit),
Triple(2, Unit, Unit),
Triple(3, Unit, Unit)
).allFail(
Triple(4, Unit, Unit),
Triple(5, Unit, Unit),
Triple(6, Unit, Unit)
)
}
@Test
fun second_meansTheGivenValidationsMatchTheSecondElementOfTheTriple() {
constraint<Triple<Unit, Int, Unit>> {
second {
max(3)
}
}.allMatch(
Triple(Unit, -1, Unit),
Triple(Unit, 1, Unit),
Triple(Unit, 2, Unit),
Triple(Unit, 3, Unit)
).allFail(
Triple(Unit, 4, Unit),
Triple(Unit, 5, Unit),
Triple(Unit, 6, Unit)
)
}
@Test
fun third_meansTheGivenValidationsMatchTheThirdElementOfTheTriple() {
constraint<Triple<Unit, Unit, Int>> {
third {
max(3)
}
}.allMatch(
Triple(Unit, Unit, -1),
Triple(Unit, Unit, 1),
Triple(Unit, Unit, 2),
Triple(Unit, Unit, 3)
).allFail(
Triple(Unit, Unit, 4),
Triple(Unit, Unit, 5),
Triple(Unit, Unit, 6)
)
}
}
| 0 |
Kotlin
|
0
| 4 |
6f25a7110d4ebb016c1c6719a43a49757c6abdbf
| 1,779 |
kotlin-validation
|
Apache License 2.0
|
app/src/main/java/my/dzeko/footapp/model/entity/News.kt
|
dzeko14
| 168,025,712 | false | null |
package my.dzeko.footapp.model.entity
import android.arch.persistence.room.Entity
import android.arch.persistence.room.Ignore
import android.arch.persistence.room.PrimaryKey
import my.dzeko.newsparser.entities.ParsedNews
@Entity
data class News(
@PrimaryKey(autoGenerate = true) var id: Long = 0,
val title :String,
val summary :String,
val date :Long,
val content :List<String>,
val images: List<String>,
val originalUrl :String
){
@Ignore var tags :List<Tag>? = null
@Ignore
constructor(parsedNews: ParsedNews)
: this(
title = parsedNews.title,
content = parsedNews.content,
date = parsedNews.date,
images = parsedNews.images,
originalUrl = parsedNews.originalUrl,
summary = parsedNews.summary
)
companion object {
fun createEmptyNews(): News {
return News(
0,
"empty",
"empty",
0,
emptyList<String>(),
emptyList<String>(),
""
)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
654eed725a45d96c1d887382238746eef6ae8685
| 1,104 |
foot-news-app-client
|
MIT License
|
dynamic-query-specification/src/main/kotlin/br/com/dillmann/dynamicquery/specification/predicate/binary/GreaterThanBinarySpecification.kt
|
lucasdillmann
| 766,655,271 | false |
{"Kotlin": 291320, "ANTLR": 1360}
|
package br.com.dillmann.dynamicquery.specification.predicate.binary
import jakarta.persistence.criteria.CriteriaBuilder
/**
* [BinarySpecification] implementation for greater than expressions
*
* @param attributeName Full path of the attribute
* @param value Value to be compared to
*/
class GreaterThanBinarySpecification(attributeName: String, value: String):
BinarySpecification(attributeName, value, CriteriaBuilder::greaterThan)
| 0 |
Kotlin
|
0
| 1 |
cf3f0c3fd81da87bb6a097b9d219f42264244fd9
| 445 |
dynamic-query
|
MIT License
|
statcraft-common/src/main/kotlin/com/demonwav/statcraft/sql/Table.kt
|
DenWav
| 67,326,995 | false |
{"Kotlin": 96559, "Java": 46949}
|
/*
* StatCraft Plugin
*
* Copyright (c) 2016 <NAME> (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.sql
import org.intellij.lang.annotations.Language
enum class Table(@Language("MySQL") val create: String, val columnNames: List<String>) {
PLAYERS(
//language=MySQL
"""
CREATE TABLE IF NOT EXISTS `players` (
`uuid` binary(16) NOT NULL,
`name` varchar(16) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE KEY `players_uuid_uindex` (`uuid`),
UNIQUE KEY `players_name_uindex` (`name`),
UNIQUE KEY `players_id_uindex` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
""".trimIndent(),
listOf("uuid", "name", "id")),
WORLDS(
//language=MySQL
"""
CREATE TABLE IF NOT EXISTS `worlds` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uuid` binary(16) NOT NULL,
`name` varchar(255) NOT NULL,
`custom_name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `worlds_id_uindex` (`id`),
UNIQUE KEY `worlds_uuid_uindex` (`uuid`),
KEY `worlds_name_index` (`name`),
KEY `worlds_custom_name_index` (`custom_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
""".trimIndent(),
listOf("id", "uuid", "name", "custom_name")),
NAMESPACE(
//language=MySQL
"""
CREATE TABLE `namespace` (
`uuid` binary(16) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE KEY `namespace_uuid_uindex` (`uuid`),
UNIQUE KEY `namespace_id_uindex` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
""".trimIndent(),
listOf("uuid", "id")
),
STATS(
//language=MySQL
"""
CREATE TABLE IF NOT EXISTS `stats` (
`namespace_id` int(11) NOT NULL,
`stat_id` int(11) NOT NULL,
`player_id` int(11) NOT NULL,
`world_id` int(11) NOT NULL,
`primary_stat_type_id` int(11) NOT NULL,
`secondary_stat_type_id` int(11) NOT NULL,
`primary_stat_target` varchar(255) NOT NULL,
`secondary_stat_target` varchar(255) NOT NULL,
`value` bigint(20) NOT NULL,
PRIMARY KEY (`namespace_id`,`stat_id`,`player_id`,`world_id`,`primary_stat_type_id`,`secondary_stat_type_id`,`primary_stat_target`,`secondary_stat_target`),
KEY `player_index` (`player_id`),
KEY `world_index` (`world_id`),
KEY `namespace_index` (`namespace_id`),
CONSTRAINT `stats_namespace_id_fk` FOREIGN KEY (`namespace_id`) REFERENCES `namespace` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT `stats_players_id_fk` FOREIGN KEY (`player_id`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT `stats_worlds_id_fk` FOREIGN KEY (`world_id`) REFERENCES `worlds` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8
""".trimIndent(),
listOf("namespace_id", "stat_id", "player_id", "world_id", "primary_stat_type_id", "secondary_stat_type_id", "primary_stat_target", "secondary_stat_target", "value")),
CACHED_STATS(
//language=MySQL
"""
CREATE TABLE IF NOT EXISTS `cached_stats` (
`namespace_id` int(11) NOT NULL,
`stat_id` int(11) NOT NULL,
`player_id` int(11) NOT NULL,
`world_id` int(11) NOT NULL,
`primary_stat_type_id` int(11) NOT NULL,
`secondary_stat_type_id` int(11) NOT NULL,
`primary_stat_target` int(11) NOT NULL,
`secondary_stat_target` int(11) NOT NULL,
`value` bigint(20) NOT NULL,
PRIMARY KEY (`namespace_id`,`stat_id`,`player_id`,`world_id`,`primary_stat_type_id`,`secondary_stat_type_id`,`primary_stat_target`,`secondary_stat_target`),
KEY `player_index` (`player_id`),
KEY `world_index` (`world_id`),
KEY `namespace_index` (`namespace_id`),
KEY `1` (`namespace_id`,`stat_id`,`primary_stat_type_id`,`secondary_stat_type_id`,`primary_stat_target`,`secondary_stat_target`),
KEY `2` (`namespace_id`,`stat_id`,`world_id`,`primary_stat_type_id`,`secondary_stat_type_id`,`primary_stat_target`,`secondary_stat_target`),
CONSTRAINT `stats_namespace_id_fk` FOREIGN KEY (`namespace_id`) REFERENCES `namespace` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT `cached_stats_players_id_fk` FOREIGN KEY (`player_id`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT ,
CONSTRAINT `cached_stats_worlds_id_fk` FOREIGN KEY (`world_id`) REFERENCES `worlds` (`id`) ON UPDATE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8
""".trimIndent(),
listOf("namespace_id", "stat_id", "player_id", "world_id", "primary_stat_type_id", "secondary_stat_type_id", "primary_stat_target", "secondary_stat_target", "value")
);
fun getName() = name.toLowerCase()
fun getColumnCount() = columnNames.size
}
| 0 |
Kotlin
|
0
| 1 |
1ed39babc661a948b17b2b8ad6f9fad5d5fd5c64
| 5,186 |
StatCraftGradle
|
MIT License
|
libnavigation-util/src/main/java/com/mapbox/navigation/utils/internal/GroupedVoiceInstructionsFactory.kt
|
mapbox
| 87,455,763 | false |
{"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624}
|
package com.mapbox.navigation.utils.internal
import com.mapbox.api.directions.v5.models.DirectionsRoute
import com.mapbox.api.directions.v5.models.VoiceInstructions
import kotlin.math.abs
object GroupedVoiceInstructionsFactory {
/**
* Will examine a route and determine voice instructions that are close together.
* [VoiceInstructions] will be grouped to reflect the beginning and ending range of
* the voice instructions that are within a specified distance of each other.
*
* @param route the route to use
* @param rangeDistance the distance in meters for the grouping. For example if the value is
* 100 any voice instructions within 100 meters of each other will be grouped together. The
* resulting grouping range can be greater than this distance. For example, voice instruction A
* occurring at 50 meters into the route, voice instruction B at 100 meters and voice instruction C at 150 meters.
* All three of these voice instructions would be grouped together. B is with in 100 meters of A and C is with
* in 100 meters of B.
* @param rangePrefixDistance a distance in meters that is prepended to the beginning of
* the grouped range. This is useful for creating a range that starts at a distance before the
* voice instruction occurs.
* @param rangeSuffixDistance a distance in meters that is appended to the end of the grouped
* range.
* @return [GroupedAnnouncementRanges] which contains voice instruction ranges if they were
* derived.
*/
fun getGroupedAnnouncementRanges(
route: DirectionsRoute,
rangeDistance: Double,
): GroupedAnnouncementRanges {
var runningDist = 0.0
val intermediateDistances = mutableListOf<Double>()
val ranges = mutableListOf<IntRange>()
val voiceInstructionDistances = mutableListOf<Double>()
ifNonNull(route.legs()?.first()?.steps()) { legSteps ->
legSteps.forEach { legStep ->
runningDist += legStep.distance()
legStep.voiceInstructions()?.forEach {
val absoluteDistance = runningDist - (it.distanceAlongGeometry() ?: 0.0)
voiceInstructionDistances.add(absoluteDistance)
}
}
}
voiceInstructionDistances.forEachIndexed { index, distance ->
if (index > 1) {
if (abs(distance - voiceInstructionDistances[index - 1]) < rangeDistance) {
if (intermediateDistances.isEmpty()) {
intermediateDistances.add(voiceInstructionDistances[index - 1])
intermediateDistances.add(distance)
} else {
intermediateDistances.add(distance)
}
} else {
if (intermediateDistances.size >= 2) {
ranges.add(
IntRange(
intermediateDistances.first().toInt(),
intermediateDistances.last().toInt(),
),
)
}
intermediateDistances.clear()
}
}
}
if (intermediateDistances.size >= 2) {
ranges.add(
IntRange(
intermediateDistances.first().toInt(),
intermediateDistances.last().toInt(),
),
)
}
return GroupedAnnouncementRanges(ranges)
}
class GroupedAnnouncementRanges internal constructor(
private val ranges: List<IntRange>,
) {
fun isInRange(distance: Int): Boolean {
return ranges.any { it.contains(distance) }
}
}
}
| 508 |
Kotlin
|
318
| 621 |
88163ae3d7e34948369d6945d5b78a72bdd68d7c
| 3,829 |
mapbox-navigation-android
|
Apache License 2.0
|
releases-hub-gradle-plugin/src/main/java/com/releaseshub/gradle/plugin/task/ListDependenciesToUpgradeTask.kt
|
committedteadrinker
| 254,077,941 | true |
{"Kotlin": 92091, "Shell": 2559, "Java": 15}
|
package com.releaseshub.gradle.plugin.task
import com.releaseshub.gradle.plugin.artifacts.ArtifactUpgradeStatus
import com.releaseshub.gradle.plugin.common.AbstractTask
import com.releaseshub.gradle.plugin.core.FileSizeFormatter
open class ListDependenciesToUpgradeTask : AbstractTask() {
companion object {
const val TASK_NAME = "listDependenciesToUpgrade"
}
init {
description = "List all dependencies to upgrade"
}
override fun onExecute() {
getExtension().validateServerName()
getExtension().validateUserToken()
getExtension().validateDependenciesClassNames()
val dependenciesParserResult = DependenciesExtractor.extractArtifacts(project.rootProject.projectDir, dependenciesBasePath!!, dependenciesClassNames!!, includes, excludes)
if (dependenciesParserResult.excludedArtifacts.isNotEmpty()) {
log("Dependencies excluded:")
dependenciesParserResult.excludedArtifacts.sortedBy { it.toString() }.forEach {
log(" * $it ${it.fromVersion}")
}
log("")
}
val artifactsUpgrades = createArtifactsService().getArtifactsUpgrades(dependenciesParserResult.getAllArtifacts(), getRepositories())
val notFoundArtifacts = artifactsUpgrades.filter { it.artifactUpgradeStatus == ArtifactUpgradeStatus.NOT_FOUND }
if (notFoundArtifacts.isNotEmpty()) {
log("Dependencies not found:")
notFoundArtifacts.forEach {
log(" * $it ${it.fromVersion}")
}
log("")
}
val artifactsToUpgrade = artifactsUpgrades.filter { it.artifactUpgradeStatus == ArtifactUpgradeStatus.PENDING_UPGRADE }
if (artifactsToUpgrade.isNullOrEmpty()) {
log("No dependencies to upgrade")
} else {
log("Dependencies to upgrade:")
artifactsToUpgrade.forEach {
log(" * $it ${it.fromVersion} -> ${it.toVersion}")
if (it.toSize != null) {
val builder = StringBuilder()
builder.append(" - Size: ${FileSizeFormatter.format(it.toSize!!)}")
// TODO We need to store the complete history of versions on the backend to make the diff work
// log("**** fromSize " + it.fromSize)
// if (it.fromSize != null) {
// val diff = it.toSize!! - it.fromSize!!
// if (abs(diff) > 1024) {
// builder.append("(" + (if (diff > 0) "+" else "-") + diff + " KB)")
// }
// }
log(builder.toString())
}
if (!it.toAndroidPermissions.isNullOrEmpty()) {
log(" - Android permissions: ${it.toAndroidPermissions}")
}
if (it.releaseNotesUrl != null) {
log(" - Releases notes: ${it.releaseNotesUrl}")
}
if (it.sourceCodeUrl != null) {
log(" - Source code: ${it.sourceCodeUrl}")
}
if (it.documentationUrl != null) {
log(" - Documentation: ${it.documentationUrl}")
}
if (it.issueTrackerUrl != null) {
log(" - Issue tracker: ${it.issueTrackerUrl}")
}
log("")
}
}
}
}
| 0 | null |
0
| 0 |
688ec8df572f2296e39327d88dddf3531626841b
| 3,487 |
releases-hub-gradle-plugin
|
Apache License 2.0
|
app/src/main/java/andrefigas/com/github/myapplication/data/model/StarshipResponse.kt
|
andrefigas
| 485,530,761 | false |
{"Kotlin": 33052}
|
package andrefigas.com.github.myapplication.data.model
data class StarshipResponse(val url : String, val name : String)
| 0 |
Kotlin
|
0
| 0 |
3dd097e49b93bf3005d087be82b6ad1e821ae1c5
| 120 |
StarWarsJetpackCompose
|
Apache License 2.0
|
app/src/main/kotlin/com/boscatov/schedulercw/worker/NearestTaskWorker.kt
|
23alot
| 160,862,563 | false | null |
package com.boscatov.schedulercw.worker
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.boscatov.schedulercw.Actions
import com.boscatov.schedulercw.R
import com.boscatov.schedulercw.data.entity.TASK_ACTION
import com.boscatov.schedulercw.data.entity.Task
import com.boscatov.schedulercw.data.entity.TaskAction
import com.boscatov.schedulercw.data.entity.TaskStatus
import com.boscatov.schedulercw.di.Scopes
import com.boscatov.schedulercw.interactor.task.TaskInteractor
import com.boscatov.schedulercw.receiver.NotificationTaskReceiver
import toothpick.Toothpick
import java.text.SimpleDateFormat
import javax.inject.Inject
class NearestTaskWorker(
private val context: Context,
params: WorkerParameters
) : Worker(context, params) {
@Inject
lateinit var taskInteractor: TaskInteractor
init {
val scope = Toothpick.openScope(Scopes.TASK_SCOPE)
Toothpick.inject(this, scope)
}
override fun doWork(): Result {
sendNotificationStart(taskInteractor.getNearestTask(arrayOf(TaskStatus.PENDING, TaskStatus.ACTIVE)))
return Result.success()
}
private fun sendNotificationStart(task: Task?) {
createNotificationChannel()
task?.let {
if (it.taskStatus == TaskStatus.ACTIVE) return
}
val remoteViews: RemoteViews
if (task != null && task.taskStatus == TaskStatus.PENDING && task.taskDateStart != null) {
remoteViews = RemoteViews(context.packageName, R.layout.notification_start)
remoteViews.setTextViewText(R.id.notificationStartTitleTV, task.taskTitle)
remoteViews.setTextViewText(
R.id.notificationStartTimeTV,
SimpleDateFormat("HH:mm").format(task.taskDateStart)
)
val intent = Intent(Actions.NOTIFICATION_TASK).also {
it.putExtra(TASK_ACTION, TaskAction.START.ordinal)
it.setClass(context, NotificationTaskReceiver::class.java)
}
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
remoteViews.setOnClickPendingIntent(R.id.notificationStartIB, pendingIntent)
val intent2 = Intent(Actions.NOTIFICATION_TASK).also {
it.putExtra(TASK_ACTION, TaskAction.ABANDON.ordinal)
it.setClass(context, NotificationTaskReceiver::class.java)
}
val pendingIntent2 = PendingIntent.getBroadcast(context, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT)
remoteViews.setOnClickPendingIntent(R.id.notificationStartCancelIB, pendingIntent2)
} else {
remoteViews = RemoteViews(context.packageName, R.layout.notification_no_tasks)
remoteViews.setTextViewText(R.id.notificationNoTaskTitleTV, "No recent tasks")
remoteViews.setTextViewText(R.id.notificationNoTaskTimeTV, "You've done all tasks yet")
}
val builder = NotificationCompat.Builder(context, PERIODIC_TASK_NOTIFICATION_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setCustomContentView(remoteViews)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
with(NotificationManagerCompat.from(context)) {
val notification = builder.build()
notification.flags = Notification.FLAG_ONGOING_EVENT
notify(TASK_MONITOR_ID, notification)
}
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel =
NotificationChannel(PERIODIC_TASK_NOTIFICATION_ID, "Tasks", NotificationManager.IMPORTANCE_DEFAULT)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
mNotificationManager?.createNotificationChannel(notificationChannel)
}
}
companion object {
const val PERIODIC_TASK_NOTIFICATION_ID = "TASK_CHANNEL"
const val TASK_MONITOR_ID = 672
}
}
| 0 |
Kotlin
|
0
| 0 |
28ef14d8134a8555b1f2dee62bce9bef5ad6f607
| 4,464 |
scheduler-cw
|
Apache License 2.0
|
github/src/main/java/com/haibin/calendarview/RCalendarViewDelegate.kt
|
hongri-xiao
| 273,206,205 | true |
{"Kotlin": 431326}
|
package com.haibin.calendarview
import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.util.AttributeSet
import com.angcyo.github.R
import com.angcyo.library.ex._color
/**
*
* Email:<EMAIL>
* @author angcyo
* @date 2019/07/05
* Copyright (c) 2019 ShenZhen O&M Cloud Co., Ltd. All rights reserved.
*/
class RCalendarViewDelegate(context: Context, attributeSet: AttributeSet? = null) :
CalendarViewDelegate(context, attributeSet) {
var isInEditMode = false
override fun init() {
try {
mWeekBarClass = if (TextUtils.isEmpty(mWeekBarClassPath))
WeekBar::class.java
else
Class.forName(mWeekBarClassPath)
} catch (e: Exception) {
e.printStackTrace()
}
try {
mYearViewClass = if (TextUtils.isEmpty(mYearViewClassPath))
DefaultYearView::class.java
else
Class.forName(mYearViewClassPath)
} catch (e: Exception) {
e.printStackTrace()
}
try {
mMonthViewClass = if (TextUtils.isEmpty(mMonthViewClassPath))
RMonthView::class.java
else
Class.forName(mMonthViewClassPath)
} catch (e: Exception) {
e.printStackTrace()
}
try {
mWeekViewClass = if (TextUtils.isEmpty(mWeekViewClassPath))
DefaultWeekView::class.java
else
Class.forName(mWeekViewClassPath)
} catch (e: Exception) {
e.printStackTrace()
}
super.init()
monthViewClass
weekBarClass
weekViewClass
yearViewClass
//calendarItemHeight = 100 * dpi
//monthViewShowMode = MODE_ALL_MONTH
//selectMode = SELECT_MODE_DEFAULT
mCurrentMonthTextColor = _color(R.color.text_general_color)
mCurMonthLunarTextColor = _color(R.color.text_sub_color)
mSelectedTextColor = Color.WHITE
mSelectedLunarTextColor = Color.WHITE
mWeekTextColor = Color.WHITE
if (!isInEditMode) {
mCurDayTextColor = _color(R.color.colorAccent)
mYearViewCurDayTextColor = _color(R.color.colorAccent)
mWeekBackground = _color(R.color.colorAccent)
mSelectedThemeColor = _color(R.color.colorAccent)
}
}
fun getSelectedStartRangeCalendar(): Calendar? {
return mSelectedStartRangeCalendar
}
fun getSelectedEndRangeCalendar(): Calendar? {
return mSelectedEndRangeCalendar
}
}
| 0 | null |
0
| 0 |
f0c03e123e47c50cf6226fcc9439e3cfa75e04bf
| 2,623 |
UICoreEx
|
MIT License
|
app/src/main/java/com/jeff/bundles/Read.kt
|
Jeffkent01coder
| 419,342,822 | false | null |
package com.jeff.bundles
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.jeff.bundles.databinding.ActivityMain2Binding
class Read : AppCompatActivity() {
private lateinit var binding: ActivityMain2Binding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMain2Binding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
val info = intent.getSerializableExtra("New_Data")as Person
binding.tvName.text = info.toString()
}
}
| 0 |
Kotlin
|
0
| 1 |
f8c087fa3819362b58b40d6eeb0340fa580c95e2
| 571 |
Bundles
|
Apache License 2.0
|
app/src/main/java/com/jeff/bundles/Read.kt
|
Jeffkent01coder
| 419,342,822 | false | null |
package com.jeff.bundles
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.jeff.bundles.databinding.ActivityMain2Binding
class Read : AppCompatActivity() {
private lateinit var binding: ActivityMain2Binding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMain2Binding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
val info = intent.getSerializableExtra("New_Data")as Person
binding.tvName.text = info.toString()
}
}
| 0 |
Kotlin
|
0
| 1 |
f8c087fa3819362b58b40d6eeb0340fa580c95e2
| 571 |
Bundles
|
Apache License 2.0
|
backend/core/src/main/kotlin/at/sensatech/openfastlane/mailing/MailRequest.kt
|
sensatech
| 724,093,399 | false |
{"Kotlin": 442921, "Dart": 408727, "HTML": 5563, "FreeMarker": 2659, "Dockerfile": 946, "Shell": 554}
|
package at.sensatech.openfastlane.mailing
import java.util.Locale
data class MailRequest(
val subject: String,
val to: String,
val templateFile: String,
val templateMap: Map<String, Any>,
val locale: Locale,
)
object MailRequests {
fun sendQrPdf(
to: String,
locale: Locale,
firstName: String,
lastName: String,
): MailRequest {
return MailRequest(
subject = "[OpenFastLane] Ein neuer QR-Code wurde erstellt",
to = to,
templateFile = "send_qr_pdf.ftl",
templateMap = mapOf(
"firstName" to firstName,
"lastName" to lastName,
),
locale = locale,
)
}
}
| 0 |
Kotlin
|
1
| 1 |
f80421a9db7a2b3b4fee71ebc9724789623d74bd
| 738 |
openfastlane
|
Apache License 2.0
|
app/src/main/java/com/young/youngnet/demo/BodyClientCreatorActivity.kt
|
HZHAndroid
| 402,099,012 | false | null |
package com.young.youngnet.demo
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.young.net.YoungNetWorking
import com.young.net.callback.ICallback
import com.young.net.callback.IGetCall
import com.young.net.exception.ApiException
import com.young.net.utils.JsonUtil
import com.young.youngnet.R
import com.young.youngnet.databinding.ActivityBodyClientCreatorBinding
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.Call
/**
* @author: Young
* .
* @email: <EMAIL>
* .
* @date : 2021/9/3 10:09 周五
* へ /|
/\7 ∠_/
/ │ / /
│ Z _,< / /`ヽ
│ ヽ / 〉
Y ` / /
イ● 、 ● ⊂⊃〈 /
() へ | \〈
>ー 、_ ィ │ //
/ へ / ノ<| \\
ヽ_ノ (_/ │//
7 |/
>―r ̄ ̄`ー―_
* @description: 构建带Body等功能的请求客户端构建者 demo
*/
class BodyClientCreatorActivity : AppCompatActivity() {
private val mBinding by lazy {
ActivityBodyClientCreatorBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(mBinding.root)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.menu_body_client_creator, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.post -> {
post()
}
R.id.postSync -> {
postSync()
}
R.id.put -> {
put()
}
R.id.putSync -> {
putSync()
}
R.id.patch -> {
patch()
}
R.id.patchSync -> {
pathSync()
}
}
return super.onOptionsItemSelected(item)
}
private fun showResult(msg: String?) {
runOnUiThread {
mBinding.textView.text = msg ?: ""
}
}
private fun showLoading() {
runOnUiThread {
mBinding.progressBar.visibility = View.VISIBLE
}
}
private fun hideLoading() {
runOnUiThread {
mBinding.progressBar.visibility = View.GONE
}
}
/**
* post 请求
*/
private fun post() {
showLoading()
// 方式 1
// YoungNetWorking.createBodyClientCreator("book", Any::class.java)
// .addParam("userId", "${SystemClock.currentThreadTimeMillis()}")
// .addParam("bookId", "${SystemClock.currentThreadTimeMillis()}")
// .addHeader("agent","android-app")
// .setGetCall(object : IGetCall {
// override fun onGet(call: Call<*>) {
// Log.e("shenlong", "call call call ${call}")
// }
//
// })
// .build()
// .post(object : ICallback<Any> {
// override fun onFailure(e: ApiException) {
// showResult("post ${e.msg}")
// hideLoading()
// }
//
// override fun onSuccess(data: Any?) {
// showResult("post ${data?.toString()}")
// hideLoading()
// }
// })
// 方式 2
val paramMap = mutableMapOf<String, Any>()
paramMap["userId"] = "${SystemClock.currentThreadTimeMillis()}"
paramMap["bookId"] = "${SystemClock.currentThreadTimeMillis()}"
YoungNetWorking.createBodyClientCreator("book", Any::class.java)
.setBody(
JsonUtil.toJson(paramMap)
.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
)
.addHeader("agent", "android-app")
.setGetCall(object : IGetCall {
override fun onGet(call: Call<*>) {
Log.e("shenlong", "call call call ${call}")
}
})
.build()
.post(object : ICallback<Any> {
override fun onFailure(e: ApiException) {
showResult("post ${e.msg}")
hideLoading()
}
override fun onSuccess(data: Any?) {
showResult("post ${data?.toString()}")
hideLoading()
}
})
}
/**
* post 请求(同步)
*/
private fun postSync() {
Thread {
try {
val paramMap = mutableMapOf<String, Any>()
paramMap["userId"] = "${SystemClock.currentThreadTimeMillis()}"
paramMap["bookId"] = "${SystemClock.currentThreadTimeMillis()}"
val result = YoungNetWorking.createBodyClientCreator("book", Any::class.java)
.setBody(
JsonUtil.toJson(paramMap)
.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
)
.addHeader("agent", "android-app")
.setGetCall(object : IGetCall {
override fun onGet(call: Call<*>) {
Log.e("shenlong", "call call call ${call}")
}
})
.build()
.post()
showResult("postSync ${result?.toString()}")
} catch (e: Exception) {
showResult("postSync ${e.message}")
} finally {
hideLoading()
}
}.start()
}
/**
* put 请求
*/
private fun put() {
showLoading()
// 方式 1
// YoungNetWorking.createBodyClientCreator("book", Any::class.java)
// .addParam("userId", "${SystemClock.currentThreadTimeMillis()}")
// .addParam("bookId", "${SystemClock.currentThreadTimeMillis()}")
// .addHeader("agent","android-app")
// .setGetCall(object : IGetCall {
// override fun onGet(call: Call<*>) {
// Log.e("shenlong", "call call call ${call}")
// }
//
// })
// .build()
// .put(object : ICallback<Any> {
// override fun onFailure(e: ApiException) {
// showResult("put ${e.msg}")
// hideLoading()
// }
//
// override fun onSuccess(data: Any?) {
// showResult("put ${data?.toString()}")
// hideLoading()
// }
// })
// 方式 2
val paramMap = mutableMapOf<String, Any>()
paramMap["userId"] = "${SystemClock.currentThreadTimeMillis()}"
paramMap["bookId"] = "${SystemClock.currentThreadTimeMillis()}"
YoungNetWorking.createBodyClientCreator("book", Any::class.java)
.setBody(
JsonUtil.toJson(paramMap)
.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
)
.addHeader("agent", "android-app")
.setGetCall(object : IGetCall {
override fun onGet(call: Call<*>) {
Log.e("shenlong", "call call call ${call}")
}
})
.build()
.put(object : ICallback<Any> {
override fun onFailure(e: ApiException) {
showResult("put ${e.msg}")
hideLoading()
}
override fun onSuccess(data: Any?) {
showResult("put ${data?.toString()}")
hideLoading()
}
})
}
/**
* put 请求(同步)
*/
private fun putSync() {
Thread {
try {
val paramMap = mutableMapOf<String, Any>()
paramMap["userId"] = "${SystemClock.currentThreadTimeMillis()}"
paramMap["bookId"] = "${SystemClock.currentThreadTimeMillis()}"
val result = YoungNetWorking.createBodyClientCreator("book", Any::class.java)
.setBody(
JsonUtil.toJson(paramMap)
.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
)
.addHeader("agent", "android-app")
.setGetCall(object : IGetCall {
override fun onGet(call: Call<*>) {
Log.e("shenlong", "call call call ${call}")
}
})
.build()
.put()
showResult("putSync ${result?.toString()}")
} catch (e: Exception) {
showResult("putSync ${e.message}")
} finally {
hideLoading()
}
}.start()
}
/**
* patch 请求
*/
private fun patch() {
showLoading()
// 方式 1
// YoungNetWorking.createBodyClientCreator("book", Any::class.java)
// .addParam("userId", "${SystemClock.currentThreadTimeMillis()}")
// .addParam("bookId", "${SystemClock.currentThreadTimeMillis()}")
// .addHeader("agent","android-app")
// .setGetCall(object : IGetCall {
// override fun onGet(call: Call<*>) {
// Log.e("shenlong", "call call call ${call}")
// }
//
// })
// .build()
// .patch(object : ICallback<Any> {
// override fun onFailure(e: ApiException) {
// showResult("patch ${e.msg}")
// hideLoading()
// }
//
// override fun onSuccess(data: Any?) {
// showResult("patch ${data?.toString()}")
// hideLoading()
// }
// })
// 方式 2
val paramMap = mutableMapOf<String, Any>()
paramMap["userId"] = "${SystemClock.currentThreadTimeMillis()}"
paramMap["bookId"] = "${SystemClock.currentThreadTimeMillis()}"
YoungNetWorking.createBodyClientCreator("book", Any::class.java)
.setBody(
JsonUtil.toJson(paramMap)
.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
)
.addHeader("agent", "android-app")
.setGetCall(object : IGetCall {
override fun onGet(call: Call<*>) {
Log.e("shenlong", "call call call ${call}")
}
})
.build()
.patch(object : ICallback<Any> {
override fun onFailure(e: ApiException) {
showResult("patch ${e.msg}")
hideLoading()
}
override fun onSuccess(data: Any?) {
showResult("patch ${data?.toString()}")
hideLoading()
}
})
}
/**
* path 请求(同步)
*/
private fun pathSync() {
Thread {
try {
val paramMap = mutableMapOf<String, Any>()
paramMap["userId"] = "${SystemClock.currentThreadTimeMillis()}"
paramMap["bookId"] = "${SystemClock.currentThreadTimeMillis()}"
val result = YoungNetWorking.createBodyClientCreator("book", Any::class.java)
.setBody(
JsonUtil.toJson(paramMap)
.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
)
.addHeader("agent", "android-app")
.setGetCall(object : IGetCall {
override fun onGet(call: Call<*>) {
Log.e("shenlong", "call call call ${call}")
}
})
.build()
.patch()
showResult("pathSync ${result?.toString()}")
} catch (e: Exception) {
showResult("pathSync ${e.message}")
} finally {
hideLoading()
}
}.start()
}
}
| 1 | null |
1
| 1 |
ab3bb852ecdee8de2a5595a606da3d7a6137ca13
| 12,448 |
youngnet
|
MIT License
|
src/main/kotlin/com/github/hotm/blocks/PlasseinSporeBlock.kt
|
Heart-of-the-Machine
| 271,669,718 | false | null |
package com.github.hotm.blocks
import com.github.hotm.blocks.spore.PlasseinSporeGenerator
import net.minecraft.block.Block
import net.minecraft.block.BlockState
import net.minecraft.block.Fertilizable
import net.minecraft.block.ShapeContext
import net.minecraft.server.world.ServerWorld
import net.minecraft.state.StateManager
import net.minecraft.state.property.Properties
import net.minecraft.util.math.BlockPos
import net.minecraft.util.shape.VoxelShape
import net.minecraft.world.BlockView
import net.minecraft.world.World
import java.util.*
class PlasseinSporeBlock(private val generator: PlasseinSporeGenerator, settings: Settings) :
PlasseinPlantBlock(settings), Fertilizable {
companion object {
val STAGE = Properties.STAGE
val SHAPE = createCuboidShape(2.0, 0.0, 2.0, 14.0, 12.0, 14.0)
}
init {
defaultState = stateManager.defaultState.with(STAGE, 0)
}
override fun getOutlineShape(
state: BlockState,
world: BlockView,
pos: BlockPos,
context: ShapeContext
): VoxelShape {
return SHAPE
}
override fun randomTick(state: BlockState, world: ServerWorld, pos: BlockPos, random: Random) {
if (world.getLightLevel(pos.up()) >= 9 && random.nextInt(7) == 0) {
generate(world, pos, state, random)
}
}
fun generate(serverWorld: ServerWorld, blockPos: BlockPos, blockState: BlockState, random: Random) {
if (blockState.get(STAGE) == 0) {
serverWorld.setBlockState(blockPos, blockState.cycle(STAGE), 4)
} else {
generator.generate(
serverWorld, serverWorld.chunkManager.chunkGenerator,
blockPos, blockState, random
)
}
}
override fun isFertilizable(world: BlockView, pos: BlockPos, state: BlockState, isClient: Boolean): Boolean {
return true
}
override fun canGrow(world: World, random: Random, pos: BlockPos, state: BlockState): Boolean {
return world.random.nextFloat() < 0.45
}
override fun grow(world: ServerWorld, random: Random, pos: BlockPos, state: BlockState) {
generate(world, pos, state, random)
}
override fun appendProperties(builder: StateManager.Builder<Block, BlockState>) {
builder.add(STAGE)
}
}
| 7 |
Kotlin
|
0
| 5 |
de148c50f9c8ea1d1a3bd4f4dfb035c4614d70a1
| 2,318 |
heart-of-the-machine
|
MIT License
|
app/src/main/kotlin/photos/network/settings/SettingsUiState.kt
|
photos-network
| 336,262,847 | false | null |
/*
* Copyright 2020-2022 Photos.network developers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package photos.network.settings
data class SettingsUiState(
val serverStatus: ServerStatus = ServerStatus.UNAVAILABLE,
val host: String = "",
val clientId: String = "",
val clientSecret: String = "",
)
enum class ServerStatus {
AVAILABLE(),
UNAVAILABLE(),
PROGRESS(),
UNAUTHORIZED(),
}
| 5 | null |
0
| 4 |
c3e0031688e4871977e8c07192e125dfac07c524
| 935 |
android
|
Apache License 2.0
|
definitions-ecs-ashley/src/test/kotlin/fledware/ecs/definitions/ashley/AshleyWorldTest.kt
|
fledware
| 408,627,203 | false |
{"Kotlin": 545508}
|
package fledware.ecs.definitions.ashley
import fledware.ecs.definitions.test.WorldTest
class AshleyWorldTest : WorldTest() {
override fun createDriver() = createAshleyDriver()
}
| 6 |
Kotlin
|
0
| 0 |
2422b5f3bce36d5e7ea5e0962e94f2f2bcd3997e
| 181 |
FledDefs
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppschallengesupportinterventionplanapi/client/prisonersearch/PrisonerSearchClient.kt
|
ministryofjustice
| 797,799,207 | false |
{"Kotlin": 666637, "PLpgSQL": 56741, "Mermaid": 31355, "Shell": 1890, "Dockerfile": 1386}
|
package uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.client.prisonersearch
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.bodyToMono
import reactor.core.publisher.Mono
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.client.prisonersearch.dto.PrisonerDto
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.client.retryIdempotentRequestOnTransientException
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.exception.DownstreamServiceException
@Component
class PrisonerSearchClient(@Qualifier("prisonerSearchWebClient") private val webClient: WebClient) {
fun getPrisoner(prisonerId: String): PrisonerDto? {
return try {
webClient
.get()
.uri("/prisoner/{prisonerId}", prisonerId)
.exchangeToMono { res ->
when (res.statusCode()) {
HttpStatus.NOT_FOUND -> Mono.empty()
HttpStatus.OK -> res.bodyToMono<PrisonerDto>()
else -> res.createError()
}
}
.retryIdempotentRequestOnTransientException()
.block()
} catch (e: Exception) {
throw DownstreamServiceException("Get prisoner request failed", e)
}
}
}
| 1 |
Kotlin
|
0
| 0 |
f2da8bcb174b3d6d5442c2eb5e0d73cfa6b79ae8
| 1,466 |
hmpps-challenge-support-intervention-plan-api
|
MIT License
|
src/main/kotlin/top/wsure/top/utils/FileUtils.kt
|
WsureWarframe
| 421,626,743 | false | null |
package top.wsure.top.utils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import top.wsure.top.utils.JsonUtils.jsonToObject
import java.io.*
import java.util.*
object FileUtils {
val logger: Logger = LoggerFactory.getLogger(javaClass)
inline fun <reified T> String.readResourceJson(): T? {
return kotlin.runCatching { FileUtils::class.java.classLoader.getResource(this)?.readText()?.jsonToObject<T>() }
.onFailure {
logger.warn("Read resource file {} by classloader failure !!", this, it)
}.getOrNull()
}
inline fun <reified T> String.readFileJson(): T? {
return kotlin.runCatching { File(this).readText().jsonToObject<T>() }
.onFailure {
logger.warn("Read file {} by File method failure !!", this, it)
}.getOrNull()
}
fun createFileAndDirectory(file:File,isDir:Boolean){
if(isDir) file.mkdirs()
else if(file.parentFile.exists() || file.parentFile.mkdirs()){
file.createNewFile()
}
}
fun File.copyInputStreamToFile(inputStream: InputStream) {
this.outputStream().use { fileOut ->
inputStream.copyTo(fileOut)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
b592c81de1e4812b5ffa85143145d1e6fbbdf1c7
| 1,224 |
warframe-api-ktor
|
MIT License
|
eco-core/core-proxy/src/main/kotlin/com/willfp/eco/internal/spigot/proxy/PacketHandlerProxy.kt
|
Auxilor
| 325,856,799 | false | null |
package com.willfp.eco.internal.spigot.proxy
import com.willfp.eco.core.EcoPlugin
import com.willfp.eco.core.packet.Packet
import com.willfp.eco.core.packet.PacketListener
import org.bukkit.entity.Player
interface PacketHandlerProxy {
fun sendPacket(player: Player, packet: Packet)
fun clearDisplayFrames()
fun getPacketListeners(plugin: EcoPlugin): List<PacketListener>
}
| 82 | null |
53
| 156 |
81de46a1c122a3cd6be06696b5b02d55fd9a73e5
| 389 |
eco
|
MIT License
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/sagemaker/CfnNotebookInstanceLifecycleConfigDsl.kt
|
F43nd1r
| 643,016,506 | false | null |
package com.faendir.awscdkkt.generated.services.sagemaker
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.String
import kotlin.Unit
import software.amazon.awscdk.services.sagemaker.CfnNotebookInstanceLifecycleConfig
import software.amazon.awscdk.services.sagemaker.CfnNotebookInstanceLifecycleConfigProps
import software.constructs.Construct
@Generated
public fun Construct.cfnNotebookInstanceLifecycleConfig(id: String):
CfnNotebookInstanceLifecycleConfig = CfnNotebookInstanceLifecycleConfig(this, id)
@Generated
public fun Construct.cfnNotebookInstanceLifecycleConfig(id: String, initializer: @AwsCdkDsl
CfnNotebookInstanceLifecycleConfig.() -> Unit): CfnNotebookInstanceLifecycleConfig =
CfnNotebookInstanceLifecycleConfig(this, id).apply(initializer)
@Generated
public fun Construct.cfnNotebookInstanceLifecycleConfig(id: String,
props: CfnNotebookInstanceLifecycleConfigProps): CfnNotebookInstanceLifecycleConfig =
CfnNotebookInstanceLifecycleConfig(this, id, props)
@Generated
public fun Construct.cfnNotebookInstanceLifecycleConfig(
id: String,
props: CfnNotebookInstanceLifecycleConfigProps,
initializer: @AwsCdkDsl CfnNotebookInstanceLifecycleConfig.() -> Unit,
): CfnNotebookInstanceLifecycleConfig = CfnNotebookInstanceLifecycleConfig(this, id,
props).apply(initializer)
@Generated
public fun Construct.buildCfnNotebookInstanceLifecycleConfig(id: String, initializer: @AwsCdkDsl
CfnNotebookInstanceLifecycleConfig.Builder.() -> Unit): CfnNotebookInstanceLifecycleConfig =
CfnNotebookInstanceLifecycleConfig.Builder.create(this, id).apply(initializer).build()
| 1 |
Kotlin
|
0
| 0 |
e9a0ff020b0db2b99e176059efdb124bf822d754
| 1,655 |
aws-cdk-kt
|
Apache License 2.0
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/activities/LoginActivity.kt
|
waffle-iron
| 98,105,778 | true |
{"Kotlin": 44602}
|
package io.github.feelfreelinux.wykopmobilny.activities
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.objects.APP_KEY
import io.github.feelfreelinux.wykopmobilny.utils.ApiPreferences
import io.github.feelfreelinux.wykopmobilny.utils.WykopApiManager
import io.github.feelfreelinux.wykopmobilny.utils.invisible
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity : AppCompatActivity() {
private val apiPreferences = ApiPreferences()
private val webViewClient = WykopWebViewClient()
private val apiManager: WykopApiManager by lazy { WykopApiManager(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
title = getString(R.string.login)
setupLoginViewClient()
checkIfUserIsLogged()
}
private fun setupLoginViewClient() {
webViewClient.onLoginSuccess {
startMikroblog()
}
}
private fun checkIfUserIsLogged() {
if (apiPreferences.isUserAuthorized())
startMikroblog()
else {
showLoginWebView()
}
}
private fun showLoginWebView() {
webView.webViewClient = webViewClient
webView.loadUrl("http://a.wykop.pl/user/connect/appkey/$APP_KEY")
}
fun startMikroblog() {
supportActionBar?.hide()
webView.invisible()
apiManager.getUserSessionToken(
successCallback = {
launchMikroblogHotList(apiManager.getData())
finish()
})
}
}
| 0 |
Kotlin
|
0
| 0 |
3b3a26b9a12c2a1b7fd8395ec8d76b574f759349
| 1,723 |
WykopMobilny
|
MIT License
|
testKit/src/test/java/io/hkhc/gradle/test/DefaultGradleProjectSetup.kt
|
hkhc
| 242,200,840 | false | null |
/*
* Copyright (c) 2020. Herman Cheung
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package io.hkhc.gradle.test
import io.hkhc.gradle.test.artifacory.MockArtifactoryRepositoryServer
import io.hkhc.utils.PropertiesEditor
import io.hkhc.utils.tree.Tree
import java.io.File
/**
* setup
* - keystore location
* - local repo location
* - base path to template projects
* - settings.gradle
* - gradle.properties
*/
open class DefaultGradleProjectSetup(val projectDir: File) {
/* Sub-project directories */
var subProjDirs = arrayOf<String>()
/* directory to place file signing keystore */
var keystoreTemplateDir = "functionalTestData/keystore"
/* directories to copy source code to project, or subprojects if any */
var sourceSetTemplateDirs = arrayOf("functionalTestData/lib")
/* directory for local repository */
var localRepoDir = "localRepo"
/* environment variables to run Gradle */
var envs = defaultEnvs(projectDir)
/* mock server to mimic repository servers to accept requests for test */
var mockServers = mutableListOf<BaseMockRepositoryServer>()
var mavenMockServer: MockMavenRepositoryServer? = null
set(value) {
if (value != null) {
mockServers.add(value)
}
field = value
}
var artifactoryMockServer: MockArtifactoryRepositoryServer? = null
set(value) {
if (value != null) {
mockServers.add(value)
}
field = value
}
/* expect list of tasks executed in the Gradle run, should be prefixed by ':' or ':proj:' */
lateinit var expectedTaskGraph: Tree<String>
val localRepoDirFile = File(projectDir, localRepoDir)
fun setupKeystore() {
File(keystoreTemplateDir).copyRecursively(projectDir)
}
open fun setupSourceSets() {
if (subProjDirs.isEmpty()) {
sourceSetTemplateDirs.forEach { source ->
File(source).copyRecursively(projectDir)
}
} else {
sourceSetTemplateDirs.zip(subProjDirs).forEach { (source, proj) ->
File(source).copyRecursively(File(projectDir, proj))
}
}
}
fun setupLocalRepo() {
localRepoDirFile.mkdirs()
System.setProperty("maven.repo.local", localRepoDirFile.absolutePath)
}
fun setupGradleProperties(block: PropertiesEditor.() -> Unit = {}) {
PropertiesEditor("$projectDir/gradle.properties") {
"org.gradle.jvmargs" to "-Xmx2000m"
"org.gradle.parallel" to "false"
setupKeyStore(projectDir)
block.invoke(this)
}
}
fun setupSettingsGradle(base: String = "") {
if (subProjDirs.size >= 1) {
val projList = subProjDirs.joinToString(",") { "\":$it\"" }
writeFile(
"settings.gradle",
"$base\n" +
"""
include($projList)
""".trimIndent()
)
}
}
fun setup(block: DefaultGradleProjectSetup.() -> Unit = {}): DefaultGradleProjectSetup {
block.invoke(this)
subProjDirs.forEach {
File("$projectDir/$it").mkdirs()
}
setupKeystore()
setupSourceSets()
setupLocalRepo()
setupSettingsGradle()
return this
}
fun writeFile(relativePath: String, content: String) {
File("$projectDir/$relativePath").writeText(content)
}
fun getGradleTaskTester(): GradleTaskTester {
return GradleTaskTester(
projectDir,
envs
)
}
}
| 1 | null |
1
| 1 |
ffa517f9eec0e240e11d057afc53f0d0cb026de8
| 4,189 |
jarbird
|
Apache License 2.0
|
app/src/main/java/com/example/background/workers/SaveImageToFileWorker.kt
|
DMcolmi
| 460,326,864 | false |
{"Kotlin": 19205}
|
package com.example.background.workers
import android.content.Context
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import com.example.background.KEY_IMAGE_URI
import java.text.SimpleDateFormat
import java.util.*
private const val TAG = "SaveImageToFileWorker"
class SaveImageToFileWorker(context: Context,workerParams: WorkerParameters ): Worker(context,workerParams) {
private val title = "Blured Image"
private val dateFormatter = SimpleDateFormat(
"yyyy.MM.dd 'at' HH:mm:ss z",
Locale.getDefault()
)
override fun doWork(): Result {
makeStatusNotification("saving img", applicationContext)
sleep()
val resolver = applicationContext.contentResolver
return try {
val resourceUri = inputData.getString(KEY_IMAGE_URI)
val bitmap = BitmapFactory.decodeStream(
resolver.openInputStream(Uri.parse(resourceUri))
)
val imageUrl = MediaStore.Images.Media.insertImage(
resolver,bitmap,title,dateFormatter.format(Date())
)
if(!imageUrl.isNullOrEmpty()){
Result.success(workDataOf(KEY_IMAGE_URI to imageUrl))
} else {
Log.e(TAG,"Writing to MediaStore failed")
Result.failure()
}
} catch (e: Throwable) {
e.printStackTrace()
Result.failure()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
4b2c8cfa65ad95ce4abaa01bdaf549e74e80dcc4
| 1,600 |
BlurOMatic
|
Apache License 2.0
|
src/main/kotlin/com/imma/model/console/Subject.kt
|
Indexical-Metrics-Measure-Advisory
| 344,732,013 | false |
{"XML": 2, "Gradle Kotlin DSL": 2, "INI": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 175, "Java": 3}
|
package com.imma.model.console
import com.imma.model.CollectionNames
import com.imma.model.Tuple
import com.imma.model.core.compute.ParameterDelegate
import com.imma.model.core.compute.ParameterJointDelegate
import com.imma.persist.annotation.*
import java.util.*
data class SubjectDataSetColumn(
var columnId: String = "",
var parameter: ParameterDelegate = mutableMapOf(),
var alias: String = ""
)
@Suppress("EnumEntryName")
enum class TopicJoinType(val type: String) {
left("left"),
right("right"),
`inner`("inner");
}
data class SubjectDataSetJoin(
var topicId: String = "",
var factorId: String = "",
var secondaryTopicId: String = "",
var secondaryFactorId: String = "",
var type: TopicJoinType = TopicJoinType.`inner`,
)
data class SubjectDataSet(
var filters: ParameterJointDelegate = mutableMapOf(),
var columns: List<SubjectDataSetColumn> = mutableListOf(),
var joins: List<SubjectDataSetJoin> = mutableListOf()
)
@Entity(CollectionNames.SUBJECT)
data class Subject(
@Id
var subjectId: String? = null,
@Field("name")
var name: String? = null,
@Field("connect_id")
var connectId: String? = null,
@Field("user_id")
var userId: String? = null,
@Field("auto_refresh_interval")
var autoRefreshInterval: Boolean? = null,
@Field("dataset")
var dataset: SubjectDataSet = SubjectDataSet(),
@Field("last_visit_time")
var lastVisitTime: String? = null,
@CreatedAt
override var createTime: Date? = null,
@LastModifiedAt
override var lastModifyTime: Date? = null,
) : Tuple() {
@Transient
var reports: MutableList<Report> = mutableListOf()
}
| 0 |
Kotlin
|
0
| 1 |
c42a959826e72ac8cea7a8390ccc7825f047a591
| 1,578 |
watchmen-ktor
|
MIT License
|
common/src/main/java/com/yuriikonovalov/common/application/entities/transaction/TransactionType.kt
|
yuriikonovalov
| 563,974,428 | false |
{"Kotlin": 872022}
|
package com.yuriikonovalov.common.application.entities.transaction
import com.yuriikonovalov.common.application.entities.category.CategoryType
enum class TransactionType {
INCOME, EXPENSE
}
/**
* A bridge between [CategoryType] and [TransactionType] for comparing values.
*/
fun TransactionType.equalsTo(categoryType: CategoryType): Boolean {
return when {
this == TransactionType.INCOME && categoryType == CategoryType.INCOME -> true
this == TransactionType.EXPENSE && categoryType == CategoryType.EXPENSE -> true
else -> false
}
}
| 0 |
Kotlin
|
0
| 0 |
8063508f836512fc8f8a0ba18f794bb895ee2449
| 573 |
budgethub
|
MIT License
|
core/session-front/impl/src/commonMain/kotlin/ru/kyamshanov/mission/session_front/impl/data/model/UserDto.kt
|
KYamshanov
| 656,042,097 | false |
{"Kotlin": 438060, "Batchfile": 2703, "HTML": 199, "Dockerfile": 195}
|
package ru.kyamshanov.mission.session_front.impl.data.model
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
/**
* Dto-Модель - Тело запроса для регистрации пользователя
* @property login <NAME>
* @property password <PASSWORD>
* @property info Дополнительная информация о пользователе
*/
@Serializable
internal data class UserDto(
val login: String,
val password: String,
val info: Map<String, String>? = null
)
| 7 |
Kotlin
|
0
| 1 |
11b2f6c17bf59fd3ef027536a0c1033f61b49684
| 463 |
Mission-app
|
Apache License 2.0
|
src/main/kotlin/com/mnnit/moticlubs/MotiClubsServiceApplication.kt
|
CC-MNNIT
| 583,707,830 | false |
{"Kotlin": 121890, "Shell": 385}
|
package com.mnnit.moticlubs
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication
import org.springframework.cache.annotation.EnableCaching
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories
import org.springframework.scheduling.annotation.EnableScheduling
@SpringBootApplication(exclude = [ReactiveUserDetailsServiceAutoConfiguration::class])
@EnableR2dbcRepositories
@ConfigurationPropertiesScan
@EnableCaching
@EnableScheduling
class MotiClubsServiceApplication
fun main(args: Array<String>) {
runApplication<MotiClubsServiceApplication>(*args)
}
| 0 |
Kotlin
|
2
| 1 |
8d4a09bec88014c892e425eae1e0f60fe0a98733
| 834 |
MotiClubs-Service
|
MIT License
|
mvicore/src/main/java/com/badoo/mvicore/feature/MemoFeature.kt
|
badoo
| 124,955,999 | false |
{"Kotlin": 242909, "Java": 258}
|
package com.badoo.mvicore.feature
/**
* An implementation of a single threaded feature.
*
* Please be aware of the following threading behaviours based on whether a 'featureScheduler' is provided.
*
* No 'featureScheduler' provided:
* The feature must execute on the thread that created the class. If the bootstrapper/actor observables
* change to a different thread it is your responsibility to switch back to the feature's original
* thread via observeOn, otherwise an exception will be thrown.
*
* 'featureScheduler' provided (this must be single threaded):
* The feature does not have to execute on the thread that created the class. It automatically
* switches to the feature scheduler thread when necessary.
*/
open class MemoFeature<State : Any>(
initialState: State,
featureScheduler: FeatureScheduler? = null
) : Feature<State, State, Nothing> by ReducerFeature<State, State, Nothing>(
initialState = initialState,
reducer = { _, effect -> effect },
featureScheduler = featureScheduler
)
| 35 |
Kotlin
|
86
| 1,211 |
eafc9e2435af67183d63846c3b22fcd6c3e4683c
| 1,031 |
MVICore
|
Apache License 2.0
|
ast-psi/src/test/kotlin/ktast/ast/MutableVisitorTest.kt
|
orangain
| 499,813,857 | false | null |
package ktast.ast
import ktast.ast.psi.ConverterWithMutableExtras
import ktast.ast.psi.Parser
import org.junit.Test
class MutableVisitorTest {
@Test
fun testIdentityVisitor() {
assertMutateAndWriteExact(
"""
val x = 1
val y = 2
""".trimIndent(),
{ v, _ -> v },
"""
val x = 1
val y = 2
""".trimIndent(),
)
}
@Test
fun testMutableVisitor() {
assertMutateAndWriteExact(
"""
val x = 1
val y = 2
""".trimIndent(),
{ v, _ ->
if (v is Node.Expression.NameExpression) {
when (v.text) {
"x" -> v.copy(text = "a")
"y" -> v.copy(text = "b")
else -> v
}
} else {
v
}
},
"""
val a = 1
val b = 2
""".trimIndent(),
)
}
}
private fun assertMutateAndWriteExact(
origCode: String,
fn: (v: Node, parent: Node?) -> Node,
expectedCode: String
) {
val origExtrasConv = ConverterWithMutableExtras()
val origFile = Parser(origExtrasConv).parseFile(origCode)
println("----ORIG AST----\n${Dumper.dump(origFile, origExtrasConv)}\n------------")
val newFile = MutableVisitor.preVisit(origFile, origExtrasConv, fn)
val newCode = Writer.write(newFile, origExtrasConv)
kotlin.test.assertEquals(
expectedCode.trim(),
newCode.trim(),
"Parse -> Mutate -> Write for original code, not equal"
)
}
| 0 |
Kotlin
|
0
| 4 |
495893317805b9899583e893e12a0ac72e951b9c
| 1,726 |
ktast
|
MIT License
|
app/src/main/java/com/example/maymay/MemeAdapter.kt
|
CerritusCodersComm
| 501,297,724 | false | null |
package com.example.maymay
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class MemeAdapter(private val context: Context) :
RecyclerView.Adapter<MemeAdapter.ViewHolder>() {
private lateinit var memeModel: MemeModel
private var memes: List<MemeModel.Meme> = listOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.meme_template_item, parent, false)
return ViewHolder(
view
)
}
fun setData(memeModel: MemeModel) {
this.memeModel = memeModel
memes = memeModel.data.memes
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val meme = memes[position]
// sets the title of a question to the textView from our itemHolder class
holder.memeId.text = meme.id
holder.memeName.text = meme.name
Glide.with(context)
.load(meme.url)
.error(R.drawable.ic_launcher_background)
.into(holder.memeImage)
}
// return the number of the items in the list
override fun getItemCount(): Int {
return memes.size
}
class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
val memeImage: ImageView = itemView.findViewById(R.id.meme_image)
val memeId: TextView = itemView.findViewById(R.id.meme_id)
val memeName: TextView = itemView.findViewById(R.id.meme_name)
}
}
| 0 |
Kotlin
|
1
| 1 |
46ccb5ad6f85e8c026d5a80a2008804a16c3a34b
| 1,728 |
MayMay
|
MIT License
|
architecture/src/main/java/com/cyymusic/architecture/utils/CompatUtils.kt
|
cyl-87-74-87
| 688,786,463 | false |
{"Kotlin": 310280, "Java": 253233, "HTML": 58163}
|
package com.cyymusic.architecture.utils
import android.content.ClipData
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import java.io.File
/**
* <pre>
* author:
* blog :
* time :
* desc : utils derry
</pre> *
*/
class CompatUtils {
private var uriClipUri: Uri? = null
private var takePhotoSaveAdr: Uri? = null
private fun taskPhoto(activity: AppCompatActivity) {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val mImageCaptureUri: Uri
// 判断7.0android系统
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//临时添加一个拍照权限
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
//通过FileProvider获取uri
takePhotoSaveAdr = FileProvider.getUriForFile(
activity, activity.packageName,
File(activity.externalCacheDir, "savephoto.jpg")
)
intent.putExtra(MediaStore.EXTRA_OUTPUT, takePhotoSaveAdr)
} else {
mImageCaptureUri = Uri.fromFile(File(activity.externalCacheDir, "savephoto.jpg"))
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri)
}
activity.startActivityForResult(intent, TAKE_PHOTO)
}
private fun selecetPhoto(activity: AppCompatActivity) {
val intent = Intent(Intent.ACTION_PICK, null)
intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*")
activity.startActivityForResult(intent, PHOTO_ALBUM)
}
private fun startPhotoZoom(activity: AppCompatActivity, uri: Uri?, requestCode: Int) {
val intent = Intent("com.android.camera.action.CROP")
intent.setDataAndType(uri, "image/*")
intent.putExtra("crop", "true")
intent.putExtra("aspectX", 1)
intent.putExtra("aspectY", 1)
intent.putExtra("outputX", 60)
intent.putExtra("outputY", 60)
//uriClipUri为Uri类变量,实例化uriClipUri
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (requestCode == TAKE_PHOTO) {
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.clipData = ClipData.newRawUri(MediaStore.EXTRA_OUTPUT, uri)
uriClipUri = uri
} else if (requestCode == PHOTO_ALBUM) {
uriClipUri = Uri.parse(
"file://" + "/" + activity.externalCacheDir!!
.absolutePath + "/" + "clip.jpg"
)
}
} else {
uriClipUri =
Uri.parse("file://" + "/" + activity.externalCacheDir!!.absolutePath + "/" + "clip.jpg")
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriClipUri)
intent.putExtra("return-data", false)
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString())
intent.putExtra("noFaceDetection", true)
activity.startActivityForResult(intent, PHOTO_CLIP)
}
fun onActivityResult(
activity: AppCompatActivity,
requestCode: Int,
resultCode: Int,
data: Intent
) {
if (resultCode == AppCompatActivity.RESULT_OK) {
when (requestCode) {
TAKE_PHOTO -> {
var clipUri: Uri? = null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (takePhotoSaveAdr != null) {
clipUri = takePhotoSaveAdr
}
} else {
clipUri =
Uri.fromFile(File(activity.externalCacheDir.toString() + "/savephoto.jpg"))
}
startPhotoZoom(activity, clipUri, TAKE_PHOTO)
}
PHOTO_ALBUM -> startPhotoZoom(activity, data.data, PHOTO_ALBUM)
PHOTO_CLIP -> {
}
else -> {
}
}
}
}
companion object {
private const val TAKE_PHOTO = 100
private const val PHOTO_ALBUM = 200
private const val PHOTO_CLIP = 300
}
}
| 0 |
Kotlin
|
0
| 1 |
e99f5d0258e401747c57acc79458b6fd8d857104
| 4,303 |
CYYMusic
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.