path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/org/blitzortung/android/map/overlay/PopupOverlay.kt
|
KubaDeX
| 49,097,832
| true
|
{"Kotlin": 220517, "Java": 62}
|
package org.blitzortung.android.map.overlay
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import android.widget.TextView
import com.google.android.maps.GeoPoint
import com.google.android.maps.ItemizedOverlay
import com.google.android.maps.MapView
import com.google.android.maps.OverlayItem
import org.blitzortung.android.app.R
import org.blitzortung.android.map.OwnMapActivity
abstract class PopupOverlay<Item : OverlayItem>(val activity: OwnMapActivity, defaultMarker: Drawable) : ItemizedOverlay<Item>(defaultMarker) {
internal var popupShown: Boolean = false
init {
popupShown = false
}
protected fun showPopup(location: GeoPoint, text: String) {
val map = activity.mapView
val popUp = map.popup
map.removeView(popUp)
val statusText = popUp.findViewById(R.id.popup_text) as TextView
statusText.setBackgroundColor(-2013265920)
statusText.setPadding(5, 5, 5, 5)
statusText.text = text
val mapParams = MapView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
location, 0, 0, MapView.LayoutParams.BOTTOM_CENTER)
map.addView(popUp, mapParams)
popupShown = true
}
fun clearPopup(): Boolean {
val map = activity.mapView
val popUp = map.popup
map.removeView(popUp)
val popupShownStatus = popupShown
popupShown = false
return popupShownStatus
}
override fun onTap(arg0: GeoPoint?, arg1: MapView?): Boolean {
val eventHandled = super.onTap(arg0, arg1)
if (!eventHandled) {
clearPopup()
}
return eventHandled
}
}
| 0
|
Kotlin
|
0
| 0
|
1197dbf9693b588f92ce8bdb1254507274838a8a
| 1,716
|
bo-android
|
MIT License
|
app/src/main/java/com/example/mymovieapp/activitys/HomeFragment.kt
|
alpcetinkus
| 606,760,722
| false
| null |
package com.example.mymovieapp.activitys
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.mymovieapp.R
import com.example.mymovieapp.adapter.BestFromYearAdapter
import com.example.mymovieapp.adapter.FromTurkeyAdapter
import com.example.mymovieapp.adapter.PopularMovieAdapter
import com.example.mymovieapp.adapter.UpComingAdapter
import com.example.mymovieapp.model.*
import com.example.mymovieapp.service.MovieApiInterfaces
import com.example.mymovieapp.service.MovieApiService
import kotlinx.android.synthetic.main.fragment_home.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class HomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
rc_trending.setHasFixedSize(true)
rc_trending.layoutManager =
StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL)
rc_person_popular.setHasFixedSize(true)
rc_person_popular.layoutManager =
StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL)
rc_upcoming.setHasFixedSize(true)
rc_upcoming.layoutManager =
StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL)
rc_bestfromturkey.setHasFixedSize(true)
rc_bestfromturkey.layoutManager =
StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL)
fetchPopularMovie { movies ->
rc_trending.adapter = PopularMovieAdapter(movies)
}
fetchBestFromYearMovie { movies ->
rc_person_popular.adapter = BestFromYearAdapter(movies)
}
fetchUpComingMovie { movies ->
rc_upcoming.adapter = UpComingAdapter(movies)
}
fetchFromTurkey { movies ->
rc_bestfromturkey.adapter = FromTurkeyAdapter(movies)
}
}
fun fetchPopularMovie(callback: (List<PopularMovie>) -> Unit) {
val apiService = MovieApiService.getInstance().create(MovieApiInterfaces::class.java)
apiService.getPopularList().enqueue(object : Callback<PopularMovieResponse> {
override fun onResponse(
call: Call<PopularMovieResponse>,
response: Response<PopularMovieResponse>
) {
return callback(response.body()!!.PopularMovie)
Log.e("success", response.body()!!.PopularMovie.toString())
}
override fun onFailure(call: Call<PopularMovieResponse>, t: Throwable) {
Log.e("fail", t.message.toString())
}
})
}
fun fetchBestFromYearMovie(callback: (List<BestFromYearMovie>) -> Unit) {
val apiService = MovieApiService.getInstance().create(MovieApiInterfaces::class.java)
apiService.getBestFromYearList().enqueue(object : Callback<BestFromYearResponse> {
override fun onResponse(
call: Call<BestFromYearResponse>,
response: Response<BestFromYearResponse>
) {
return callback(response.body()!!.bestFromYearMovie)
Log.e("success", response.body()!!.bestFromYearMovie.toString())
}
override fun onFailure(call: Call<BestFromYearResponse>, t: Throwable) {
Log.e("fail", t.message.toString())
}
})
}
fun fetchUpComingMovie(callback: (List<UpComingMovie>) -> Unit) {
val apiService = MovieApiService.getInstance().create(MovieApiInterfaces::class.java)
apiService.getUpComingMovieList().enqueue(object : Callback<UpComingResponse> {
override fun onResponse(
call: Call<UpComingResponse>,
response: Response<UpComingResponse>
) {
return callback(response.body()!!.UpComingMovies)
Log.e("success", response.body()!!.UpComingMovies.toString())
}
override fun onFailure(call: Call<UpComingResponse>, t: Throwable) {
Log.e("fail", t.message.toString())
}
})
}
fun fetchFromTurkey(callback: (List<FromTurkey>) -> Unit) {
val apiService = MovieApiService.getInstance().create(MovieApiInterfaces::class.java)
apiService.getPopularFromTurkeyList().enqueue(object : Callback<FromTurkeyResponse> {
override fun onResponse(
call: Call<FromTurkeyResponse>,
response: Response<FromTurkeyResponse>
) {
return callback(response.body()!!.fromTurkeyMovie)
Log.e("success", response.body()!!.fromTurkeyMovie.toString())
}
override fun onFailure(call: Call<FromTurkeyResponse>, t: Throwable) {
Log.e("fail", t.message.toString())
}
})
}
}
// fetchPopularMovie fonksiyonu, popüler film verilerini API'den almak için kullanılır.
// Bu fonksiyon, MovieApiService sınıfından bir örnek alır ve ardından getPopularMovieList fonksiyonunu çağırarak popüler film verilerini alır.
// Bu işlem, bir Callback nesnesi kullanılarak gerçekleştirilir.
| 0
|
Kotlin
|
0
| 0
|
2998699e52828ebb8dfd21740877f06431efd381
| 5,592
|
MyMovieApp
|
MIT License
|
fluxo-core/src/commonMain/kotlin/kt/fluxo/core/SideEffectsStrategy.kt
|
fluxo-kt
| 566,869,438
| false
| null |
@file:Suppress("CanSealedSubClassBeObject")
package kt.fluxo.core
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kt.fluxo.core.SideEffectsStrategy.RECEIVE
import kt.fluxo.core.annotation.InternalFluxoApi
import kotlin.jvm.JvmField
/**
* Available strategies for how side effects sharing can be handled in the [Store].
* When in doubt, use the [default][RECEIVE] one, and change if you have issues.
*/
public sealed interface SideEffectsStrategy {
/**
* [Channel]-based strategy with sharing through the [receiveAsFlow].
* Multiple subscribers allowed. One side effect will be emitted to one subscriber only and **the order of subscribers unspecified**.
*
* @see kotlinx.coroutines.flow.receiveAsFlow
* @see SHARE
* @see CONSUME
*/
public object RECEIVE : SideEffectsStrategy {
/** @hide */
@InternalFluxoApi
override fun toString(): String = "RECEIVE"
}
/**
* [Channel]-based strategy with sharing through the [consumeAsFlow].
*
* **Restricts the count of subscribers to 1**. Consumes the underlying [Channel] completely on the first subscription from the flow!
* The resulting flow can be collected just once and throws [IllegalStateException] when trying to collect it more than once.
*
* Attempting to subscribe or resubscribe to side effects from a [Store] already subscribed will result in an exception.
* In other words, you will be required to create a new [Store] for each subscriber!
*
* **In the most cases you need [RECEIVE] or [SHARE] strategies instead of this one!**
*
* @see kotlinx.coroutines.flow.consumeAsFlow
* @see RECEIVE
* @see SHARE
*/
public object CONSUME : SideEffectsStrategy {
/** @hide */
@InternalFluxoApi
override fun toString(): String = "CONSUME"
}
/**
* [MutableSharedFlow]-based strategy. Shares emitted side effects among all subscribers in a broadcast fashion,
* so that all collectors get all emitted side effects.
*
* Keeps a [specified number][replay] of the most recent values in its replay cache. Every new subscriber first gets
* the values from the replay cache and then gets new emitted values.
*
* @param replay the number of side effects replayed to new subscribers (cannot be negative, defaults to zero).
*
* @see kotlinx.coroutines.flow.MutableSharedFlow
*/
public class SHARE(
@JvmField
public val replay: Int,
) : SideEffectsStrategy {
public constructor() : this(replay = 0)
/** @hide */
@InternalFluxoApi
override fun toString(): String = "SHARE(replay=$replay)"
/** @hide */
@InternalFluxoApi
override fun equals(other: Any?): Boolean = this === other || other is SHARE && replay == other.replay
/** @hide */
@InternalFluxoApi
override fun hashCode(): Int = replay
}
/**
* Side effects are completely disabled.
* Saves a bit of app memory, and sometimes your brain cells (as a purer way is to use only state+intent).
*/
public object DISABLE : SideEffectsStrategy {
/** @hide */
@InternalFluxoApi
override fun toString(): String = "DISABLE"
}
}
| 0
|
Kotlin
|
0
| 4
|
0b4ee15e9ce497d53c92fddb41eea5072243c648
| 3,444
|
fluxo-mvi
|
Apache License 2.0
|
src/main/kotlin/org/celtric/kotlin/html/summary.kt
|
celtric
| 121,420,012
| false
| null |
package org.celtric.kotlin.html
fun summary(
// Global
classes: String? = null,
id: String? = null,
// Custom
other: Attributes = emptyMap(),
data: Attributes = emptyMap(),
// Content
content: () -> Any
) = BlockElement("summary", content(), AllAttributes(mapOf(
"class" to classes,
"id" to id
), other, data))
fun summary(content: String) = summary { content }
fun summary(content: Node) = summary { content }
fun summary(content: List<Node>) = summary { content }
| 1
|
Kotlin
|
3
| 25
|
70cd501bb534ad84f8c8c3a8f8fb18dddd7054e4
| 510
|
kotlin-html
|
Apache License 2.0
|
examples/src/tl/telegram/upload/UploadWebFile.kt
|
andreypfau
| 719,064,910
| false
|
{"Kotlin": 62259}
|
// This file is generated by TLGenerator.kt
// Do not edit manually!
package tl.telegram.upload
import io.github.andreypfau.tl.serialization.Base64ByteStringSerializer
import io.github.andreypfau.tl.serialization.TLCombinatorId
import kotlin.jvm.JvmName
import kotlinx.io.bytestring.ByteString
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import tl.telegram.storage.StorageFileType
@Serializable
@SerialName("upload.webFile")
@TLCombinatorId(0x21E753BC)
public data class UploadWebFile(
@get:JvmName("size")
public val size: Int,
@SerialName("mime_type")
@get:JvmName("mimeType")
public val mimeType: String,
@SerialName("file_type")
@get:JvmName("fileType")
public val fileType: StorageFileType,
@get:JvmName("mtime")
public val mtime: Int,
@get:JvmName("bytes")
public val bytes: @Serializable(Base64ByteStringSerializer::class) ByteString,
) {
public companion object
}
| 0
|
Kotlin
|
0
| 1
|
11f05ad1f977235e3e360cd6f6ada6f26993208e
| 964
|
tl-kotlin
|
MIT License
|
common/src/jvmMain/kotlin/com/saveourtool/common/security/CommentPermissionEvaluator.kt
|
saveourtool
| 300,279,336
| false
|
{"Kotlin": 3428381, "SCSS": 86430, "JavaScript": 9061, "HTML": 8852, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366}
|
package com.saveourtool.common.security
import com.saveourtool.common.domain.Role
import com.saveourtool.common.entities.Comment
import com.saveourtool.common.entities.CommentDto
import com.saveourtool.common.permission.Permission
import com.saveourtool.common.utils.hasRole
import org.springframework.security.core.Authentication
import org.springframework.stereotype.Component
/**
* Class that is capable of assessing user permissions.
*
* TODO: move all the hasPermission methods here
*/
@Component
class CommentPermissionEvaluator {
/**
* Check permission for user to read, write and delete [Comment]s by its [CommentDto]
*
* @param authentication
* @param comment
* @param permission
* @return true if user with [authentication] has [permission] for [comment]
*/
fun hasPermission(
authentication: Authentication?,
comment: CommentDto,
permission: Permission,
): Boolean {
authentication ?: return false
if (authentication.hasRole(Role.SUPER_ADMIN)) {
return true
}
return when (permission) {
Permission.READ -> true
else -> comment.userName == authentication.name
}
}
}
| 201
|
Kotlin
|
3
| 38
|
8f62e13ee6618a36ad2df7ff15ecfb8019ec19d5
| 1,236
|
save-cloud
|
MIT License
|
src/main/kotlin/io/daobab/demo/example/part_c/JoinLeft.kt
|
daobab-projects
| 638,170,318
| false
|
{"Kotlin": 243943, "HTML": 1652, "Java": 667}
|
package io.daobab.demo.example.part_c
import io.daobab.demo.DemoApplication
import io.daobab.demo.base.ServiceBase
import io.daobab.demo.example.part_c.JoinLeft
import io.daobab.model.FlatPlate
import io.daobab.statement.join.JoinType
import org.springframework.boot.SpringApplication
import org.springframework.stereotype.Component
/**
* ---------------------------------------------------------
* Join Left
* ---------------------------------------------------------
* - How to use LEFT_JOIN or other join types
*/
@Component
class JoinLeft : ServiceBase<List<FlatPlate>>() {
override fun call(): List<FlatPlate> {
return way01()
.onEach { log.info(it.toString()) }
}
fun way01(): List<FlatPlate> {
val c = db.tabCustomer
val a = db.tabAddress
return db.select(c.colFirstName(), c.colLastName(), a.colPhone())
.join(JoinType.LEFT_JOIN, a, c.colAddressId())
.flat()
.findMany()
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
SpringApplication.run(DemoApplication::class.java, JoinLeft::class.java.name)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4262bc0412e68ccbd7faaae811f42a0ec041c926
| 1,176
|
daobab-100plus-examples-kotlin
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/visitscheduler/dto/visitnotification/PrisonerReleasedNotificationDto.kt
|
ministryofjustice
| 409,259,375
| false
|
{"Kotlin": 1429494, "PLpgSQL": 148899, "FreeMarker": 14114, "Dockerfile": 1541, "Shell": 238}
|
package uk.gov.justice.digital.hmpps.visitscheduler.dto.visitnotification
import jakarta.validation.constraints.NotBlank
data class PrisonerReleasedNotificationDto(
@NotBlank
val prisonerNumber: String,
@NotBlank
val prisonCode: String,
)
| 0
|
Kotlin
|
2
| 6
|
9ab9fe6020336f21bf879354326df2fef402abc4
| 249
|
visit-scheduler
|
MIT License
|
app/src/main/java/com/frogobox/research/ui/detail/DetailActivity.kt
|
armorycodes
| 556,466,917
| false
| null |
package com.frogobox.research.ui.detail
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import com.frogobox.research.core.BaseBindActivity
import com.frogobox.research.databinding.ActivityDetailBinding
import com.frogobox.research.util.Constant
import com.frogobox.research.util.Constant.Extra.EXTRA_KEY_FRAGMENT
import com.frogobox.research.util.Constant.Extra.RESULT_EXTRA_DATA
import com.frogobox.research.util.Constant.ResultCode.RESULT_CODE_FROM_DETAIL_TO_ACTIVITY
import com.frogobox.research.util.Constant.ResultCode.RESULT_CODE_FROM_DETAIL_TO_FRAGMENT
class DetailActivity : BaseBindActivity<ActivityDetailBinding>() {
companion object {
private val TAG: String = DetailActivity::class.java.simpleName
}
private val viewModel: DetailViewModel by viewModels()
private val extraData: String by lazy {
intent.getStringExtra(Constant.Extra.EXTRA_DATA) ?: ""
}
override fun initBinding(): ActivityDetailBinding {
return ActivityDetailBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
// Call View Model Here
Log.d(TAG, "View Model : ${viewModel::class.java.simpleName}")
}
// TODO : Add your code here
}
override fun initView() {
super.initView()
binding.apply {
btnBackToMain.setOnClickListener {
val message = "Horee $extraData from Detail Activity"
if (intent.hasExtra(EXTRA_KEY_FRAGMENT)) {
setResult(RESULT_CODE_FROM_DETAIL_TO_FRAGMENT, Intent().apply {
putExtra(RESULT_EXTRA_DATA, message)
})
} else {
setResult(RESULT_CODE_FROM_DETAIL_TO_ACTIVITY, Intent().apply {
putExtra(RESULT_EXTRA_DATA, message)
})
}
finish() // finishing activity
}
}
}
override fun initObserver() {
super.initObserver()
viewModel.apply {
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4d8fd945d79f3eb8e9ed9d7af102df5a24177217
| 2,229
|
android-activity-result
|
Apache License 2.0
|
app/src/main/java/com/zeronesky/kcoolweather/db/County.kt
|
zyxins
| 123,904,974
| false
| null |
package com.zeronesky.kcoolweather.db
import org.litepal.crud.DataSupport
/**
* Created by zyxins on 05/03/2018.
*/
class County: DataSupport() {
var id: Int = 0
var countyName: String? = ""
var weatherId: String? = ""
var cityId: Int = 0
}
| 0
|
Kotlin
|
0
| 0
|
f2e84590dbefe9dbb2463310a052234885cef2f8
| 260
|
kcoolweather
|
Apache License 2.0
|
app/src/main/java/com/catscoffeeandkitchen/fitnessjournal/services/TimerService.kt
|
allisonjoycarter
| 563,490,185
| false
| null |
package com.catscoffeeandkitchen.fitnessjournal.services
import android.app.*
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.IBinder
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import com.catscoffeeandkitchen.fitnessjournal.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import timber.log.Timber
class TimerService: LifecycleService() {
private val binder = LocalBinder()
var seconds = 0L
var startingSeconds = 0L
private var timerJob: Job = Job()
companion object {
const val channelId = "TimerChannel"
const val notificationId = 1
}
inner class LocalBinder : Binder() {
// Return this instance of LocalService so clients can call public methods
fun getService(): TimerService = this@TimerService
}
override fun onBind(intent: Intent): IBinder {
super.onBind(intent)
return binder
}
fun cancelTimer() {
Timber.d("*** cancelling previous timer...")
seconds = 0L
timerJob.cancel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
val channel = NotificationChannel(channelId, "Timer", NotificationManager.IMPORTANCE_NONE)
channel.description = "Keep the timers running while you're away from the app."
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(NotificationChannel(channelId, "Timer", NotificationManager.IMPORTANCE_DEFAULT))
val secondsInIntent = intent?.getLongExtra("seconds", 30L) ?: 30L
seconds = secondsInIntent
startingSeconds = secondsInIntent
val notificationManager = TimerNotificationManager()
val notification = notificationManager.createNotification(this, secondsInIntent, secondsInIntent)
startForeground(notificationId, notification)
timerJob = lifecycleScope.launch(Dispatchers.IO) {
(0L..secondsInIntent)
.asFlow()
.onEach { delay(1_000) }
.collect { sec ->
val remaining = secondsInIntent - sec
seconds = remaining
notificationManager.updateNotification(this@TimerService, remaining, secondsInIntent)
if (remaining == 0L) {
val player = MediaPlayer.create(this@TimerService, R.raw.alert_chime)
player.start()
this@TimerService.stopSelf()
}
}
}
return START_STICKY
}
}
| 1
|
Kotlin
|
0
| 0
|
1c52a737c7d3d55da242719cb1759b166e1182a5
| 2,889
|
FitnessJournal
|
MIT License
|
listmaker/app/src/main/java/com/trios2024amdj/listmaker/ui/detail/ui/detail/ListDetailViewModel.kt
|
dougjasper2013
| 841,438,527
| false
|
{"Kotlin": 16673}
|
package com.trios2024amdj.listmaker.ui.detail.ui.detail
import androidx.lifecycle.ViewModel
import com.trios2024amdj.listmaker.models.TaskList
class ListDetailViewModel : ViewModel() {
lateinit var onTaskAdded: (() -> Unit)
lateinit var list: TaskList
fun addTask(task: String) {
list.tasks.add(task)
onTaskAdded.invoke()
}
}
| 0
|
Kotlin
|
0
| 0
|
872de5f0fa513132e86d064100fe8b6bca433dc1
| 361
|
listmakeram
|
MIT License
|
data/src/main/java/com/mkdev/data/source/TransactionCacheDataSource.kt
|
msddev
| 469,005,380
| false
| null |
package com.mkdev.data.source
import com.mkdev.data.models.TransactionEntity
import com.mkdev.data.repository.TransactionCache
import com.mkdev.data.repository.TransactionDataSource
import javax.inject.Inject
class TransactionCacheDataSource @Inject constructor(
private val cache: TransactionCache
) : TransactionDataSource {
override suspend fun getTransactions(): List<TransactionEntity> =
cache.getTransactions()
override suspend fun saveTransaction(data: TransactionEntity) =
cache.saveTransaction(data)
override suspend fun getTransactionCount(): Int =
cache.getTransactionCount()
}
| 0
|
Kotlin
|
0
| 0
|
ca6eacd6b5c6e4e612c766cf9b2df45f6b7ed9d0
| 632
|
Currency-Exchange
|
Apache License 2.0
|
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/TableMoveAbove.kt
|
Konyaco
| 574,321,009
| false
| null |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.TableMoveAbove: ImageVector
get() {
if (_tableMoveAbove != null) {
return _tableMoveAbove!!
}
_tableMoveAbove = fluentIcon(name = "Regular.TableMoveAbove") {
fluentPath {
moveTo(20.25f, 4.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, -1.5f)
lineTo(3.75f, 3.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, 1.5f)
horizontalLineToRelative(16.5f)
close()
moveTo(20.25f, 8.5f)
curveToRelative(0.41f, 0.0f, 0.75f, 0.34f, 0.75f, 0.75f)
verticalLineToRelative(8.5f)
curveToRelative(0.0f, 1.8f, -1.46f, 3.25f, -3.25f, 3.25f)
lineTo(6.25f, 21.0f)
arcTo(3.25f, 3.25f, 0.0f, false, true, 3.0f, 17.75f)
verticalLineToRelative(-8.5f)
curveToRelative(0.0f, -0.41f, 0.34f, -0.75f, 0.75f, -0.75f)
horizontalLineToRelative(4.27f)
arcTo(1.75f, 1.75f, 0.0f, false, false, 10.0f, 10.48f)
lineTo(10.0f, 14.0f)
horizontalLineToRelative(4.0f)
verticalLineToRelative(-3.52f)
arcToRelative(1.75f, 1.75f, 0.0f, false, false, 1.98f, -1.98f)
horizontalLineToRelative(4.27f)
close()
moveTo(8.5f, 10.0f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(4.0f)
horizontalLineToRelative(4.0f)
verticalLineToRelative(-4.0f)
close()
moveTo(8.5f, 15.5f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(2.25f)
curveToRelative(0.0f, 0.97f, 0.78f, 1.75f, 1.75f, 1.75f)
lineTo(8.5f, 19.5f)
verticalLineToRelative(-4.0f)
close()
moveTo(14.0f, 19.5f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(4.0f)
horizontalLineToRelative(4.0f)
close()
moveTo(15.5f, 19.5f)
horizontalLineToRelative(2.25f)
curveToRelative(0.97f, 0.0f, 1.75f, -0.78f, 1.75f, -1.75f)
lineTo(19.5f, 15.5f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(4.0f)
close()
moveTo(15.5f, 10.0f)
verticalLineToRelative(4.0f)
horizontalLineToRelative(4.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(-4.0f)
close()
moveTo(14.81f, 9.25f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.06f, 0.06f)
lineToRelative(-1.0f, -0.89f)
verticalLineToRelative(2.83f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.5f, 0.0f)
lineTo(11.25f, 8.42f)
lineToRelative(-1.0f, 0.9f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.0f, -1.13f)
lineToRelative(2.25f, -2.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 1.0f, 0.0f)
lineToRelative(2.25f, 2.0f)
curveToRelative(0.3f, 0.27f, 0.34f, 0.75f, 0.06f, 1.06f)
close()
}
}
return _tableMoveAbove!!
}
private var _tableMoveAbove: ImageVector? = null
| 1
|
Kotlin
|
3
| 83
|
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
| 3,809
|
compose-fluent-ui
|
Apache License 2.0
|
order/src/main/kotlin/dev/yn/restaraunt/user/aggregation/UserAggregation.kt
|
dgoetsch
| 100,337,343
| false
| null |
/*
* Copyright 2017 Devyn Goetsch
*
* 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.yn.restauant.user.aggregation
import dev.yn.entity.domain.EntityError
import dev.yn.event.aggregator.SimpleAggregator
import dev.yn.event.serialization.Serialization
import dev.yn.restauant.user.domain.UserEvent
import dev.yn.restauant.user.domain.UserState
import dev.yn.restauant.user.serialization.UserEventSerialization
class UserAggregation(userStateSerialization: Serialization<EntityError, UserState>,
userEventSerialization: UserEventSerialization): SimpleAggregator<UserState, UserEvent>(userStateSerialization, userEventSerialization){
override fun incorporate(state: UserState?): (UserEvent) -> UserState? = { event ->
state?.let {
if(state.deleted) {
state
} else {
when (event) {
is UserEvent.UpdateEmail -> state.updateEmail(event)
is UserEvent.UpdateName -> state.updateName(event)
is UserEvent.UpdateRoles -> state.updateRoles(event)
is UserEvent.DeleteUser -> state.delete(event)
else -> state
}
}
} ?: when(event) {
is UserEvent.Create -> event.initialState
else -> state
}
}
}
| 0
|
Kotlin
|
0
| 5
|
afe6b2caba24b2a08347dc508d019a70bdeba10f
| 1,899
|
akka-vertx-demo
|
Apache License 2.0
|
app/src/main/java/com/example/georeality/MapFragment.kt
|
RoopeVaarama
| 297,615,110
| false
|
{"Kotlin": 68378}
|
package com.example.georeality
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.gson.Gson
import kotlinx.android.synthetic.main.fragment_map.*
/**
* @author <NAME>, <NAME>
* @since 24.09.2020
*/
/**
* MapFragment includes all Google Maps related implementation
*/
class MapFragment : Fragment(), GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener, OnMapReadyCallback {
private lateinit var navController : NavController
private lateinit var lastLocation: Location
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var map : GoogleMap
private var dbViewModel : DBViewModel? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_map, container, false)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity().applicationContext)
navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment)
val mapFragment =
childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(this)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fab.setOnClickListener(fabClickListener)
}
override fun onMapReady(googleMap: GoogleMap?) {
map = googleMap ?: return
googleMap.setOnMyLocationButtonClickListener(this)
googleMap.setOnMyLocationClickListener(this)
enableMyLocation()
loadEntitys()
map.setInfoWindowAdapter(CustomInfoWindowAdapter(requireActivity()))
map.setOnInfoWindowClickListener { marker ->
val startPoint = lastLocation
val endPoint = Location(LocationManager.GPS_PROVIDER)
endPoint.latitude = marker.position.latitude
endPoint.longitude = marker.position.longitude
val dist = startPoint.distanceTo(endPoint)
if (dist < 15.0) {
MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.cache_dialog_title)
.setMessage(resources.getString(R.string.cache_dialog_message))
.setNegativeButton(resources.getString(R.string.cache_dialog_cancel)) { _, _ ->
return@setNegativeButton
}
.setPositiveButton(resources.getString(R.string.cache_dialog_open)) { _, _ ->
val gson = Gson()
if (marker.tag is ARMarker) {
val markerClass = marker.tag as ARMarker
val markerJsonString = gson.toJson(markerClass)
Log.d("Tags", markerClass.toString())
val action = MapFragmentDirections.actionMapFragmentToArFragment(markerJsonString)
navController.navigate(action)
} else if (marker.tag is AudioMarker) {
val markerClass = marker.tag as AudioMarker
val markerJsonString = gson.toJson(markerClass)
Log.d("Tags", markerJsonString)
val action = MapFragmentDirections.actionMapFragmentToAudioListeningFragment(markerJsonString)
navController.navigate(action)
}
}
.show()
}
}
map.setOnMarkerClickListener { marker ->
val startPoint = lastLocation
val endPoint = Location(LocationManager.GPS_PROVIDER)
endPoint.latitude = marker.position.latitude
endPoint.longitude = marker.position.longitude
val dist = startPoint.distanceTo(endPoint)
if (dist < 15.0) {
Log.d("marker", "onclick in range")
Log.d("marker", "distance to marker: $dist meters")
marker.snippet = "Click here to open cache!"
marker.showInfoWindow()
} else {
marker.snippet = "Too far away!"
val distance = String.format("%.0f", dist-15)
Toast.makeText(requireContext(), getString(R.string.distanceText, distance), Toast.LENGTH_LONG).show()
marker.showInfoWindow()
Log.d("marker", "onclick")
Log.d("marker", "distance to marker: $dist meters")
}
true
}
}
//Enables My Location layer if the fine location permission has been granted.
private fun enableMyLocation() {
if (!::map.isInitialized) return
if (ContextCompat.checkSelfPermission(requireActivity().applicationContext, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
) {
map.isMyLocationEnabled = true
} else {
//Permission to access the location is missing. Show rationale and request permission
if ((Build.VERSION.SDK_INT >= 26 && ContextCompat.checkSelfPermission(
requireActivity().applicationContext,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED)
) {
ActivityCompat.requestPermissions(
requireActivity(),
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
0
)
}
}
fusedLocationClient.lastLocation.addOnSuccessListener(requireActivity()) { location ->
if (location != null) {
lastLocation = location
val currentLatLng = LatLng(location.latitude, location.longitude)
map.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 12f))
}
}
}
//Fab listener for adding markers and entitys
@SuppressLint("MissingPermission")
private val fabClickListener = View.OnClickListener {
fusedLocationClient.lastLocation.addOnSuccessListener(requireActivity()) { location ->
if (location != null) {
lastLocation = location
val currentLatLng = LatLng(location.latitude, location.longitude)
map.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 12f))
}
/*Toast.makeText(
requireActivity().applicationContext,
"Current location:${lastLocation.latitude} ${lastLocation.longitude}",
Toast.LENGTH_LONG
).show()*/
val locationdata = "${lastLocation.latitude}, ${lastLocation.longitude}"
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
val editor = sharedPref?.edit()
editor?.putString("locationData", locationdata)
editor?.commit()
navController = Navigation.findNavController(it)
navController.navigate(R.id.action_mapFragment_to_cacheCreationFragment)
}
}
private fun loadEntitys(){
dbViewModel = Database.dbViewModel
dbViewModel!!.audioMarkers.observe(viewLifecycleOwner, {
Log.d("onCreateView", it.toString())
// Create audio markers on map
for (i in it.indices){
Log.d("marker", "${it[i].latitude!!} ${it[i].longitude}" )
map.addMarker(
MarkerOptions()
.position(LatLng(it[i].latitude!!, it[i].longitude!!))
.title(it[i].title)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.snippet("${it[i].creator} \n asdasd")
).tag = it[i]
}
})
dbViewModel!!.arMarkers.observe(viewLifecycleOwner, {
Log.d("OnCreateView", it.toString())
// Create AR markers on map
for (i in it.indices){
Log.d("marker", "${it[i].latitude!!} ${it[i].longitude}" )
map.addMarker(
MarkerOptions()
.position(LatLng(it[i].latitude!!, it[i].longitude!!))
.title(it[i].title)
.snippet("${it[i].creator} \n asdasd")
).tag = it[i]
}
})
}
override fun onMyLocationButtonClick(): Boolean {
return false
}
override fun onMyLocationClick(location: Location) {
}
}
| 0
|
Kotlin
|
0
| 0
|
553996945609cc1ce4e8e4008885afd37dd7f77a
| 9,871
|
GeoReality
|
Apache License 2.0
|
app/src/main/java/com/mycompany/advioo/api/PinfoAPI.kt
|
demirelarda
| 609,874,629
| false
| null |
package com.mycompany.advioo.api
import com.mycompany.advioo.models.pinfo.PinfoResponse
import com.mycompany.advioo.util.Util.GET_PINFO
import retrofit2.Response
import retrofit2.http.GET
interface PinfoAPI {
@GET(GET_PINFO)
suspend fun getPinfos(): Response<PinfoResponse>
}
| 0
|
Kotlin
|
0
| 0
|
092240cd5de976186b94312eddf4f03d1c553bfa
| 287
|
Advioo
|
FSF All Permissive License
|
src/algorithmdesignmanualbook/graph/PrimMinSpanningTree.kt
|
realpacific
| 234,499,820
| false
| null |
package algorithmdesignmanualbook.graph
import _utils.UseCommentAsDocumentation
/**
* Solution: https://www.programiz.com/dsa/prim-algorithm
*
* Given vertices with weighted edges, from start vertex, chose the edge with min edge such that it doesnt form cycle.
*/
@UseCommentAsDocumentation
fun prim(graph: Array<Array<Int>>, vertex: Int) {
var sum = 0
var numberOfEdges = 0
val selected = Array(vertex) { false }
// Start from the root
selected[0] = true
// Number of edge is always less than V-1 and no cycles
while (numberOfEdges < vertex - 1) {
var min = Integer.MAX_VALUE
var x = 0 // row
var y = 0 // col
for (i in 0 until vertex) {
// min cost edge is always selected
if (selected[i]) {
for (j in 0 until vertex) {
if (!selected[j] && graph[i][j] != 0 && min > graph[i][j]) {
// if min, record it
min = graph[i][j]
x = i
y = j
}
}
}
}
println("$x $y : ${graph[x][y]}")
sum += graph[x][y]
numberOfEdges++
// select the min cost edge
selected[y] = true
}
println("Sum = $sum")
}
fun main() {
// Adjacent matrix
val matrix = arrayOf(
arrayOf(0, 9, 75, 0, 0),
arrayOf(9, 0, 95, 19, 42),
arrayOf(75, 95, 0, 51, 66),
arrayOf(0, 19, 51, 0, 31),
arrayOf(0, 42, 66, 31, 0)
)
prim(matrix, matrix.size)
}
| 4
| null |
5
| 93
|
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
| 1,586
|
algorithms
|
MIT License
|
core/src/main/java/io/github/thibaultbee/streampack/streamers/interfaces/IFileStreamer.kt
|
ThibaultBee
| 262,623,449
| false
| null |
/*
* Copyright (C) 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.thibaultbee.streampack.streamers.interfaces
import java.io.File
import java.io.OutputStream
interface IFileStreamer {
/**
* [File] where o write the stream.
*/
var file: File?
/**
* [OutputStream] where to write the stream.
*/
var outputStream: OutputStream?
}
| 5
|
Kotlin
|
37
| 99
|
3a9af52fd6f34c2dac308ece85a2a38c6d64760e
| 908
|
StreamPack
|
Apache License 2.0
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/modules/driveTrain/DriveTrain.kt
|
WoEN239
| 850,255,356
| false
|
{"Kotlin": 92236, "Java": 48138}
|
package org.firstinspires.ftc.teamcode.modules.driveTrain
import com.qualcomm.robotcore.hardware.DcMotorEx
import com.qualcomm.robotcore.hardware.DcMotorSimple
import org.firstinspires.ftc.teamcode.collectors.BaseCollector
import org.firstinspires.ftc.teamcode.collectors.IRobotModule
import org.firstinspires.ftc.teamcode.modules.navigation.gyro.MergeGyro
import org.firstinspires.ftc.teamcode.modules.navigation.odometry.MergeOdometry
import org.firstinspires.ftc.teamcode.utils.configs.Configs
import org.firstinspires.ftc.teamcode.utils.pidRegulator.PIDRegulator
import org.firstinspires.ftc.teamcode.utils.units.Vec2
object DriveTrain : IRobotModule {
private lateinit var _leftForwardDrive: DcMotorEx
private lateinit var _rightForwardDrive: DcMotorEx
private lateinit var _leftBackDrive: DcMotorEx
private lateinit var _rightBackDrive: DcMotorEx
private val _velocityPidfForward = PIDRegulator(Configs.DriveTrainConfig.VELOCITY_PIDF_FORWARD)
private val _velocityPidfSide = PIDRegulator(Configs.DriveTrainConfig.VELOCITY_PIDF_SIDE)
private val _velocityPidfRotate = PIDRegulator(Configs.DriveTrainConfig.VELOCITY_PIDF_ROTATE)
override fun init(collector: BaseCollector) {
_leftForwardDrive = collector.devices.leftForwardDrive
_rightForwardDrive = collector.devices.rightForwardDrive
_leftBackDrive = collector.devices.leftBackDrive
_rightBackDrive = collector.devices.rightBackDrive
_rightBackDrive.direction = DcMotorSimple.Direction.REVERSE
_rightForwardDrive.direction = DcMotorSimple.Direction.REVERSE
}
private fun driveSimpleDirection(direction: Vec2, rotate: Double) {
_leftForwardDrive.power = direction.x - direction.y - rotate
_rightBackDrive.power = direction.x - direction.y + rotate
_leftBackDrive.power = direction.x + direction.y - rotate
_rightForwardDrive.power = direction.x + direction.y + rotate
}
private var _targetDirectionVelocity = Vec2.ZERO
private var _targetRotateVelocity = 0.0
fun driveTicksDirection(direction: Vec2, rotate: Double) {
_targetDirectionVelocity = direction
_targetRotateVelocity = rotate
}
fun driveCmDirection(direction: Vec2, rotate: Double) = driveTicksDirection(
Vec2(
direction.x / Configs.OdometryConfig.ODOMETER_DIAMETER * Configs.OdometryConfig.ODOMETER_TICKS,
direction.y / Configs.OdometryConfig.ODOMETER_DIAMETER * Configs.OdometryConfig.ODOMETER_TICKS * Configs.DriveTrainConfig.Y_LAG
),
rotate * Configs.DriveTrainConfig.WHEEL_CENTER_RADIUS / Configs.OdometryConfig.ODOMETER_DIAMETER * Configs.OdometryConfig.ODOMETER_TICKS
)
fun drivePowerDirection(direction: Vec2, rotate: Double) =/* driveTicksDirection(
direction * Vec2(Configs.DriveTrainConfig.MAX_SPEED_FORWARD, Configs.DriveTrainConfig.MAX_SPEED_SIDE), rotate * Configs.DriveTrainConfig.MAX_SPEED_TURN)*/
driveSimpleDirection(direction, rotate)
override fun stop(){
drivePowerDirection(Vec2(0.0, 0.0), 0.0)
}
override fun update() {
/*driveSimpleDirection(Vec2(
_velocityPidfForward.update(_targetDirectionVelocity.x - MergeOdometry.velocity.x, _targetDirectionVelocity.x),
_velocityPidfSide.update(_targetDirectionVelocity.y - MergeOdometry.velocity.y, _targetDirectionVelocity.y)),
_velocityPidfRotate.update(_targetRotateVelocity - MergeGyro.velocity, MergeGyro.velocity))*/
}
}
| 1
|
Kotlin
|
0
| 1
|
ca7b06e73585bb3a1d65ccd4f604d1d7576f2b86
| 3,519
|
IntoTheDeep18742
|
BSD 3-Clause Clear License
|
app/src/main/java/com/cb/meapps/domain/usecase/GetAdditionalPaymentsUseCase.kt
|
cbedoy
| 871,038,589
| false
|
{"Kotlin": 170130}
|
package com.cb.meapps.domain.usecase
import com.cb.meapps.data.repository.AdditionalPaymentsRepository
import com.cb.meapps.data.repository.CardsRepository
import com.cb.meapps.domain.fake.IsFakeDataEnabledUseCase
import com.cb.meapps.domain.fake.getFakeAdditionalPayments
import com.cb.meapps.domain.fake.getFakeCards
import com.cb.meapps.domain.model.AdditionalPayment
import com.cb.meapps.domain.model.Card
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class GetAdditionalPaymentsUseCase @Inject constructor(
private val isFakeDataEnabledUseCase: IsFakeDataEnabledUseCase,
private val repository: AdditionalPaymentsRepository
) {
suspend operator fun invoke(): Flow<List<AdditionalPayment>> {
return repository.getAll()
.map { entityList ->
if (isFakeDataEnabledUseCase()) {
getFakeAdditionalPayments()
} else {
entityList.map { entity ->
AdditionalPayment(
id = entity.id,
name = entity.name,
day = entity.day,
value = entity.value
)
}
}
}
.distinctUntilChanged()
.catch {
emit(emptyList())
}
}
}
| 0
|
Kotlin
|
0
| 2
|
bdb052be05a4d7583e27e3d7d5105ce1489e54d3
| 1,511
|
DayMate
|
Apache License 2.0
|
app/src/main/java/com/utkarshambassadorfsm/features/damageProduct/api/GetDamageProductListRegRepository.kt
|
DebashisINT
| 702,488,999
| false
|
{"Kotlin": 13578428, "Java": 995803}
|
package com.utkarshambassadorfsm.features.damageProduct.api
import android.content.Context
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import com.utkarshambassadorfsm.app.FileUtils
import com.utkarshambassadorfsm.base.BaseResponse
import com.utkarshambassadorfsm.features.NewQuotation.model.*
import com.utkarshambassadorfsm.features.addshop.model.AddShopRequestData
import com.utkarshambassadorfsm.features.addshop.model.AddShopResponse
import com.utkarshambassadorfsm.features.damageProduct.model.DamageProductResponseModel
import com.utkarshambassadorfsm.features.damageProduct.model.delBreakageReq
import com.utkarshambassadorfsm.features.damageProduct.model.viewAllBreakageReq
import com.utkarshambassadorfsm.features.login.model.userconfig.UserConfigResponseModel
import com.utkarshambassadorfsm.features.myjobs.model.WIPImageSubmit
import com.utkarshambassadorfsm.features.photoReg.model.*
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.gson.Gson
import io.reactivex.Observable
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
class GetDamageProductListRegRepository(val apiService : GetDamageProductListApi) {
fun viewBreakage(req: viewAllBreakageReq): Observable<DamageProductResponseModel> {
return apiService.viewBreakage(req)
}
fun delBreakage(req: delBreakageReq): Observable<BaseResponse>{
return apiService.BreakageDel(req.user_id!!,req.breakage_number!!,req.session_token!!)
}
}
| 0
|
Kotlin
|
0
| 0
|
620e44c4b91351436f99da862ebae19eae8c1eaa
| 1,538
|
UtkarshClasses
|
Apache License 2.0
|
app/src/main/java/com/kursx/chart/ui/screen/Input.kt
|
KursX
| 676,468,282
| false
| null |
package com.kursx.chart.ui.screen
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Button
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.kursx.chart.R
import com.kursx.chart.ui.MainViewModel
import com.kursx.chart.ui.MainViewModelContract
import kotlinx.coroutines.delay
@Composable
fun Input(
initialValue: String,
onValueChanged: (String) -> Unit,
modifier: Modifier = Modifier,
) {
val focusRequester = remember { FocusRequester() }
var input by rememberSaveable { mutableStateOf(initialValue) }
val viewModel: MainViewModel = hiltViewModel()
val onClickSubmit = {
viewModel.sendEvent(MainViewModelContract.Event.OnSubmitClick(input.toInt()))
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier
.padding(16.dp)
.fillMaxWidth(),
) {
Text(stringResource(R.string.info_block))
OutlinedTextField(
value = TextFieldValue(input, TextRange(input.length)),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done,
),
keyboardActions = KeyboardActions(
onDone = { onClickSubmit() },
),
onValueChange = { value ->
input = value.text.filter { it.isDigit() }
onValueChanged(input)
},
placeholder = {
Text(stringResource(R.string.placeholder))
},
modifier = Modifier
.padding(vertical = 16.dp)
.focusRequester(focusRequester),
)
if (input.isNotEmpty()) {
Button(onClick = onClickSubmit) {
Text(text = stringResource(R.string.go))
}
}
}
LaunchedEffect(Unit) {
delay(300)
focusRequester.requestFocus()
}
}
@Preview
@Composable
private fun Preview() {
Input("", {})
}
| 0
|
Kotlin
|
0
| 0
|
065d6fb5275ab614ef4ebd70225fa8d75cfc052a
| 3,149
|
points_demo
|
Apache License 2.0
|
src/main/kotlin/com/sbl/sulmun2yong/survey/domain/reward/NotStartedDrawSetting.kt
|
SUIN-BUNDANG-LINE
| 819,257,518
| false
|
{"Kotlin": 349771}
|
package com.sbl.sulmun2yong.survey.domain.reward
/** 시작 전 상태의 불완전한 리워드 지급 설정 */
data class NotStartedDrawSetting(
override val type: RewardSettingType,
override val rewards: List<Reward>,
override val targetParticipantCount: Int?,
override val finishedAt: FinishedAt?,
) : RewardSetting
| 0
|
Kotlin
|
1
| 3
|
e2203ff721fcde4bcdcc7e21b8aeb0c849dae17d
| 304
|
Backend
|
MIT License
|
data/models/src/commonMain/kotlin/dev/avatsav/linkding/data/model/Errors.kt
|
avatsav
| 576,855,763
| false
|
{"Kotlin": 255958, "Swift": 2031}
|
package dev.avatsav.linkding.data.model
data class BookmarkError(val message: String)
sealed class AuthError(open val message: String) {
data class InvalidHostname(override val message: String) : AuthError(message)
data class InvalidApiKey(override val message: String) : AuthError(message)
data class Other(override val message: String) : AuthError(message)
}
| 2
|
Kotlin
|
0
| 9
|
73518b1652503edc4ba4323922281bc616a6be8f
| 375
|
linkding-apps
|
MIT License
|
BLEApplication/app/src/main/java/com/demo/bleapplication/ble/BluetoothServer.kt
|
Zz-m
| 82,144,524
| false
|
{"Text": 9, "Markdown": 10, "C++": 6, "CMake": 4, "C": 26, "Ignore List": 40, "XML": 136, "Maven POM": 31, "Java": 215, "Makefile": 2, "CSS": 56, "JavaScript": 31, "JSON with Comments": 16, "JSON": 57, "EditorConfig": 7, "Browserslist": 7, "HTML": 47, "SVG": 2, "Gradle": 12, "Shell": 5, "Batchfile": 5, "INI": 6, "Groovy": 3, "AsciiDoc": 1, "Java Properties": 5, "Go": 11, "TSX": 2, "Ruby": 2, "Kotlin": 44, "Dotenv": 1, "OpenStep Property List": 2, "Objective-C": 3, "Objective-C++": 1, "Gradle Kotlin DSL": 3, "Proguard": 1, "SQL": 4, "Java Server Pages": 1, "Microsoft Visual Studio Solution": 1, "C#": 6, "Protocol Buffer": 64}
|
package com.demo.bleapplication.ble
import android.annotation.SuppressLint
import android.bluetooth.BluetoothGattService
import android.bluetooth.BluetoothManager
import android.bluetooth.le.AdvertiseData
import android.bluetooth.le.AdvertiseSettings
import android.content.Context
import android.os.Build
import android.provider.SyncStateContract
import com.demo.bleapplication.YOUR_MANUFACTURER_ID
import com.demo.bleapplication.data.UserProfileData
import com.demo.bleapplication.viewModel.GetData
import com.welie.blessed.AdvertiseError
import com.welie.blessed.BluetoothPeripheralManager
import com.welie.blessed.BluetoothPeripheralManagerCallback
import com.welie.blessed.GattStatus
import timber.log.Timber
@SuppressLint("MissingPermission")
class BluetoothServer(private val context: Context) {
var isInitialized = false
var peripheralManager: BluetoothPeripheralManager
private val bluetoothManager: BluetoothManager
private val peripheralManagerCallback: BluetoothPeripheralManagerCallback =
object : BluetoothPeripheralManagerCallback() {
override fun onServiceAdded(status: GattStatus, service: BluetoothGattService) {}
override fun onAdvertisingStarted(settingsInEffect: AdvertiseSettings) {}
override fun onAdvertiseFailure(advertiseError: AdvertiseError) {}
override fun onAdvertisingStopped() {}
}
fun startAdvertising() {
val advertiseSettings = AdvertiseSettings.Builder()
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
.setConnectable(true)
.setTimeout(0)
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_ULTRA_LOW)
.build()
Timber.tag("Local User:").d(getLocalData().toString())
val advertiseData = AdvertiseData.Builder()
.setIncludeTxPowerLevel(true)
.setIncludeDeviceName(true)
.addManufacturerData(YOUR_MANUFACTURER_ID, UserProfileData.toByteArray(getLocalData()))
.build() //Create payload
val scanResponse = AdvertiseData.Builder()
.setIncludeDeviceName(true)
.build()
peripheralManager.startAdvertising(advertiseSettings, advertiseData, scanResponse)
}
fun stopAdvertising() {
if (peripheralManager.isAdvertising) {
peripheralManager.stopAdvertising()
}
}
private fun getLocalData(): UserProfileData {
return UserProfileData(
IsMan = GetData.IsMan,
IsLookingForMan = GetData.IsLookingForMan,
FriendsToTalk = GetData.FriendsToTalk,
LongRelationsship = GetData.LongRelationsship,
TouristInTown = GetData.TouristInTown,
JustSexualIntentions = GetData.JustSexualIntentions,
ProfilSliderPosition = GetData.ProfilSliderPosition,
Parameters = GetData.Parameters,
LookingForSliderPosition = GetData.LookingForSliderPosition
)
}
fun initialize() {
val bluetoothAdapter = bluetoothManager.adapter
bluetoothAdapter.name = "MyBLE"
peripheralManager.openGattServer()
peripheralManager.removeAllServices()
isInitialized = true
}
init {
Timber.plant(Timber.DebugTree())
bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
peripheralManager =
BluetoothPeripheralManager(context, bluetoothManager, peripheralManagerCallback)
}
companion object {
@SuppressLint("StaticFieldLeak")
private var instance: BluetoothServer? = null
@JvmStatic
@Synchronized
fun getInstance(context: Context): BluetoothServer {
if (instance == null) {
instance = BluetoothServer(context.applicationContext)
}
return instance!!
}
}
}
| 0
|
Java
|
0
| 0
|
9722d96d2689d57091ced32eff288c9c8c1e0503
| 3,919
|
Practice-collection
|
MIT License
|
pop-miners/altchain-pop-miner/src/main/kotlin/org/veriblock/miners/pop/serialization/MessageSerializer.kt
|
VeriBlock
| 179,742,374
| false
| null |
// VeriBlock Blockchain Project
// Copyright 2017-2018 VeriBlock, Inc
// Copyright 2018-2021 <NAME>
// All rights reserved.
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
package org.veriblock.miners.pop.serialization
import nodecore.api.grpc.RpcBlock
import nodecore.api.grpc.RpcBlockHeader
import nodecore.api.grpc.RpcSignedMultisigTransaction
import nodecore.api.grpc.RpcSignedTransaction
import nodecore.api.grpc.RpcTransactionUnion
import nodecore.api.grpc.RpcVeriBlockPublication
import org.veriblock.sdk.extensions.ByteStringAddressUtility
import org.veriblock.sdk.extensions.ByteStringUtility
import org.veriblock.sdk.extensions.asVbkPreviousBlockHash
import org.veriblock.sdk.extensions.asVbkPreviousKeystoneHash
import org.veriblock.core.utilities.createLogger
import org.veriblock.sdk.models.Address
import org.veriblock.sdk.models.BitcoinTransaction
import org.veriblock.sdk.models.MerklePath
import org.veriblock.sdk.models.Output
import org.veriblock.core.crypto.asBtcHash
import org.veriblock.core.crypto.asTruncatedMerkleRoot
import org.veriblock.sdk.models.BlockMetaPackage
import org.veriblock.sdk.models.FullBlock
import org.veriblock.sdk.models.VeriBlockBlock
import org.veriblock.sdk.models.VeriBlockMerklePath
import org.veriblock.sdk.models.VeriBlockPopTransaction
import org.veriblock.sdk.models.VeriBlockPublication
import org.veriblock.sdk.models.VeriBlockTransaction
import org.veriblock.sdk.models.asCoin
import org.veriblock.sdk.services.SerializeDeserializeService
import org.veriblock.spv.model.StandardTransaction
private val logger = createLogger {}
fun RpcBlockHeader.deserialize(): VeriBlockBlock =
SerializeDeserializeService.parseVeriBlockBlock(header.toByteArray())
private fun RpcTransactionUnion.deserializeNormalTransaction(transactionPrefix: Byte?): VeriBlockTransaction {
return when (transactionCase) {
RpcTransactionUnion.TransactionCase.SIGNED -> signed.deserializeStandardTransaction(transactionPrefix)
RpcTransactionUnion.TransactionCase.SIGNED_MULTISIG -> signedMultisig.deserializeMultisigTransaction(transactionPrefix)
else -> error("Can't deserialize a transaction with a transaction case: $transactionCase.") // Should be impossible
}
}
fun RpcTransactionUnion.deserializePopTransaction(transactionPrefix: Byte?): VeriBlockPopTransaction =
signed.deserializePopTransaction(transactionPrefix)
fun RpcBlock.deserialize(transactionPrefix: Byte?): FullBlock {
return FullBlock(
number,
version.toShort(),
previousHash.asVbkPreviousBlockHash(),
secondPreviousHash.asVbkPreviousKeystoneHash(),
thirdPreviousHash.asVbkPreviousKeystoneHash(),
ByteStringUtility.byteStringToHex(merkleRoot).asTruncatedMerkleRoot(),
timestamp,
encodedDifficulty,
winningNonce,
regularTransactionsList.map { tx -> tx.deserializeNormalTransaction(transactionPrefix) },
popTransactionsList.map { tx -> tx.deserializePopTransaction(transactionPrefix) },
BlockMetaPackage(blockContentMetapackage.hash.toByteArray().asBtcHash())
)
}
fun RpcSignedTransaction.deserializePopTransaction(transactionPrefix: Byte?): VeriBlockPopTransaction {
val txMessage = transaction
return VeriBlockPopTransaction(
Address(ByteStringAddressUtility.parseProperAddressTypeAutomatically(txMessage.sourceAddress)),
SerializeDeserializeService.parseVeriBlockBlock(txMessage.endorsedBlockHeader.toByteArray()),
BitcoinTransaction(txMessage.bitcoinTransaction.toByteArray()),
MerklePath(txMessage.merklePath),
SerializeDeserializeService.parseBitcoinBlock(txMessage.bitcoinBlockHeaderOfProof.header.toByteArray()),
txMessage.contextBitcoinBlockHeadersList.map { header ->
SerializeDeserializeService.parseBitcoinBlock(header.header.toByteArray())
},
signature.toByteArray(),
publicKey.toByteArray(),
transactionPrefix
)
}
fun StandardTransaction.deserializeStandardTransaction(transactionPrefix: Byte?): VeriBlockTransaction {
return VeriBlockTransaction(
1, // STANDARD
Address(inputAddress!!.get()),
inputAmount!!,
getOutputs().map { o ->
Output.of(o.address.get(), o.amount.atomicUnits)
},
getSignatureIndex(),
SerializeDeserializeService.parsePublicationData(data!!),
signature!!,
publicKey!!,
transactionPrefix
)
}
fun RpcSignedTransaction.deserializeStandardTransaction(transactionPrefix: Byte?): VeriBlockTransaction {
val txMessage = transaction
return VeriBlockTransaction(
txMessage.type.number.toByte(),
Address(ByteStringAddressUtility.parseProperAddressTypeAutomatically(txMessage.sourceAddress)),
txMessage.sourceAmount.asCoin(),
txMessage.outputsList.map { o ->
Output.of(ByteStringAddressUtility.parseProperAddressTypeAutomatically(o.address), o.amount)
},
signatureIndex,
SerializeDeserializeService.parsePublicationData(txMessage.data.toByteArray()),
signature.toByteArray(),
publicKey.toByteArray(),
transactionPrefix
)
}
fun RpcSignedMultisigTransaction.deserializeMultisigTransaction(transactionPrefix: Byte?): VeriBlockTransaction {
val txMessage = transaction
return VeriBlockTransaction(
txMessage.type.number.toByte(),
Address(ByteStringAddressUtility.parseProperAddressTypeAutomatically(txMessage.sourceAddress)),
txMessage.sourceAmount.asCoin(),
txMessage.outputsList.map { o ->
Output.of(ByteStringAddressUtility.parseProperAddressTypeAutomatically(o.address), o.amount)
},
signatureIndex,
SerializeDeserializeService.parsePublicationData(txMessage.data.toByteArray()),
ByteArray(0),
ByteArray(0),
transactionPrefix
)
}
fun RpcVeriBlockPublication.deserialize(transactionPrefix: Byte?): VeriBlockPublication {
val context: List<VeriBlockBlock> =
contextToEndorsedList.map {
SerializeDeserializeService.parseVeriBlockBlock(it.toByteArray())
} +
SerializeDeserializeService.parseVeriBlockBlock(popTransaction.transaction.endorsedBlockHeader.toByteArray()) +
contextToContainingList.map {
SerializeDeserializeService.parseVeriBlockBlock(it.toByteArray())
}
return VeriBlockPublication(
popTransaction.deserializePopTransaction(transactionPrefix),
VeriBlockMerklePath(compactMerklePath),
SerializeDeserializeService.parseVeriBlockBlock(containingBlock.toByteArray()),
context
)
}
| 72
| null |
16
| 12
|
ef06c51c1410ba59da13403b65e367b21dcfed21
| 6,813
|
nodecore
|
MIT License
|
src/main/kotlin/dev/epicsquid/superiorshields/capability/SuperiorShieldCapProvider.kt
|
EpicSquid
| 153,854,411
| false
| null |
package dev.epicsquid.superiorshields.capability
import dev.epicsquid.superiorshields.registry.CapabilityRegistry
import net.minecraft.core.Direction
import net.minecraft.nbt.CompoundTag
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.common.capabilities.ICapabilityProvider
import net.minecraftforge.common.util.INBTSerializable
import net.minecraftforge.common.util.LazyOptional
class SuperiorShieldCapProvider : ICapabilityProvider, INBTSerializable<CompoundTag> {
private val shield = SuperiorShieldCapImpl()
private val op: LazyOptional<SuperiorShieldCap> = LazyOptional.of { shield }
override fun <T : Any?> getCapability(cap: Capability<T>, side: Direction?): LazyOptional<T> =
CapabilityRegistry.SUPERIOR_SHIELD_CAP.orEmpty(cap, op)
override fun serializeNBT(): CompoundTag = shield.serializeNBT()
override fun deserializeNBT(nbt: CompoundTag) = shield.deserializeNBT(nbt)
}
| 8
|
Kotlin
|
7
| 7
|
22f893a47e82493cbd02bd7c41b5c747ba9b7cbb
| 931
|
SuperiorShields
|
MIT License
|
android/app/src/main/java/com/francesco/montano/notify/MainActivity.kt
|
Monti03
| 240,569,383
| false
| null |
package com.francesco.montano.notify
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_main.*
import android.content.Context.MODE_PRIVATE
import android.R.id.edit
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent.getActivity
import android.content.Context
import com.google.firebase.iid.FirebaseInstanceId
import androidx.core.app.ComponentActivity
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.os.Build
import android.util.JsonToken
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.firebase.functions.FirebaseFunctions
import com.google.firebase.functions.FirebaseFunctionsException
class MainActivity : AppCompatActivity() {
private lateinit var functions: FirebaseFunctions
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
createNotificationChannel()
val fms = MyFirebaseMessagingService()
val sharedPref = this?.getPreferences(Context.MODE_PRIVATE)
val oldId = sharedPref.getString("ID", "defaultValue")
Log.d("before", oldId)
if(oldId == "defaultValue"){ // I have to generate a new token
//var progressBar = findViewById<ProgressBar>(R.id.progressBar) as ProgressBar
Thread(Runnable {
// dummy thread mimicking some operation whose progress cannot be tracked
// display the indefinite progressbar
this@MainActivity.runOnUiThread(java.lang.Runnable {
findViewById<ProgressBar>(R.id.progressBar).visibility = View.VISIBLE
})
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
val newToken = instanceIdResult.token
Log.d("newToken", newToken)
this.getPreferences(Context.MODE_PRIVATE).edit().putString("fb", newToken).apply()
functions = FirebaseFunctions.getInstance()
addToken(newToken)
.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
val e = task.exception
Log.e("getting the new id", e.toString())
} else {
Log.d("getting the new id", task.result)
val res = stringToString(task.result)
val sharedPref = this?.getPreferences(Context.MODE_PRIVATE)
with (sharedPref.edit()) {
putString("ID", res)
commit()
}
// when is completed, make progressBar gone
this@MainActivity.runOnUiThread(java.lang.Runnable {
findViewById<ProgressBar>(R.id.progressBar).visibility = View.GONE
//findViewById<ProgressBar>(R.id.progressBar).visibility = View.INVISIBLE
})
displayId(res)
}
})
}
}).start()
}
else{
val oldId = stringToString(sharedPref.getString("ID", "defaultValue"))
Log.d("old Id", oldId)
displayId(oldId)
}
FirebaseInstanceId.getInstance().instanceId.addOnFailureListener(this) {instanceIdResult ->
Log.e("newToken", "error")
}
}
private fun createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Notify"
val descriptionText = "Notification channel for Notify app"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("Notify", name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
private fun addToken(token: String): Task<String> {
// Create the arguments to the callable function.
val data : HashMap<String, String> = hashMapOf("token" to token)
Log.d("before calling", "before calling")
return functions
.getHttpsCallable("addToken")
.call(data)
.continueWith { task ->
// This continuation runs on either success or failure, but if the task
// has failed then result will throw an Exception which will be
// propagated down.
val result = task.result?.data as String
result
}
}
private fun displayId(id:String){
val textView: TextView = findViewById(R.id.id) as TextView
textView.text = id
}
private fun stringToString(str:String?): String{
return str ?: ""
}
/*override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
}
| 3
|
Kotlin
|
0
| 1
|
37895872fe7584f241f9232c536fdcdc22c47571
| 6,770
|
Notify
|
MIT License
|
walletlibrary/src/main/java/com/microsoft/walletlibrary/util/http/httpagent/IResponse.kt
|
microsoft
| 567,422,889
| false
|
{"Kotlin": 1390274}
|
package com.microsoft.walletlibrary.util.http.httpagent
class IResponse(
val status: Int,
val headers: Map<String, String>,
val body: ByteArray
)
| 13
|
Kotlin
|
8
| 20
|
b31d71b53baef4e1390a4f85f0c80bba3ae35702
| 158
|
entra-verifiedid-wallet-library-android
|
MIT License
|
app/src/main/java/com/hulusimsek/cryptoapp/data/repository/CryptoRepositoryImp.kt
|
hulusimsek
| 841,740,788
| false
|
{"Kotlin": 115100}
|
package com.hulusimsek.cryptoapp.data.repository
import com.hulusimsek.cryptoapp.data.database.entity.SearchQuery
import com.hulusimsek.cryptoapp.data.remote.dto.Crypto
import com.hulusimsek.cryptoapp.data.remote.dto.CryptoItem
import com.hulusimsek.cryptoapp.data.remote.dto.CryptoList
import com.hulusimsek.cryptoapp.data.database.dao.CryptoDao
import com.hulusimsek.cryptoapp.data.remote.CryptoAPI
import com.hulusimsek.cryptoapp.data.remote.dto.Klines
import com.hulusimsek.cryptoapp.domain.repository.CryptoRepository
import com.hulusimsek.cryptoapp.util.Resource
import javax.inject.Inject
class CryptoRepositoryImp @Inject constructor(
private val api: CryptoAPI,
private val cryptoDao: CryptoDao
) : CryptoRepository {
override suspend fun insertSearchQuery(searchQuery: SearchQuery) {
cryptoDao.insertQuery(searchQuery)
}
override suspend fun deleteSearchQuery(searchQuery: SearchQuery) {
cryptoDao.deleteQuery(searchQuery)
}
override suspend fun deleteSearchQueryByQuery(query: String) {
cryptoDao.deleteSearchQueryByQuery(query)
}
override suspend fun getSearchQuery(): List<SearchQuery> {
return cryptoDao.getAllQueries()
}
override suspend fun getCryptoList(): Resource<CryptoList> {
val response = try {
api.getCryptoList()
} catch (e: Exception) {
return Resource.Error("Error")
}
return Resource.Success(response)
}
override suspend fun getCrypto(id: String): CryptoItem {
return api.getCrypto(id)
}
override suspend fun getCryptoList24hr(): Crypto {
return api.getCryptoList24hr()
}
override suspend fun getKlines(id: String, interval: String): Klines {
return api.getKlines(id, interval)
}
}
| 0
|
Kotlin
|
0
| 0
|
66d49b82a178a8d29a8585d0ab5633e4256a1205
| 1,806
|
Cointograf
|
MIT License
|
src/main/kotlin/dev/programadorthi/migration/visitor/SyntheticReferenceRecursiveVisitor.kt
|
programadorthi
| 598,366,528
| false
| null |
package dev.programadorthi.migration.visitor
import android.databinding.tool.ext.parseXmlResourceReference
import android.databinding.tool.ext.toCamelCaseAsVar
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.xml.XmlAttribute
import com.intellij.psi.xml.XmlAttributeValue
import com.intellij.psi.xml.XmlFile
import com.intellij.psi.xml.XmlTag
import dev.programadorthi.migration.model.AndroidView
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.nj2k.postProcessing.resolve
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtBinaryExpressionWithTypeRHS
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtCatchClause
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassBody
import org.jetbrains.kotlin.psi.KtClassInitializer
import org.jetbrains.kotlin.psi.KtContainerNode
import org.jetbrains.kotlin.psi.KtDoWhileExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.KtPropertyDelegate
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.KtSafeQualifiedExpression
import org.jetbrains.kotlin.psi.KtStringTemplateEntry
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.KtTryExpression
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.psi.KtVisitorVoid
import org.jetbrains.kotlin.psi.KtWhenEntry
import org.jetbrains.kotlin.psi.KtWhenExpression
class SyntheticReferenceRecursiveVisitor : KtVisitorVoid() {
private val mutableAndroidViews = mutableListOf<AndroidView>()
private val mutableViewHolderItemViews = mutableListOf<PsiReference>()
val androidViews: List<AndroidView>
get() = mutableAndroidViews
val viewHolderItemViews: List<PsiReference>
get() = mutableViewHolderItemViews
// ========================================================================
// Start section that do something
// ========================================================================
/**
* Class in the file
*/
override fun visitClass(klass: KtClass) {
super.visitClass(klass)
val body = klass.body ?: return
body.accept(this)
}
/**
* Reference to other element
*/
override fun visitReferenceExpression(expression: KtReferenceExpression) {
super.visitReferenceExpression(expression)
tryMapXmlAttributeValue(expression.resolve(), expression.references.firstOrNull())
}
private fun tryMapXmlAttributeValue(psiElement: PsiElement?, psiReference: PsiReference?) {
if (psiElement == null || psiReference == null || checkAndMapViewHolderType(psiElement, psiReference)) return
if (psiElement is XmlAttributeValue) {
val xmlFile = psiElement.containingFile as? XmlFile ?: return
// TODO: Are we still need lookup for include layouts?
val elementTag = getXmlAttributeValueTag(psiElement) ?: return
val viewIdReference = runCatching {
psiElement.value.parseXmlResourceReference()
}.getOrNull()
if (viewIdReference == null || viewIdReference.type != "id") return
mutableAndroidViews += AndroidView(
reference = psiReference,
layoutNameWithoutExtension = xmlFile.name.removeSuffix(".xml"),
rootTagName = xmlFile.rootTag?.name ?: "",
includeLayoutName = if (elementTag != "include") null else getLayoutName(psiElement),
viewStubLayoutName = if (elementTag != "ViewStub") null else getLayoutName(psiElement),
viewId = viewIdReference.name.toCamelCaseAsVar()
)
}
}
private fun checkAndMapViewHolderType(psiElement: PsiElement, psiReference: PsiReference): Boolean {
val currentPsiElement = psiElement.namedUnwrappedElement ?: return false
val parentName = currentPsiElement.parent?.namedUnwrappedElement?.name ?: ""
if (("itemView" == currentPsiElement.name || "containerView" == currentPsiElement.name) &&
("ViewHolder" == parentName || "GroupieViewHolder" == parentName)
) {
mutableViewHolderItemViews += psiReference
return true
}
return false
}
/**
* current ref is: "@+id/someIdentifier"
* His parent is: android:id="@+id/someIdentifier"
* His parent from parent is always a tag: <Tag android:id="@+id/someIdentifier" />
*/
private fun getXmlAttributeValueTag(xmlAttributeValue: XmlAttributeValue): String? {
var currentParent = xmlAttributeValue.parent
while (true) {
if (currentParent is XmlTag) {
return currentParent.name
}
currentParent = currentParent.parent ?: break
}
return null
}
// TODO: Are we still need lookup for include layouts?
private fun getLayoutName(xmlAttributeValue: XmlAttributeValue): String? {
var parent: PsiElement? = xmlAttributeValue.parent ?: return null
while (parent != null && parent !is XmlTag) {
parent = parent.parent
}
if (parent is XmlTag && (parent.name == "include" || parent.name == "ViewStub")) {
val layoutAttribute = parent.children
.filterIsInstance<XmlAttribute>()
.firstOrNull { it.text.contains(ANDROID_LAYOUT_PREFIX) }
if (layoutAttribute != null) {
val layout = layoutAttribute.text.split(ANDROID_LAYOUT_PREFIX)
if (layout.size > 1) {
return layout[1].removeSuffix("\"")
}
}
}
return null
}
// ========================================================================
// End section that do something
// ========================================================================
// ========================================================================
// Start recursive operations section
// ========================================================================
/**
* Function argument
*
* doSomething(something) <-- something is an argument
* setOnClickListener {} <-- lambda is an argument for setOnClickListener function
* something.apply {} <-- {} is an argument for apply function
*/
override fun visitArgument(argument: KtValueArgument) {
super.visitArgument(argument)
for (child in argument.children) {
child.accept(this)
}
}
/**
* Assignment operation (=)
*/
override fun visitBinaryExpression(expression: KtBinaryExpression) {
super.visitBinaryExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* Instance of operation (is)
*/
override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) {
super.visitBinaryWithTypeRHSExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* Function block {}
*/
override fun visitBlockExpression(expression: KtBlockExpression) {
super.visitBlockExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* Function call
*
* lazy {}
* doSomething()
* doOtherSomething(something)
* setOnClickListener {}
* super.onStart() <-- onStart() is call expression only
* something.apply {} <-- apply{} is call expression only
*/
override fun visitCallExpression(expression: KtCallExpression) {
super.visitCallExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* try {} catch {}
*/
override fun visitCatchSection(catchClause: KtCatchClause) {
super.visitCatchSection(catchClause)
for (child in catchClause.children) {
child.accept(this)
}
}
/**
* Class content inside {}
*/
override fun visitClassBody(classBody: KtClassBody) {
super.visitClassBody(classBody)
for (child in classBody.children) {
child.accept(this)
}
}
/**
* init {}
*/
override fun visitClassInitializer(initializer: KtClassInitializer) {
super.visitClassInitializer(initializer)
for (child in initializer.children) {
child.accept(this)
}
}
/**
* Expression using Dot(.)
*
* super.onStart()
* variable.run()
* noNullable.doSomething()
*/
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
super.visitDotQualifiedExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* do {} while()
*
* Check [visitKtElement] to know how access his condition or body content
*/
override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
super.visitDoWhileExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* for () {}
*
* Check [visitKtElement] to know how access his condition or body content
*/
override fun visitForExpression(expression: KtForExpression) {
super.visitForExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* if {} or both if {} else {}
*
* Check [visitKtElement] to know how access his condition or body content
*/
override fun visitIfExpression(expression: KtIfExpression) {
super.visitIfExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* Any element
*/
override fun visitKtElement(element: KtElement) {
super.visitKtElement(element)
// if/else/while/for conditional section () or content body {}
if (element is KtContainerNode) {
for (child in element.children) {
child.accept(this)
}
}
}
/**
* Kotlin file content
*/
override fun visitKtFile(file: KtFile) {
super.visitKtFile(file)
for (child in file.children) {
if (child is KtClass || child is KtNamedFunction) {
child.accept(this)
}
}
}
/**
* Function declared in class body or top-level file
*
* class {
* fun ... <- this is a named function
* }
*
* fun ... <- this is a named function too
*/
override fun visitNamedFunction(function: KtNamedFunction) {
super.visitNamedFunction(function)
for (child in function.children) {
child.accept(this)
}
}
/**
* Any argument with lambda value
*
* myVariable = {} <-- {} is a lambda expression
* setOnClickListener {} <-- {} is a lambda expression
* something.apply {} <-- {} is a lambda expression
* something.map {} <-- {} is a lambda expression
*/
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
super.visitLambdaExpression(lambdaExpression)
for (child in lambdaExpression.functionLiteral.children) {
child.accept(this)
}
}
/**
* Property inside class, function or any declaration local
* Almost declared using val or var
*/
override fun visitProperty(property: KtProperty) {
super.visitProperty(property)
for (child in property.children) {
child.accept(this)
}
}
/**
* get() or set(...) for a property
*/
override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
super.visitPropertyAccessor(accessor)
for (child in accessor.children) {
child.accept(this)
}
}
/**
* Delegated property
*
* val variable by lazy {} <-- by is a property delegate
*/
override fun visitPropertyDelegate(delegate: KtPropertyDelegate) {
super.visitPropertyDelegate(delegate)
for (child in delegate.children) {
child.accept(this)
}
}
/**
* Expression using ?.
*
* nullable?.something()
* fun1()?.fun2()
*/
override fun visitSafeQualifiedExpression(expression: KtSafeQualifiedExpression) {
super.visitSafeQualifiedExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* String in template form "${}" or """${}"""
*/
override fun visitStringTemplateExpression(expression: KtStringTemplateExpression) {
super.visitStringTemplateExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* String template entry "${entry1}..." or """${entry1}something${entry2}..."""
*/
override fun visitStringTemplateEntry(entry: KtStringTemplateEntry) {
super.visitStringTemplateEntry(entry)
for (child in entry.children) {
child.accept(this)
}
}
/**
* try {} catch {}
*/
override fun visitTryExpression(expression: KtTryExpression) {
super.visitTryExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* Argument list for a function call
*
* fun1(arg1, arg2, ...)
* something.map { arg1, arg2, ... }
*/
override fun visitValueArgumentList(list: KtValueArgumentList) {
super.visitValueArgumentList(list)
for (argument in list.arguments) {
argument.accept(this)
}
}
/**
* when (...) {} or when {}
*/
override fun visitWhenExpression(expression: KtWhenExpression) {
super.visitWhenExpression(expression)
for (child in expression.children) {
child.accept(this)
}
}
/**
* when ... {
* entry1 -> ...
* entry2 -> ...
* ...
* else -> ... <-- else is a when entry too
* }
*/
override fun visitWhenEntry(jetWhenEntry: KtWhenEntry) {
super.visitWhenEntry(jetWhenEntry)
for (child in jetWhenEntry.children) {
child.accept(this)
}
}
// ========================================================================
// End recursive operations section
// ========================================================================
companion object {
private const val ANDROID_LAYOUT_PREFIX = "@layout/"
}
}
| 0
|
Kotlin
|
0
| 17
|
ac0bdfd1add6d6c37d8eebf96666833f259e910c
| 15,495
|
synthetic-to-viewbinding
|
MIT License
|
app/src/main/java/com/biolumeaccessfsm/features/login/model/productlistmodel/ProductListResponseModel.kt
|
DebashisINT
| 740,453,031
| false
|
{"Kotlin": 13980759, "Java": 1001438}
|
package com.biolumeaccessfsm.features.login.model.productlistmodel
import com.biolumeaccessfsm.app.domain.ProductListEntity
import com.biolumeaccessfsm.base.BaseResponse
/**
* Created by Saikat on 20-11-2018.
*/
class ProductListResponseModel : BaseResponse() {
//var product_list: ArrayList<ProductListDataModel>? = null
var product_list: ArrayList<ProductListEntity>? = null
}
| 0
|
Kotlin
|
0
| 0
|
1a51f3bdcf8e79c9ef523846fb89fcfb6072bbb4
| 390
|
BIOLUMESKINSCIENCE
|
Apache License 2.0
|
sample/src/main/java/com/decathlon/design/sample/components/screens/resources/icons/IconsFragment.kt
|
Decathlon
| 353,745,954
| false
|
{"Kotlin": 63972}
|
package com.decathlon.design.sample.components.screens.resources.icons
import androidx.lifecycle.LiveData
import androidx.navigation.fragment.findNavController
import com.decathlon.design.sample.R
import com.decathlon.design.sample.components.screens.resources.common.AbstractResourcesFragment
import com.decathlon.design.sample.components.screens.resources.common.ResourceModel
class IconsFragment : AbstractResourcesFragment() {
override fun showSearchOption(): Boolean = true
override fun onSearchClick() {
findNavController().navigate(R.id.action_icons_to_icons_search)
}
override fun getData(): LiveData<List<ResourceModel>> {
return resourcesViewModel.icons
}
}
| 7
|
Kotlin
|
18
| 74
|
11b7df97d3b9f2f1110cc56f4669007375b621da
| 709
|
vitamin-android
|
Apache License 2.0
|
src/HelloWorld.kt
|
saugatlamichhane
| 700,642,753
| false
|
{"Kotlin": 6362}
|
fun main() {
//use println() for output with endline
//can use just println() for a single empty line output
//use print() for printing a line without endline
println("Hello World!")
println()
print("from ")
println("Nepal")
}
| 0
|
Kotlin
|
0
| 0
|
6c33b6425ca67be0ec70381f410a3b277b43414f
| 256
|
LearnKotlin
|
MIT License
|
shared/src/commonMain/kotlin/util/KermitLogging.kt
|
OlayG
| 662,705,249
| false
| null |
package util
import co.touchlab.kermit.Logger
import org.koin.core.component.KoinComponent
import org.koin.core.component.get
import org.koin.core.module.Module
import org.koin.core.parameter.parametersOf
import org.koin.core.scope.Scope
/**
* Setup default logger with koin.
*
* @param baseLogger
*/
fun Module.kermitLoggerModule(baseLogger: Logger) = factory { (tag: String?) ->
if (tag != null) baseLogger.withTag(tag) else baseLogger
}
/**
* Get logger from koin.
*
* @param L Type of logger
* @param tag unique identifier for each log
* @return Instance of the Logger
*/
inline fun <reified L : Logger> Scope.getLoggerWithTag(tag: String): L {
return get(parameters = { parametersOf(tag) })
}
/**
* Get logger from koin.
*
* @param L Type of logger
* @param tag unique identifier for each log
* @return Instance of the Logger
*/
inline fun <reified L : Logger> KoinComponent.getLoggerWithTag(tag: String): L {
return get(parameters = { parametersOf(tag) })
}
| 0
|
Kotlin
|
0
| 0
|
3202ccf478b03ef42dd869d0af6f825abffb1a89
| 996
|
KMM-AlbumViewer
|
Apache License 2.0
|
app/src/main/java/com/boolder/boolder/view/contribute/ContributeFragment.kt
|
boolder-org
| 566,723,758
| false
|
{"Kotlin": 485650}
|
package com.boolder.boolder.view.contribute
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.ui.platform.ComposeView
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import com.boolder.boolder.view.compose.BoolderTheme
import java.util.Locale
class ContributeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View =
ComposeView(inflater.context).apply {
setContent {
BoolderTheme {
ContributeScreen(
onStartContributingClicked = ::onStartContributingClicked,
onLearnMoreClicked = ::onLearnMoreClicked
)
}
}
}
private fun onStartContributingClicked() {
openWebUrl("https://www.boolder.com/${getUrlLocale()}/contribute?dismiss_banner=true")
}
private fun onLearnMoreClicked() {
openWebUrl("https://www.boolder.com/${getUrlLocale()}/about")
}
private fun openWebUrl(url: String) {
val intent = Intent(Intent.ACTION_VIEW, url.toUri())
startActivity(intent)
}
private fun getUrlLocale(): String =
if (Locale.getDefault().language == "fr") "fr" else "en"
}
| 8
|
Kotlin
|
11
| 23
|
fcd50ffbe2510764b911257862409038c18dde35
| 1,440
|
boolder-android
|
MIT License
|
feature/home/favorites/src/main/java/com/uragiristereo/mikansei/feature/home/favorites/favgroup/new/core/NewFavGroupTopAppBar.kt
|
uragiristereo
| 583,834,091
| false
|
{"Kotlin": 978568}
|
package com.uragiristereo.mikansei.feature.home.favorites.favgroup.new.core
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import com.uragiristereo.mikansei.core.product.component.ProductTopAppBar
import com.uragiristereo.mikansei.core.resources.R
@Composable
fun NewFavGroupTopAppBar(
onNavigateBack: () -> Unit,
modifier: Modifier = Modifier,
) {
ProductTopAppBar(
title = {
Text(text = stringResource(id = R.string.new_favorite_group))
},
navigationIcon = {
IconButton(
onClick = onNavigateBack,
content = {
Icon(
painter = painterResource(id = R.drawable.arrow_back),
contentDescription = null,
)
},
)
},
modifier = modifier,
)
}
| 3
|
Kotlin
|
2
| 62
|
4f136b0479ee7772f3d7ba48927cef9389d5c2be
| 1,109
|
Mikansei
|
Apache License 2.0
|
src/backend/job/biz-job/src/main/kotlin/com/tencent/bkrepo/job/config/properties/ProjectRepoMetricsStatJobProperties.kt
|
TencentBlueKing
| 548,243,758
| false
|
{"Kotlin": 13657594, "Vue": 1261332, "JavaScript": 683823, "Shell": 124343, "Lua": 100415, "SCSS": 34137, "Python": 25877, "CSS": 17382, "HTML": 13052, "Dockerfile": 4483, "Smarty": 3661, "Java": 423}
|
package com.tencent.bkrepo.job.config.properties
open class ProjectRepoMetricsStatJobProperties : MongodbJobProperties() {
val ignoreArchiveProjects: MutableList<String> = ArrayList()
}
| 363
|
Kotlin
|
38
| 70
|
54b0c7ab20ddbd988387bac6c9143b594681e73c
| 191
|
bk-repo
|
MIT License
|
components-core/src/test/java/com/adyen/checkout/components/core/paymentmethod/TwintPaymentMethodTest.kt
|
Adyen
| 91,104,663
| false
|
{"Kotlin": 4787892, "Shell": 4706}
|
package com.adyen.checkout.components.core.paymentmethod
import org.json.JSONObject
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class TwintPaymentMethodTest {
@Test
fun `when serializing, then all fields should be serialized correctly`() {
val request = TwintPaymentMethod(
type = "twint",
checkoutAttemptId = "checkoutAttemptId",
subtype = "sdk",
storedPaymentMethodId = "storedPaymentMethodId",
)
val actual = TwintPaymentMethod.SERIALIZER.serialize(request)
val expected = JSONObject()
.put("type", "twint")
.put("checkoutAttemptId", "checkoutAttemptId")
.put("subtype", "sdk")
.put("storedPaymentMethodId", "storedPaymentMethodId")
assertEquals(expected.toString(), actual.toString())
}
@Test
fun `when deserializing, then all fields should be deserializing correctly`() {
val response = JSONObject()
.put("type", "twint")
.put("checkoutAttemptId", "checkoutAttemptId")
.put("subtype", "sdk")
.put("storedPaymentMethodId", "storedPaymentMethodId")
val actual = TwintPaymentMethod.SERIALIZER.deserialize(response)
val expected = TwintPaymentMethod(
type = "twint",
checkoutAttemptId = "checkoutAttemptId",
subtype = "sdk",
storedPaymentMethodId = "storedPaymentMethodId",
)
assertEquals(expected, actual)
}
}
| 22
|
Kotlin
|
66
| 126
|
c45a6ee4d2039163ae075436a9d1231ffcb16f5c
| 1,570
|
adyen-android
|
MIT License
|
src/testData/jvm/expression/call/call8/ProviderCall8.kt
|
XYZboom
| 767,934,164
| false
|
{"Kotlin": 1241229, "Java": 26268}
|
package expression.call.call8
class ProviderCall8 {
/*<target>*/fun func() {
}/*<target/>*/
}
| 0
|
Kotlin
|
0
| 0
|
6b7dab23cd8af5c94edcf6888050be89cf4acbdc
| 103
|
psi-reference-extractor
|
Apache License 2.0
|
lib/src/main/java/dev/tunnicliff/replace_me/Example.kt
|
Brent-Tunnicliff
| 750,803,978
| false
|
{"Kotlin": 7019}
|
package dev.tunnicliff.replace_me
class Example {
companion object {
const val VALUE = "Hello world!"
}
}
| 0
|
Kotlin
|
0
| 0
|
7c9dffc0234916451bee3fb9e77d944860e9193f
| 122
|
template-lib-android
|
MIT License
|
adaptive-core/src/commonMain/kotlin/fun/adaptive/foundation/util.kt
|
spxbhuhb
| 788,711,010
| false
|
{"Kotlin": 2273072, "Java": 24502, "HTML": 7707, "JavaScript": 3880, "Shell": 687}
|
package `fun`.adaptive.foundation
fun AdaptiveAdapter.dumpFragmentTree(): String =
rootFragment.dumpFragmentTree()
fun AdaptiveFragment.dumpFragmentTree(indent: String = ""): String {
val lines = mutableListOf<String>()
lines += indent + this.toString()
for (child in children) {
lines += child.dumpFragmentTree("$indent ")
}
return lines.joinToString("\n")
}
| 33
|
Kotlin
|
0
| 3
|
98e84716b9a2e3713b70b64c36bfaeecbab397d0
| 394
|
adaptive
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/frauddetector/CfnEntityTypeDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.frauddetector
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.String
import kotlin.Unit
import software.amazon.awscdk.services.frauddetector.CfnEntityType
import software.amazon.awscdk.services.frauddetector.CfnEntityTypeProps
import software.constructs.Construct
@Generated
public fun Construct.cfnEntityType(id: String, props: CfnEntityTypeProps): CfnEntityType =
CfnEntityType(this, id, props)
@Generated
public fun Construct.cfnEntityType(
id: String,
props: CfnEntityTypeProps,
initializer: @AwsCdkDsl CfnEntityType.() -> Unit,
): CfnEntityType = CfnEntityType(this, id, props).apply(initializer)
@Generated
public fun Construct.buildCfnEntityType(id: String, initializer: @AwsCdkDsl
CfnEntityType.Builder.() -> Unit): CfnEntityType = CfnEntityType.Builder.create(this,
id).apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
e08d201715c6bd4914fdc443682badc2ccc74bea
| 916
|
aws-cdk-kt
|
Apache License 2.0
|
app/src/main/java/io/betterapps/graysky/MainActivity.kt
|
raychenon
| 290,579,350
| false
| null |
package io.betterapps.graysky
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.location.Location
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.widget.Autocomplete
import com.google.android.libraries.places.widget.AutocompleteActivity
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode
import es.dmoral.toasty.Toasty
import io.betterapps.graysky.const.GlobalConstants
import io.betterapps.graysky.data.db.entities.LocationEntity
import io.betterapps.graysky.data.domains.GeoLocation
import io.betterapps.graysky.data.domains.LocationName
import io.betterapps.graysky.geoloc.UserLocationDelegate
import io.betterapps.graysky.ui.main.MainViewModel
import io.betterapps.graysky.ui.weatherforecast.WeatherForecastFragment
import io.betterapps.graysky.ui.weatherforecast.onDeleteLocation
import kotlinx.android.synthetic.main.main_activity.*
import org.koin.android.viewmodel.ext.android.viewModel
import timber.log.Timber
class MainActivity : AppCompatActivity(), onDeleteLocation {
// lazy inject
val mainViewModel: MainViewModel by viewModel()
private lateinit var userLocationDelegate: UserLocationDelegate
private lateinit var locationNames: MutableList<LocationName>
private var lastUserKnownLocation: GeoLocation? = null
companion object {
private val BUNDLE_GEOLOC = "GEOLOC_EXTRA"
fun createIntent(context: Context, geolocEnabled: Boolean): Intent {
val intent = Intent(context, MainActivity::class.java)
intent.putExtra(BUNDLE_GEOLOC, geolocEnabled)
return intent
}
}
init {
locationNames = mutableListOf()
locationNames.addAll(GlobalConstants.CITIES)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
mainViewModel.initialize()
val extras = intent.extras
extras?.let {
val enabled = it.getBoolean(BUNDLE_GEOLOC)
if (enabled) {
userLocationDelegate = UserLocationDelegate(this)
if (savedInstanceState == null) {
launchPermission()
}
} else {
displayWeatherFromLocations(GlobalConstants.USER_LOCATION)
}
}
// Initialize the SDK
Places.initialize(applicationContext, getString(R.string.cloud_platform_api))
}
fun showWeatherFragments(locations: List<LocationName>) {
val ft = supportFragmentManager.beginTransaction()
var position = 0
for (location in locations) {
val fragment = WeatherForecastFragment.newInstance(
location.name, location.geoLocation.latitude, location.geoLocation.longitude,
location.distanceInKm, position++)
fragment.setDeleteListener(this)
ft.add(
R.id.main_container,
fragment,
location.name
)
}
ft.commitNow()
}
private fun launchPermission() {
if (!userLocationDelegate.checkLocationPermission(this)) {
userLocationDelegate.requestPermissions(::showRationale)
} else {
userLocationDelegate.getLastLocation(
{ loc ->
displayWeatherOrError(loc)
}
)
}
}
private val AUTOCOMPLETE_REQUEST_CODE = 1
fun launchAutocomplete(): Unit {
// Set the fields to specify which types of place data to
// return after the user has made a selection.
val fields = listOf(
Place.Field.ID,
Place.Field.NAME,
Place.Field.LAT_LNG,
Place.Field.ADDRESS
)
// Start the autocomplete intent.
val intent = Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
.build(this)
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
when (resultCode) {
Activity.RESULT_OK -> {
data?.let {
val place = Autocomplete.getPlaceFromIntent(data)
Timber.i("onActivityResult Place: ${place.name}, ${place.id}, ${place.latLng} , address = ${place.address} , \n , ${place.toString()}")
mainViewModel.addLocation(
LocationEntity(
place.id!!,
place.name!!,
place.address!!,
place.latLng!!.latitude,
place.latLng!!.longitude
)
)
val geolocation = lastUserKnownLocation ?: GlobalConstants.USER_LOCATION
displayWeatherFromLocations(geolocation)
}
}
AutocompleteActivity.RESULT_ERROR -> {
// TODO: Handle the error.
data?.let {
val status = Autocomplete.getStatusFromIntent(data)
Timber.i("onActivityResult ${status.statusMessage}")
}
}
Activity.RESULT_CANCELED -> {
Timber.i("onActivityResult cancelled")
}
}
return
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.menu_weather, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_add -> {
launchAutocomplete()
true
}
else -> {
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
super.onOptionsItemSelected(item)
}
}
private fun showRationale() {
Toasty.error(this, R.string.permission_rationale, Toast.LENGTH_SHORT, true).show()
}
private fun showErrorLastLocation() {
Toasty.error(this, R.string.permission_last_location_not_found, Toast.LENGTH_LONG, true)
.show()
}
private fun displayWeatherOrError(location: Location?) {
location?.let {
val geoLocation = location2Geolocation(it)
lastUserKnownLocation = geoLocation
displayWeatherFromLocations(geoLocation)
} ?: run {
showErrorLastLocation()
}
}
private fun displayWeatherFromLocations(currentUserlocation: GeoLocation) {
// clean previous views
main_container.removeAllViews()
mainViewModel.sortByDistance(currentUserlocation)
.observe(
this,
androidx.lifecycle.Observer {
it?.let { locations ->
showWeatherFragments(
locations
)
}
}
)
}
private fun location2Geolocation(location: Location): GeoLocation =
GeoLocation(location.latitude, location.longitude)
/**
* Callback received when a permissions request has been completed.
*/
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
Timber.i("onRequestPermissionResult")
userLocationDelegate.onRequestPermissionsResultDelete(
requestCode,
permissions,
grantResults,
{ loc -> displayWeatherOrError(loc) }
)
}
override fun onDelete(position: Int, locationName: String) {
dialogDeleteConfirmation(position, locationName).show()
}
private fun dialogDeleteConfirmation(position: Int, locationName: String): AlertDialog {
val builder = AlertDialog.Builder(this)
builder.setTitle(R.string.location_delete_title)
builder.setMessage(getString(R.string.location_delete_description, locationName))
.setCancelable(false)
.setPositiveButton(R.string.location_delete_confirm) { dialog, id ->
main_container.removeViewAt(position)
mainViewModel.deleteLocation(locationName)
}
.setNegativeButton(R.string.location_delete_no) { dialog, id ->
dialog.cancel()
}
return builder.create()
}
}
| 5
|
Kotlin
|
1
| 1
|
a99094c666a56640c947b0b0b65e654f0caacf37
| 9,148
|
gray-sky-weather
|
Apache License 2.0
|
src/twentytwentytwo/day13/Day13.kt
|
colinmarsch
| 571,723,956
| false
| null |
package day13
import readInput
fun main() {
fun part1(input: List<String>): Int {
var total = 0
input.chunked(3).forEachIndexed { index, pair ->
val left = parse(pair[0])
val right = parse(pair[1])
if (inOrder(left, right)) {
total += index + 1
}
}
return total
}
fun part2(input: List<String>): Int {
var total = 0
val items = input.filter { it.isNotEmpty() }.map { parse(it) }.toMutableList()
val first = ListItem(mutableListOf(ListItem(mutableListOf(IntItem(2)))))
val second = ListItem(mutableListOf(ListItem(mutableListOf(IntItem(6)))))
items.add(first)
items.add(second)
items.sort()
return (items.indexOf(first) + 1) * (items.indexOf(second) + 1)
}
val input = readInput("day13", "Day13_input")
println(part1(input))
println(part2(input))
}
interface Item : Comparable<Item> {
override fun compareTo(other: Item): Int
}
class IntItem(val value: Int) : Item {
override fun compareTo(other: Item): Int {
return when (other) {
is IntItem -> this.value.compareTo(other.value)
is ListItem -> {
return ListItem(mutableListOf(this)).compareTo(other)
}
else -> throw IllegalStateException()
}
}
}
class ListItem(val list: MutableList<Item> = mutableListOf()) : Item {
override fun compareTo(other: Item): Int {
when (other) {
is IntItem -> {
return this.compareTo(ListItem(mutableListOf(other)))
}
is ListItem -> {
list.forEachIndexed { index, item ->
if (index >= other.list.size) return 1
val compare = item.compareTo(other.list[index])
if (compare != 0)
return compare
}
return if (list.size == other.list.size) 0 else -1
}
else -> throw IllegalStateException()
}
}
}
private fun inOrder(left: ListItem, right: ListItem): Boolean {
return left <= right
}
private fun parse(line: String): ListItem {
val stack = ArrayDeque<MutableList<Any>>()
var current = mutableListOf<Any>()
var number = -1
fun flushNumber() {
if (number != -1) {
current.add(number)
number = -1
}
}
line.forEach { char ->
when (char) {
'[' -> {
stack.addLast(current)
current = mutableListOf()
stack.last().add(current)
}
']' -> {
flushNumber()
current = stack.removeLast()
}
',' -> flushNumber()
else -> number = number.coerceAtLeast(0) * 10 + (char - '0')
}
}
return ListItem((current[0] as List<*>).toItem().toMutableList())
}
private fun List<*>.toItem(): List<Item> = map {
if (it is List<*>) {
ListItem(it.toItem().toMutableList())
} else {
IntItem(it as Int)
}
}
| 0
|
Kotlin
|
0
| 0
|
423bb0fa53c42169b62b8a5ee792032dd1477280
| 3,145
|
advent-of-code-kotlin-2022
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com.yunext.twins/ui/page/device/TwinsDevicePage.kt
|
LaputaZeej
| 665,861,090
| false
| null |
package com.yunext.twins.ui.page.device
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.yunext.twins.data.DeviceAndState
import com.yunext.twins.data.ItemDefaults
import com.yunext.twins.ui.compoents.TwinsBackgroundBlock
import com.yunext.twins.ui.compoents.TwinsEmptyView
import com.yunext.twins.ui.compoents.TwinsTitle
import com.yunext.twins.ui.compoents.CHItemShadowShape
import com.yunext.twins.ui.page.home.DeviceCommunicationIdAndModel
import com.yunext.twins.ui.theme.app_background_70
import com.yunext.twins.ui.theme.app_textColor_333333
import com.yunext.twins.ui.theme.app_textColor_666666
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
enum class DeviceTab(val text: String) {
Properties("属性"),
Events("事件"),
Services("服务")
;
}
enum class MenuData(val icon: String, val text: String) {
ConfigWiFi("icon_twins_distribution_network.png", "进入配网模式"),
Setting("icon_twins_set_up.png", "配置"),
Logger("icon_twins_log.png", "通信日志"),
UpdateTsl("icon_twins_refresh.png", "检查更新物模型")
;
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun <T> TwinsDevicePage(
device: DeviceAndState,
list: List<T>,
onTabSelected: (tab: DeviceTab) -> Unit,
onMenuClick: (MenuData) -> Unit,
onLeft: () -> Unit,
onRight: () -> Unit,
) {
var curTab by remember { mutableStateOf(DeviceTab.Properties) }
var showMenu by remember { mutableStateOf(false) }
var editingProperty: Any? by remember { mutableStateOf(null) }
var addProperty by remember { mutableStateOf(false) }
var showTips by remember {
mutableStateOf("")
}
TwinsBackgroundBlock()
Column(modifier = Modifier.fillMaxSize()) {
// 标题
TwinsTitle(modifier = Modifier
.background(app_background_70),
text = device.name,
leftClick = {
onLeft()
},
rightClick = {
showMenu = !showMenu
})
// 内容
Box(Modifier.fillMaxWidth()) {
Column() {
// top
Column(
Modifier
.fillMaxWidth()
.background(app_background_70)
.padding(vertical = 0.dp, horizontal = 12.dp),
) {
Top(device = device)
Spacer(Modifier.height(12.dp))
}
// tab
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Tab(
modifier = Modifier.weight(1f, true)
.padding(16.dp), curTab
) {
curTab = it
onTabSelected.invoke(it)
}
// 统计
CountInfo(
modifier = Modifier
.padding(horizontal = 16.dp), count = list.size
)
}
// list
KVList(
curTab,
list,
onPropertyAction = {
if (editingProperty == null) {
editingProperty = it
}
},
onEventAction = {},
onServiceAction = {})
}
// pop
if (showMenu) {
MenuList(
modifier = Modifier
.padding(horizontal = 12.dp)
.align(Alignment.TopEnd), onDismiss = { showMenu = false }) {
onMenuClick(it)
}
}
// 属性修改
val temp = editingProperty
if (temp != null) {
Box(modifier = Modifier.align(Alignment.BottomCenter)) {
PropertyBottomSheet(temp, onClose = {
editingProperty = null
}, onCommitted = {
editingProperty = null
showTips = "选择了$it"
}, add = false to {
addProperty = true
})
}
}
// 属性添加
if (addProperty) {
Box(modifier = Modifier.fillMaxSize()) {
Box(
modifier = Modifier
.align(Alignment.BottomCenter)
) {
PropertyBottomSheet("", onClose = {
addProperty = false
}, onCommitted = {
addProperty = false
showTips = "添加了$it"
}, add = true to {
})
}
}
}
}
}
}
@Composable
private fun Top(
device: DeviceAndState,
modifier: Modifier = Modifier,
) {
DeviceCommunicationIdAndModel(modifier, device.communicationId, device.model)
}
@Composable
private fun Tab(modifier: Modifier, tab: DeviceTab, onTabSelected: (tab: DeviceTab) -> Unit) {
LazyRow(modifier = modifier) {
val array = DeviceTab.values()
items(items = array, key = {
it.ordinal
}) { item ->
CHTabItem(
tab == item,
icon = Icons.Default.Home,
title = (item.text),
onClick = { onTabSelected.invoke(item) }
)
}
}
}
@Composable
private fun CHTabItem(
selected: Boolean,
icon: ImageVector,
title: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Box(
modifier = modifier
.width(56.dp)
.height(36.dp)
//.border(2.dp,Color.Red)
.clip(CircleShape)
.clickable(onClick = onClick),
//.padding(16.dp)
// verticalArrangement = Arrangement.Center,
// horizontalAlignment = Alignment.CenterHorizontally
) {
// Icon(
// imageVector = icon,
// contentDescription = null
// )
// Spacer(modifier = Modifier.width(16.dp))
Text(
text = title,
color = Color(0xff333333),
fontSize = if (selected) 18.sp else 14.sp,
fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,
modifier = Modifier.align(
Alignment.Center
)
)
Spacer(modifier = Modifier.height(16.dp))
if (selected) {
Box(
modifier = Modifier
.width(12.dp)
.height(3.dp)
.background(color = Color(0xff339DFF))
.clip(RoundedCornerShape(3.dp))
.align(Alignment.BottomCenter)
) {
}
}
}
}
@Composable
private fun CountInfo(modifier: Modifier = Modifier, count: Int) {
Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
Text(
text = "共计",
color = app_textColor_666666,
fontSize = 12.sp,
fontWeight = FontWeight.Light
)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = "$count",
color = app_textColor_333333,
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
}
}
@Composable
private fun <T> KVList(
tab: DeviceTab, list: List<T>,
onPropertyAction: (T) -> Unit,
onServiceAction: (T) -> Unit,
onEventAction: (T) -> Unit,
) {
if (list.isEmpty()) {
TwinsEmptyView()
} else {
Box(Modifier.padding(horizontal = 16.dp)) {
when (tab) {
DeviceTab.Properties -> {
ListTslProperty(list = list) {
onPropertyAction.invoke(it)
}
}
DeviceTab.Events -> {
ListTslEvent(list = list) {
onEventAction(it)
}
}
DeviceTab.Services -> {
ListTslService(list = list) {
onServiceAction(it)
}
}
}
}
}
}
@Composable
private fun MenuList(
modifier: Modifier = Modifier,
onDismiss: () -> kotlin.Unit,
onMenuClick: (MenuData) -> Unit,
) {
val list: Array<MenuData> by remember {
mutableStateOf(MenuData.values())
}
XPopContainer(onDismiss = {
onDismiss()
}) {
CHItemShadowShape(elevation = 16.dp, modifier = modifier) {
Column(
modifier = Modifier
// .size(300.dp)
// .wrapContentWidth()
.width(180.dp)
// .widthIn(max = 300.dp, min = 100.dp)
// .wrapContentHeight()
.clip(RoundedCornerShape(8.dp))
.background(ItemDefaults.itemBackground)
// .padding(16.dp)
) {
list.forEach {
MenuItem(it) {
onMenuClick(it)
}
}
}
}
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
private fun MenuItem(menuData: MenuData, onClick: () -> Unit) {
Row(modifier = Modifier
.height(49.dp)
.fillMaxWidth()
.clickable {
onClick()
}
.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
Image(
painter = painterResource(menuData.icon),
contentDescription = null,
modifier = Modifier.size(20.dp),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.width(12.dp))
Text(
text = (menuData.text),
fontSize = 14.sp,
color = app_textColor_333333
)
}
}
/**
* todo 点击事件的问题
*/
@Composable
internal fun XPopContainer(
contentAlignment: Alignment = Alignment.TopStart,
dimAmount:Float=.5f,
onDismiss: () -> Unit = {},
content: @Composable BoxScope.() -> Unit,
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = dimAmount))
.clickable(interactionSource = MutableInteractionSource(), indication = null) {
onDismiss()
}, contentAlignment = contentAlignment
) {
content()
}
}
| 0
|
Kotlin
|
0
| 0
|
9d6daea9fa00a172dca17a317854da8ea12b46ea
| 12,416
|
XComposer
|
Apache License 2.0
|
src/main/kotlin/de/debuglevel/monitoring/monitors/TcpMonitor.kt
|
debuglevel
| 151,229,232
| false
| null |
package de.debuglevel.monitoring.monitors
import de.debuglevel.monitoring.ServiceState
import de.debuglevel.monitoring.monitoring.Monitoring
import mu.KotlinLogging
import java.net.*
class TcpMonitor : Monitor {
private val logger = KotlinLogging.logger {}
override fun isValid(url: String): Boolean {
val uri = try {
URI(url)
} catch (e: Exception) {
return false
}
if (uri.port < 0 || uri.port > 65535) {
return false
}
return true
}
override fun check(monitoring: Monitoring): ServiceState {
return try {
val socket = Socket()
val timeout = 500
socket.soTimeout = timeout
try {
logger.debug { "Connecting to socket with timeout ${timeout}ms..." }
socket.connect(InetSocketAddress(URI(monitoring.url).host, URI(monitoring.url).port), timeout)
logger.debug { "Connected to socket" }
ServiceState.Up
} catch (e: Exception) {
logger.debug { "Connection to socket failed: ${e.message}" }
logger.debug { "Host is down due to: ${e.message}" }
ServiceState.Down
} finally {
logger.debug { "Closing socket..." }
socket.close()
logger.debug { "Closed socket" }
}
} catch (e: UnknownHostException) {
logger.debug { "Host is down due to: ${e.message}" }
ServiceState.Down
} catch (e: ConnectException) {
logger.debug { "Host is down due to: ${e.message}" }
ServiceState.Down
} catch (e: NoRouteToHostException) {
logger.debug { "Host is down due to: ${e.message}" }
ServiceState.Down
} catch (e: Exception) {
logger.warn(e) { "Unhandled exception" }
ServiceState.Down
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e82a562af83b39c4b83835360473b34765abe1fe
| 1,963
|
monitoring-microservice
|
The Unlicense
|
theme-controller/src/main/java/com/vkondrav/ram/theme/controller/usecase/ToggleThemeUseCase.kt
|
vkondrav
| 481,052,423
| false
| null |
package com.vkondrav.ram.theme.controller.usecase
import com.vkondrav.ram.theme.controller.core.ThemeController
class ToggleThemeUseCase(
private val themeController: ThemeController,
) {
operator fun invoke() {
themeController.toggleTheme()
}
}
| 0
|
Kotlin
|
1
| 0
|
78c466563652800d8001a58504a533b764507461
| 268
|
rick_and_morty_compose
|
MIT License
|
src/main/kotlin/marais/vibin/App.kt
|
Gui-Yom
| 312,903,100
| false
| null |
package marais.vibin
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import uk.co.caprica.vlcj.factory.MediaPlayerFactory
import uk.co.caprica.vlcj.player.base.MediaPlayer
import uk.co.caprica.vlcj.player.base.MediaPlayerEventAdapter
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent
import uk.co.caprica.vlcj.player.component.InputEvents
import uk.co.caprica.vlcj.player.embedded.fullscreen.unsupported.UnsupportedFullScreenStrategy
import java.awt.*
import java.awt.event.MouseEvent
import java.awt.event.MouseWheelEvent
import java.io.File
import java.net.URLConnection
import java.util.concurrent.locks.ReentrantLock
import javax.swing.event.MouseInputAdapter
import kotlin.concurrent.withLock
import kotlin.system.exitProcess
fun main() {
val config: Config = Json.decodeFromString(File("config.vibin.json").readText())
val mediaDir = File(config.player_settings.mediaDir)
if (!mediaDir.exists() || !mediaDir.isDirectory || mediaDir.list() == null) {
println("Wrong media directory ${config.player_settings.mediaDir}.")
exitProcess(-1)
}
val mediaFiles = mediaDir.listFiles { file, name ->
URLConnection.guessContentTypeFromName(name).startsWith("video")
}
if (mediaFiles == null || mediaFiles.isEmpty()) {
println("No playable video found in ${config.player_settings.mediaDir}")
exitProcess(-1)
}
val frame = Frame("Vibin")
frame.isResizable = false
frame.isUndecorated = true
frame.isAlwaysOnTop = config.player_settings.alwaysOnTop
frame.size = Dimension(128, 128)
frame.layout = BorderLayout()
frame.opacity = config.player_settings.opacity
val factory = MediaPlayerFactory()
val playerComponent =
EmbeddedMediaPlayerComponent(factory, null, UnsupportedFullScreenStrategy(), InputEvents.DISABLE_NATIVE, null)
val player = playerComponent.mediaPlayer()
player.video().setScale(0.5f)
val lock = ReentrantLock()
val lockCondition = lock.newCondition()
var mediaPointer = -1
fun playNext() {
val newPtr = ++mediaPointer
val media = if (newPtr < mediaFiles.size) mediaFiles[newPtr] else {
mediaPointer = 0
mediaFiles[0]
}
val options = config.getMediaOptions(media.name) ?: MediaOptionsEntry("")
player.media().start(config.player_settings.mediaDir + media, "--volume ${options.defaultVolume}")
}
val listener = object : MouseInputAdapter() {
var location: Point? = null
var pressed: MouseEvent? = null
override fun mouseClicked(e: MouseEvent) {
if (e.button == MouseEvent.BUTTON1 && e.isControlDown) {
if (player.status().isPlaying) player.controls().pause() else player.controls().play()
} else if (e.button == MouseEvent.BUTTON2) {
lock.withLock { lockCondition.signalAll() }
} else if (e.button == MouseEvent.BUTTON3) {
player.controls().stop()
playNext()
}
}
override fun mousePressed(e: MouseEvent) {
pressed = e
}
override fun mouseDragged(e: MouseEvent) {
val component: Component = frame
location = component.getLocation(location)
val x: Int = location!!.x - pressed!!.x + e.x
val y: Int = location!!.y - pressed!!.y + e.y
component.setLocation(x, y)
}
override fun mouseWheelMoved(e: MouseWheelEvent) {
if (e.isControlDown) {
frame.opacity = (frame.opacity - e.wheelRotation * 0.1f).coerceIn(config.player_settings.minOpacity, 1f)
} else {
player.submit {
player.audio().setVolume(player.audio().volume() - e.wheelRotation * 5)
}
println(player.audio().volume())
}
}
}
playerComponent.videoSurfaceComponent().addMouseListener(listener)
playerComponent.videoSurfaceComponent().addMouseMotionListener(listener)
playerComponent.videoSurfaceComponent().addMouseWheelListener(listener)
frame.add(playerComponent, BorderLayout.CENTER)
frame.isVisible = true
player.events().addMediaPlayerEventListener(object : MediaPlayerEventAdapter() {
override fun finished(mediaPlayer: MediaPlayer?) {
player.submit {
playNext()
}
}
})
playNext()
// Wait for window close event
lock.withLock { lockCondition.await() }
player.controls().stop()
playerComponent.release()
factory.release()
frame.dispose()
}
| 0
|
Kotlin
|
0
| 2
|
247c475288149a0b0277dabc2a00df4e3ef87392
| 4,691
|
vibin
|
Apache License 2.0
|
app/src/main/kotlin/de/nanogiants/a5garapp/model/entities/domain/NearbyPOI.kt
|
5GAR-Hackathon
| 283,319,676
| false
| null |
package de.nanogiants.a5garapp.model.entities.domain
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class NearbyPOI(
override val id: Int,
override val name: String,
override val description: String,
override val tags: List<Tag>,
override val coordinates: Coordinates,
override val images: List<Image>,
override val reviews: List<Review>,
override val upvotes: Int,
override val downvotes: Int,
override val openingHours: List<OpeningHour>,
val address: String,
val distance: Float,
val url: String
) : POI(id, name, description, tags, coordinates, images, reviews, upvotes, downvotes, openingHours, null)
| 0
|
Kotlin
|
0
| 1
|
c672c4b0353ca3c27d06268c27ae49b5252dc848
| 662
|
5g-ar-hackathon-app-android
|
MIT License
|
moviedb/src/main/java/com/santimattius/moviedb/network/model/Tv.kt
|
santimattius
| 295,560,177
| false
| null |
package com.santimattius.moviedb.network.model
import com.squareup.moshi.Json
private const val BASE_IMAGE_URL = "https://image.tmdb.org/t/p/w500"
data class Tv(
@Json(name = "id")
val id: Int = 0,
@Json(name = "first_air_date")
val firstAirDate: String = "",
@Json(name = "overview")
val overview: String = "",
@Json(name = "original_language")
val originalLanguage: String = "",
@Json(name = "genre_ids")
val genreIds: List<Int> = emptyList(),
@Json(name = "poster_path")
private val posterPath: String?,
@Json(name = "origin_country")
val originCountry: List<String> = emptyList(),
@Json(name = "backdrop_path")
val backdropPath: String?,
@Json(name = "original_name")
val originalName: String = "",
@Json(name = "popularity")
val popularity: Double = 0.0,
@Json(name = "vote_average")
val voteAverage: Double = 0.0,
@Json(name = "name")
val name: String = "",
@Json(name = "vote_count")
val voteCount: Int = 0
) {
val poster: String
get() = "$BASE_IMAGE_URL${posterPath}"
}
| 0
|
Kotlin
|
0
| 4
|
75083390066ad4850d94bb7f3e6af5e19511407c
| 1,097
|
android-sample-paging
|
Apache License 2.0
|
HIGOODS-Infra/src/main/kotlin/com/higoods/infra/config/slack/SlackProperties.kt
|
higoods-hongik
| 663,934,695
| false
|
{"Kotlin": 324199, "Dockerfile": 291}
|
package com.higoods.infra.config.slack
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.ConstructorBinding
@ConfigurationProperties(prefix = "slack")
@ConstructorBinding
data class SlackProperties(
val webhook: SlackSecret
) {
data class SlackSecret(
val token: String,
val url: String,
val channelId: String,
val userName: String
)
}
| 4
|
Kotlin
|
0
| 1
|
5cc4812aa57ce6706e62bc1566eccb7c02a01c82
| 458
|
HIGOODS-Backend
|
MIT License
|
appupdatewrapper/src/main/java/com/motorro/appupdatewrapper/UpdateFlowBreaker.kt
|
dev-mgkaung
| 302,810,342
| true
|
{"Kotlin": 118087}
|
/*
* Copyright 2019 <NAME> (motorro).
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package com.motorro.appupdatewrapper
import android.content.SharedPreferences
import java.util.concurrent.TimeUnit
/**
* Checks if user has already refused to install update and terminates update flow
*/
interface UpdateFlowBreaker: TimeCancelledStorage {
/**
* Checks if enough time has passed since user had explicitly cancelled update
*/
fun isEnoughTimePassedSinceLatestCancel(): Boolean
companion object {
/**
* Creates a dummy breaker that never interrupts callback
*/
fun alwaysOn(): UpdateFlowBreaker = AlwaysOn
/**
* Creates a breaker that checks if given interval has passed since last time user had cancelled update
* @param interval An interval between user cancels the update and the next time he is prompted
* @param timeUnit Time-units the interval is measured in
* @param storage Stores time cancelled
*/
fun withInterval(interval: Long, timeUnit: TimeUnit, storage: TimeCancelledStorage): UpdateFlowBreaker =
IntervalBreaker(interval, timeUnit, storage)
/**
* Creates a breaker to delay update for one day
* @param storage Stores time cancelled
*/
fun forOneDay(storage: TimeCancelledStorage): UpdateFlowBreaker =
withInterval(1L, TimeUnit.DAYS, storage)
/**
* Creates a breaker to delay update for one day storing data in [SharedPreferences]
* @param storage SharedPreferences instance
*/
fun forOneDay(storage: SharedPreferences): UpdateFlowBreaker =
withInterval(1L, TimeUnit.DAYS, TimeCancelledStorage.withPreferences(storage))
}
}
/**
* Always-on flow breaker
*/
internal object AlwaysOn: UpdateFlowBreaker {
override fun isEnoughTimePassedSinceLatestCancel(): Boolean = true
override fun getTimeCanceled(): Long = 0
override fun saveTimeCanceled() = Unit
}
/**
* Checks if given interval has passed since last time user had cancelled update
* @param interval An interval between user cancels the update and the next time he is prompted
* @param timeUnit Time-units the interval is measured in
* @param storage Stores time cancelled
* @param clock Time provider
*/
internal class IntervalBreaker(
interval: Long,
timeUnit: TimeUnit,
private val storage: TimeCancelledStorage,
private val clock: Clock = Clock.SYSTEM
): UpdateFlowBreaker, TimeCancelledStorage by storage, Tagged {
/**
* [isEnoughTimePassedSinceLatestCancel] will return `true` after this interval since latest cancel
*/
private val intervalMillis = timeUnit.toMillis(interval)
/**
* Checks if enough time has passed since user had explicitly cancelled update
*/
override fun isEnoughTimePassedSinceLatestCancel(): Boolean {
val timeCancelled = storage.getTimeCanceled()
val currentTime = clock.getMillis()
return (currentTime - timeCancelled > intervalMillis).also {
timber.d(
"Last time cancelled: %d, Current time: %d, Enough time passed: %s",
timeCancelled,
currentTime,
if(it) "yes" else "no"
)
}
}
}
/**
* Stores time the update was cancelled
*/
interface TimeCancelledStorage {
/**
* Gets the latest time user has explicitly cancelled update (in milliseconds)
*/
fun getTimeCanceled(): Long
/**
* Saves current time as the latest one user has explicitly cancelled update
*/
fun saveTimeCanceled()
companion object {
/**
* Creates [SharedPreferences] storage
* @param storage SharedPreferences instance
*/
fun withPreferences(storage: SharedPreferences): TimeCancelledStorage = WithPreferences(storage)
}
}
/**
* Stores time cancelled in shared preferences
* @param storage SharedPreferences instance
* @param clock Time provider
*/
internal class WithPreferences(
private val storage: SharedPreferences,
private val clock: Clock = Clock.SYSTEM
): TimeCancelledStorage, Tagged {
/**
* Gets the latest time user has explicitly cancelled update
*/
override fun getTimeCanceled(): Long = storage.getLong(LATEST_CANCEL_PROPERTY, 0)
/**
* Saves current time as the latest one user has explicitly cancelled update
*/
override fun saveTimeCanceled() {
val currentTime = clock.getMillis()
timber.d("Saving time cancelled: %d", currentTime)
storage
.edit()
.putLong(LATEST_CANCEL_PROPERTY, currentTime)
.apply()
}
}
| 0
| null |
0
| 0
|
726b233cb16372b0138cae73edd1f0abdecfe1ee
| 5,254
|
AppUpdateWrapper
|
Apache License 2.0
|
app/src/main/java/me/robbin/wanandroid/ui/fragment/me/viewmodel/ProjectViewModel.kt
|
ModestoMa
| 278,850,144
| false
| null |
package me.robbin.wanandroid.ui.fragment.me.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.paging.PagingData
import kotlinx.coroutines.flow.Flow
import me.robbin.wanandroid.ui.fragment.common.viewmodel.BaseArticlesViewModel
import me.robbin.wanandroid.api.ApiService
import me.robbin.wanandroid.model.Article
import me.robbin.wanandroid.model.Chapter
import me.robbin.wanandroid.ui.fragment.common.view.ArticleType
/**
* 项目界面 ViewModel
* Create by Robbin at 2020/7/27
*/
class ProjectViewModel : BaseArticlesViewModel() {
val projectList: MutableLiveData<MutableList<Chapter>> = MutableLiveData()
val cid: MutableLiveData<Int> = MutableLiveData()
/**
* 获取项目分类列表
* Create by Robbin at 2020/7/27
*/
fun getProjectList() =
launchGo(
block = { projectList.value = ApiService.getApi().getProjectList().data }
)
/**
* 根据 cid 获取文章列表
* Create by Robbin at 2020/7/27
*/
override fun getArticles(type: ArticleType, cid: Int): Flow<PagingData<Article>> =
articleRepository.getArticles(ArticleType.PROJECT, cid)
}
| 1
|
Kotlin
|
1
| 21
|
e8808e53b6a26110ea3e5d4e710a62545b237b0d
| 1,122
|
WanAndroidMVVM
|
Apache License 2.0
|
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotcover/report/BundledDotCover.kt
|
JetBrains
| 49,584,664
| false
|
{"Kotlin": 2624677, "C#": 319161, "Java": 95520, "Dockerfile": 831, "CSS": 123}
|
package jetbrains.buildServer.dotcover.report
import jetbrains.buildServer.agent.BundledToolsRegistry
import jetbrains.buildServer.dotnet.CoverageConstants
import jetbrains.buildServer.util.FileUtil
import java.io.File
class BundledDotCover(private val _registry: BundledToolsRegistry) {
val dotCoverPath: File?
get() {
val tool = _registry.findTool(CoverageConstants.DOTCOVER_BUNDLED_TOOL_ID) ?: return null
val path = FileUtil.getCanonicalFile(tool.rootPath)
return if (!path.isDirectory) null else path
}
}
| 3
|
Kotlin
|
25
| 94
|
9665e2ac5c4e70b3b50b95275346cce1f95574d5
| 569
|
teamcity-dotnet-plugin
|
Apache License 2.0
|
src/main/kotlin/com/unscrambler/controllers/WordController.kt
|
blrB
| 93,422,946
| false
| null |
package com.unscrambler.controllers
import com.unscrambler.models.Word
import com.unscrambler.models.getLanguageByString
import com.unscrambler.services.WordService
import org.springframework.web.bind.annotation.*
@RestController
class WordController(val wordService: WordService) {
@RequestMapping(value = "{lang}/word/{letters}")
fun getWords(@PathVariable("lang") lang: String, @PathVariable("letters") letters: String): List<Word> {
val language = getLanguageByString(lang)
return wordService.findAllByTemplate(language, letters)
}
}
| 0
|
Kotlin
|
0
| 0
|
225fa64c1b4da63db237ebce81b250cf39996304
| 569
|
UnscramblerWord
|
The Unlicense
|
kukot/src/main/java/com/abohomol/kukot/user/RetrofitUserProfileRepository.kt
|
abohomol
| 138,405,695
| false
| null |
package com.abohomol.kukot.user
import com.abohomol.kukot.network.BaseRepository
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class RetrofitUserProfileRepository(
private val profileService: ProfileService,
secret: String
) : BaseRepository(secret) {
fun getUserProfile(): Single<UserProfile> {
return profileService.getUserProfile(getHeaders(ENDPOINT, ""), ENDPOINT)
.doOnSuccess { onResponse(it) }
.map { it.data }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
companion object {
private const val ENDPOINT = "/v1/user/info"
}
}
| 0
|
Kotlin
|
2
| 11
|
73576cd218506ee8bde52cae65a6a727470c5f0a
| 756
|
kukot
|
Apache License 2.0
|
common/resources/src/main/java/com/juzabel/composables/CommonComposables.kt
|
juzabel
| 810,698,846
| false
|
{"Kotlin": 42936}
|
package com.juzabel.composables
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.width
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
@Composable
fun Loading() {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator(
modifier = Modifier.width(64.dp),
color = MaterialTheme.colorScheme.secondary,
trackColor = MaterialTheme.colorScheme.surfaceVariant
)
}
}
@Composable
fun ErrorMessage(error: String? = "") {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
Text(
text = stringResource(id = com.juzabel.resources.R.string.error_message) + " " + error,
style = MaterialTheme.typography.titleLarge
)
}
}
| 0
|
Kotlin
|
0
| 0
|
36739eba94bd163c989d6e336e3dadb020a9731e
| 1,225
|
user-list-test
|
MIT License
|
browser-kotlin/src/jsMain/kotlin/web/gpu/GPUStoreOp.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6272741}
|
// Automatically generated - do not modify!
package web.gpu
import seskar.js.JsValue
sealed external interface GPUStoreOp {
companion object {
@JsValue("store")
val store: GPUStoreOp
@JsValue("discard")
val discard: GPUStoreOp
}
}
| 0
|
Kotlin
|
8
| 36
|
95b065622a9445caf058ad2581f4c91f9e2b0d91
| 275
|
types-kotlin
|
Apache License 2.0
|
library/src/main/java/com/afollestad/aesthetic/views/AestheticNavigationView.kt
|
weidiaoxiang
| 149,248,717
| true
|
{"Kotlin": 170261}
|
/*
* Licensed under Apache-2.0
*
* Designed and developed by <NAME> (@afollestad)
*/
package com.afollestad.aesthetic.views
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.StateListDrawable
import android.util.AttributeSet
import com.afollestad.aesthetic.Aesthetic
import com.afollestad.aesthetic.ColorIsDarkState
import com.afollestad.aesthetic.ColorIsDarkState.Companion.creator
import com.afollestad.aesthetic.NavigationViewMode.SELECTED_ACCENT
import com.afollestad.aesthetic.NavigationViewMode.SELECTED_PRIMARY
import com.afollestad.aesthetic.R.color
import com.afollestad.aesthetic.utils.adjustAlpha
import com.afollestad.aesthetic.utils.color
import com.afollestad.aesthetic.utils.distinctToMainThread
import com.afollestad.aesthetic.utils.onErrorLogAndRethrow
import com.google.android.material.navigation.NavigationView
import io.reactivex.Observable.combineLatest
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
/** @author <NAME> (afollestad) */
@SuppressLint("RestrictedApi")
class AestheticNavigationView(
context: Context,
attrs: AttributeSet? = null
) : NavigationView(context, attrs) {
private var modeSubscription: Disposable? = null
private var colorSubscription: Disposable? = null
private fun invalidateColors(state: ColorIsDarkState) {
val selectedColor = state.color
val isDark = state.isDark
val baseColor = if (isDark) Color.WHITE else Color.BLACK
val unselectedIconColor = baseColor.adjustAlpha(.54f)
val unselectedTextColor = baseColor.adjustAlpha(.87f)
val selectedItemBgColor = context.color(
if (isDark)
color.ate_navigation_drawer_selected_dark
else
color.ate_navigation_drawer_selected_light
)
val iconSl = ColorStateList(
arrayOf(
intArrayOf(-android.R.attr.state_checked), intArrayOf(android.R.attr.state_checked)
),
intArrayOf(unselectedIconColor, selectedColor)
)
val textSl = ColorStateList(
arrayOf(
intArrayOf(-android.R.attr.state_checked), intArrayOf(android.R.attr.state_checked)
),
intArrayOf(unselectedTextColor, selectedColor)
)
itemTextColor = textSl
itemIconTintList = iconSl
val bgDrawable = StateListDrawable()
bgDrawable.addState(
intArrayOf(android.R.attr.state_checked), ColorDrawable(selectedItemBgColor)
)
itemBackground = bgDrawable
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
modeSubscription = Aesthetic.get()
.navigationViewMode()
.distinctToMainThread()
.subscribe(
Consumer { mode ->
when (mode) {
SELECTED_PRIMARY ->
colorSubscription = combineLatest(
Aesthetic.get().colorPrimary(),
Aesthetic.get().isDark,
creator()
)
.distinctToMainThread()
.subscribe(
Consumer { this.invalidateColors(it) },
onErrorLogAndRethrow()
)
SELECTED_ACCENT ->
colorSubscription = combineLatest(
Aesthetic.get().colorAccent(),
Aesthetic.get().isDark,
creator()
)
.distinctToMainThread()
.subscribe(
Consumer { colors -> invalidateColors(colors) },
onErrorLogAndRethrow()
)
else -> throw IllegalStateException("Unknown nav view mode: $mode")
}
},
onErrorLogAndRethrow()
)
}
override fun onDetachedFromWindow() {
modeSubscription?.dispose()
colorSubscription?.dispose()
super.onDetachedFromWindow()
}
}
| 0
|
Kotlin
|
0
| 0
|
867080a54b5afcf9526e6d1f072a295cad79ecb8
| 4,090
|
aesthetic
|
Apache License 2.0
|
src/main/kotlin/net/bjoernpetersen/deskbot/lifecycle/Lifecyclist.kt
|
BjoernPetersen
| 89,800,914
| false
| null |
package net.bjoernpetersen.deskbot.lifecycle
import com.google.inject.Guice
import com.google.inject.Injector
import com.google.inject.Module
import javafx.application.Platform
import javafx.concurrent.Task
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import net.bjoernpetersen.deskbot.fximpl.FxProgressFeedback
import net.bjoernpetersen.deskbot.impl.Broadcaster
import net.bjoernpetersen.deskbot.impl.FileConfigStorage
import net.bjoernpetersen.deskbot.impl.FileStorageImpl
import net.bjoernpetersen.deskbot.impl.ImageLoaderImpl
import net.bjoernpetersen.deskbot.impl.MainConfigEntries
import net.bjoernpetersen.deskbot.impl.SongPlayedNotifierModule
import net.bjoernpetersen.deskbot.rest.KtorServer
import net.bjoernpetersen.deskbot.view.DeskBot
import net.bjoernpetersen.deskbot.view.get
import net.bjoernpetersen.deskbot.view.show
import net.bjoernpetersen.musicbot.api.auth.BotUser
import net.bjoernpetersen.musicbot.api.auth.DefaultPermissions
import net.bjoernpetersen.musicbot.api.config.ConfigManager
import net.bjoernpetersen.musicbot.api.config.GenericConfigScope
import net.bjoernpetersen.musicbot.api.config.MainConfigScope
import net.bjoernpetersen.musicbot.api.config.PluginConfigScope
import net.bjoernpetersen.musicbot.api.config.listSerializer
import net.bjoernpetersen.musicbot.api.config.serialization
import net.bjoernpetersen.musicbot.api.config.serialized
import net.bjoernpetersen.musicbot.api.module.BrowserOpenerModule
import net.bjoernpetersen.musicbot.api.module.ConfigModule
import net.bjoernpetersen.musicbot.api.module.DefaultDatabaseConnectionModule
import net.bjoernpetersen.musicbot.api.module.DefaultImageCacheModule
import net.bjoernpetersen.musicbot.api.module.DefaultPlayerModule
import net.bjoernpetersen.musicbot.api.module.DefaultQueueModule
import net.bjoernpetersen.musicbot.api.module.DefaultResourceCacheModule
import net.bjoernpetersen.musicbot.api.module.DefaultSongLoaderModule
import net.bjoernpetersen.musicbot.api.module.DefaultTokenHandlerModule
import net.bjoernpetersen.musicbot.api.module.DefaultUserDatabaseModule
import net.bjoernpetersen.musicbot.api.module.FileStorageModule
import net.bjoernpetersen.musicbot.api.module.InstanceStopper
import net.bjoernpetersen.musicbot.api.module.PluginClassLoaderModule
import net.bjoernpetersen.musicbot.api.module.PluginModule
import net.bjoernpetersen.musicbot.api.player.PlayerState
import net.bjoernpetersen.musicbot.api.player.QueueEntry
import net.bjoernpetersen.musicbot.api.plugin.PluginLoaderImpl
import net.bjoernpetersen.musicbot.api.plugin.category
import net.bjoernpetersen.musicbot.api.plugin.management.DefaultDependencyManager
import net.bjoernpetersen.musicbot.api.plugin.management.PluginFinder
import net.bjoernpetersen.musicbot.api.plugin.management.findDependencies
import net.bjoernpetersen.musicbot.spi.player.Player
import net.bjoernpetersen.musicbot.spi.player.QueueChangeListener
import net.bjoernpetersen.musicbot.spi.player.SongQueue
import net.bjoernpetersen.musicbot.spi.plugin.NoSuchSongException
import net.bjoernpetersen.musicbot.spi.plugin.Plugin
import net.bjoernpetersen.musicbot.spi.plugin.PluginLookup
import net.bjoernpetersen.musicbot.spi.plugin.Provider
import net.bjoernpetersen.musicbot.spi.plugin.Suggester
import net.bjoernpetersen.musicbot.spi.plugin.management.DependencyManager
import net.bjoernpetersen.musicbot.spi.util.BrowserOpener
import org.controlsfx.control.TaskProgressView
import java.io.File
import java.io.IOException
import java.nio.file.Paths
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
import javax.inject.Inject
import kotlin.concurrent.thread
import kotlin.concurrent.withLock
import kotlin.coroutines.CoroutineContext
@Suppress("TooManyFunctions")
class Lifecyclist : CoroutineScope {
private val logger = KotlinLogging.logger {}
private lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Default + job
var stage: Stage = Stage.New
private set
// Created stage vars
private lateinit var configManager: ConfigManager
private lateinit var classLoader: ClassLoader
private lateinit var dependencyManager: DependencyManager
// Injected stage vars
private lateinit var pluginFinder: PluginFinder
private lateinit var injector: Injector
private lateinit var mainConfig: MainConfigEntries
// Run stage vars
private lateinit var broadcaster: Broadcaster
private fun <T> stagedBlock(stage: Stage, exact: Boolean = true, action: () -> T): T {
if (exact) {
check(this.stage == stage)
} else {
check(this.stage >= stage)
}
return action()
}
private suspend fun <T> staged(
stage: Stage,
exact: Boolean = true,
action: suspend () -> T
): T {
if (exact) {
check(this.stage == stage)
} else {
check(this.stage >= stage)
}
return action()
}
fun getConfigManager() = stagedBlock(Stage.Created, false) { configManager }
fun getPluginClassLoader() = stagedBlock(Stage.Created, false) { classLoader }
fun getDependencyManager() = stagedBlock(
Stage.Created, false
) { dependencyManager }
fun getPluginFinder() = stagedBlock(Stage.Injected, false) { pluginFinder }
fun getInjector() = stagedBlock(Stage.Injected, false) { injector }
fun getMainConfig() = stagedBlock(Stage.Injected, false) { mainConfig }
private fun createConfig() {
configManager = ConfigManager(
FileConfigStorage(configDir),
FileConfigStorage(secretDir),
FileConfigStorage(stateDir)
)
}
private fun createPlugins(pluginDir: File) {
val loader = PluginLoaderImpl(pluginDir)
dependencyManager = DefaultDependencyManager(configManager[MainConfigScope].plain, loader)
classLoader = loader.loader
}
fun create(pluginDir: File): DependencyManager = stagedBlock(Stage.New) {
job = Job()
createConfig()
createPlugins(pluginDir)
stage = Stage.Created
dependencyManager
}
private fun modules(browserOpener: BrowserOpener, suggester: Suggester?): List<Module> = listOf(
ConfigModule(configManager),
DefaultPlayerModule(suggester),
DefaultQueueModule(),
DefaultSongLoaderModule(),
DefaultDatabaseConnectionModule(Paths.get("UserDatabase.db")),
DefaultUserDatabaseModule(),
DefaultTokenHandlerModule(),
PluginClassLoaderModule(classLoader),
PluginModule(pluginFinder),
BrowserOpenerModule(browserOpener),
SongPlayedNotifierModule(),
DefaultImageCacheModule(),
ImageLoaderImpl,
DefaultResourceCacheModule(),
FileStorageModule(FileStorageImpl::class)
)
fun inject(browserOpener: BrowserOpener) = stagedBlock(Stage.Created) {
pluginFinder = dependencyManager.finish(emptyList(), emptyList())
mainConfig = MainConfigEntries(configManager, pluginFinder, classLoader)
// TODO calling finish twice is terrible.
pluginFinder = dependencyManager.finish(
mainConfig.providerOrder.get() ?: emptyList(),
mainConfig.suggesterOrder.get() ?: emptyList()
)
val suggester = mainConfig.defaultSuggester.get()
logger.info { "Default suggester: ${suggester?.name}" }
injector = Guice.createInjector(modules(browserOpener, suggester))
pluginFinder.allPlugins().forEach {
injector.injectMembers(it)
}
pluginFinder.allPlugins().forEach {
val configs = configManager[PluginConfigScope(it::class)]
it.createConfigEntries(configs.plain)
it.createSecretEntries(configs.secrets)
it.createStateEntries(configs.state)
}
stage = Stage.Injected
}
suspend fun run(result: (Throwable?) -> Unit) = staged(Stage.Injected) {
// TODO rollback in case of failure
coroutineScope {
Initializer(pluginFinder).start {
if (it != null) {
logger.error(it) { "Could not initialize!" }
result(it)
return@start
}
DefaultPermissions.defaultPermissions = mainConfig.defaultPermissions.get()!!
val player = injector.getInstance(Player::class.java)
player.start()
val ktor = injector.getInstance(KtorServer::class.java)
ktor.start()
broadcaster = Broadcaster().apply { start() }
GlobalScope.launch {
val dumper = injector.getInstance(QueueDumper::class.java)
dumper.restoreQueue()
player.addListener { _, newState -> dumper.dumpQueue(newState) }
injector.getInstance(SongQueue::class.java)
.addListener(object : QueueChangeListener {
override fun onAdd(entry: QueueEntry) {
dumper.dumpQueue()
}
override fun onMove(entry: QueueEntry, fromIndex: Int, toIndex: Int) {
dumper.dumpQueue()
}
override fun onRemove(entry: QueueEntry) {
dumper.dumpQueue()
}
})
}
DeskBot.runningInstance = this@Lifecyclist
stage = Stage.Running
result(null)
}
}
}
fun stop() = stagedBlock(Stage.Running) {
try {
broadcaster.close()
} catch (e: IOException) {
logger.error(e) { "Could not close broadcaster" }
}
runBlocking {
coroutineScope {
withContext(coroutineContext) {
val stopper = InstanceStopper(injector).apply {
register(KtorServer::class.java) { ktor ->
ktor.close()
}
}
stopper.stop()
stage = Stage.Stopped
}
}
job.cancel()
}
}
enum class Stage {
Stopped, New, Created, Injected, Running
}
private companion object {
val stateDir = File("state")
val configDir = File("config")
val secretDir = File(configDir, "secret")
}
}
@Suppress("MagicNumber")
private class Initializer(private val finder: PluginFinder) {
private val logger = KotlinLogging.logger {}
fun start(result: (Throwable?) -> Unit) {
val view = TaskProgressView<Task<*>>()
val tasks = view.tasks
val lock: Lock = ReentrantLock()
val done = lock.newCondition()
val finished: MutableSet<Plugin> = HashSet(64)
val errors: MutableList<Throwable> = ArrayList()
val res = DeskBot.resources
val window = view.show(modal = true, title = res["window.initialization"])
val parentTask = object : Task<Unit>() {
override fun call() {
updateTitle(res["task.parent.title"])
updateMessage(res["task.parent.description"])
// TODO timeout/cancel
val todo = finder.run {
genericPlugins.size + playbackFactories.size + providers.size + suggesters.size
}.toLong()
updateProgress(0, todo)
lock.withLock {
var finishedCount = finished.size.toLong()
while (finishedCount != todo) {
updateProgress(finishedCount, todo)
done.await()
finishedCount = finished.size.toLong()
}
}
val exception = if (errors.isEmpty()) null
else errors.fold(Exception("One or more initializations failed")) { e, t ->
e.apply { addSuppressed(t) }
}
Platform.runLater {
result(exception)
window.close()
}
}
}
thread(name = "InitializationParent", isDaemon = true) { parentTask.run() }
tasks.add(parentTask)
finder.allPlugins().forEach { plugin ->
val task = object : Task<Unit>() {
val writer = FxProgressFeedback(::updateMessage)
override fun call() {
updateTitle(
res["task.plugin.title"].format(plugin.category.simpleName, plugin.name)
)
plugin.findDependencies()
.asSequence()
.map { finder[it]!! }
.forEach {
if (it !in finished) {
val type = it.category.simpleName
lock.withLock {
while (it !in finished) {
writer.state(
res["task.plugin.waiting"].format(type, it.name)
)
done.await()
}
}
}
}
writer.state("Starting...")
runBlocking {
@Suppress("TooGenericExceptionCaught")
try {
plugin.initialize(writer)
} catch (e: Throwable) {
logger.error(e) { "Could not initialize $plugin" }
throw e
}
}
lock.withLock {
finished.add(plugin)
done.signalAll()
}
}
}
tasks.add(task)
thread(isDaemon = true, name = "Init${plugin.category.simpleName}${plugin.name}") {
task.run()
}
}
}
}
private val songSerializer = serialization<Pair<String, String>> {
serialize { "${it.first}|${it.second}" }
deserialize { it.split('|').let { (a, b) -> a to b } }
}
private class QueueDumper @Inject private constructor(
private val queue: SongQueue,
private val player: Player,
private val pluginLookup: PluginLookup,
configManager: ConfigManager
) {
private val logger = KotlinLogging.logger {}
private val entry by configManager[GenericConfigScope(QueueDumper::class)].state
.serialized<List<Pair<String, String>>> {
serializer = songSerializer.listSerializer()
description = ""
check { null }
}
private var lastQueue: List<QueueEntry> = emptyList()
private fun buildDumpQueue(
playerState: PlayerState,
queue: List<QueueEntry>
): List<QueueEntry> {
val result = ArrayList<QueueEntry>(queue.size)
val currentEntry = playerState.entry
if (currentEntry is QueueEntry) {
// If there is a current song which has not been auto-suggested, prepend it
logger.debug { "Dumping current song first" }
result.add(currentEntry)
} else {
logger.debug { "Not dumping current song. State: ${player.state}" }
}
result.addAll(queue)
return result
}
fun dumpQueue(playerState: PlayerState = player.state) {
logger.debug { "Dumping queue" }
val dumpQueue = buildDumpQueue(playerState, queue.toList())
if (dumpQueue == lastQueue) {
logger.debug { "Not dumping unchanged queue." }
return
} else {
lastQueue = dumpQueue
}
entry.set(dumpQueue.map { it.song.provider.id to it.song.id })
}
suspend fun restoreQueue() {
logger.info("Restoring queue")
withContext(Dispatchers.IO) {
val pairs = entry.get()
if (pairs.isNullOrEmpty()) return@withContext
val songs = pairs.asSequence()
.map { pluginLookup.lookup<Provider>(it.first) to it.second }
.map {
async {
try {
it.first?.lookup(it.second)
} catch (e: NoSuchSongException) {
null
}
}
}
.toList()
songs.forEach {
val song = it.await()
if (song != null) {
queue.insert(QueueEntry(song, BotUser))
}
}
}
}
}
| 21
|
Kotlin
|
1
| 1
|
c66cdad693ae982d51780d3a9dbee5c1b1909820
| 17,386
|
MusicBot-desktop
|
MIT License
|
app/src/main/java/com/kevalpatel2106/yip/edit/EditDeadlineActivity.kt
|
kevalpatel2106
| 166,789,807
| false
| null |
package com.kevalpatel2106.yip.edit
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import androidx.databinding.DataBindingUtil
import androidx.navigation.navArgs
import com.kevalpatel2106.yip.R
import com.kevalpatel2106.yip.core.ext.getLaunchIntent
import com.kevalpatel2106.yip.core.ext.set
import com.kevalpatel2106.yip.core.ext.showOrHideLoader
import com.kevalpatel2106.yip.core.ext.showSnack
import com.kevalpatel2106.yip.core.livedata.nullSafeObserve
import com.kevalpatel2106.yip.core.livedata.nullSafeValue
import com.kevalpatel2106.yip.databinding.ActivityEditDeadlineBinding
import com.kevalpatel2106.yip.edit.EditDeadlineUseCases.conformBeforeExit
import com.kevalpatel2106.yip.edit.EditDeadlineUseCases.showDatePicker
import com.kevalpatel2106.yip.edit.EditDeadlineUseCases.showNotificationPickerDialog
import com.kevalpatel2106.yip.edit.colorPicker.ColorPickerListener
import com.kevalpatel2106.yip.edit.colorPicker.ColorsAdapter
import com.kevalpatel2106.yip.edit.notificationList.NotificationViewer
import com.kevalpatel2106.yip.payment.PaymentActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.activity_edit_deadline.edit_color
import kotlinx.android.synthetic.main.activity_edit_deadline.edit_deadline_description
import kotlinx.android.synthetic.main.activity_edit_deadline.edit_deadline_title
import kotlinx.android.synthetic.main.activity_edit_deadline.edit_toolbar
import kotlinx.android.synthetic.main.activity_edit_deadline.notification_times
@AndroidEntryPoint
internal class EditDeadlineActivity : AppCompatActivity(), ColorPickerListener,
NotificationViewer.NotificationViewerInterface {
private val navArgs by navArgs<EditDeadlineActivityArgs>()
private val model: EditDeadlineViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DataBindingUtil.setContentView<ActivityEditDeadlineBinding>(
this,
R.layout.activity_edit_deadline
).apply {
lifecycleOwner = this@EditDeadlineActivity
viewModel = model
}
// Actionbar set up
setSupportActionBar(edit_toolbar)
supportActionBar?.set(showTitle = false)
notification_times.callback = this
edit_deadline_title.doAfterTextChanged { model.onTitleChanged(it.toString()) }
edit_deadline_description.doAfterTextChanged { model.onDescriptionChanged(it.toString()) }
val colorsAdapter = setUpColorPicker()
// Monitor view model
monitorViewState(colorsAdapter)
monitorSingleViewEvent()
onNewIntent(intent)
}
private fun setUpColorPicker(): ColorsAdapter {
val colorsAdapter = ColorsAdapter(context = this, colorSelectedListener = this)
edit_color.adapter = colorsAdapter
return colorsAdapter
}
private fun monitorViewState(colorsAdapter: ColorsAdapter) {
model.viewState.nullSafeObserve(this@EditDeadlineActivity) { viewState ->
with(viewState) {
invalidateOptionsMenu()
if (!viewState.isTitleChanged()) {
edit_deadline_title.setText(initialTitle)
edit_deadline_title.setSelection(initialTitle.length)
}
if (!viewState.isDescriptionChanged()) {
edit_deadline_description.setText(initialDescription)
edit_deadline_description.setSelection(initialDescription.length)
}
colorsAdapter.setSelectedColor(selectedColor.colorInt)
colorsAdapter.isLocked = showLockedColorPicker
}
}
}
private fun monitorSingleViewEvent() {
model.singleViewState.nullSafeObserve(this@EditDeadlineActivity) { state ->
when (state) {
OpenPaymentScreen -> PaymentActivity.launch(this@EditDeadlineActivity)
CloseScreen -> finish()
ShowConfirmationDialog -> conformBeforeExit()
is ShowUserMessage -> {
showSnack(state.message, dismissListener = { if (state.closeScreen) finish() })
}
ShowNotificationPicker -> {
showNotificationPickerDialog { percent -> model.onNotificationAdded(percent) }
}
OpenDatePicker -> {
showDatePicker(
fragmentManager = supportFragmentManager,
startDateSelection = model.viewState.nullSafeValue().startTime,
endDateSelection = model.viewState.nullSafeValue().endTime,
listener = { start, end -> model.onDateRangeSelected(start, end) }
)
}
}
}
}
override fun addNotificationClicked() = model.onAddNotificationClicked()
override fun onNotificationRemoved(percent: Float) = model.onNotificationRemoved(percent)
override fun onColorSelected(color: Int) = model.onColorSelected(color)
override fun onNewIntent(intent: Intent?) {
model.setDeadlineId(navArgs.deadlineToEdit)
super.onNewIntent(intent)
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onBackPressed() = model.onClosePressed()
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_deadline_save, menu)
menu?.findItem(R.id.menu_deadline_save)?.showOrHideLoader(
context = this@EditDeadlineActivity,
isShow = model.viewState.nullSafeValue().isLoading
)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_deadline_save -> model.saveDeadline()
}
return super.onOptionsItemSelected(item)
}
companion object {
internal fun createNew(context: Context) = context.startActivity(createNewIntent(context))
internal fun createNewIntent(context: Context): Intent {
return context.getLaunchIntent(EditDeadlineActivity::class.java) {
putExtras(EditDeadlineActivityArgs().toBundle())
}
}
internal fun edit(context: Context, args: EditDeadlineActivityArgs) {
val intent = context.getLaunchIntent(EditDeadlineActivity::class.java) {
putExtras(args.toBundle())
}
context.startActivity(intent)
}
}
}
| 0
|
Kotlin
|
1
| 16
|
61311ba7d40802ba7fed87b2f16b72089c6f7746
| 6,843
|
year-in-progress
|
Apache License 2.0
|
app/src/main/java/pl/elpassion/cloudtimer/base/CloudTimerActivity.kt
|
elpassion
| 50,499,984
| false
| null |
package pl.elpassion.cloudtimer.base
import android.support.v7.app.AppCompatActivity
open class CloudTimerActivity : AppCompatActivity()
| 17
|
Kotlin
|
0
| 2
|
8b5d5af736356aa707d417cb219a75ea076d539b
| 138
|
cloud-timer-android
|
Apache License 2.0
|
app/src/test/java/com/amitranofinzi/vimata/data/dao/UserDaoTest.kt
|
Ggino11
| 788,949,158
| false
|
{"Kotlin": 399279}
|
package com.amitranofinzi.vimata.data.dao
import com.amitranofinzi.vimata.data.dao.UserDao
import com.amitranofinzi.vimata.data.model.User
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
class UserDaoTest {
// Mock UserDao object
private lateinit var userDao: UserDao
@Before
fun setup() {
// Initialize the UserDao mock
userDao = mock(UserDao::class.java)
}
@Test
fun insertUser_retrieveByPrimaryKey(): Unit = runBlocking {
// Arrange
val user = User(
uid = "user1",
email = "john.doe@example.com",
name = "John",
password = "hashed_password",
surname = "Doe",
userType = "ATHLETE"
)
`when`(userDao.getWithPrimaryKey("user1")).thenReturn(user)
// Act
userDao.insert(user)
val retrievedUser = userDao.getWithPrimaryKey("user1")
// Assert
assertEquals(user, retrievedUser)
verify(userDao).insert(user)
verify(userDao).getWithPrimaryKey("user1")
}
@Test
fun getWhereEqual_fieldEqualsValue(): Unit = runBlocking {
// Arrange
val user1 = User(
uid = "user1",
email = "john.doe@example.com",
name = "John",
password = "hashed_password",
surname = "Doe",
userType = "ATHLETE"
)
val user2 = User(
uid = "user2",
email = "jane.doe@example.com",
name = "Jane",
password = "hashed_password",
surname = "Doe",
userType = "TRAINER"
)
val expectedUsers = listOf(user1)
`when`(userDao.getWhereEqual("email", "john.doe@example.com")).thenReturn(expectedUsers)
// Act
val result = userDao.getWhereEqual("email", "john.doe@example.com")
// Assert
assertEquals(expectedUsers, result)
verify(userDao).getWhereEqual("email", "john.doe@example.com")
}
@Test
fun getWhereIn_fieldInValues(): Unit = runBlocking {
// Arrange
val user1 = User(
uid = "user1",
email = "john.doe@example.com",
name = "John",
password = "hashed_password",
surname = "Doe",
userType = "ATHLETE"
)
val user2 = User(
uid = "user2",
email = "jane.doe@example.com",
name = "Jane",
password = "hashed_password",
surname = "Doe",
userType = "TRAINER"
)
val user3 = User(
uid = "user3",
email = "jim.beam@example.com",
name = "Jim",
password = "hashed_password",
surname = "Beam",
userType = "ATHLETE"
)
val expectedUsers = listOf(user1, user3)
`when`(userDao.getWhereIn("uid", listOf("user1", "user3"))).thenReturn(expectedUsers)
// Act
val result = userDao.getWhereIn("uid", listOf("user1", "user3"))
// Assert
assertEquals(expectedUsers, result)
verify(userDao).getWhereIn("uid", listOf("user1", "user3"))
}
@Test
fun updateUser_checkUpdatedValues(): Unit = runBlocking {
// Arrange
val user = User(
uid = "user1",
email = "john.doe@example.com",
name = "John",
password = "hashed_password",
surname = "Doe",
userType = "ATHLETE"
)
val updatedUser = user.copy(name = "John Smith")
`when`(userDao.getWithPrimaryKey("user1")).thenReturn(updatedUser)
// Act
userDao.update(updatedUser)
val retrievedUser = userDao.getWithPrimaryKey("user1")
// Assert
assertEquals(updatedUser, retrievedUser)
verify(userDao).update(updatedUser)
verify(userDao).getWithPrimaryKey("user1")
}
@Test
fun getWithPrimaryKey_noUserFound(): Unit = runBlocking {
// Arrange
`when`(userDao.getWithPrimaryKey("non_existing_user_id")).thenReturn(null)
// Act
val retrievedUser = userDao.getWithPrimaryKey("non_existing_user_id")
// Assert
assertNull(retrievedUser)
verify(userDao).getWithPrimaryKey("non_existing_user_id")
}
}
| 0
|
Kotlin
|
0
| 0
|
e864fc070b7343394457425601c7e276968a2ca6
| 4,520
|
ProgettoAmitranoFinzi-progMob
|
MIT License
|
androidDemo/src/test/java/com/zachklipp/seqdiag/demo/DemoTest.kt
|
zach-klippenstein
| 578,426,759
| false
|
{"Kotlin": 97672, "Shell": 383}
|
package com.zachklipp.seqdiag.demo
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class DemoTest {
@get:Rule
val rule = createAndroidComposeRule<MainActivity>()
@Test
fun launches() {
rule.onNodeWithText("Label on a line").assertIsDisplayed()
}
}
| 1
|
Kotlin
|
1
| 60
|
8ea350740ac929cc8e3b3ed95ff42e56db315dbe
| 552
|
compose-seqdiag
|
Apache License 2.0
|
app/src/main/java/emu/cosmic/data/Permissions.kt
|
shadergz
| 664,406,301
| false
|
{"C++": 360624, "Kotlin": 52114, "CMake": 5937}
|
package emu.cosmic.data
import android.Manifest
class Permissions(val permissions: Array<String>) {
companion object {
val storageAccess = Permissions(arrayOf(Manifest.permission.MANAGE_EXTERNAL_STORAGE))
}
}
| 10
|
C++
|
5
| 192
|
d960de0b62a4637f8a2368ee1e5f0c5f69a95ef4
| 226
|
cosmic-station
|
MIT License
|
app/src/main/java/com/nb/daggermvvmdemo/extensions/Extenstions.kt
|
jayshah3893
| 219,512,909
| false
| null |
package com.nb.daggermvvmdemo.extensions
import android.app.Activity
import android.util.Log
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import com.nb.daggermvvmdemo.App.Companion.getAppInstance
import com.nb.daggermvvmdemo.R
fun Activity.toast(msg: String) = Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
fun Fragment.toast(msg: String) {
toast(msg)
}
fun Activity.toast(@StringRes msg: Int) = Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
fun Fragment.toast(@StringRes msg: Int) {
toast(msg)
}
fun logMessage(aMsg: String) = Log.d(getAppInstance().getString(R.string.app_name), aMsg)
fun logError(aMsg: String) = Log.e(getAppInstance().getString(R.string.app_name), aMsg)
| 0
|
Kotlin
|
0
| 1
|
c9211ab7f6c203421a712a5da05e0f5dc505916a
| 759
|
MVVM-Dagger-Retrofit-Rxjava2-Demo
|
MIT License
|
components-core/src/main/java/com/adyen/checkout/components/core/internal/ui/PermissionRequestingDelegate.kt
|
Adyen
| 91,104,663
| false
|
{"Kotlin": 4787892, "Shell": 4706}
|
/*
* Copyright (c) 2024 <NAME>.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by ararat on 8/1/2024.
*/
package com.adyen.checkout.components.core.internal.ui
import androidx.annotation.RestrictTo
import com.adyen.checkout.components.core.internal.PermissionRequestData
import kotlinx.coroutines.flow.Flow
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
interface PermissionRequestingDelegate {
val permissionFlow: Flow<PermissionRequestData>
}
| 22
|
Kotlin
|
66
| 126
|
c45a6ee4d2039163ae075436a9d1231ffcb16f5c
| 523
|
adyen-android
|
MIT License
|
app/src/main/java/app/eluvio/wallet/data/AspectRatio.kt
|
eluv-io
| 719,801,077
| false
|
{"Kotlin": 748789, "Java": 22753}
|
package app.eluvio.wallet.data
object AspectRatio {
const val SQUARE = 1f
const val WIDE = 16f / 9f // A.K.A. "Landscape"
const val POSTER = 2f / 3f // A.K.A. "Portrait"
fun parse(aspectRatioString: String?): Float? {
return when (aspectRatioString) {
"Square" -> SQUARE
"Wide", "Landscape" -> WIDE
"Poster", "Portrait" -> POSTER
else -> null
}
}
}
| 8
|
Kotlin
|
1
| 0
|
d9fc4a936b1b8c0186812fc75faaaf6ffbcec7f5
| 435
|
elv-wallet-android
|
MIT License
|
data/src/main/java/dev/mslalith/focuslauncher/data/di/modules/DtoMapperModule.kt
|
mslalith
| 453,114,601
| false
| null |
package dev.mslalith.focuslauncher.data.di.modules
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dev.mslalith.focuslauncher.data.database.dao.AppsDao
import dev.mslalith.focuslauncher.data.database.dao.QuotesDao
import dev.mslalith.focuslauncher.data.dto.AppToRoomMapper
import dev.mslalith.focuslauncher.data.dto.FavoriteToRoomMapper
import dev.mslalith.focuslauncher.data.dto.HiddenToRoomMapper
import dev.mslalith.focuslauncher.data.dto.QuoteResponseToRoomMapper
import dev.mslalith.focuslauncher.data.dto.QuoteToRoomMapper
import javax.inject.Qualifier
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DtoMapperModule {
@AppToRoomMapperProvider
@Provides
@Singleton
fun provideAppToRoomMapper(): AppToRoomMapper = AppToRoomMapper()
@FavoriteToRoomMapperProvider
@Provides
@Singleton
fun provideFavoriteToRoomMapper(
appsDao: AppsDao,
@AppToRoomMapperProvider appToRoomMapper: AppToRoomMapper
): FavoriteToRoomMapper = FavoriteToRoomMapper(
appsDao = appsDao,
appToRoomMapper = appToRoomMapper
)
@HiddenToRoomMapperProvider
@Provides
@Singleton
fun provideHiddenToRoomMapper(
appsDao: AppsDao,
@AppToRoomMapperProvider appToRoomMapper: AppToRoomMapper
): HiddenToRoomMapper = HiddenToRoomMapper(
appsDao = appsDao,
appToRoomMapper = appToRoomMapper
)
@QuoteToRoomMapperProvider
@Provides
@Singleton
fun provideQuoteToRoomMapper(quotesDao: QuotesDao): QuoteToRoomMapper = QuoteToRoomMapper(quotesDao)
@QuoteResponseToRoomMapperProvider
@Provides
@Singleton
fun provideQuoteResponseToRoomMapper(): QuoteResponseToRoomMapper = QuoteResponseToRoomMapper()
}
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class AppToRoomMapperProvider
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class FavoriteToRoomMapperProvider
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class HiddenToRoomMapperProvider
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class QuoteToRoomMapperProvider
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class QuoteResponseToRoomMapperProvider
| 8
|
Kotlin
|
5
| 40
|
3298e2505e9f3eb6f8760b603586bd8c60d065e4
| 2,321
|
focus_launcher
|
Apache License 2.0
|
library/src/commonMain/kotlin/com/ioki/passenger/api/models/ApiPersonalDiscountTypeResponse.kt
|
ioki-mobility
| 838,801,042
| false
|
{"Kotlin": 344735}
|
package com.ioki.passenger.api.models
import kotlinx.datetime.LocalDate
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.nullable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
@Serializable
public data class ApiPersonalDiscountTypeResponse(
val id: String,
val title: String,
val description: String,
@SerialName(value = "price") val price: ApiMoney,
@SerialName(value = "time_validity_mode")
@Serializable(with = TimeValidityModeSerializer::class)
val timeValidityMode: TimeValidityMode?,
@SerialName(value = "default_duration")
val defaultDuration: Int?,
@SerialName(value = "fixed_start_date")
val fixedStartDate: LocalDate?,
@SerialName(value = "fixed_end_date")
val fixedEndDate: LocalDate?,
) {
@Serializable
public enum class TimeValidityMode {
@SerialName(value = "relative_to_creation")
RELATIVE_TO_CREATION,
@SerialName(value = "fixed_start_and_end")
FIXED_START_AND_END,
UNSUPPORTED,
}
}
private object TimeValidityModeSerializer :
KSerializer<ApiPersonalDiscountTypeResponse.TimeValidityMode?> {
override val descriptor = String.serializer().descriptor
@OptIn(ExperimentalSerializationApi::class)
override fun serialize(encoder: Encoder, value: ApiPersonalDiscountTypeResponse.TimeValidityMode?) {
if (value == null) {
encoder.encodeNull()
return
}
encoder.encodeString(
when (value) {
ApiPersonalDiscountTypeResponse.TimeValidityMode.RELATIVE_TO_CREATION ->
"relative_to_creation"
ApiPersonalDiscountTypeResponse.TimeValidityMode.FIXED_START_AND_END ->
"fixed_start_and_end"
ApiPersonalDiscountTypeResponse.TimeValidityMode.UNSUPPORTED ->
"unsupported"
},
)
}
@OptIn(ExperimentalSerializationApi::class)
override fun deserialize(decoder: Decoder): ApiPersonalDiscountTypeResponse.TimeValidityMode? {
val stringValue =
decoder.decodeNullableSerializableValue(String.serializer().nullable) ?: return null
return when (stringValue) {
"relative_to_creation" ->
ApiPersonalDiscountTypeResponse.TimeValidityMode.RELATIVE_TO_CREATION
"fixed_start_and_end" ->
ApiPersonalDiscountTypeResponse.TimeValidityMode.FIXED_START_AND_END
else -> ApiPersonalDiscountTypeResponse.TimeValidityMode.UNSUPPORTED
}
}
}
| 4
|
Kotlin
|
0
| 1
|
0a4bf35a2bdb523b9f705712cb35577f1664b76b
| 2,813
|
kmp-passenger-api
|
MIT License
|
app/src/main/kotlin/com/simplemobiletools/calendar/pro/dialogs/ExportEventsDialog.kt
|
GiridharanS1729
| 724,120,449
| false
|
{"Kotlin": 796515, "Ruby": 909}
|
package com.simplemobiletools.calendar.pro.dialogs
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.calendar.pro.R
import com.simplemobiletools.calendar.pro.activities.SimpleActivity
import com.simplemobiletools.calendar.pro.adapters.FilterEventTypeAdapter
import com.simplemobiletools.calendar.pro.databinding.DialogExportEventsBinding
import com.simplemobiletools.calendar.pro.extensions.config
import com.simplemobiletools.calendar.pro.extensions.eventsHelper
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import java.io.File
class ExportEventsDialog(
val activity: SimpleActivity, val path: String, val hidePath: Boolean,
val callback: (file: File, eventTypes: ArrayList<Long>) -> Unit
) {
private var realPath = path.ifEmpty { activity.internalStoragePath }
private val config = activity.config
private val binding by activity.viewBinding(DialogExportEventsBinding::inflate)
init {
binding.apply {
exportEventsFolder.setText(activity.humanizePath(realPath))
exportEventsFilename.setText("${activity.getString(R.string.events)}_${activity.getCurrentFormattedDateTime()}")
exportEventsCheckbox.isChecked = config.exportEvents
exportEventsCheckboxHolder.setOnClickListener {
exportEventsCheckbox.toggle()
}
exportTasksCheckbox.isChecked = config.exportTasks
exportTasksCheckboxHolder.setOnClickListener {
exportTasksCheckbox.toggle()
}
exportPastEventsCheckbox.isChecked = config.exportPastEntries
exportPastEventsCheckboxHolder.setOnClickListener {
exportPastEventsCheckbox.toggle()
}
if (hidePath) {
exportEventsFolderHint.beGone()
exportEventsFolder.beGone()
} else {
exportEventsFolder.setOnClickListener {
activity.hideKeyboard(exportEventsFilename)
FilePickerDialog(activity, realPath, false, showFAB = true) {
exportEventsFolder.setText(activity.humanizePath(it))
realPath = it
}
}
}
activity.eventsHelper.getEventTypes(activity, false) {
val eventTypes = HashSet<String>()
it.mapTo(eventTypes) { it.id.toString() }
exportEventsTypesList.adapter = FilterEventTypeAdapter(activity, it, eventTypes)
if (it.size > 1) {
exportEventsPickTypes.beVisible()
}
}
}
activity.getAlertDialogBuilder()
.setPositiveButton(com.simplemobiletools.commons.R.string.ok, null)
.setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null)
.apply {
activity.setupDialogStuff(binding.root, this, R.string.export_events) { alertDialog ->
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
val filename = binding.exportEventsFilename.value
when {
filename.isEmpty() -> activity.toast(com.simplemobiletools.commons.R.string.empty_name)
filename.isAValidFilename() -> {
val file = File(realPath, "$filename.ics")
if (!hidePath && file.exists()) {
activity.toast(com.simplemobiletools.commons.R.string.name_taken)
return@setOnClickListener
}
val exportEventsChecked = binding.exportEventsCheckbox.isChecked
val exportTasksChecked = binding.exportTasksCheckbox.isChecked
if (!exportEventsChecked && !exportTasksChecked) {
activity.toast(com.simplemobiletools.commons.R.string.no_entries_for_exporting)
return@setOnClickListener
}
ensureBackgroundThread {
config.apply {
lastExportPath = file.absolutePath.getParentPath()
exportEvents = exportEventsChecked
exportTasks = exportTasksChecked
exportPastEntries = binding.exportPastEventsCheckbox.isChecked
}
val eventTypes = (binding.exportEventsTypesList.adapter as FilterEventTypeAdapter).getSelectedItemsList()
callback(file, eventTypes)
alertDialog.dismiss()
}
}
else -> activity.toast(com.simplemobiletools.commons.R.string.invalid_name)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
2e539105f60e2bb7eda892f458619789918f0361
| 5,321
|
Event_Calendar
|
MIT License
|
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/broken/Discover.kt
|
Tlaster
| 560,394,734
| false
|
{"Kotlin": 25133302}
|
package moe.tlaster.icons.vuesax.vuesaxicons.broken
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
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 moe.tlaster.icons.vuesax.vuesaxicons.BrokenGroup
public val BrokenGroup.Discover: ImageVector
get() {
if (_discover != null) {
return _discover!!
}
_discover = Builder(name = "Discover", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(14.71f, 14.03f)
curveTo(15.51f, 13.07f, 16.0f, 11.84f, 16.0f, 10.5f)
curveTo(16.0f, 9.13f, 14.87f, 8.0f, 13.5f, 8.0f)
curveTo(10.47f, 8.0f, 8.0f, 10.48f, 8.0f, 13.5f)
curveTo(8.0f, 14.87f, 9.12f, 16.0f, 10.5f, 16.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 6.0f)
curveTo(2.75f, 7.67f, 2.0f, 9.75f, 2.0f, 12.0f)
curveTo(2.0f, 17.52f, 6.48f, 22.0f, 12.0f, 22.0f)
curveTo(17.52f, 22.0f, 22.0f, 17.52f, 22.0f, 12.0f)
curveTo(22.0f, 6.48f, 17.52f, 2.0f, 12.0f, 2.0f)
curveTo(10.57f, 2.0f, 9.2f, 2.3f, 7.97f, 2.85f)
}
}
.build()
return _discover!!
}
private var _discover: ImageVector? = null
| 0
|
Kotlin
|
0
| 2
|
b8a8231e6637c2008f675ae76a3423b82ee53950
| 2,321
|
VuesaxIcons
|
MIT License
|
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Grid1.kt
|
Tlaster
| 560,394,734
| false
|
{"Kotlin": 25133302}
|
package moe.tlaster.icons.vuesax.vuesaxicons.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup
public val OutlineGroup.Grid1: ImageVector
get() {
if (_grid1 != null) {
return _grid1!!
}
_grid1 = Builder(name = "Grid1", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.0f, 22.75f)
horizontalLineTo(9.0f)
curveTo(3.57f, 22.75f, 1.25f, 20.43f, 1.25f, 15.0f)
verticalLineTo(9.0f)
curveTo(1.25f, 3.57f, 3.57f, 1.25f, 9.0f, 1.25f)
horizontalLineTo(15.0f)
curveTo(20.43f, 1.25f, 22.75f, 3.57f, 22.75f, 9.0f)
verticalLineTo(15.0f)
curveTo(22.75f, 20.43f, 20.43f, 22.75f, 15.0f, 22.75f)
close()
moveTo(9.0f, 2.75f)
curveTo(4.39f, 2.75f, 2.75f, 4.39f, 2.75f, 9.0f)
verticalLineTo(15.0f)
curveTo(2.75f, 19.61f, 4.39f, 21.25f, 9.0f, 21.25f)
horizontalLineTo(15.0f)
curveTo(19.61f, 21.25f, 21.25f, 19.61f, 21.25f, 15.0f)
verticalLineTo(9.0f)
curveTo(21.25f, 4.39f, 19.61f, 2.75f, 15.0f, 2.75f)
horizontalLineTo(9.0f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.9993f, 9.25f)
horizontalLineTo(2.0293f)
curveTo(1.6193f, 9.25f, 1.2793f, 8.91f, 1.2793f, 8.5f)
curveTo(1.2793f, 8.09f, 1.6193f, 7.75f, 2.0293f, 7.75f)
horizontalLineTo(21.9993f)
curveTo(22.4093f, 7.75f, 22.7493f, 8.09f, 22.7493f, 8.5f)
curveTo(22.7493f, 8.91f, 22.4093f, 9.25f, 21.9993f, 9.25f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.9993f, 16.25f)
horizontalLineTo(2.0293f)
curveTo(1.6193f, 16.25f, 1.2793f, 15.91f, 1.2793f, 15.5f)
curveTo(1.2793f, 15.09f, 1.6193f, 14.75f, 2.0293f, 14.75f)
horizontalLineTo(21.9993f)
curveTo(22.4093f, 14.75f, 22.7493f, 15.09f, 22.7493f, 15.5f)
curveTo(22.7493f, 15.91f, 22.4093f, 16.25f, 21.9993f, 16.25f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(8.5098f, 22.7398f)
curveTo(8.0998f, 22.7398f, 7.7598f, 22.3998f, 7.7598f, 21.9898f)
verticalLineTo(2.0098f)
curveTo(7.7598f, 1.5998f, 8.0998f, 1.2598f, 8.5098f, 1.2598f)
curveTo(8.9198f, 1.2598f, 9.2598f, 1.5998f, 9.2598f, 2.0098f)
verticalLineTo(21.9798f)
curveTo(9.2598f, 22.3998f, 8.9298f, 22.7398f, 8.5098f, 22.7398f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.5098f, 22.7398f)
curveTo(15.0998f, 22.7398f, 14.7598f, 22.3998f, 14.7598f, 21.9898f)
verticalLineTo(2.0098f)
curveTo(14.7598f, 1.5998f, 15.0998f, 1.2598f, 15.5098f, 1.2598f)
curveTo(15.9198f, 1.2598f, 16.2598f, 1.5998f, 16.2598f, 2.0098f)
verticalLineTo(21.9798f)
curveTo(16.2598f, 22.3998f, 15.9298f, 22.7398f, 15.5098f, 22.7398f)
close()
}
}
.build()
return _grid1!!
}
private var _grid1: ImageVector? = null
| 0
|
Kotlin
|
0
| 2
|
b8a8231e6637c2008f675ae76a3423b82ee53950
| 5,149
|
VuesaxIcons
|
MIT License
|
app/src/main/java/com/github/kuya32/chitchat/core/presentation/MainActivity.kt
|
kuya32
| 422,393,629
| false
|
{"Kotlin": 174412}
|
package com.github.kuya32.chitchat.core.presentation
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.github.kuya32.chitchat.core.presentation.components.StandardScaffold
import com.github.kuya32.chitchat.core.presentation.ui.theme.ChitChatTheme
import com.github.kuya32.chitchat.core.presentation.components.Navigation
import com.github.kuya32.chitchat.core.utils.Screen
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@ExperimentalMaterialApi
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ChitChatTheme {
Surface(
color = MaterialTheme.colors.background,
modifier = Modifier.fillMaxSize()
) {
val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState()
val scaffoldState = rememberScaffoldState()
StandardScaffold(
navController = navController,
showBottomBar = navBackStackEntry?.destination?.route in listOf(
Screen.MainFeedScreen.route,
Screen.MessageScreen.route,
Screen.ActivityScreen.route,
Screen.ProfileScreen.route,
),
state = scaffoldState,
modifier = Modifier.fillMaxSize(),
onFabClick = {
navController.navigate(Screen.CreatePostScreen.route)
}
) {
Navigation(navController, scaffoldState)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
dc05a0f479d286cd3eb066f31a30d92f8fc35434
| 2,411
|
Chit-Chat
|
MIT License
|
shared/src/commonMain/kotlin/feature_detail/data/remote/dto/watchProvider/WatchProvidersDto.kt
|
tolgaprm
| 712,824,422
| false
|
{"Kotlin": 281188, "Swift": 657, "Shell": 228}
|
package feature_detail.data.remote.dto.watchProvider
import kotlinx.serialization.Serializable
@Serializable
data class WatchProvidersDto(
val results: WatchProviderRegionDto?
)
| 2
|
Kotlin
|
0
| 0
|
1bf08352171b694b04a5cc702cf5dfaa7bd4073f
| 183
|
MovaApp-compose-multiplatform
|
Apache License 2.0
|
src/main/kotlin/net/mt32/expoll/entities/User.kt
|
Universumgames
| 508,613,455
| false
|
{"Kotlin": 257520, "TSQL": 5917, "Dockerfile": 2077, "Shell": 1946}
|
package net.mt32.expoll.entities
import com.yubico.webauthn.data.ByteArray
import io.ktor.util.*
import net.mt32.expoll.config
import net.mt32.expoll.database.DatabaseEntity
import net.mt32.expoll.database.UUIDLength
import net.mt32.expoll.entities.notifications.APNDevice
import net.mt32.expoll.entities.notifications.WebNotificationDevice
import net.mt32.expoll.helper.UnixTimestamp
import net.mt32.expoll.helper.toUnixTimestampFromDB
import net.mt32.expoll.helper.upsertCustom
import net.mt32.expoll.serializable.admin.responses.UserInfo
import net.mt32.expoll.serializable.responses.SimpleUser
import net.mt32.expoll.tPollID
import net.mt32.expoll.tUserID
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.*
interface ISimpleUser {
val firstName: String
val lastName: String
val username: String
val id: String
}
interface IUser : ISimpleUser {
override val id: tUserID
override var username: String
override var firstName: String
override var lastName: String
var mail: String
val polls: List<Poll>
val votes: List<Vote>
val sessions: List<Session>
val notes: List<PollUserNote>
var active: Boolean
var admin: Boolean
val challenges: List<Challenge>
val authenticators: List<Authenticator>
}
class User : IUser, DatabaseEntity {
override var id: String
private set
override var username: String
override var firstName: String
override var lastName: String
val fullName: String
get() = "$firstName $lastName"
override var mail: String
override val polls: List<Poll>
get() {
return cachedPolls ?: Poll.accessibleForUser(id)
}
override val votes: List<Vote>
get() = Vote.fromUser(this)
val otps: List<OTP>
get() = OTP.fromUser(id)
override val sessions: List<Session>
get() {
return Session.forUser(id)
}
override val notes: List<PollUserNote>
get() {
return PollUserNote.forUser(id)
}
override var active: Boolean
override var admin: Boolean
val superAdmin: Boolean
get() = mail.equals(config.superAdminMail, ignoreCase = true)
override val challenges: List<Challenge>
get() {
return Challenge.forUser(id)
}
override val authenticators: List<Authenticator>
get() {
return Authenticator.fromUser(id)
}
private var cachedPolls: List<Poll>? = null
val notificationPreferences: NotificationPreferences
get() = NotificationPreferences.fromUser(id)
val apnDevices: List<APNDevice>
get() = APNDevice.fromUser(id)
val webNotificationDevices: List<WebNotificationDevice>
get() = WebNotificationDevice.fromUser(id)
val created: UnixTimestamp
val deleted: UnixTimestamp?
val oidConnections: List<OIDCUserData>
get() = OIDCUserData.byUser(id)
constructor(
username: String,
firstName: String,
lastName: String,
mail: String,
active: Boolean = true,
admin: Boolean
) {
this.id = UUID.randomUUID().toString()
this.username = username
this.firstName = firstName
this.lastName = lastName
this.mail = mail
this.active = active
this.admin = admin
this.created = UnixTimestamp.now()
this.deleted = null
}
constructor(userRow: ResultRow) {
this.id = userRow[User.id]
this.username = userRow[User.username]
this.mail = userRow[User.mail]
this.firstName = userRow[User.firstName]
this.lastName = userRow[User.lastName]
this.active = userRow[User.active]
this.admin = userRow[User.admin] || config.superAdminMail.equals(mail, ignoreCase = true)
this.created = userRow[User.created].toUnixTimestampFromDB()
this.deleted = userRow[User.deleted]?.toUnixTimestampFromDB()
}
override fun save(): Boolean {
transaction {
User.upsertCustom(User.id) {
it[id] = <EMAIL>
it[username] = <EMAIL>
it[mail] = <EMAIL>
it[firstName] = <EMAIL>
it[lastName] = <EMAIL>
it[active] = <EMAIL>
it[admin] = <EMAIL>
it[created] = <EMAIL>.toDB()
it[deleted] = this@User.deleted?.toDB()
}
}
return true
}
override fun saveConsecutive(): Boolean {
save()
transaction {
sessions.forEach { it.save() }
challenges.forEach { it.save() }
authenticators.forEach { it.save() }
votes.forEach { it.save() }
}
return true
}
override fun delete(): Boolean {
otps.forEach { it.delete() }
sessions.forEach { it.delete() }
challenges.forEach { it.delete() }
authenticators.forEach { it.delete() }
apnDevices.forEach { it.delete() }
OIDCUserData.byUser(id).forEach { it.delete() }
UserDeletionConfirmation.getPendingConfirmationForUser(id)?.delete()
webNotificationDevices.forEach { it.delete() }
//votes.forEach { it.delete() }
//polls.forEach { if(it.adminID != id) UserPolls.removeConnection(id, it.id) }
val oldActive = active
transaction {
User.upsertCustom(User.id) {
it[id] = <EMAIL>
it[username] = "Deleted User " + <EMAIL>
it[firstName] = "Deleted"
it[lastName] = "User"
it[mail] = "unknown" + <EMAIL>
it[created] = this@User.created.toDB()
it[active] = false
it[admin] = false
it[deleted] = UnixTimestamp.now().toDB()
}
}
if (!oldActive) {
votes.forEach { it.delete() }
notes.forEach { it.delete() }
polls.forEach {
if (it.adminID == id) it.delete()
UserPolls.removeConnection(id, it.id)
}
notificationPreferences.delete()
transaction {
User.deleteWhere { User.id eq this@User.id }
}
}
return true
}
/**
* Creates and saves new OTP for current user
*/
fun createOTP(forApp: Boolean): OTP {
return OTP.create(id, forApp)
}
fun createSessionFromScratch(): Session {
val session = Session(id, "unknown")
session.save()
return session
}
companion object : Table("user") {
const val maxUserNameLength = 255
const val maxNameComponentLength = 255
const val maxMailLength = 255
val id = varchar("id", UUIDLength).default(UUID.randomUUID().toString())
val username = varchar("username", maxUserNameLength).uniqueIndex()
val firstName = varchar("firstName", maxNameComponentLength)
val lastName = varchar("lastName", maxNameComponentLength)
val mail = varchar("mail", maxMailLength).uniqueIndex()
val active = bool("active")
val admin = bool("admin")
val created = long("createdTimestamp")
val deleted = long("deletedTimestamp").nullable()
override val primaryKey = PrimaryKey(id)
fun loadFromID(id: String): User? {
return transaction {
val userRow = User.select { User.id eq id }.limit(1).firstOrNull()
return@transaction userRow?.let { User(it) }
}
}
fun byMail(mail: String): User? {
return transaction {
val userRow = User.select { User.mail eq mail }.firstOrNull()
return@transaction userRow?.let { User(it) }
}
}
fun byUsername(username: String): User? {
return transaction {
val userRow = User.select { User.username eq username }.firstOrNull()
return@transaction userRow?.let { User(it) }
}
}
fun all(): List<User> {
return transaction {
return@transaction User.selectAll().toList().map { User(it) }
}
}
fun fromUserHandle(handle: ByteArray?): User? {
if (handle == null) return null
val b64 = handle.base64
val decoded = b64.decodeBase64String()
return loadFromID(decoded)
}
fun ensureTestUserExistence() {
val existing = User.byUsername(config.testUser.username)
if (existing != null) return
val user = User(
config.testUser.username,
config.testUser.firstName,
config.testUser.lastName,
config.testUser.email,
admin = false
)
user.save()
}
fun admins(): List<User> {
return transaction {
return@transaction User.select { (User.admin eq true) or (User.mail eq config.superAdminMail) }
.map { User(it) }
}
}
/*val id = "4411a4b1-f62a-11ec-bd56-0242ac190002"
val b64 = id.encodeBase64()
println(b64)
val bb64 = ByteArray.fromBase64(b64)
val decoded2 = bb64.base64
println(decoded2.decodeBase64String())
println(b64.decodeBase64String())*/
}
val userHandle: ByteArray
get() = ByteArray.fromBase64(id.encodeBase64())
fun asSimpleUser(): SimpleUser {
return SimpleUser(
firstName,
lastName,
username,
id
)
}
fun asUserInfo(): UserInfo {
return UserInfo(
id,
username,
firstName,
lastName,
mail,
admin,
superAdmin,
active,
oidConnections.map { it.toConnectionOverview().name },
created.toClient()
)
}
override fun equals(other: Any?): Boolean {
if (other is User) return this.id == other.id
if (other is SimpleUser) return this.id == other.id
return super.equals(other)
}
fun addPoll(pollID: tPollID) {
UserPolls.addConnection(id, pollID)
}
fun removePoll(pollID: tPollID) {
UserPolls.removeConnection(id, pollID)
}
}
class UserDeletionConfirmation : DatabaseEntity {
val userID: tUserID
val initTimestamp: UnixTimestamp
val key: String
constructor(userID: tUserID) {
this.userID = userID
this.initTimestamp = UnixTimestamp.now()
this.key = createKey()
}
constructor(resultRow: ResultRow) {
this.userID = resultRow[UserDeletionConfirmation.userID]
this.initTimestamp = resultRow[UserDeletionConfirmation.initTimestamp].toUnixTimestampFromDB()
this.key = resultRow[UserDeletionConfirmation.key]
}
companion object : Table("userDeletionConfirmation") {
val userID = varchar("userID", UUIDLength)
val initTimestamp = long("initTimestamp")
val key = varchar("key", 255)
override val primaryKey = PrimaryKey(userID)
private fun createKey(): String {
return UUID.randomUUID().toString()
}
fun getPendingConfirmationForKey(key: String): UserDeletionConfirmation? {
return transaction {
val resultRow = UserDeletionConfirmation.select { UserDeletionConfirmation.key eq key }.firstOrNull()
return@transaction resultRow?.let { UserDeletionConfirmation(it) }
}
}
fun getPendingConfirmationForUser(userID: tUserID): UserDeletionConfirmation? {
return transaction {
val resultRow =
UserDeletionConfirmation.select { UserDeletionConfirmation.userID eq userID }.firstOrNull()
return@transaction resultRow?.let { UserDeletionConfirmation(it) }
}
}
}
override fun save(): Boolean {
transaction {
UserDeletionConfirmation.upsertCustom(UserDeletionConfirmation.userID) {
it[userID] = this@UserDeletionConfirmation.userID
it[initTimestamp] = this@UserDeletionConfirmation.initTimestamp.toDB()
it[key] = this@UserDeletionConfirmation.key
}
}
return true
}
override fun delete(): Boolean {
transaction {
UserDeletionConfirmation.deleteWhere { UserDeletionConfirmation.userID eq userID }
}
return true
}
}
| 0
|
Kotlin
|
1
| 0
|
9411f9bc6b226dacbb4f9bed01827a52622ac94d
| 12,723
|
expoll_server
|
MIT License
|
app/src/main/java/com/comicreader/comicray/ui/fragments/read/controller/ReadController.kt
|
Comic-Ray
| 399,188,798
| false
| null |
package com.comicreader.comicray.ui.fragments.read.controller
import com.airbnb.epoxy.EpoxyController
import com.comicreader.comicray.data.models.BookType
import com.comicreader.comicray.epoxyModels.readImage
import java.util.concurrent.CopyOnWriteArrayList
class ReadController : EpoxyController() {
private val imageList: CopyOnWriteArrayList<String> = CopyOnWriteArrayList()
var bookType: BookType = BookType.Comic
fun submitImageList(imageList: List<String>) {
this.imageList.clear()
this.imageList.addAll(imageList)
requestModelBuild()
}
override fun buildModels() {
for(image in imageList) {
readImage {
id(image.hashCode())
imageUrl(image)
bookType(this@ReadController.bookType)
}
}
}
}
| 0
|
Kotlin
|
1
| 0
|
86ccfe98a883a8e16f0f2d87f00c1bb05b2c9bf1
| 835
|
comicray-android
|
Apache License 2.0
|
app/src/main/java/com/hardiktrivedi/letthemusicplay/detail/TrackListAdapter.kt
|
hardik-trivedi
| 381,812,894
| false
| null |
package com.hardiktrivedi.letthemusicplay.detail
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.hardiktrivedi.letthemusicplay.data.model.Track
import com.hardiktrivedi.letthemusicplay.databinding.TrackListItemBinding
import com.hardiktrivedi.letthemusicplay.util.toSongDuration
class TrackListAdapter :
ListAdapter<Track, TrackListAdapter.TrackListViewHolder>(TrackListDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TrackListViewHolder {
val binding = TrackListItemBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
return TrackListViewHolder(binding)
}
override fun onBindViewHolder(holder: TrackListViewHolder, position: Int) {
holder.bind(getItem(position))
}
inner class TrackListViewHolder(private val binding: TrackListItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: Track) {
with(binding) {
titleTextView.text = item.name
artistTextView.text = item.artist.name
durationTextView.text = item.duration.toSongDuration()
}
}
}
}
/**
* Diff logic helps RecyclerView to identify the new entiry in adapter
*/
private class TrackListDiffCallback : DiffUtil.ItemCallback<Track>() {
override fun areItemsTheSame(oldItem: Track, newItem: Track): Boolean {
return oldItem.name == newItem.name && oldItem.artist.name == newItem.artist.name
}
override fun areContentsTheSame(oldItem: Track, newItem: Track): Boolean {
return oldItem == newItem
}
}
| 0
|
Kotlin
|
0
| 0
|
7d8d9776fe14477017aa0a749a7e617de5794948
| 1,789
|
LetTheMusicPlay
|
Apache License 2.0
|
src/main/kotlin/br/com/zup/edu/pix/exceptions/ChavePixExistenteException.kt
|
victorsimiao
| 397,702,881
| true
|
{"Kotlin": 80556}
|
package br.com.zup.edu.pix.exceptions
import java.lang.RuntimeException
class ChavePixExistenteException(message:String?): RuntimeException(message) {
}
| 0
|
Kotlin
|
0
| 0
|
e9048ebf0ca5c3a360a7efe199452c9a6ee29c95
| 154
|
orange-talents-06-template-pix-keymanager-grpc
|
Apache License 2.0
|
src/main/kotlin/exercises/linkedlist/LinkedList.kt
|
edgardobarriam
| 829,169,780
| false
|
{"Kotlin": 25858}
|
package exercises.linkedlist
class LinkedList<T> {
var head : Node<T>? = null
fun insertFirst(value : T) {
this.head = Node(value, this.head)
}
fun size(): Int {
var node = this.head
var size = 0
while (node != null) {
size++
node = node.next
}
return size
}
fun getFirst() : Node<T>? {
return this.head
}
fun getLast() : Node<T>? {
var node = this.head
while (node?.next != null) {
node = node.next
}
return node
}
fun clear() {
this.head = null
}
fun removeFirst() {
if (this.head != null) {
this.head = this.head?.next
}
}
fun removeLast() {
var node = this.head
if (node != null) {
while (node?.next?.next != null) {
node = node.next
}
if (node?.next != null) {
node.next = null
} else {
this.head = null
}
}
}
fun insertLast(value : T) {
if (this.getLast() != null) {
this.getLast()?.next = Node(value, null)
} else {
this.head = Node(value, null)
}
}
fun getAt(value : Int) : Node<T>? {
var node = this.head
var index = 0
while (node != null && index != value) {
node = node.next
index++
}
return node
}
fun removeAt(index : Int) {
if (index < 0) {return}
if (this.head != null && index == 0) {
this.head = this.head?.next
return
}
val node = this.getAt(index - 1)
if (node != null) {
node.next = this.getAt(index + 1)
}
}
fun insertAt(index : Int, value : T) {
if (index < 0) {return}
if (index == 0) {
this.head = Node(value, this.head)
return
}
val node = this.getAt(index - 1)
if (node != null) {
node.next = Node(value, this.getAt(index))
} else {
this.getLast()?.next = Node(value, null)
}
}
fun forEach(action : (Node<T>, Int) -> Unit) {
var node = this.head
var index = 0
while (node != null) {
action(node, index)
node = node.next
index++
}
}
}
| 0
|
Kotlin
|
0
| 0
|
facf3174a8a0665f9d182e5ded60d8ae19548ce4
| 2,054
|
algo-kasts
|
Apache License 2.0
|
app/src/main/java/com/nafanya/mp3world/features/albums/AlbumListManager.kt
|
AlexSoWhite
| 445,900,000
| false
| null |
package com.nafanya.mp3world.features.albums
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.map
import com.nafanya.mp3world.core.coroutines.IOCoroutineProvider
import com.nafanya.mp3world.core.listManagers.ListManager
import com.nafanya.mp3world.core.mediaStore.MediaStoreInteractor
import com.nafanya.mp3world.core.wrappers.PlaylistWrapper
import com.nafanya.mp3world.core.wrappers.local.LocalSong
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
/**
* Object that holds albums data. Populated by [MediaStoreInteractor]. Updates when [MediaStoreInteractor] is updated.
*/
@Singleton
class AlbumListManager @Inject constructor(
mediaStoreInteractor: MediaStoreInteractor,
ioCoroutineProvider: IOCoroutineProvider
) : ListManager() {
private val mAlbums = MutableLiveData<List<Album>>()
val albums: LiveData<List<Album>>
get() = mAlbums
private var suspendedList = mutableListOf<Album>()
init {
ioCoroutineProvider.ioScope.launch {
mediaStoreInteractor.allSongs.collectLatest {
it?.let { list ->
fillSuspendedList(list)
updateData()
}
}
}
}
override fun getPlaylistByContainerId(id: Long): LiveData<PlaylistWrapper?> {
return albums.map {
it.firstOrNull { album ->
album.id == id
}?.playlist
}
}
private fun fillSuspendedList(songList: List<LocalSong>) {
songList.forEach { song ->
val album = Album(
id = song.albumId,
name = song.album,
image = song.art
)
add(album, song)
}
}
private fun add(element: Album, song: LocalSong) {
val index = suspendedList.indexOf(element)
if (index != -1) {
val playlist = suspendedList[index].playlist
suspendedList.elementAt(index).playlist = playlist?.copy(
songList = listOf(song) + playlist.songList
)
} else {
element.playlist = PlaylistWrapper(
listOf(song),
name = element.name
)
suspendedList.add(element)
}
}
private fun updateData() {
mAlbums.postValue(suspendedList)
suspendedList = mutableListOf()
}
}
| 0
|
Kotlin
|
0
| 0
|
480fa9c16460890d393ece7c8aa2466c031d8f78
| 2,505
|
mp3world
|
MIT License
|
library/src/commonMain/kotlin/net/freshplatform/ktor_server/firebase_app_check/service/FirebaseAppCheckTokenVerifierService.kt
|
freshplatform
| 704,895,371
| false
|
{"Kotlin": 60653, "Shell": 64}
|
package net.freshplatform.ktor_server.firebase_app_check.service
import net.freshplatform.ktor_server.firebase_app_check.service.jwt.DecodedJwt
import kotlin.time.Duration
import kotlin.time.Duration.Companion.hours
/**
* Configuration data class for fetching Firebase App Check public keys. This class
* encapsulates various configurations, including cache and rate limiting settings.
*
* @param cacheConfiguration Configuration for the cache of public keys.
* @param rateLimitedConfig Configuration for rate limiting of key fetch requests.
*/
data class FetchFirebaseAppCheckPublicKeyConfig(
val cacheConfiguration: FetchFirebaseAppCheckPublicKeyCacheConfig = FetchFirebaseAppCheckPublicKeyCacheConfig(),
val rateLimitedConfig: FetchFirebaseAppCheckPublicKeyRateLimitedConfig = FetchFirebaseAppCheckPublicKeyRateLimitedConfig(),
)
/**
* Configuration data class for the cache of public keys. This class defines the size
* of the cache and the duration for keys to expire within the cache.
*
* @param cacheSize The size of the cache for public keys.
* @param expiresIn The duration for public keys to expire in the cache.
*/
data class FetchFirebaseAppCheckPublicKeyCacheConfig(
val cacheSize: Long = 10,
val expiresIn: Duration = 24.hours,
)
/**
* Configuration data class for rate limiting of key fetch requests.
*
* @param enabled
*/
data class FetchFirebaseAppCheckPublicKeyRateLimitedConfig(
val enabled: Boolean = true
)
/**
* Object containing functions for fetching and verifying Firebase App Check tokens.
*/
interface FirebaseAppCheckTokenVerifierService {
/**
* Suspended function to verify a Firebase App Check token.
*
* @param firebaseAppCheckTokenJwt The JWT string to be verified.
* @param firebaseProjectId The Firebase project ID.
* @param firebaseProjectNumber The Firebase project number.
* @param issuerBaseUrl The base URL of the Firebase App Check issuer.
* @return The verified Decoded JWT.
*/
suspend fun verifyFirebaseAppCheckToken(
firebaseAppCheckTokenJwt: String,
firebaseProjectId: String,
firebaseProjectNumber: String,
issuerBaseUrl: String,
publicKeyUrl: String
): DecodedJwt
}
expect class FirebaseAppCheckTokenVerifierServiceImpl(): FirebaseAppCheckTokenVerifierService
| 0
|
Kotlin
|
0
| 12
|
d58821422b60d29d8ea30e5140edcae0affae3ef
| 2,343
|
ktor-server-firebase-app-check
|
MIT License
|
shared/src/commonMain/kotlin/model/AppRecord.kt
|
sdercolin
| 708,470,210
| false
|
{"Kotlin": 307043, "Swift": 2742, "Shell": 1668}
|
package model
import androidx.compose.runtime.Immutable
import kotlinx.serialization.Serializable
@Immutable
@Serializable
data class AppRecord(
val windowSizeDp: Pair<Float, Float> = Pair(800f, 500f),
)
| 0
|
Kotlin
|
0
| 7
|
46d6a8e699c4c89d715b3ad80ea185ce12272530
| 210
|
recstar
|
Apache License 2.0
|
Fucntions/functions_6.kt
|
abhijitramesh
| 172,509,609
| false
| null |
fun main(args: Array<String>){
pritInts(1,2,3,4,5)
}
fun pritInts(vararg ints: Int){
for(n in ints)
print("$n \t")
}
| 5
|
Kotlin
|
1
| 9
|
ab668eb4c96700a559081f653c11d03a83a290bd
| 120
|
Kotlin
|
Apache License 2.0
|
app/src/main/java/com/jumpy/activity/MainActivity.kt
|
Hert97
| 601,104,498
| false
| null |
package com.jumpy.activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.view.animation.TranslateAnimation
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.example.SoundSystem
import com.jumpy.Animator
import com.jumpy.Spritesheet
import com.example.jumpy.R
class MainActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var anime : Animator
private lateinit var catImageView : ImageView
private var gameStart = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_menu)
SoundSystem.playBgMusic(this, R.raw.mainmenu )
val buttonPlay : ImageView = findViewById(R.id.imagePlay)
val buttonExit : LinearLayout = findViewById(R.id.button_exit)
val buttonLeaderboard : LinearLayout = findViewById(R.id.button_leaderboard)
buttonPlay.setOnClickListener(this)
buttonExit.setOnClickListener(this)
buttonLeaderboard.setOnClickListener(this)
catImageView = findViewById(R.id.mm_image_1)
// val context = this
// val resources = context.resources
// val drawableId = R.drawable.animation
//
// val animDrawable = ResourcesCompat.getDrawable(resources, drawableId, null) as AnimationDrawable
// catImageView.setImageDrawable(animDrawable)
// animDrawable.start()
val frameDuration = 0.5f //seconds
val spriteSheet = BitmapFactory.decodeResource(resources, R.drawable.idle)
val frames = Spritesheet.slice(spriteSheet, 1, 3)
anime = Animator(resources, frames, frameDuration)
//val anime = Animator(catImageView, resources, frames, null)
anime.setImageView(catImageView)
anime.start()
}
override fun onClick(view: View) {
when (view.id) {
R.id.imagePlay -> {
if(gameStart) return
else gameStart = true
catImageView.setImageResource(R.drawable.jump)
val timer = object: CountDownTimer(1000, 1000) {
override fun onTick(millisUntilFinished: Long)
{
val btm = findViewById<ConstraintLayout>(R.id.container).height.toFloat() - catImageView.height.toFloat()
// Animate the image view during the countdown
val animation = TranslateAnimation(0f, 0f, 0f, btm)
animation.duration = 1000
catImageView.startAnimation(animation)
}
override fun onFinish() {
val intent = Intent(this@MainActivity, GameActivity::class.java)
startActivity(intent)
}
}
timer.start()
}
R.id.button_leaderboard -> {
val intent = Intent(this, LeaderboardActivity::class.java)
startActivity(intent)
}
R.id.button_exit -> {
finish()
}
}
}
override fun onPause() {
super.onPause()
SoundSystem.pauseAll()
}
override fun onResume() {
super.onResume()
SoundSystem.resumeAll()
}
}
| 0
|
Kotlin
|
0
| 0
|
66c3711a10f2d07f5dd8cc19f901e4997c052ac2
| 3,593
|
Jumpy
|
MIT License
|
mpp-library/domain/src/commonMain/kotlin/com/kotlinconf/library/domain/entity/GameConfig.kt
|
JetBrains
| 204,497,967
| false
| null |
package com.kotlinconf.library.domain.entity
import dev.icerock.moko.network.generated.models.ConfigResponse
data class GameConfig(
val index: Int,
val active: Int?,
val winnerCount: Int,
val hints: Map<Int, String>,
val facts: List<String>
)
internal fun ConfigResponse.toDomain(): GameConfig = GameConfig(
index = index,
active = activeBeacons,
winnerCount = winnerCount,
hints = hints?.associate { it.code to it.hint }.orEmpty(),
facts = facts.orEmpty()
)
| 1
|
Kotlin
|
7
| 33
|
915eb539cf04248b1314a14a596b8affb68352c1
| 502
|
KotlinFinder
|
Apache License 2.0
|
JetNews/app/src/main/java/com/example/jetnews/data/posts/impl/BlockingFakePostsRepository.kt
|
zach-klippenstein
| 267,634,112
| false
| null |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetnews.data.posts.impl
import android.content.Context
import androidx.ui.graphics.imageFromResource
import com.example.jetnews.data.Result
import com.example.jetnews.data.posts.PostsRepository
import com.example.jetnews.model.Post
/**
* Implementation of PostsRepository that returns a hardcoded list of
* posts with resources synchronously.
*/
class BlockingFakePostsRepository(private val context: Context) : PostsRepository {
private val postsWithResources: List<Post> by lazy {
posts.map {
it.copy(
image = imageFromResource(context.resources, it.imageId),
imageThumb = imageFromResource(context.resources, it.imageThumbId)
)
}
}
override fun getPost(postId: String, callback: (Result<Post?>) -> Unit) {
callback(Result.Success(postsWithResources.find { it.id == postId }))
}
override fun getPosts(callback: (Result<List<Post>>) -> Unit) {
callback(Result.Success(postsWithResources))
}
}
| 0
| null |
0
| 1
|
d3c4d349f8022137000c66f0e59deb6b886fb1dd
| 1,651
|
compose-samples-workflowed
|
Apache License 2.0
|
src/main/kotlin/org/wagham/config/locale/subcommands/ItemInfoLocale.kt
|
kaironbot
| 566,988,243
| false
|
{"Kotlin": 584271, "Dockerfile": 237}
|
package org.wagham.config.locale.subcommands
import dev.kord.common.Locale
import org.wagham.config.locale.LocaleEnum
enum class ItemInfoLocale(val localeMap: Map<Locale, String>): LocaleEnum {
ATTUNEMENT(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Attunement required?",
Locale.ITALIAN to "Richiede sintonia?"
)
),
CAN_BUY(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Buy price",
Locale.ITALIAN to "Prezzo di acquisto"
)
),
CAN_CRAFT(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Can be crafted",
Locale.ITALIAN to "Craftabile"
)
),
CAN_GIVE(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Give/receive ratio",
Locale.ITALIAN to "Rapporto oggetti dati:ricevuti"
)
),
CAN_USE(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Usable?",
Locale.ITALIAN to "Usabile?"
)
),
CANNOT_BUY(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Cannot be bought",
Locale.ITALIAN to "Non acquistabile"
)
),
CANNOT_CRAFT(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Cannot be crafted",
Locale.ITALIAN to "Non craftabile"
)
),
CANNOT_GIVE(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Cannot be given",
Locale.ITALIAN to "Non può essere ceduto"
)
),
CANNOT_SELL(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Cannot be sold",
Locale.ITALIAN to "Non vendibile"
)
),
DESCRIPTION(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Show the info about an item",
Locale.ITALIAN to "Mostra le informazioni riguardanti un oggetto"
)
),
ITEM(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "The item to show",
Locale.ITALIAN to "L'oggetto da mostrare"
)
),
MATERIAL_OF(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Can be used to craft",
Locale.ITALIAN to "Può essere usato per craftare"
)
),
SELLABLE(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Sell price",
Locale.ITALIAN to "Prezzo di vendita"
)
),
SOURCE(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Source",
Locale.ITALIAN to "Fonte"
)
),
TARGET(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "The user to give the item to",
Locale.ITALIAN to "L'utente a cui assegnare l'oggetto"
)
);
override fun locale(language: String) = locale(Locale.fromString(language))
override fun locale(locale: Locale) = localeMap[locale] ?: localeMap.getValue(Locale.ENGLISH_GREAT_BRITAIN)
}
| 3
|
Kotlin
|
0
| 0
|
62769fdbe0c2f4976edfbc1dab2d832db61d751f
| 2,841
|
kairon-bot
|
MIT License
|
app/src/main/java/fr/nexhub/homedia/features/settings/SettingsMenuItem.kt
|
valmnt
| 795,633,176
| false
|
{"Kotlin": 238030}
|
@file:OptIn(ExperimentalTvMaterial3Api::class)
package fr.nexhub.homedia.features.settings
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.tv.material3.ClickableSurfaceDefaults
import androidx.tv.material3.ExperimentalTvMaterial3Api
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Text
import fr.nexhub.homedia.features.common.components.FocusableItem
import fr.nexhub.homedia.features.settings.data.SettingsMenuModel
@Composable
fun SettingsMenuItem(item: SettingsMenuModel, onMenuSelected: (SettingsMenuModel) -> Unit) {
when (item.text) {
SettingsMenuDataItem.Logout.name -> {
FocusableItem(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
color = ClickableSurfaceDefaults.colors(
containerColor = MaterialTheme.colorScheme.error,
contentColor = MaterialTheme.colorScheme.onSurface,
focusedContainerColor = MaterialTheme.colorScheme.onSurface,
focusedContentColor = MaterialTheme.colorScheme.error
),
onClick = { onMenuSelected(item) }) {
Text(
text = item.text, modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)
)
}
}
else -> {
FocusableItem(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
onClick = { onMenuSelected(item) }) {
Text(
text = item.text, modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)
)
}
}
}
}
@Preview
@Composable
fun SettingsMenuItemPrev() {
SettingsMenuItem(SettingsMenuModel("Menu", "")) {}
}
| 6
|
Kotlin
|
0
| 6
|
0cd04aa9cb4944da6be1dd796e827ebc72ac7f05
| 1,969
|
homedia
|
Apache License 2.0
|
Android-Application/Dhanrakshak2/app/src/main/java/com/example/dhanrakshak/presentation/viewModel/AddTransactionViewModel.kt
|
omkarugale7
| 614,695,364
| false
| null |
package com.example.dhanrakshak.presentation.viewModel
import androidx.lifecycle.ViewModel
import com.example.dhanrakshak.data.model.entities.Transaction
import com.example.dhanrakshak.use_case.AddTransaction
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import androidx.lifecycle.viewModelScope
import com.example.dhanrakshak.data.model.entities.InvalidTransactionException
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
@HiltViewModel
class AddTransactionViewModel @Inject constructor(
private val addTransactionUseCases: AddTransaction
): ViewModel(){
private val _eventFlow = MutableSharedFlow<UiEvent>()
val eventFlow = _eventFlow.asSharedFlow()
fun addTransaction(transaction: Transaction){
viewModelScope.launch {
try {
addTransactionUseCases.invoke(
transaction
)
_eventFlow.emit(UiEvent.SaveTransaction)
} catch (e: InvalidTransactionException){
_eventFlow.emit(
UiEvent.ShowSnackBar(
message = e.message ?: "Couldn't save not"
)
)
}
}
}
sealed class UiEvent{
data class ShowSnackBar(val message: String): UiEvent()
object SaveTransaction: UiEvent()
}
}
| 0
|
Kotlin
|
1
| 1
|
39c32d97c2f65144da1ab9d8b4c77515fa78d6e3
| 1,436
|
Homies
|
MIT License
|
matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/QueuedTask.kt
|
ActiveGymnastics
| 323,292,168
| true
|
{"Kotlin": 8316611, "Java": 157700, "HTML": 24247, "Shell": 18884, "Python": 11382, "FreeMarker": 7722, "JavaScript": 1782}
|
/*
* Copyright 2020 The Matrix.org Foundation C.I.C.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.android.sdk.internal.session.room.send.queue
import org.matrix.android.sdk.api.util.Cancelable
abstract class QueuedTask : Cancelable {
var retryCount = 0
private var hasBeenCancelled: Boolean = false
suspend fun execute() {
if (!isCancelled()) {
doExecute()
}
}
abstract suspend fun doExecute()
abstract fun onTaskFailed()
open fun isCancelled() = hasBeenCancelled
final override fun cancel() {
hasBeenCancelled = true
}
}
| 0
|
Kotlin
|
0
| 0
|
30980088d994dda56d4ada50c5fca6baaca12257
| 1,136
|
element-android
|
Apache License 2.0
|
src/main/kotlin/com/melardev/spring/rest/dtos/responses/ErrorResponse.kt
|
melardev
| 192,565,304
| false
| null |
package com.melardev.spring.rest.dtos.responses
import com.melardev.spring.rest.dtos.responses.AppResponse
class ErrorResponse(errorMessage: String) : AppResponse(false) {
init {
addFullMessage(errorMessage)
}
}
| 0
|
Kotlin
|
0
| 0
|
8c53438b73fcf8e3ad246fde154b65889fb5cbb6
| 232
|
KotlinSpringBootRxApiRxMongoCrud
|
MIT License
|
event-log/src/main/kotlin/dev/yn/event/service/EventService.kt
|
dgoetsch
| 100,337,343
| 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.
*/
package dev.yn.event.service
import dev.yn.event.domain.AggregateEvent
import dev.yn.event.domain.Event
import dev.yn.event.domain.EventError
import dev.yn.event.domain.EventHistory
import java.util.*
/**
* BAse class for event service.
*
* Provides basic get and log methods as well as a framework for aggregation.
*/
interface EventService {
/**
* Aggregation logic to be implemented by the user
*/
val aggregator: dev.yn.event.aggregator.Aggregator
/**
* Aggregate a single event against the current Aggregate
*/
fun incorporate(event: Event, aggregateEvent: AggregateEvent): AggregateEvent {
return aggregateEvent.copy(
date = event.eventTime,
eventTypes = aggregateEvent.eventTypes + event.eventType,
userIds = aggregateEvent.userIds + event.userId,
body = aggregator.incorporate(event.body, aggregateEvent.body))
}
fun incorporateAndResetEventTypesAndUserIds(event: Event, aggregateEvent: AggregateEvent) : AggregateEvent {
return aggregateEvent.copy(
date = event.eventTime,
eventTypes = listOf(event.eventType),
userIds = listOf(event.userId),
body = aggregator.incorporate(event.body, aggregateEvent.body))
}
/**
* Aggregate many events against the current optional state.
*
* Will be null if and only if incorporate event is null and events is empty
*
*/
fun aggregate(events: List<Event>, aggregateEvent: AggregateEvent?): AggregateEvent? {
if (events.isNotEmpty()) {
return aggregateEvent?.let { aggregated ->
aggregated.copy(
date = events.last().eventTime,
eventTypes = aggregated.eventTypes + events.map { it.eventType },
userIds = aggregated.userIds + events.map { it.userId },
body = aggregator.aggregate(events.map { it.body }, aggregated.body))
} ?:
AggregateEvent(
resourceId = events.first().resourceId,
date = events.last().eventTime,
eventTypes = events.map { it.eventType },
userIds = events.map { it.userId },
body = aggregator.aggregate(events.map { it.body }, aggregator.baseEventBytes))
} else {
return aggregateEvent
}
}
fun logEvent(event: Event): org.funktionale.either.Either<EventError, Unit>
fun getEventHistory(resourceId: java.util.UUID): org.funktionale.either.Either<EventError, EventHistory>
fun getEvents(entityId: java.util.UUID, day: java.util.Date): List<Event>
fun getCurrentAggregate(resourceId: java.util.UUID): AggregateEvent?
fun getLatest(resourceId: UUID): Event?
fun processLoggedEvent(event: Event): AggregateEvent?
fun processLoggedEvent(resourceId: UUID): AggregateEvent? {
return getLatest(resourceId)
?.let(this::processLoggedEvent)
}
}
| 0
|
Kotlin
|
0
| 5
|
afe6b2caba24b2a08347dc508d019a70bdeba10f
| 3,743
|
akka-vertx-demo
|
Apache License 2.0
|
Kernl.Runtime/src/main/kotlin/org/mattshoe/shoebox/kernl/runtime/cache/invalidation/tracker/impl/EagerRefreshInvalidationExecutor.kt
|
mattshoe
| 825,957,770
| false
|
{"Kotlin": 344588, "Shell": 1045}
|
package org.mattshoe.shoebox.kernl.runtime.cache.invalidation.tracker.impl
import kotlinx.coroutines.flow.*
import org.mattshoe.shoebox.kernl.InvalidationStrategy
import org.mattshoe.shoebox.kernl.runtime.DataResult
import org.mattshoe.shoebox.kernl.runtime.cache.invalidation.tracker.BaseInvalidationExecutor
import org.mattshoe.shoebox.kernl.runtime.ext.conflatingChannelFlow
import org.mattshoe.shoebox.kernl.runtime.session.KernlResourceManager
class EagerRefreshInvalidationExecutor(
private val strategy: InvalidationStrategy.EagerRefresh,
kernlResourceManager: KernlResourceManager
): BaseInvalidationExecutor(kernlResourceManager) {
private val manualRefreshStream = MutableSharedFlow<Unit>()
override val invalidationStream = MutableSharedFlow<Unit>()
override val refreshStream: Flow<Unit>
get() = conflatingChannelFlow {
kernlRegistration.timeToLiveStream
.onEach {
send(it)
}.launchIn(this)
manualRefreshStream
.onEach {
send(it)
}.launchIn(this)
}
override suspend fun shouldForceFetch(currentState: DataResult<*>?): Boolean = false
override suspend fun onDataChanged() {
resetTimeToLive(strategy.timeToLive)
}
override suspend fun onInvalidated() {
manualRefreshStream.emit(Unit)
}
}
| 10
|
Kotlin
|
1
| 9
|
9682fcafeb1dccd468443e1265eab55c05757e52
| 1,407
|
kernl
|
Apache License 2.0
|
kotlin-mui-icons/src/main/generated/mui/icons/material/SignalWifi0Bar.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/SignalWifi0Bar")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val SignalWifi0Bar: SvgIconComponent
| 10
|
Kotlin
|
145
| 983
|
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
| 210
|
kotlin-wrappers
|
Apache License 2.0
|
lib_framework/src/main/java/com/logan/framework/log/XLogger.kt
|
logan0817
| 790,127,966
| false
| null |
package com.sum.framework.log
import android.app.Application
import android.util.Log
//import com.tencent.mars.xlog.Log
//import com.tencent.mars.xlog.Xlog
/**
* XLog的管理工具类
*/
class XLogger {
/**
* 初始化xlog
*/
fun init(context: Application, isDebug: Boolean, logPath: String, namePrefix: String = "sumTea") {
System.loadLibrary("c++_shared")
System.loadLibrary("marsxlog")
val cachePath = context.filesDir.absolutePath + "sumTea/xlog"
// val xlog = Xlog()
// xlog.apply {
// val level: Int
// if (isDebug) {
// level = Xlog.LEVEL_VERBOSE
// xlog.setConsoleLogOpen(0, true)
// } else {
// level = Xlog.LEVEL_WARNING
// xlog.setConsoleLogOpen(0, false)
// }
//
// appenderOpen(level, Xlog.AppednerModeAsync, cachePath, logPath, namePrefix, 0)
// }
// Log.setLogImp(xlog)
}
fun v(tag: String, msg: String) {
Log.v(tag, msg)
}
fun d(tag: String, msg: String) {
Log.d(tag, msg)
}
fun i(tag: String, msg: String) {
Log.i(tag, msg)
}
fun w(tag: String, msg: String) {
Log.w(tag, msg)
}
fun e(tag: String, msg: String) {
Log.e(tag, msg)
}
// /**
// * 异常日志打印
// */
// fun logThrowable(tag: String, tr: Throwable, msg: String) {
// Log.printErrStackTrace(tag, tr, msg)
// }
//
// /**
// * 将缓存的日志刷新到文件内
// */
// fun flushLog() {
// Log.appenderFlush()
// }
//
// /**
// * 关闭日志,退出应用时调用
// */
// fun close() {
// Log.appenderClose()
// }
}
| 0
| null |
0
| 2
|
20b74ca8af06dea1f48b5f188f86f31944826aa0
| 1,679
|
BleExplorer
|
Apache License 2.0
|
src/commonTest/kotlin/csense/kotlin/extensions/primitives/ByteTest.kt
|
csense-oss
| 136,911,995
| false
| null |
package csense.kotlin.extensions.primitives
import csense.kotlin.tests.assertions.*
import kotlin.test.*
class ByteTest {
@Test
fun isNotZero() {
val zero: Byte = Byte.zero
val positive: Byte = 1
val negative: Byte = -1
zero.isNotZero.assertFalse()
positive.isNotZero.assertTrue()
negative.isNotZero.assertTrue()
}
@Test
fun isZero() {
val zero: Byte = Byte.zero
val positive: Byte = 1
val negative: Byte = -1
zero.isZero.assertTrue()
positive.isZero.assertFalse()
negative.isZero.assertFalse()
}
@Test
fun isNegativeOrZero() {
val zero: Byte = Byte.zero
val positive: Byte = 1
val negative: Byte = -1
zero.isNegativeOrZero.assertTrue()
positive.isNegativeOrZero.assertFalse()
negative.isNegativeOrZero.assertTrue()
}
@Test
fun isPositiveOrZero() {
val zero: Byte = Byte.zero
val positive: Byte = 1
val negative: Byte = -1
zero.isPositiveOrZero.assertTrue()
positive.isPositiveOrZero.assertTrue()
negative.isPositiveOrZero.assertFalse()
}
@Test
fun isNegative() {
val zero: Byte = Byte.zero
val positive: Byte = 1
val negative: Byte = -1
zero.isNegative.assertFalse()
positive.isNegative.assertFalse()
negative.isNegative.assertTrue()
}
@Test
fun isPositive() {
val zero: Byte = Byte.zero
val positive: Byte = 1
val negative: Byte = -1
zero.isPositive.assertFalse()
positive.isPositive.assertTrue()
negative.isPositive.assertFalse()
}
@Test
fun isEven() {
0.toByte().isEven.assertTrue()
1.toByte().isEven.assertFalse()
2.toByte().isEven.assertTrue()
23.toByte().isEven.assertFalse()
26.toByte().isEven.assertTrue()
}
@Test
fun isOdd() {
0.toByte().isOdd.assertFalse()
1.toByte().isOdd.assertTrue()
2.toByte().isOdd.assertFalse()
27.toByte().isOdd.assertTrue()
16.toByte().isOdd.assertFalse()
}
@Test
fun toChars() {
0.toByte().toChars { upperChar, lowerChar ->
upperChar.assert('0', ignoreCase = true)
lowerChar.assert('0', ignoreCase = true)
42
}.assert(42)
0xFE.toByte().toChars { upperChar, lowerChar ->
upperChar.assert('F', ignoreCase = true)
lowerChar.assert('E', ignoreCase = true)
}
}
@Test
fun toHexString() {
0x00.toByte().toHexString().assert("00")
0x04.toByte().toHexString().assert("04")
0x0E.toByte().toHexString().assert("0E")
0x1E.toByte().toHexString().assert("1E")
0xFE.toByte().toHexString().assert("FE")
}
@Test
fun byteCompanionZero() {
Byte.zero.assert(0)
}
@Test
fun byteNegative() {
0.toByte().negative.assert(-0)
(-1).toByte().negative.assert(-1)
1.toByte().negative.assert(-1)
80.toByte().negative.assert(-80)
(-82).toByte().negative.assert(-82)
}
@Test
fun byteIsOdd() {
0.toByte().isOdd.assertFalse()
(-1).toByte().isOdd.assertTrue()
1.toByte().isOdd.assertTrue()
80.toByte().isOdd.assertFalse()
(-82).toByte().isOdd.assertFalse()
}
@Test
fun byteIsEven() {
0.toByte().isEven.assertTrue()
(-1).toByte().isEven.assertFalse()
1.toByte().isEven.assertFalse()
80.toByte().isEven.assertTrue()
(-82).toByte().isEven.assertTrue()
}
@Test
fun byteIsPositive() {
0.toByte().isPositive.assertFalse()
(-1).toByte().isPositive.assertFalse()
1.toByte().isPositive.assertTrue()
80.toByte().isPositive.assertTrue()
(-82).toByte().isPositive.assertFalse()
}
@Test
fun byteIsNegative() {
0.toByte().isNegative.assertFalse()
(-1).toByte().isNegative.assertTrue()
1.toByte().isNegative.assertFalse()
80.toByte().isNegative.assertFalse()
(-82).toByte().isNegative.assertTrue()
}
@Test
fun byteIsPositiveOrZero() {
0.toByte().isPositiveOrZero.assertTrue()
(-1).toByte().isPositiveOrZero.assertFalse()
1.toByte().isPositiveOrZero.assertTrue()
80.toByte().isPositiveOrZero.assertTrue()
(-82).toByte().isPositiveOrZero.assertFalse()
}
@Test
fun byteIsNegativeOrZero() {
0.toByte().isNegativeOrZero.assertTrue()
(-1).toByte().isNegativeOrZero.assertTrue()
1.toByte().isNegativeOrZero.assertFalse()
80.toByte().isNegativeOrZero.assertFalse()
(-82).toByte().isNegativeOrZero.assertTrue()
}
@Test
fun byteIsZero() {
0.toByte().isZero.assertTrue()
(-1).toByte().isZero.assertFalse()
1.toByte().isZero.assertFalse()
80.toByte().isZero.assertFalse()
(-82).toByte().isZero.assertFalse()
}
@Test
fun byteIsNotZero() {
0.toByte().isNotZero.assertFalse()
(-1).toByte().isNotZero.assertTrue()
1.toByte().isNotZero.assertTrue()
80.toByte().isNotZero.assertTrue()
(-82).toByte().isNotZero.assertTrue()
}
@Test
fun bytePositive() {
0.toByte().positive.assert(0)
(-1).toByte().positive.assert(1)
1.toByte().positive.assert(1)
80.toByte().positive.assert(80)
(-82).toByte().positive.assert(82)
}
@Test
fun byteToIntBitWise() {
0.toByte().toIntBitWise().assert(0)
(-1).toByte().toIntBitWise().assert(0b11111111)
1.toByte().toIntBitWise().assert(1)
80.toByte().toIntBitWise().assert(80)
(-82).toByte().toIntBitWise().assert(0b10101110) //-82 in binary is 10101110
}
}
| 1
|
Kotlin
|
0
| 2
|
49113dd6b2cb1e18992d07faa1e0305d18f766f4
| 5,890
|
csense-kotlin
|
MIT License
|
db-async-common/src/main/kotlin/com/github/mauricio/async/db/util/DaemonThreadsFactory.kt
|
KotlinPorts
| 77,183,383
| false
| null |
/*
* Copyright 2013 <NAME>
*
* <NAME> licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.util
import java.util.concurrent.Executors
import java.util.concurrent.ThreadFactory
import java.util.concurrent.atomic.AtomicInteger
data class DaemonThreadsFactory(val name: String) : ThreadFactory {
private val threadNumber = AtomicInteger(1)
override fun newThread(r: Runnable): Thread {
val thread = Executors.defaultThreadFactory().newThread(r)
thread.setDaemon(true)
val threadName = name + "-thread-" + threadNumber.getAndIncrement()
thread.setName(threadName)
return thread
}
}
| 5
|
Kotlin
|
2
| 23
|
942ebfeee4601f9580916ed551fcfd2f8084d701
| 1,195
|
pooled-client
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.