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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/test/kotlin/com/wprdev/foxcms/domain/branch/EnumTest.kt | w0wka91 | 223,784,077 | false | null | package com.wprdev.foxcms.domain.branch
import com.wprdev.foxcms.common.Name
import org.assertj.core.api.Assertions
import org.junit.Test
class EnumTest {
@Test
fun test_constructor() {
Enum(Name("PublishStatus"), ModelName("PublishStatus"), listOf("Draft", "Published"))
}
@Test
fun test_constructor_DuplicateValue() {
val enum = Enum(Name("PublishStatus"), ModelName("PublishStatus"), listOf("Draft", "Published", "Draft"))
Assertions.assertThat(enum.generateSDL()).isEqualTo("enum PublishStatus { Draft Published }")
}
@Test
fun testGenerateSDL() {
val enum = Enum(Name("PublishStatus"), ModelName("PublishStatus"), listOf("Draft", "Published"))
Assertions.assertThat(enum.generateSDL()).isEqualTo("enum PublishStatus { Draft Published }")
}
} | 0 | Kotlin | 0 | 0 | ea91e3b69496a0640483ab376218a1afc71a401a | 828 | foxcms | MIT License |
library/src/main/java/network/zenon/android/api/embedded/Stake.kt | ItsChaceD | 499,639,615 | false | {"Kotlin": 214139} | package network.zenon.android.api.embedded
import network.zenon.android.client.Client
import network.zenon.android.client.RPC_MAX_PAGE_SIZE
import network.zenon.android.embedded.Definitions
import network.zenon.android.model.embedded.RewardHistoryList
import network.zenon.android.model.embedded.StakeList
import network.zenon.android.model.embedded.UncollectedReward
import network.zenon.android.model.nom.AccountBlockTemplate
import network.zenon.android.model.primitives.Address
import network.zenon.android.model.primitives.Hash
import network.zenon.android.model.primitives.STAKE_ADDRESS
import network.zenon.android.model.primitives.ZNN_ZTS
import org.json.JSONObject
class StakeApi {
lateinit var client: Client
// RPC
fun getEntriesByAddress(address: Address, pageIndex: Int = 0, pageSize: Int = RPC_MAX_PAGE_SIZE): StakeList {
val response = client.sendRequest("embedded.stake.getEntriesByAddress", listOf(address.toString(), pageIndex, pageSize))
return StakeList.fromJson(response as JSONObject)
}
// Common RPC
fun getUncollectedReward(address: Address): UncollectedReward {
val response = client.sendRequest("embedded.stake.getUncollectedReward", listOf(address.toString()))
return UncollectedReward.fromJson(response as JSONObject)
}
fun getFrontierRewardByPage(address: Address, pageIndex: Int = 0, pageSize: Int = RPC_MAX_PAGE_SIZE): RewardHistoryList {
val response = client.sendRequest("embedded.stake.getFrontierRewardByPage", listOf(address.toString(), pageIndex, pageSize))
return RewardHistoryList.fromJson(response as JSONObject)
}
// Contract methods
fun stake(durationInSec: Int, amount: Int): AccountBlockTemplate {
return AccountBlockTemplate.callContract(STAKE_ADDRESS, ZNN_ZTS, amount, Definitions.stake.encodeFunction("Stake", listOf(durationInSec.toString())))
}
fun cancel(id: Hash): AccountBlockTemplate {
return AccountBlockTemplate.callContract(STAKE_ADDRESS, ZNN_ZTS, 0, Definitions.stake.encodeFunction("Cancel", listOf(id.hash)))
}
// Common contract methods
fun collectReward(): AccountBlockTemplate {
return AccountBlockTemplate.callContract(STAKE_ADDRESS, ZNN_ZTS, 0, Definitions.common.encodeFunction("CollectReward", emptyList<Any>()))
}
} | 0 | Kotlin | 0 | 2 | 998aac9a250d6a3de9dca35490e1e711e4e0b827 | 2,330 | zenon-android | MIT License |
shared/src/commonMain/kotlin/com/andb/apps/aspen/Platform.kt | andyburris | 280,325,042 | false | {"Kotlin": 290084, "Swift": 5541, "Ruby": 2045, "HTML": 570} | package com.andb.apps.aspen
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Job
expect fun currentTimeMillis(): Long
internal expect fun printThrowable(t: Throwable)
expect fun newIOThread(block: suspend CoroutineScope.() -> Unit): Job
expect fun <T> asyncIO(block: suspend CoroutineScope.() -> T): Deferred<T>
expect suspend fun mainThread(block: suspend CoroutineScope.() -> Unit)
expect suspend fun ioThread(block: suspend CoroutineScope.() -> Unit) | 1 | Kotlin | 1 | 1 | 8e85c0ba819f731470e302608dbd3d4ef5644955 | 510 | GradePoint | Apache License 2.0 |
core/src/commonMain/kotlin/pw/binom/io/MemoryFileSystem.kt | caffeine-mgn | 182,165,415 | false | {"C": 13079003, "Kotlin": 1913743, "C++": 200, "Shell": 88} | package pw.binom.io
import pw.binom.AsyncInput
import pw.binom.AsyncOutput
import pw.binom.asyncInput
import pw.binom.asyncOutput
import pw.binom.net.Path
import pw.binom.net.toPath
class MemoryFileSystem : FileSystem {
override suspend fun getQuota(path: Path): Quota? = null
override val isSupportUserSystem: Boolean
get() = false
private val root = FileEntity.Directory(name = "", parent = null)
override suspend fun <T> useUser(user: Any?, func: suspend () -> T): T = func()
override suspend fun mkdir(path: Path): FileSystem.Entity? {
if (path.raw.isEmpty()) {
return null
}
val it = path.elements.iterator()
var current = root
it.next()
while (it.hasNext()) {
val e = it.next()
val found = current.entities.find { it.name == e }
?: return if (it.hasNext()) {
null
} else {
val new = FileEntity.Directory(e, current)
current.entities += new
EntityWrapper(new)
}
if (found !is FileEntity.Directory) {
return null
}
current = found
}
throw FileSystem.EntityExistException(path)
}
override suspend fun getDir(path: Path): List<FileSystem.Entity>? {
if (path.raw.isEmpty()) {
return root.entities.map { EntityWrapper(it) }
}
val it = path.elements.iterator()
var current = root
it.next()
while (it.hasNext()) {
val e = it.next()
val found = current.entities.find { it.name == e } ?: return null
if (found !is FileEntity.Directory) {
return null
}
current = found
}
return current.entities.map { EntityWrapper(it) }
}
override suspend fun get(path: Path): FileSystem.Entity? {
if (path.raw.isEmpty()) {
return EntityWrapper(root)
}
val it = path.elements.iterator()
var current = root
it.next()
while (it.hasNext()) {
val e = it.next()
val found = current.entities.find { it.name == e } ?: return null
if (!it.hasNext()) {
return EntityWrapper(found)
}
if (found !is FileEntity.Directory) {
return null
}
current = found
}
return EntityWrapper(current)
}
override suspend fun new(path: Path): AsyncOutput {
TODO("Not yet implemented")
}
private inner class EntityWrapper(val e: FileEntity) : FileSystem.Entity {
override val length: Long
get() = when (e) {
is FileEntity.File -> e.body.size.toLong()
is FileEntity.Directory -> 0
}
override val isFile: Boolean
get() = e is FileEntity.File
override val lastModified: Long
get() = when (e) {
is FileEntity.File -> e.lastModified
is FileEntity.Directory -> 0
}
override val path: Path
get() {
val r = ArrayList<FileEntity>()
var c = e
do {
r += c
c = c.parent ?: break
} while (true)
r.reverse()
return r.joinToString("/") { it.name }.toPath
}
override val fileSystem: FileSystem
get() = this@MemoryFileSystem
override suspend fun read(offset: ULong, length: ULong?): AsyncInput? =
when (e) {
is FileEntity.Directory -> null
is FileEntity.File -> ByteArrayInput(e.body).asyncInput()
}
override suspend fun copy(path: Path, overwrite: Boolean): FileSystem.Entity {
TODO("Not yet implemented")
}
override suspend fun move(path: Path, overwrite: Boolean): FileSystem.Entity {
TODO("Not yet implemented")
}
override suspend fun delete() {
if (e === root) {
throw FileSystemAccess.AccessException.ForbiddenException()
}
val parent = e.parent ?: throw IllegalStateException("Maybe file ${e.name} already removed")
if (!parent.entities.remove(e)) {
throw IllegalStateException()
}
}
override suspend fun rewrite(): AsyncOutput {
val file = e as? FileEntity.File ?: throw FileSystemAccess.AccessException.ForbiddenException()
return object : ByteArrayOutput() {
override fun close() {
super.close()
file.body = this.toByteArray()
}
}.asyncOutput()
}
}
}
private sealed interface FileEntity {
var name: String
var parent: Directory?
class File(override var name: String, override var parent: Directory?) : FileEntity {
var body = ByteArray(0)
var lastModified: Long = 0
}
class Directory(override var name: String, override var parent: Directory?) : FileEntity {
val entities = ArrayList<FileEntity>()
}
} | 7 | C | 2 | 59 | 580ff27a233a1384273ef15ea6c63028dc41dc01 | 5,293 | pw.binom.io | Apache License 2.0 |
core-starter/src/main/kotlin/com/labijie/application/ErrorCodedException.kt | hongque-pro | 309,874,586 | false | {"Kotlin": 1051148, "Java": 72766} | package com.labijie.application
/**
* Created with IntelliJ IDEA.
* @author <NAME>
* @date 2019-09-05
*/
open class ErrorCodedException(
val error: String,
message: String? = null,
cause: Throwable? = null,
localizedMessage: String? = null
) : ApplicationRuntimeException(message, cause){
private val locMessage: String = localizedMessage ?: localeErrorMessage(error)
open fun getDetails():Map<String, Any>? {
return null
}
override fun getLocalizedMessage(): String = locMessage
override val message: String?
get() = super.message ?: localizedMessage
} | 0 | Kotlin | 0 | 8 | f2f709ee8fff5b6d416bc35c5d7e234a4781b096 | 613 | application-framework | Apache License 2.0 |
src/main/kotlin/com/easykotlin/reakt/advice/GlobalExceptionHandlerAdvice.kt | EasyKotlin | 114,452,054 | false | null | package com.reaktboot.reakt.advice
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
@ControllerAdvice(basePackages = arrayOf("com.ksb.ksb_with_shiro"))
class GlobalExceptionHandlerAdvice {
/**表示捕捉到 Exception的异常*/
@ExceptionHandler(value = Exception::class)
fun exception(exception: Exception, model: Model): String {
model.addAttribute("errorMessage", exception.message)
model.addAttribute("stackTrace", exception.stackTrace)
return "/error"
}
}
| 0 | null | 5 | 16 | 743aedcb14564868e373953237744b0b13e664c3 | 605 | reakt | Apache License 2.0 |
data/src/main/java/com/ravnnerdery/data/database/DatabaseDao.kt | hunter4466 | 456,732,583 | false | null | package com.ravnnerdery.data.database
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.ravnnerdery.data.database.models.PhotoInfoEntity
@Dao
interface DatabaseDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertPhoto(photoEntity: PhotoInfoEntity)
@Query("SELECT * from photo_table LIMIT 100")
fun getPhotos(): List<PhotoInfoEntity>
}
| 0 | Kotlin | 0 | 0 | 026dd91b13289b5d8eda63650dda3878637dc988 | 450 | hilt_photo_challenge | MIT License |
core/src/com/coronadefense/receiver/messages/HealthAnimationMessage.kt | swa-group1 | 346,617,304 | false | {"Kotlin": 102514} | package com.coronadefense.receiver.messages
data class HealthAnimationMessage(
val newValue: Int,
val time: Float,
): IMessage
| 7 | Kotlin | 0 | 1 | c93845de7e2ed4b4d95070547721ef93e0357a6e | 136 | corona-defense-client | MIT License |
app/src/main/java/com/example/newsapp/ui/detail/DetailFAQ.kt | Parentify | 726,522,077 | false | {"Kotlin": 71428} | package com.example.newsapp.ui.detail
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.newsapp.databinding.ActivityDetailFaqBinding
import com.example.newsapp.ui.favorites.FavoritesFragment
class DetailFAQ : AppCompatActivity() {
private lateinit var binding: ActivityDetailFaqBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDetailFaqBinding.inflate(layoutInflater)
setContentView(binding.root)
initFaqAction()
}
private fun initFaqAction(){
binding.btnFaqBack.setOnClickListener {
back()
}
}
private fun back() {
val intent = Intent(this@DetailFAQ, FavoritesFragment::class.java)
startActivity(intent)
finish()
}
} | 0 | Kotlin | 0 | 0 | 31e0622f5a442d67ecc3b6d74891f81daf1f8954 | 874 | Parentify-Mobile-Development | MIT License |
src/main/kotlin/com/danielmichalski/algorithms/algorithms/_09_sorting/bubble/BubbleSortService.kt | DanielMichalski | 288,453,885 | false | null | package pl.dmichalski.algorithms._9_sorting.bubble
import pl.dmichalski.algorithms._9_sorting.SortService
/**
* Bubble sort algorithm.
*
* O(n2) time complexity
* O(1) space complexity
*/
internal class BubbleSortService : SortService {
override fun sort(values: IntArray): IntArray {
val valuesCopy = values.copyOf()
val n = valuesCopy.size
for (i in 0 until n - 1) {
for (j in 0 until n - i - 1) {
if (valuesCopy[j] > valuesCopy[j + 1]) {
val tmp = valuesCopy[j]
valuesCopy[j] = valuesCopy[j + 1]
valuesCopy[j + 1] = tmp
}
}
}
return valuesCopy
}
}
| 0 | null | 1 | 7 | 6327b0fdb6899550b25b01eb093fa3d239938cb1 | 725 | algorithms-and-data-structures-in-kotlin | MIT License |
src/main/kotlin/nft/freeport/processor/cms/strapi/dto/AuthResponse.kt | rodrigoieh | 437,271,281 | false | null | package nft.freeport.processor.cms.strapi.dto
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import nft.freeport.processor.cms.strapi.dto.AuthData
@JsonIgnoreProperties(ignoreUnknown = true)
data class AuthResponse(val data: AuthData)
| 0 | null | 0 | 0 | 1bb284acbd01b94b80a4e6d20c1672f191fbfe77 | 251 | freeport-sc-event-listener | Apache License 2.0 |
src/jsMain/kotlin/org/andstatus/game2048/PlatformUtil.kt | andstatus | 299,049,641 | false | {"Kotlin": 247499, "Shell": 1083} | package org.andstatus.game2048
import korlibs.logger.Console
import korlibs.korge.view.Stage
import korlibs.io.concurrent.atomic.KorAtomicRef
import korlibs.io.concurrent.atomic.korAtomic
import korlibs.math.geom.SizeInt
import org.andstatus.game2048.presenter.Presenter
import kotlin.coroutines.CoroutineContext
private const val platformSourceFolder = "jsMain"
actual val CoroutineContext.gameWindowSize: SizeInt get() = defaultDesktopGameWindowSize
actual val CoroutineContext.isDarkThemeOn: Boolean get() = false
actual val defaultLanguage: String get() = ""
actual fun Presenter.shareText(actionTitle: String, fileName: String, value: Sequence<String>) =
shareTextCommon(actionTitle, fileName, value)
actual fun Stage.loadJsonGameRecord(settings: Settings, sharedJsonHandler: (Sequence<String>) -> Unit) {
Console.log("$platformSourceFolder, loadJsonGameRecord")
sharedJsonHandler(emptySequence())
}
actual fun Stage.exitApp() {}
actual fun <T> initAtomicReference(initial: T): KorAtomicRef<T> = korAtomic(initial)
actual fun <T> KorAtomicRef<T>.compareAndSetFixed(expect: T, update: T): Boolean = compareAndSet(expect, update)
| 7 | Kotlin | 11 | 61 | 7ab38d367cf8070ebc9a11a61a1983679846375f | 1,155 | game2048 | Apache License 2.0 |
app/src/main/java/org/savit/savitauthenticator/ui/dashboard/DashboardScreen.kt | develNerd | 441,734,994 | false | {"Kotlin": 186847, "CMake": 137642, "C++": 115631, "C": 9464} | package org.savit.savitauthenticator.ui.dashboard
import android.R.attr
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.text.style.ParagraphStyle
import android.util.Log
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.rounded.MoreHoriz
import androidx.compose.runtime.Composable
import androidx.compose.runtime.*
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import androidx.core.content.ContextCompat.startActivity
import org.koin.androidx.compose.get
import org.koin.androidx.compose.getViewModel
import org.savit.savitauthenticator.R
import org.savit.savitauthenticator.ui.dashboard.viewmodel.DashboardViewModel
import org.savit.savitauthenticator.ui.genericviews.CustomProgressBar
import org.savit.savitauthenticator.ui.genericviews.PinCameraActivity
import org.savit.savitauthenticator.ui.theme.*
import org.savit.savitauthenticator.utils.Coroutines
import org.savit.savitauthenticator.utils.SavitDataStore
import org.savit.savitauthenticator.utils.TotpCounter
import org.savit.savitauthenticator.utils.otp.CountDownListener
import org.savit.savitauthenticator.utils.otp.OtpProvider
import org.savit.savitauthenticator.utils.otp.TotpCountdownTask
import android.app.Activity
import android.widget.Toast
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.ui.input.pointer.pointerInput
import android.R.attr.text
import android.R.attr.label
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context.CLIPBOARD_SERVICE
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.InteractionSource
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.getSystemService
private val DEFAULT_INTERVAL:Int = 30
private val TOTP_COUNTDOWN_REFRESH_PERIOD_MILLIS = 100L
@ExperimentalFoundationApi
@Composable
fun DashboardScreen(viewModel: DashboardViewModel){
val isGrid by viewModel.isGrid.observeAsState()
val userAccounts by viewModel.userAccounts.observeAsState()
val setShowDeleteSnackbar by viewModel.showDeleteSnackbar.observeAsState(false)
val isDark = isSystemInDarkTheme()
val context = LocalContext.current
val clipboard = context.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
Box(modifier = Modifier
.fillMaxWidth()
.padding(bottom = 70.dp)) {
Column(modifier = Modifier
.fillMaxSize()
.padding(top = 3.dp, start = 3.dp, end = 3.dp))
{
if (!userAccounts.isNullOrEmpty()){
Card(modifier = Modifier
.fillMaxWidth()
.padding(7.dp)) {
Box(modifier = Modifier.fillMaxWidth()) {
Text(text = "Accounts",fontWeight = FontWeight.Bold,modifier = Modifier
.align(Alignment.CenterStart)
.padding(top = 15.dp, start = 10.dp, bottom = 15.dp))
Text(text = if (userAccounts.isNullOrEmpty()) "" else userAccounts!!.size.toString(),fontWeight = FontWeight.Bold,modifier = Modifier
.align(Alignment.CenterEnd)
.padding(top = 15.dp, end = 10.dp, bottom = 15.dp))
}
}
if (isGrid != null){
if (!isGrid!! && !userAccounts.isNullOrEmpty()){
LazyColumn(modifier = Modifier.fillMaxHeight()) {
items(userAccounts!!){userAccount ->
RowAccountItem(isDark = isDark,userAccount.name?:"",userAccount.issuer?:"",userAccount.sharedKey,icon = userAccount.image,viewModel,context,clipboard)
}
}
}else if(isGrid!! && !userAccounts.isNullOrEmpty()){
LazyVerticalGrid(cells = GridCells.Fixed(2)) {
items(userAccounts!!){userAccount ->
GridAccountItem(isDark = isDark,userAccount.name?:"",userAccount.issuer?:"",userAccount.sharedKey,icon = userAccount.image,viewModel,context,clipboard)
}
}
}
}
}else if (userAccounts != null && userAccounts!!.isEmpty()){
Box(modifier = Modifier
.fillMaxSize()
.padding(bottom = 80.dp)) {
Column(modifier = Modifier
.align(Alignment.Center)
.fillMaxSize(),horizontalAlignment = Alignment.CenterHorizontally) {
Image(painter = painterResource(id = R.drawable.intro_pic), contentDescription = "",modifier = Modifier.weight(0.4F))
Spacer(modifier = Modifier.size(10.dp))
Text(text = "No Accounts Added")
Spacer(modifier = Modifier.size(10.dp))
OutlinedButton(onClick = {
val intent = Intent(context as Activity, PinCameraActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
(context as Activity).startActivity(intent)
}) {
Icon(Icons.Default.Add, contentDescription = "",modifier = Modifier.padding(end = 10.dp))
Text(text = "Add User Account",color = if (isDark) Green201 else Green500)
}
}
}
}
}
if (setShowDeleteSnackbar){
ShwDeleteSnackBar(modifier = Modifier.align(Alignment.BottomCenter)) {
viewModel.setShowDeleteSnackBar(it)
}
}
}
}
fun deleteAccount(sharedKey:String,viewModel: DashboardViewModel){
viewModel.setShowDeleteSnackBar(true)
Handler(Looper.getMainLooper())
.postDelayed({
val delete = viewModel.showDeleteSnackbar.value?:false
if (delete){
viewModel.deleteAccount(sharedKey)
viewModel.setShowDeleteSnackBar(false)
}
},3000)
}
@Composable
fun ShwDeleteSnackBar(modifier: Modifier = Modifier,setShowSnackBar:(Boolean) -> Unit){
Box(modifier = modifier
.height(80.dp)
.fillMaxWidth()
.padding(15.dp)
.background(shape = RoundedCornerShape(3.dp), color = darkBg)) {
Row(modifier = modifier.fillMaxSize(),verticalAlignment = Alignment.CenterVertically) {
Box(modifier = Modifier
.fillMaxHeight()
.background(
color = red,
shape = RoundedCornerShape(topStart = 3.dp, bottomStart = 3.dp)
)
.width(3.dp))
Text(text = "Account Deleted",modifier = Modifier.padding(start = 10.dp,end = 5.dp),color = textColorDark,fontSize = 16.sp)
}
TextButton(onClick = { setShowSnackBar(false) },modifier = Modifier.align(Alignment.CenterEnd)) {
Text(text = "Undo",modifier = Modifier.padding(5.dp),color = Green200,fontSize = 16.sp)
}
}
}
@Preview(showBackground = true)
@Composable
fun RowAccountItemPreview(){
SavitAuthenticatorTheme() {
Box(modifier = Modifier
.padding(7.dp)
.fillMaxWidth()
.background(color = UserAccountBg, shape = RoundedCornerShape(10))) {
Column(modifier = Modifier.fillMaxWidth()) {
Row(modifier = Modifier
.wrapContentWidth()
.padding(end = 71.dp),verticalAlignment = Alignment.CenterVertically) {
Image(painter = painterResource(id = R.drawable.slack), contentDescription = "",modifier = Modifier
.padding(top = 15.dp, bottom = 15.dp, start = 10.dp, end = 10.dp)
.size(48.dp))
Column(verticalArrangement = Arrangement.Center,modifier = Modifier
.wrapContentSize()
.padding(top = 10.dp, bottom = 10.dp)) {
Text(text = "Slack",fontWeight = FontWeight.Bold,fontSize = 14.sp)
Text(text = "<EMAIL>",fontWeight = FontWeight.SemiBold,fontSize = 14.sp,modifier = Modifier.padding(top = 6.dp))
Text(text = "908765",fontWeight = FontWeight.Bold,fontSize = 18.sp,modifier = Modifier.padding(top = 6.dp))
}
}
IconButton(onClick = { /*TODO*/ },modifier = Modifier.align(Alignment.CenterHorizontally)) {
Icon(Icons.Rounded.MoreHoriz, contentDescription = "")
}
}
Box(modifier = Modifier
.size(70.dp)
.align(Alignment.CenterEnd)
.padding(end = 5.dp)) {
CustomProgressBar(progressMutiplyingFactor = 1F,"")
}
}
}
}
@Composable
fun RowAccountItem(isDark:Boolean,name:String,issuer:String,key:String,icon:Int,viewModel: DashboardViewModel,context: Context,clipboard: ClipboardManager){
var totpCountdownTask: TotpCountdownTask? = null
var totpCounter: TotpCounter
var otpProvider: OtpProvider
val timeService = get<SavitDataStore>()
val realName = if (name.contains(":")) name.split(":")[1] else name
totpCounter = TotpCounter(DEFAULT_INTERVAL.toLong())
totpCountdownTask = TotpCountdownTask(totpCounter,TOTP_COUNTDOWN_REFRESH_PERIOD_MILLIS)
otpProvider = OtpProvider(key,timeService)
var progress by remember {
mutableStateOf(1F)
}
var pin by remember {
mutableStateOf(otpProvider.getNextCode(key))
}
var secondsRemaining by remember {
mutableStateOf("")
}
//val color = if (progress <= 0.33) red else if (progress <= 0.66) lightblue else Green500
val countDownListener = object : CountDownListener {
override fun onTotpCountdown(millisRemaining: Long) {
val progressPhase =
millisRemaining.toDouble() / secondsToMillis(totpCounter.getTimeStep())
secondsRemaining = millisToSeconds(millisRemaining).toString()
progress = progressPhase.toFloat()
}
override fun onTotpCounterValueChanged() {
Coroutines.main {
try {
progress = 1F
pin = otpProvider.getNextCode(key)
} catch (e: Exception) {
Log.e("Error Message", e.message.toString())
totpCountdownTask!!.stop()
totpCountdownTask!!.setListener(null)
totpCountdownTask!!.setListener(this)
totpCountdownTask!!.start()
}
}
}
}
totpCountdownTask!!.setListener(countDownListener)
totpCountdownTask!!.startAndNotifyListener()
val lastcolor = if (isDark) myGreen else Green500
val (showDeleteDialog,setShowDeleteDialog) = remember {
mutableStateOf(false)
}
SavitAuthenticatorTheme() {
Box(modifier = Modifier
.padding(7.dp)
.fillMaxWidth()
.pointerInput(Unit) {
detectTapGestures(
onLongPress = {
setShowDeleteDialog(true)
},
onTap = {
val clip: ClipData = ClipData.newPlainText("SP", pin)
clipboard.setPrimaryClip(clip)
Toast
.makeText(context, "Pin Copied", Toast.LENGTH_SHORT)
.show()
}
)
}
.background(
color = if (isDark) GreenTrans200 else UserAccountBg,
shape = RoundedCornerShape(8)
)) {
Row(modifier = Modifier.wrapContentWidth(),verticalAlignment = Alignment.CenterVertically) {
Image(painter = painterResource(id = icon), contentDescription = "",modifier = Modifier
.padding(top = 15.dp, bottom = 15.dp, start = 10.dp, end = 10.dp)
.size(48.dp))
Column(verticalArrangement = Arrangement.Center,modifier = Modifier
.wrapContentSize()
.padding(top = 10.dp, bottom = 10.dp)) {
Text(text = issuer?:"-",fontWeight = FontWeight.Bold,fontSize = 14.sp)
Text(text = realName?:"-",fontWeight = FontWeight.SemiBold,fontSize = 14.sp,modifier = Modifier.padding(top = 6.dp))
Text(text = pin?:"",fontWeight = FontWeight.SemiBold,fontSize = 24.sp,modifier = Modifier.padding(top = 6.dp),color = if (progress <= 0.33) red else if (progress <= 0.66) lightblue else lastcolor)
}
}
Box(modifier = Modifier
.size(70.dp)
.align(Alignment.CenterEnd)
.padding(end = 5.dp)) {
CustomProgressBar(progressMutiplyingFactor = progress,secondsRemaining)
}
}
}
if (showDeleteDialog){
AlertDialog(
title = {
Text(text = "Delete Account $realName",modifier = Modifier.fillMaxWidth(),textAlign = TextAlign.Center)
},
text = {
Text(text = "You are about to delete account for $issuer:$realName",modifier = Modifier.fillMaxWidth(),textAlign = TextAlign.Center)
},onDismissRequest = {
setShowDeleteDialog(false)
},
properties = DialogProperties(true, dismissOnClickOutside = true),
confirmButton = {
TextButton(onClick = {
deleteAccount(key,viewModel)
setShowDeleteDialog(false)
}) {
Text(text = "Delete",color = red)
}
},dismissButton = {
TextButton(onClick = {
setShowDeleteDialog(false)
}) {
Text(text = "Cancel",color = if (!isDark) Green500 else Green201)
}
},modifier = Modifier.padding(15.dp))
}
}
@Composable
fun GridAccountItem(isDark:Boolean,name:String,issuer:String,key:String,icon:Int,viewModel: DashboardViewModel,context: Context,clipboard: ClipboardManager){
var totpCountdownTask: TotpCountdownTask? = null
val totpCounter: TotpCounter
val otpProvider: OtpProvider
val timeService = get<SavitDataStore>()
val realName = if (name.contains(":")) name.split(":")[1] else name
totpCounter = TotpCounter(DEFAULT_INTERVAL.toLong())
totpCountdownTask = TotpCountdownTask(totpCounter,TOTP_COUNTDOWN_REFRESH_PERIOD_MILLIS)
otpProvider = OtpProvider(key,timeService)
var progress by remember {
mutableStateOf(1F)
}
var pin by remember {
mutableStateOf(otpProvider.getNextCode(key))
}
var secondsRemaining by remember {
mutableStateOf("")
}
//val color = if (progress <= 0.33) red else if (progress <= 0.66) lightblue else Green500
val countDownListener = object : CountDownListener {
override fun onTotpCountdown(millisRemaining: Long) {
val progressPhase =
millisRemaining.toDouble() / secondsToMillis(totpCounter.getTimeStep())
secondsRemaining = millisToSeconds(millisRemaining).toString()
progress = progressPhase.toFloat()
}
override fun onTotpCounterValueChanged() {
Coroutines.main {
try {
progress = 1F
pin = otpProvider.getNextCode(key)
} catch (e: Exception) {
Log.e("Error Message", e.message.toString())
totpCountdownTask!!.stop()
totpCountdownTask!!.setListener(null)
totpCountdownTask!!.setListener(this)
totpCountdownTask!!.start()
}
}
}
}
totpCountdownTask!!.setListener(countDownListener)
totpCountdownTask!!.startAndNotifyListener()
val lastcolor = if (isDark) myGreen else Green500
val (showDeleteDialog,setShowDeleteDialog) = remember {
mutableStateOf(false)
}
SavitAuthenticatorTheme() {
Column(modifier = Modifier
.fillMaxWidth()
.padding(7.dp),horizontalAlignment = Alignment.CenterHorizontally) {
Image(painter = painterResource(id = icon), contentDescription = "",modifier = Modifier
.padding(top = 15.dp, bottom = 15.dp, start = 10.dp, end = 10.dp)
.size(48.dp))
Box(modifier = Modifier
.background(
color = if (isDark) GreenTrans200 else UserAccountBg,
shape = RoundedCornerShape(8)
)
.pointerInput(Unit) {
detectTapGestures(
onLongPress = {
setShowDeleteDialog(true)
},
onTap = {
val clip: ClipData = ClipData.newPlainText("SP", pin)
clipboard.setPrimaryClip(clip)
Toast
.makeText(context, "Pin Copied", Toast.LENGTH_SHORT)
.show()
}
)
}
.wrapContentHeight())
{
Column(verticalArrangement = Arrangement.Center,horizontalAlignment = Alignment.CenterHorizontally,modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp, bottom = 10.dp)) {
Text(text = issuer,fontWeight = FontWeight.Bold,fontSize = 14.sp,textAlign = TextAlign.Center,modifier = Modifier.align(
Alignment.CenterHorizontally))
Text(text = realName,fontWeight = FontWeight.SemiBold,fontSize = 14.sp,modifier = Modifier
.padding(top = 6.dp)
.align(
Alignment.CenterHorizontally
),textAlign = TextAlign.Center)
Text(text = pin?:"",fontWeight = FontWeight.SemiBold,fontSize = 24.sp,modifier = Modifier
.padding(top = 6.dp)
.align(
Alignment.CenterHorizontally
),textAlign = TextAlign.Center,color = if (progress <= 0.33) red else if (progress <= 0.66) lightblue else lastcolor)
Box(modifier = Modifier
.size(70.dp)
.align(Alignment.CenterHorizontally)
.padding(top = 5.dp)) {
CustomProgressBar(progressMutiplyingFactor = progress,secondsRemaining)
}
}
}
}
}
if (showDeleteDialog){
AlertDialog(
title = {
Text(text = "Delete Account $realName",modifier = Modifier.fillMaxWidth(),textAlign = TextAlign.Center)
},
text = {
Text(text = "You are about to delete account for $issuer:$realName",modifier = Modifier.fillMaxWidth(),textAlign = TextAlign.Center)
},onDismissRequest = {
},
properties = DialogProperties(true, dismissOnClickOutside = true),
confirmButton = {
TextButton(onClick = {
deleteAccount(key,viewModel = viewModel)
setShowDeleteDialog(false)
}) {
Text(text = "Delete",color = red)
}
},dismissButton = {
TextButton(onClick = {
setShowDeleteDialog(false)
}) {
Text(text = "Cancel",color = if (!isDark) Green500 else Green201)
}
},modifier = Modifier.padding(15.dp))
}
}
@Preview(showBackground = true)
@Composable
fun GridAccountItemP(){
val isDark = false
SavitAuthenticatorTheme() {
Column(modifier = Modifier
.fillMaxWidth()
.padding(7.dp),horizontalAlignment = Alignment.CenterHorizontally) {
Image(painter = painterResource(id = R.drawable.slack), contentDescription = "",modifier = Modifier
.padding(top = 15.dp, bottom = 15.dp, start = 10.dp, end = 10.dp)
.size(48.dp))
Box(modifier = Modifier
.background(
color = if (isDark) GreenTrans200 else UserAccountBg,
shape = RoundedCornerShape(8)
)
.wrapContentHeight()) {
Column(verticalArrangement = Arrangement.Center,horizontalAlignment = Alignment.CenterHorizontally,modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp, bottom = 10.dp)) {
Text(text = "Slack",fontWeight = FontWeight.Bold,fontSize = 14.sp,textAlign = TextAlign.Center,modifier = Modifier.align(
Alignment.CenterHorizontally))
Text(text = "<EMAIL>",fontWeight = FontWeight.SemiBold,fontSize = 14.sp,modifier = Modifier
.padding(top = 6.dp)
.align(
Alignment.CenterHorizontally
),textAlign = TextAlign.Center)
Text(text = "908765",fontWeight = FontWeight.Bold,fontSize = 18.sp,modifier = Modifier
.padding(top = 6.dp)
.align(
Alignment.CenterHorizontally
)
,textAlign = TextAlign.Center)
Box(modifier = Modifier
.size(70.dp)
.align(Alignment.CenterHorizontally)
.padding(top = 5.dp)) {
CustomProgressBar(progressMutiplyingFactor = 1F,"")
}
}
}
}
}
}
private fun secondsToMillis(timeSeconds: Long): Long {
return timeSeconds * 1000
}
private fun millisToSeconds(timeinMillis: Long): Long {
return timeinMillis / 1000
} | 0 | Kotlin | 0 | 2 | f8856266f20bbbcf233ac34fd200accd2650dc65 | 23,890 | SavitAuthenticator | MIT License |
frontend/android-feedme-app/app/src/main/java/com/mobilesystems/feedme/data/response/ProductResponse.kt | JaninaMattes | 523,417,679 | false | null | package com.mobilesystems.feedme.data.response
data class ProductResponse(
val productId: Int,
val expirationDate: String,
val manufacturer: String,
val nutritionValue: String,
val productName: String,
val productImage: ImageResponse? = null,
val productTags: List<ProductTag>? = null,
val quantity: String) | 1 | Kotlin | 0 | 2 | 3913a24db0ee341b30be864882c14d91cd24f535 | 340 | fudge-android-springboot | MIT License |
app/src/main/java/org/mcxa/vortaro/AboutActivity.kt | wildeyedskies | 96,164,084 | false | null | package org.mcxa.vortaro
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_about.*
class AboutActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about)
setSupportActionBar(toolbar)
//show the back button on the toolbar
if (supportActionBar != null) {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
}
about_content.movementMethod = LinkMovementMethod.getInstance()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// handle arrow click here
if (item.itemId == android.R.id.home) {
finish() // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item)
}
}
| 1 | null | 2 | 19 | 711273816aae40034e237c9b42939df59c129d7f | 1,072 | vortaro | Apache License 2.0 |
src/main/kotlin/topicWise/bitManipulation/136. Single Number.kt | sandeep549 | 262,513,267 | false | null | package topicWise.bitManipulation
private fun findNumber(nums: IntArray): Int {
var ans = 0
for (a in nums) {
ans = ans.xor(a)
}
return ans
}
| 1 | Kotlin | 0 | 0 | 166e24331a24a73051995ccd31db2cf56523c432 | 167 | leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/com/willoutwest/kalahari/scene/camera/lenses/ThinLens.kt | wbknez | 217,644,047 | false | null | package com.willoutwest.kalahari.scene.camera.lenses
import com.willoutwest.kalahari.math.Point3
import com.willoutwest.kalahari.math.Ray3
import com.willoutwest.kalahari.render.Coords
import com.willoutwest.kalahari.scene.camera.Camera
import com.willoutwest.kalahari.scene.camera.Lens
import com.willoutwest.kalahari.scene.camera.Viewport
/**
* Represents an implementation of [Lens] that creates camera rays for a
* scene as if viewing it through a circular lens of finite radius, thereby
* allowing for depth of field.
*/
class ThinLens : AbstractLens(), Lens {
override fun capture(coords: Coords, camera: Camera,
viewport: Viewport): Ray3 {
val height = viewport.bounds.height
val ps = viewport.pixelSize * (1f / camera.zoom)
val width = viewport.bounds.width
val dp = camera.sampler.nextSample()
val sp = viewport.sampler.nextSample()
val pX = ps * (coords.x - width / 2.0f * sp.x) + camera.xShift
val pY = ps * (coords.y - height / 2.0f * sp.y)
val lX = dp.x * camera.radius
val lY = dp.y * camera.radius
val dX = pX * camera.focus / camera.distance
val dY = pY * camera.focus / camera.distance
return Ray3(camera.uvw.u.clone()
.timesSelf(dX - lX)
.plusTimesSelf(dY - lY, camera.uvw.v)
.minusTimesSelf(camera.focus, camera.uvw.w)
.normalizeSelf(),
Point3(camera.eye.x + lX * camera.uvw.u.x +
lY * camera.uvw.v.x,
camera.eye.x + lX * camera.uvw.u.x +
lY * camera.uvw.v.x,
camera.eye.x + lX * camera.uvw.u.x +
lY * camera.uvw.v.x))
}
} | 0 | Kotlin | 0 | 0 | 46b1b3de9474dda22291a33b93a9b40b634c29c0 | 1,847 | kalahari | Apache License 2.0 |
compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/intrinsics/IrCheckNotNull.kt | jossiwolf | 219,828,597 | true | {"Markdown": 60, "Gradle": 598, "Gradle Kotlin DSL": 294, "Java Properties": 12, "Shell": 11, "Ignore List": 11, "Batchfile": 9, "Git Attributes": 5, "Protocol Buffer": 11, "Java": 6356, "Kotlin": 48188, "Proguard": 8, "XML": 1560, "Text": 10288, "JavaScript": 266, "JAR Manifest": 2, "Roff": 211, "Roff Manpage": 36, "INI": 115, "AsciiDoc": 1, "SVG": 31, "HTML": 463, "Groovy": 31, "JSON": 45, "JFlex": 3, "Maven POM": 95, "CSS": 4, "JSON with Comments": 7, "Ant Build System": 50, "Graphviz (DOT)": 25, "C": 1, "ANTLR": 1, "YAML": 2, "Ruby": 2, "OpenStep Property List": 2, "Swift": 2, "Objective-C": 2, "Scala": 1} | /*
* Copyright 2010-2019 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.backend.jvm.intrinsics
import org.jetbrains.kotlin.backend.jvm.codegen.BlockInfo
import org.jetbrains.kotlin.backend.jvm.codegen.ExpressionCodegen
import org.jetbrains.kotlin.backend.jvm.codegen.PromisedValue
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression
import org.jetbrains.org.objectweb.asm.Label
object IrCheckNotNull : IntrinsicMethod() {
override fun invoke(expression: IrFunctionAccessExpression, codegen: ExpressionCodegen, data: BlockInfo): PromisedValue? {
val arg0 = expression.getValueArgument(0)!!.accept(codegen, data)
if (AsmUtil.isPrimitive(arg0.type)) return arg0
return object : PromisedValue(codegen, arg0.type, expression.type) {
override fun materialize() {
arg0.materialize()
mv.dup()
if (codegen.state.languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4) {
mv.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, "checkNotNull", "(Ljava/lang/Object;)V", false)
} else {
val ifNonNullLabel = Label()
mv.ifnonnull(ifNonNullLabel)
mv.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, "throwNpe", "()V", false)
mv.mark(ifNonNullLabel)
}
}
}
}
}
| 1 | null | 0 | 1 | f17e9ba9febdabcf7a5e0f17e4be02e0f9e87f13 | 1,739 | kotlin | Apache License 2.0 |
app/src/main/java/com/autumnsun/suncoinmarket/core/utils/BindingAdapters.kt | fatihkurcenli | 459,047,502 | false | null | package com.autumnsun.suncoinmarket.core.utils
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.text.HtmlCompat
import androidx.databinding.BindingAdapter
import com.autumnsun.suncoinmarket.R
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterInside
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
@BindingAdapter(value = ["imageUrl"])
fun ImageView.bindLoadRoundedImage(
usersImageUrl: String,
) {
usersImageUrl.let {
Glide.with(this.context)
.load(it)
.transition(DrawableTransitionOptions.withCrossFade())
.into(this)
}
}
@BindingAdapter(value = ["roundedImage24"])
fun ImageView.roundedImage24(
imageUrl: String?,
) {
imageUrl.let {
Glide.with(this.context)
.load(imageUrl)
.transform(CenterInside(), RoundedCorners(24))
.transition(DrawableTransitionOptions.withCrossFade())
.into(this)
}
}
@BindingAdapter(value = ["resizeImageUrl"])
fun ImageView.resizeImageUrl(
screenShotUrl: String,
) {
screenShotUrl.let {
Glide.with(this.context)
.load(it)
.apply(RequestOptions().override(600, 300))
.transition(DrawableTransitionOptions.withCrossFade())
.into(this)
}
}
@BindingAdapter(value = ["largeImageUrl"])
fun ImageView.largeImageUrl(
screenShotLargeUrl: String,
) {
screenShotLargeUrl.let {
Glide.with(this.context)
.load(it)
.apply(RequestOptions().override(600, 300))
.transition(DrawableTransitionOptions.withCrossFade())
.into(this)
}
}
@BindingAdapter(value = ["intToString"])
fun AppCompatTextView.intToString(
intValue: Int
) {
intValue.let {
this.text = intValue.toString()
}
}
@BindingAdapter(value = ["doubleToString"])
fun AppCompatTextView.doubleToString(
doubleValue: Double
) {
doubleValue.let {
this.text = "$doubleValue $"
}
}
@BindingAdapter("setArrow")
fun ImageView.setArrow(
getCoinData: Double?
) {
getCoinData?.let {
this.setBackgroundResource(if (getCoinData > 0) R.drawable.ic_arrow_up else R.drawable.ic_arrow_down)
}
}
@BindingAdapter("setArrowBlack")
fun ImageView.setArrowBlack(
getCoinData: Double?
) {
getCoinData?.let {
this.setBackgroundResource(if (getCoinData > 0) R.drawable.ic_arrow_up_black else R.drawable.ic_arrow_down_black)
}
}
@BindingAdapter(value = ["currentValuePrice"])
fun AppCompatTextView.setCurrentValuePrice(
currentPrice: Double
) {
this.text = "$currentPrice $"
}
@BindingAdapter(value = ["currentPriceUpgradeOrDown"])
fun AppCompatTextView.setCurrentPriceUpgradeOrDown(
currentUpgrade: Double
) {
this.text = "$currentUpgrade %"
}
@BindingAdapter(value = ["setHtmlDescription"])
fun AppCompatTextView.setHtmlDescription(
description: String?
) {
description?.let {
this.text = HtmlCompat.fromHtml(description, HtmlCompat.FROM_HTML_MODE_COMPACT)
} ?: ""
}
@BindingAdapter(value = ["checkNullVisible"])
fun ImageView.checkNullVisible(
imageUrl: String?,
) {
imageUrl?.let {
Glide.with(this.context)
.load(it)
.transition(DrawableTransitionOptions.withCrossFade())
.transform(CenterInside(), RoundedCorners(24))
.transition(DrawableTransitionOptions.withCrossFade())
.into(this)
}
}
| 0 | Kotlin | 0 | 4 | f8b092c399cdfa344ab331fcddc154e8182ca4d2 | 3,638 | SunCoinMarket | MIT License |
app/src/main/java/com/ctech/eaty/ui/gallery/view/PagerAdapter.kt | dbof10 | 116,687,959 | false | null | package com.ctech.eaty.ui.gallery.view
import android.app.Activity
import android.support.v4.view.PagerAdapter
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ctech.eaty.R
import com.ctech.eaty.entity.MediaType
import com.ctech.eaty.ui.gallery.viewmodel.GalleryItemViewModel
import com.ctech.eaty.util.ResizeImageUrlProvider
import com.ctech.eaty.widget.drawable.CircleProgressBarDrawable
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.view.SimpleDraweeView
import com.facebook.imagepipeline.request.ImageRequest
import com.google.android.youtube.player.YouTubeThumbnailView
class PagerAdapter(private val context: Activity) : PagerAdapter() {
private var items: List<GalleryItemViewModel> = emptyList()
private lateinit var image: SimpleDraweeView
private lateinit var video: YouTubeThumbnailView
private lateinit var loadVideo: (YouTubeThumbnailView, String) -> Unit
private lateinit var playVideo: (String) -> Unit
private val thumbNailSize = context.resources.getDimensionPixelSize(R.dimen.thumbnail_preview_size)
override fun instantiateItem(collection: ViewGroup, position: Int): Any {
val inflater = LayoutInflater.from(context)
val layout: ViewGroup
val item = items[position]
if (item.type == MediaType.IMAGE) {
image = inflater.inflate(R.layout.item_gallery_image, collection, false) as SimpleDraweeView
loadImage(image, item.imageUrl)
collection.addView(image)
return image
} else {
layout = inflater.inflate(R.layout.item_gallery_video, collection, false) as ViewGroup
video = layout.findViewById(R.id.ivThumbnail)
layout.findViewById<View>(R.id.ivPlay).setOnClickListener {
playVideo(item.videoUrl!!)
}
video.setOnClickListener {
playVideo(item.videoUrl!!)
}
loadVideo(video, item.videoUrl!!)
collection.addView(layout)
return layout
}
}
private fun loadImage(image: SimpleDraweeView, imageUrl: String) {
val controller = Fresco.newDraweeControllerBuilder()
.setLowResImageRequest(ImageRequest.fromUri(ResizeImageUrlProvider.overrideUrl(imageUrl, thumbNailSize)))
.setImageRequest(ImageRequest.fromUri(imageUrl))
.build()
image.hierarchy.setProgressBarImage(CircleProgressBarDrawable(context))
image.controller = controller
}
fun onPlayClick(block: (String) -> Unit) {
playVideo = block
}
fun onThumbnailLoad(block: (YouTubeThumbnailView, String) -> Unit) {
loadVideo = block
}
override fun destroyItem(collection: ViewGroup, position: Int, view: Any) {
collection.removeView(view as View)
}
fun setItems(items: List<GalleryItemViewModel>) {
this.items = items
notifyDataSetChanged()
}
override fun getCount(): Int = items.size
override fun isViewFromObject(view: View, obj: Any): Boolean {
return view === obj
}
} | 2 | Kotlin | 11 | 49 | 2e3445debaedfea03f9b44ab62744046fe07f1cc | 3,190 | hunt-android | Apache License 2.0 |
features-activity/src/main/java/com/duowan/featuresActivity/bean/SelectInfo.kt | zhengyoxin | 133,010,168 | false | null | package com.duowan.featuresActivity.bean
import com.duowan.mobile.main.feature.Feature
import com.duowan.mobile.main.feature.wrapper.FeatureWrapper
/**
* Created by zhengyongxin on 2018/5/10.
*/
data class SelectInfo(val wrapper: FeatureWrapper<Feature, Any>) : BaseInfo() {
constructor(wrapper: FeatureWrapper<Feature, Any>, type: Int) : this(wrapper) {
this.type = type
}
} | 1 | null | 1 | 1 | 52508f497dbcfd98674f8c4d1d4e97d59119f7e7 | 395 | Features | Apache License 2.0 |
mobile/src/main/java/io/github/prefanatic/toomanysensors/Application.kt | prefanatic | 44,787,864 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Java": 2, "XML": 41, "Kotlin": 54} | /*
* Copyright 2015-2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.prefanatic.toomanysensors
import com.google.android.gms.wearable.Wearable
import edu.uri.egr.hermes.Hermes
import io.realm.Realm
import io.realm.RealmConfiguration
import timber.log.Timber
public class Application : android.app.Application() {
override fun onCreate() {
super.onCreate()
val realmConfig = RealmConfiguration.Builder(this)
.deleteRealmIfMigrationNeeded()
.build()
Realm.setDefaultConfiguration(realmConfig);
Realm.getInstance(realmConfig).close()
val config = Hermes.Config()
.addApi(Wearable.API)
.enableDebug(BuildConfig.DEBUG)
Hermes.init(this, config)
}
}
| 0 | Kotlin | 0 | 1 | 3b2631dc612c9fe1bf0c32bbb2539d2011e58187 | 1,315 | Too-Many-Sensors | Apache License 2.0 |
sample-flow/src/main/java/com/hannesdorfmann/mosby/sample/flow/model/InfoText.kt | ZaneSummer | 58,110,035 | true | {"Java Properties": 2, "YAML": 1, "Gradle": 15, "Shell": 3, "Markdown": 5, "Batchfile": 1, "Text": 1, "Ignore List": 11, "Proguard": 8, "Java": 275, "XML": 122, "Kotlin": 31, "INI": 4} | package com.hannesdorfmann.mosby.sample.flow.model
import android.support.annotation.StringRes
/**
*
*
* @author <NAME>
*/
data class InfoText(@StringRes val titleRes: Int, val text: String) : Info | 0 | Java | 0 | 1 | ed2784af661feda20d9b707f070eeb434a78e9d5 | 203 | mosby | Apache License 2.0 |
app/src/main/java/com/yoyiyi/soleil/network/exception/ApiException.kt | yoyiyi | 97,073,764 | false | null | package com.yoyiyi.soleil.network.exception
/**
* @author zzq 作者 E-mail: <EMAIL>
* *
* @date 创建时间:2017/5/10 10:23
* * 描述:ApiException
*/
class ApiException(msg: String) : Exception(msg)
| 2 | null | 25 | 141 | 044f76fd499bb49b0fe94d9c83c9bb1db283b8ea | 196 | bilisoleil-kotlin | Apache License 2.0 |
app/src/main/java/workshop/akbolatss/tagsnews/screen/news/NewsPresenter.kt | iRYO400 | 101,170,143 | false | null | package workshop.akbolatss.tagsnews.screen.news
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import me.toptas.rssconverter.RssItem
import workshop.akbolatss.tagsnews.api.NewsApiService
import workshop.akbolatss.tagsnews.base.BasePresenter
import workshop.akbolatss.tagsnews.model.dao.RssFeedItem
import java.io.IOException
import java.net.SocketTimeoutException
import javax.inject.Inject
/**
* MVP Presenter for #NewsFragment
* @see NewsFragment
*/
class NewsPresenter @Inject
constructor() : BasePresenter<NewsView>() {
internal lateinit var url: String
@Inject
lateinit var mApiService: NewsApiService
/**
* Show loading state and fetch RSS feed from #url
*/
fun onLoadNews() {
view.onShowLoading()
mApiService.getRss(url)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ rssFeed ->
view.onLoadNews(rssFeed)
view.onHideLoading()
}, { e ->
if (e is SocketTimeoutException) {
view.onTimeout()
} else if (e is IOException) {
view.onNetworkError()
} else {
view.onUnknownError(e.message!!)
}
view.onHideLoading()
})
}
/**
* Mapping RssItem to RssFeedItem
*/
fun mapRssFeed(rssItem: RssItem, mRssSourceId: Long?): RssFeedItem {
val rssFeedItem = RssFeedItem()
rssFeedItem.title = rssItem.title
rssFeedItem.link = rssItem.link
rssFeedItem.pubDate = rssItem.publishDate
rssFeedItem.image = rssItem.image
rssFeedItem.description = rssItem.description
rssFeedItem.rssSourceId = mRssSourceId
return rssFeedItem
}
}
| 1 | null | 1 | 5 | 629a9c97f4870c9b4e5d2ec15336d8bf060f2b9b | 1,937 | TagsNews | Apache License 2.0 |
dagger-kotlin/app/src/main/java/com/coder/dagger_kotlin/di/ActivityContext.kt | hennasingh | 179,349,774 | false | {"Java": 17678, "Kotlin": 12604} | package com.coder.dagger_kotlin.di
import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.SOURCE)
annotation class ActivityContext {
} | 1 | null | 1 | 1 | 3eb64bb69862b5c2703cc85c85c7e83dce84fc6d | 153 | android-dagger | MIT License |
wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandler.kt | square | 12,274,147 | false | null | /*
* Copyright (C) 2022 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.recipes
import com.squareup.wire.schema.Extend
import com.squareup.wire.schema.Field
import com.squareup.wire.schema.MessageType
import com.squareup.wire.schema.SchemaHandler
import com.squareup.wire.schema.Service
import com.squareup.wire.schema.Type
import okio.Path
/** Sample schema validator that enforces a field naming pattern. */
class ErrorReportingSchemaHandler : SchemaHandler() {
override fun handle(type: Type, context: SchemaHandler.Context): Path? {
val errorCollector = context.errorCollector
if ("descriptor.proto" in type.location.path) return null // Don't report errors on built-in stuff.
if (type is MessageType) {
for (field in type.fields) {
if (field.name.startsWith("a")) {
errorCollector.at(field) += "field starts with 'a'"
}
}
}
return null
}
override fun handle(service: Service, context: SchemaHandler.Context): List<Path> = emptyList()
override fun handle(extend: Extend, field: Field, context: SchemaHandler.Context): Path? = null
}
| 163 | null | 570 | 4,244 | 74715088d7d2ee1fdd6d3e070c8b413eefc7e5bd | 1,664 | wire | Apache License 2.0 |
app/src/main/java/com/savvasdalkitsis/gameframe/injector/infra/network/RetrofitInjector.kt | VeskoI | 129,795,997 | false | null | /**
* Copyright 2017 <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.injector.infra.network
import com.savvasdalkitsis.gameframe.injector.infra.network.InterceptorInjector.ipBaseHostInterceptor
import com.savvasdalkitsis.gameframe.injector.infra.network.OkHttpClientInjector.okHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitInjector {
fun retrofit(): Retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://nothing")
.client(okHttpClient(3, ipBaseHostInterceptor())
.build())
.build()
}
| 1 | null | 1 | 1 | bcd2e2167dc06d5dec0bf355c89e03ec9ba13c20 | 1,401 | gameframe | Apache License 2.0 |
app/src/test/java/cc/aoeiuv020/comic/api/ManhuataiContextTest.kt | AoEiuV020 | 55,421,417 | false | null | package cc.aoeiuv020.comic.api
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
/**
* 漫画台测试类,
* Created by AoEiuV020 on 2017.09.19-11:19:01.
*/
class ManhuataiContextTest {
init {
System.setProperty("org.slf4j.simpleLogger.log.ManhuataiContext", "info")
}
private lateinit var context: ManhuataiContext
@Before
fun setUp() {
context = ManhuataiContext()
}
@Test
fun getGenres() {
context.getGenres().forEach {
println("[${it.name}](${it.url})")
}
}
@Test
fun getNextPage() {
val genreList = listOf("http://www.manhuatai.com/zhiyinmanke.html",
"http://www.manhuatai.com/getjson.shtml?d=1505801840099&q=%E6%9F%AF%E5%8D%97",
"http://www.manhuatai.com/all.html",
"http://www.manhuatai.com/all_p813.html")
.map { ComicGenre("", it) }
genreList.forEach {
context.getNextPage(it).let {
println(it?.url)
}
}
}
@Test
fun getComicList() {
val genreList = listOf("http://www.manhuatai.com/zhiyinmanke.html",
"http://www.manhuatai.com/getjson.shtml?d=1505801840099&q=%E6%9F%AF%E5%8D%97",
"http://www.manhuatai.com/all.html")
.map { ComicGenre("", it) }
genreList.forEach {
context.getComicList(it).forEach {
println(it.name)
println(it.detailUrl)
it.img.subscribe {
println(it)
}
println(it.info)
}
}
}
@Test
fun search() {
context.search("柯南").let {
println(it.name)
println(it.url)
}
}
@Test
fun getComicDetail() {
context.getComicDetail(ComicDetailUrl("http://www.manhuatai.com/doupocangqiong/")).let {
assertEquals("斗破苍穹", it.name)
it.bigImg.subscribe {
println(it)
}
println(it.info)
it.issuesAsc.forEach {
println("[${it.name}](${it.url})")
}
}
}
@Test
fun getComicPages() {
val imgList = listOf("http://mhpic.zymkcdn.com/comic/D%2F%E6%96%97%E7%A0%B4%E8%8B%8D%E7%A9%B9%E6%8B%86%E5%88%86%E7%89%88%2F615%E8%AF%9D%2F1.jpg-mht.middle",
"http://mhpic.zymkcdn.com/comic/D%2F%E6%96%97%E7%A0%B4%E8%8B%8D%E7%A9%B9%E6%8B%86%E5%88%86%E7%89%88%2F615%E8%AF%9D%2F2.jpg-mht.middle",
"http://mhpic.zymkcdn.com/comic/D%2F%E6%96%97%E7%A0%B4%E8%8B%8D%E7%A9%B9%E6%8B%86%E5%88%86%E7%89%88%2F615%E8%AF%9D%2F3.jpg-mht.middle",
"http://mhpic.zymkcdn.com/comic/D%2F%E6%96%97%E7%A0%B4%E8%8B%8D%E7%A9%B9%E6%8B%86%E5%88%86%E7%89%88%2F615%E8%AF%9D%2F4.jpg-mht.middle",
"http://mhpic.zymkcdn.com/comic/D%2F%E6%96%97%E7%A0%B4%E8%8B%8D%E7%A9%B9%E6%8B%86%E5%88%86%E7%89%88%2F615%E8%AF%9D%2F5.jpg-mht.middle",
"http://mhpic.zymkcdn.com/comic/D%2F%E6%96%97%E7%A0%B4%E8%8B%8D%E7%A9%B9%E6%8B%86%E5%88%86%E7%89%88%2F615%E8%AF%9D%2F6.jpg-mht.middle",
"http://mhpic.zymkcdn.com/comic/D%2F%E6%96%97%E7%A0%B4%E8%8B%8D%E7%A9%B9%E6%8B%86%E5%88%86%E7%89%88%2F615%E8%AF%9D%2F7.jpg-mht.middle",
"http://mhpic.zymkcdn.com/comic/D%2F%E6%96%97%E7%A0%B4%E8%8B%8D%E7%A9%B9%E6%8B%86%E5%88%86%E7%89%88%2F615%E8%AF%9D%2F8.jpg-mht.middle")
context.getComicPages(ComicIssue("", "http://www.manhuatai.com/doupocangqiong/dpcq_615h.html")).forEachIndexed { index, (url) ->
url.subscribe { (img) ->
assertEquals(imgList[index], img)
}
}
}
} | 0 | null | 18 | 34 | f284704785b07083ae2e567a454140a7ad0230b3 | 3,719 | comic | MIT License |
android/modules/module_common/src/main/java/github/tornaco/android/thanos/module/compose/common/widget/FeatureDescription.kt | Tornaco | 228,014,878 | false | null | /*
* (C) Copyright 2022 Thanox
*
* 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.
*
*/
@file:OptIn(ExperimentalMaterial3Api::class)
package github.tornaco.android.thanos.module.compose.common.widget
import android.content.Context
import android.util.AttributeSet
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.AbstractComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import github.tornaco.android.thanos.module.common.R
import github.tornaco.android.thanos.module.compose.common.theme.getColorAttribute
class FeatureDescriptionAndroidView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) : AbstractComposeView(context, attrs, defStyleAttr) {
private val desc: MutableState<String> = mutableStateOf("")
private val isShow: MutableState<Boolean> = mutableStateOf(true)
private var onCloseClick: () -> Unit = {}
init {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
}
fun setDescription(desc: String) {
this.desc.value = desc
}
fun setOnCloseClickListener(onCloseClick: () -> Unit) {
this.onCloseClick = onCloseClick
}
@Composable
override fun Content() {
AnimatedVisibility(visible = isShow.value) {
FeatureDescription(modifier = Modifier, text = desc.value) {
onCloseClick()
}
}
}
}
@Composable
fun FeatureDescription(modifier: Modifier = Modifier, text: String, close: () -> Unit) {
val primaryColor = getColorAttribute(R.attr.appCardBackground)
Box(modifier = modifier
.fillMaxWidth()
.clip(RoundedCornerShape(24.dp))
.background(color = Color(0XFFFFECB3))
.padding(16.dp)) {
Text(modifier = Modifier
.align(Alignment.CenterStart)
.padding(end = 32.dp),
text = text,
fontSize = 10.sp)
FilledTonalIconButton(
modifier = Modifier
.align(Alignment.CenterEnd)
.size(24.dp),
colors = IconButtonDefaults.filledTonalIconButtonColors(Color(primaryColor)),
onClick = { close() }) {
Icon(
modifier = Modifier
.size(12.dp),
imageVector = Icons.Filled.Check,
contentDescription = "Check"
)
}
}
} | 392 | null | 87 | 2,145 | b8b756152e609c96fd07f1f282b77582d8cde647 | 3,774 | Thanox | Apache License 2.0 |
vertx-lang/vertx-lang-kotlin/src/main/kotlin/org/vertx/kotlin/deploy/KotlinVerticleFactory.kt | iamsteveholmes | 6,116,843 | false | {"Markdown": 10, "Batchfile": 2, "Java Properties": 4, "JavaScript": 135, "Ruby": 57, "Java": 330, "Kotlin": 26, "Python": 83, "TeX": 1, "HTML": 43} | package org.vertx.kotlin.deploy
import java.util.Arrays
import java.util.Collections
import org.jetbrains.jet.cli.jvm.compiler.KotlinToJVMBytecodeCompiler
import org.jetbrains.jet.lang.parsing.JetScriptDefinition
import org.jetbrains.jet.lang.resolve.AnalyzerScriptParameter
import org.jetbrains.jet.lang.resolve.name.Name
import org.jetbrains.jet.lang.types.ref.JetTypeName
import org.vertx.java.core.Vertx
import org.vertx.java.deploy.Container
import org.vertx.java.deploy.Verticle
import org.vertx.java.deploy.VerticleFactory
import org.vertx.java.deploy.impl.VerticleManager
import org.jetbrains.jet.utils.KotlinPaths
import org.jetbrains.jet.utils.PathUtil
public class KotlinVerticleFactory() : VerticleFactory {
private var mgr : VerticleManager? = null
public override fun init(manager: VerticleManager?) {
this.mgr = mgr
}
public override fun createVerticle(main: String?, parentCL: ClassLoader?): Verticle? {
val url = parentCL!!.getResource(main)
val path: String = url!!.getPath()!!
val kotlinPaths: KotlinPaths = PathUtil.getKotlinPathsForCompiler()
val vertxParameter = AnalyzerScriptParameter(Name.identifier("vertx"), JetTypeName.fromJavaClass(javaClass<Vertx>()))
val containerParameter = AnalyzerScriptParameter(Name.identifier("container"), JetTypeName.fromJavaClass(javaClass<Container>()))
val verticleParameter = AnalyzerScriptParameter(Name.identifier("verticle"), JetTypeName.fromJavaClass(javaClass<KotlinScriptVerticle>()))
val scriptParameters: List<AnalyzerScriptParameter>? = Arrays.asList(vertxParameter, containerParameter, verticleParameter)?.toList()
val scriptDefinitions: List<JetScriptDefinition>? = Arrays.asList(JetScriptDefinition(".kts", Collections.emptyList<AnalyzerScriptParameter>()), JetScriptDefinition(".ktscript", Collections.emptyList<AnalyzerScriptParameter>()))?.toList()
val clazz = KotlinToJVMBytecodeCompiler.compileScript(parentCL, kotlinPaths, path, scriptParameters, scriptDefinitions)!!
val verticle = KotlinScriptVerticle(clazz)
return verticle
}
public override fun reportException(t: Throwable?) {
t!!.printStackTrace()
mgr?.getLogger()!!.error("Exception in Kotlin verticle script", t)
}
}
| 1 | null | 1 | 1 | f00b015a10d70b01256d350da9c545420ff3cac2 | 2,300 | vert.x | Apache License 2.0 |
app/src/main/kotlin/io/armcha/ribble/data/mapper/Mapper.kt | armcha | 98,714,221 | false | null | package io.armcha.ribble.data.mapper
import io.armcha.ribble.data.response.*
import io.armcha.ribble.domain.entity.*
import io.armcha.ribble.presentation.utils.extensions.emptyString
import io.armcha.ribble.presentation.utils.extensions.toHtml
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by Chatikyan on 03.08.2017.
*/
class Mapper {
@JvmName("translateShotEntity")
fun translate(shotResponseList: List<ShotResponse>): List<Shot> {
return shotResponseList
.asSequence()
.map {
translate(it)
}
.toList()
}
@JvmName("translateLikeEntity")
fun translate(likeResponseList: List<LikeResponse>): List<Like> {
return likeResponseList
.asSequence()
.map {
Like(it.id, translate(it.shotResponse))
}
.toList()
}
@JvmName("translateCommentEntity")
fun translate(commentResponseList: List<CommentResponse>): List<Comment> {
return commentResponseList
.asSequence()
.map {
val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH)
Comment(it.comment?.toHtml(), translate(it.user), it.likesCount, format.parse(it.createdAt))
}
.toList()
}
fun translate(userResponse: UserResponse?): User {
return User(userResponse?.name,
userResponse?.avatarUrl ?: emptyString,
userResponse?.username,
userResponse?.location ?: emptyString)
}
private fun translate(imageResponse: ImageResponse?): Image {
return imageResponse.let {
Image(imageResponse?.small ?: emptyString,
imageResponse?.normal ?: emptyString,
imageResponse?.big ?: emptyString)
}
}
private fun translate(shotResponse: ShotResponse?): Shot {
return Shot(shotResponse?.title,
shotResponse?.id,
translate(shotResponse?.image),
translate(shotResponse?.user),
shotResponse?.description,
shotResponse?.likesCount,
shotResponse?.viewsCount,
shotResponse?.bucketsCount)
}
} | 6 | Kotlin | 120 | 879 | 815beaeb7c6c3f5d7d5c32aa60172372b2e5a844 | 2,354 | Ribble | Apache License 2.0 |
app/src/main/java/org/oppia/android/app/survey/SurveyMultipleChoiceOptionView.kt | oppia | 148,093,817 | false | {"Kotlin": 13302271, "Starlark": 693163, "Java": 34760, "Shell": 18872} | package org.oppia.android.app.survey
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.databinding.ObservableList
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.RecyclerView
import org.oppia.android.app.recyclerview.BindableAdapter
import org.oppia.android.app.shim.ViewBindingShim
import org.oppia.android.app.survey.surveyitemviewmodel.MultipleChoiceOptionContentViewModel
import org.oppia.android.app.view.ViewComponentFactory
import org.oppia.android.app.view.ViewComponentImpl
import javax.inject.Inject
/**
* A custom [RecyclerView] for displaying a variable list of items that may be selected by a user as
* part of the multiple choice option selection.
*/
class SurveyMultipleChoiceOptionView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {
@Inject
lateinit var bindingInterface: ViewBindingShim
@Inject
lateinit var singleTypeBuilderFactory: BindableAdapter.SingleTypeBuilder.Factory
private lateinit var dataList: ObservableList<MultipleChoiceOptionContentViewModel>
override fun onAttachedToWindow() {
super.onAttachedToWindow()
val viewComponentFactory = FragmentManager.findFragment<Fragment>(this) as ViewComponentFactory
val viewComponent = viewComponentFactory.createViewComponent(this) as ViewComponentImpl
viewComponent.inject(this)
maybeInitializeAdapter()
}
/**
* Sets the view's RecyclerView [MultipleChoiceOptionContentViewModel] data list.
*
* Note that this needs to be used instead of the generic RecyclerView 'data' binding adapter
* since this one takes into account initialization order with other binding properties.
*/
fun setSelectionData(dataList: ObservableList<MultipleChoiceOptionContentViewModel>) {
this.dataList = dataList
maybeInitializeAdapter()
}
private fun maybeInitializeAdapter() {
if (::singleTypeBuilderFactory.isInitialized &&
::dataList.isInitialized
) {
adapter = createAdapter().also { it.setData(dataList) }
}
}
private fun createAdapter(): BindableAdapter<MultipleChoiceOptionContentViewModel> {
return singleTypeBuilderFactory.create<MultipleChoiceOptionContentViewModel>()
.registerViewBinder(
inflateView = { parent ->
bindingInterface.provideMultipleChoiceItemsInflatedView(
LayoutInflater.from(parent.context),
parent,
/* attachToParent= */ false
)
},
bindView = { view, viewModel ->
bindingInterface.provideMultipleChoiceOptionViewModel(
view,
viewModel
)
}
)
.build()
}
}
| 508 | Kotlin | 517 | 315 | 95699f922321f49a3503783187a14ad1cef0d5d3 | 2,831 | oppia-android | Apache License 2.0 |
data/RF01742/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF01742"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
8 to 14
84 to 90
}
value = "#283ff1"
}
color {
location {
16 to 23
75 to 82
}
value = "#be08f0"
}
color {
location {
27 to 28
70 to 71
}
value = "#6e9ff7"
}
color {
location {
31 to 32
66 to 67
}
value = "#0c1cea"
}
color {
location {
33 to 34
63 to 64
}
value = "#567fa7"
}
color {
location {
36 to 37
60 to 61
}
value = "#b403ba"
}
color {
location {
40 to 46
51 to 57
}
value = "#c9611b"
}
color {
location {
93 to 100
105 to 112
}
value = "#0b8ddb"
}
color {
location {
15 to 15
83 to 83
}
value = "#9ace8f"
}
color {
location {
24 to 26
72 to 74
}
value = "#646b7d"
}
color {
location {
29 to 30
68 to 69
}
value = "#0edd42"
}
color {
location {
33 to 32
65 to 65
}
value = "#3adb63"
}
color {
location {
35 to 35
62 to 62
}
value = "#00f7e4"
}
color {
location {
38 to 39
58 to 59
}
value = "#756a0e"
}
color {
location {
47 to 50
}
value = "#0728bd"
}
color {
location {
101 to 104
}
value = "#238a19"
}
color {
location {
1 to 7
}
value = "#e523ff"
}
color {
location {
91 to 92
}
value = "#cbda30"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 2,791 | Rfam-for-RNArtist | MIT License |
cacheable/src/main/java/sk/alival/crutch/cacheable/CacheableDataSource.kt | Alival-IT | 722,898,443 | false | {"Kotlin": 157174, "Shell": 466} | package sk.alival.crutch.cacheable
import androidx.annotation.Keep
/**
* Cacheable data source indicating from where we got the data
*/
@Keep
enum class CacheableDataSource {
CACHE,
NEW
}
| 1 | Kotlin | 0 | 0 | c02f462242f5ee71c7d214ab44b2c91c5113ae0c | 200 | Crutch | MIT License |
shared/src/commonMain/kotlin/core/domain/usecase/ValidateNameUseCase.kt | wgcarvajal | 683,392,078 | false | {"Kotlin": 406626, "Swift": 1993, "Shell": 228} | package com.carpisoft.guau.core.domain.usecase
class ValidateNameUseCase {
operator fun invoke(name: String): Boolean {
return name.isNotEmpty() && name.length >= 2
}
} | 0 | Kotlin | 0 | 0 | be534933e385e57cd1c083e01b4bc1c2dccd2764 | 185 | guau-multiplatform | Apache License 2.0 |
app/src/main/java/com/github/satoshun/example/AppActivity.kt | satoshun-android-example | 217,644,602 | false | null | package com.github.satoshun.example
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewTreeLifecycleOwner
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.navigation.fragment.findNavController
import com.github.satoshun.example.databinding.AppActBinding
import com.github.satoshun.example.databinding.AppFragBinding
class AppActivity : AppCompatActivity() {
private lateinit var binding: AppActBinding
private val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) {}
private val normalContracts = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.app_act)
ViewTreeLifecycleOwner.set(window.decorView, this)
binding.root.findViewTreeLifecycleOwner()!!
getContent.launch("")
normalContracts.launch(Intent())
}
}
class AppFragment : Fragment(R.layout.app_frag) {
private val binding: AppFragBinding by dataBinding()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.desugarTime.setOnClickListener {
findNavController().navigate(AppFragmentDirections.navAppToDesguarTime())
}
println("Hit: ${view.findViewTreeLifecycleOwner()}")
}
}
| 0 | Kotlin | 0 | 0 | 81db07277d2d1a09179643e3644fd5783eab226c | 1,649 | AndroidStudioFeature | Apache License 2.0 |
ceres-components/src/main/kotlin/dev/teogor/ceres/components/events/UiEvent.kt | teogor | 555,090,893 | false | null | /*
* Copyright 2022 teogor (<NAME>) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.teogor.ceres.components.events
import androidx.annotation.StringRes
import dev.teogor.ceres.core.intent.IntentType
open class UiEvent {
object HideKeyboard : UiEvent()
class ShowToast(
@StringRes val messageResId: Int
) : UiEvent()
class ShowToastString(
val message: String
) : UiEvent()
class StartIntent(
val intentType: IntentType
) : UiEvent()
}
| 6 | Kotlin | 3 | 22 | dd556d2f43fa8b0fd44edf9d091d8059a9c8caac | 1,012 | ceres | Apache License 2.0 |
shared/src/commonMain/kotlin/com/ramo/sociality/data/model/Like.kt | OmAr-Kader | 841,632,337 | false | {"Kotlin": 254988, "Swift": 204510} | package com.ramo.sociality.data.model
import com.ramo.sociality.data.util.BaseObject
import kotlinx.datetime.Instant
import kotlinx.datetime.format
import kotlinx.datetime.format.DateTimeComponents
import kotlinx.datetime.format.byUnicodePattern
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.encodeToJsonElement
import kotlinx.serialization.json.jsonObject
@Serializable
data class Like(
@SerialName("id")
val id: Long = 0,
@SerialName("user_id")
val userId: String = "",// FOREIGN
@SerialName("post_id")
val postId: Long = 0,// FOREIGN // Not required
@SerialName("comment_id")
val commentId: Long = -1L,// FOREIGN // Not required
@SerialName("date")
val date: String = "",
): BaseObject() {
constructor() : this(0L, "", 0L, 0L)
private val dat: Instant get() = Instant.parse(date)
val timestamp: String get() {
return dat.format(DateTimeComponents.Format {
byUnicodePattern("MM/dd HH:mm")
})
}
//val now = Clock.System.now()
override fun json(): JsonObject {
return kotlinx.serialization.json.Json.encodeToJsonElement(this.copy()).jsonObject.toMutableMap().apply {
remove("id")
}.let(::JsonObject)
}
} | 0 | Kotlin | 0 | 0 | cc126af01ed268ef56a2d2b8db3dd4df74e29dd6 | 1,387 | Sociality | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/FileDelete.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.group
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.FileDelete: ImageVector
get() {
if (_fileDelete != null) {
return _fileDelete!!
}
_fileDelete = Builder(name = "FileDelete", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
group {
path(fill = SolidColor(Color(0xFF374957)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(13.9999f, 7.0f)
verticalLineTo(0.46f)
curveTo(14.9249f, 0.8093f, 15.7652f, 1.3513f, 16.4649f, 2.05f)
lineTo(19.9489f, 5.536f)
curveTo(20.6484f, 6.2349f, 21.1908f, 7.0749f, 21.5399f, 8.0f)
horizontalLineTo(14.9999f)
curveTo(14.7347f, 8.0f, 14.4803f, 7.8946f, 14.2928f, 7.7071f)
curveTo(14.1052f, 7.5196f, 13.9999f, 7.2652f, 13.9999f, 7.0f)
close()
moveTo(21.9999f, 10.485f)
verticalLineTo(19.0f)
curveTo(21.9983f, 20.3256f, 21.471f, 21.5964f, 20.5337f, 22.5338f)
curveTo(19.5963f, 23.4711f, 18.3255f, 23.9984f, 16.9999f, 24.0f)
horizontalLineTo(6.9999f)
curveTo(5.6743f, 23.9984f, 4.4034f, 23.4711f, 3.4661f, 22.5338f)
curveTo(2.5288f, 21.5964f, 2.0015f, 20.3256f, 1.9999f, 19.0f)
verticalLineTo(5.0f)
curveTo(2.0015f, 3.6744f, 2.5288f, 2.4036f, 3.4661f, 1.4662f)
curveTo(4.4034f, 0.5289f, 5.6743f, 0.0016f, 6.9999f, 0.0f)
lineTo(11.5149f, 0.0f)
curveTo(11.6779f, 0.0f, 11.8389f, 0.013f, 11.9999f, 0.024f)
verticalLineTo(7.0f)
curveTo(11.9999f, 7.7957f, 12.3159f, 8.5587f, 12.8786f, 9.1213f)
curveTo(13.4412f, 9.6839f, 14.2042f, 10.0f, 14.9999f, 10.0f)
horizontalLineTo(21.9759f)
curveTo(21.9869f, 10.161f, 21.9999f, 10.322f, 21.9999f, 10.485f)
close()
moveTo(13.4139f, 17.0f)
lineTo(15.2069f, 15.207f)
curveTo(15.389f, 15.0184f, 15.4898f, 14.7658f, 15.4876f, 14.5036f)
curveTo(15.4853f, 14.2414f, 15.3801f, 13.9906f, 15.1947f, 13.8052f)
curveTo(15.0093f, 13.6198f, 14.7585f, 13.5146f, 14.4963f, 13.5123f)
curveTo(14.2341f, 13.51f, 13.9815f, 13.6108f, 13.7929f, 13.793f)
lineTo(11.9999f, 15.586f)
lineTo(10.2069f, 13.793f)
curveTo(10.0183f, 13.6108f, 9.7657f, 13.51f, 9.5035f, 13.5123f)
curveTo(9.2413f, 13.5146f, 8.9905f, 13.6198f, 8.8051f, 13.8052f)
curveTo(8.6196f, 13.9906f, 8.5145f, 14.2414f, 8.5122f, 14.5036f)
curveTo(8.5099f, 14.7658f, 8.6107f, 15.0184f, 8.7929f, 15.207f)
lineTo(10.5859f, 17.0f)
lineTo(8.7929f, 18.793f)
curveTo(8.6974f, 18.8852f, 8.6212f, 18.9956f, 8.5688f, 19.1176f)
curveTo(8.5164f, 19.2396f, 8.4888f, 19.3708f, 8.4876f, 19.5036f)
curveTo(8.4865f, 19.6364f, 8.5118f, 19.7681f, 8.5621f, 19.891f)
curveTo(8.6123f, 20.0138f, 8.6866f, 20.1255f, 8.7805f, 20.2194f)
curveTo(8.8744f, 20.3133f, 8.986f, 20.3875f, 9.1089f, 20.4378f)
curveTo(9.2318f, 20.4881f, 9.3635f, 20.5134f, 9.4963f, 20.5123f)
curveTo(9.6291f, 20.5111f, 9.7603f, 20.4835f, 9.8823f, 20.4311f)
curveTo(10.0043f, 20.3787f, 10.1146f, 20.3025f, 10.2069f, 20.207f)
lineTo(11.9999f, 18.414f)
lineTo(13.7929f, 20.207f)
curveTo(13.9815f, 20.3892f, 14.2341f, 20.49f, 14.4963f, 20.4877f)
curveTo(14.7585f, 20.4854f, 15.0093f, 20.3802f, 15.1947f, 20.1948f)
curveTo(15.3801f, 20.0094f, 15.4853f, 19.7586f, 15.4876f, 19.4964f)
curveTo(15.4898f, 19.2342f, 15.389f, 18.9816f, 15.2069f, 18.793f)
lineTo(13.4139f, 17.0f)
close()
}
}
}
.build()
return _fileDelete!!
}
private var _fileDelete: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,167 | icons | MIT License |
app/src/main/java/com/mcmp2023/s/ui/for_you/product/userProducts/userProducstRecyclerView/UserProductsVIewAdapter.kt | S-B-Corporation | 649,775,096 | false | {"Kotlin": 122677} | package com.mcmp2023.s.ui.for_you.product.userProducts.userProducstRecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.mcmp2023.s.data.db.models.Product
import com.mcmp2023.s.databinding.ProductItemBinding
class UserProductsVIewAdapter() :
RecyclerView.Adapter<UserProductsViewHolder>() {
private val products = ArrayList<Product>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserProductsViewHolder {
val binding = ProductItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return UserProductsViewHolder(binding)
}
override fun getItemCount(): Int = products.size ?: 0
override fun onBindViewHolder(holder: UserProductsViewHolder, position: Int) {
val product = products[position]
holder.bind(product)
}
fun setData(productsList: List<Product>) {
products.clear()
products.addAll(productsList)
}
} | 0 | Kotlin | 0 | 0 | 2a6ba547eb84bdacc295efdfc93827393d18500b | 1,019 | AplicationSB | MIT License |
foryouandme/src/main/java/com/foryouandme/ui/yourdata/compose/RatingBar.kt | 4YouandMeData | 610,425,317 | false | null | package com.foryouandme.ui.yourdata.compose
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.GenericShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlin.math.cos
import kotlin.math.sin
@Composable
fun RatingBar(
rating: Float,
modifier: Modifier = Modifier,
startSpacing: Dp = 0.dp,
startColor: Color = Color.Yellow,
backgroundColor: Color = Color.Gray
) {
Row(modifier = modifier.wrapContentSize()) {
(1..5).forEach { step ->
val stepRating = when {
rating > step -> 1f
step.rem(rating) < 1 -> rating - (step - 1f)
else -> 0f
}
RatingStar(stepRating, startColor, backgroundColor)
if(step != 5)
Spacer(modifier = Modifier.width(startSpacing))
}
}
}
@Composable
private fun RatingStar(
rating: Float,
startColor: Color = Color.Yellow,
backgroundColor: Color = Color.Gray
) {
BoxWithConstraints(
modifier = Modifier
.fillMaxHeight()
.aspectRatio(1f)
.clip(starShape)
) {
Canvas(modifier = Modifier.size(maxHeight)) {
drawRect(
brush = SolidColor(backgroundColor),
size = Size(
height = size.height * 1.4f,
width = size.width * 1.4f
),
topLeft = Offset(
x = -(size.width * 0.1f),
y = -(size.height * 0.1f)
)
)
if (rating > 0) {
drawRect(
brush = SolidColor(startColor),
size = Size(
height = size.height * 1.1f,
width = size.width * rating
)
)
}
}
}
}
private val starShape = GenericShape { size, _ ->
addPath(starPath(size.height))
}
private val starPath = { size: Float ->
Path().apply {
val outerRadius: Float = size / 1.8f
val innerRadius: Double = outerRadius / 2.5
var rot: Double = Math.PI / 2 * 3
val cx: Float = size / 2
val cy: Float = size / 20 * 11
var x: Float = cx
var y: Float = cy
val step = Math.PI / 5
moveTo(cx, cy - outerRadius)
repeat(5) {
x = (cx + cos(rot) * outerRadius).toFloat()
y = (cy + sin(rot) * outerRadius).toFloat()
lineTo(x, y)
rot += step
x = (cx + cos(rot) * innerRadius).toFloat()
y = (cy + sin(rot) * innerRadius).toFloat()
lineTo(x, y)
rot += step
}
close()
}
}
@Preview
@Composable
fun RatingBarPreview() {
Column(
Modifier.background(Color.White)
) {
RatingBar(
2.8f,
modifier = Modifier.height(20.dp)
)
}
} | 0 | Kotlin | 0 | 0 | bc82972689db5052344365ac07c8f6711f5ad7fa | 3,447 | 4YouandMeAndroid | MIT License |
widget/src/main/java/me/wxc/widget/base/DailyTaskModel.kt | blackfrogxxoo | 601,097,393 | false | {"Kotlin": 234662} | package me.wxc.widget.base
import android.graphics.RectF
import me.wxc.widget.tools.adjustTimestamp
import me.wxc.widget.tools.hourMillis
import me.wxc.widget.tools.nowMillis
import me.wxc.widget.tools.quarterMillis
data class DailyTaskModel(
val id: Long = 0,
override var beginTime: Long = nowMillis.adjustTimestamp(quarterMillis, true),
var duration: Long = hourMillis / 2,
var title: String = "",
var repeatId: String = "",
var repeatMode: RepeatMode = RepeatMode.Never,
val calendarEventId: Long = 0,
var remindMode: RemindMode = RemindMode.Never,
val editingTaskModel: EditingTaskModel? = null,
) : IScheduleModel {
override val endTime: Long
get() = beginTime + duration
fun changeBeginTime(time: Long) {
val temp = beginTime
beginTime = time
duration -= time - temp
}
fun changeEndTime(time: Long) {
duration += time - endTime
}
internal val expired: Boolean
get() = nowMillis > endTime
}
enum class State {
IDLE, DRAG_BODY, DRAG_TOP, DRAG_BOTTOM
}
data class EditingTaskModel(
var draggingRect: RectF? = null,
var state: State = State.IDLE,
val onNeedScrollBlock: (x: Int, y: Int) -> Unit = { x, y -> }
) | 0 | Kotlin | 16 | 86 | ecf4f92188e2d0aa9ec3a52dfba9b52f94c052b0 | 1,244 | ScheduleView | Apache License 2.0 |
widget/src/main/java/me/wxc/widget/base/DailyTaskModel.kt | blackfrogxxoo | 601,097,393 | false | {"Kotlin": 234662} | package me.wxc.widget.base
import android.graphics.RectF
import me.wxc.widget.tools.adjustTimestamp
import me.wxc.widget.tools.hourMillis
import me.wxc.widget.tools.nowMillis
import me.wxc.widget.tools.quarterMillis
data class DailyTaskModel(
val id: Long = 0,
override var beginTime: Long = nowMillis.adjustTimestamp(quarterMillis, true),
var duration: Long = hourMillis / 2,
var title: String = "",
var repeatId: String = "",
var repeatMode: RepeatMode = RepeatMode.Never,
val calendarEventId: Long = 0,
var remindMode: RemindMode = RemindMode.Never,
val editingTaskModel: EditingTaskModel? = null,
) : IScheduleModel {
override val endTime: Long
get() = beginTime + duration
fun changeBeginTime(time: Long) {
val temp = beginTime
beginTime = time
duration -= time - temp
}
fun changeEndTime(time: Long) {
duration += time - endTime
}
internal val expired: Boolean
get() = nowMillis > endTime
}
enum class State {
IDLE, DRAG_BODY, DRAG_TOP, DRAG_BOTTOM
}
data class EditingTaskModel(
var draggingRect: RectF? = null,
var state: State = State.IDLE,
val onNeedScrollBlock: (x: Int, y: Int) -> Unit = { x, y -> }
) | 0 | Kotlin | 16 | 86 | ecf4f92188e2d0aa9ec3a52dfba9b52f94c052b0 | 1,244 | ScheduleView | Apache License 2.0 |
app/src/main/java/com/stacrux/paceclock/service/impl/SettingsServiceSharedPreferencesImpl.kt | sta-crux | 805,072,349 | false | {"Kotlin": 23132, "Java": 3813} | package com.stacrux.paceclock.service.impl
import android.content.Context.MODE_PRIVATE
import androidx.appcompat.app.AppCompatActivity
import com.stacrux.paceclock.model.ChosenOrientation
import com.stacrux.paceclock.model.ClockFace
import com.stacrux.paceclock.model.SoundSet
import com.stacrux.paceclock.service.SettingsService
/**
* Implementation of SettingsService based upon the shared preferences
*/
class SettingsServiceSharedPreferencesImpl(private val mainContext: AppCompatActivity) :
SettingsService {
private val sharedPreferences = mainContext.getSharedPreferences("MyPreferences", MODE_PRIVATE)
private val clockFaceSettingsIdentifier = "clockFace"
private val soundSetIdentifier = "soundSet"
private val setsCounterVisibilityIdentifier = "setsCounterVisibile"
private val chosenOrientationIdentifier = "chosenOrientation"
override fun getClockFace(): ClockFace {
val clockFacePref =
sharedPreferences.getString(clockFaceSettingsIdentifier, ClockFace.WHITE.name)
if (ClockFace.WHITE.name == clockFacePref) {
return ClockFace.WHITE
}
if (ClockFace.BLACK.name == clockFacePref) {
return ClockFace.BLACK
}
if (ClockFace.MODERN.name == clockFacePref) {
return ClockFace.MODERN
}
// default in case of not found
return ClockFace.WHITE
}
override fun changeClockFace(clockFace: ClockFace) {
sharedPreferences.edit().putString(clockFaceSettingsIdentifier, clockFace.name).apply()
}
override fun getSoundSet(): SoundSet {
val soundSet = sharedPreferences.getString(soundSetIdentifier, SoundSet.NONE.name)
if (soundSet == SoundSet.EFFECTS.name) {
return SoundSet.EFFECTS
}
if (soundSet == SoundSet.NOTES.name) {
return SoundSet.NOTES
}
return SoundSet.NONE
}
override fun changeSoundSet(soundSet: SoundSet) {
sharedPreferences.edit().putString(soundSetIdentifier, soundSet.name).apply()
}
override fun isSoundEnabled(): Boolean {
val soundSet = getSoundSet()
return soundSet != SoundSet.NONE
}
override fun isSetsCounterEnabled(): Boolean {
return sharedPreferences.getBoolean(setsCounterVisibilityIdentifier, true)
}
override fun changeSetsCounterVisibility(isVisible: Boolean) {
sharedPreferences.edit().putBoolean(setsCounterVisibilityIdentifier, isVisible)
.apply()
}
override fun getChosenOrientation(): ChosenOrientation {
val orientation =
sharedPreferences.getString(soundSetIdentifier, ChosenOrientation.PORTRAIT.name)
if (orientation == ChosenOrientation.LANDSCAPE.name) {
return ChosenOrientation.LANDSCAPE
}
return ChosenOrientation.LANDSCAPE
}
override fun changeChosenOrientation(chosenOrientation: ChosenOrientation) {
sharedPreferences.edit()
.putString(chosenOrientationIdentifier, ChosenOrientation.PORTRAIT.name)
.apply()
}
} | 0 | Kotlin | 0 | 0 | 2462c8b1ccd6bbb6e5f351bedc085b08082ef26c | 3,100 | PaceClock | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/LaptopMobile.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.LaptopMobile: ImageVector
get() {
if (_laptopMobile != null) {
return _laptopMobile!!
}
_laptopMobile = Builder(name = "LaptopMobile", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 18.0f)
lineTo(3.0f, 18.0f)
curveToRelative(-1.66f, 0.0f, -3.0f, -1.34f, -3.0f, -3.0f)
verticalLineToRelative(-1.0f)
lineTo(8.15f, 14.0f)
lineToRelative(0.85f, 1.0f)
horizontalLineToRelative(3.01f)
verticalLineToRelative(3.0f)
close()
moveTo(24.0f, 12.0f)
curveToRelative(0.0f, -1.65f, -1.35f, -3.0f, -3.0f, -3.0f)
horizontalLineToRelative(-4.0f)
curveToRelative(-1.65f, 0.0f, -3.0f, 1.35f, -3.0f, 3.0f)
verticalLineToRelative(12.0f)
horizontalLineToRelative(10.0f)
lineTo(24.0f, 12.0f)
close()
moveTo(12.0f, 12.0f)
curveToRelative(0.0f, -2.76f, 2.24f, -5.0f, 5.0f, -5.0f)
horizontalLineToRelative(4.0f)
curveToRelative(0.34f, 0.0f, 0.68f, 0.04f, 1.0f, 0.1f)
lineTo(22.0f, 0.0f)
lineTo(2.0f, 0.0f)
lineTo(2.0f, 12.0f)
horizontalLineToRelative(7.08f)
lineToRelative(0.85f, 1.0f)
horizontalLineToRelative(2.07f)
verticalLineToRelative(-1.0f)
close()
}
}
.build()
return _laptopMobile!!
}
private var _laptopMobile: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,563 | icons | MIT License |
src/main/kotlin/io/github/takusan23/resettable/screen/ResetTableScreenHandlers.kt | takusan23 | 461,187,880 | false | {"Kotlin": 36688, "Java": 621} | package io.github.takusan23.resettable.screen
import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerType
/**
* このMODで使うスクリーンハンドラー
* */
object ResetTableScreenHandlers {
/**
* リセットテーブルブロックのエンティティのスクリーンハンドラー
*/
val RESET_TABLE_SCREEN_HANDLER = ExtendedScreenHandlerType { syncId, inventory, buf -> ResetTableScreenHandler(syncId, inventory, buf) }
} | 1 | Kotlin | 0 | 0 | da6315ea9de5fdb00ed67b712fa8fa695fb45933 | 386 | ResetTable | Apache License 2.0 |
src/test/kotlin/day5/Day5Test.kt | alxgarcia | 435,549,527 | false | null | package day5
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class Day5Test {
private val sampleData = buildMatrix(
listOf(
"0,9 -> 5,9",
"8,0 -> 0,8",
"9,4 -> 3,4",
"2,2 -> 2,1",
"7,0 -> 7,4",
"6,4 -> 2,0",
"0,9 -> 2,9",
"3,4 -> 1,4",
"0,0 -> 8,8",
"5,5 -> 8,2"
)
)
@Test
fun regex() {
assertEquals(listOf(0, 9, 5, 9), parseLine("0,9 -> 5,9"))
assertEquals(listOf(0, 19, 15, 9), parseLine("0,19 -> 15,9"))
}
@Test
fun expandRange() {
assertEquals(listOf(1 to 0, 1 to 1, 1 to 2, 1 to 3, 1 to 4), expandSegmentRange(1, 0, 1, 4))
assertEquals(listOf(1 to 0, 2 to 0, 3 to 0), expandSegmentRange(1, 0, 3, 0))
assertEquals(listOf(1 to 0, 2 to 1, 3 to 2), expandSegmentRange(1, 0, 3, 2))
assertEquals(listOf(3 to 0, 2 to 1, 1 to 2), expandSegmentRange(3, 0, 1, 2))
}
@Test
fun `build matrix from cloudy segments`() {
val input1 = listOf("0,0 -> 0,0")
val expected1 = mapOf((0 to 0) to 1)
assertEquals(expected1, buildMatrix(input1))
val input2a = listOf("0,0 -> 0,3")
val input2b = listOf("0,3 -> 0,0")
val expected2 = mapOf(
(0 to 0) to 1,
(0 to 1) to 1,
(0 to 2) to 1,
(0 to 3) to 1,
)
assertEquals(expected2, buildMatrix(input2a))
assertEquals(expected2, buildMatrix(input2b))
val input3 = listOf("0,0 -> 0,3", "0,1 -> 0,2")
val expected3 = mapOf(
(0 to 0) to 1,
(0 to 1) to 2,
(0 to 2) to 2,
(0 to 3) to 1,
)
assertEquals(expected3, buildMatrix(input3))
}
@Test
fun `number of points where at least two cloudy segments overlap`() {
assertEquals(12, countCloudSegmentOverlappingPoints(sampleData))
}
} | 0 | Kotlin | 0 | 0 | d6b10093dc6f4a5fc21254f42146af04709f6e30 | 1,780 | advent-of-code-2021 | MIT License |
ktor-jmh/src/org/jetbrains/ktor/tests/IntegrationBenchmark.kt | rinekri | 73,641,148 | true | {"Kotlin": 1065085, "Java": 61930, "FreeMarker": 6356, "CSS": 5404, "HTML": 1964, "JavaScript": 1451} | package org.jetbrains.ktor.tests
import ch.qos.logback.classic.Level
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.content.*
import org.jetbrains.ktor.jetty.*
import org.jetbrains.ktor.routing.*
import org.openjdk.jmh.annotations.*
import org.slf4j.*
import org.slf4j.Logger
import java.io.*
import java.net.*
@State(Scope.Benchmark)
open class IntegrationBenchmark {
private val packageName = FullBenchmark::class.java.`package`.name
private val classFileName = FullBenchmark::class.simpleName!! + ".class"
private val pomFile = File("pom.xml")
lateinit private var server: JettyApplicationHost
private val port = 5678
@Setup
fun configureServer() {
val root = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) as ch.qos.logback.classic.Logger
root.level = Level.ERROR
server = embeddedJettyServer(port) {
routing {
get("/sayOK") {
call.respond("OK")
}
get("/jarfile") {
call.respond(call.resolveClasspathWithPath("java/lang/", "String.class")!!)
}
get("/regularClasspathFile") {
call.respond(call.resolveClasspathWithPath(packageName, classFileName)!!)
}
get("/regularFile") {
call.respond(LocalFileContent(pomFile))
}
}
}
server.start()
}
@TearDown
fun shutdownServer() {
server.stop()
}
@Benchmark
fun sayOK(): String {
return URL("http://localhost:$port/sayOK").readText()
}
@Benchmark
fun jarfile(): ByteArray {
return URL("http://localhost:$port/jarfile").readBytes()
}
@Benchmark
fun regularClasspathFile(): ByteArray {
return URL("http://localhost:$port/regularClasspathFile").readBytes()
}
@Benchmark
fun regularFile(): ByteArray {
return URL("http://localhost:$port/regularFile").readBytes()
}
}
/*
Benchmark Mode Cnt Score Error Units
IntegrationBenchmark.jarfile thrpt 10 10.041 ± 3.944 ops/ms
IntegrationBenchmark.regularClasspathFile thrpt 10 8.444 ± 2.189 ops/ms
IntegrationBenchmark.regularFile thrpt 10 15.393 ± 2.060 ops/ms
IntegrationBenchmark.sayOK thrpt 10 21.573 ± 3.653 ops/ms
*/
fun main(args: Array<String>) {
benchmark(args) {
threads = 8
run<IntegrationBenchmark>()
}
}
| 0 | Kotlin | 0 | 0 | 9676a764e34f5c552b56ce856b39aa92f155cf28 | 2,559 | ktor | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/CommentArrowDown.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.CommentArrowDown: ImageVector
get() {
if (_commentArrowDown != null) {
return _commentArrowDown!!
}
_commentArrowDown = Builder(name = "CommentArrowDown", defaultWidth = 512.0.dp,
defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 0.0f)
curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
horizontalLineToRelative(12.0f)
lineTo(24.0f, 12.0f)
curveTo(24.0f, 5.383f, 18.617f, 0.0f, 12.0f, 0.0f)
close()
moveTo(22.0f, 22.0f)
lineTo(12.0f, 22.0f)
curveToRelative(-5.514f, 0.0f, -10.0f, -4.486f, -10.0f, -10.0f)
reflectiveCurveTo(6.486f, 2.0f, 12.0f, 2.0f)
reflectiveCurveToRelative(10.0f, 4.486f, 10.0f, 10.0f)
verticalLineToRelative(10.0f)
close()
moveTo(16.293f, 11.962f)
lineToRelative(1.414f, 1.414f)
lineToRelative(-3.889f, 3.889f)
curveToRelative(-0.491f, 0.491f, -1.135f, 0.737f, -1.777f, 0.737f)
curveToRelative(-0.631f, 0.0f, -1.26f, -0.238f, -1.738f, -0.716f)
lineToRelative(-3.91f, -3.91f)
lineToRelative(1.414f, -1.414f)
lineToRelative(3.192f, 3.193f)
lineTo(10.999f, 6.0f)
horizontalLineToRelative(2.0f)
lineTo(12.999f, 15.256f)
lineToRelative(3.293f, -3.293f)
close()
}
}
.build()
return _commentArrowDown!!
}
private var _commentArrowDown: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,613 | icons | MIT License |
booking-service/presentation/web/src/test/kotlin/eu/grand/hotel/bookingservice/BookingServiceApiTestEnvironment.kt | dzappold | 657,489,140 | false | {"Kotlin": 35867} | package eu.grand.hotel.bookingservice
import eu.grand.hotel.bookingservice.BookingServiceApiSettings.BOOKING_POLICY_SERVICE_URL
import eu.grand.hotel.bookingservice.BookingServiceApiSettings.HOTEL_SERVICE_URL
import org.http4k.config.Environment
import org.http4k.core.Uri
val BookingServiceApiTestEnvironment =
Environment.defaults(
BOOKING_POLICY_SERVICE_URL of Uri.of("http://booking-policy"),
HOTEL_SERVICE_URL of Uri.of("http://hotel")
)
| 0 | Kotlin | 0 | 0 | a9ee7005ed2bf221f9444464a5782f8d78152392 | 469 | CorporateHotelBooking | Apache License 2.0 |
aoc_2023/src/test/kotlin/problems/day20/PulsePropagationTest.kt | Cavitedev | 725,682,393 | false | {"Kotlin": 228779} | package problems.day20
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import problems.utils.readInput
class PulsePropagationTest {
lateinit var pulsePropagation: PulsePropagation
@BeforeEach
fun setUp() {
pulsePropagation = PulsePropagation(readInput(("day20/it1")))
}
@Test
fun getModules() {
assertEquals(5, pulsePropagation.modules.size)
val inv = pulsePropagation.modules["inv"] as ConjuctionModule
assertEquals(Signal.LOW, inv.dependantModules.first().lastSignal)
}
@Test
fun pulseButton() {
val pulseResult = pulsePropagation.pulseButton()
assertEquals(8, pulseResult.lowPulses)
assertEquals(4, pulseResult.highPulses)
}
@Test
fun pulseButton1000() {
val pulseResult = pulsePropagation.pulseButton(1000L)
assertEquals(8000, pulseResult.lowPulses)
assertEquals(4000, pulseResult.highPulses)
}
}
| 0 | Kotlin | 0 | 1 | aa7af2d5aa0eb30df4563c513956ed41f18791d5 | 1,022 | advent-of-code-2023 | MIT License |
src/main/kotlin/net/backupcup/hexed/statusEffects/SmoulderingStatusEffect.kt | EndLone | 753,337,271 | false | {"Kotlin": 68642, "Java": 6223} | package net.backupcup.hexed.statusEffects
import net.minecraft.entity.effect.StatusEffect
import net.minecraft.entity.effect.StatusEffectCategory
class SmoulderingStatusEffect(category: StatusEffectCategory?, color: Int) : StatusEffect(category, color) {
} | 0 | Kotlin | 0 | 0 | a79e4392fce488d5fb38a0cf27ce6ed575a1c514 | 258 | hexed | Creative Commons Zero v1.0 Universal |
src/main/kotlin/me/nobaboy/nobaaddons/commands/subcommands/SSClearCommand.kt | nobaboy | 778,328,806 | false | {"Kotlin": 147079} | package me.nobaboy.nobaaddons.commands.subcommands
import me.nobaboy.nobaaddons.NobaAddons
import me.nobaboy.nobaaddons.commands.ISubCommand
import me.nobaboy.nobaaddons.features.dungeons.data.SSFile
import me.nobaboy.nobaaddons.util.ChatUtils
import java.io.IOException
class SSClearCommand : ISubCommand {
override val name: String = "ssClearTimes"
override val aliases: List<String> = listOf("ssClear")
override fun run(args: Array<String>) {
val times = SSFile.times
if (times.isEmpty()) {
ChatUtils.addMessage("You have not completed a single Simon Says device in the Catacombs Floor 7.")
return
}
try {
ChatUtils.addMessage("Successfully cleared SS Times.")
SSFile.personalBest = null
SSFile.times.clear()
SSFile.save()
} catch (ex: IOException) {
NobaAddons.LOGGER.error("Failed to modify simon-says-times.json", ex)
}
}
} | 0 | Kotlin | 0 | 1 | cebdef91337207fe8289c978e2cc878fc3bfd63f | 983 | NobaAddons-old | The Unlicense |
tokenization/src/main/java/com/paysafe/android/tokenization/domain/repository/ThreeDSecureAuthRepository.kt | paysafegroup | 739,327,660 | false | {"Kotlin": 630913, "Shell": 912} | package com.paysafe.android.tokenization.domain.repository
import com.paysafe.android.core.data.entity.PSResult
import com.paysafe.android.tokenization.domain.model.threedsauth.FinalizeAuthResult
import com.paysafe.android.tokenization.domain.model.threedsauth.ThreeDSAuth
import com.paysafe.android.tokenization.domain.model.threedsauth.ThreeDSAuthParams
internal interface ThreeDSecureAuthRepository {
suspend fun authenticate3DS(threeDSAuthParams: ThreeDSAuthParams, accountId: String): PSResult<ThreeDSAuth>
suspend fun finalize3DSAuthentication(paymentHandleId: String, authenticationId: String): PSResult<FinalizeAuthResult>
} | 0 | Kotlin | 0 | 0 | 56acf1d166317d7ddfb5e3eac5e61485c63e6a8a | 643 | paysafe_sdk_android_payments_api | MIT License |
src/main/kotlin/com/github/shiverawe/cheque/nalogru/NalogRu.kt | vladimirshefer | 123,981,549 | false | null | package com.github.shiverawe.cheque.nalogru
import com.github.shiverawe.cheque.entities.ChequeCredentials
import org.apache.commons.io.IOUtils
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClients
import java.io.OutputStreamWriter
import java.net.HttpURLConnection
import java.net.URL
import javax.xml.bind.DatatypeConverter
object NalogRu {
val api = "https://proverkacheka.nalog.ru:9999"
private val DEFAULT_USER_AGENT = "" +
"Mozilla/5.0 (X11; Linux x86_64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/33.0.1750.152 " +
"Safari/537.36"
private fun executeGet(uri: String): String {
val req = HttpGet(uri)
req.setHeader("User-Agent", DEFAULT_USER_AGENT)
HttpClients.createDefault().use { client ->
client.execute(req).use { response ->
val inputStream = response.entity.content
return IOUtils.toString(inputStream)
}
}
}
fun url(cc: ChequeCredentials): String {
val url = """${api}/v1/inns/*/kkts/*/fss/${cc.fn}/tickets/${cc.fd}?fiscalSign=${cc.fp}&sendToEmail=no"""
val obj = URL(url)
val conn = obj.openConnection() as HttpURLConnection
conn.doOutput = true
conn.requestMethod = "POST"
val credentials = "${Credentials.username}:${Credentials.pass}"
val authtoken = "Basic " + DatatypeConverter
.printBase64Binary(credentials.toByteArray())
//println(authtoken)
conn.setRequestProperty("Content-Type", "application/json")
conn.setRequestProperty("Device-Id", "")
conn.setRequestProperty("Accept-Encoding", "gzip")
conn.setRequestProperty("Connection", "Keep-Alive")
conn.setRequestProperty("Device-OS", "Android 5.1")
conn.setRequestProperty("Version", "2")
conn.setRequestProperty("ClientVersion", "1.4.4.1")
conn.setRequestProperty("UserAgent", "okhttp/3.0.1")
conn.setRequestProperty("Authorization", authtoken)
val data = """{"format":"json","pattern":"#"}"""
conn.outputStream.use {
OutputStreamWriter(it).use {
it.write(data)
}
}
val response = conn.inputStream.use {
it.bufferedReader().use {
it.lines()
}
}
print(response)
return response.toString()
}
} | 0 | Kotlin | 0 | 0 | ad6a0cedde62d3412e96dd8fa26b358600d716a7 | 2,479 | Cheque | Apache License 2.0 |
src/main/kotlin/com/team2898/robot/commands/ActivateIntake.kt | TheFlyingHedgehogs | 587,113,427 | false | null | package com.team2898.robot.commands
import com.team2898.robot.subsystems.Intake
import edu.wpi.first.wpilibj.Timer
import edu.wpi.first.wpilibj2.command.CommandBase
/**
* Runs intake forwards or backwards to take a game peice or deposit it
* @author Ori
*/
class ActivateIntake(private val mode: RunningIntakes) : CommandBase() {
private val timer = Timer()
override fun initialize() {
if (mode == RunningIntakes.RUNINTAKE) {
Intake.runIntake()
}
else if (mode == RunningIntakes.RUNOUTTAKE) {
Intake.runOuttake()
}
timer.start()
}
override fun isFinished(): Boolean {
return timer.hasElapsed(0.75)
}
override fun end(interrupted: Boolean) {
Intake.stopIntake()
}
enum class RunningIntakes {
RUNINTAKE,
RUNOUTTAKE
}
} | 0 | Kotlin | 0 | 1 | 0cc74fcd5d88ad5f171fea83981dbc64ac57d88c | 857 | 2898-2023-charged-up | Apache License 2.0 |
app/src/main/java/reach52/marketplace/community/fragments/insurance/PolicyOwnerDetailsFragment.kt | reach52 | 422,514,975 | false | {"Kotlin": 1436380, "Java": 18303} | package reach52.marketplace.community.fragments.insurance
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import arrow.core.Option
import com.jakewharton.rxbinding3.view.clicks
import reach52.marketplace.community.R
import reach52.marketplace.community.models.insurance.InsurancePurchase
import reach52.marketplace.community.persistence.DispergoDatabase
import reach52.marketplace.community.viewmodels.InsuranceViewModel
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.fragment_policy_owner_details.view.*
import org.threeten.bp.format.DateTimeFormatter
@Suppress("UNCHECKED_CAST")
class PolicyOwnerDetailsFragment : Fragment() {
private val disposables = CompositeDisposable()
private val insuranceViewModelGetter by lazy {
Option.fromNullable(activity).map {
ViewModelProvider(it)[InsuranceViewModel::class.java]
}
}
private val insurancePurchase by lazy {
InsurancePurchase(DispergoDatabase.getInstance(context!!))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menu.findItem(R.id.app_bar_search).isVisible = false
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_policy_owner_details, container, false).apply {
insuranceViewModelGetter.map { model ->
if(arguments!=null){
val policyOwner = model.policyOwnerDocumentId.value?.let { insurancePurchase.get(it) }
val policyInsured = policyOwner?.insured
when(arguments?.get("data")){
"policyOwner" -> {
dataName.text = policyOwner?.policyOwnerFullName
addressDisplay.text = policyOwner?.address
emailDisplay.text = policyOwner?.email
contactDisplay.text = policyOwner?.contact
civilStatusDisplay.text = policyOwner?.civilStatus
genderDisplay.text = policyOwner?.gender
dateOfBirthDisplay.text = policyOwner?.dateOfBirth?.format(DateTimeFormatter.ofPattern("MMM dd, yyyy"))
relationshipText.visibility = View.INVISIBLE
relationshipDisplay.visibility = View.INVISIBLE
}
"insured" -> {
dataName.text = policyInsured?.display
addressDisplay.text = policyInsured?.address
emailDisplay.text = policyInsured?.email
contactDisplay.text = policyInsured?.contact
civilStatusDisplay.text = policyInsured?.civilStatus
genderDisplay.text = policyInsured?.gender
dateOfBirthDisplay.text = policyInsured?.dateOfBirth?.format(DateTimeFormatter.ofPattern("MMM dd, yyyy"))
relationshipDisplay.text = policyInsured?.relationship
}
}
}
when((activity as AppCompatActivity).supportActionBar?.title){
context.getString(R.string.insured_details) -> {
model.selectedPolicyInsured.observe(viewLifecycleOwner, Observer {
dataName.text = it.display
addressDisplay.text = it.address
emailDisplay.text = it.email
contactDisplay.text = it.contact
civilStatusDisplay.text = it.civilStatus
genderDisplay.text = it.gender
dateOfBirthDisplay.text = it.dateOfBirth.format(DateTimeFormatter.ofPattern("MMM dd, yyyy"))
relationshipDisplay.text = it.relationship
when(it.relationship) {
"" -> {
relationshipDisplay.text = context.getString(R.string.self)
}
}
})
}
context.getString(R.string.policy_owner_details) -> {
relationshipText.visibility = View.GONE
relationshipDisplay.visibility = View.GONE
model.selectedPolicyOwnerFullName.observe(viewLifecycleOwner, Observer {
dataName.text = it
})
model.selectedPolicyOwnerAddress.observe(viewLifecycleOwner, Observer {
addressDisplay.text = it
})
model.selectedPolicyOwnerEmail.observe(viewLifecycleOwner, Observer {
emailDisplay.text = it
})
model.selectedPolicyOwnerContact.observe(viewLifecycleOwner, Observer {
contactDisplay.text = it
})
model.selectedPolicyOwnerCivilStatus.observe(viewLifecycleOwner, Observer {
civilStatusDisplay.text = it
})
model.selectedPolicyOwnerGender.observe(viewLifecycleOwner, Observer {
genderDisplay.text = it
})
model.selectedPolicyOwnerDateOfBirth.observe(viewLifecycleOwner, Observer {
dateOfBirthDisplay.text = it.format(DateTimeFormatter.ofPattern("MMM dd, yyyy"))
})
}
}
}
disposables.add(goBackButton.clicks().subscribe{
parentFragmentManager.popBackStack()
})
}
}
} | 0 | Kotlin | 0 | 0 | 629c52368d06f978f19238d0bd865f4ef84c23d8 | 6,748 | Marketplace-Community-Edition | MIT License |
composeApp/src/androidMain/kotlin/UCViewModel.kt | max-potapov | 808,783,679 | false | {"Kotlin": 7748} | import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.usercentrics.sdk.BannerSettings
import com.usercentrics.sdk.SecondLayerStyleSettings
import com.usercentrics.sdk.Usercentrics
import com.usercentrics.sdk.UsercentricsBanner
import com.usercentrics.sdk.UsercentricsConsentUserResponse
import com.usercentrics.sdk.UsercentricsServiceConsent
import java.lang.ref.WeakReference
class UCViewModel(context: Context) : ViewModel() {
val score = MutableLiveData("0")
val isReady = MutableLiveData(false)
private var banner: UsercentricsBanner? = null
private val contextRef: WeakReference<Context> = WeakReference(context)
private val context: Context?
get() = contextRef.get()
init {
Usercentrics.isReady(onSuccess = { status ->
if (!status.shouldCollectConsent) {
applyConsent(status.consents)
}
isReady.value = true
}, onFailure = { error ->
isReady.value = false
// TODO: Handle error
error.printStackTrace()
})
}
fun update() {
val settings = BannerSettings(
secondLayerStyleSettings = SecondLayerStyleSettings(
showCloseButton = true,
)
)
banner = context?.let { context ->
UsercentricsBanner(context, settings).also { banner ->
banner.showSecondLayer(
callback = ::handleUserResponse
)
}
}
}
private fun handleUserResponse(userResponse: UsercentricsConsentUserResponse?) {
userResponse ?: return
applyConsent(userResponse.consents)
}
private fun applyConsent(consents: List<UsercentricsServiceConsent>) {
// TODO: apply consent
val enabledTemplateIDs = consents.filter { it.status }.map { it.templateId }
calculateScore(enabledTemplateIDs)
}
private fun calculateScore(enabledTemplateIDs: List<String>) {
val data = Usercentrics.instance.getCMPData()
val enabledServices = data.services.filter { enabledTemplateIDs.contains(it.templateId) }
val services: List<UCService> = enabledServices.map { UCService(it) }
services.sumOf { it.cost }.toString().also { score.value = it }
services.forEach { service ->
println("${service.name} = ${service.cost}")
}
}
}
| 0 | Kotlin | 0 | 0 | 7680912d4f5da3d338b987b1cbbf515a45ace3ea | 2,459 | uc-kmp | Apache License 2.0 |
app/src/main/java/com/example/news/home/presentation/HomeScreen.kt | info-kareemmohamed | 865,667,916 | false | {"Kotlin": 62474} | package com.example.news.home.presentation
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.layout.Column
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.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.paging.compose.LazyPagingItems
import com.example.news.R
import com.example.news.core.presentation.common.SearchBar
import com.example.news.core.presentation.navgraph.Route
import com.example.news.core.util.Dimens.MediumPadding_24
import com.example.news.core.domain.model.Article
import com.example.news.core.presentation.common.ArticlesList
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HomeScreen(articles: LazyPagingItems<Article>, navigate:(String) -> Unit) {
val titles by remember {
derivedStateOf {
if (articles.itemCount > 10) {
articles.itemSnapshotList.items
.slice(IntRange(start = 0, endInclusive = 9))
.joinToString(separator = " \uD83D\uDFE5 ") { it.title }
} else {
""
}
}
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(top = MediumPadding_24)
.statusBarsPadding()
) {
Image(
painter = painterResource(id = R.drawable.ic_logo),
contentDescription = null,
modifier = Modifier
.width(150.dp)
.height(30.dp)
.padding(horizontal = MediumPadding_24)
)
Spacer(modifier = Modifier.height(MediumPadding_24))
SearchBar(
modifier = Modifier
.padding(horizontal = MediumPadding_24)
.fillMaxWidth(),
text = "",
readOnly = true,
onValueChange = {},
onSearch = {},
onClick = {
navigate(Route.SearchScreen.route)
}
)
Spacer(modifier = Modifier.height(MediumPadding_24))
Text(
text = titles, modifier = Modifier
.fillMaxWidth()
.padding(start = MediumPadding_24)
.basicMarquee(), fontSize = 12.sp,
color = colorResource(id = R.color.placeholder)
)
Spacer(modifier = Modifier.height(MediumPadding_24))
ArticlesList(
modifier = Modifier.padding(horizontal = MediumPadding_24),
articles = articles,
onClick = {
//TODO: Navigate to Details Screen
}
)
}
} | 0 | Kotlin | 0 | 0 | cf8106fba62a80c016bd54b684c972813b444238 | 3,339 | News-App-Jetpack-Compose | MIT License |
identity/src/main/java/com/stripe/android/identity/utils/PhotoTaker.kt | stripe | 6,926,049 | false | null | package com.stripe.android.identity.utils
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
/**
* A class to take a photo through camera.
*/
internal class PhotoTaker(
activityResultCaller: ActivityResultCaller
) {
private var newPhotoTakenUri: Uri? = null
private var onPhotoTaken: ((Uri) -> Unit)? = null
private val takePhotoLauncher: ActivityResultLauncher<Intent> =
activityResultCaller.registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
requireNotNull(onPhotoTaken) {
"onPhotoTaken callback is not set."
}(
requireNotNull(newPhotoTakenUri) {
"newPhotoTakeUri is still null after a photo is taken."
}
)
}
/**
* Starts an Activity to take a photo with camera, saves it locally to the app's internal file
* storage and posts its Uri to [onPhotoTaken] when finished.
*/
// TODO(ccen): add error/exception
internal fun takePhoto(context: Context, onPhotoTaken: (Uri) -> Unit) {
this.onPhotoTaken = onPhotoTaken
takePhotoLauncher.launch(
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
// Ensure that there's a camera activity to handle the intent
takePictureIntent.resolveActivity(context.packageManager).also {
createInternalFileUri(context).also {
newPhotoTakenUri = it.contentUri
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, newPhotoTakenUri)
}
}
}
)
}
}
| 64 | Kotlin | 522 | 935 | bec4fc5f45b5401a98a310f7ebe5d383693936ea | 1,937 | stripe-android | MIT License |
src/main/kotlin/abc/007-b.kt | kirimin | 197,707,422 | false | null | package abc
import java.util.*
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
val a = sc.next()
println(problem007b(a))
}
fun problem007b(a: String): String {
if (a == "a"){
return "-1"
}
return "a"
} | 0 | Kotlin | 1 | 5 | 87f20b4aa2031c130867c546dd5533890f1978ee | 250 | AtCoderLog | The Unlicense |
videoplayermanager/src/main/java/com/hb/videoplayermanager/EncryptionConfig.kt | hbdevmdm | 369,506,633 | false | null | package com.hb.videoplayermanager
import java.io.Serializable
data class EncryptionConfig(val algorithm: String,
val key: String) :Serializable
| 0 | Kotlin | 0 | 0 | 91b189452bfc80365b0dfb6eafb88f68c6fc31ab | 174 | VideoPlayerManager | Apache License 2.0 |
kotlin-typescript/src/main/generated/typescript/NamespaceImport.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
package typescript
sealed external interface NamespaceImport : NamedDeclaration, Union.NamespaceImport_ {
override val kind: SyntaxKind.NamespaceImport
override val parent: ImportClause
override val name: Identifier
}
| 12 | Kotlin | 145 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 276 | kotlin-wrappers | Apache License 2.0 |
src/test/kotlin/logic/TestWorld.kt | jpgagnebmc | 625,129,199 | false | null | package logic
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
public class TestWorld {
@Test
fun singleVar(): Unit {
Logic.parse("A").world.print().apply {
print()
assertEquals(2, rowsCount())
assertEquals(2, columnsCount())
}
}
@Test
fun twoVar(): Unit {
Logic.parse("A =⇒ B").print().world.apply {
print()
assertEquals(4, rowsCount())
assertEquals(3, columnsCount())
}
}
@Test
fun invalid() {
listOf( //invalid
"A ∧ ¬A"
).onEach {
LogicParser(it).model().apply {
world.print()
assertFalse(valid)
}
}
}
} | 0 | Kotlin | 0 | 0 | 087bcc0f908fb71da2e3f0e03fe8066f44797643 | 779 | homework | Apache License 2.0 |
app/src/main/kotlin/com/sk/android/letswatch/movies/TopRatedMoviesUseCase.kt | skhanzada | 147,043,367 | false | null | package com.sk.android.letswatch.movies
import com.sk.android.letswatch.data.source.MovieRepository
import com.sk.android.letswatch.data.source.remote.MovieWebServiceRequest
import com.sk.android.letswatch.data.source.remote.MovieWebServiceResponse
import com.sk.android.letswatch.testing.OpenForTesting
import com.sk.android.letswatch.vo.Resource
import javax.inject.Inject
@OpenForTesting
class TopRatedMoviesUseCase @Inject constructor(private val movieRepository: MovieRepository) :
UseCase<MovieWebServiceRequest, MovieWebServiceResponse>() {
override suspend fun run(request: MovieWebServiceRequest): Resource<MovieWebServiceResponse> {
return movieRepository.getTopRatedMovies(request.page)
}
} | 0 | Kotlin | 0 | 0 | 17a6f75cd7b681c620ca9178fc6751ffc83605db | 724 | letswatch | MIT License |
core/domain/src/main/java/komu/seki/domain/repository/PlaybackRepository.kt | shrimqy | 827,172,253 | false | {"Kotlin": 238692} | package komu.seki.domain.repository
import komu.seki.domain.models.PlaybackData
import kotlinx.coroutines.flow.StateFlow
interface PlaybackRepository {
fun updatePlaybackData(data: PlaybackData)
fun readPlaybackData(): StateFlow<PlaybackData?>
} | 1 | Kotlin | 0 | 45 | b4601316ca792a7247ca08fa2a9af43761875a85 | 257 | Sekia | Apache License 2.0 |
app/src/main/java/com/lukieoo/rickandmorty/MainActivity.kt | Lukieoo | 323,849,579 | false | null | package com.lukieoo.rickandmorty
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityOptionsCompat
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.lukieoo.rickandmorty.adapters.AdapterCharacters
import com.lukieoo.rickandmorty.databinding.ActivityMainBinding
import com.lukieoo.rickandmorty.models.characters.ApiDataModel
import com.lukieoo.rickandmorty.models.characters.Result
import com.lukieoo.rickandmorty.util.AdapterOnClickListener
import com.lukieoo.rickandmorty.util.ProgressStatus
import com.lukieoo.rickandmorty.viewModel.CharacterViewModel
import dagger.hilt.android.AndroidEntryPoint
import java.util.*
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity(), ProgressStatus {
@Inject
lateinit var adapterCharacters: AdapterCharacters
private val characterViewModel: CharacterViewModel by viewModels()
private lateinit var binding: ActivityMainBinding
private var isEnd = false
private var page = 1
private var timer: Timer? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setContentView with viewBinding
initViewBinding()
// init Adapter for recyclerView
initRecyclerView()
// set refresh event
setProgressStatus()
// set listener for pagination per 20
setRecyclerViewPagination()
// init view model observer for data
initViewModel()
}
private fun setProgressStatus() {
showProgress()
binding.refreshLayout.setOnRefreshListener {
page = 1
adapterCharacters.clearCharacters()
characterViewModel.getCharacterByPage(page)
}
}
private fun setRecyclerViewPagination() {
isEnd = false
binding.charactersList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (!recyclerView.canScrollVertically(1)) {
if (!isEnd) {
isEnd = true
if (adapterCharacters.itemCount > 0) {
// showProgressBar()
loadMoreCharacters()
showProgress()
}
}
}
}
})
}
private fun loadMoreCharacters() {
page++
characterViewModel.getCharacterByPage(page)
}
private fun initViewBinding() {
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
setSupportActionBar(binding.toolbar)
}
private fun initViewModel() {
characterViewModel.observeCharacters().observe(this, {
if (it != null) {
adapterCharacters.addCharacters(it.results)
checkIsLastPage(it)
updateView(it)
binding.error.visibility = View.GONE
} else {
binding.error.visibility = View.VISIBLE
}
hideProgress()
})
}
private fun updateView(it: ApiDataModel) {
binding.numberCharacters.text = "${adapterCharacters.itemCount}/${it.info.count}"
}
private fun checkIsLastPage(it: ApiDataModel) {
timer = Timer()
timer!!.schedule(object : TimerTask() {
override fun run() {
isEnd = page == it.info.pages
}
}, 600)
}
private fun initRecyclerView() {
adapterCharacters.setAdapterOnClickListener(object : AdapterOnClickListener {
override fun onClick(result: Result, imageView: ImageView) {
val intent = Intent(application.applicationContext, DetailActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
val gson = Gson()
intent.putExtra("characterDetails", gson.toJson(result))
val bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
this@MainActivity,
imageView,
"avatar"
)
startActivity(intent, bundle.toBundle())
}
})
binding.charactersList.adapter = adapterCharacters
}
override fun hideProgress() {
binding.refreshLayout.isRefreshing = false
}
override fun showProgress() {
binding.refreshLayout.isRefreshing = true
}
} | 0 | Kotlin | 0 | 0 | eba16653ae59dea2977e58b509055739e37ec991 | 4,839 | RickAndMorty | MIT License |
src/main/kotlin/com/github/iguissouma/nxconsole/actions/NxCliActionGroup.kt | iguissouma | 297,120,009 | false | null | package com.github.iguissouma.nxconsole.actions
import com.github.iguissouma.nxconsole.NxIcons
import com.github.iguissouma.nxconsole.cli.config.NxConfigProvider
import com.github.iguissouma.nxconsole.cli.config.NxProject
import com.github.iguissouma.nxconsole.cli.config.WorkspaceType
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.actionSystem.UpdateInBackground
import java.util.*
class NxCliActionGroup : ActionGroup(), UpdateInBackground {
override fun update(e: AnActionEvent) {
val project = e.getData(LangDataKeys.PROJECT) ?: return
val file = e.getData(LangDataKeys.VIRTUAL_FILE) ?: return
val nxWorkspaceType = NxConfigProvider.getNxWorkspaceType(project, file)
if (nxWorkspaceType == WorkspaceType.UNKNOWN) {
e.presentation.isEnabledAndVisible = false
return
}
val label = nxWorkspaceType.label().lowercase().capitalized()
e.presentation.text = "$label Task (Ui)..."
e.presentation.description = "$label Task (Ui)..."
e.presentation.icon =
if (nxWorkspaceType == WorkspaceType.ANGULAR) NxIcons.ANGULAR
else NxIcons.NRWL_ICON
}
override fun getChildren(event: AnActionEvent?): Array<AnAction> {
val project = event?.project ?: return emptyArray()
val virtualFile = event.getData(LangDataKeys.VIRTUAL_FILE) ?: project.baseDir
val nxConfig = NxConfigProvider.getNxConfig(project, virtualFile) ?: return emptyArray()
return listOf(
// "Generate",
// "Run",
"Build",
"Serve",
"Test",
"E2e",
"Lint"
).map { command ->
object : ActionGroup(command, true) {
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
return nxConfig.projects.filter { it.architect.containsKey(command.lowercase(Locale.getDefault())) }.map {
NxCliAction(
command.lowercase(Locale.getDefault()),
it.name,
it.architect[command.lowercase(Locale.getDefault())]!!,
virtualFile,
it.name,
it.name,
if (it.type == NxProject.AngularProjectType.APPLICATION) NxIcons.NX_APP_FOLDER
else NxIcons.NX_LIB_FOLDER
)
}.toTypedArray()
}
}
}.toTypedArray()
}
}
fun WorkspaceType.label(): String {
return if (this == WorkspaceType.ANGULAR) WorkspaceType.ANGULAR.name else WorkspaceType.NX.name
}
| 33 | Kotlin | 9 | 41 | 1c796ffc986db407f558b5e17dff75b948f346b2 | 2,902 | nx-console-idea-plugin | Apache License 2.0 |
examples/src/org/nilsr/kotlin/examples/2Classes.kt | NilsRenaud | 108,672,219 | false | {"JavaScript": 179289, "CSS": 76509, "HTML": 37267} | package org.nilsr.kotlin.examples
import javax.naming.OperationNotSupportedException
/**
* Shows :
* - Data class definition
* - Data class fields definition using var/val
* - Data class auto generated methods
* - Operator overloads
* - Destructuring declaration
* - Data class components auto-definition
* - Class definition
* - Constructor definition
* - Init method
* - public/private fields
* - Specific getters and setters
* - Lazy evaluation
* - Enums
* - Java interoperability
*/
fun main(args : Array<String>) {
val rect = Rectangle(1, 2)
val rect2 = Rectangle(1, 2)
// "rect.length = 1" does not compile
println("${rect.length}, ${rect.width}")
println(rect == rect2)
val rectMut = MutableRectangle(1, 2)
rectMut.length = 4
val (width, length) = rectMut
println("${rectMut.component1()} = $width, ${rectMut.component2()} = $length")
// Example of an empty class instantiation
val empty = Empty()
// Example of a Customer Instantiation
var customer = Customer("Nils", "Test", "privateVal")
println("${customer.customerKey} : ${customer.firstName} ${customer.lastName}")
// customer.age & customer.privateField are not reachable.
customer = Customer("Nils")
println("$customer has name ? ${customer.hasAName}")
}
data class Rectangle(val width : Int, val length : Int)
data class MutableRectangle(var width : Int, var length : Int)
class Empty
class Customer(val firstName: String, val lastName: String?, privateField: String) {
val customerKey = lastName?.toUpperCase()
private val age : Int
constructor(firstname : String) : this(firstname, null, "secret"){
//Some Stuff
}
init {
age = 0
println("$customerKey : $privateField")
}
var hasAName: Boolean
get() = this.lastName == null
set(value) {
throw OperationNotSupportedException()
}
val lazyField : String by lazy { println("should be printed only once"); "lazyValue" }
}
enum class Color(val red : Int, val green : Int, val blue : Int){
RED(255, 0, 0),
GREEN(0, 255, 0),
BLUE(0, 0, 255)
}
enum class ProtocolState {
WAITING {
override fun signal() = TALKING
},
TALKING {
override fun signal() = WAITING
};
abstract fun signal(): ProtocolState
} | 0 | JavaScript | 0 | 0 | b01f174774b85b1312c665539c9ec06b2ff46bbb | 2,351 | kotlin-presentation | MIT License |
codespace/src/main/java/coder/apps/space/library/extension/Theme.kt | coderspacedev | 866,955,067 | false | {"Kotlin": 27170} | package coder.apps.space.library.extension
import android.content.*
import androidx.appcompat.app.*
import coder.apps.space.library.helper.*
fun Context.themeToggleMode() {
when (TinyDB(this).getInt(THEME, 3)) {
1 -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
2 -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
else -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
} | 0 | Kotlin | 0 | 0 | 0ba4ef0f29586a2bf3865c8dcf11fc4faf4fe36f | 492 | codespace | The Unlicense |
thumbprint/src/main/java/com/thumbtack/thumbprint/views/radiobutton/ThumbprintRadioButton.kt | thumbtack | 389,767,985 | false | null | package com.thumbtack.thumbprint.views.radiobutton
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.accessibility.AccessibilityNodeInfo
import androidx.appcompat.widget.AppCompatRadioButton
import androidx.core.content.ContextCompat
import androidx.core.widget.CompoundButtonCompat
import com.thumbtack.thumbprint.R
import com.thumbtack.thumbprint.utilities.getThumbprintFont
/**
* Simple Thumbprint radio button--just button and text--that supports error-state styling.
*/
class ThumbprintRadioButton(context: Context, attrs: AttributeSet? = null) :
AppCompatRadioButton(context, attrs) {
private val defaultTextColors: ColorStateList? = textColors
private val defaultButtonTintList: ColorStateList? = buttonTintList
private val defaultButtonDrawable: Drawable? = CompoundButtonCompat.getButtonDrawable(this)
private val errorButtonDrawable: Drawable?
private val errorTextColor: Int
init {
// Stash the button drawable and text color for the error attribute.
context.theme.obtainStyledAttributes(
R.style.Thumbprint_RadioButton_Error,
errorStyleAttributes
).apply {
try {
errorButtonDrawable =
defaultButtonDrawable?.constantState?.newDrawable()?.mutate()?.apply {
setTintList(
ColorStateList.valueOf(
getColor(
errorStyleAttributes.indexOf(android.R.attr.buttonTint),
ContextCompat.getColor(context, R.color.tp_red)
)
)
)
}
errorTextColor = getColor(
errorStyleAttributes.indexOf(android.R.attr.textColor),
ContextCompat.getColor(context, R.color.tp_red)
)
} finally {
recycle()
}
}
// Apply the isError attribute if set
applyIsErrorAttribute(context, attrs)
// Apply text styling
applyTextStyling(context, attrs)
}
/**
* Indicates whether the button should be rendered as being in an error state. The button
* will still be enabled, and can therefore be checked/unchecked, but its appearance
* will indicate that there is an error condition, according to the standard Thumbprint
* design. If the button is also disabled, then the styling for the disabled state will
* take precedence.
*/
var isError: Boolean = false
set(value) {
field = value
updateForError(value)
}
/**
* Enables or disables the radio button, overriding the [isError] setting as well.
* @see [AppCompatRadioButton.setEnabled].
*/
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
updateForError(isError)
}
/**
* If [isError] is true, this will call [AccessibilityNodeInfo.setContentDescription]
* with the phrase "Error. " + contentDescription|text to indicate that this
* [ThumbprintRadioButton] is in an error state. That way, it will be made clear to
* Accessibility Services like screen readers.
*/
override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo?) {
super.onInitializeAccessibilityNodeInfo(info)
info?.apply {
if (isError) {
this.contentDescription =
context.getString(R.string.compound_button_error_utterance)
.plus(
contentDescription.takeUnless {
it.isNullOrBlank()
} ?: text
)
}
}
}
private fun applyIsErrorAttribute(context: Context, attrs: AttributeSet?) {
context.theme.obtainStyledAttributes(
attrs,
R.styleable.ThumbprintCompoundButtonStyleable,
NO_DEFAULT_STYLE_ATTRIBUTE,
NO_DEFAULT_STYLE_RESOURCE
).apply {
try {
isError = getBoolean(R.styleable.ThumbprintCompoundButtonStyleable_isError, false)
} finally {
recycle()
}
}
}
private fun applyTextStyling(context: Context, attrs: AttributeSet?) {
context.theme.obtainStyledAttributes(
attrs,
textAttributes,
NO_DEFAULT_STYLE_ATTRIBUTE,
R.style.Thumbprint_RadioButton
).apply {
try {
setTextSize(
TypedValue.COMPLEX_UNIT_PX,
getDimension(
textAttributes.indexOf(android.R.attr.textSize),
resources.getDimension(R.dimen.body_1)
)
)
setLineSpacing(
getDimension(
textAttributes.indexOf(android.R.attr.lineSpacingExtra),
resources.getDimension(R.dimen.body_1_line_spacing_extra)
),
1f
)
typeface = getThumbprintFont(context, typeface)
if (isEnabled && !isError) {
setTextColor(
getColor(
textAttributes.indexOf(android.R.attr.textColor),
ContextCompat.getColor(context, R.color.tp_black)
)
)
}
} finally {
recycle()
}
}
}
private fun updateForError(isError: Boolean) {
if (isEnabled && isError) {
buttonDrawable = errorButtonDrawable
setTextColor(errorTextColor)
} else {
buttonDrawable = defaultButtonDrawable
if (defaultTextColors != null) {
setTextColor(defaultTextColors)
}
if (defaultButtonTintList != null) {
buttonTintList = defaultButtonTintList
}
}
}
companion object {
// Attribute arrays that are passed to obtainStyledAttributes() must be sorted,
// per documentation for that method.
private val errorStyleAttributes =
arrayOf(android.R.attr.textColor, android.R.attr.buttonTint).toIntArray().sortedArray()
private val textAttributes = arrayOf(
android.R.attr.textSize,
android.R.attr.lineSpacingExtra,
android.R.attr.textColor
).toIntArray().sortedArray()
const val NO_DEFAULT_STYLE_ATTRIBUTE = 0
const val NO_DEFAULT_STYLE_RESOURCE = 0
}
}
| 8 | Kotlin | 3 | 7 | 808cff8ee5891e212b6fa5fee7059de9c8228809 | 6,932 | thumbprint-android | Apache License 2.0 |
app/src/main/java/quizzo/app/ui/category/CategoryAdapter.kt | ibtesam123 | 271,865,081 | false | {"Kotlin": 99034} | package quizzo.app.ui.category
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.single_category_layout.view.*
import quizzo.app.R
import quizzo.app.util.capitalizeWords
import quizzo.app.util.category.Category
import java.util.*
class CategoryAdapter(
private val itemClicked: (category: String) -> Unit,
private val context: Context
) : ListAdapter<Category, CategoryAdapter.CategoryViewHolder>(CALLBACK) {
companion object {
val CALLBACK = object : DiffUtil.ItemCallback<Category>() {
override fun areItemsTheSame(oldItem: Category, newItem: Category): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: Category, newItem: Category): Boolean {
return oldItem == newItem
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
return CategoryViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.single_category_layout,
parent,
false
)
)
}
override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
val category = getItem(position)
holder.tvCategory.text = category.name.capitalizeWords()
holder.ivCategoryImage.setImageDrawable(context.getDrawable(category.imageId))
holder.layoutCategory.setOnClickListener {
itemClicked(category.name)
}
}
class CategoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvCategory = itemView.tv_category!!
val ivCategoryImage = itemView.iv_categoryImage!!
val layoutCategory = itemView.layout_category!!
}
} | 2 | Kotlin | 13 | 35 | d4449a7e7a97cfcd0e4a57f2ec7b300aeb9abcdf | 2,016 | Quizzo | MIT License |
Stock/common/data/src/main/java/tech/antee/stock/data/local/dao/StockDao.kt | AnteeOne | 494,828,095 | false | null | package tech.antee.stock.data.local.dao
import androidx.room.*
import kotlinx.coroutines.flow.Flow
import tech.antee.stock.data.local.entities.SubResultEntity
import tech.antee.stock.data.local.entities.SubStockEntity
@Dao
interface StockDao {
@Query("SELECT * FROM sub_stock_entities")
fun getAllSubStocks(): List<SubStockEntity>
@Query("SELECT * FROM sub_result_entities")
fun getAllSubResultsFlow(): Flow<List<SubResultEntity>>
@Query("SELECT * FROM sub_stock_entities WHERE stockId LIKE :id LIMIT 1")
fun getSubStockById(id: String): SubStockEntity
@Query("SELECT * FROM sub_stock_entities WHERE stockId LIKE :id LIMIT 1")
fun getSubStockFlowById(id: String): Flow<SubStockEntity?>
@Query("SELECT * FROM sub_result_entities WHERE stockId LIKE :id LIMIT 1")
fun getSubResultById(id: String): SubResultEntity
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertSubStocks(vararg subStocks: SubStockEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertSubResults(vararg subResults: SubResultEntity)
@Delete
fun deleteSubStocks(vararg subStocks: SubStockEntity)
@Delete
fun deleteSubResults(vararg subResults: SubResultEntity)
}
| 0 | Kotlin | 0 | 0 | 2e6bf1c3c58ea90501575668bd9349de76d94ef2 | 1,232 | stock | Apache License 2.0 |
src/main/kotlin/com/dude/dms/ui/components/dialogs/ChangelogDialog.kt | axelvondreden | 208,427,538 | false | null | package com.dude.dms.ui.components.dialogs
import com.dude.dms.brain.t
import com.dude.dms.utils.changelogService
import com.github.mvysny.karibudsl.v10.label
import com.github.mvysny.karibudsl.v10.textArea
class ChangelogDialog : DmsDialog(t("changelog"), 70, 70) {
init {
label("DMS Version: ${changelogService.currentVersion}")
changelogService.findAll().sortedBy { it.published }.reversed().forEach { changelog ->
textArea(changelog.tag) {
setWidthFull()
value = changelog.body
isReadOnly = true
}
}
}
}
| 46 | Kotlin | 1 | 3 | 418c7df3589b85c934f0da13642f14aa4c66a851 | 616 | dms | Apache License 2.0 |
source-code/starter-project/SideEffectHandlers/app/src/main/java/com/droidcon/tasktimer/db/TaskDao.kt | droidcon-academy | 784,702,823 | false | {"Kotlin": 65200} | package com.droidcon.tasktimer.db
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.droidcon.tasktimer.model.Task
import kotlinx.coroutines.flow.Flow
@Dao
interface TaskDao {
@Insert
suspend fun addTask(task: Task)
@Update
suspend fun updateTask(task: Task)
@Query("SELECT * FROM task")
fun getAllTasks(): Flow<List<Task>>
} | 0 | Kotlin | 0 | 0 | 8def1e91ce98f5ccd51c16ab35ff229a426c4f96 | 422 | android-cbc-side-effect-handlers-compose | Apache License 2.0 |
src/main/java/de/aiarena/community/AMTPClient.kt | Tahlaria | 326,987,259 | false | null | package de.aiarena.community
import java.io.BufferedReader
import java.io.Closeable
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.Socket
import java.util.*
import kotlin.collections.HashMap
import kotlin.system.exitProcess
class AMTPClient(host: String, port: Int, secret: String, private val broadcastCallback: (MessageFromServer,Boolean) -> Unit, private val debug: Boolean = false): Closeable, Runnable{
constructor(host: String, port: Int, secret: String, jcbc: JavaCompatibleBroadcastCallback, debug: Boolean = false)
: this(host, port, secret, jcbc::onMessage,debug)
private val socket : Socket
private val reader : BufferedReader
private val writer : PrintWriter
private val pendingCallbacks : HashMap<String,(MessageFromServer) -> Unit>
private var mySlot = -1
init{
socket = Socket(host,port)
reader = BufferedReader(InputStreamReader(socket.getInputStream()))
writer = PrintWriter(socket.getOutputStream())
pendingCallbacks = HashMap()
Thread(this).start()
send(
MessageToServer(
"CLAIM",
"AMTP/0.0",
hashMapOf(
"Secret" to secret,
"Role" to "Player"
)
)
)
}
override fun run() {
var currentMessage: MessageFromServer? = null
while(true){
try{
val line = reader.readLine()
?: break
if(debug){
println("> $line")
}
if(line == ""){
currentMessage?.let{
onMessageCompletion(it)
}
currentMessage = null
continue
}
when(currentMessage){
null -> {
currentMessage = MessageFromServer(line.toInt())
}
else -> {
currentMessage.headers[line.substring(0,line.indexOf(":"))] = line.substring(line.indexOf(":")+1,line.length).trim()
}
}
}catch(ex : Exception){
System.err.println("Exception: $ex")
ex.printStackTrace()
}
}
}
private fun onMessageCompletion(msg: MessageFromServer){
if(msg.code == 9){
println("Connection closed by Remote")
exitProcess(0)
}
if(msg.code == 5){
mySlot = msg.headers["Slot"]!!.toInt()
return
}
if(msg.code == 1){
var myActionRequired = false;
try {
myActionRequired = (msg.headers["ActionRequiredBy"] == "*" ) || ( msg.headers["ActionRequiredBy"]!!.toInt() == mySlot)
}catch(ex : Exception){}
broadcastCallback(msg,myActionRequired)
return
}
msg.headers["Identifier"]?.let{
id ->
pendingCallbacks[id]
?.let{
cb -> cb(msg)
pendingCallbacks.remove(id)
return
}
}
println("Warning: Ignored message:")
println(msg)
}
fun sendJC(message: MessageToServer, callback: JavaCompatibleMessageCallback? = null){
when(callback){
null -> send(message,null)
else -> send(message,callback::onResponse)
}
}
fun getMySlot() : Int{
return mySlot
}
fun send(message: MessageToServer, callback: ((MessageFromServer) -> Unit)? = null){
val key = UUID.randomUUID().toString()
callback?.let{
message.headers["Identifier"] = key
pendingCallbacks[key] = it
}
if(debug) {
message.debugLog()
}
writer.write(message.toString())
writer.flush()
}
override fun close() {
reader.close()
writer.close()
socket.close()
}
}
| 0 | Kotlin | 0 | 0 | 4edf4ad266f3e538cc5717793c7941dd4c61f9ab | 4,109 | Simple-AMTP-Client | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/example/cz2006ver2/HomePage/HomePage4.kt | kombucha7 | 483,281,978 | false | null | package com.example.cz2006ver2.HomePage
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.cz2006ver2.R
import kotlinx.android.synthetic.main.activity_home_page4.*
/**
* Class for HomePage4
* Page to delete tasks
*/
class HomePage4 : AppCompatActivity() {
/**
* Main Function of HomePage4
* Includes Back Button to return to previous page
* And confirm button to confirm task deletion
* @param savedInstanceState
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home_page4)
val elderUID = intent.getStringExtra("key").toString()
home4_confirmbutton.setOnClickListener{
val intent = Intent(this, HomePage5::class.java)
intent.putExtra("key", elderUID)
startActivity(intent)
}
home4_back_button_word.setOnClickListener {
val intent = Intent(this, HomePage1::class.java)
intent.putExtra("key", elderUID)
startActivity(intent)
}
}
} | 0 | Kotlin | 0 | 0 | d7c8a87db3681a2cd7132968958479d3d56e6c1d | 1,147 | CZ2006 | Apache License 2.0 |
app/src/main/java/rezaei/mohammad/ecoa/ui/MainActivity.kt | MohammadRezaei92 | 120,993,166 | false | null | package rezaei.mohammad.ecoa.ui
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.*
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.support.transition.TransitionManager
import android.support.v4.content.res.ResourcesCompat
import android.support.v4.view.ViewCompat
import android.support.v4.widget.NestedScrollView
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.StyleSpan
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.hsalf.smilerating.BaseRating
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import rezaei.mohammad.ecoa.EstimateCostAndTime
import rezaei.mohammad.ecoa.R
import rezaei.mohammad.ecoa.objects.Settings
import java.lang.StringBuilder
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.*
class MainActivity : AppCompatActivity() {
val typeface by lazy {
ResourcesCompat.getFont(this,R.font.iran_sans)
}
private var programmerLevel: Settings.ProgrammerLevel = Settings.ProgrammerLevel.Intern
private var appHardness: Settings.AppHardness = Settings.AppHardness.VerySimple
private var activities = 0
private var services = 0
private var graphic: Settings.Graphic = Settings.Graphic.None
private var needSource: Boolean = false
private var needSupport: Boolean = false
private val HoursOfDay = 8.0
private val DaysOfWeek = 5.0
private val WeeksOfMonth = 4.0
private lateinit var costAndTime: Pair<Long,Int>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.decorView.layoutDirection = View.LAYOUT_DIRECTION_RTL
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
supportActionBar?.title = ""
initAppbar()
initViews()
}
private fun initAppbar(){
val param = appBar.layoutParams
val screenX = resources.displayMetrics.widthPixels
val height = screenX.div(1.8f)
param.height = height.toInt()
appBar.layoutParams = param
scrollView.setOnScrollChangeListener { v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int ->
if(scrollView.canScrollVertically(-1)){
ViewCompat.setElevation(appBar,8f)
} else {
ViewCompat.setElevation(appBar,0f)
}
}
}
private fun initViews(){
checkboxSource.typeface = typeface
checkboxSupport.typeface = typeface
checkboxSource.setOnCheckedChangeListener { buttonView, isChecked ->
needSource = isChecked
showResult()
}
checkboxSupport.setOnCheckedChangeListener { buttonView, isChecked ->
needSupport = isChecked
showResult()
}
txtPrice.setDecimalFormat(DecimalFormat("###,###,###"))
txtPrice.setAnimationDuration(1000)
txtTime.setAnimationDuration(1000)
layTime.setOnClickListener {
TransitionManager.beginDelayedTransition(layResult)
if(layTimeDetail.visibility == View.VISIBLE) {
layTimeDetail.visibility = View.GONE
imgCollapse.setImageResource(R.drawable.arrow_down)
}
else {
layTimeDetail.visibility = View.VISIBLE
imgCollapse.setImageResource(R.drawable.arrow_up)
}
}
help.setOnClickListener {
AlertDialog.Builder(this)
.setView(R.layout.time_tip)
.setPositiveButton("خب") { dialog, _ ->
dialog.dismiss()
}
.show()
}
pickerActivites.setListener {
activities = it
showResult()
}
pickerServices.setListener {
services = it
showResult()
}
viewProgrammerLevel.setNameForSmile(BaseRating.TERRIBLE,"کارآموز")
viewProgrammerLevel.setNameForSmile(BaseRating.BAD,"مبتدی")
viewProgrammerLevel.setNameForSmile(BaseRating.OKAY,"نیمه حرفه ای")
viewProgrammerLevel.setNameForSmile(BaseRating.GOOD,"حرفه ای")
viewProgrammerLevel.setNameForSmile(BaseRating.GREAT,"فول استک")
viewProgrammerLevel.setTypeface(typeface)
viewProgrammerLevel.setSelectedSmile(BaseRating.TERRIBLE,false)
viewAppHardness.setNameForSmile(BaseRating.TERRIBLE,"خیلی ساده")
viewAppHardness.setNameForSmile(BaseRating.BAD,"ساده")
viewAppHardness.setNameForSmile(BaseRating.OKAY,"متوسط")
viewAppHardness.setNameForSmile(BaseRating.GOOD,"حدودا سخت")
viewAppHardness.setNameForSmile(BaseRating.GREAT,"سخت")
viewAppHardness.setTypeface(typeface)
viewAppHardness.setSelectedSmile(BaseRating.TERRIBLE,false)
viewGraphic.setNameForSmile(BaseRating.TERRIBLE,"بدون گرافیک")
viewGraphic.setNameForSmile(BaseRating.BAD,"مبتدی")
viewGraphic.setNameForSmile(BaseRating.OKAY,"قابل قبول")
viewGraphic.setNameForSmile(BaseRating.GOOD,"خوب")
viewGraphic.setNameForSmile(BaseRating.GREAT,"عالی")
viewGraphic.setTypeface(typeface)
viewGraphic.setSelectedSmile(BaseRating.TERRIBLE,false)
viewProgrammerLevel.setOnSmileySelectionListener { smiley, reselected ->
when(smiley){
BaseRating.TERRIBLE -> programmerLevel = Settings.ProgrammerLevel.Intern
BaseRating.BAD -> programmerLevel = Settings.ProgrammerLevel.Beginner
BaseRating.OKAY -> programmerLevel = Settings.ProgrammerLevel.SemiProfessional
BaseRating.GOOD -> programmerLevel = Settings.ProgrammerLevel.Professional
BaseRating.GREAT -> programmerLevel = Settings.ProgrammerLevel.FullStack
}
showResult()
}
viewAppHardness.setOnSmileySelectionListener { smiley, reselected ->
when(smiley){
BaseRating.TERRIBLE -> appHardness = Settings.AppHardness.VerySimple
BaseRating.BAD -> appHardness = Settings.AppHardness.Simple
BaseRating.OKAY -> appHardness = Settings.AppHardness.Medium
BaseRating.GOOD ->appHardness = Settings.AppHardness.SemiHard
BaseRating.GREAT -> appHardness = Settings.AppHardness.Hard
}
showResult()
}
viewGraphic.setOnSmileySelectionListener { smiley, reselected ->
when(smiley){
BaseRating.TERRIBLE -> graphic = Settings.Graphic.None
BaseRating.BAD -> graphic = Settings.Graphic.Beginner
BaseRating.OKAY -> graphic = Settings.Graphic.Acceptable
BaseRating.GOOD -> graphic = Settings.Graphic.Good
BaseRating.GREAT -> graphic = Settings.Graphic.Best
}
showResult()
}
showResult()
}
@SuppressLint("SetTextI18n")
private fun showResult(){
activities = pickerActivites.value
services = pickerServices.value
costAndTime = EstimateCostAndTime(programmerLevel
, appHardness
, graphic
, activities
, services
, needSource
, needSupport).getCostAndTime()
txtPrice.countAnimation(txtPrice.text.toString().filter { it.isDigit() }.toInt(),costAndTime.first.toInt())
txtTime.countAnimation(txtTime.text.toString().toInt(),costAndTime.second)
val month = Math.floor(costAndTime.second.div(HoursOfDay).div(DaysOfWeek).div(WeeksOfMonth))
val week = Math.floor((costAndTime.second.div(HoursOfDay).div(DaysOfWeek)).minus(month.times(WeeksOfMonth)))
val day = Math.floor((costAndTime.second.div(HoursOfDay)).minus(month.times(WeeksOfMonth).times(DaysOfWeek) + week.times(DaysOfWeek)))
txtTimeDetail.text = spanTimeText(month.toInt().toString(),"ماه و").append("\n" +
spanTimeText(week.toInt().toString(),"هفته و").append("\n" +
spanTimeText(day.toInt().toString(),"روز")))
}
private fun spanTimeText(time: String, text: String): SpannableStringBuilder {
val result = SpannableStringBuilder("$time $text")
result.setSpan(StyleSpan(Typeface.BOLD),
0, time.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
return result
}
private fun shareText(){
val result = StringBuilder()
result.appendln("نتیجه تخمین هزینه برای اپلیکیشن اندرویدی شما به شرح زیر است")
result.appendln("قیمت تقریبی: ${NumberFormat.getNumberInstance(Locale.US).format(costAndTime.first)} تومان")
result.appendln("زمان تقریبی: ${costAndTime.second} ساعت")
result.appendln("محاسبه بالا توسط فاکتورهای زیر انجام گرفته است")
result.appendln("سطح برنامه نویس: ${programmerLevel.getName()}")
result.appendln("سختی برنامه: ${appHardness.getName()}")
result.appendln("تعداد اکتیویتی، فرگمنت: $activities")
result.appendln("تعداد سرویس: $services")
result.appendln("سطح گرافیک برنامه: ${graphic.getName()}")
result.appendln("تحویل سورس: ${if(needSource) "بله" else "خیر"}")
result.appendln("پشتیبانی یکساله: ${if(needSupport) "بله" else "خیر"}")
result.appendln("*تخمین هزینه و زمان توسط اپلیکیشن ecoa*")
result.appendln("دریافت اپلیکیشن ecoa")
result.appendln("market://details?id=$packageName")
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/html"
intent.putExtra(Intent.EXTRA_TEXT,result.toString())
startActivity(Intent.createChooser(intent,"Share as..."))
}
private fun shareImage(){
val header = getBitmapFromView(appBar)
val body = getBitmapFromScrollView(scrollView,scrollView.getChildAt(0).height,scrollView.width)
val result = mergeBitmaps(header,body)
val bitmapPath = MediaStore.Images.Media.insertImage(contentResolver,result,"title",null)
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/*"
intent.putExtra(Intent.EXTRA_STREAM,Uri.parse(bitmapPath))
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.putExtra(Intent.EXTRA_TEXT,"تخمین هزینه و زمان توسط اپلیکیشن ecoa")
startActivity(Intent.createChooser(intent,"Share as..."))
}
private fun getBitmapFromView(view: View): Bitmap {
view.isDrawingCacheEnabled = true
view.buildDrawingCache(true)
val bitmap = Bitmap.createBitmap(view.drawingCache)
view.isDrawingCacheEnabled = false
return bitmap
}
private fun getBitmapFromScrollView(view: View,height: Int,width: Int): Bitmap {
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val bgDrawable = view.background
if (bgDrawable != null)
bgDrawable.draw(canvas)
else
canvas.drawColor(Color.WHITE)
view.draw(canvas)
return bitmap
}
private fun mergeBitmaps(bitmap1: Bitmap, bitmap2: Bitmap): Bitmap{
val width = bitmap1.width
val height = bitmap1.height + bitmap2.height
val result = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888)
val canvas = Canvas(result)
canvas.drawBitmap(bitmap1,0f,0f,null)
canvas.drawBitmap(bitmap2,0f,bitmap1.height.toFloat(),null)
return result
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main,menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item?.itemId){
R.id.action_info -> {
val intent = Intent(this@MainActivity,AboutActivity::class.java)
startActivity(intent)
}
R.id.action_share_text -> shareText()
R.id.action_share_image -> {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1 &&
checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
checkPermission()
else
shareImage()
}
}
return true
}
private fun checkPermission(){
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1)
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),1)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode == 1 && grantResults.isNotEmpty())
shareImage()
}
}
| 0 | Kotlin | 0 | 2 | e6b3543e3fd6c6690675c969d28571819737e442 | 13,196 | ecoa | The Unlicense |
osmunda/src/main/java/moe/sunjiao/osmunda/model/ImportOption.kt | Aka-crypto | 258,895,339 | true | {"Kotlin": 49862} | package moe.sunjiao.osmunda.model
enum class ImportOption {
INCLUDE_WAYS, INCLUDE_RELATIONS
} | 0 | null | 0 | 0 | 6a88aaff2d6a02abc0e37b0dc4dff751c073ff41 | 98 | Osmunda | Apache License 2.0 |
ktmultisample/src/commonMain/kotlin/Main.kt | mareklangiewicz | 103,748,342 | false | {"Kotlin": 47582, "CSS": 1349, "HTML": 572, "Shell": 90} | package pl.mareklangiewicz.ktsample
import pl.mareklangiewicz.kground.*
fun main() {
"Main START".teePP
val calc = MicroCalc(0)
"Micro Calc result is ${calc.result}".tee
calc.add(10)
"Micro Calc result is ${calc.result}".tee
"Main END".tee
}
| 1 | Kotlin | 2 | 7 | 11a4ec04aab4e16182625fee9c62f4326547de51 | 257 | USpek | Apache License 2.0 |
openmrs-client/src/main/java/org/openmrs/mobile/activities/providerdashboard/ProviderDashboardViewModel.kt | openmrs | 22,269,108 | false | null | package org.openmrs.mobile.activities.providerdashboard
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import com.openmrs.android_sdk.library.api.repository.ProviderRepository
import com.openmrs.android_sdk.library.models.Provider
import com.openmrs.android_sdk.library.models.ResultType
import com.openmrs.android_sdk.utilities.ApplicationConstants.BundleKeys.PROVIDER_BUNDLE
import dagger.hilt.android.lifecycle.HiltViewModel
import org.openmrs.mobile.activities.BaseViewModel
import rx.android.schedulers.AndroidSchedulers
import javax.inject.Inject
@HiltViewModel
class ProviderDashboardViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val savedStateHandle: SavedStateHandle
) : BaseViewModel<Unit>() {
val provider = savedStateHandle.get<Provider>(PROVIDER_BUNDLE)!!
val screenTitle: String get() {
var display = provider.person!!.display
if (display == null) {
display = provider.person!!.name.nameString
}
return display
}
fun deleteProvider(): LiveData<ResultType> {
val resultType = MutableLiveData<ResultType>()
addSubscription(providerRepository.deleteProviders(provider.uuid)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ resultType.value = it },
{ resultType.value = ResultType.ProviderDeletionError }
)
)
return resultType
}
}
| 16 | Kotlin | 431 | 174 | 0d9395f0ca83bb671dc4eb87282bbd54a7a32ce8 | 1,579 | openmrs-contrib-android-client | RSA Message-Digest License |
buildSrc/src/main/kotlin/Dependencies.kt | alexoooo | 133,441,467 | false | {"Kotlin": 6483, "JavaScript": 206} | const val kotlinVersion = "1.9.23"
const val jvmTargetVersion = "21"
const val javaVersion = 21
const val jvmToolchainVersion = 21
const val kzenAutoVersion = "0.28.0"
| 1 | Kotlin | 0 | 0 | 9c43731f5076d1fce87838728950012ced26caca | 169 | kzen-project | MIT License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/glue/CfnTableOptimizerDsl.kt | F43nd1r | 643,016,506 | false | {"Kotlin": 5432532} | package com.faendir.awscdkkt.generated.services.glue
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.String
import kotlin.Unit
import software.amazon.awscdk.services.glue.CfnTableOptimizer
import software.amazon.awscdk.services.glue.CfnTableOptimizerProps
import software.constructs.Construct
@Generated
public fun Construct.cfnTableOptimizer(
id: String,
props: CfnTableOptimizerProps,
initializer: @AwsCdkDsl CfnTableOptimizer.() -> Unit = {},
): CfnTableOptimizer = CfnTableOptimizer(this, id, props).apply(initializer)
@Generated
public fun Construct.buildCfnTableOptimizer(id: String, initializer: @AwsCdkDsl
CfnTableOptimizer.Builder.() -> Unit = {}): CfnTableOptimizer =
CfnTableOptimizer.Builder.create(this, id).apply(initializer).build()
| 1 | Kotlin | 0 | 4 | 3d0f80e3da7d0d87d9a23c70dda9f278dbd3f763 | 805 | aws-cdk-kt | Apache License 2.0 |
app/src/main/java/dev/kxxcn/maru/data/source/firebase/FirebaseDataSource.kt | kxxcn | 281,122,468 | false | null | package dev.kxxcn.maru.data.source.firebase
import androidx.lifecycle.LiveData
import com.android.billingclient.api.Purchase
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query.Direction.DESCENDING
import com.google.firebase.firestore.QuerySnapshot
import com.google.firebase.firestore.ktx.toObject
import dev.kxxcn.maru.data.*
import dev.kxxcn.maru.data.Result.Error
import dev.kxxcn.maru.data.Result.Success
import dev.kxxcn.maru.data.source.DataSource
import dev.kxxcn.maru.data.source.api.dto.DirectionDto
import dev.kxxcn.maru.util.*
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
class FirebaseDataSource(
private val firestore: FirebaseFirestore,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : DataSource {
override suspend fun getUsers(): Result<List<User>> {
TODO("Not yet implemented")
}
override suspend fun saveUser(user: User): Result<Any?> {
TODO("Not yet implemented")
}
override suspend fun getTasks(): Result<List<Task>> {
TODO("Not yet implemented")
}
override suspend fun updateTask(taskId: String, isCompleted: Int) {
TODO("Not yet implemented")
}
override suspend fun updateTasks(tasks: List<Task>): Result<Any?> {
TODO("Not yet implemented")
}
override suspend fun deleteTasks(tasks: List<Task>): Result<Any?> {
TODO("Not yet implemented")
}
override suspend fun getTaskDetail(taskId: String): Result<TaskDetail> {
TODO("Not yet implemented")
}
override suspend fun getAccounts(): Result<List<Account>> {
TODO("Not yet implemented")
}
override suspend fun getAccount(taskId: String): Result<Account> {
TODO("Not yet implemented")
}
override suspend fun saveAccount(account: Account): Result<Any?> {
TODO("Not yet implemented")
}
override suspend fun replaceTasks(items: List<Task>) {
TODO("Not yet implemented")
}
override suspend fun getSummary(): Result<List<Summary>> {
TODO("Not yet implemented")
}
override fun observeSummary(): LiveData<List<Summary>> {
TODO("Not yet implemented")
}
override suspend fun getDirection(
start: String,
goal: String,
option: String?
): Result<DirectionDto?> {
TODO("Not yet implemented")
}
override suspend fun saveDirection(direction: DirectionDto, goal: String): Result<Any?> {
TODO("Not yet implemented")
}
override suspend fun saveDay(day: Day): Result<Any?> {
TODO("Not yet implemented")
}
override suspend fun deleteDay(day: Day): Result<Any?> {
TODO("Not yet implemented")
}
override suspend fun getNotices(): Result<QuerySnapshot?> = withContext(ioDispatcher) {
return@withContext try {
val data = firestore
.collection(COLLECTION_NOTICE)
.orderBy(FILED_CREATED_AT, DESCENDING)
.get()
.await()
Success(data)
} catch (e: Exception) {
Error(e)
}
}
override suspend fun editName(name: String): Result<Any?> {
TODO("Not yet implemented")
}
override suspend fun editBudget(budget: Long): Result<Any?> {
TODO("Not yet implemented")
}
override suspend fun addTask(task: Task): Result<Any?> {
TODO("Not yet implemented")
}
override suspend fun savePremium(email: String?, purchase: Purchase?): Result<Any?> =
withContext(ioDispatcher) {
return@withContext try {
if (purchase == null) throw NullPointerException("Invalid input object.")
val history = hashMapOf(
FILED_EMAIL to email,
FILED_ORDER_ID to purchase.orderId,
FILED_ORDER_TIME to purchase.purchaseTime,
FILED_ORDER_TOKEN to purchase.purchaseToken,
FILED_SIGNATURE to purchase.signature,
FILED_SKU to purchase.skus.toString()
)
val data = firestore
.collection(COLLECTION_PURCHASE)
.add(history)
.await()
Success(data)
} catch (e: Exception) {
Error(e)
}
}
override suspend fun isPremium(email: String?): Result<Boolean> = withContext(ioDispatcher) {
return@withContext try {
if (email == null) throw NullPointerException("Invalid email address.")
val data = firestore
.collection(COLLECTION_PURCHASE)
.whereEqualTo(FILED_EMAIL, email)
.get()
.await()
Success(!data.isEmpty)
} catch (e: Exception) {
Error(e)
}
}
override suspend fun backup(email: String, encoded: String): Result<Any?> =
withContext(ioDispatcher) {
return@withContext try {
val backup = hashMapOf(
FILED_DATA to encoded,
FILED_TIME to System.currentTimeMillis()
)
firestore
.collection(COLLECTION_BACKUP)
.document(email)
.set(backup)
.await()
Success(Unit)
} catch (e: Exception) {
Error(e)
}
}
override suspend fun findRestore(email: String): Result<Restore?> =
withContext(ioDispatcher) {
return@withContext try {
val data = firestore
.collection(COLLECTION_BACKUP)
.document(email)
.get()
.await()
.run { toObject<Restore>() }
Success(data)
} catch (e: Exception) {
Error(e)
}
}
override suspend fun restore(summary: Summary): Result<Any?> {
TODO("Not yet implemented")
}
}
| 0 | Kotlin | 0 | 0 | 8a83ab615390a5e1b1cf7ff1ae0644ebedd9bbcd | 6,210 | maru | Apache License 2.0 |
src/main/kotlin/org/wasabi/routing/PatternMatchingChannelLocator.kt | swishy | 13,486,733 | true | {"Kotlin": 115417, "Groovy": 3328, "Shell": 582, "CSS": 36} | package org.wasabi.routing
import org.wasabi.websocket.Channel
import java.util.ArrayList
import org.slf4j.LoggerFactory
/**
* Created with IntelliJ IDEA.
* User: swishy
* Date: 5/11/13
* Time: 10:47 PM
* To change this template use File | Settings | File Templates.
*/
public class PatternMatchingChannelLocator(val channels: ArrayList<Channel>) : ChannelLocator {
private var log = LoggerFactory.getLogger(javaClass<PatternMatchingChannelLocator>())
override fun findChannelHandler(channel: String): Channel {
// Handshaker has full uri on instance so we strip off the protocol and search for raw path
val matchingChannel = channels.filter { it.path == channel.split("ws://")[0] }
if (matchingChannel.count() == 0) {
throw ChannelNotFoundException()
}
// We should only ever have one handler for a websocket channel
return matchingChannel.first!!
}
} | 0 | Kotlin | 0 | 0 | 2e8f22cb16bfbd84b023e933304ca0a3668030c3 | 936 | wasabi | Apache License 2.0 |
app/src/main/java/com/ingjuanocampo/enfila/domain/usecases/LogoutUC.kt | ingjuanocampo | 387,043,993 | false | {"Kotlin": 247926} | package com.ingjuanocampo.enfila.domain.usecases
import com.ingjuanocampo.enfila.domain.di.data.DELETABLE
import com.ingjuanocampo.enfila.domain.usecases.repository.base.Repository
import javax.inject.Inject
class LogoutUC
@Inject
constructor(
@DELETABLE private val deletables: Set<@JvmSuppressWildcards Repository<*>>,
) {
suspend operator fun invoke() {
deletables.forEach {
it.deleteAll()
}
}
}
| 1 | Kotlin | 0 | 0 | 48511b31463997a8ba114be7f4e35ca0eeac1972 | 481 | EnFila-Android | MIT License |
app/src/main/java/ir/magiccodes/wikipedia/SecondActivity.kt | Mahdi-Jamshidi | 473,155,814 | false | {"Kotlin": 56198} | package ir.magiccodes.wikipedia
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import ir.magiccodes.wikipedia.data.ItemPost
import ir.magiccodes.wikipedia.databinding.ActivitySecondBinding
import ir.magiccodes.wikipedia.fragment.KEY_SEND_DATA_TO_SECOND_ACTIVITY
class SecondActivity : AppCompatActivity() {
lateinit var binding: ActivitySecondBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySecondBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbarAsli)
binding.collapsingMain.setExpandedTitleColor(
ContextCompat.getColor(
this,
android.R.color.transparent
)
)
supportActionBar!!.setHomeButtonEnabled(true)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
val dataPost = intent.getParcelableExtra<ItemPost>(KEY_SEND_DATA_TO_SECOND_ACTIVITY)
if (dataPost != null) {
showData(dataPost)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
}
return true
}
private fun showData(itemPost: ItemPost) {
Glide.with(this)
.load(itemPost.imgUrl)
.into(binding.imgDetail)
binding.txtDetailTitle.text = itemPost.txtTitle
binding.txtDetailSubtitle.text = itemPost.txtSubtitle
binding.txtDetailText.text = itemPost.txtDetail
binding.fabDetailOpenWikipedia.setOnClickListener {
val url = "https://en.wikipedia.org/wiki/Main_Page"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
}
//Set the toolbar title with the item
binding.collapsingMain.title = itemPost.txtTitle
}
}
| 0 | Kotlin | 0 | 0 | 2cea481fa0da5cf63afeafa0e37b799de72b56d3 | 2,075 | Wikipedia | MIT License |
zenet/request/src/main/kotlin/br/com/khomdrake/request/Config.kt | KhomDrake | 776,191,044 | false | {"Kotlin": 92853} | package br.com.khomdrake.request
import androidx.annotation.WorkerThread
import br.com.khomdrake.request.cache.Cache
import br.com.khomdrake.request.data.Response
import br.com.khomdrake.request.data.responseData
import br.com.khomdrake.request.data.responseError
import br.com.khomdrake.request.data.responseLoading
import br.com.khomdrake.request.exception.RequestNotImplementedException
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.withTimeout
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
enum class CacheType {
MEMORY,
DISK
}
class Config<Data>(private val key: String) {
private var maxDuration = 5.minutes
private var minDuration: Duration = 200.milliseconds
private val withCache: Boolean
get() = cache != null
private var execution: (suspend () -> Data)? = null
private var cache: Cache<Data>? = null
fun maxDuration(duration: Duration) = apply {
maxDuration = duration
}
fun minDuration(duration: Duration) = apply {
minDuration = duration
}
fun cache(function: Cache<Data>.() -> Unit) = apply {
cache = Cache<Data>(key)
.apply(function)
}
fun request(function: suspend () -> Data) = apply {
execution = function
}
@WorkerThread
suspend fun execute(
collector: FlowCollector<Response<Data>>,
handler: RequestHandler<Data>
) {
withTimeout(maxDuration) {
runCatching {
val currentTime = System.currentTimeMillis()
val cacheExpired = cache?.isExpired(currentTime) ?: true
collector.emit(responseLoading())
if(!withCache) {
executionWithoutCache(handler, collector)
} else if(cacheExpired && withCache) {
executionCacheExpiredOrNotSet(handler, collector, isExpired = true)
} else {
executionCache(handler, collector)
}
}.onFailure {
handler.logInfo("[Config] Emitting error")
collector.emit(responseError(it))
handler.logInfo("[Config] Error emitted: $it")
}
}
}
private suspend inline fun executionCache(
handler: RequestHandler<Data>,
collector: FlowCollector<Response<Data>>
) {
handler.logInfo("[Config] using cache key: $key")
val savedData = cache?.retrieve()
savedData?.let {
handler.logInfo("[Config] cache retrieved: $it")
collector.emit(responseData(savedData))
} ?: executionCacheExpiredOrNotSet(handler, collector, isExpired = false)
}
private suspend inline fun executionCacheExpiredOrNotSet(
handler: RequestHandler<Data>,
collector: FlowCollector<Response<Data>>,
isExpired: Boolean
) {
if(isExpired) {
handler.logInfo("[Config] Request started - Cache expired")
cache?.remove()
} else handler.logInfo("[Config] Request started - Cache not set")
val execution = execution ?: throw RequestNotImplementedException()
val data = execution.invoke()
handler.logInfo("[Config] Request ended, data: $data")
cache?.save(data)
handler.logInfo("[Config] Data emitted: $data")
collector.emit(responseData(data))
}
private suspend inline fun executionWithoutCache(
handler: RequestHandler<Data>,
collector: FlowCollector<Response<Data>>
) {
handler.logInfo("[Config] Request started")
val execution = execution ?: throw RequestNotImplementedException()
val data = execution.invoke()
handler.logInfo("[Config] Request ended, data: $data")
collector.emit(responseData(data))
handler.logInfo("[Config] Data emitted: $data")
}
} | 0 | Kotlin | 0 | 0 | cee648d765ca6c18a3be00160da00c1a73cb7545 | 3,951 | Zenet | Apache License 2.0 |
app/src/main/kotlin/de/nickbw2003/stopinfo/common/data/WebException.kt | nickbw2003 | 169,991,061 | false | null | package de.nickbw2003.stopinfo.common.data
import de.nickbw2003.stopinfo.common.data.models.Error
class WebException(val error: Error, val code: Int, val internalException: Exception? = null) : Exception() {
companion object {
const val UNKNOWN_RESPONSE_CODE = 999
}
} | 0 | Kotlin | 0 | 4 | b22c4c3ac29338cab65a6061474020b03f653260 | 286 | stop-info-android | MIT License |
src/main/kotlin/com/github/sgtsilvio/gradle/android/retrofix/RetroFixPlugin.kt | SgtSilvio | 196,088,225 | false | {"Kotlin": 38398} | package com.github.sgtsilvio.gradle.android.retrofix
import com.android.build.api.AndroidPluginVersion
import com.android.build.api.instrumentation.InstrumentationScope
import com.android.build.api.variant.AndroidComponentsExtension
import com.android.build.gradle.BaseExtension
import com.android.build.gradle.BasePlugin
import org.gradle.api.GradleException
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.FileCollection
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.withType
import java.util.zip.ZipFile
/**
* @author <NAME>
*/
@Suppress("unused")
class RetroFixPlugin : Plugin<Project> {
@Override
override fun apply(project: Project) {
project.plugins.withType<BasePlugin> {
val configuration = project.configurations.create("retrofix")
project.configurations.named("implementation") {
extendsFrom(configuration)
}
val androidComponents = project.extensions["androidComponents"] as AndroidComponentsExtension<*, *, *>
if (androidComponents.pluginVersion >= AndroidPluginVersion(7, 2)) {
androidComponents.onVariants { applicationVariant ->
applicationVariant.instrumentation.transformClassesWith(
RetroFixClassVisitorFactory::class.java,
InstrumentationScope.ALL,
) { parameters ->
parameters.classList.set(classListProvider(project, configuration))
}
}
} else {
androidComponents.onVariants { applicationVariant ->
@Suppress("DEPRECATION") applicationVariant.transformClassesWith(
RetroFixClassVisitorFactory::class.java,
InstrumentationScope.ALL,
) { parameters ->
parameters.classList.set(classListProvider(project, configuration))
}
}
}
}
project.afterEvaluate {
val androidExtension = project.extensions["android"] as? BaseExtension
?: throw GradleException("The RetroFix plugin requires the 'com.android.application' plugin.")
if (androidExtension.defaultConfig.minSdkVersion!!.apiLevel >= 24) {
throw GradleException("The RetroFix plugin should not be used when minSdk >= 24.")
}
}
}
}
private fun classListProvider(project: Project, libraries: FileCollection) = project.provider {
val classList = mutableListOf<String>()
for (library in libraries) {
if (!library.isFile || !library.name.endsWith(".jar")) {
throw GradleException("libraries are expected to be only jar files, but found $library")
}
ZipFile(library).stream().map { it.name.replace('\\', '/') }.forEach { name ->
if (name.endsWith(".class") &&
!name.startsWith("META-INF/") &&
(name != "module-info.class") &&
(name != "package-info.class")
) {
classList.add(name.removeSuffix(".class"))
}
}
}
classList
}
| 1 | Kotlin | 7 | 64 | 2df87c88fc2192e50e734045b7f4007f76f26088 | 3,246 | android-retrofix | Apache License 2.0 |
kafkistry-service-logic/src/main/kotlin/com/infobip/kafkistry/service/topic/inspectors/TopicNoConsumersInspector.kt | infobip | 456,885,171 | false | {"Kotlin": 2621597, "FreeMarker": 812131, "JavaScript": 297269, "CSS": 7204} | package com.infobip.kafkistry.service.topic.inspectors
import com.infobip.kafkistry.kafkastate.KafkaConsumerGroupsProvider
import com.infobip.kafkistry.service.StatusLevel
import com.infobip.kafkistry.service.consumers.ConsumersService
import com.infobip.kafkistry.service.topic.*
import com.infobip.kafkistry.service.topic.offsets.TopicOffsetsService
import org.springframework.stereotype.Component
val NO_CONSUMERS = TopicInspectionResultType(
name = "NO_CONSUMERS",
level = StatusLevel.WARNING,
category = IssueCategory.NONE,
doc = "Topic has no consumers reading it",
)
@Component
class TopicNoConsumersInspector(
private val consumerGroupsProvider: KafkaConsumerGroupsProvider,
) : TopicExternalInspector {
override fun inspectTopic(
ctx: TopicInspectCtx,
outputCallback: TopicExternalInspectCallback
) {
if (ctx.existingTopic == null) {
return //topic doesn't exist
}
if (ctx.existingTopic.internal) {
return //don't expect regular consumers reading from kafka's internal topic
}
val clusterGroups = consumerGroupsProvider.getLatestState(ctx.clusterRef.identifier)
.valueOrNull()
?: return //no data from cluster
val groups = clusterGroups.topicConsumerGroups[ctx.topicName].orEmpty()
if (groups.isEmpty()) {
outputCallback.addStatusType(NO_CONSUMERS)
}
}
}
| 2 | Kotlin | 6 | 42 | bbd06186aff2fd73fc2b42f0b282cfbef271ed75 | 1,444 | kafkistry | Apache License 2.0 |
kafkistry-service-logic/src/main/kotlin/com/infobip/kafkistry/service/topic/inspectors/TopicNoConsumersInspector.kt | infobip | 456,885,171 | false | {"Kotlin": 2621597, "FreeMarker": 812131, "JavaScript": 297269, "CSS": 7204} | package com.infobip.kafkistry.service.topic.inspectors
import com.infobip.kafkistry.kafkastate.KafkaConsumerGroupsProvider
import com.infobip.kafkistry.service.StatusLevel
import com.infobip.kafkistry.service.consumers.ConsumersService
import com.infobip.kafkistry.service.topic.*
import com.infobip.kafkistry.service.topic.offsets.TopicOffsetsService
import org.springframework.stereotype.Component
val NO_CONSUMERS = TopicInspectionResultType(
name = "NO_CONSUMERS",
level = StatusLevel.WARNING,
category = IssueCategory.NONE,
doc = "Topic has no consumers reading it",
)
@Component
class TopicNoConsumersInspector(
private val consumerGroupsProvider: KafkaConsumerGroupsProvider,
) : TopicExternalInspector {
override fun inspectTopic(
ctx: TopicInspectCtx,
outputCallback: TopicExternalInspectCallback
) {
if (ctx.existingTopic == null) {
return //topic doesn't exist
}
if (ctx.existingTopic.internal) {
return //don't expect regular consumers reading from kafka's internal topic
}
val clusterGroups = consumerGroupsProvider.getLatestState(ctx.clusterRef.identifier)
.valueOrNull()
?: return //no data from cluster
val groups = clusterGroups.topicConsumerGroups[ctx.topicName].orEmpty()
if (groups.isEmpty()) {
outputCallback.addStatusType(NO_CONSUMERS)
}
}
}
| 2 | Kotlin | 6 | 42 | bbd06186aff2fd73fc2b42f0b282cfbef271ed75 | 1,444 | kafkistry | Apache License 2.0 |
src/ii_collections/n19Sum.kt | textbook | 139,580,449 | true | {"Kotlin": 69177, "Java": 4952} | package ii_collections
fun Customer.getTotalOrderPrice(): Double = orders.flatMap { it.products }.sumByDouble { it.price }
| 0 | Kotlin | 0 | 0 | 96abd46966f30f58e5e67564759d937ad34769c5 | 124 | kotlin-koans | MIT License |
src/main/kotlin/dev/dfreer/contacts/json/Parser.kt | danielfreer | 510,142,986 | false | {"Kotlin": 35009} | package dev.dfreer.contacts.json
import dev.dfreer.contacts.api.v1.Contact
import dev.dfreer.contacts.api.v1.ContactWithId
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
class Parser {
private val json = Json { prettyPrint = true }
inline fun <reified T> decodeFromString(json: String): T = Json.decodeFromString(json)
fun encodeToString(contact: Contact) = json.encodeToString(contact)
fun encodeToString(contactWithId: ContactWithId) = json.encodeToString(contactWithId)
fun encodeToString(contactsWithId: List<ContactWithId>) = json.encodeToString(contactsWithId)
}
| 0 | Kotlin | 0 | 0 | 472a00f00dffdedcf27e566a666558c689e569c5 | 674 | contacts | MIT License |
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/market/AddResponse.kt | alatushkin | 156,866,851 | false | null | package name.alatushkin.api.vk.generated.market
open class AddResponse(
val marketItemId: Long? = null
) | 2 | Kotlin | 3 | 10 | 123bd61b24be70f9bbf044328b98a3901523cb1b | 110 | kotlin-vk-api | MIT License |
model/src/commonMain/kotlin/com/kentvu/csproblems/components/MainComponent.kt | KentVu | 210,312,595 | false | {"Kotlin": 53299} | package com.kentvu.csproblems.components
import co.touchlab.kermit.Logger
import com.arkivanov.decompose.ComponentContext
import com.arkivanov.decompose.value.MutableValue
import com.arkivanov.decompose.value.Value
import com.arkivanov.decompose.value.update
import com.kentvu.csproblems.Problem
import com.kentvu.csproblems.Solution
import com.kentvu.csproblems.components.RootComponent.NavigationEvent
import com.kentvu.csproblems.data.Repository
import com.kentvu.utils.ListWithSelection
import com.kentvu.utils.essenty.coroutineScope
import com.kentvu.utils.listWithSelectionOf
import com.kentvu.utils.withSelection
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.collections.first
import kotlin.coroutines.CoroutineContext
interface MainComponent {
val state: Value<State>
fun onEvent(event: Event)
data class State(
val problems: ListWithSelection<Problem> = listWithSelectionOf(),
val solutions: ListWithSelection<Solution> = listWithSelectionOf(),
val input: String = "",
val result: String = "",
)
sealed interface Event {
data object ObsoletedClick : Event
data class ProblemSelect(val problem: Problem) : Event {}
data class InputChange(val value: String) : Event {}
data class SolutionSelect(val solution: Solution) : Event {}
data object RunClick : Event
}
class Default(
baseLogger: Logger,
cContext: ComponentContext,
mainDispatcher: CoroutineContext,
private val repo: Repository,
private val onNavigationEvent: (NavigationEvent.Main) -> Unit,
) : MainComponent {
private val logger = baseLogger.withTag("MainComponent")
private val scope = cContext.coroutineScope(mainDispatcher + SupervisorJob())
override val state = MutableValue(State())
init {
scope.launch {
val problems = withContext(Dispatchers.IO) {
repo.problems.loadProblems()
}
state.value = State(
problems = problems.withSelection(),
)
}
}
override fun onEvent(event: Event) {
when (event) {
is Event.ObsoletedClick ->
onNavigationEvent(NavigationEvent.Main.ObsoletedClick)
is Event.ProblemSelect -> scope.launch {
val solutions = withContext(Dispatchers.IO) {
repo.solutions.load(event.problem.id)
}
state.update {
it.copy(
problems = it.problems.select(event.problem),
solutions = solutions.takeIf { it.isNotEmpty() }?.withSelection(0) ?: it.solutions,
input = event.problem.sampleInputs.first(),
)
}
}
is Event.InputChange -> state.update {
it.copy(input = event.value)
}
Event.RunClick -> {
logger.d("buttonRunClick")
val code = state.value.solutions.selectedItem?.kotlinCode
if (code != null) {
val result = try {
code.invoke(state.value.input)
} catch (e: Exception) {
e
}
state.update { it.copy(result = result.toString()) }
}
}
is Event.SolutionSelect -> state.update {
it.copy(solutions = it.solutions.select(event.solution))
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | d3652f4e9a54db313f9da0b3077aa26325150c62 | 3,396 | CSProblems | Apache License 2.0 |
app/src/main/java/com/example/stsotre/ui/screens/home/MostFavoriteProductShowMore.kt | shirinvn | 711,298,897 | false | {"Kotlin": 193308, "Java": 7887} | package com.example.stsotre.ui.screens.home
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
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.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.stsotre.R
import com.example.stsotre.ui.theme.DarkCyan
import com.example.stsotre.ui.theme.darkText
import com.example.stsotre.ui.theme.spacing
@Composable
fun MostFavoriteProductShowMore (){
Column( modifier = Modifier
.size(160.dp, 320.dp)
.padding(
end = MaterialTheme.spacing.medium,
start = MaterialTheme.spacing.semismall,
top = MaterialTheme.spacing.semilarge
),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(
painter = painterResource(id = R.drawable.show_more),
contentDescription = "",
tint = MaterialTheme.colors.DarkCyan,
modifier = Modifier.size(40.dp, 40.dp))
Spacer(modifier = Modifier.height(20.dp))
Text(text = stringResource(id = R.string.see_all),
style = MaterialTheme.typography.h6,
fontWeight = FontWeight.SemiBold,
color= MaterialTheme.colors.darkText )
}
} | 0 | Kotlin | 0 | 0 | 4d9d291f9432a3ee8d397914a678eee15ff3727c | 1,943 | STStore | MIT License |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsmanageprisonvisitsorchestration/integration/visit/VisitByReferenceTest.kt | ministryofjustice | 575,484,836 | false | null | package uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.integration.visit
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.springframework.http.HttpHeaders
import org.springframework.test.web.reactive.server.WebTestClient
import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.visit.scheduler.VisitDto
import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.integration.IntegrationTestBase
@DisplayName("Get visits by reference")
class VisitByReferenceTest : IntegrationTestBase() {
fun callVisitByReference(
webTestClient: WebTestClient,
reference: String,
authHttpHeaders: (HttpHeaders) -> Unit,
): WebTestClient.ResponseSpec {
return webTestClient.get().uri("/visits/$reference")
.headers(authHttpHeaders)
.exchange()
}
@Test
fun `when visit exists search by reference returns that visit`() {
// Given
val reference = "aa-bb-cc-dd"
val createdBy = "created-user"
val lastUpdatedBy = "updated-user"
val visitDto = createVisitDto(reference = reference, createdBy = createdBy, updatedBy = lastUpdatedBy, cancelledBy = null)
visitSchedulerMockServer.stubGetVisit(reference, visitDto)
// When
val responseSpec = callVisitByReference(webTestClient, reference, roleVisitSchedulerHttpHeaders)
// Then
responseSpec.expectStatus().isOk
val visitDtoResponse = objectMapper.readValue(responseSpec.expectBody().returnResult().responseBody, VisitDto::class.java)
Assertions.assertThat(visitDtoResponse.reference).isEqualTo(visitDto.reference)
Assertions.assertThat(visitDtoResponse.createdBy).isEqualTo(createdBy)
Assertions.assertThat(visitDtoResponse.updatedBy).isEqualTo(lastUpdatedBy)
Assertions.assertThat(visitDtoResponse.cancelledBy).isNull()
}
@Test
fun `when visit does not exist search by reference returns NOT_FOUND status`() {
// Given
val reference = "xx-yy-cc-dd"
visitSchedulerMockServer.stubGetVisit(reference, null)
// When
val responseSpec = callVisitByReference(webTestClient, reference, roleVisitSchedulerHttpHeaders)
// Then
responseSpec.expectStatus().isNotFound
}
}
| 1 | Kotlin | 0 | 2 | 50873a58365a25650fd1e3af3433fc94236c0c16 | 2,253 | hmpps-manage-prison-visits-orchestration | MIT License |
browser-kotlin/src/jsMain/kotlin/web/history/ScrollRestoration.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6149331} | // Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.history
// language=JavaScript
@JsName("""(/*union*/{auto: 'auto', manual: 'manual'}/*union*/)""")
sealed external interface ScrollRestoration {
companion object {
val auto: ScrollRestoration
val manual: ScrollRestoration
}
}
| 0 | Kotlin | 6 | 26 | 188d780966c530ed7385f81248ebac5e5abcc40b | 404 | types-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.