path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/canon/parser/map/strategy/ItemStrategy.kt | leftshiftone | 205,671,409 | false | null | package canon.parser.map.strategy
import canon.api.IRenderable
import canon.model.Item
class ItemStrategy : AbstractParseStrategy<Item>() {
override fun parse(map: Map<String, Any>, factory: (Map<String, Any>) -> List<IRenderable>): Item {
return Item(
map["id"]?.toString()?.ifEmpty { null },
map["class"]?.toString()?.ifEmpty { null },
map["ariaLabel"]?.toString()?.ifEmpty { null },
factory(map)
)
}
} | 0 | Kotlin | 1 | 0 | 00030eeabff75a1f87927940d989cb122273a0bf | 478 | canon | MIT License |
sdk-mobile/src/main/kotlin/io/github/wulkanowy/sdk/mobile/Mobile.kt | dominik-korsa | 237,057,001 | true | {"Kotlin": 509705, "HTML": 128700, "Shell": 505} | package io.github.wulkanowy.sdk.mobile
import com.migcomponents.migbase64.Base64
import io.github.wulkanowy.sdk.mobile.attendance.Attendance
import io.github.wulkanowy.sdk.mobile.dictionaries.Dictionaries
import io.github.wulkanowy.sdk.mobile.exams.Exam
import io.github.wulkanowy.sdk.mobile.exception.InvalidPinException
import io.github.wulkanowy.sdk.mobile.exception.NoStudentsException
import io.github.wulkanowy.sdk.mobile.exception.TokenDeadException
import io.github.wulkanowy.sdk.mobile.exception.TokenNotFoundException
import io.github.wulkanowy.sdk.mobile.exception.UnknownTokenException
import io.github.wulkanowy.sdk.mobile.exception.UnsupportedTokenException
import io.github.wulkanowy.sdk.mobile.grades.Grade
import io.github.wulkanowy.sdk.mobile.grades.GradesSummaryResponse
import io.github.wulkanowy.sdk.mobile.homework.Homework
import io.github.wulkanowy.sdk.mobile.messages.Message
import io.github.wulkanowy.sdk.mobile.messages.Recipient
import io.github.wulkanowy.sdk.mobile.notes.Note
import io.github.wulkanowy.sdk.mobile.register.CertificateResponse
import io.github.wulkanowy.sdk.mobile.register.Student
import io.github.wulkanowy.sdk.mobile.repository.RepositoryManager
import io.github.wulkanowy.sdk.mobile.school.Teacher
import io.github.wulkanowy.sdk.mobile.timetable.Lesson
import io.github.wulkanowy.signer.getPrivateKeyFromCert
import io.reactivex.Single
import okhttp3.Interceptor
import okhttp3.logging.HttpLoggingInterceptor
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalDateTime
import java.nio.charset.Charset
class Mobile {
var classId = 0
var studentId = 0
var loginId = 0
private val resettableManager = resettableManager()
var logLevel = HttpLoggingInterceptor.Level.BASIC
set(value) {
field = value
resettableManager.reset()
}
var privateKey = ""
set(value) {
field = value
resettableManager.reset()
}
var certKey = ""
set(value) {
field = value
resettableManager.reset()
}
var baseUrl = ""
set(value) {
field = value
resettableManager.reset()
}
var schoolSymbol = ""
set(value) {
field = value
resettableManager.reset()
}
private val serviceManager by resettableLazy(resettableManager) { RepositoryManager(logLevel, privateKey, certKey, interceptors, baseUrl, schoolSymbol) }
private val routes by resettableLazy(resettableManager) { serviceManager.getRoutesRepository() }
private val mobile by resettableLazy(resettableManager) { serviceManager.getMobileRepository() }
private val interceptors: MutableList<Pair<Interceptor, Boolean>> = mutableListOf()
fun setInterceptor(interceptor: Interceptor, network: Boolean = false) {
interceptors.add(interceptor to network)
}
private lateinit var dictionaries: Dictionaries
fun getDictionaries(): Single<Dictionaries> {
if (::dictionaries.isInitialized) return Single.just(dictionaries)
return mobile.getDictionaries(0, 0, classId).map {
it.apply { dictionaries = this }
}
}
fun getCertificate(token: String, pin: String, symbol: String, deviceName: String, androidVer: String, firebaseToken: String): Single<CertificateResponse> {
return routes.getRouteByToken(token).flatMap { baseUrl ->
serviceManager.getRegisterRepository(baseUrl, symbol).getCertificate(token, pin, deviceName, androidVer, firebaseToken)
}
}
fun getStudents(certRes: CertificateResponse, apiKey: String = ""): Single<List<Student>> {
if (certRes.isError) when {
certRes.message == "TokenDead" -> throw TokenDeadException(certRes.message)
certRes.message == "TokenNotFound" -> throw TokenNotFoundException(certRes.message)
certRes.message?.startsWith("Podany numer PIN jest niepoprawny") == true -> throw InvalidPinException(certRes.message.orEmpty())
certRes.message?.startsWith("Trzykrotnie wpisano niepoprawny kod PIN") == true -> throw InvalidPinException(certRes.message.orEmpty())
certRes.message == "NoPupils" -> throw NoStudentsException(certRes.message.orEmpty())
certRes.message == "OnlyKindergarten" -> throw UnsupportedTokenException(certRes.message)
else -> throw UnknownTokenException(certRes.message.orEmpty())
}
val cert = certRes.tokenCert!!
certKey = cert.certificateKey
baseUrl = cert.baseUrl.removeSuffix("/")
privateKey = getPrivateKeyFromCert(apiKey.ifEmpty {
Base64.decode(if (cert.baseUrl.contains("fakelog")) "KDAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OUFCKQ==" else "<KEY>)
.toString(Charset.defaultCharset())
.removeSurrounding("(", ")")
}, cert.certificatePfx)
return serviceManager.getRegisterRepository(cert.baseUrl).getStudents().map { students ->
students.map {
it.copy().apply {
certificateKey = [email protected]
privateKey = [email protected]
mobileBaseUrl = [email protected]
}
}
}
}
fun getStudents(): Single<List<Student>> {
return serviceManager.getRegisterRepository(baseUrl).getStudents()
}
fun getAttendance(start: LocalDate, end: LocalDate, classificationPeriodId: Int): Single<List<Attendance>> {
return mobile.getAttendance(start, end, classId, classificationPeriodId, studentId)
}
fun getExams(start: LocalDate, end: LocalDate, classificationPeriodId: Int): Single<List<Exam>> {
return mobile.getExams(start, end, classId, classificationPeriodId, studentId)
}
fun getGrades(classificationPeriodId: Int): Single<Pair<List<Grade>, GradesSummaryResponse>> {
return getGradesDetails(classificationPeriodId).flatMap { details ->
getGradesSummary(classificationPeriodId).map { summary ->
details to summary
}
}
}
fun getGradesDetails(classificationPeriodId: Int): Single<List<Grade>> {
return mobile.getGradesDetails(classId, classificationPeriodId, studentId)
}
fun getGradesSummary(classificationPeriodId: Int): Single<GradesSummaryResponse> {
return mobile.getGradesSummary(classId, classificationPeriodId, studentId)
}
fun getHomework(start: LocalDate, end: LocalDate, classificationPeriodId: Int): Single<List<Homework>> {
return mobile.getHomework(start, end, classId, classificationPeriodId, studentId)
}
fun getNotes(classificationPeriodId: Int): Single<List<Note>> {
return mobile.getNotes(classificationPeriodId, studentId)
}
fun getTeachers(studentId: Int, semesterId: Int): Single<List<Teacher>> {
return mobile.getTeachers(studentId, semesterId)
}
fun getMessages(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> {
return mobile.getMessages(start, end, loginId, studentId)
}
fun getMessagesSent(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> {
return mobile.getMessagesSent(start, end, loginId, studentId)
}
fun getMessagesDeleted(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> {
return mobile.getMessagesDeleted(start, end, loginId, studentId)
}
fun changeMessageStatus(messageId: Int, folder: String, status: String): Single<String> {
return mobile.changeMessageStatus(messageId, folder, status, loginId, studentId)
}
fun sendMessage(subject: String, content: String, recipients: List<Recipient>): Single<Message> {
return getStudents().map { students ->
students.singleOrNull { it.loginId == loginId }?.name.orEmpty()
}.flatMap { sender ->
mobile.sendMessage(sender, subject, content, recipients, loginId, studentId)
}
}
fun getTimetable(start: LocalDate, end: LocalDate, classificationPeriodId: Int): Single<List<Lesson>> {
return mobile.getTimetable(start, end, classId, classificationPeriodId, studentId)
}
}
| 0 | Kotlin | 0 | 0 | 2d2b5176e6b3d5e5eb6b812441c1af740f26eeb5 | 8,242 | sdk | Apache License 2.0 |
app/src/main/java/br/com/fioalpha/heromarvel/domain/IsCharacterFavoriteUseCase.kt | fioalpha | 264,306,059 | false | null | package br.com.fioalpha.heromarvel.domain
import br.com.fioalpha.heromarvel.domain.model.CharacterDomain
import io.reactivex.Observable
interface IsCharacterFavoriteUseCase : UserCase<Observable<List<CharacterDomain>>> {
fun setCharacters(characters: List<CharacterDomain>): IsCharacterFavoriteUseCase
}
| 0 | Kotlin | 0 | 3 | 7b0ee22d4431c2330e147de651b92022d61aea5a | 310 | Hero-Marvel | The Unlicense |
data/src/main/java/com/ribsky/data/service/offline/active/ActiveLessonDao.kt | nexy791 | 607,748,138 | false | null | package com.ribsky.data.service.offline.active
import androidx.room.*
import com.ribsky.data.model.ActiveApiModel
@Dao
interface ActiveLessonDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(active: ActiveApiModel)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun _insert(active: List<ActiveApiModel>)
@Transaction
suspend fun insert(active: List<ActiveApiModel>) {
delete()
_insert(active)
}
@Query("DELETE FROM activeapimodel")
suspend fun delete()
@Query("SELECT * FROM activeapimodel")
suspend fun get(): List<ActiveApiModel>
}
| 0 | Kotlin | 0 | 7 | d2e9f7c04635e1793bfe8f421b4bc5ef162556c0 | 635 | dymka | Apache License 2.0 |
src/main/kotlin/adapter/UserIdColumnAdapter.kt | mchllngr | 374,221,076 | false | null | package adapter
import com.squareup.sqldelight.ColumnAdapter
import model.user.UserId
class UserIdColumnAdapter : ColumnAdapter<UserId, String> {
override fun decode(databaseValue: String): UserId = UserId(databaseValue)
override fun encode(value: UserId): String = value.id
}
| 18 | Kotlin | 2 | 0 | 9b0c68b72aa3bf3cd49a7154287422d3cfff0b66 | 289 | mchllngr-slack-bot | Apache License 2.0 |
library/src/test/java/io/github/toyota32k/bindit/CheckBindingTest.kt | toyota-m2k | 643,389,596 | false | {"Kotlin": 303617} | package io.github.toyota32k.bindit
import android.widget.ToggleButton
import androidx.appcompat.app.AppCompatActivity
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.android.controller.ActivityController
@RunWith(RobolectricTestRunner::class)
class CheckBindingTest {
@Rule
@JvmField
val instantExecutorRule : InstantTaskExecutorRule = InstantTaskExecutorRule()
lateinit var activityController : ActivityController<JustTestActivity>
fun createActivity(): AppCompatActivity {
activityController = Robolectric.buildActivity(JustTestActivity::class.java)
return activityController.create().start().get() as AppCompatActivity
}
fun finish() {
activityController.pause().destroy()
}
@Test
fun oneWayCheckTest() {
val activity = createActivity()
val view = ToggleButton(activity)
val data = MutableLiveData<Boolean>(false)
val binding = CheckBinding.create(activity, view, data, BoolConvert.Straight, BindingMode.OneWay)
assertEquals(data.value, view.isChecked)
assertFalse(view.isChecked)
data.value = true
assertEquals(data.value, view.isChecked)
assertTrue(view.isChecked)
view.isChecked = false
assertTrue(data.value!!)
}
@Test
fun oneWayToSourceCheckTest() {
val activity = createActivity()
val view = ToggleButton(activity)
val data = MutableLiveData<Boolean>(false)
view.isChecked = true
val binding = CheckBinding.create(activity, view, data, BoolConvert.Straight, BindingMode.OneWayToSource)
assertEquals(data.value, view.isChecked)
assertTrue(data.value!!)
view.isChecked = false
assertEquals(data.value, view.isChecked)
assertFalse(data.value!!)
data.value = true
assertNotEquals(data.value, view.isChecked)
assertFalse(view.isChecked)
}
@Test
fun twoWayCheckTest() {
val activity = createActivity()
val view = ToggleButton(activity)
val data = MutableLiveData<Boolean>(false)
view.isChecked = true
val binding = CheckBinding.create(activity, view, data, BoolConvert.Straight, BindingMode.TwoWay)
assertEquals(data.value, view.isChecked)
assertFalse(view.isChecked)
view.isChecked = false
assertEquals(data.value, view.isChecked)
assertFalse(data.value!!)
data.value = true
assertEquals(data.value, view.isChecked)
assertTrue(view.isChecked)
}
} | 0 | Kotlin | 0 | 0 | a5ee49c1b17b59fbd147ab61ac5aed3b1fada8c3 | 2,819 | bind-it | Apache License 2.0 |
Sample/KotlinWeather/app/src/main/java/com/liuguilin/kotlinweather/ui/CitySelectActivity.kt | LiuGuiLinAndroid | 110,441,745 | false | null | package com.liuguilin.kotlinweather.ui
import android.content.Intent
import android.view.MotionEvent
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.liuguilin.kotlinweather.MainActivity
import com.liuguilin.kotlinweather.R
import com.liuguilin.kotlinweather.adapter.CitySelectAdapter
import com.liuguilin.kotlinweather.base.BaseActivity
import com.liuguilin.kotlinweather.bean.CityListBean
import com.liuguilin.kotlinweather.net.NetManager
import com.liuguilin.kotlinweather.utils.L
import com.liuguilin.kotlinweather.utils.SpUtils
import kotlinx.android.synthetic.main.activity_city_select.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
/**
* FileName: CitySelectActivity
* Founder: LiuGuiLin
* Profile:
*/
class CitySelectActivity : BaseActivity() {
//装载省级的列表
private var provinceList: List<String>? = null
//适配器
private var mCityAdapter: CitySelectAdapter? = null
override fun getLayoutId(): Int {
return R.layout.activity_city_select
}
override fun isShowBack(): Boolean {
return true
}
override fun initView() {
supportActionBar?.title = getString(R.string.tv_select_city)
mCityAdapter = CitySelectAdapter(this)
mCityView.layoutManager = LinearLayoutManager(this)
mCityView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
mCityView.adapter = mCityAdapter
mCitySelectView.setShowView(mShowCity)
mCityAdapter!!.setOnItemClickListener {
SpUtils.instance.putString("city", it.id)
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("city", it.id)
startActivity(intent)
finish()
}
mCitySelectView.setOnMoveItemListener { city ->
mShowCity.text = city
findScrollIndex(city)
}
mCityView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
val lm = recyclerView.layoutManager
if (lm is LinearLayoutManager) {
//屏幕可见的第一个Item
val firstIndex = lm.findFirstVisibleItemPosition()
//根据可见下标得到值
val city = provinceList!![firstIndex]
mCitySelectView.setItemCity(city)
}
}
})
loadCityList()
}
//根据城市名查找下标并且滚动
private fun findScrollIndex(city: String) {
var scrollIndex = 0
provinceList?.let {
//满足条件的第一个
for ((k, v) in it.withIndex()) {
if (city == v) {
scrollIndex = k
return@let
}
}
}
mCityView.scrollToPosition(scrollIndex)
}
private fun loadCityList() {
NetManager.getCityList().enqueue(object : Callback<CityListBean> {
override fun onFailure(call: Call<CityListBean>, t: Throwable) {
L.i("加载失败")
}
override fun onResponse(call: Call<CityListBean>, response: Response<CityListBean>) {
L.i("加载成功")
response.body()?.result?.let { mCityAdapter?.updateData(it) }
mCitySelectView.setCity(buildCity(response.body()?.result))
}
})
}
/**
* 对城市列表进行过滤
*/
private fun buildCity(result: List<CityListBean.ResultBean>?): MutableList<String> {
//加载城市列表
provinceList = result?.map {
it.province
}
val list: MutableList<String> = ArrayList()
//去除重复
for (p in provinceList!!) {
if (!list.contains(p)) {
list.add(p)
}
}
return list
}
} | 0 | null | 8 | 28 | 42cb233852a72eaa47f57c757e94fd9f83bb0589 | 3,966 | Kotlin | Apache License 2.0 |
app/src/callback/java/com/alicloud/databox/demo/AuthLoginActivity.kt | alibaba | 730,014,798 | false | {"Kotlin": 72928, "Java": 99} | package com.alicloud.databox.demo
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class AuthLoginActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_auth_login)
findViewById<View>(R.id.btnOAuth).setOnClickListener {
startOAuth()
}
}
private fun startOAuth() {
val context = this
AliyunpanApp.aliyunpanClient?.oauth({
Toast.makeText(context, "开始授权", Toast.LENGTH_SHORT).show()
}, {
Toast.makeText(context, "发起授权失败", Toast.LENGTH_SHORT).show()
})
}
} | 1 | Kotlin | 0 | 6 | cf0650181d24de9899cd9154f6a788f3ccb72c85 | 748 | aliyunpan-android-sdk | MIT License |
client/src/jsMain/kotlin/io/eqoty/secretk/extensions/accesscontrol/newPermitWithTargetSpecificWallet.kt | eqoty-labs | 473,021,738 | false | null | package io.eqoty.secretk.extensions.accesscontrol
import io.eqoty.secret.std.types.Permission
import io.eqoty.secret.std.types.StdSignature
import io.eqoty.secretk.wallet.AminoSignResponse
import io.eqoty.secretk.wallet.Wallet
import io.eqoty.wallet.OfflineSignerOnlyAminoWalletWrapper
import jslibs.keplrwallet.types.KeplrSignOptionsImpl
import kotlinx.coroutines.await
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlin.js.Promise
internal actual suspend fun PermitFactory.newPermitWithTargetSpecificWallet(
wallet: Wallet,
owner: String,
chainId: String,
permitName: String,
allowedTokens: List<String>,
permissions: List<Permission>
): StdSignature? {
return if (wallet is OfflineSignerOnlyAminoWalletWrapper) {
val jsAminoSignResponse = (wallet.keplr
.signAmino(
chainId,
owner,
JSON.parse(Json.encodeToString(newSignDoc(chainId, permitName, allowedTokens, permissions))),
// not sure why I can't just directly use KeplrSignOptionsImpl here 🙃
signOptions = JSON.parse(
Json.encodeToString(
KeplrSignOptionsImpl(
preferNoSetFee = true, // Fee must be 0, so hide it from the user
preferNoSetMemo = true, // Memo must be empty, so hide it from the user
disableBalanceCheck = true
)
)
)
) as Promise<dynamic>)
.await()
val aminoSignResponse: AminoSignResponse = Json.decodeFromString(JSON.stringify(jsAminoSignResponse))
aminoSignResponse.signature
} else {
null
}
} | 6 | null | 2 | 9 | 3da2b337a1a025d098d24f7a7d0cde661a3e5e99 | 1,787 | secretk | MIT License |
packages/expo-updates/android/src/androidTest/java/expo/modules/updates/codesigning/SignatureHeaderInfoTest.kt | Norfeldt | 473,755,573 | true | {"Objective-C": 15250673, "Java": 10675005, "C++": 7801498, "TypeScript": 5338441, "Kotlin": 5206246, "Objective-C++": 3042251, "Swift": 1014264, "JavaScript": 977729, "Starlark": 514419, "Ruby": 348519, "C": 278256, "Makefile": 154769, "Shell": 51832, "Assembly": 31156, "HTML": 20674, "CMake": 19397, "Batchfile": 89} | package expo.modules.updates.codesigning
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4ClassRunner::class)
class SignatureHeaderInfoTest {
@Test
fun test_parseSignatureHeader_ParsesCodeSigningInfo() {
val codeSigningInfo = SignatureHeaderInfo.parseSignatureHeader("sig=\"12345\", keyid=\"test\", alg=\"rsa-v1_5-sha256\"")
Assert.assertEquals(codeSigningInfo.signature, "12345")
Assert.assertEquals(codeSigningInfo.keyId, "test")
Assert.assertEquals(codeSigningInfo.algorithm, CodeSigningAlgorithm.RSA_SHA256)
}
@Test
fun test_parseSignatureHeader_DefaultsKeyIdAndAlg() {
val codeSigningInfo = SignatureHeaderInfo.parseSignatureHeader("sig=\"12345\"")
Assert.assertEquals(codeSigningInfo.signature, "12345")
Assert.assertEquals(codeSigningInfo.keyId, "root")
Assert.assertEquals(codeSigningInfo.algorithm, CodeSigningAlgorithm.RSA_SHA256)
}
@Test(expected = Exception::class)
@Throws(Exception::class)
fun test_parseSignatureHeader_ThrowsForInvalidAlg() {
SignatureHeaderInfo.parseSignatureHeader("sig=\"12345\", alg=\"blah\"")
}
}
| 0 | null | 0 | 0 | f67aa9d28cf9523b7eefa75640110219c230c935 | 1,214 | expo | MIT License |
sdk/src/main/java/com/stytch/sdk/b2b/organization/Organization.kt | stytchauth | 314,556,359 | false | null | package com.stytch.sdk.b2b.organization
import com.stytch.sdk.b2b.OrganizationResponse
/**
* The Organization interface provides methods for retrieving the current authenticated user's organization.
*/
public interface Organization {
/**
* Wraps Stytch’s organization/me endpoint.
* @return [OrganizationResponse]
*/
public suspend fun get(): OrganizationResponse
/**
* Wraps Stytch’s organization/me endpoint.
* @param callback a callback that receives an [OrganizationResponse]
*/
public fun get(callback: (OrganizationResponse) -> Unit)
}
| 0 | Kotlin | 0 | 8 | bcc4045ca304e6eed4605678a86f3147b756ae0b | 593 | stytch-android | MIT License |
misk-testing/src/main/kotlin/misk/MiskTestingServiceModule.kt | cashapp | 113,107,217 | false | {"Kotlin": 3741317, "TypeScript": 235821, "Java": 83564, "JavaScript": 4076, "Shell": 3462, "HTML": 1536, "CSS": 58} | package misk
import misk.concurrent.FakeSleeperModule
import misk.environment.FakeEnvVarModule
import misk.inject.KAbstractModule
import misk.random.FakeRandomModule
import misk.resources.TestingResourceLoaderModule
import misk.time.FakeClockModule
import misk.time.FakeTickerModule
import misk.tokens.FakeTokenGeneratorModule
/**
* [MiskTestingServiceModule] should be installed in unit testing environments.
*
* This should not contain application level fakes for testing. It includes a small, selective
* set of fake bindings to replace real bindings that cannot exist in a unit testing environment
* (e.g system env vars and filesystem dependencies).
*/
class MiskTestingServiceModule : KAbstractModule() {
override fun configure() {
install(TestingResourceLoaderModule())
install(FakeEnvVarModule())
install(FakeClockModule())
install(FakeSleeperModule())
install(FakeTickerModule())
install(FakeRandomModule())
install(FakeTokenGeneratorModule())
install(MiskCommonServiceModule())
}
}
| 172 | Kotlin | 168 | 395 | d13f8e10fa64c45c5a0a9574730ec02bb642e85f | 1,036 | misk | Apache License 2.0 |
app/src/main/java/com/example/spendwise/data/AppUiState.kt | hugozeminian | 770,198,846 | false | {"Kotlin": 163227, "JavaScript": 16952} | package com.example.spendwise.data
import com.example.spendwise.model.RewardItem
import com.example.spendwise.model.Spending
import com.example.spendwise.model.SpendingsCategories
import com.example.spendwise.model.User
import com.example.spendwise.network.Response
data class AppUiState(
//Navbar icons state
val selectedIconIndex: Int = 0,
//Sample list to show items in "Spendings" screen - first list
val breakDownListSample: List<Spending> = listOf(),
//List of user's credentials
val userListSample: List<User> = listOf(),
val loggedUser: User = User("","","",""),
//Set if the user is successfully logged or not
val isLogged: Boolean = true,
//Dark mode settings
val isDarkMode: Boolean = false,
//Monthly income
val income: Float = 0F,
//Monthly budget
val monthlyBudget: Float = 0F,
val weeklyBudget: Float = 0F,
val budgetAlert: Float = 0F,
val savingsPercentage: Float = 0F,
//Alert Limit
val showAlert: Boolean = false,
//Spendings Categories
val spendingsCategoriesList: List<SpendingsCategories> = listOf(
SpendingsCategories("Insert new category", 0F),
),
//Selection of recap list (monthly or weekly)
val spendingRecap: String = "Weekly",
//Rewards list
val rewardsBalance: Float = 0F,
val rewardsList: List<RewardItem> = listOf(),
val response: List<Response> = listOf()
)
| 0 | Kotlin | 0 | 0 | 1ede61cbd0dd7abf2dfee153be535c3f0a139f7a | 1,428 | Android-SpendWise-FinalProject | Apache License 2.0 |
libs/task-manager/src/main/kotlin/net/corda/taskmanager/TaskManager.kt | corda | 346,070,752 | false | {"Kotlin": 20107119, "Java": 320782, "Smarty": 115617, "Shell": 54666, "Groovy": 30254, "PowerShell": 6509, "TypeScript": 5826, "Solidity": 2024} | package net.corda.taskmanager
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
interface TaskManager : Executor {
fun <T> executeShortRunningTask(command: () -> T): CompletableFuture<T>
fun <T> executeLongRunningTask(command: () -> T): CompletableFuture<T>
fun shutdown(): CompletableFuture<Void>
} | 28 | Kotlin | 25 | 57 | 4c5568483411af5fa31ca995fafdd7aafe378134 | 346 | corda-runtime-os | Apache License 2.0 |
src/test/kotlin/framework/LifetimeEx.kt | Binkus | 378,663,715 | true | {"Kotlin": 113022, "C#": 9474, "PowerShell": 3060} | package me.fornever.avaloniarider.tests.framework
import com.jetbrains.rd.platform.util.startOnUiAsync
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rdclient.util.idea.waitAndPump
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import java.time.Duration
@OptIn(ExperimentalCoroutinesApi::class)
fun <T> runPumping(timeout: Duration = Duration.ofMinutes(1L), action: suspend CoroutineScope.() -> T): T {
Lifetime.using { lt ->
val deferred = lt.startOnUiAsync(action = action)
waitAndPump(timeout, { deferred.isCompleted })
return deferred.getCompleted()
}
}
| 0 | null | 0 | 0 | 4d025b9b763fbeec10263e1eb5b69a6d854e3fd2 | 659 | AvaloniaRider | MIT License |
tezos-michelson/src/test/kotlin/it/airgap/tezos/michelson/internal/utils/JsonTest.kt | airgap-it | 460,351,851 | false | null | package it.airgap.tezos.michelson.internal.utils
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class JsonTest {
@Test
fun `should check if JsonObject contains any of specified keys`() {
val jsonObject = buildJsonObject {
put("a", JsonPrimitive(1))
put("b", JsonPrimitive(2))
}
assertTrue(jsonObject.containsOneOfKeys("a", "1"))
assertTrue(jsonObject.containsOneOfKeys("1", "a"))
assertTrue(jsonObject.containsOneOfKeys("b", "1"))
assertTrue(jsonObject.containsOneOfKeys("1", "b"))
assertTrue(jsonObject.containsOneOfKeys("a", "b"))
assertFalse(jsonObject.containsOneOfKeys())
assertFalse(jsonObject.containsOneOfKeys("1"))
assertFalse(jsonObject.containsOneOfKeys("1", "2"))
}
} | 0 | Kotlin | 2 | 1 | c5af5ffdd4940670bd66842580d82c2b9d682d84 | 933 | tezos-kotlin-sdk | MIT License |
privacy-dashboard/src/main/java/com/github/privacydashboard/communication/repositories/UpdateDataAttributeStatusApiRepository.kt | L3-iGrant | 174,165,127 | false | null | package com.github.privacydashboard.communication.repositories
import com.github.privacydashboard.communication.PrivacyDashboardAPIServices
import com.github.privacydashboard.models.consent.ConsentStatusRequest
import com.github.privacydashboard.models.interfaces.consent.ResultResponse
class UpdateDataAttributeStatusApiRepository(private val apiService: PrivacyDashboardAPIServices) {
suspend fun updateAttributeStatus(
orgID: String?,
userId: String?,
consentId: String?,
purposeId: String?,
attributeId: String?,
body: ConsentStatusRequest?
): Result<ResultResponse?> {
return try {
val response = apiService.setAttributeStatus(
orgID = orgID,
userId = userId,
consentId = consentId,
purposeId = purposeId,
attributeId = attributeId,
body = body
)
if (response?.isSuccessful == true) {
val data = response.body()
if (data != null) {
Result.success(data)
} else {
Result.failure(Exception("Response body is null"))
}
} else {
Result.failure(Exception("Request failed with code: ${response?.code()}"))
}
} catch (e: Exception) {
Result.failure(e)
}
}
} | 21 | null | 0 | 1 | d13fdde31df5aebb36461545735ed0d992bf0f30 | 1,430 | privacy-dashboard-android | Apache License 2.0 |
parser/src/main/kotlin/gay/pizza/pork/parser/Tokenizer.kt | GayPizzaSpecifications | 680,636,847 | false | {"Kotlin": 253081} | package gay.pizza.pork.parser
class Tokenizer(val source: CharSource) {
private var startIndex: SourceIndex = SourceIndex.zero()
private var currentLineIndex = 1
private var currentLineColumn = 0
private fun readBlockComment(firstChar: Char): Token {
val comment = buildString {
append(firstChar)
var endOfComment = false
while (true) {
val char = nextChar()
if (char == CharSource.NullChar) {
throw UnterminatedTokenError("block comment", currentSourceIndex())
}
append(char)
if (endOfComment) {
if (char != '/') {
endOfComment = false
continue
}
break
}
if (char == '*') {
endOfComment = true
}
}
}
return produceToken(TokenType.BlockComment, comment)
}
private fun readLineComment(firstChar: Char): Token {
val comment = buildString {
append(firstChar)
while (true) {
val char = source.peek()
if (char == CharSource.NullChar || char == '\n') {
break
}
append(nextChar())
}
}
return produceToken(TokenType.LineComment, comment)
}
private fun readStringLiteral(firstChar: Char): Token {
val string = buildString {
append(firstChar)
while (true) {
val char = source.peek()
if (char == CharSource.NullChar) {
throw UnterminatedTokenError("string", currentSourceIndex())
}
append(nextChar())
if (char == '"') {
break
}
}
}
return produceToken(TokenType.StringLiteral, string)
}
fun next(): Token {
while (source.peek() != CharSource.NullChar) {
startIndex = currentSourceIndex()
val char = nextChar()
if (char == '/' && source.peek() == '*') {
return readBlockComment(char)
}
if (char == '/' && source.peek() == '/') {
return readLineComment(char)
}
for (item in TokenType.SingleChars) {
val itemChar = item.singleChar!!.char
if (itemChar != char) {
continue
}
var type = item
var text = itemChar.toString()
var promoted = true
while (promoted) {
promoted = false
for (promotion in type.promotions) {
if (source.peek() != promotion.nextChar) {
continue
}
val nextChar = nextChar()
type = promotion.type
text += nextChar
promoted = true
}
}
return produceToken(type, text)
}
var index = 0
for (item in TokenType.CharConsumers) {
if (!item.charConsumer!!.matcher.valid(char, index)) {
continue
}
val text = buildString {
append(char)
while (item.charConsumer.matcher.valid(source.peek(), ++index)) {
append(nextChar())
}
}
var token = produceToken(item, text)
val tokenUpgrader = item.tokenUpgrader
if (tokenUpgrader != null) {
token = tokenUpgrader.maybeUpgrade(token) ?: token
}
return token
}
if (char == '"') {
return readStringLiteral(char)
}
throw BadCharacterError(char, startIndex)
}
return Token.endOfFile(startIndex.copy(index = source.currentIndex))
}
fun tokenize(): TokenStream {
val tokens = mutableListOf<Token>()
while (true) {
val token = next()
tokens.add(token)
if (token.type == TokenType.EndOfFile) {
break
}
}
return TokenStream(tokens)
}
private fun produceToken(type: TokenType, text: String) =
Token(type, startIndex, text)
private fun nextChar(): Char {
val char = source.next()
if (char == '\n') {
currentLineIndex++
currentLineColumn = 0
}
currentLineColumn++
return char
}
private fun currentSourceIndex(): SourceIndex =
SourceIndex(source.currentIndex, currentLineIndex, currentLineColumn)
}
| 1 | Kotlin | 1 | 0 | fdac4fb96ab3ed6b27368e10ecfb1361c047f9e5 | 4,056 | pork | MIT License |
klog/src/main/kotlin/com/coditory/klog/text/plain/PlainTextStringFormatterBuilder.kt | coditory | 736,731,539 | false | {"Kotlin": 187827, "Shell": 1311} | package com.coditory.klog.text.plain
import kotlin.math.max
class PlainTextStringFormatterBuilder internal constructor() {
private var cacheSize: Int = 0
private var maxLength: Int = Integer.MAX_VALUE
private var padding: Padding? = null
private var prefix: StyledText = StyledText.empty()
private var postfix: StyledText = StyledText.empty()
private var style = TextStyle.empty()
private var compactSectionSeparator: Char? = null
private var precomputeValues: List<String> = emptyList()
private var ansi: Boolean = ConsoleColors.ANSI_CONSOLE
private var mapper: ((String) -> String?)? = null
// Template: <prefix><padding><style><value><style><padding><postfix>
fun cacheSize(size: Int): PlainTextStringFormatterBuilder {
this.cacheSize = size
return this
}
fun maxLength(maxLength: Int): PlainTextStringFormatterBuilder {
this.maxLength = maxLength
return this
}
fun padLeft(pad: Char = ' '): PlainTextStringFormatterBuilder {
this.padding = Padding.left(pad)
return this
}
fun pasRight(pad: Char = ' '): PlainTextStringFormatterBuilder {
this.padding = Padding.right(pad)
return this
}
fun ansi(enable: Boolean = true): PlainTextStringFormatterBuilder {
this.ansi = enable
return this
}
fun prefix(
prefix: String,
style: TextStyle = TextStyle.empty(),
): PlainTextStringFormatterBuilder {
this.prefix = StyledText(prefix, style)
return this
}
fun postfix(
postfix: String,
style: TextStyle = TextStyle.empty(),
): PlainTextStringFormatterBuilder {
this.postfix = StyledText(postfix, style)
return this
}
fun style(style: TextStyle): PlainTextStringFormatterBuilder {
this.style = style
return this
}
fun mapped(mapper: (String) -> String?): PlainTextStringFormatterBuilder {
this.mapper = mapper
return this
}
fun precomputeValues(values: List<String>): PlainTextStringFormatterBuilder {
precomputeValues = values
return this
}
fun precomputeClassNamesFromPackage(
packageName: String,
recursive: Boolean = true,
max: Int = Int.MAX_VALUE,
): PlainTextStringFormatterBuilder {
precomputeValues = ClassNameLister.getClassNamesFromPackage(packageName, recursive, max)
return this
}
fun compactSections(separator: Char = '.'): PlainTextStringFormatterBuilder {
compactSectionSeparator = separator
return this
}
fun build(): PlainTextStringFormatter {
val separator = compactSectionSeparator
val style = if (ansi) this.style else TextStyle.empty()
val prefix = if (ansi) prefix else prefix.resetStyle()
val postfix = if (ansi) postfix else postfix.resetStyle()
val formatter =
if (separator != null) {
CompactedPlainTextStringFormatter(
separator = separator,
maxLength = maxLength,
padding = padding,
prefix = prefix,
postfix = postfix,
style = style,
)
} else {
ConfigurablePlainTextStringFormatter(
maxLength = maxLength,
padding = padding,
prefix = prefix,
postfix = postfix,
style = style,
)
}
val mapper = mapper
val mapped =
if (mapper != null) {
MappedTextFormatter(mapper, formatter)
} else {
formatter
}
return if (precomputeValues.isNotEmpty()) {
PrecomputedTextFormatter.precompute(mapped, precomputeValues)
} else {
mapped
}
}
}
internal class ConfigurablePlainTextStringFormatter(
private val maxLength: Int,
private val padding: Padding?,
private val prefix: StyledText,
private val postfix: StyledText,
private val style: TextStyle,
) : PlainTextStringFormatter {
private val pad: String? =
padding?.let {
("" + it.pad).repeat(maxLength)
}
override fun format(
text: String,
appendable: Appendable,
) {
if (text.isEmpty()) return
prefix.format(appendable)
if (padding?.left() == true && text.length < maxLength) {
appendable.append(pad, 0, text.length - maxLength)
}
appendable.append(style.prefix)
if (text.length < maxLength) {
appendable.append(text)
} else {
appendable.append(text, 0, maxLength)
}
appendable.append(style.postfix)
if (padding?.right() == true && text.length < maxLength) {
appendable.append(pad, 0, text.length - maxLength)
}
postfix.format(appendable)
}
}
internal class CompactedPlainTextStringFormatter(
private val separator: Char,
private val maxLength: Int,
private val padding: Padding?,
private val prefix: StyledText,
private val postfix: StyledText,
private val style: TextStyle,
) : PlainTextStringFormatter {
private val pad: String? =
padding?.let {
("" + it.pad).repeat(maxLength)
}
override fun format(
text: String,
appendable: Appendable,
) {
if (text.isEmpty()) return
val chunks = text.split(separator).filter { it.isNotEmpty() }
val last = chunks.last()
prefix.format(appendable)
if (last.length + 1 > maxLength) {
appendable.append(style.prefix)
appendable.append(last.substring(0, maxLength))
appendable.append(style.postfix)
postfix.format(appendable)
return
}
val length = (chunks.size * 2) + last.length
if (padding?.left() == true && length < maxLength) {
appendable.append(pad, 0, length - maxLength)
}
val prefixMaxLength = maxLength - last.length
val start = max(0, chunks.size - (prefixMaxLength / 2))
appendable.append(style.prefix)
for (i in start..<chunks.size) {
appendable.append(chunks[i][0])
appendable.append(separator)
}
appendable.append(last)
appendable.append(style.postfix)
if (padding?.right() == true && length < maxLength) {
appendable.append(pad, 0, length - maxLength)
}
postfix.format(appendable)
}
}
| 3 | Kotlin | 0 | 0 | dc34894d4a929f486280ec689be81a71e904cae2 | 6,675 | klog | Apache License 2.0 |
src/main/kotlin/de/smartsquare/starter/mqtt/MqttProperties.kt | SmartsquareGmbH | 344,485,602 | false | {"Kotlin": 80904} | package de.smartsquare.starter.mqtt
import com.hivemq.client.mqtt.mqtt5.message.connect.Mqtt5Connect
import jakarta.validation.constraints.Max
import jakarta.validation.constraints.Min
import jakarta.validation.constraints.NotEmpty
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.validation.annotation.Validated
/**
* Properties for connection to the mqtt broker.
*/
@Validated
@ConfigurationProperties(prefix = "mqtt")
data class MqttProperties(
/**
* The host the mqtt broker is available under.
*/
@get:NotEmpty
val host: String = "",
/**
* The port the mqtt broker is available under.
*/
@get:Min(1)
@get:Max(65535)
val port: Int = 0,
/**
* The client id this component should connect with.
*/
val clientId: String? = null,
/**
* The username this component should connect with.
*/
val username: String? = null,
/**
* The password this component should connect with.
*/
val password: String? = null,
/**
* If ssl should be used for the connection to the mqtt broker.
*/
val ssl: Boolean = false,
/**
* If the client should connect with a clean session.
*/
val clean: Boolean = true,
/**
* The optional group subscriptions should be prefixed with.
*/
val group: String? = null,
/**
* The mqtt protocol version to use.
*/
@get:MqttVersion
val version: Int = 3,
/**
* The timeout for connection to the broker in milliseconds.
*/
val connectTimeout: Long = 10_000,
/**
* The shutdown configuration for the mqtt processor.
*/
val shutdown: MqttShutdown = MqttShutdown.GRACEFUL,
/**
* The session expiry interval in seconds. Has to be in [0, 4294967295] (0 by default).
* Setting the value to 0 means the session will expire immediately after disconnect.
* Setting it to 4_294_967_295 means the session will never expire.
* This setting is only going into effect for MQTT 5.
*/
@get:Min(0)
@get:Max(Mqtt5Connect.NO_SESSION_EXPIRY)
val sessionExpiry: Long = Mqtt5Connect.DEFAULT_SESSION_EXPIRY_INTERVAL,
) {
/**
* Configuration for shutting a mqtt processor.
*/
enum class MqttShutdown {
/**
* The mqtt processor should support graceful shutdown, allowing active tasks time to complete.
*/
GRACEFUL,
/**
* The mqtt processor should shut down immediately.
*/
IMMEDIATE,
}
}
| 1 | Kotlin | 5 | 15 | ade03a092f150d6aa9954543532ea918030c1ed5 | 2,588 | mqtt-starter | MIT License |
client/core/src/commonMain/kotlin/org/timemates/rrpc/client/RRpcServiceClient.kt | timemates | 713,625,067 | false | {"Kotlin": 261080} | @file:OptIn(InternalRRpcAPI::class)
package org.timemates.rrpc.client
import org.timemates.rrpc.annotations.InternalRRpcAPI
import org.timemates.rrpc.client.config.RRpcClientConfig
import org.timemates.rrpc.client.options.RPCsOptions
/**
* The abstraction for the clients that are generated by `RRpc`.
*/
public abstract class RRpcServiceClient(
config: RRpcClientConfig,
) {
public constructor(
creator: RRpcClientConfig.Builder.() -> Unit,
) : this(RRpcClientConfig.create(creator))
/**
* Responsible for the logic around RSocket for interceptors and request/response data management.
* No direct access to RSocket is used in the generated code.
*/
protected val handler: ClientRequestHandler = ClientRequestHandler(config)
/**
* Container of the options related to the RPC methods by name.
* Used and generated internally by the code-generation.
*/
protected abstract val rpcsOptions: RPCsOptions
}
| 8 | Kotlin | 0 | 8 | e349daf1ae419c3cf544dc9b27a93f2274ad90e3 | 975 | rrpc-kotlin | MIT License |
archimedes-usecase/src/test/kotlin/io/archimedesfw/usecase/EntityRepository.kt | archimedes-projects | 362,401,748 | false | {"Kotlin": 278527, "PLpgSQL": 3068} | package io.archimedesfw.usecase
internal interface EntityRepository {
fun save(entity: Entity)
fun findByName(name: String): List<Entity>
}
| 1 | Kotlin | 5 | 26 | 53088b3788e3dbe878a7b330214c3b3142e47650 | 152 | archimedes-jvm | Apache License 2.0 |
app/src/main/java/com/berkaykurtoglu/securevisage/presentation/HomeOwners/FloatingActionButton.kt | BerkayyKurtoglu | 780,353,148 | false | {"Kotlin": 85613, "Java": 8001} | package com.berkaykurtoglu.securevisage.presentation.HomeOwners
import android.net.Uri
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.Upload
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.LargeFloatingActionButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun CustomFloatingActionButton(
modifier: Modifier = Modifier,
photoPickerLauncher : ManagedActivityResultLauncher<PickVisualMediaRequest, Uri?>
) {
FloatingActionButton(
modifier = modifier,
onClick = {
/*TODO : Take persons picture*/
photoPickerLauncher.launch(
PickVisualMediaRequest(
ActivityResultContracts.PickVisualMedia.ImageOnly
)
)
},
containerColor = MaterialTheme.colorScheme.surface
) {
Icon(
imageVector = Icons.Outlined.Add,
contentDescription = "Upload Image"
)
}
}
| 0 | Kotlin | 0 | 0 | 5112394092f542ada46f815182526c63d70a15b6 | 1,514 | Aws-Security-App | Apache License 2.0 |
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/usecases/GetToolbarTitleChangeDialogUseCase.kt | Waboodoo | 34,525,124 | false | null | package ch.rmy.android.http_shortcuts.usecases
import androidx.annotation.CheckResult
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.extensions.createDialogState
import javax.inject.Inject
class GetToolbarTitleChangeDialogUseCase
@Inject
constructor() {
@CheckResult
operator fun invoke(onToolbarTitleChangeSubmitted: (String) -> Unit, oldTitle: String) =
createDialogState {
title(R.string.title_set_title)
.textInput(
prefill = oldTitle,
allowEmpty = true,
maxLength = TITLE_MAX_LENGTH,
callback = onToolbarTitleChangeSubmitted,
)
.build()
}
companion object {
private const val TITLE_MAX_LENGTH = 50
}
}
| 29 | Kotlin | 94 | 671 | b364dfef22569ad326ee92492079790eaef4399d | 820 | HTTP-Shortcuts | MIT License |
app/src/main/java/com/example/TechTusQuiz/ui/GameOverScreen.kt | PatrickLyonsISD | 715,627,637 | false | {"Kotlin": 87898} | package com.example.TechTusQuiz.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.absolutePadding
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
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.requiredHeight
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.em
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.example.unscramble.R
import com.example.unscramble.frame27.inter
import com.google.relay.compose.CrossAxisAlignment
import com.google.relay.compose.MainAxisAlignment
import com.google.relay.compose.RelayContainer
import com.google.relay.compose.RelayContainerArrangement
import com.google.relay.compose.RelayContainerScope
import com.google.relay.compose.RelayImage
import com.google.relay.compose.RelayText
import com.google.relay.compose.RelayVector
import com.google.relay.compose.relayDropShadow
@Composable
fun GameOverScreen(navController: NavHostController, gameViewModel: QuizViewModel, finalScore: Int) {
Column(
modifier = Modifier
.fillMaxSize()
.background(Color(0xFF00594C)),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Image(
painter = painterResource(id = R.drawable.q3_question_ecovitaelogo3),
contentDescription = "Logo",
modifier = Modifier.size(150.dp)
)
Spacer(modifier = Modifier.height(32.dp))
Box(
modifier = Modifier
.background(Color(0xFFa39461), RoundedCornerShape(8.dp))
.padding(16.dp)
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Thanks for Playing!",
style = MaterialTheme.typography.headlineMedium,
color = Color.Black
)
Text(
text = "Your Final Score: $finalScore",
style = MaterialTheme.typography.bodyLarge,
color = Color.Black
)
}
}
Spacer(modifier = Modifier.height(24.dp))
Button(
onClick = {
gameViewModel.resetGame()
navController.navigate("gameScreen") {
popUpTo("gameScreen") { inclusive = true }
}
},
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFF0BEE6))
) {
Text(
text = "Play Again",
style = MaterialTheme.typography.headlineMedium,
color = Color.Black
)
}
}
}
| 0 | Kotlin | 1 | 0 | 722390de3fcc35bc6e06cbff32c3a411ee036d50 | 4,260 | InnovativeTechGame | Apache License 2.0 |
transformers/picasso-gpu/src/main/java/jp/wasabeef/transformers/picasso/gpu/GPUFilterTransformation.kt | wasabeef | 217,567,762 | false | null | package jp.wasabeef.transformers.picasso.gpu
import android.content.Context
import android.graphics.Bitmap
import com.squareup.picasso.Transformation
import jp.co.cyberagent.android.gpuimage.GPUImage
import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilter
import jp.wasabeef.transformers.picasso.gpu.BuildConfig.Version
/**
* Copyright (C) 2020 Wasabeef
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
abstract class GPUFilterTransformation(
private val context: Context,
private val filter: GPUImageFilter
) : Transformation {
val version: String = Version
protected val id: String
get() = "${this::class.java.name}-$version"
override fun transform(
source: Bitmap
): Bitmap {
val gpuImage = GPUImage(context)
gpuImage.setImage(source)
gpuImage.setFilter(filter)
val output = gpuImage.bitmapWithFilterApplied
source.recycle()
return output
}
} | 2 | Kotlin | 15 | 273 | 1759088865fd62b8ee07107ccdbae8f8fe773c24 | 1,427 | transformers | Apache License 2.0 |
app/src/main/java/com/gabor/cleanarchitecture/data/remote/ApiService.kt | gyorgygabor | 440,453,398 | false | {"Kotlin": 109509} | /*
* Copyright 2022 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gabor.cleanarchitecture.data.remote
import com.gabor.cleanarchitecture.domain.movies.entities.GenresDTO
import com.gabor.cleanarchitecture.domain.movies.entities.MovieDTO
import com.gabor.cleanarchitecture.domain.movies.entities.MoviesDTO
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface ApiService {
@GET("/3/discover/movie")
suspend fun getMovies(@Query("language") language: String, @Query("page") page: Int): MoviesDTO
@GET("/3/genre/movie/list")
suspend fun getGenres(@Query("language") language: String): GenresDTO
@GET("/3/movie/{movieId}")
suspend fun getMovieDetails(@Path("movieId") movieId: Int, @Query("language") language: String, @Query("append_to_response") append_to_response: String = "videos"): MovieDTO
}
| 0 | Kotlin | 0 | 0 | 9f5828f70c6cfa21741b452f803b205ea1c4c6d3 | 1,423 | clean_architecture | Apache License 2.0 |
plugin/src/main/kotlin/xyz/luccboy/noobcloud/plugin/shared/config/Config.kt | NoobCloudSystems | 518,232,292 | false | {"Kotlin": 155606, "Shell": 69, "Batchfile": 45} | package xyz.luccboy.noobcloud.plugin.shared.config
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import xyz.luccboy.noobcloud.api.group.GroupType
import java.nio.file.Files
import kotlin.io.path.Path
class Config(private val groupType: GroupType) {
lateinit var messages: Messages
private set
private val mapper: ObjectMapper = YAMLMapper().registerKotlinModule()
fun loadConfig() {
try {
val messagePath: String = (if (groupType == GroupType.PROXY) "plugins" else "extensions") + "/NoobCloud/messages.yml"
messages = Files.newBufferedReader(Path(messagePath)).use { mapper.readValue(it, Messages::class.java) }
} catch (exception: Exception) {
exception.printStackTrace()
}
}
} | 1 | Kotlin | 2 | 3 | 0ecea76f391fa60bec8d7e924af45922543093c3 | 893 | NoobCloud | Apache License 2.0 |
data/src/test/java/com/kuluruvineeth/data/categories/model/CategoryDataModelTest.kt | kuluruvineeth | 595,400,329 | false | null | package com.kuluruvineeth.data.categories.model
import android.graphics.Color
import com.kuluruvineeth.data.core.UNSPECIFIED_ID
import com.kuluruvineeth.data.features.categories.model.CategoryDataModel
import com.kuluruvineeth.data.features.categories.model.toDataModel
import com.kuluruvineeth.data.features.categories.model.toDomain
import com.kuluruvineeth.domain.features.categories.models.Category
import com.kuluruvineeth.domain.features.categories.models.CategoryType
import com.kuluruvineeth.domain.features.categories.models.CreateCategoryPayload
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class CategoryDataModelTest {
@Test
fun `test CategoryDataModel_toDomain() function returns Category model with correct fields`() {
val categoryDataModel = CategoryDataModel(
id = 1,
title = "Title",
color = Color.WHITE,
type = "GLOBAL",
isMutable = false
)
val domainModel = categoryDataModel.toDomain()
assertEquals(categoryDataModel.id, domainModel.id.toInt())
assertEquals(categoryDataModel.title, domainModel.title)
assertEquals(categoryDataModel.color, domainModel.color)
assertEquals(categoryDataModel.type, domainModel.categoryType.name)
assertEquals(categoryDataModel.isMutable, domainModel.isMutable)
}
@Test
fun `test Category_toDataModel() function returns CategoryDataModel model with correct fields`() {
val domainModel = Category(
id = "1",
title = "Title",
color = Color.WHITE,
categoryType = CategoryType.GLOBAL,
isMutable = false
)
val dataModel = domainModel.toDataModel()
assertEquals(domainModel.id.toInt(), dataModel.id)
assertEquals(domainModel.title, dataModel.title)
assertEquals(domainModel.color, dataModel.color)
assertEquals(domainModel.categoryType.name, dataModel.type)
assertEquals(domainModel.isMutable, dataModel.isMutable)
}
@Test
fun `test CreateCategory_toDataModel() function returns CategoryDataModel model with correct fields`() {
val payload = CreateCategoryPayload(
title = "Title",
color = Color.WHITE
)
val dataModel = payload.toDataModel()
assertEquals(dataModel.id, UNSPECIFIED_ID)
assertEquals(dataModel.title, payload.title)
assertEquals(dataModel.color, payload.color)
assertEquals(dataModel.type, CategoryType.PERSONAL.name)
assertTrue(dataModel.isMutable)
}
} | 0 | Kotlin | 0 | 0 | a8603d847f831bf6391fa07009cff633f676805c | 2,633 | pointsofinterests | Apache License 2.0 |
domain/src/main/java/com/mperezc/domain/usecases/ProductUseCase.kt | MOccam | 589,286,826 | false | null | package com.mperezc.domain.usecases
import com.mperezc.domain.model.ProductModel
import kotlinx.coroutines.flow.Flow
interface ProductUseCase {
companion object {
const val DEFAULT_CURRENCY = "EUR"
}
suspend fun getProducts(): Flow<Result<List<ProductModel>>>
suspend fun getProductByName(sku: String): Flow<Result<List<ProductModel>>>
} | 0 | Kotlin | 0 | 0 | be729c54c7e6116cc8045a2da6b3355d6f23670f | 366 | GNBTrades | Apache License 2.0 |
fontawesome/src/de/msrd0/fontawesome/icons/FA_FORT_AWESOME.kt | msrd0 | 363,665,023 | false | null | /* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.BRANDS
object FA_FORT_AWESOME: Icon {
override val name get() = "Fort Awesome"
override val unicode get() = "f286"
override val styles get() = setOf(BRANDS)
override fun svg(style: Style) = when(style) {
BRANDS -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M489.2 287.9h-27.4c-2.6 0-4.6 2-4.6 4.6v32h-36.6V146.2c0-2.6-2-4.6-4.6-4.6h-27.4c-2.6 0-4.6 2-4.6 4.6v32h-36.6v-32c0-2.6-2-4.6-4.6-4.6h-27.4c-2.6 0-4.6 2-4.6 4.6v32h-36.6v-32c0-6-8-4.6-11.7-4.6v-38c8.3-2 17.1-3.4 25.7-3.4 10.9 0 20.9 4.3 31.4 4.3 4.6 0 27.7-1.1 27.7-8v-60c0-2.6-2-4.6-4.6-4.6-5.1 0-15.1 4.3-24 4.3-9.7 0-20.9-4.3-32.6-4.3-8 0-16 1.1-23.7 2.9v-4.9c5.4-2.6 9.1-8.3 9.1-14.3 0-20.7-31.4-20.8-31.4 0 0 6 3.7 11.7 9.1 14.3v111.7c-3.7 0-11.7-1.4-11.7 4.6v32h-36.6v-32c0-2.6-2-4.6-4.6-4.6h-27.4c-2.6 0-4.6 2-4.6 4.6v32H128v-32c0-2.6-2-4.6-4.6-4.6H96c-2.6 0-4.6 2-4.6 4.6v178.3H54.8v-32c0-2.6-2-4.6-4.6-4.6H22.8c-2.6 0-4.6 2-4.6 4.6V512h182.9v-96c0-72.6 109.7-72.6 109.7 0v96h182.9V292.5c.1-2.6-1.9-4.6-4.5-4.6zm-288.1-4.5c0 2.6-2 4.6-4.6 4.6h-27.4c-2.6 0-4.6-2-4.6-4.6v-64c0-2.6 2-4.6 4.6-4.6h27.4c2.6 0 4.6 2 4.6 4.6v64zm146.4 0c0 2.6-2 4.6-4.6 4.6h-27.4c-2.6 0-4.6-2-4.6-4.6v-64c0-2.6 2-4.6 4.6-4.6h27.4c2.6 0 4.6 2 4.6 4.6v64z"/></svg>"""
else -> null
}
}
| 0 | Kotlin | 0 | 0 | e757d073562077a753280bf412eebfc4a9121b33 | 2,149 | fontawesome-kt | Apache License 2.0 |
usecase/src/main/java/org/plavelo/prs/usecase/RssUseCase.kt | plavelo | 410,888,609 | false | {"Kotlin": 31073} | package org.plavelo.prs.usecase
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.single
import org.plavelo.prs.domain.Article
import org.plavelo.prs.domain.ArticleId
import org.plavelo.prs.domain.Channel
import org.plavelo.prs.domain.ChannelId
import org.plavelo.prs.domain.Feed
import org.plavelo.prs.usecase.repository.RssRepository
class RssUseCase @Inject constructor(
private val rssRepository: RssRepository,
) {
fun feeds(): Flow<List<Feed>> =
rssRepository.feeds()
fun channels(): Flow<List<Channel>> =
rssRepository.channels()
fun article(articleId: ArticleId): Flow<Article> =
rssRepository.article(articleId)
fun articles(channelId: ChannelId): Flow<List<Article>> =
rssRepository.articles(channelId)
suspend fun add(feed: Feed) {
rssRepository.fetch(feed)
// If the fetch succeeds, add the feed
rssRepository.add(feed)
}
suspend fun reload() {
val feeds = rssRepository.feeds().first()
for (feed in feeds) {
rssRepository.fetch(feed)
}
}
}
| 0 | Kotlin | 0 | 0 | 113fa56d5b0d415e9f345e89f1a0a3cd4d139cfc | 1,169 | prs | MIT License |
Client/app/src/main/java/com/t3ddyss/clother/presentation/profile/ProfileEditorFragment.kt | t3ddyss | 337,083,750 | false | null | package com.t3ddyss.clother.presentation.profile
import android.app.DatePickerDialog
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.DatePicker
import androidx.core.view.isVisible
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.t3ddyss.clother.R
import com.t3ddyss.clother.databinding.FragmentProfileEditorBinding
import com.t3ddyss.clother.presentation.chat.ImageSelectorDialog
import com.t3ddyss.clother.util.text
import com.t3ddyss.clother.util.toEditable
import com.t3ddyss.core.domain.models.Error
import com.t3ddyss.core.domain.models.Success
import com.t3ddyss.core.presentation.BaseFragment
import com.t3ddyss.core.util.extensions.getThemeColor
import com.t3ddyss.core.util.extensions.showSnackbarWithText
import com.t3ddyss.core.util.utils.ToolbarUtils
import dagger.hilt.android.AndroidEntryPoint
import java.util.*
@AndroidEntryPoint
class ProfileEditorFragment :
BaseFragment<FragmentProfileEditorBinding>(FragmentProfileEditorBinding::inflate) {
private val viewModel by viewModels<ProfileEditorViewModel>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
ToolbarUtils.setupToolbar(
activity,
binding.toolbar,
getString(R.string.profile_edit),
ToolbarUtils.NavIcon.CLOSE
)
setHasOptionsMenu(true)
binding.avatar.setOnClickListener {
findNavController().navigate(
ProfileEditorFragmentDirections.actionProfileEditorFragmentToAvatarMenuDialog(
isRemoveVisible = viewModel.avatar.value != null
)
)
}
subscribeUi()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.toolbar_apply_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.apply -> {
viewModel.onApplyClick(
nameInput = binding.editTextName.text(),
statusInput = binding.editTextStatus.text()
)
true
}
else -> {
super.onOptionsItemSelected(item)
}
}
}
override fun onStop() {
super.onStop()
viewModel.updateName(binding.editTextName.text())
viewModel.updateStatus(binding.editTextStatus.text())
}
private fun subscribeUi() {
viewModel.avatar.observe(viewLifecycleOwner) { avatar ->
AvatarLoader.loadAvatar(binding.avatar, avatar, R.drawable.ic_avatar_add)
}
viewModel.name.observe(viewLifecycleOwner) {
binding.editTextName.text = it.toEditable()
}
viewModel.status.observe(viewLifecycleOwner) {
binding.editTextStatus.text = it.orEmpty().toEditable()
}
viewModel.isLoading.observe(viewLifecycleOwner) {
binding.layoutLoading.isVisible = it
}
viewModel.applyResult.observe(viewLifecycleOwner) {
when (it) {
is Success -> {
findNavController().popBackStack()
}
is Error -> {
binding.layoutLoading.isVisible = false
when (it.content) {
is ValidationError -> {
binding.textInputName.error = getString(R.string.auth_name_requirements)
binding.textInputName.isErrorEnabled = true
}
else -> {
binding.textInputName.isErrorEnabled = false
showSnackbarWithText(it)
}
}
}
else -> Unit
}
}
setFragmentResultListener(ImageSelectorDialog.SELECTED_IMAGE_KEY) { _, bundle ->
bundle.getParcelable<Uri>(ImageSelectorDialog.SELECTED_IMAGE_URI)?.let { uri ->
viewModel.updateAvatar(uri)
}
}
setFragmentResultListener(AvatarMenuDialog.SELECTED_ACTION_KEY) { _, bundle ->
(bundle.getSerializable(AvatarMenuDialog.SELECTED_ACTION) as? AvatarMenuDialog.Action)?.let { action ->
if (action == AvatarMenuDialog.Action.REMOVE) {
viewModel.removeAvatar()
}
}
}
}
private fun showDatePickerDialog() {
val calendar = Calendar.getInstance()
val currentYear = calendar.get(Calendar.YEAR)
val currentMonth = calendar.get(Calendar.MONTH)
val currentDay = calendar.get(Calendar.DAY_OF_MONTH)
val listener = DatePickerDialog.OnDateSetListener { _: DatePicker, year: Int, month: Int, day: Int -> }
DatePickerDialog(
requireContext(),
listener,
currentYear,
currentMonth,
currentDay
).apply {
show()
datePicker.maxDate = System.currentTimeMillis()
val buttonTextColor = requireContext().getThemeColor(R.attr.colorOnPrimary)
getButton(DatePickerDialog.BUTTON_NEGATIVE).setTextColor(buttonTextColor)
getButton(DatePickerDialog.BUTTON_POSITIVE).setTextColor(buttonTextColor)
}
}
} | 0 | Kotlin | 1 | 23 | a2439707002e0086de09bf37c3d10e7c8cf9f060 | 5,578 | Clother | MIT License |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/filled/SortDescendingShapes.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.tabler.tabler.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.FilledGroup
public val FilledGroup.SortAscendingShapes: ImageVector
get() {
if (_sortAscendingShapes != null) {
return _sortAscendingShapes!!
}
_sortAscendingShapes = Builder(name = "SortAscendingShapes", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(7.0f, 5.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f)
verticalLineToRelative(9.584f)
lineToRelative(1.293f, -1.291f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.32f, -0.083f)
lineToRelative(0.094f, 0.083f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, 1.414f)
lineToRelative(-3.0f, 3.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -0.112f, 0.097f)
lineToRelative(-0.11f, 0.071f)
lineToRelative(-0.114f, 0.054f)
lineToRelative(-0.105f, 0.035f)
lineToRelative(-0.149f, 0.03f)
lineToRelative(-0.117f, 0.006f)
lineToRelative(-0.075f, -0.003f)
lineToRelative(-0.126f, -0.017f)
lineToRelative(-0.111f, -0.03f)
lineToRelative(-0.111f, -0.044f)
lineToRelative(-0.098f, -0.052f)
lineToRelative(-0.096f, -0.067f)
lineToRelative(-0.09f, -0.08f)
lineToRelative(-3.0f, -3.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.414f, -1.414f)
lineToRelative(1.293f, 1.293f)
verticalLineToRelative(-9.586f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f)
moveToRelative(12.0f, -2.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f)
verticalLineToRelative(4.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, 2.0f)
horizontalLineToRelative(-4.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f)
verticalLineToRelative(-4.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f)
close()
moveTo(17.864f, 13.496f)
lineToRelative(3.5f, 6.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -0.864f, 1.504f)
horizontalLineToRelative(-7.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -0.864f, -1.504f)
lineToRelative(3.5f, -6.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.728f, 0.0f)
}
}
.build()
return _sortAscendingShapes!!
}
private var _sortAscendingShapes: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 3,646 | compose-icon-collections | MIT License |
app/src/main/java/com/vaibhavmojidra/androidkotlindemo2workmanagerperiodicworkrequest/MyPeriodicWorker.kt | VaibhavMojidra | 652,754,377 | false | null | package com.vaibhavmojidra.androidkotlindemo2workmanagerperiodicworkrequest
import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import java.text.SimpleDateFormat
import java.util.Calendar
class MyPeriodicWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
override fun doWork(): Result {
Thread.sleep(5000)
val currentTime = Calendar.getInstance().time
val timeFormat = SimpleDateFormat("HH:mm:ss")
val formattedTime = timeFormat.format(currentTime)
Log.i("MyTag","Task Completed : $formattedTime")
return Result.success()
}
} | 0 | Kotlin | 0 | 0 | 224ac4e89435dc291d7d27a60f796151afe1ef2b | 696 | Android-Kotlin---Demo-2-Work-Manager-Periodic-Work-Request | MIT License |
src/main/kotlin/io/openfuture/chain/domain/transaction/PendingTransactionRequest.kt | cdeyoung | 138,206,181 | true | {"Kotlin": 38267} | package io.openfuture.chain.domain.transaction
open class PendingTransactionRequest(
val amount: Int,
val timestamp: Long,
val recipientKey: String,
val senderKey: String,
val signature: String
) | 0 | Kotlin | 0 | 0 | 205807f47c43f6e7b608f06d6943b3489b01d4e6 | 216 | open-chain | MIT License |
core/src/main/java/com/lionparcel/commonandroid/form/LPCountInput.kt | Lionparcel | 258,373,753 | false | {"Kotlin": 565360} | package com.lionparcel.commonandroid.form
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.ImageButton
import android.widget.LinearLayout
import androidx.core.widget.addTextChangedListener
import com.lionparcel.commonandroid.R
class LPCountInput : LinearLayout {
private var imgBtnCountInputMin: ImageButton
private var txtCountInputValue: EditText
private var imgBtnCountInputPlus: ImageButton
private var minQtyValue = 0
private var maxQtyValue = 99
private var qtyValue = minQtyValue
private var withDivider = true
private var countEditable = true
private var enabled = true
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
val layoutInflater = LayoutInflater.from(context)
layoutInflater.inflate(R.layout.lp_count_input_view, this, true)
context.theme.obtainStyledAttributes(
attrs,
R.styleable.LPCountInput,
0,
0
).apply {
try {
minQtyValue = getInt(R.styleable.LPCountInput_minQtyValue, minQtyValue)
maxQtyValue = getInt(R.styleable.LPCountInput_maxQtyValue, maxQtyValue)
withDivider = getBoolean(R.styleable.LPCountInput_withDivider, withDivider)
countEditable = getBoolean(R.styleable.LPCountInput_countEditable, countEditable)
} finally {
recycle()
}
}
imgBtnCountInputMin = findViewById(R.id.imgBtnCountInputMin)
txtCountInputValue = findViewById(R.id.txtCountInputValue)
imgBtnCountInputPlus = findViewById(R.id.imgBtnCountInputPlus)
initImageButton()
initTxtCountInput()
setEnablePlusMinusButton(this.qtyValue)
setViewEnabledState()
}
override fun setEnabled(enabled: Boolean) {
this.enabled = enabled
setViewEnabledColor()
setViewEnabledState()
}
override fun isEnabled() = this.enabled
private fun initTxtCountInput() {
if (!this.withDivider) txtCountInputValue.background = null
txtCountInputValue.setText(this.qtyValue.toString())
txtCountInputValue.addTextChangedListener {
val newQty = it.toString().toIntOrNull()
newQty?.let {
if (newQty > this.maxQtyValue) {
txtCountInputValue.setText(this.maxQtyValue.toString())
} else if (newQty < this.minQtyValue) {
txtCountInputValue.setText(this.minQtyValue.toString())
}
this.qtyValue = newQty
setEnablePlusMinusButton(newQty)
} ?: run {
txtCountInputValue.setText(this.minQtyValue.toString())
}
}
}
private fun initImageButton() {
imgBtnCountInputMin.setOnClickListener {
val newQty = (txtCountInputValue.text.toString().toIntOrNull() ?: 0) - 1
txtCountInputValue.setText(newQty.toString())
}
imgBtnCountInputPlus.setOnClickListener {
val newQty = (txtCountInputValue.text.toString().toIntOrNull() ?: 0) + 1
txtCountInputValue.setText(newQty.toString())
}
}
private fun setEnablePlusMinusButton(qty: Int) {
imgBtnCountInputPlus.isEnabled = qty < this.maxQtyValue
imgBtnCountInputMin.isEnabled = qty > this.minQtyValue
}
private fun setViewEnabledState() {
imgBtnCountInputPlus.isClickable = this.enabled
imgBtnCountInputMin.isClickable = this.enabled
txtCountInputValue.isEnabled = this.enabled && this.countEditable
}
private fun setViewEnabledColor() {
txtCountInputValue.alpha = if (this.enabled) 1F else 0.5F
imgBtnCountInputMin.alpha = if (this.enabled) 1F else 0.5F
imgBtnCountInputPlus.alpha = if (this.enabled) 1F else 0.5F
}
fun setCurrentQty(qty: Int) {
this.qtyValue = qty
initTxtCountInput()
}
fun setMinQtyValue(minValue: Int) {
this.minQtyValue = minValue
initTxtCountInput()
}
fun setMaxQtyValue(maxValue: Int) {
this.maxQtyValue = maxValue
initTxtCountInput()
}
fun setEditCountDivider(divider: Boolean) {
this.withDivider = divider
initTxtCountInput()
}
fun setEditCountEditable(editable: Boolean) {
this.countEditable = editable
setViewEnabledState()
}
fun getCountValue() = this.qtyValue
fun getEditText() = txtCountInputValue
} | 0 | Kotlin | 0 | 0 | ac1bc20950fa9fcdb2a8438ba1adf1baf3f8c286 | 4,833 | common-android | MIT License |
src/test/kotlin/no/nav/omsorgspenger/testutils/mocks/DokarkivproxyMock.kt | navikt | 314,496,410 | false | null | package no.nav.omsorgspenger.testutils.mocks
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.MappingBuilder
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.client.WireMock.aResponse
import com.github.tomakehurst.wiremock.client.WireMock.containing
import com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching
import com.github.tomakehurst.wiremock.matching.AnythingPattern
import io.ktor.http.HttpHeaders
private const val dokarkivproxyPath = "/dokarkivproxy-mock"
private fun MappingBuilder.dokarkivproxyMapping() = this
.withHeader(HttpHeaders.Authorization, containing("Bearer "))
.withHeader(ProxiedHeader, AnythingPattern())
.willReturn(
aResponse()
.withBody("{}")
.withStatus(200)
.withHeader("Content-Type", "application/json")
)
private fun WireMockServer.stubDokarkivproxyPut(): WireMockServer {
stubFor(
WireMock.put(urlPathMatching(".*$dokarkivproxyPath.*"))
.withHeader(HttpHeaders.ContentType, WireMock.equalTo("application/json"))
.dokarkivproxyMapping()
)
return this
}
internal fun WireMockServer.dokarkivproxyUrl(): String = baseUrl() + dokarkivproxyPath
internal fun WireMockServer.stubDokarkivproxy() = this
.stubDokarkivproxyPut()
| 7 | Kotlin | 0 | 0 | 87d0cfc14760a41ee8396d762ee058dcf993555b | 1,374 | omsorgspenger-proxy | MIT License |
repository/src/main/java/com/github/lion4ik/repository/RepositoryModule.kt | lion4ik | 154,719,120 | false | null | package com.github.lion4ik.repository
import com.github.lion4ik.core.remote.ForecastRemote
import com.github.lion4ik.core.repository.ForecastRepository
import com.github.lion4ik.core.storage.ForecastStorage
import com.github.lion4ik.repository.impl.ForecastRepositoryImpl
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class RepositoryModule {
@Singleton
@Provides
fun provideForecastRepository(forecastRemote: ForecastRemote, forecastStorage: ForecastStorage): ForecastRepository =
ForecastRepositoryImpl(forecastRemote, forecastStorage)
} | 0 | Kotlin | 0 | 2 | b837a78240a1be17504f52847faf4573cf8cdd9c | 598 | WeatherApp | MIT License |
app/src/test/java/com/imaginaryrhombus/proctimer/TimerModelTest.kt | fizxive | 161,662,097 | false | null | package com.imaginaryrhombus.proctimer
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.imaginaryrhombus.proctimer.ui.timer.TimerModel
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.koin.test.AutoCloseKoinTest
@RunWith(AndroidJUnit4::class)
class TimerModelTest : AutoCloseKoinTest() {
/**
* インスタンス作成テスト.
*/
@Test
fun testInitialize() {
val timerModel = TimerModel()
assertEquals(0.0f, timerModel.seconds.value)
assertEquals(0.0f, timerModel.defaultSeconds)
assertTrue(timerModel.isEnded)
assertNull(timerModel.onEndListener)
}
/**
* 秒数.設定テスト.
*/
@Test
fun setSecondsTest() {
val timerModel = TimerModel()
timerModel.setSeconds(5.0f)
assertEquals(5.0f, timerModel.seconds.value)
assertEquals(5.0f, timerModel.defaultSeconds)
assertFalse(timerModel.isEnded)
timerModel.setSeconds(99.0f)
assertEquals(99.0f, timerModel.seconds.value)
assertEquals(99.0f, timerModel.defaultSeconds)
assertFalse(timerModel.isEnded)
timerModel.setSeconds(0.0f)
assertEquals(0.0f, timerModel.seconds.value)
assertEquals(0.0f, timerModel.defaultSeconds)
assertTrue(timerModel.isEnded)
timerModel.setSeconds(-1.0f)
assertEquals(0.0f, timerModel.seconds.value)
assertEquals(0.0f, timerModel.defaultSeconds)
assertTrue(timerModel.isEnded)
}
/**
* 時間経過テスト
*/
@Test
fun testTick() {
val timerModel = TimerModel()
val tickMethod = timerModel.javaClass.getDeclaredMethod("tick", Float::class.java)
tickMethod.isAccessible = true
fun callTick(deltaSecond: Float) {
tickMethod.invoke(timerModel, deltaSecond)
}
timerModel.setSeconds(60.0f)
callTick(30.0f)
assertEquals(30.0f, timerModel.seconds.value)
callTick(30.0f)
assertEquals(0.0f, timerModel.seconds.value)
timerModel.setSeconds(15.0f)
callTick(20.0f)
assertEquals(0.0f, timerModel.seconds.value)
timerModel.setSeconds(50.0f)
callTick(0.0f)
assertEquals(50.0f, timerModel.seconds.value)
timerModel.setSeconds(0.0f)
callTick(999.0f)
assertEquals(0.0f, timerModel.seconds.value)
}
}
| 8 | Kotlin | 0 | 0 | 33f31e22355d7e59fa791236aa1d5f619e4b108e | 2,513 | ProcTimer | MIT License |
async-buffer/src/main/kotlin/org/project/async/buffer/batch/async/db/fixed/step/FixedStepWriter.kt | leltonborges | 710,551,341 | false | {"Kotlin": 91566} | package org.project.async.buffer.batch.async.db.fixed.step
import jakarta.annotation.PostConstruct
import org.project.async.buffer.batch.AbstractItemWriterStep
import org.project.async.buffer.core.pattern.vo.PersonVO
import org.project.async.buffer.functional.logger
import org.project.async.buffer.functional.logInfoWriter
import org.springframework.batch.core.configuration.annotation.StepScope
import org.springframework.batch.item.Chunk
import org.springframework.batch.item.ExecutionContext
import org.springframework.batch.item.support.SynchronizedItemStreamWriter
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Component
import org.springframework.util.StopWatch
@StepScope
@Component("fixedStepWriter")
class FixedStepWriter(
@Qualifier("asyncItemStreamWriterFixed") val itemStreamWriter: SynchronizedItemStreamWriter<PersonVO>,
): AbstractItemWriterStep<PersonVO>() {
@PostConstruct
fun init(){
this.itemStreamWriter.open(ExecutionContext())
}
override fun write(chunk: Chunk<out PersonVO>) {
val stopWatch = StopWatch()
stopWatch.start()
this.itemStreamWriter.write(chunk)
stopWatch.stop()
logInfoWriter(stopWatch, chunk.size(), this.logger())
}
} | 0 | Kotlin | 0 | 0 | 8f8b9652ebfbee3a1a6161865a350fd602f9a016 | 1,286 | buffer_async_read_writer | MIT License |
src/main/kotlin/lol/bai/explosion/ExplosionDesc.kt | badasintended | 697,683,788 | false | {"Kotlin": 10926} | package lol.bai.explosion
import org.gradle.api.artifacts.ExternalModuleDependency
import org.gradle.api.provider.Provider
import java.io.File
interface ExplosionDesc {
fun maven(notation: String)
fun <T : ExternalModuleDependency> maven(provider: Provider<T>)
fun local(file: File)
} | 0 | Kotlin | 0 | 2 | 8b62cf9a7c3cbf01e2a97ed96f3ecf3694bbecb9 | 302 | explosion | MIT License |
src/main/kotlin/kcmtgateway/UndertowHttpServlet.kt | nick-rakoczy | 101,071,049 | false | null | package kcmtgateway
import io.undertow.server.HttpHandler
import io.undertow.server.HttpServerExchange
import io.undertow.servlet.spec.HttpServletRequestImpl
import org.slf4j.LoggerFactory
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletRequestWrapper
import javax.servlet.http.HttpServletResponse
abstract class UndertowHttpServlet : HttpServlet() {
private val logger = LoggerFactory.getLogger(UndertowHttpServlet::class.java.name)
tailrec fun unwrapToUndertowRequest(req: HttpServletRequest?): HttpServletRequestImpl? {
if (req == null) {
return null
}
if (req is HttpServletRequestImpl) {
return req
}
if (req is HttpServletRequestWrapper) {
val req2 = req.request
if (req2 is HttpServletRequest) {
return unwrapToUndertowRequest(req2)
}
}
return null
}
override final fun service(req: HttpServletRequest?, res: HttpServletResponse?) {
if (req != null && res != null) {
val req2 = unwrapToUndertowRequest(req) ?: error("Unknown response type")
this.process(req, res, req2.exchange::dispatch)
}
}
abstract fun process(req: HttpServletRequest, res: HttpServletResponse, dispatch: (HttpHandler) -> HttpServerExchange)
} | 0 | Kotlin | 0 | 2 | d495ca9db37e8f67c7471236c1d3948706490ef5 | 1,250 | kc-mt-gateway | MIT License |
mapview-desktop/src/desktopMain/kotlin/example/map/ContentRepository.kt | ShreyashKore | 672,328,509 | false | {"Kotlin": 908472, "HTML": 3575, "Swift": 640} | package template.map
interface ContentRepository<K, T> {
suspend fun loadContent(key: K): T
}
| 4 | Kotlin | 2 | 94 | a0d32d8abc3e6b0470f38e74d1e632e1ab3f0999 | 99 | wonderous_compose | MIT License |
app/src/main/java/com/example/bitfit_v1_android_app/AppDatabase.kt | ba-00001 | 779,551,775 | false | {"Kotlin": 8378} | package com.example.bitfit.data.local.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.bitfit.data.local.dao.DrinkEntryDao
@Database(entities = [DrinkEntry::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun drinkEntryDao(): DrinkEntryDao
companion object {
@Volatile
private var INSTANCE: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"bitfit_database"
).fallbackToDestructiveMigration()
.build()
INSTANCE = instance
// return instance
instance
}
}
}
} | 0 | Kotlin | 0 | 0 | fe85ddff4719bd026bf237a193c1f68929a84b3b | 989 | bitfit_v1_android_app | Apache License 2.0 |
feature-assets/src/main/java/com/edgeverse/wallet/feature_assets/presentation/transaction/filter/TransactionHistoryFilterFragment.kt | finn-exchange | 512,140,809 | false | null | package com.edgeverse.wallet.feature_assets.presentation.transaction.filter
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.CompoundButton
import androidx.lifecycle.lifecycleScope
import com.edgeverse.wallet.common.base.BaseFragment
import com.edgeverse.wallet.common.di.FeatureUtils
import com.edgeverse.wallet.common.utils.invoke
import com.edgeverse.wallet.common.view.ButtonState
import com.edgeverse.wallet.common.view.bindFromMap
import com.edgeverse.wallet.feature_assets.R
import com.edgeverse.wallet.feature_assets.di.AssetsFeatureApi
import com.edgeverse.wallet.feature_assets.di.AssetsFeatureComponent
import com.edgeverse.wallet.feature_wallet_api.domain.interfaces.TransactionFilter
import kotlinx.android.synthetic.main.fragment_transactions_filter.transactionFilterApplyBtn
import kotlinx.android.synthetic.main.fragment_transactions_filter.transactionsFilterOtherTransactions
import kotlinx.android.synthetic.main.fragment_transactions_filter.transactionsFilterRewards
import kotlinx.android.synthetic.main.fragment_transactions_filter.transactionsFilterSwitchTransfers
import kotlinx.android.synthetic.main.fragment_transactions_filter.transactionsFilterToolbar
class TransactionHistoryFilterFragment : BaseFragment<TransactionHistoryFilterViewModel>() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = layoutInflater.inflate(R.layout.fragment_transactions_filter, container, false)
override fun initViews() {
transactionsFilterToolbar.setHomeButtonListener { viewModel.backClicked() }
transactionsFilterToolbar.setRightActionClickListener {
viewModel.resetFilter()
}
transactionsFilterRewards.bindFilter(TransactionFilter.REWARD)
transactionsFilterSwitchTransfers.bindFilter(TransactionFilter.TRANSFER)
transactionsFilterOtherTransactions.bindFilter(TransactionFilter.EXTRINSIC)
transactionFilterApplyBtn.setOnClickListener { viewModel.applyClicked() }
}
override fun inject() {
FeatureUtils.getFeature<AssetsFeatureComponent>(
requireContext(),
AssetsFeatureApi::class.java
).transactionHistoryComponentFactory()
.create(this)
.inject(this)
}
override fun subscribe(viewModel: TransactionHistoryFilterViewModel) {
viewModel.isApplyButtonEnabled.observe {
transactionFilterApplyBtn.setState(if (it) ButtonState.NORMAL else ButtonState.DISABLED)
}
}
private fun CompoundButton.bindFilter(filter: TransactionFilter) {
lifecycleScope.launchWhenResumed {
bindFromMap(filter, viewModel.filtersEnabledMap(), viewLifecycleOwner.lifecycleScope)
}
}
}
| 0 | Kotlin | 1 | 0 | 6cc7a0a4abb773daf3da781b7bd1dda5dbf9b01d | 2,847 | edgeverse-wallet | Apache License 2.0 |
yabapi-core/src/commonMain/kotlin/moe/sdl/yabapi/data/search/results/BangumiResult.kt | SDLMoe | 437,756,989 | false | null | @file:UseSerializers(BooleanJsSerializer::class, RgbColorStringSerializer::class)
package moe.sdl.yabapi.data.search.results
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.decodeFromJsonElement
import moe.sdl.yabapi.data.RgbColor
import moe.sdl.yabapi.serializer.BooleanJsSerializer
import moe.sdl.yabapi.serializer.data.RgbColorStringSerializer
@Serializable
public data class BangumiResult(
@SerialName("type") val type: String,
@SerialName("media_id") val mediaId: Int,
@SerialName("title") val title: String,
@SerialName("org_title") val orgTitle: String,
@SerialName("media_type") val mediaType: Int,
@SerialName("cv") val cv: String,
@SerialName("staff") val staff: String,
@SerialName("season_id") val seasonId: Int,
@SerialName("is_avid") val isAvId: Boolean,
@SerialName("hit_columns") val hitColumns: List<String> = emptyList(),
@SerialName("hit_epids") val hitEpids: String,
@SerialName("season_type") val seasonType: Int,
@SerialName("season_type_name") val seasonTypeName: String,
@SerialName("selection_style") val selectionStyle: String,
@SerialName("ep_size") val epSize: Int,
@SerialName("url") val url: String,
@SerialName("button_text") val buttonText: String,
@SerialName("is_follow") val isFollow: Boolean,
@SerialName("is_selection") val isSelection: Boolean,
@SerialName("eps") val eps: List<BangumiEpisode> = emptyList(),
@SerialName("badges") val badges: List<ColorsInfo> = emptyList(),
@SerialName("cover") val cover: String,
@SerialName("areas") val areas: String,
@SerialName("styles") val styles: String,
@SerialName("goto_url") val gotoUrl: String,
@SerialName("desc") val description: String,
@SerialName("pubtime") val releaseDate: String,
@SerialName("media_mode") val mediaMode: Int,
@SerialName("fix_pubtime_str") val fixReleaseTimeString: String,
@SerialName("media_score") val mediaScore: MediaScore,
@SerialName("display_info") val displayInfo: List<ColorsInfo> = emptyList(),
@SerialName("pgc_season_id") val pgcSeasonId: Int,
@SerialName("corner") val corner: Int,
) : SearchResult {
@Serializable
public data class BangumiEpisode(
@SerialName("id") val id: Int,
@SerialName("cover") val cover: String,
@SerialName("title") val title: String,
@SerialName("url") val url: String,
@SerialName("release_date") val releaseDate: String,
@SerialName("badges") val badges: JsonElement? = null,
@SerialName("index_title") val indexTitle: String,
@SerialName("long_title") val longTitle: String,
)
@Serializable
public data class ColorsInfo(
@SerialName("text") val text: String,
@SerialName("text_color") val textColor: RgbColor,
@SerialName("text_color_night") val textColorNight: RgbColor,
@SerialName("bg_color") val bgColor: RgbColor,
@SerialName("bg_color_night") val bgColorNight: RgbColor,
@SerialName("border_color") val borderColor: RgbColor,
@SerialName("border_color_night") val borderColorNight: RgbColor,
@SerialName("bg_style") val bgStyle: Int,
)
public companion object : ResultFactory() {
override val code: String = "media_bangumi"
override fun decode(json: Json, data: JsonObject): BangumiResult = json.decodeFromJsonElement(data)
}
}
@Serializable
public data class MediaScore(
@SerialName("score") val score: Double,
@SerialName("user_count") val userCount: Int,
)
| 0 | null | 1 | 26 | c8be46f9b5e4db1e429c33b0821643fd94789fa1 | 3,783 | Yabapi | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/example/bitfit/MainActivity.kt | steelemeg | 555,668,143 | false | null | package com.example.bitfit
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
private val drinks = mutableListOf<WaterEntity>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val hydroRv = findViewById<RecyclerView>(R.id.rvWater)
val dashboardFragment = DashboardFragment()
val logFragment = WaterLogFragment()
val drinkFragment = DrinkWaterFragment()
val bottomNavigationView: BottomNavigationView = findViewById(R.id.bottom_navigation)
// Start up with the log
replaceFragment(logFragment)
bottomNavigationView.setOnItemSelectedListener {
when(it.itemId){
R.id.action_log->replaceFragment(logFragment)
R.id.action_stats->replaceFragment(dashboardFragment)
R.id.action_goal->replaceFragment(drinkFragment)
}
true
}
}
private fun replaceFragment(fragment: Fragment) {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.apply { replace(R.id.water_frame_layout, fragment) }
fragmentTransaction.commit()
}
public fun backToLog(){
// Begin the transaction
replaceFragment(WaterLogFragment())
}
} | 1 | Kotlin | 0 | 0 | e977024739c87d1fb04e904c16d5fbddcaaf2de5 | 1,679 | HydroTask2 | Apache License 2.0 |
backend/persistence/src/main/kotlin/org/rm3l/devfeed/persistence/ArticleUpdater.kt | rm3l | 187,110,569 | false | {"Kotlin": 152359, "Dart": 90384, "Objective-C": 4107, "Shell": 2556, "Dockerfile": 1979, "Procfile": 190} | /*
* The MIT License (MIT)
*
* Copyright (c) 2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.rm3l.devfeed.persistence
import java.util.function.Supplier
import org.rm3l.devfeed.common.contract.Article
import org.slf4j.LoggerFactory
class ArticleUpdater(private val dao: DevFeedDao, private val article: Article) : Supplier<Unit> {
companion object {
@JvmStatic private val logger = LoggerFactory.getLogger(ArticleUpdater::class.java)
}
override fun get() {
if (logger.isDebugEnabled) {
logger.debug(">>> Handling article crawled: $article")
}
if (article.id != null && dao.shouldRequestScreenshot(article.title, article.url)) {
dao.updateArticleScreenshotData(article)
}
}
}
| 10 | Kotlin | 11 | 23 | be9da13cd470aa2b39cee3dbdb8207052e299cb4 | 1,778 | dev-feed | MIT License |
src/main/kotlin/org/urielserv/uriel/extensions/EventDispatcherExtensions.kt | UrielHabboServer | 729,131,075 | false | null | package org.urielserv.uriel.extensions
import org.urielserv.uriel.EventDispatcher
import org.urielserv.uriel.core.event_dispatcher.UrielEvent
fun on(eventType: String, callback: (UrielEvent) -> Unit) {
EventDispatcher.on(eventType, callback)
} | 0 | null | 0 | 7 | 5ed582f93a604182f05f63d3057524d021513f99 | 249 | Uriel | MIT License |
shared/src/iosMain/kotlin/com/myapplication/di/IosFactory.kt | mobidroid92 | 642,819,457 | false | {"Kotlin": 49342, "Swift": 580, "Shell": 228, "Ruby": 101} | package com.myapplication.di
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import com.myapplication.model.local.database.AppDatabase
import io.ktor.client.HttpClient
import io.ktor.client.engine.darwin.Darwin
import io.ktor.client.plugins.DefaultRequest
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logging
import io.ktor.http.URLProtocol
import io.ktor.http.path
import io.ktor.serialization.kotlinx.json.json
import io.ktor.util.PlatformUtils
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.serialization.json.Json
import platform.Foundation.NSDocumentDirectory
import platform.Foundation.NSFileManager
import platform.Foundation.NSUserDomainMask
actual fun createHttpClient() = HttpClient(Darwin) {
expectSuccess = true
//Serializer
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
ignoreUnknownKeys = true
})
}
//Logger
install(Logging) {
level = if(PlatformUtils.IS_DEVELOPMENT_MODE) {
LogLevel.ALL
} else {
LogLevel.NONE
}
}
//Defaults
install(DefaultRequest) {
url {
protocol = URLProtocol.HTTPS
host = BASE_CHARACTERS_HOST
path(BASE_CHARACTERS_PATH)
}
}
developmentMode = PlatformUtils.IS_DEVELOPMENT_MODE
}
fun createAppDatabase(): AppDatabase {
return createDataBaseBuilder()
.fallbackToDestructiveMigrationOnDowngrade(true)
.setDriver(BundledSQLiteDriver())
.setQueryCoroutineContext(Dispatchers.IO)
.build()
}
private fun createDataBaseBuilder(): RoomDatabase.Builder<AppDatabase> {
val dbFilePath = documentDirectory() + "/app_database.db"
return Room.databaseBuilder<AppDatabase>(
name = dbFilePath,
)
}
@OptIn(ExperimentalForeignApi::class)
private fun documentDirectory(): String {
val documentDirectory = NSFileManager.defaultManager.URLForDirectory(
directory = NSDocumentDirectory,
inDomain = NSUserDomainMask,
appropriateForURL = null,
create = false,
error = null,
)
return requireNotNull(documentDirectory?.path)
} | 0 | Kotlin | 0 | 1 | d31e04107e471cb93b59b646d66b78beb93349a9 | 2,548 | Compose-Multiplatform-Demo | Apache License 2.0 |
midterms/midterm_01/android/app/src/main/kotlin/com/example/midterm_01/MainActivity.kt | uabua | 348,785,089 | false | {"Dart": 186114, "HTML": 33947, "Swift": 3636, "Kotlin": 1159, "Objective-C": 342} | package com.example.midterm_01
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | 3c0ad78c735c9656b72edba885809b2ba78f053b | 127 | flutter-development | MIT License |
app/src/main/java/com/babylon/wallet/android/presentation/account/settings/specificdepositor/SpecificDepositorNav.kt | radixdlt | 513,047,280 | false | {"Kotlin": 3560926, "HTML": 215350, "Java": 18496, "Ruby": 2312, "Shell": 1962} | package com.babylon.wallet.android.presentation.account.settings.specificdepositor
import androidx.compose.animation.AnimatedContentScope
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.runtime.remember
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import com.babylon.wallet.android.presentation.account.settings.thirdpartydeposits.AccountThirdPartyDepositsViewModel
import com.babylon.wallet.android.presentation.account.settings.thirdpartydeposits.ROUTE_ACCOUNT_THIRD_PARTY_DEPOSITS
import com.google.accompanist.navigation.animation.composable
fun NavController.specificDepositor() {
navigate("account_specific_depositor_route")
}
@OptIn(ExperimentalAnimationApi::class)
fun NavGraphBuilder.specificDepositor(navController: NavController, onBackClick: () -> Unit) {
composable(
route = "account_specific_depositor_route",
enterTransition = {
slideIntoContainer(AnimatedContentScope.SlideDirection.Left)
},
exitTransition = {
null
},
popExitTransition = {
slideOutOfContainer(AnimatedContentScope.SlideDirection.Right)
},
popEnterTransition = {
EnterTransition.None
}
) {
val parentEntry = remember(it) {
navController.getBackStackEntry(ROUTE_ACCOUNT_THIRD_PARTY_DEPOSITS)
}
val sharedVM = hiltViewModel<AccountThirdPartyDepositsViewModel>(parentEntry)
SpecificDepositorScreen(
sharedViewModel = sharedVM,
onBackClick = onBackClick,
)
}
}
| 8 | Kotlin | 0 | 4 | 21feebd30b21f03476dcd2e462cea509acf74d8a | 1,733 | babylon-wallet-android | Apache License 2.0 |
src/test/kotlin/eu/thesimplecloud/clientserverapi/testobject/TestObj.kt | theSimpleCloud | 271,379,161 | false | {"Kotlin": 315780, "Java": 8090} | /*
* MIT License
*
* Copyright (C) 2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package eu.thesimplecloud.clientserverapi.testobject
import eu.thesimplecloud.clientserverapi.lib.json.PacketExclude
class TestObj(private val number: Int) : ITestObj {
@PacketExclude
val referenceObj = RecursiveReferenceObj(this)
override fun getNumber(): Int {
return number
}
} | 0 | Kotlin | 0 | 1 | 6b5989f646a1986261a8b0faa1a78691a23a5ebf | 1,432 | clientserverapi | MIT License |
modules/effects/arrow-effects-rx2/src/main/kotlin/arrow/effects/SingleK.kt | enhan | 157,443,888 | true | {"Kotlin": 1919806, "CSS": 187519, "JavaScript": 66836, "HTML": 11798, "Java": 4465, "Shell": 3043} | package arrow.effects
import arrow.core.Either
import arrow.core.Left
import arrow.core.Right
import arrow.effects.CoroutineContextRx2Scheduler.asScheduler
import arrow.effects.typeclasses.Disposable
import arrow.effects.typeclasses.ExitCase
import arrow.effects.typeclasses.Proc
import arrow.higherkind
import io.reactivex.Single
import io.reactivex.SingleEmitter
import kotlin.coroutines.CoroutineContext
fun <A> Single<A>.k(): SingleK<A> = SingleK(this)
fun <A> SingleKOf<A>.value(): Single<A> = this.fix().single
@higherkind
data class SingleK<A>(val single: Single<A>) : SingleKOf<A>, SingleKKindedJ<A> {
fun <B> map(f: (A) -> B): SingleK<B> =
single.map(f).k()
fun <B> ap(fa: SingleKOf<(A) -> B>): SingleK<B> =
flatMap { a -> fa.fix().map { ff -> ff(a) } }
fun <B> flatMap(f: (A) -> SingleKOf<B>): SingleK<B> =
single.flatMap { f(it).fix().single }.k()
fun <B> bracketCase(use: (A) -> SingleKOf<B>, release: (A, ExitCase<Throwable>) -> SingleKOf<Unit>): SingleK<B> =
flatMap { a ->
use(a).fix().single
.doOnSuccess { release(a, ExitCase.Completed) }
.doOnError { release(a, ExitCase.Error(it)) }
.k()
}
fun handleErrorWith(function: (Throwable) -> SingleK<A>): SingleK<A> =
single.onErrorResumeNext { t: Throwable -> function(t).single }.k()
fun continueOn(ctx: CoroutineContext): SingleK<A> =
single.observeOn(ctx.asScheduler()).k()
fun runAsync(cb: (Either<Throwable, A>) -> SingleKOf<Unit>): SingleK<Unit> =
single.flatMap { cb(Right(it)).value() }.onErrorResumeNext { cb(Left(it)).value() }.k()
fun runAsyncCancellable(cb: (Either<Throwable, A>) -> SingleKOf<Unit>): SingleK<Disposable> =
Single.fromCallable {
val disposable: io.reactivex.disposables.Disposable = runAsync(cb).value().subscribe()
val dispose: () -> Unit = { disposable.dispose() }
dispose
}.k()
override fun equals(other: Any?): Boolean =
when (other) {
is SingleK<*> -> this.single == other.single
is Single<*> -> this.single == other
else -> false
}
override fun hashCode(): Int = single.hashCode()
companion object {
fun <A> just(a: A): SingleK<A> =
Single.just(a).k()
fun <A> raiseError(t: Throwable): SingleK<A> =
Single.error<A>(t).k()
operator fun <A> invoke(fa: () -> A): SingleK<A> =
defer { just(fa()) }
fun <A> defer(fa: () -> SingleKOf<A>): SingleK<A> =
Single.defer { fa().value() }.k()
fun <A> async(fa: Proc<A>): SingleK<A> =
Single.create { emitter: SingleEmitter<A> ->
fa { either: Either<Throwable, A> ->
either.fold({
emitter.onError(it)
}, {
emitter.onSuccess(it)
})
}
}.k()
tailrec fun <A, B> tailRecM(a: A, f: (A) -> SingleKOf<Either<A, B>>): SingleK<B> {
val either = f(a).fix().value().blockingGet()
return when (either) {
is Either.Left -> tailRecM(either.a, f)
is Either.Right -> Single.just(either.b).k()
}
}
}
}
| 0 | Kotlin | 0 | 0 | 4cc7fb77ccaf1165d97dd3efc4d06df513a0385b | 3,045 | arrow | Apache License 2.0 |
dsl-annotation-processor/src/main/kotlin/dev/vihang/neo4jstore/dsl/model/annotation/processor/DTO.kt | vihangpatil | 255,573,656 | false | null | package dev.vihang.neo4jstore.dsl.model.annotation.processor
data class ClassInfo(val className: String, val packageName: String) {
constructor(qualifiedName: String) : this(
className = qualifiedName.substringAfterLast("."),
packageName = qualifiedName.substringBeforeLast(".")
)
}
data class RelationInfo(
val name: String,
val from: ClassInfo,
val to: ClassInfo,
/**
* FROM forwardRelation TO
*/
val forwardRelation: String,
/**
* TO reverseRelation FROM
*/
val reverseRelation: String,
/**
* get FROM forwardQuery TO
*/
val forwardQuery: String,
/**
* get TO reverseQuery FROM
*/
val reverseQuery: String
)
| 0 | Kotlin | 0 | 2 | e210f023a25762cc0da31e12ac5bb98209f950d1 | 726 | neo4j-store | Apache License 2.0 |
app/src/main/java/com/eskeitec/apps/weatherman/domain/usecase/GetLocationUseCase.kt | eskeikim | 742,292,727 | false | {"Kotlin": 124313} | package com.eskeitec.apps.weatherman.domain.usecase
import android.os.Build
import androidx.annotation.RequiresApi
import com.eskeitec.apps.weatherman.data.datasource.location.LocationService
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class GetLocationUseCase @Inject constructor(
private val locationService: LocationService,
) {
@RequiresApi(Build.VERSION_CODES.S)
operator fun invoke(): Flow<LatLng?> = locationService.requestLocationUpdates()
}
| 0 | Kotlin | 0 | 0 | 83a30050a1cd96f6da2e77b68bdf934c6f6956f6 | 531 | MVVM-Weather-app | Apache License 2.0 |
app/src/main/java/com/eskeitec/apps/weatherman/domain/usecase/GetLocationUseCase.kt | eskeikim | 742,292,727 | false | {"Kotlin": 124313} | package com.eskeitec.apps.weatherman.domain.usecase
import android.os.Build
import androidx.annotation.RequiresApi
import com.eskeitec.apps.weatherman.data.datasource.location.LocationService
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class GetLocationUseCase @Inject constructor(
private val locationService: LocationService,
) {
@RequiresApi(Build.VERSION_CODES.S)
operator fun invoke(): Flow<LatLng?> = locationService.requestLocationUpdates()
}
| 0 | Kotlin | 0 | 0 | 83a30050a1cd96f6da2e77b68bdf934c6f6956f6 | 531 | MVVM-Weather-app | Apache License 2.0 |
tegral-di/tegral-di-core/src/test/kotlin/guru/zoroark/tegral/di/environment/IdentifierTest.kt | utybo | 491,247,680 | false | {"Kotlin": 1066259, "Nix": 2449, "Shell": 8} | /*
* 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 guru.zoroark.tegral.di.environment
import kotlin.test.Test
import kotlin.test.assertEquals
class IdentifierTest {
@Test
fun `ctor, empty qualifier by default`() {
val identifier = Identifier(String::class)
assertEquals(EmptyQualifier, identifier.qualifier)
}
@Test
fun `toString, non-anonymous object`() {
val identifier = Identifier(IdentifierTest::class)
assertEquals("guru.zoroark.tegral.di.environment.IdentifierTest (<no qualifier>)", identifier.toString())
}
@Test
fun `toString, anonymous object`() {
val anonymousObject = object {}
val identifier = Identifier(anonymousObject::class)
assertEquals("<anonymous> (<no qualifier>)", identifier.toString())
}
}
| 26 | Kotlin | 4 | 37 | fa4284047f2ce7ba9ee78e92d8c67954716e9dcc | 1,331 | Tegral | Apache License 2.0 |
app/src/main/java/com/lostincontext/condition/pick/BottomSheetGridItemViewHolder.kt | LostInContext | 65,417,953 | false | null | package com.lostincontext.condition.pick
import android.view.LayoutInflater
import android.view.ViewGroup
import com.lostincontext.commons.list.ViewHolder
import com.lostincontext.databinding.ItemBottomSheetGridBinding
class BottomSheetGridItemViewHolder(private val binding: ItemBottomSheetGridBinding,
callback: PickerDialogCallback)
: ViewHolder(binding.root) {
init {
binding.callback = callback
}
fun bindTo(item: GridBottomSheetItem) {
binding.item = item
binding.executePendingBindings()
}
companion object {
fun create(inflater: LayoutInflater,
parent: ViewGroup,
callback: PickerDialogCallback): BottomSheetGridItemViewHolder {
val itemBinding = ItemBottomSheetGridBinding.inflate(inflater,
parent,
false)
return BottomSheetGridItemViewHolder(itemBinding, callback)
}
}
}
| 1 | Kotlin | 5 | 46 | 0a2650852fb8bc56cb71c158fc1724f69cdbb640 | 1,083 | LostContext-App | Beerware License |
app/src/main/java/com/libdumper/app/appListAdapter.kt | AndnixSH | 413,814,320 | true | {"C": 46461, "Kotlin": 34719, "C++": 25086, "CMake": 112} | package com.libdumper.app
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.libdumper.R
import com.libdumper.glide.GlideApp
/**
* @author
* The adapter of processes from the selected app
*/
class appListAdapter(var context: Context, var applist:ArrayList<AppDetail>) :RecyclerView.Adapter<appListAdapter.ProcessHolder>(){
private var onapplistener: onAppListener?=null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProcessHolder {
return ProcessHolder(LayoutInflater.from(context).inflate(R.layout.row_app,null))
}
override fun onBindViewHolder(holder: ProcessHolder, position: Int) {
applist[position].let {
appdetail->
holder.appname.text=appdetail.appname
holder.packagename.text=appdetail.packagename
GlideApp.with(context)
.load(appdetail.applicationInfo?.loadIcon(context.getPackageManager()))
.into(holder.appicon)
holder.view.setOnClickListener {
onapplistener?.onSelect(appdetail,position)
}
}
}
fun setAppListener(onAppListener: onAppListener){
this.onapplistener=onAppListener
}
override fun getItemCount(): Int {
return applist.size
}
class ProcessHolder(view:View):RecyclerView.ViewHolder(view){
var view=view
var appname=view.findViewById<TextView>(R.id.appname)
var packagename=view.findViewById<TextView>(R.id.packagename)
var appicon=view.findViewById<ImageView>(R.id.appicon)
}
} | 0 | null | 1 | 5 | 281d2471126027d4126df59641423d66c4303bc6 | 1,759 | LibDumper-1 | MIT License |
core/src/commonMain/kotlin/ireader/core/http/BrowserEngine.kt | kazemcodes | 540,829,865 | true | {"Kotlin": 2179459} | package ireader.core.http
import okhttp3.Cookie
import okhttp3.Headers
interface BrowserEngineInterface {
suspend fun fetch(
url: String,
selector: String? = null,
headers: Headers? = null,
timeout: Long = 50000L,
userAgent: String = DEFAULT_USER_AGENT
): Result
}
expect class BrowserEngine : BrowserEngineInterface {
override suspend fun fetch(
url: String,
selector: String?,
headers: Headers?,
timeout: Long,
userAgent: String,
): Result
}
/**
* This object is representing the result of an request
* @param responseBody - the response responseBody
* @param responseStatus - the http responses status code and message
* @param contentType - the http responses content type
* @param responseHeader - the http responses headers
* @param cookies - the http response's cookies
*/
@Suppress("LongParameterList")
class Result(
val responseBody: String,
val cookies: List<Cookie> = emptyList(),
)
| 10 | Kotlin | 16 | 6 | b6b2414fa002cec2aa0d199871fcfb4c2e190a8f | 1,012 | IReader | Apache License 2.0 |
src/main/kotlin/sola/angel/geom2d/OpenRange.kt | angelsolaorbaiceta | 159,042,202 | false | null | package sola.angel.geom2d
class OpenRange(val start: Double, val end: Double) {
val length: Double = end - start
fun contains(value: Double): Boolean = value > start && value < end
fun overlaps(other: OpenRange): Boolean {
return contains(other.start) || contains(other.end)
|| other.contains(start) || other.contains(end)
}
fun overlapRange(other: OpenRange): OpenRange? {
if (!overlaps(other)) return null
return OpenRange(
Math.max(start, other.start),
Math.min(end, other.end)
)
}
} | 0 | Kotlin | 0 | 0 | 3355a4f738b0a8a403d00b49f0ad89b61dfc7153 | 587 | geom2d | MIT License |
example/src/main/kotlin/com/expedia/graphql/sample/extension/CustomSchemaGeneratorHooks.kt | tkruener | 196,866,673 | true | {"Kotlin": 324093, "HTML": 20063, "Shell": 2927} | package com.expedia.graphql.sample.extension
import com.expedia.graphql.directives.KotlinDirectiveWiringFactory
import com.expedia.graphql.execution.DataFetcherExecutionPredicate
import com.expedia.graphql.hooks.GraphQlTypeExtender
import com.expedia.graphql.hooks.SchemaGeneratorHooks
import com.expedia.graphql.hooks.TopLevelType
import com.expedia.graphql.sample.resolvers.GraphlQlCustomArgumentResolver
import com.expedia.graphql.sample.resolvers.GraphlQlTypeExtenderProvider
import com.expedia.graphql.sample.resolvers.Mutation
import com.expedia.graphql.sample.resolvers.Query
import com.expedia.graphql.sample.resolvers.Resolver
import com.expedia.graphql.sample.resolvers.Subscription
import com.expedia.graphql.sample.resolvers.isAnnotatedWith
import com.expedia.graphql.sample.validation.DataFetcherExecutionValidator
import graphql.language.StringValue
import graphql.schema.Coercing
import graphql.schema.GraphQLScalarType
import graphql.schema.GraphQLType
import org.springframework.stereotype.Component
import java.util.UUID
import javax.validation.Validator
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KType
import kotlin.reflect.full.instanceParameter
import kotlin.reflect.full.superclasses
import kotlin.reflect.jvm.jvmErasure
/**
* Schema generator hook that adds additional scalar types.
*/
@Component
class CustomSchemaGeneratorHooks(validator: Validator,
override val wiringFactory: KotlinDirectiveWiringFactory,
private val schemaExtender: GraphlQlTypeExtenderProvider,
override val parameterResolver: GraphlQlCustomArgumentResolver) : SchemaGeneratorHooks {
/**
* Register additional GraphQL scalar types.
*/
override fun willGenerateGraphQLType(type: KType): GraphQLType? = when (type.classifier) {
UUID::class -> graphqlUUIDType
else -> null
}
override val dataFetcherExecutionPredicate: DataFetcherExecutionPredicate? = DataFetcherExecutionValidator(validator)
override fun getTypeExtenders(kClass: KClass<*>): List<GraphQlTypeExtender> = schemaExtender.getTypeExtendersForType(kClass)
override fun isValidTopLevelFunction(topLevelType: TopLevelType, function: KFunction<*>) = when {
function.isTargetingResolver() -> function.isResolverTopLevelFunction(topLevelType)
else -> super.isValidTopLevelFunction(topLevelType, function)
}
private fun KFunction<*>.isResolverTopLevelFunction(topLevelType: TopLevelType) = when (topLevelType) {
TopLevelType.Query -> isAnnotatedWith<Query>()
TopLevelType.Mutation -> isAnnotatedWith<Mutation>()
TopLevelType.Subscription -> isAnnotatedWith<Subscription>()
}
private fun KFunction<*>.isTargetingResolver() = this.instanceParameter?.let {
it.type.jvmErasure.superclasses.contains(Resolver::class)
} ?: false
}
internal val graphqlUUIDType = GraphQLScalarType("UUID",
"A type representing a formatted java.util.UUID",
UUIDCoercing
)
private object UUIDCoercing : Coercing<UUID, String> {
override fun parseValue(input: Any?): UUID = UUID.fromString(
serialize(
input
)
)
override fun parseLiteral(input: Any?): UUID? {
val uuidString = (input as? StringValue)?.value
return UUID.fromString(uuidString)
}
override fun serialize(dataFetcherResult: Any?): String = dataFetcherResult.toString()
} | 0 | Kotlin | 0 | 0 | 5197d3245b6d24fbdac3380b9f28e14115eb0377 | 3,292 | graphql-kotlin | Apache License 2.0 |
urbanairship-core/src/test/java/com/urbanairship/channel/ChannelApiClientTest.kt | urbanairship | 58,972,818 | false | {"Kotlin": 3266979, "Java": 2582150, "Python": 10137, "Shell": 589} | /* Copyright Airship and Contributors */
package com.urbanairship.channel
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.urbanairship.TestAirshipRuntimeConfig
import com.urbanairship.TestRequestSession
import com.urbanairship.http.RequestAuth
import com.urbanairship.http.RequestBody
import com.urbanairship.http.toSuspendingRequestSession
import com.urbanairship.remoteconfig.RemoteAirshipConfig
import com.urbanairship.remoteconfig.RemoteConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestResult
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(AndroidJUnit4::class)
public class ChannelApiClientTest {
private val payload = ChannelRegistrationPayload.Builder().build()
private val config = TestAirshipRuntimeConfig()
private val requestSession = TestRequestSession()
private val testDispatcher = StandardTestDispatcher()
private val client = ChannelApiClient(config, requestSession.toSuspendingRequestSession())
@Before
public fun setup() {
Dispatchers.setMain(testDispatcher)
config.updateRemoteConfig(
RemoteConfig(
airshipConfig = RemoteAirshipConfig(
deviceApiUrl = "https://example.com"
)
)
)
}
@After
public fun tearDown() {
Dispatchers.resetMain()
}
@Test
public fun testCreate(): TestResult = runTest {
requestSession.addResponse(200, "{ \"ok\": true, \"channel_id\": \"someChannelId\"}")
val response = client.createChannel(payload)
val result = requireNotNull(response.value)
assertEquals(
Channel(
"someChannelId", "https://example.com/api/channels/someChannelId"
), result
)
assertEquals("POST", requestSession.lastRequest.method)
assertEquals(
"https://example.com/api/channels/", requestSession.lastRequest.url.toString()
)
assertEquals(RequestAuth.GeneratedAppToken, requestSession.lastRequest.auth)
assertEquals(requestSession.lastRequest.body, RequestBody.Json(payload))
}
@Test
public fun testCreateNullUrl(): TestResult = runTest {
config.updateRemoteConfig(RemoteConfig())
requestSession.addResponse(200, "{ \"ok\": true, \"channel_id\": \"someChannelId\"}")
val response = client.createChannel(payload)
assertNotNull(response.exception)
}
@Test
public fun testUpdate(): TestResult = runTest {
requestSession.addResponse(200)
val response = client.updateChannel("someChannelId", payload)
val result = requireNotNull(response.value)
assertEquals(
Channel(
"someChannelId", "https://example.com/api/channels/someChannelId"
), result
)
assertEquals("PUT", requestSession.lastRequest.method)
assertEquals(RequestAuth.ChannelTokenAuth("someChannelId"), requestSession.lastRequest.auth)
assertEquals(
"https://example.com/api/channels/someChannelId", requestSession.lastRequest.url.toString()
)
assertEquals(requestSession.lastRequest.body, RequestBody.Json(payload))
}
@Test
public fun testUpdateNullUrl(): TestResult = runTest {
config.updateRemoteConfig(RemoteConfig())
requestSession.addResponse(200, "{ \"ok\": true, \"channel_id\": \"someChannelId\"}")
val response = client.updateChannel("someChannelId", payload)
assertNotNull(response.exception)
}
}
| 2 | Kotlin | 122 | 111 | 21d49c3ffd373e3ba6b51a706a4839ab3713db11 | 3,966 | android-library | Apache License 2.0 |
app/src/main/java/com/battlelancer/seriesguide/shows/overview/SeasonsViewModel.kt | UweTrottmann | 1,990,682 | false | {"Gradle Kotlin DSL": 7, "PowerShell": 1, "Text": 3, "Markdown": 14, "Java Properties": 1, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "YAML": 5, "TOML": 1, "INI": 1, "Proguard": 2, "XML": 403, "JSON": 11, "Kotlin": 408, "Java": 170} | // SPDX-License-Identifier: Apache-2.0
// Copyright 2018, 2020-2024 <NAME>
package com.battlelancer.seriesguide.shows.overview
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.battlelancer.seriesguide.provider.SgRoomDatabase
import com.battlelancer.seriesguide.shows.database.SgSeason2
import com.battlelancer.seriesguide.util.TimeTools
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
class SeasonsViewModel(
application: Application,
private val showId: Long
) : AndroidViewModel(application) {
private val order = MutableStateFlow(SeasonsSettings.getSeasonSortOrder(getApplication()))
data class SeasonStats(
val total: Int,
val notWatchedReleased: Int,
val notWatchedToBeReleased: Int,
val notWatchedNoRelease: Int,
val skipped: Int,
val collected: Int
) {
constructor() : this(0, 0, 0, 0, 0, 0)
}
data class SgSeasonWithStats(
val season: SgSeason2,
val stats: SeasonStats
)
private val seasonStats = MutableStateFlow(mapOf<Long, SeasonStats>())
val seasonsWithStats = order
.flatMapLatest {
val helper = SgRoomDatabase.getInstance(application).sgSeason2Helper()
if (it == SeasonsSettings.SeasonSorting.LATEST_FIRST) {
helper.getSeasonsOfShowLatestFirst(showId)
} else {
helper.getSeasonsOfShowOldestFirst(showId)
}
}
.combine(seasonStats) { seasons, stats ->
seasons.map { SgSeasonWithStats(it, stats[it.id] ?: SeasonStats()) }
}
.flowOn(Dispatchers.IO)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = listOf()
)
val remainingCountData = RemainingCountLiveData(application, viewModelScope)
fun updateOrder() {
order.value = SeasonsSettings.getSeasonSortOrder(getApplication())
}
/**
* Updates episode counts for a specific [seasonIdToUpdate] or all seasons if null.
*/
fun updateSeasonStats(seasonIdToUpdate: Long?) {
viewModelScope.launch(Dispatchers.IO) {
val database = SgRoomDatabase.getInstance(getApplication())
val seasonIds = if (seasonIdToUpdate != null) {
listOf(seasonIdToUpdate)
} else {
database.sgSeason2Helper().getSeasonIdsOfShow(showId)
}
val newMap = seasonStats.value.toMutableMap()
val helper = database.sgEpisode2Helper()
val currentTime = TimeTools.getCurrentTime(getApplication())
for (seasonId in seasonIds) {
val total = helper.countEpisodesOfSeason(seasonId)
newMap[seasonId] = SeasonStats(
total = total,
notWatchedReleased = helper
.countNotWatchedReleasedEpisodesOfSeason(seasonId, currentTime),
notWatchedToBeReleased = helper
.countNotWatchedToBeReleasedEpisodesOfSeason(seasonId, currentTime),
notWatchedNoRelease = helper.countNotWatchedNoReleaseEpisodesOfSeason(seasonId),
skipped = helper.countSkippedEpisodesOfSeason(seasonId),
collected = total - helper.countNotCollectedEpisodesOfSeason(seasonId)
)
}
seasonStats.value = newMap
}
}
}
class SeasonsViewModelFactory(
private val application: Application,
private val showId: Long
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return SeasonsViewModel(application, showId) as T
}
} | 50 | Kotlin | 399 | 1,920 | 20bb18d5310046b0400f8b9dc105334f9212f226 | 4,200 | SeriesGuide | Apache License 2.0 |
kochange-core/src/commonMain/kotlin/dev/itbasis/kochange/core/currency/Currency.kt | itbasis | 430,295,476 | false | {"Kotlin": 50677} | package dev.itbasis.kochange.core.currency
public expect fun Currency.Companion.all(): Set<Currency>
public abstract class Currency protected constructor() {
public abstract val code: String
public abstract val name: String
public abstract val alternativeCodes: List<String>
public abstract val comment: String
public fun alternativesAsInstances(): Collection<Currency> = alternativeCodes.map {
currencies.getValue(it)
}
override fun toString(): String = code
override fun hashCode(): Int {
var result = code.hashCode()
result = 31 * result + name.hashCode()
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null) return false
if (other !is Currency) return false
if (code == other.code) return true
if (alternativeCodes.contains(other.code)) return true
if (other.alternativeCodes.contains(code)) return true
return false
}
public companion object {
public fun resetCache() {
currencies.clear()
currencies.putAll(initCurrencies())
}
public fun getInstanceNotCreate(code: String): Currency? = currencies[code]
public fun getOrCreateInstance(code: String, baseCurrency: Currency? = null): Currency = currencies.getOrPut(code) {
object : Currency() {
override val code = code
override val name = baseCurrency?.name ?: code
override val alternativeCodes = baseCurrency?.let { it.alternativeCodes + it.code } ?: emptyList()
override val comment = ""
}
}
}
}
| 8 | Kotlin | 0 | 1 | 95b464deefbb1a947adb433563fc9ed25fd1cf31 | 1,494 | kochange | MIT License |
app/src/main/java/com/mg/ticket/ui/view/fragments/EntryFragment.kt | AbdielMg007 | 711,192,123 | false | {"Kotlin": 21792} | package com.mg.ticket.ui.view.fragments
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isInvisible
import androidx.fragment.app.commit
import com.google.firebase.auth.FirebaseAuth
import com.mg.ticket.R
import com.mg.ticket.databinding.FragmentEntryBinding
import com.mg.ticket.ui.view.activities.MenuActivity
class EntryFragment : Fragment(R.layout.fragment_entry) {
private lateinit var binding: FragmentEntryBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentEntryBinding.bind(view)
setup()
}
private fun setup() {
binding.progressBar.isInvisible = true
binding.forgotTv.setOnClickListener {
forgotTvAction()
}
binding.loginEntryTv.setOnClickListener {
loginEntryTvAction()
}
binding.entryBtn.setOnClickListener {
binding.progressBar.isInvisible = false
entryBtnAction()
}
}
private fun entryBtnAction() {
if (binding.emailInput.text.isEmpty() || binding.passwordInput.text.isEmpty()) {
binding.progressBar.isInvisible = true
Toast.makeText(context, resources.getString(R.string.text_empty_alert), Toast.LENGTH_SHORT).show()
return
}
FirebaseAuth.getInstance().signInWithEmailAndPassword(
binding.emailInput.text.toString(),
binding.passwordInput.text.toString()
).addOnCompleteListener {
if (it.isSuccessful) {
val nextScreen = Intent(context, MenuActivity::class.java)
binding.progressBar.isInvisible = true
startActivity(nextScreen)
} else {
binding.progressBar.isInvisible = true
showAlert()
}
}
}
private fun loginEntryTvAction() {
requireActivity().supportFragmentManager.commit {
replace(R.id.fragmentLogin, CreateAccountFragment())
addToBackStack(null)
}
}
private fun forgotTvAction() {
requireActivity().supportFragmentManager.commit {
replace(R.id.fragmentLogin, ForgotPassFragment())
addToBackStack(null)
}
}
private fun showAlert() {
val builder = context?.let { AlertDialog.Builder(it) }
builder?.setTitle("Error")
builder?.setMessage("Verifiique si su usuario o contraseña son correctos")
builder?.setPositiveButton("Aceptar", null)
builder?.create()?.show()
}
} | 0 | Kotlin | 0 | 0 | 0bde777b241e6e665766a90537901d3f9efccb17 | 2,766 | Tickets | MIT License |
app/src/main/java/com/mg/ticket/ui/view/fragments/EntryFragment.kt | AbdielMg007 | 711,192,123 | false | {"Kotlin": 21792} | package com.mg.ticket.ui.view.fragments
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isInvisible
import androidx.fragment.app.commit
import com.google.firebase.auth.FirebaseAuth
import com.mg.ticket.R
import com.mg.ticket.databinding.FragmentEntryBinding
import com.mg.ticket.ui.view.activities.MenuActivity
class EntryFragment : Fragment(R.layout.fragment_entry) {
private lateinit var binding: FragmentEntryBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentEntryBinding.bind(view)
setup()
}
private fun setup() {
binding.progressBar.isInvisible = true
binding.forgotTv.setOnClickListener {
forgotTvAction()
}
binding.loginEntryTv.setOnClickListener {
loginEntryTvAction()
}
binding.entryBtn.setOnClickListener {
binding.progressBar.isInvisible = false
entryBtnAction()
}
}
private fun entryBtnAction() {
if (binding.emailInput.text.isEmpty() || binding.passwordInput.text.isEmpty()) {
binding.progressBar.isInvisible = true
Toast.makeText(context, resources.getString(R.string.text_empty_alert), Toast.LENGTH_SHORT).show()
return
}
FirebaseAuth.getInstance().signInWithEmailAndPassword(
binding.emailInput.text.toString(),
binding.passwordInput.text.toString()
).addOnCompleteListener {
if (it.isSuccessful) {
val nextScreen = Intent(context, MenuActivity::class.java)
binding.progressBar.isInvisible = true
startActivity(nextScreen)
} else {
binding.progressBar.isInvisible = true
showAlert()
}
}
}
private fun loginEntryTvAction() {
requireActivity().supportFragmentManager.commit {
replace(R.id.fragmentLogin, CreateAccountFragment())
addToBackStack(null)
}
}
private fun forgotTvAction() {
requireActivity().supportFragmentManager.commit {
replace(R.id.fragmentLogin, ForgotPassFragment())
addToBackStack(null)
}
}
private fun showAlert() {
val builder = context?.let { AlertDialog.Builder(it) }
builder?.setTitle("Error")
builder?.setMessage("Verifiique si su usuario o contraseña son correctos")
builder?.setPositiveButton("Aceptar", null)
builder?.create()?.show()
}
} | 0 | Kotlin | 0 | 0 | 0bde777b241e6e665766a90537901d3f9efccb17 | 2,766 | Tickets | MIT License |
kotlin-client/src/main/kotlin/com/couchbase/client/kotlin/kv/LookupInResult.kt | couchbase | 151,122,650 | false | null | /*
* Copyright 2021 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.couchbase.client.kotlin.kv
import com.couchbase.client.core.error.subdoc.DocumentTooDeepException
import com.couchbase.client.core.error.subdoc.PathInvalidException
import com.couchbase.client.core.error.subdoc.PathTooDeepException
import com.couchbase.client.core.msg.kv.SubDocumentField
import com.couchbase.client.kotlin.codec.JsonSerializer
import com.couchbase.client.kotlin.codec.TypeRef
import com.couchbase.client.kotlin.codec.typeRef
import com.couchbase.client.kotlin.internal.toStringUtf8
public class LookupInResult(
public val id: String,
public val size: Int,
public val cas: Long,
public val deleted: Boolean,
private val fields: List<SubDocumentField>,
private val defaultSerializer: JsonSerializer,
private val spec: LookupInSpec,
) {
// When the LookupInResult is in scope as a receiver,
// Subdoc instances have these addition properties / methods
// for accessing field values.
public val SubdocExists.value: Boolean get() = exists(spec, index)
public val SubdocCount.value: Int get() = content(this).toStringUtf8().toInt()
public val Subdoc.contentAsBytes: ByteArray get() = content(this)
public val Subdoc.exists: Boolean get() = exists(spec, index)
public inline fun <reified T> Subdoc.contentAs(serializer: JsonSerializer? = null): T
= internalContentAs(this, typeRef(), serializer)
@PublishedApi
internal fun <T> internalContentAs(subdoc: Subdoc, type: TypeRef<T>, serializer: JsonSerializer? = null): T {
return (serializer ?: defaultSerializer).deserialize(content(subdoc), type)
}
private fun exists(spec: LookupInSpec, index: Int): Boolean {
checkSpec(spec)
checkIndex(index, 0 until size)
val field = fields[index]
field.error().ifPresent {
// In these cases, can't tell if the path exists
if (it is PathTooDeepException) throw it
if (it is DocumentTooDeepException) throw it
if (it is PathInvalidException) throw it
}
return !field.error().isPresent
}
internal operator fun get(index: Int): SubDocumentField {
checkIndex(index, 0 until size)
val field = fields[index]
field.error().ifPresent { throw it }
return field
}
internal fun content(subdoc: Subdoc): ByteArray {
checkSpec(subdoc.spec)
return get(subdoc.index).value()
}
internal fun content(subdoc: SubdocCount): ByteArray {
checkSpec(subdoc.spec)
return get(subdoc.index).value()
}
private fun checkSpec(spec: LookupInSpec) {
require(spec == this.spec) { "Subdoc was not created from the same LookupInSpec as this result." }
}
}
internal fun checkIndex(index: Int, range: IntRange): Int {
if (index !in range) throw IndexOutOfBoundsException("Index $index not in range $range")
return index
}
| 2 | null | 24 | 32 | da1786cd84e03921c01538c8a997e043d909015f | 3,506 | couchbase-jvm-clients | Apache License 2.0 |
attribution/src/main/java/com/affise/attribution/events/JsonEventClass.kt | affise | 496,592,599 | false | null | package com.affise.attribution.events
import com.affise.attribution.events.predefined.*
import com.affise.attribution.events.subscription.*
import com.affise.attribution.parameters.Parameters
import org.json.JSONObject
fun JSONObject.classOfEvent(): Class<out Event>? {
val name = this.optString(Parameters.AFFISE_EVENT_NAME)
val subtype = this.optJSONObject(Parameters.AFFISE_EVENT_DATA)?.optString(SubscriptionParameters.AFFISE_SUBSCRIPTION_EVENT_TYPE_KEY)
return when (name) {
"AchieveLevel" -> AchieveLevelEvent::class.java
"AddPaymentInfo" -> AddPaymentInfoEvent::class.java
"AddToCart" -> AddToCartEvent::class.java
"AddToWishlist" -> AddToWishlistEvent::class.java
"ClickAdv" -> ClickAdvEvent::class.java
"CompleteRegistration" -> CompleteRegistrationEvent::class.java
"CompleteStream" -> CompleteStreamEvent::class.java
"CompleteTrial" -> CompleteTrialEvent::class.java
"CompleteTutorial" -> CompleteTutorialEvent::class.java
"ContentItemsView" -> ContentItemsViewEvent::class.java
"CustomId01" -> CustomId01Event::class.java
"CustomId02" -> CustomId02Event::class.java
"CustomId03" -> CustomId03Event::class.java
"CustomId04" -> CustomId04Event::class.java
"CustomId05" -> CustomId05Event::class.java
"CustomId06" -> CustomId06Event::class.java
"CustomId07" -> CustomId07Event::class.java
"CustomId08" -> CustomId08Event::class.java
"CustomId09" -> CustomId09Event::class.java
"CustomId10" -> CustomId10Event::class.java
"DeepLinked" -> DeepLinkedEvent::class.java
"InitiatePurchase" -> InitiatePurchaseEvent::class.java
"InitiateStream" -> InitiateStreamEvent::class.java
"Invite" -> InviteEvent::class.java
"LastAttributedTouch" -> LastAttributedTouchEvent::class.java
"ListView" -> ListViewEvent::class.java
"Login" -> LoginEvent::class.java
"OpenedFromPushNotification" -> OpenedFromPushNotificationEvent::class.java
"Purchase" -> PurchaseEvent::class.java
"Rate" -> RateEvent::class.java
"ReEngage" -> ReEngageEvent::class.java
"Reserve" -> ReserveEvent::class.java
"Sales" -> SalesEvent::class.java
"Search" -> SearchEvent::class.java
"Share" -> ShareEvent::class.java
"SpendCredits" -> SpendCreditsEvent::class.java
"StartRegistration" -> StartRegistrationEvent::class.java
"StartTrial" -> StartTrialEvent::class.java
"StartTutorial" -> StartTutorialEvent::class.java
"Subscribe" -> SubscribeEvent::class.java
"TravelBooking" -> TravelBookingEvent::class.java
"UnlockAchievement" -> UnlockAchievementEvent::class.java
"Unsubscribe" -> UnsubscribeEvent::class.java
"Update" -> UpdateEvent::class.java
"ViewAdv" -> ViewAdvEvent::class.java
"ViewCart" -> ViewCartEvent::class.java
"ViewItem" -> ViewItemEvent::class.java
"ViewItems" -> ViewItemsEvent::class.java
SubscriptionParameters.AFFISE_SUBSCRIPTION_ACTIVATION,
SubscriptionParameters.AFFISE_SUBSCRIPTION_CANCELLATION,
SubscriptionParameters.AFFISE_SUBSCRIPTION_ENTERED_BILLING_RETRY,
SubscriptionParameters.AFFISE_SUBSCRIPTION_FIRST_CONVERSION,
SubscriptionParameters.AFFISE_SUBSCRIPTION_REACTIVATION,
SubscriptionParameters.AFFISE_SUBSCRIPTION_RENEWAL,
SubscriptionParameters.AFFISE_SUBSCRIPTION_RENEWAL_FROM_BILLING_RETRY -> subscriptionEventClass(subtype)
else -> null
}
}
private fun subscriptionEventClass(subtype: String?): Class<out BaseSubscriptionEvent>? {
return when (subtype) {
SubscriptionParameters.AFFISE_SUB_INITIAL_SUBSCRIPTION -> InitialSubscriptionEvent::class.java
SubscriptionParameters.AFFISE_SUB_INITIAL_TRIAL -> InitialTrialEvent::class.java
SubscriptionParameters.AFFISE_SUB_INITIAL_OFFER -> InitialOfferEvent::class.java
SubscriptionParameters.AFFISE_SUB_FAILED_TRIAL -> FailedTrialEvent::class.java
SubscriptionParameters.AFFISE_SUB_FAILED_OFFERISE -> FailedOfferiseEvent::class.java
SubscriptionParameters.AFFISE_SUB_FAILED_SUBSCRIPTION -> FailedSubscriptionEvent::class.java
SubscriptionParameters.AFFISE_SUB_FAILED_TRIAL_FROM_RETRY -> FailedTrialFromRetryEvent::class.java
SubscriptionParameters.AFFISE_SUB_FAILED_OFFER_FROM_RETRY -> FailedOfferFromRetryEvent::class.java
SubscriptionParameters.AFFISE_SUB_FAILED_SUBSCRIPTION_FROM_RETRY -> FailedSubscriptionFromRetryEvent::class.java
SubscriptionParameters.AFFISE_SUB_TRIAL_IN_RETRY -> TrialInRetryEvent::class.java
SubscriptionParameters.AFFISE_SUB_OFFER_IN_RETRY -> OfferInRetryEvent::class.java
SubscriptionParameters.AFFISE_SUB_SUBSCRIPTION_IN_RETRY -> SubscriptionInRetryEvent::class.java
SubscriptionParameters.AFFISE_SUB_CONVERTED_TRIAL -> ConvertedTrialEvent::class.java
SubscriptionParameters.AFFISE_SUB_CONVERTED_OFFER -> ConvertedOfferEvent::class.java
SubscriptionParameters.AFFISE_SUB_REACTIVATED_SUBSCRIPTION -> ReactivatedSubscriptionEvent::class.java
SubscriptionParameters.AFFISE_SUB_RENEWED_SUBSCRIPTION -> RenewedSubscriptionEvent::class.java
SubscriptionParameters.AFFISE_SUB_CONVERTED_TRIAL_FROM_RETRY -> ConvertedTrialFromRetryEvent::class.java
SubscriptionParameters.AFFISE_SUB_CONVERTED_OFFER_FROM_RETRY -> ConvertedOfferFromRetryEvent::class.java
SubscriptionParameters.AFFISE_SUB_RENEWED_SUBSCRIPTION_FROM_RETRY -> RenewedSubscriptionFromRetryEvent::class.java
else -> null
}
} | 0 | Kotlin | 0 | 3 | ed6209e9eff536569c2ce618945365e63c9419fd | 5,689 | sdk-android | The Unlicense |
src/main/kotlin/com/github/afezeria/simplescheduler/entity.kt | afezeria | 337,101,425 | false | {"PLpgSQL": 88549, "Kotlin": 81617} | package com.github.afezeria.simplescheduler
import java.time.LocalDateTime
/**
* 计划信息
* 调度器根据计划生成任务并执行
* @property id 唯一标识,自动生成
* @property type 类型,可选值:basic(根据执行间隔计算执行时间) cron(根据表达式计算执行时间)
* @property cron cron 表达式,cron类型专用
* @property name 计划名称
* @property status 计划状态,可选值:active inactive error,计划错误次数或超时次数超过限制值时状态变为error
* @property executing 是否正在执行
* @property ord 优先级,0-100,0最高
* @property intervalTime 执行间隔时间,basic类型专用
* @property remainingTimes 剩余执行次数,为null时无限执行,指定次数后每次执行减一,
* 为0时计划状态变为incative,不再执行
* @property actionName 动作名称,[ActionProvider]接口根据该名称查找实现
* @property execAfterStart 开始后是否立刻执行,
* 当 [type] 为 basic ,值为false时第一次执行时间为计划开始时间+执行间隔秒数
* 当 [type] 为 cron ,值为false时第一次执行时间为计划开始时间后第一个符合表达式的时间
* @property serialExec 是否并行执行
* 当 [type] 为 basic 时,值为true时下次执行时间为 [lastExecEndTime]+[intervalTime]s 且不能有任务正在执行,
* 为false时为 [lastExecStartTime]+[intervalTime]s
* 当 [type] 为 cron 时,值为true时到达下次执行时间时如果 [executing] 为 true 则跳过这次执行,
* 为false时到达下次执行时间时直接执行,不判断 [executing] 的值
* @property totalTimes 总执行次数
* @property errorTimes 错误次数
* @property allowErrorTimes 允许错误次数,小于 [errorTimes]+[timeoutTimes] 时计划状态变为 error
* @property timeout 超时时间,单位:秒
* @property timeoutTimes 超时次数
* @property startTime 计划开始时间
* @property endTime 计划结束时间,可为null
* @property createTime 创建时间,自动生成
* @property createUser 创建用户,随意
* @property planData 计划数据,执行动作时作为参数传给实现
* @property lastExecStartTime 上一次执行开始时间,自动生成
* @property lastExecEndTime 上一次执行结束时间,自动生成
* @property nextExecTime 下一次执行时间,自动生成
* @property remark 备注
* @author afezeria
*/
class PlanInfo(map: Map<String, Any?>) {
var id: Int
var type: String
var cron: String?
var name: String
var status: String
var executing: Boolean
var ord: Int
var intervalTime: Int?
var remainingTimes: Int?
var actionName: String
var execAfterStart: Boolean
var serialExec: Boolean
var totalTimes: Int
var errorTimes: Int
var allowErrorTimes: Int?
var timeout: Int
var timeoutTimes: Int
var startTime: LocalDateTime
var endTime: LocalDateTime?
var createTime: LocalDateTime
var createUser: String?
var planData: String?
var lastExecStartTime: LocalDateTime
var lastExecEndTime: LocalDateTime
var nextExecTime: LocalDateTime
var remark: String?
init {
id = map["id"] as Int
type = map["type"] as String
cron = map["cron"] as String?
name = map["name"] as String
status = map["status"] as String
executing = map["executing"] as Boolean
ord = map["ord"] as Int
intervalTime = map["interval_time"] as Int?
remainingTimes = map["remaining_times"] as Int?
actionName = map["action_name"] as String
execAfterStart = map["exec_after_start"] as Boolean
serialExec = map["serial_exec"] as Boolean
totalTimes = map["total_times"] as Int
errorTimes = map["error_times"] as Int
allowErrorTimes = map["allow_error_times"] as Int?
timeout = map["timeout"] as Int
timeoutTimes = map["timeout_times"] as Int
startTime = map["start_time"] as LocalDateTime
endTime = map["end_time"] as LocalDateTime?
createTime = map["create_time"] as LocalDateTime
createUser = map["create_user"] as String?
planData = map["plan_data"] as String?
lastExecStartTime = map["last_exec_start_time"] as LocalDateTime
lastExecEndTime = map["last_exec_end_time"] as LocalDateTime
nextExecTime = map["next_exec_time"] as LocalDateTime
remark = map["remark"] as String?
}
}
/**
* 调度器信息
* @property name 名称,不唯一
* @property startTime 第一次拉取任务的时间
* @property status 状态,可能的值: active inactive dead
* @property checkInterval 心跳间隔,单位:秒
* @property lastHeartbeatTime 最后一次心跳时间,当前时间大于 [lastHeartbeatTime]+3*[checkInterval] 时调度器状态变为 dead
*/
class SchedulerInfo(map: Map<String, Any?>) {
var id: Int
var name: String
var startTime: LocalDateTime
var status: String
var checkInterval: Int
var lastHeartbeatTime: LocalDateTime
init {
id = map["id"] as Int
name = map["name"] as String
startTime = map["start_time"] as LocalDateTime
status = map["status"] as String
checkInterval = map["check_interval"] as Int
lastHeartbeatTime = map["last_heartbeat_time"] as LocalDateTime
}
}
/**
* 任务信息
* @property planId 所属计划id
* @property schedulerId 执行该任务的调度器id
* @property startTime 任务开始时间
* @property endTime 任务结束时间
* @property actionName 动作名称
* @property initData 初始数据,任务创建时从计划的 [PlanInfo.planData] 字段复制
* @property status 状态,可能的值: start stop error timeout
* @property timeoutTime 超时时间
* @property errorMsg 错误信息
*/
class TaskInfo(map: Map<String, Any?>) {
var id: Int
var planId: Int
var schedulerId: Int
var startTime: LocalDateTime
var endTime: LocalDateTime?
var actionName: String
var initData: String?
var status: String
var timeoutTime: LocalDateTime
var errorMsg: String?
init {
id = map["id"] as Int
planId = map["plan_id"] as Int
schedulerId = map["scheduler_id"] as Int
startTime = map["start_time"] as LocalDateTime
endTime = map["end_time"] as LocalDateTime?
actionName = map["action_name"] as String
initData = map["init_data"] as String?
status = map["status"] as String
timeoutTime = map["timeout_time"] as LocalDateTime
errorMsg = map["error_msg"] as String?
}
}
| 0 | PLpgSQL | 0 | 1 | a0e4295354b7cd2261b06ca68fc2d7da0bd81449 | 5,524 | simple-scheduler | Apache License 2.0 |
app/src/main/java/com/example/studymate/admin/view/AdminUpdateQuiz.kt | junsheng526 | 764,777,873 | false | {"Kotlin": 211404} | package com.example.studymate.admin.view
import android.app.AlertDialog
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.studymate.R
import com.example.studymate.databinding.FragmentAdminUpdateQuizBinding
import com.example.studymate.model.data.Quiz
import com.example.studymate.utility.errorDialog
import com.example.studymate.viewmodel.QuizViewModel
import kotlinx.coroutines.launch
class AdminUpdateQuiz : Fragment() {
private lateinit var binding: FragmentAdminUpdateQuizBinding
private val nav by lazy { findNavController() }
private val quizVM: QuizViewModel by activityViewModels()
private val id by lazy { arguments?.getString("quizId") ?: ""}
private var quizList: List<Quiz> = emptyList()
private var currentQuestionIndex = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = FragmentAdminUpdateQuizBinding.inflate(inflater, container, false)
reset()
binding.btnUpdQuizPrevious.setOnClickListener { navigateToPreviousQuestion() }
binding.btnUpdQuizNext.setOnClickListener { navigateToNextQuestion() }
binding.btnUpdQuizEdit.setOnClickListener { submit() }
binding.btnQuizDelete.setOnClickListener { delete() }
quizVM.getQuizLD().observe(viewLifecycleOwner) { quizzes ->
quizList = quizzes
updateUIForCurrentQuestionById()
}
return binding.root
}
private fun navigateToPreviousQuestion(){
if (currentQuestionIndex > 0) {
currentQuestionIndex--
updateUIForCurrentQuestion()
} else {
Toast.makeText(requireContext(), "This is the first question", Toast.LENGTH_SHORT).show()
}
}
private fun navigateToNextQuestion(){
if (currentQuestionIndex < quizList.size - 1) {
currentQuestionIndex++
updateUIForCurrentQuestion()
} else {
Toast.makeText(requireContext(), "This is the last question", Toast.LENGTH_SHORT).show()
}
}
private fun updateUIForCurrentQuestionById() {
val currentQuestion = quizList.find { it.id == id }
if (currentQuestion != null) {
currentQuestionIndex = quizList.indexOf(currentQuestion)
updateUIForCurrentQuestion()
}
}
private fun updateUIForCurrentQuestion() {
val currentQuiz = quizList[currentQuestionIndex]
binding.edtUpdQuizQues.setText(currentQuiz.question)
binding.edtUpdQuizA.setText(currentQuiz.optionA)
binding.edtUpdQuizB.setText(currentQuiz.optionB)
binding.edtUpdQuizC.setText(currentQuiz.optionC)
binding.edtUpdQuizD.setText(currentQuiz.optionD)
when (currentQuiz.correctAnswer) {
1 -> binding.rgpUpdQuiz.check(R.id.rdbUpdQuizA)
2 -> binding.rgpUpdQuiz.check(R.id.rdbUpdQuizB)
3 -> binding.rgpUpdQuiz.check(R.id.rdbUpdQuizC)
4 -> binding.rgpUpdQuiz.check(R.id.rdbUpdQuizD)
}
}
private fun reset() {
lifecycleScope.launch {
val q = quizVM.get(id)
if (q == null) {
nav.navigateUp()
return@launch
}
currentQuestionIndex = quizList.indexOf(q)
updateUIForCurrentQuestion()
}
}
private fun submit() {
val quiz = Quiz (
id = id,
question = binding.edtUpdQuizQues.text.toString().trim(),
optionA = binding.edtUpdQuizA.text.toString().trim(),
optionB = binding.edtUpdQuizB.text.toString().trim(),
optionC = binding.edtUpdQuizC.text.toString().trim(),
optionD = binding.edtUpdQuizD.text.toString().trim(),
correctAnswer = getCorrectAnswer()
)
val err = quizVM.validate(quiz)
if (err != "") {
errorDialog(err)
return
}
quizVM.update(quiz) {
// Show a success message here
Toast.makeText(requireContext(), "Quiz updated successfully", Toast.LENGTH_SHORT).show()
nav.navigateUp()
}
}
private fun delete() {
// Build the confirmation dialog
AlertDialog.Builder(requireContext())
.setTitle("Confirmation")
.setMessage("Are you sure you want to delete this study resource?")
.setPositiveButton("Delete") { dialog, _ ->
dialog.dismiss()
performDelete()
}
.setNegativeButton("Cancel") { dialog, _ ->23
dialog.dismiss()
}
.show()
}
private fun performDelete() {
quizVM.delete(id)
Toast.makeText(requireContext(), "Delete successfully", Toast.LENGTH_SHORT).show()
nav.navigateUp()
}
private fun getCorrectAnswer(): Int {
return when (binding.rgpUpdQuiz.checkedRadioButtonId) {
R.id.rdbUpdQuizA -> 1
R.id.rdbUpdQuizB -> 2
R.id.rdbUpdQuizC -> 3
R.id.rdbUpdQuizD -> 4
else -> -1
}
}
} | 0 | Kotlin | 0 | 0 | a472006de01c4865dd598bc9340deb84ea34aece | 5,425 | StudyMate | MIT License |
compose/src/main/kotlin/app/MindOverCNCLathe.kt | 85vmh | 543,628,296 | false | null | import androidx.compose.runtime.Composable
import cafe.adriel.voyager.navigator.tab.CurrentTab
import cafe.adriel.voyager.navigator.tab.TabNavigator
import ui.tab.ManualTab
@Composable
fun MindOverCNCLathe() {
TabNavigator(ManualTab) {
CurrentTab()
}
} | 0 | Kotlin | 1 | 2 | 27286c192bd29226d4103311d42384cea31bcf90 | 269 | mindovercnclathe | Apache License 2.0 |
user/repository/src/main/kotlin/com/gongsung/user/ConnectionRequestRepository.kt | 403-gallery-gongsung | 736,332,935 | false | {"Kotlin": 84837} | package com.gongsung.user
import com.gongsung.user.entity.ConnectionRequestEntity
import com.gongsung.user.enums.ConnectionRequestStatus
import com.gongsung.user.persist.connection.ConnectionRequestCommandPersist
import com.gongsung.user.persist.connection.ConnectionRequestQueryPersist
import org.springframework.stereotype.Repository
@Repository
class ConnectionRequestRepository(
private val jpaConnectionRequestRepository: JpaConnectionRequestRepository,
) : ConnectionRequestCommandPersist, ConnectionRequestQueryPersist {
override fun create(connectionRequestProps: ConnectionRequestProps): ConnectionRequest {
return jpaConnectionRequestRepository.save(
ConnectionRequestEntity.ofProps(
connectionRequestProps,
),
)
}
override fun update(connectionRequestProps: ConnectionRequestProps): ConnectionRequest {
getByFromUserIdAndToUserId(
UserIdentity.of(connectionRequestProps.fromUserId),
UserIdentity.of(connectionRequestProps.toUserId),
)?.let {
return jpaConnectionRequestRepository.save(
it.copy(
status = connectionRequestProps.status,
),
)
}
?: throw IllegalArgumentException("${connectionRequestProps.fromUserId} - ${connectionRequestProps.toUserId} Connection not found")
}
override fun getAllByUserId(userIdentity: UserIdentity, status: ConnectionRequestStatus): List<ConnectionRequest> {
return jpaConnectionRequestRepository.findAllByFromUserIdAndStatus(
userIdentity.userIdentity,
status,
)
}
override fun getByFromUserIdAndToUserId(
fromUserIdentity: UserIdentity,
toUserIdentity: UserIdentity,
): ConnectionRequestEntity? {
return jpaConnectionRequestRepository.findByFromUserIdAndToUserId(
fromUserIdentity.userIdentity,
toUserIdentity.userIdentity,
) ?: jpaConnectionRequestRepository.findByFromUserIdAndToUserId(
toUserIdentity.userIdentity,
fromUserIdentity.userIdentity,
)
}
}
| 15 | Kotlin | 0 | 1 | 8f709c4dd8bddbfd07f5ed1c6edcc447f00babc9 | 2,166 | meet-in | Apache License 2.0 |
app/src/main/java/com/example/ruslanyussupov/popularmovies/data/local/MovieDb.kt | ruslanyussupov | 122,436,627 | false | null | package com.example.ruslanyussupov.popularmovies.data.local
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.ruslanyussupov.popularmovies.data.model.*
@Database(entities = [Movie::class, Review::class, Video::class,
Popular::class, TopRated::class, Favorite::class],
version = 1, exportSchema = false)
abstract class MovieDb : RoomDatabase() {
abstract fun movieDao(): MovieDao
abstract fun videoDao(): VideoDao
abstract fun reviewDao(): ReviewDao
}
| 0 | Kotlin | 0 | 0 | 612674df598a86889a451f285c6aef9105838771 | 512 | popular-movies | MIT License |
Data/src/main/java/com/sdk/data/model/mapper/UserModelMapper.kt | inplayer-org | 161,477,099 | false | null | package com.sdk.data.model.mapper
import com.sdk.data.model.account.InPlayerAccount
import com.sdk.domain.entity.account.AccountType
import com.sdk.domain.entity.account.InPlayerDomainUser
class UserModelMapper : ModelMapper<InPlayerAccount, InPlayerDomainUser> {
override fun mapFromModel(model: InPlayerAccount): InPlayerDomainUser {
//Creating the list for Account Type from the returned string
val accountTypeList = mutableListOf<AccountType>()
return InPlayerDomainUser(
id = model.id,
email = model.email,
fullName = model.fullName,
referrer = model.referrer,
isCompleted = model.isCompleted,
createdAt = model.createdAt,
updatedAt = model.updatedAt,
roles = model.roles,
metadata = model.metadata,
merchantId = model.merchantId,
merchantUUID = model.merchantUUID,
username = model.username,
uuid = model.uuid)
}
override fun mapToModel(entity: InPlayerDomainUser): InPlayerAccount {
//Creating the list for Account Type from the returned string
val accountTypeList = mutableListOf<String>()
entity.roles.forEach {
accountTypeList.add(it.toString())
}
return InPlayerAccount(id = entity.id,
email = entity.email,
fullName = entity.fullName,
referrer = entity.referrer,
roles = accountTypeList,
isCompleted = entity.isCompleted,
createdAt = entity.createdAt,
updatedAt = entity.updatedAt,
metadata = entity.metadata,
merchantId = entity.merchantId,
merchantUUID = entity.merchantUUID,
username = entity.username,
uuid = entity.uuid)
}
} | 2 | null | 1 | 5 | d11faf61aee6e75a1be8bccb63c17e257282725b | 1,991 | inplayer-android-sdk | MIT License |
app/src/main/java/rio/arj/kumparantechtestrioarjuna/ui/detail/DetailActivity.kt | Rarj | 387,109,213 | false | null | package rio.arj.kumparantechtestrioarjuna.ui.detail
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import rio.arj.kumparantechtestrioarjuna.R
import rio.arj.kumparantechtestrioarjuna.data.repository.comment.model.CommentResponse
import rio.arj.kumparantechtestrioarjuna.data.repository.posts.model.PostDetail
import rio.arj.kumparantechtestrioarjuna.databinding.ActivityDetailBinding
import rio.arj.kumparantechtestrioarjuna.ui.detailuser.DetailUserActivity
class DetailActivity : AppCompatActivity() {
private val postDetailIntent: PostDetail by lazy {
intent.getParcelableExtra<PostDetail>("POST_DETAIL_KEY")
?: throw RuntimeException("${PostDetail::class.java.name} must be not null")
}
private val detailViewModel by viewModel<DetailViewModel>()
private lateinit var binding: ActivityDetailBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_detail)
binding.viewModel = detailViewModel
binding.lifecycleOwner = this
binding.title = postDetailIntent.title
binding.body = postDetailIntent.body
loadDetail()
listener()
}
private fun loadDetail() {
detailViewModel.viewModelScope.launch {
detailViewModel.getDetailUser(postDetailIntent.userId)
.collect { binding.textName.text = it.username }
detailViewModel.getComments(postDetailIntent.id)
.collect { setupCommentUi(it) }
}
}
private fun setupCommentUi(it: CommentResponse) {
val detailCommentAdapter = DetailCommentAdapter(it)
binding.recyclerComments.apply {
layoutManager = LinearLayoutManager(this@DetailActivity)
adapter = detailCommentAdapter
}
}
private fun listener() {
binding.toolbar.setNavigationOnClickListener { finish() }
binding.textName.setOnClickListener {
val intent = Intent(this, DetailUserActivity::class.java)
intent.putExtra("USER_ID_KEY", postDetailIntent.userId)
startActivity(intent)
}
}
} | 0 | Kotlin | 0 | 0 | c3f1831c706fd8164cbc13cb553faccb935bb51c | 2,371 | TypiCodeRio | MIT License |
library/src/main/kotlin/ru/dimsuz/vanilla/Combinators.kt | dimsuz | 284,305,456 | false | null | package ru.dimsuz.vanilla
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok
import com.github.michaelbull.result.andThen
import com.github.michaelbull.result.map
import com.github.michaelbull.result.mapError
fun <I, O, E> buildValidator(
body: ValidatorComposer<I, E>.() -> StartedValidatorComposer<I, O, E>,
): Validator<I, O, E> {
return body(SimpleValidatorComposer()).build()
}
// TODO document that for writing validators only, because inference problems, use compose in rules
fun <I, O1, O2, E> Validator<I, O1, E>.andThen(other: Validator<O1, O2, E>): Validator<I, O2, E> {
return Validator { input -> this.validate(input).andThen { other.validate(it) } }
}
fun <I, O1, O2, E> Validator<I, O1, E>.map(mapper: (O1) -> O2): Validator<I, O2, E> {
return Validator { input -> this.validate(input).map(mapper) }
}
fun <I, O, E1, E2> Validator<I, O, E1>.mapError(map: (E1) -> E2): Validator<I, O, E2> {
return Validator { input -> this.validate(input).mapError { errors -> errors.map(map) } }
}
// TODO when documenting, mention that outputs are ignored, only Ok/Error matters
fun <I, E> satisfiesAnyOf(validators: Iterable<Validator<I, *, E>>): Validator<I, I, E> {
require(validators.iterator().hasNext()) { "validator list is empty" }
return Validator { input ->
val errors = mutableListOf<E>()
for (v in validators) {
when (val result = v.validate(input)) {
is Ok -> return@Validator Ok(input)
is Err -> {
errors.addAll(result.error)
}
}
}
Err(errors)
}
}
// TODO when documenting, mention that outputs are ignored, only Ok/Error matters
fun <I, E> satisfiesAllOf(validators: Iterable<Validator<I, *, E>>): Validator<I, I, E> {
require(validators.iterator().hasNext()) { "validator list is empty" }
return Validator { input ->
val errors = mutableListOf<E>()
for (v in validators) {
when (val result = v.validate(input)) {
is Ok -> continue
is Err -> {
errors.addAll(result.error)
}
}
}
if (errors.isEmpty()) Ok(input) else Err(errors)
}
}
| 3 | Kotlin | 0 | 31 | ea42f6fb6c8b40b0e8ed94cf45958c4ac4de59f9 | 2,129 | vanilla | MIT License |
base/processor-base-test/src/main/resources/com/spirytusz/booster/bean/ClassWithInvisibleGetterSetterFields.kt | spirytusz | 392,160,927 | false | null | package com.spirytusz.booster.bean
import com.spirytusz.booster.annotation.Boost
@Boost
class ClassWithInvisibleGetterSetterFields {
val stringValue: String = ""
} | 1 | Kotlin | 4 | 27 | e2ede7bcece69832ae0267d1a34c4c6f2fdaac09 | 170 | GsonBooster | MIT License |
base/processor-base-test/src/main/resources/com/spirytusz/booster/bean/ClassWithInvisibleGetterSetterFields.kt | spirytusz | 392,160,927 | false | null | package com.spirytusz.booster.bean
import com.spirytusz.booster.annotation.Boost
@Boost
class ClassWithInvisibleGetterSetterFields {
val stringValue: String = ""
} | 1 | Kotlin | 4 | 27 | e2ede7bcece69832ae0267d1a34c4c6f2fdaac09 | 170 | GsonBooster | MIT License |
kittybot/src/main/kotlin/org/bezsahara/kittybot/telegram/client/Results.kt | bezsahara | 846,146,531 | false | {"Kotlin": 752625} | package org.bezsahara.kittybot.telegram.client
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
internal data class Ok<T>(
val ok: Boolean,
@JvmField val result: T,
val description: String? = null
)
@Serializable
data class TelegramError(
// ok should always be false
val ok: Boolean,
@SerialName("error_code") val errorCode: Int,
val description: String
) {
companion object {
val none = TelegramError(ok = false, errorCode = -1, description = "")
}
} | 0 | Kotlin | 1 | 5 | a0b831c9f4ad00f681b2bfba5376e321766a8cfe | 546 | TelegramKitty | MIT License |
app/src/main/java/pl/dawidfiruzek/analyticshelper/AnalyticsHelper.kt | dawidfiruzek | 126,237,548 | false | null | package pl.dawidfiruzek.analyticshelper
interface AnalyticsHelper : Analytics
| 0 | Kotlin | 0 | 3 | 5920cff362d81ba55a211d0ccd6a49acd405d3c0 | 79 | analytics-helper | Apache License 2.0 |
libnavui-tripprogress/src/main/java/com/mapbox/navigation/ui/tripprogress/model/EstimatedTimeToArrivalFormatter.kt | mapbox | 87,455,763 | false | {"Kotlin": 9692008, "Python": 65081, "Java": 36829, "HTML": 17811, "Makefile": 9840, "Shell": 7129} | package com.mapbox.navigation.tripdata.progress.model
import android.content.Context
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.format.DateFormat
import android.text.style.StyleSpan
import com.mapbox.navigation.base.TimeFormat
import com.mapbox.navigation.base.internal.time.TimeFormatter.formatTime
import com.mapbox.navigation.ui.base.formatter.ValueFormatter
import java.util.Calendar
/**
* Formats trip related data for displaying in the UI
*
* @param context an application context instance
* @param timeFormatType a value indicating whether the time should be formatted in 12 or 24 hour
* format
*/
class EstimatedTimeToArrivalFormatter(
context: Context,
@TimeFormat.Type private val timeFormatType: Int = TimeFormat.NONE_SPECIFIED,
) : ValueFormatter<Long, SpannableString> {
private val appContext: Context = context.applicationContext
/**
* Formats an update to a [SpannableString] representing the estimated time to arrival
*
* @param update represents the estimated time to arrival value
* @return a formatted string
*/
override fun format(update: Long): SpannableString {
val is24HourFormat = DateFormat.is24HourFormat(appContext)
val etaAsCalendar = Calendar.getInstance().also {
it.timeInMillis = update
}
return SpannableString(formatTime(etaAsCalendar, timeFormatType, is24HourFormat))
.also { spannableString ->
val spaceIndex = spannableString.indexOfFirst { it == ' ' }
if (spaceIndex > 0) {
spannableString.setSpan(
StyleSpan(Typeface.BOLD),
0,
spaceIndex,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
)
}
}
}
}
| 508 | Kotlin | 319 | 621 | ad73c6011348cb9b24b92a369024ca06f48845ab | 1,912 | mapbox-navigation-android | Apache License 2.0 |
app/src/main/java/com/wavesplatform/wallet/v2/ui/home/quick_action/send/fee/SponsoredFeeDetailsPresenter.kt | bianxiang | 203,493,752 | false | null | /*
* Created by Eduard Zaydel on 1/4/2019
* Copyright © 2019 Waves Platform. All rights reserved.
*/
package com.wavesplatform.wallet.v2.ui.home.quick_action.send.fee
import com.arellomobile.mvp.InjectViewState
import com.wavesplatform.sdk.crypto.WavesCrypto
import com.wavesplatform.sdk.crypto.WavesCrypto.Companion.addressFromPublicKey
import com.wavesplatform.sdk.model.response.node.AssetBalanceResponse
import com.wavesplatform.wallet.v2.data.Constants
import com.wavesplatform.wallet.v2.data.model.local.SponsoredAssetItem
import com.wavesplatform.sdk.model.response.matcher.MatcherSettingsResponse
import com.wavesplatform.sdk.model.response.node.AssetsDetailsResponse
import com.wavesplatform.sdk.model.response.node.ScriptInfoResponse
import com.wavesplatform.sdk.utils.*
import com.wavesplatform.wallet.v2.ui.base.presenter.BasePresenter
import com.wavesplatform.wallet.v2.util.EnvironmentManager
import com.wavesplatform.wallet.v2.util.WavesWallet
import io.reactivex.Observable
import javax.inject.Inject
import kotlin.math.ceil
@InjectViewState
class SponsoredFeeDetailsPresenter @Inject constructor() : BasePresenter<SponsoredFeeDetailsView>() {
var wavesFee: Long = WavesConstants.WAVES_MIN_FEE
fun loadSponsoredAssets(listener: (MutableList<SponsoredAssetItem>) -> Unit) {
addSubscription(
nodeServiceManager.assetsBalances()
.flatMapIterable { it }
.filter { it.isSponsored() || it.isWaves() }
.map {
val fee = getFee(it)
val isActive = isValidBalanceForSponsoring(it, fee)
return@map SponsoredAssetItem(it, fee, isActive)
}
.toList()
.map {
it.sortedByDescending { it.isActive }.toMutableList()
}
.compose(RxUtil.applySingleDefaultSchedulers())
.subscribe({
listener.invoke(it)
}, {
it.printStackTrace()
viewState.showNetworkError()
}))
}
fun loadExchangeCommission(amountAssetId: String?,
priceAssetId: String?,
listener: (MutableList<SponsoredAssetItem>) -> Unit) {
viewState.showProgressBar(true)
wavesFee = WavesConstants.WAVES_ORDER_MIN_FEE
var addressMatcherScripted = false
var amountAssetScripted = false
var priceAssetScripted = false
addSubscription(matcherServiceManager.getMatcherKey()
.flatMap { matcherPublicKey ->
Observable.zip(
nodeServiceManager.scriptAddressInfo(
addressFromPublicKey(WavesCrypto.base58decode(
matcherPublicKey.replace("\"", "")),
EnvironmentManager.netCode)),
nodeServiceManager.assetDetails(amountAssetId),
nodeServiceManager.assetDetails(priceAssetId),
io.reactivex.functions.Function3 { addressMatcherScripted: ScriptInfoResponse,
amountAssetDetails: AssetsDetailsResponse,
priceAssetDetails: AssetsDetailsResponse ->
return@Function3 Triple(
addressMatcherScripted, amountAssetDetails, priceAssetDetails)
})
}
.flatMap { detailsInfoTriple ->
addressMatcherScripted = detailsInfoTriple.first.extraFee != 0L
amountAssetScripted = detailsInfoTriple.second.scripted
priceAssetScripted = detailsInfoTriple.third.scripted
Observable.zip(
matcherServiceManager.getSettings(),
matcherServiceManager.getSettingsRates(),
nodeServiceManager.assetsBalances(),
io.reactivex.functions.Function3 { settings: MatcherSettingsResponse,
rates: MutableMap<String, Double>,
balances: MutableList<AssetBalanceResponse> ->
return@Function3 Triple(settings, rates, balances)
})
}
.compose(RxUtil.applyObservableDefaultSchedulers())
.subscribe({ triple ->
val matcherSettings = triple.first
val settingsRates = triple.second
val assets = triple.third
val sponsoredAssetItems = mutableListOf<SponsoredAssetItem>()
settingsRates.forEach { (assetId, rate) ->
val assetIdWavesChecked = if (assetId.isWaves()) {
WavesConstants.WAVES_ASSET_ID_EMPTY
} else {
assetId
}
val assetBalance = assets.find { it.assetId == assetIdWavesChecked }
assetBalance.notNull { matcherFeeAssetBalance ->
val executedScripts = executedScripts(
matcherFeeAssetBalance.isScripted(),
addressMatcherScripted,
amountAssetScripted,
priceAssetScripted)
val baseFee = matcherSettings.orderFee[MatcherSettingsResponse.DYNAMIC]?.baseFee!!
val minFee = countMinFee(rate, baseFee, executedScripts)
if (minFee < matcherFeeAssetBalance.balance ?: 0) {
sponsoredAssetItems.add(SponsoredAssetItem(
matcherFeeAssetBalance,
MoneyUtil.getScaledText(
minFee,
matcherFeeAssetBalance.getDecimals()).stripZeros(),
true))
}
}
}
listener.invoke(sponsoredAssetItems)
viewState.showProgressBar(false)
}, {
it.printStackTrace()
viewState.showNetworkError()
}))
}
private fun executedScripts(matcherFeeAssetScripted: Boolean,
matcherAddressScripted: Boolean,
amountAssetScripted: Boolean,
priceAssetScripted: Boolean): Int {
var executedScripts = 0
if (matcherFeeAssetScripted) {
executedScripts++
}
if (matcherAddressScripted) {
executedScripts++
}
if (amountAssetScripted) {
executedScripts++
}
if (priceAssetScripted) {
executedScripts++
}
return executedScripts
}
private fun countMinFee(rate: Double, baseFee: Long, executedScripts: Int): Long {
return ceil(rate * (baseFee + 400_000 * executedScripts)).toLong()
}
private fun isValidBalanceForSponsoring(item: AssetBalanceResponse, fee: String): Boolean {
val sponsorBalance = MoneyUtil.getScaledText(
item.getSponsorBalance(),
WavesConstants.WAVES_ASSET_INFO.precision)
.clearBalance().toBigDecimal()
val feeDecimalValue = fee.clearBalance().toBigDecimal()
val availableBalance = MoneyUtil.getScaledText(
item.getAvailableBalance(), item.getDecimals()).clearBalance().toBigDecimal()
return ((sponsorBalance >= Constants.MIN_WAVES_SPONSORED_BALANCE.toBigDecimal()
&& availableBalance >= feeDecimalValue)
|| (sponsorBalance >= MoneyUtil.getScaledText(
wavesFee, WavesConstants.WAVES_ASSET_INFO.precision)
.clearBalance()
.toBigDecimal()
&& availableBalance >= feeDecimalValue
&& item.isMyWavesToken(WavesWallet.getAddress()))
|| item.isWaves())
}
private fun getFee(item: AssetBalanceResponse): String {
return if (item.isWaves()) {
MoneyUtil.getScaledText(wavesFee, WavesConstants.WAVES_ASSET_INFO.precision).stripZeros()
} else {
calculateFeeForSponsoredAsset(item).stripZeros()
}
}
private fun calculateFeeForSponsoredAsset(item: AssetBalanceResponse): String {
val sponsorFee = MoneyUtil.getScaledText(item.minSponsoredAssetFee, item)
.clearBalance().toBigDecimal()
val value = ((MoneyUtil.getScaledText(wavesFee, WavesConstants.WAVES_ASSET_INFO.precision)
.clearBalance().toBigDecimal() /
MoneyUtil.getScaledText(WavesConstants.WAVES_MIN_FEE, WavesConstants.WAVES_ASSET_INFO.precision)
.clearBalance().toBigDecimal()) * sponsorFee)
return value.toPlainString()
}
}
| 0 | Kotlin | 1 | 0 | 246deb7760d30383f59391bb38acc7bbc3f9931c | 9,652 | WavesWallet-Android-FirebaseRemoved | MIT License |
GcbApplication/module_me/src/main/java/com/gocashback/module_me/adapter/MyGiftCardAdapter.kt | ybx945ybx | 247,870,704 | false | null | package com.gocashback.module_me.adapter
import android.app.Activity
import android.os.CountDownTimer
import android.support.constraint.ConstraintLayout
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.gocashback.lib_common.network.model.user.UserGiftCardItemModel
import com.gocashback.lib_common.utils.moneyFormat
import com.gocashback.module_me.R
/**
* @Author 55HAITAO
* @Date 2019-06-15 15:11
*/
class MyGiftCardAdapter(private val activity: Activity?, list: List<UserGiftCardItemModel>) : BaseQuickAdapter<UserGiftCardItemModel, BaseViewHolder>(R.layout.item_my_gift_card, list) {
private var countList = arrayListOf<TimerCountDown>()
override fun convert(helper: BaseViewHolder, item: UserGiftCardItemModel) {
with(item) {
helper.setText(R.id.tv_gift_cards_store, brand_name)
.setText(R.id.tv_amount_bonus, moneyFormat(amount_bonus))
.setText(R.id.tv_reward_name, reward_name)
.setText(R.id.tv_add_time, activity?.resources?.getString(R.string.gift_cards_date) + " " + add_time)
.setGone(R.id.tv_gift_cards_resend, is_available == 0)
.setVisible(R.id.iv_gift_card_spent, is_available != 0)
.setText(R.id.tv_gift_cards_resend, time)
.addOnClickListener(R.id.tv_mark_as_spent)
.addOnClickListener(R.id.tv_gift_cards_resend)
helper.getView<TextView>(R.id.tv_mark_as_spent).isEnabled = is_available == 0
helper.getView<ConstraintLayout>(R.id.clyt_content).isEnabled = is_available == 0
helper.getView<TextView>(R.id.tv_amount_bonus).isEnabled = is_available == 0
helper.getView<TextView>(R.id.tv_reward_name).isEnabled = is_available == 0
helper.getView<TextView>(R.id.tv_add_time).isEnabled = is_available == 0
}
}
fun startCount(position: Int) {
val mCountDownTimer = TimerCountDown((60 * 2000).toLong(), 1000, position)
mCountDownTimer.start()
countList.add(mCountDownTimer)
}
fun removeAllCount() {
countList.forEach { it.cancel() }
}
internal inner class TimerCountDown(millisInFuture: Long, countDownInterval: Long, val position: Int) : CountDownTimer(millisInFuture, countDownInterval) {
override fun onTick(millisUntilFinished: Long) {
data[position].apply {
isOnCount = true
time = "" + millisUntilFinished / 1000 + "s"
}
notifyItemChanged(position)
}
override fun onFinish() {
data[position].apply {
isOnCount = false
time = activity?.getString(R.string.gift_cards_resend) ?: ""
}
notifyItemChanged(position)
// get_code.text = resources.getString(R.string.verify_mail_get_code)
}
}
} | 0 | Kotlin | 0 | 0 | 0da5ca3b1dddcb8907d5bcc062722b4ad3ac3546 | 3,008 | gcb | Apache License 2.0 |
app/OutWait/app/src/androidTest/java/edu/kit/outwait/management/ManagementLoginTest.kt | OutWait | 398,042,615 | false | {"Kotlin": 725686} | package edu.kit.outwait.management
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.rules.activityScenarioRule
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import edu.kit.outwait.MainActivity
import edu.kit.outwait.R
import edu.kit.outwait.instituteRepository.InstituteRepository
import edu.kit.outwait.util.VALID_TEST_PASSWORD
import edu.kit.outwait.util.VALID_TEST_USERNAME
import edu.kit.outwait.utils.EspressoIdlingResource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import javax.inject.Inject
@HiltAndroidTest
class ManagementLoginTest {
@get:Rule(order = 0)
var hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1)
var openActivityRule = activityScenarioRule<MainActivity>()
@Inject
lateinit var instituteRepo: InstituteRepository
@Before
fun registerIdlingResource() {
hiltRule.inject()
IdlingRegistry.getInstance().register(EspressoIdlingResource.countingIdlingResource)
}
//T1
@Test
fun loginSuccessfully() {
//Input of correct login data
onView(withId(R.id.etInstituteName))
.perform(
ViewActions.typeText(VALID_TEST_USERNAME),
ViewActions.closeSoftKeyboard()
)
onView(withId(R.id.etInstitutePassword))
.perform(
ViewActions.typeText(VALID_TEST_PASSWORD),
ViewActions.closeSoftKeyboard()
)
onView(withId(R.id.btnLoginFrag)).perform(click())
//Verify of forwarding
onView(withId(R.id.floatingActionButton))
.check(matches(isDisplayed()))
onView(withId(R.id.config)).check(matches(isDisplayed()))
}
@After
fun unregisterIdlingResource() {
CoroutineScope(Dispatchers.Main).launch {
instituteRepo.logout()
}
IdlingRegistry.getInstance().unregister(EspressoIdlingResource.countingIdlingResource)
openActivityRule.scenario.close()
}
}
| 0 | Kotlin | 0 | 1 | d3b878b82294899006b21a91f48877aa555eee6e | 2,532 | OutWait | MIT License |
core/src/commonMain/kotlin/dev/brella/ktornea/spotify/data/albums/SpotifySimplifiedArtist.kt | UnderMybrella | 628,495,061 | false | null | package dev.brella.ktornea.spotify.data.albums
import dev.brella.ktornea.spotify.data.tracks.SpotifyExternalUrls
import dev.brella.ktornea.spotify.data.types.EnumSpotifyArtistType
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
public data class SpotifySimplifiedArtist(
@SerialName("external_urls")
val externalUrls: SpotifyExternalUrls,
val href: String,
val id: String,
val name: String,
@Suppress("SERIALIZER_TYPE_INCOMPATIBLE")
val type: EnumSpotifyArtistType,
val uri: String,
) | 0 | Kotlin | 0 | 1 | 78d5c2e9eb88740719a9baa947440369735fb945 | 571 | ktornea-spotify | MIT License |
src/main/kotlin/unsigned/Uint.kt | MaTriXy | 130,805,370 | true | {"Kotlin": 62013, "Batchfile": 126, "Shell": 82} | package unsigned
import unsigned.java_1_7.compareUnsigned
import unsigned.java_1_7.divideUnsigned
import unsigned.java_1_7.parseUnsignedInt
import unsigned.java_1_7.remainderUnsigned
import java.math.BigInteger
/**
* Created by GBarbieri on 20.03.2017.
*/
data class Uint(var v: Int = 0) : Number() {
companion object {
/** A constant holding the minimum value an <code>unsigned int</code> can have, 0. */
const val MIN_VALUE = 0x00000000
/** A constant holding the maximum value an <code>unsigned int</code> can have, 2<sup>32</sup>-1. */
const val MAX_VALUE = 0xffffffffL
fun checkSigned(v: Number) = v.toLong() in MIN_VALUE..MAX_VALUE
}
constructor(number: Number) : this(number.toInt())
@JvmOverloads constructor(string: String, base: Int = 10) : this(string.filter { it != '_' && it != '\'' }.parseUnsignedInt(base))
override fun toByte() = v.toByte()
override fun toShort() = v.toShort()
override fun toInt() = v
override fun toLong() = v.toULong()
fun toBigInt(): BigInteger = BigInteger.valueOf(toLong())
override fun toDouble() = toLong().toDouble()
override fun toFloat() = toLong().toFloat()
override fun toChar() = v.toChar()
operator fun inc() = Uint(v + 1)
operator fun dec() = Uint(v - 1)
infix operator fun plus(b: Uint) = Uint(v + b.v)
infix operator fun plus(b: Int) = Uint(v + b)
infix operator fun minus(b: Uint) = Uint(v - b.v)
infix operator fun minus(b: Int) = Uint(v - b)
infix operator fun times(b: Uint) = Uint(v * b.v)
infix operator fun times(b: Int) = Uint(v * b)
infix operator fun div(b: Uint) = Uint(v divideUnsigned b.toInt())
infix operator fun div(b: Int) = Uint(v divideUnsigned b)
infix operator fun rem(b: Uint) = Uint(v remainderUnsigned b.toInt())
infix operator fun rem(b: Int) = Uint(v remainderUnsigned b)
infix fun and(b: Uint) = Uint(v and b.toInt())
infix fun and(b: Int) = Uint(v and b)
infix fun or(b: Uint) = Uint(v or b.toInt())
infix fun or(b: Int) = Uint(v or b)
infix fun xor(b: Uint) = Uint(v xor b.toInt())
infix fun xor(b: Int) = Uint(v xor b)
infix fun shl(b: Uint) = Uint(v shl b.toInt())
infix fun shl(b: Int) = Uint(v shl b)
infix fun shr(b: Uint) = Uint(v ushr b.toInt())
infix fun shr(b: Int) = Uint(v ushr b)
fun inv() = Uint(v.inv())
operator fun compareTo(b: Uint) = v compareUnsigned b.toInt()
operator fun compareTo(b: Int) = v compareUnsigned b
override fun toString() = toLong().toString()
// TODO long?
} | 0 | Kotlin | 0 | 0 | 6bd09d140679e806b19977a86fc21db13a4342e7 | 2,603 | kotlin-unsigned | MIT License |
player/src/main/java/com/tomasznajda/pulpfiction/event/player/PlayerObservable.kt | tomasznajda | 141,139,295 | false | {"Kotlin": 112181} | package com.tomasznajda.pulpfiction.event.player
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.tomasznajda.pulpfiction.entity.PlayerState
import com.tomasznajda.pulpfiction.event.analitics.AnalyticsEvent
import com.tomasznajda.pulpfiction.event.analitics.AnalyticsObservable
import com.tomasznajda.pulpfiction.event.analitics.PlayerStateChangedEvent
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.functions.Function
class PlayerObservable(exoPlayer: SimpleExoPlayer,
private var analytics: Observable<AnalyticsEvent> = AnalyticsObservable(exoPlayer))
: Observable<PlayerEvent>() {
override fun subscribeActual(observer: Observer<in PlayerEvent>) {
analytics
.filter { it is PlayerStateChangedEvent }
.map { it as PlayerStateChangedEvent }
.map { createPlayerInfo(it.playbackState, it.playWhenReady) }
.onErrorResumeNext(Function { Observable.empty() })
.subscribe(observer)
}
private fun createPlayerInfo(playbackState: Int, playWhenReady: Boolean) =
when (playbackState) {
Player.STATE_IDLE -> PlayerInfo(PlayerState.IDLE)
Player.STATE_BUFFERING -> PlayerInfo(PlayerState.BUFFERING)
Player.STATE_READY -> PlayerInfo(if (playWhenReady) PlayerState.PLAYING else PlayerState.PAUSED)
Player.STATE_ENDED -> PlayerInfo(PlayerState.FINISHED)
else -> throw IllegalArgumentException()
}
} | 0 | Kotlin | 1 | 4 | 43b4db0659929cff71018be9109eb2f3ff10dbfa | 1,610 | pulpfiction | Apache License 2.0 |
plugin-dotnet-common/src/main/kotlin/jetbrains/buildServer/dotnet/CoverageConstants.kt | JetBrains | 49,584,664 | false | null | /*
* Copyright 2000-2023 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.dotnet
import jetbrains.buildServer.ArtifactsConstants
import jetbrains.buildServer.coverage.agent.serviceMessage.CoverageServiceMessageSetup
import jetbrains.buildServer.dotNet.DotNetConstants
/**
* Coverage constants.
*/
object CoverageConstants {
const val PARAM_TYPE = "dotNetCoverage.tool"
const val COVERAGE_TYPE = "dotNetCoverageDotnetRunner"
const val COVERAGE_REPORT_HOME = ArtifactsConstants.TEAMCITY_ARTIFACTS_DIR + "/.NETCoverage"
const val COVERAGE_REPORT_MULTIPLE = "$COVERAGE_REPORT_HOME/results"
// Those constants are required to have Coverage tab added and THE PART OF CONTRACT
const val COVERAGE_HTML_REPORT_ZIP = "coverage.zip"
const val COVERAGE_PUBLISH_PATH_PARAM = "teamcity.agent.dotNetCoverage.publishPath"
// Those constants are required to publish well-known artifacts and THE PART OF CONTRACT
const val COVERAGE_REPORT_NAME = "CoverageReport"
const val COVERAGE_REPORT_EXT = ".xml"
// Specifies custom coverage report .html file name
const val COVERAGE_HTML_REPORT_INDEX_KEY = "dotNetCoverage.index"
// dotCover
const val PARAM_DOTCOVER = "dotcover"
const val PARAM_DOTCOVER_HOME = "dotNetCoverage.dotCover.home.path"
const val PARAM_DOTCOVER_FILTERS = "dotNetCoverage.dotCover.filters"
const val PARAM_DOTCOVER_ATTRIBUTE_FILTERS = "dotNetCoverage.dotCover.attributeFilters"
const val PARAM_DOTCOVER_ARGUMENTS = "dotNetCoverage.dotCover.customCmd"
const val PARAM_DOTCOVER_LOG_PATH = "teamcity.agent.dotCover.log"
const val TEAMCITY_DOTCOVER_HOME = "teamcity.dotCover.home"
const val DOTCOVER_ARTIFACTS_DIR = "artifacts"
const val DOTCOVER_PUBLISH_SNAPSHOT_PARAM = "teamcity.agent.dotCover.publishSnapshot"
const val DOTCOVER_SNAPSHOT_FILE_EXTENSION = ".dcvr"
const val DOTCOVER_SNAPSHOT_DCVR = "dotCover$DOTCOVER_SNAPSHOT_FILE_EXTENSION"
const val DOTCOVER_LOGS = "dotCoverLogs.zip"
const val DOTCOVER_EXECUTABLE = "dotCover.sh"
const val DOTCOVER_WINDOWS_EXECUTABLE = "dotCover.exe"
const val DOTCOVER_TOOL_NAME = "dotCover"
const val DOTCOVER_BUNDLED_TOOL_TYPE_ID = "JetBrains.dotCover.CommandLineTools"
const val DOTCOVER_BUNDLED_TOOL_VERSION_NAME = "bundled"
const val DOTCOVER_BUNDLED_TOOL_ID = "${DOTCOVER_BUNDLED_TOOL_TYPE_ID}.${DOTCOVER_BUNDLED_TOOL_VERSION_NAME}"
val DOTNET_FRAMEWORK_PATTERN_3_5 = DotNetConstants.DOTNET_FRAMEWORK_3_5.replace(".", "\\.") + "_.+|" + DotNetConstants.DOTNET_FRAMEWORK_4 + "\\.[\\d\\.]+_.+"
val DOTNET_FRAMEWORK_PATTERN_4_6_1 = DotNetConstants.DOTNET_FRAMEWORK_4 + "\\.(6\\.(?!0)|[7-9]|[\\d]{2,})[\\d\\.]*_.+"
class ServiceMessageSetup(setup: CoverageServiceMessageSetup) {
init {
setup.addPropertyMapping(
"dotcover_home",
PARAM_DOTCOVER_HOME
)
}
}
}
| 15 | Kotlin | 23 | 90 | 0852b0e89cf930c9c64547c6176d42527a54b9ab | 3,476 | teamcity-dotnet-plugin | Apache License 2.0 |
androidApp/src/main/java/app/trian/tudu/feature/auth/changePassword/StateEvent.kt | trianapp | 452,765,555 | false | {"Kotlin": 448664, "Shell": 1721, "Ruby": 1696} | package app.trian.tudu.feature.auth.changePassword
import android.os.Parcelable
import androidx.compose.runtime.Immutable
import kotlinx.parcelize.Parcelize
@Immutable
@Parcelize
data class ChangePasswordState(
val newPassword: String = "",
val confirmPassword: String = "",
val isLoading:Boolean=false
) : Parcelable
@Immutable
sealed class ChangePasswordEvent {
object Submit : ChangePasswordEvent()
} | 1 | Kotlin | 1 | 1 | 6ab45a3a808405ebcd67c286a1e960c1901922eb | 423 | tudu | Apache License 2.0 |
src/main/java/org/kotlin/action/KotlinBase-2-interface.kt | Laomedeia | 122,696,571 | true | {"Java": 801075, "Kotlin": 38473, "JavaScript": 8268} | package org.kotlin.action
/**
* 接口及接口方法定义
*/
interface Expr
class Num(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr
// eval写法1
//fun eval(e: Expr): Int {
// if (e is Num) {
// val n = e as Num
// return n.value
// }
// if (e is Sum) {
// return eval(e.left) + eval(e.right)
// }
// throw IllegalArgumentException("unknow expression")
//}
// eval写法2
//fun eval(e: Expr): Int =
// if (e is Num) {
// e.value
// } else if (e is Sum) {
// eval(e.left) + eval(e.right)
// } else {
// throw IllegalArgumentException("unknow expression")
// }
// eval写法2
fun eval(e: Expr): Int =
when (e) {
is Num -> e.value
is Sum -> eval(e.left) + eval(e.right)
else -> throw IllegalArgumentException("unknow expression")
} | 0 | Java | 0 | 0 | 0dcd8438e0846493ced9c1294ce686bac34c8614 | 884 | Java8InAction | MIT License |
chart/src/main/java/cn/jingzhuan/lib/chart3/data/dataset/MinuteLineDataSet.kt | JingZhuanDuoYing | 98,616,882 | false | {"Java": 629990, "Kotlin": 525864, "Shell": 101} | package cn.jingzhuan.lib.chart3.data.dataset
import cn.jingzhuan.lib.chart3.Viewport
import cn.jingzhuan.lib.chart3.data.value.LineValue
import kotlin.math.abs
import kotlin.math.max
class MinuteLineDataSet(
lineValues: List<LineValue>,
override var lastClose: Float,
private val highPrice: Float = 0f,
private val lowPrice: Float = 0f
) : LineDataSet(lineValues) {
override fun calcMinMax(viewport: Viewport) {
super.calcMinMax(viewport)
if (lastClose > 0) {
if (values.isNotEmpty()) {
if (!highPrice.isNaN() && !lowPrice.isNaN() && highPrice > 0.1f && lowPrice > 0.1f) {
viewportYMax = maxOf(highPrice, viewportYMax)
viewportYMin = minOf(lowPrice, viewportYMin)
}
var maxDiff = max(abs(viewportYMin - lastClose), abs(viewportYMax - lastClose))
maxDiff = max(lastClose * 0.01f, maxDiff)
viewportYMin = lastClose - maxDiff
viewportYMax = lastClose + maxDiff
} else {
viewportYMin = lastClose * 0.99f
viewportYMax = lastClose * 1.01f
}
}
}
} | 0 | Java | 102 | 784 | f82d4ef2408a4f59c02203c528668e31b645d5f7 | 1,201 | JZAndroidChart | Apache License 2.0 |
connekted-deploy/src/main/kotlin/io/github/cfraser/connekted/deploy/resource/operator/CustomResourceDefinition.kt | c-fraser | 420,198,834 | false | null | /*
Copyright 2021 c-fraser
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.github.cfraser.connekted.deploy.resource.operator
import io.fabric8.kubernetes.client.KubernetesClient
import io.github.cfraser.connekted.deploy.resource.ManagedResource
import io.github.cfraser.connekted.k8s.MessagingApplication
/** The [ManagedResource] implementation for the [MessagingApplication.customResourceDefinition]. */
internal object CustomResourceDefinition : ManagedResource {
/** Create or replace the [MessagingApplication.customResourceDefinition]. */
override fun create(kubernetesClient: KubernetesClient) {
kubernetesClient
.apiextensions()
.v1()
.customResourceDefinitions()
.createOrReplace(MessagingApplication.customResourceDefinition)
}
/** Delete the [MessagingApplication.customResourceDefinition]. */
override fun delete(kubernetesClient: KubernetesClient) {
kubernetesClient
.apiextensions()
.v1()
.customResourceDefinitions()
.withName(MessagingApplication.customResourceDefinition.metadata.name)
.delete()
}
}
| 0 | Kotlin | 0 | 2 | 17affcb232a20ea4f8489d915ab915dd724333e1 | 1,605 | connekted | Apache License 2.0 |
app/src/main/java/com/lstudio/mvisample/ui/counter/CounterViewModel.kt | LStudioO | 320,594,817 | false | null | package com.lstudio.mvisample.ui.counter
import androidx.lifecycle.ViewModel
class CounterViewModel : ViewModel() | 0 | Kotlin | 0 | 0 | e16ae65f86ac3e7f68ab3285390c0b0eb01adde0 | 115 | BlocAndroidExample | Apache License 2.0 |
app/src/main/java/com/example/vehiclecontacting/Web/DiscussController/GetFirstPageDiscuss.kt | Bngel | 366,048,859 | false | null | package com.example.vehiclecontacting.Web.DiscussController
data class GetFirstPageDiscuss(
val code: Int,
val data: MyDiscuss,
val msg: String
)
| 0 | Kotlin | 0 | 0 | 759ffa90c487d4472a79e20bf51ca35454cc7e65 | 159 | VehicleContacting | Apache License 2.0 |
code/jvm/src/main/kotlin/pt/isel/leic/ptgest/repository/jdbi/JdbiTrainerRepo.kt | PTGest | 761,908,487 | false | {"Kotlin": 405169, "Vue": 247495, "TypeScript": 79316, "PLpgSQL": 18596, "CSS": 1471, "HTML": 368, "Shell": 274} | package pt.isel.leic.ptgest.repository.jdbi
import org.jdbi.v3.core.Handle
import org.jdbi.v3.core.kotlin.mapTo
import pt.isel.leic.ptgest.domain.trainee.model.Trainee
import pt.isel.leic.ptgest.domain.trainer.model.TrainerDetails
import pt.isel.leic.ptgest.domain.user.Gender
import pt.isel.leic.ptgest.repository.TrainerRepo
import java.util.*
class JdbiTrainerRepo(private val handle: Handle) : TrainerRepo {
override fun getTrainees(trainerId: UUID, skip: Int, limit: Int?, gender: Gender?, name: String?): List<Trainee> {
val genderCondition = gender?.let { "and gender = :gender::gender" } ?: ""
val nameCondition = name?.let { "and ut.name like :name" } ?: ""
return handle.createQuery(
"""
select t.id as trainee_id, ut.name as trainee_name, t.gender, upt.id as trainer_id, upt.name as trainer_name
from trainee t
join "user" ut on t.id = ut.id
left join trainer_trainee tt on t.id = tt.trainee_id
left join "user" upt on tt.trainer_id = upt.id
where tt.trainer_id = :trainerId $genderCondition $nameCondition
limit :limit offset :skip;
""".trimIndent()
)
.bindMap(
mapOf(
"trainerId" to trainerId,
"skip" to skip,
"limit" to limit,
"gender" to gender,
"name" to "%$name%"
)
)
.mapTo<Trainee>()
.list()
}
override fun getTotalTrainees(trainerId: UUID, gender: Gender?, name: String?): Int {
val genderCondition = gender?.let { "and gender = :gender::gender" } ?: ""
val nameCondition = name?.let { "and ut.name like :name" } ?: ""
return handle.createQuery(
"""
select count(*)
from trainee t
join "user" ut on t.id = ut.id
left join trainer_trainee tt on t.id = tt.trainee_id
left join "user" upt on tt.trainer_id = upt.id
where tt.trainer_id = :trainerId $genderCondition $nameCondition
""".trimIndent()
)
.bindMap(
mapOf(
"trainerId" to trainerId,
"gender" to gender,
"name" to "%$name%"
)
)
.mapTo<Int>()
.one()
}
override fun getTrainerDetails(trainerId: UUID): TrainerDetails? =
handle.createQuery(
"""
select gender, phone_number
from trainer
where trainer.id = :trainerId
""".trimIndent()
)
.bind("trainerId", trainerId)
.mapTo<TrainerDetails>()
.firstOrNull()
override fun getCompanyAssignedTrainer(trainerId: UUID): UUID? =
handle.createQuery(
"""
select company_id
from company_trainer
where trainer_id = :trainerId
""".trimIndent()
)
.bind("trainerId", trainerId)
.mapTo<UUID>()
.firstOrNull()
override fun associateTrainerToReport(trainerId: UUID, reportId: Int) {
handle.createUpdate(
"""
insert into report_trainer (report_id, trainer_id)
values (:reportId, :trainerId)
"""
)
.bindMap(
mapOf(
"reportId" to reportId,
"trainerId" to trainerId
)
)
.execute()
}
override fun associateTrainerToExercise(trainerId: UUID, exerciseId: Int) {
handle.createUpdate(
"""
insert into exercise_trainer (trainer_id, exercise_id)
values (:trainerId, :exerciseId)
"""
)
.bindMap(
mapOf(
"trainerId" to trainerId,
"exerciseId" to exerciseId
)
)
.execute()
}
override fun associateTrainerToSet(trainerId: UUID, setId: Int) {
handle.createUpdate(
"""
insert into set_trainer (trainer_id, set_id)
values (:trainerId, :setId)
""".trimIndent()
)
.bindMap(
mapOf(
"trainerId" to trainerId,
"setId" to setId
)
)
.execute()
}
override fun associateTrainerToWorkout(trainerId: UUID, workoutId: Int) {
handle.createUpdate(
"""
insert into workout_trainer (trainer_id, workout_id)
values (:trainerId, :workoutId)
""".trimIndent()
)
.bindMap(
mapOf(
"trainerId" to trainerId,
"workoutId" to workoutId
)
)
.execute()
}
override fun associateSessionToTrainer(trainerId: UUID, sessionId: Int) {
handle.createUpdate(
"""
insert into session_trainer (trainer_id, session_id)
values (:trainerId, :sessionId)
"""
)
.bindMap(
mapOf(
"trainerId" to trainerId,
"sessionId" to sessionId
)
)
.execute()
}
}
| 0 | Kotlin | 0 | 6 | b94fedfe747862fbc7190e6aced5b3e84833590f | 5,439 | PTGest | MIT License |
kaskade/livedata/src/test/kotlin/dev/gumil/kaskade/livedata/DamLiveDataTest.kt | gumil | 120,153,669 | false | null | package io.gumil.kaskade.livedata
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import io.gumil.kaskade.Kaskade
import io.mockk.confirmVerified
import io.mockk.mockk
import io.mockk.verify
import io.mockk.verifyOrder
import org.junit.Rule
import org.junit.rules.TestRule
import kotlin.test.BeforeTest
import kotlin.test.Test
internal class DamLiveDataTest {
@get:Rule
val rule: TestRule = InstantTaskExecutorRule()
private val kaskade = Kaskade.create<TestAction, TestState>(TestState.State1) {
on<TestAction.Action1> {
TestState.State1
}
on<TestAction.Action2> {
TestState.State2
}
on<TestAction.Action3> {
TestState.SingleStateEvent
}
}
private val mockObserver = mockk<Observer<TestState>>(relaxed = true)
@BeforeTest
fun `should emit initial state`() {
kaskade.stateDamLiveData().observeForever(mockObserver)
verify { mockObserver.onChanged(TestState.State1) }
}
@Test
fun `damLiveData when value sent should invoke observer`() {
val liveData = DamLiveData<String>()
val mockObserver = mockk<Observer<String>>(relaxed = true)
liveData.observeForever(mockObserver)
val value = "hello"
liveData.setValue(value)
verify { mockObserver.onChanged(value) }
confirmVerified(mockObserver)
}
@Test
fun `damLiveData invoke latest emitted value before observing`() {
val liveData = DamLiveData<String>()
val mockObserver = mockk<Observer<String>>(relaxed = true)
val hello = "hello"
val world = "world"
liveData.setValue("test")
liveData.setValue(world)
liveData.observeForever(mockObserver)
liveData.setValue(hello)
verifyOrder {
mockObserver.onChanged(world)
mockObserver.onChanged(hello)
}
confirmVerified(mockObserver)
}
@Test
fun `damLiveData should not invoke anything after removing observer`() {
val liveData = DamLiveData<String>()
val mockObserver = mockk<Observer<String>>(relaxed = true)
val value = "hello"
liveData.observeForever(mockObserver)
liveData.removeObserver(mockObserver)
liveData.setValue(value)
verify(exactly = 0) { mockObserver.onChanged(value) }
verify { mockObserver.equals(mockObserver) }
confirmVerified(mockObserver)
}
@Test
fun `damLiveData should invoke last emitted after removeObserver`() {
val liveData = DamLiveData<String>()
val mockObserver = mockk<Observer<String>>(relaxed = true)
val value = "hello"
liveData.observeForever(mockObserver)
liveData.removeObserver(mockObserver)
liveData.setValue(value)
liveData.observeForever(mockObserver)
verify { mockObserver.onChanged(value) }
verify { mockObserver.equals(mockObserver) }
confirmVerified(mockObserver)
}
@Test
fun `damLiveData should not invoke last emitted after cleared`() {
val liveData = DamLiveData<String>()
val mockObserver = mockk<Observer<String>>(relaxed = true)
val hello = "hello"
val world = "world"
liveData.observeForever(mockObserver)
liveData.setValue(hello)
liveData.clear()
liveData.removeObserver(mockObserver)
liveData.setValue(world)
verify { mockObserver.onChanged(hello) }
verify { mockObserver.equals(mockObserver) }
confirmVerified(mockObserver)
}
@Test
fun `create DamLivedata from kaskade using extension function`() {
kaskade.process(TestAction.Action1)
verify { mockObserver.onChanged(TestState.State1) }
confirmVerified(mockObserver)
}
@Test
fun `create DamLiveData from kaskade no emissions on initialized`() {
val stateLiveData = kaskade.stateDamLiveData()
val mockObserver = mockk<Observer<TestState>>(relaxed = true)
stateLiveData.observeForever(mockObserver)
verify(exactly = 0) { mockObserver.onChanged(any()) }
confirmVerified(mockObserver)
}
@Test
fun `create DamLiveData from kaskade should not emit SingleEvent state on new observer`() {
val stateLiveData = kaskade.stateDamLiveData()
val mockObserver = mockk<Observer<TestState>>(relaxed = true)
kaskade.process(TestAction.Action1)
stateLiveData.observeForever(mockObserver)
kaskade.process(TestAction.Action3)
stateLiveData.removeObserver(mockObserver)
stateLiveData.observeForever(mockObserver)
verifyOrder {
mockObserver.onChanged(TestState.State1)
mockObserver.onChanged(TestState.SingleStateEvent)
mockObserver.onChanged(TestState.State1)
}
verify { mockObserver.equals(mockObserver) }
confirmVerified(mockObserver)
}
@Test
fun `should emit initial state and processed state`() {
val mockObserver = mockk<Observer<TestState>>(relaxed = true)
val kaskade = Kaskade.create<TestAction, TestState>(TestState.State1) {
on<TestAction.Action1> {
TestState.State1
}
on<TestAction.Action2> {
TestState.State2
}
}
kaskade.process(TestAction.Action2)
kaskade.stateDamLiveData().observeForever(mockObserver)
verifyOrder {
mockObserver.onChanged(TestState.State1)
mockObserver.onChanged(TestState.State2)
}
confirmVerified(mockObserver)
}
}
| 10 | null | 6 | 228 | cd88de5e622c66d3ef4a505b551d23ebe22bc618 | 5,714 | Kaskade | Apache License 2.0 |
analysis/src/org/jetbrains/kotlin/idea/references/KtArrayAccessReferenceDescriptorsImpl.kt | JetBrains | 278,369,660 | false | null | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.references
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.psi.KtArrayAccessExpression
import org.jetbrains.kotlin.psi.KtImportAlias
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingContext.INDEXED_LVALUE_GET
import org.jetbrains.kotlin.resolve.BindingContext.INDEXED_LVALUE_SET
internal class KtArrayAccessReferenceDescriptorsImpl(
expression: KtArrayAccessExpression
) : KtArrayAccessReference(expression), KtDescriptorsBasedReference {
override fun handleElementRename(newElementName: String): PsiElement = renameImplicitConventionalCall(newElementName)
override fun isReferenceToImportAlias(alias: KtImportAlias): Boolean {
return super<KtDescriptorsBasedReference>.isReferenceToImportAlias(alias)
}
override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> {
val getFunctionDescriptor = context[INDEXED_LVALUE_GET, expression]?.candidateDescriptor
val setFunctionDescriptor = context[INDEXED_LVALUE_SET, expression]?.candidateDescriptor
return listOfNotNull(getFunctionDescriptor, setFunctionDescriptor)
}
}
| 0 | Kotlin | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 1,475 | intellij-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.