path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/breezeyellowbird/features/login/api/productlistapi/ProductListRepo.kt
DebashisINT
859,710,978
false
{"Kotlin": 15925690, "Java": 1028108}
package com.breezefieldsalesmalaxmi.features.login.api.productlistapi import com.breezefieldsalesmalaxmi.app.Pref import com.breezefieldsalesmalaxmi.app.domain.ProductListEntity import com.breezefieldsalesmalaxmi.app.utils.AppUtils import com.breezefieldsalesmalaxmi.base.BaseResponse import com.breezefieldsalesmalaxmi.features.login.model.productlistmodel.ProductListOfflineResponseModel import com.breezefieldsalesmalaxmi.features.login.model.productlistmodel.ProductListOfflineResponseModelNew import com.breezefieldsalesmalaxmi.features.login.model.productlistmodel.ProductListResponseModel import com.breezefieldsalesmalaxmi.features.login.model.productlistmodel.ProductRateListResponseModel import com.breezefieldsalesmalaxmi.features.orderITC.GetOrderHistory import com.breezefieldsalesmalaxmi.features.orderITC.GetProductRateReq import com.breezefieldsalesmalaxmi.features.orderITC.GetProductReq import com.breezefieldsalesmalaxmi.features.orderITC.SyncOrd import com.breezefieldsalesmalaxmi.features.viewAllOrder.orderOptimized.ProductRateOnlineListResponseModel import io.reactivex.Observable import timber.log.Timber /** * Created by Saikat on 20-11-2018. */ class ProductListRepo(val apiService: ProductListApi) { fun getProductList(session_token: String, user_id: String, last_update_date: String): Observable<ProductListResponseModel> { Timber.d("ProductListRepo hit ${Pref.isOrderShow} ${Pref.IsShowQuotationFooterforEurobond}" + "Time : " + AppUtils.getCurrentDateTime()) return apiService.getProductList(session_token, user_id, last_update_date) } fun getProductRateList(shop_id: String): Observable<ProductRateListResponseModel> { return apiService.getProductRateList(Pref.session_token!!, Pref.user_id!!, shop_id) } fun getProductRateListByEntity(shop_id: String): Observable<ProductRateOnlineListResponseModel> { return apiService.getProductRateOnlineList(Pref.session_token!!, Pref.user_id!!, shop_id) } fun getProductRateOfflineList(): Observable<ProductListOfflineResponseModel> { return apiService.getOfflineProductRateList(Pref.session_token!!, Pref.user_id!!) } fun getProductRateOfflineListNew(): Observable<ProductListOfflineResponseModelNew> { return apiService.getOfflineProductRateListNew(Pref.session_token!!, Pref.user_id!!) } fun syncProductListITC(obj: SyncOrd): Observable<BaseResponse> { return apiService.syncProductListITC(obj) } fun getProductListITC(session_token: String, user_id: String): Observable<GetProductReq> { return apiService.getProductListITC(session_token, user_id) } fun getProductRateListITC(session_token: String, user_id: String): Observable<GetProductRateReq> { return apiService.getProductRateListITC(session_token, user_id) } fun getOrderHistory(user_id:String): Observable<GetOrderHistory> { return apiService.getOrderHistoryApi(user_id) } }
0
Kotlin
0
0
e244b9fd9ad06267854f6e26b248674e8eba8b31
2,974
YellowBird
Apache License 2.0
src/main/kotlin/com/example/bootkotlin/service/impl/QuestionServiceImpl.kt
licxi
126,296,770
false
{"JavaScript": 1232633, "Kotlin": 87830, "HTML": 66857, "CSS": 6644}
package com.example.bootkotlin.service.impl import com.example.bootkotlin.entity.master.AnswerOnly import com.example.bootkotlin.entity.master.Question import com.example.bootkotlin.repository.master.QuestionRepo import com.example.bootkotlin.service.QuestionService import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.domain.Page import org.springframework.data.domain.PageRequest import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service("questionService") @Transactional class QuestionServiceImpl : QuestionService { @Autowired lateinit var questionRepo: QuestionRepo override fun findAllByExamId(examId: Long, page: Int, size: Int): Page<Question> { return questionRepo.findAllByExamId(examId, PageRequest(page, size)) } override fun findAllByExamIdAndTitleContaining(examId: Long, title: String, page: Int, size: Int): Page<Question> { return questionRepo.findAllByExamIdAndTitleContaining(examId, title, PageRequest(page, size)) } @Transactional(readOnly = false) override fun save(question: Question): Boolean { return questionRepo.save(question) != null } @Transactional(readOnly = false) override fun save(questions: Iterable<Question>): Boolean { return questionRepo.save(questions) != null } @Transactional(readOnly = false) override fun deleteAllByExamId(examId: Long): Int { return questionRepo.deleteByExamId(examId) } @Transactional(readOnly = false) override fun deleteById(id: Long): Boolean { return try { //根据是否抛出异常判断删除结果 questionRepo.delete(id) true } catch (e: Exception) { println(e.message) //e.printStackTrace() false } } override fun findOneById(id: Long): Question? { return questionRepo.findOne(id) } override fun findById(id: Long): AnswerOnly = questionRepo.findOneById(7) }
0
JavaScript
0
0
1413ad600dd09eb1c4bc503e58ee53cf5f453ac1
2,034
spring-boot-kotlin
Apache License 2.0
base-feature/src/main/java/eu/krzdabrowski/currencyadder/basefeature/presentation/CurrencyAdderModule.kt
krzdabrowski
591,082,023
false
{"Kotlin": 176180}
package eu.krzdabrowski.currencyadder.basefeature.presentation import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dagger.multibindings.IntoSet import eu.krzdabrowski.currencyadder.core.navigation.NavigationFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) internal interface CurrencyAdderModule { @Singleton @Binds @IntoSet fun bindCurrencyAdderNavigationFactory(factory: CurrencyAdderNavigationFactory): NavigationFactory }
0
Kotlin
1
1
e7ec91605b19c8092c603beb3c14d46d800bd2d9
553
android-currency-adder
MIT License
src/pw/gerard/gsmelter/tree/leaf/MessageLeaf.kt
GerardSmit
102,296,996
false
{"Kotlin": 20969}
package pw.gerard.gsmelter.tree.leaf import com.runemate.game.api.script.framework.tree.LeafTask class MessageLeaf(val message: String): LeafTask() { override fun execute() { println(message) } }
0
Kotlin
1
1
fafa7b7e796790e98e4ce1abdec1f38dd818a7af
213
gSmelter
MIT License
app/src/main/java/com/dkgoody/dtimer/ui/main/MainActivity.kt
dkgoody
327,734,068
false
null
package com.dkgoody.dtimer.ui.main import android.os.Build import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.dkgoody.dtimer.DTimerViewModel import com.dkgoody.dtimer.R class MainActivity : AppCompatActivity() { lateinit var viewModel : DTimerViewModel lateinit var keep_menu : Menu override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) viewModel = viewModels<DTimerViewModel>().value } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.menu, menu) if (viewModel.autostart()) menu.getItem(0).setChecked(true) if (viewModel.voicealert()) menu.getItem(1).setChecked(true) if(viewModel.alarm()) menu.getItem(2).setChecked(true) keep_menu = menu return true } // actions on click menu items override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_autostart -> { item.setChecked(!item.isChecked()) viewModel.set_autostart(item.isChecked()) keep_menu.getItem(2).setEnabled(!item.isChecked()) if (item.isChecked()) { keep_menu.getItem(2).setChecked(false) viewModel.set_alarm(false) } true } R.id.action_voicealert -> { item.setChecked(!item.isChecked()) viewModel.set_voicealert(item.isChecked()) true } R.id.action_alarm -> { item.setChecked(!item.isChecked()) viewModel.set_alarm(item.isChecked()) true } else -> { // If we got here, the user's action was not recognized. // Invoke the superclass to handle it. super.onOptionsItemSelected(item) } } fun msgShow(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_LONG).show() } override fun onPause() { super.onPause() if (!isRecreating()) { viewModel.putToBackground(this) Log.i("DTimer", "BACKGROUND") } } override fun onResume() { if (!isRecreating()) { Log.i("DTimer", "FOREGROUND") viewModel.putToForeground(this) } super.onResume() } fun isRecreating(): Boolean { //consider pre honeycomb not recreating return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && isChangingConfigurations() } }
0
Kotlin
0
0
7e926f83003bd66813ea4b679d46049899e80588
2,808
dtimer
MIT License
data/src/main/java/com/cheesecake/data/repository/mappers/TeamStatisticsMapper.kt
CheeseCake-Team
645,082,831
false
{"Kotlin": 443813}
import com.cheesecake.data.remote.models.TeamStatisticsDTO import com.cheesecake.domain.entity.ScoreStats import com.cheesecake.domain.entity.TeamStatisticsEntity @JvmName("teamStatisticsDTOToTeamStatisticsEntity") fun TeamStatisticsDTO.toEntity(): TeamStatisticsEntity = TeamStatisticsEntity( form = this.form?.let { form-> form.map { it.toString() } } ?: listOf(), played = scoreStats( this.fixtures.played.home, this.fixtures.played.away, this.fixtures.played.total ), wins = scoreStats( this.fixtures.wins.home, this.fixtures.wins.away, this.fixtures.wins.total ), draws = scoreStats( this.fixtures.draws.home, this.fixtures.draws.away, this.fixtures.draws.total ), loses = scoreStats( this.fixtures.loses.home, this.fixtures.loses.away, this.fixtures.loses.total ), cleanSheet = scoreStats( this.cleanSheet.home, this.cleanSheet.away, this.cleanSheet.total ), failedToScore = scoreStats( this.failedToScore.home, this.failedToScore.away, this.failedToScore.total ), goalsFor = scoreStats( this.goals.goalsFor.total.home, this.goals.goalsFor.total.away, this.goals.goalsFor.total.total ), goalsAgainst = scoreStats( this.goals.goalsAgainst.total.home, this.goals.goalsAgainst.total.away, this.goals.goalsAgainst.total.total ) ) private fun scoreStats(home: Float, away: Float, total: Float): ScoreStats = ScoreStats(home.toInt(), away.toInt(), total.toInt())
0
Kotlin
2
4
cb032f91ae1fb7f35fc5242de6f6eb076ce51330
1,800
kickoff
Apache License 2.0
app/src/main/java/com/to/kotlinmessenger/util/ImageLoader.kt
CodeHunterDev
466,328,192
true
{"Kotlin": 86216}
package com.to.kotlinmessenger.util import android.graphics.drawable.Drawable import android.net.Uri import android.widget.ImageView import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.to.kotlinmessenger.model.User /** * 画像をロードしてImageViewに表示する。 * * @param imageUri 画像ファイルのURI * @param targetImageView 表示対象のImageView */ fun loadImageIntoView( imageUri: String, targetImageView: ImageView, listener: ImageLoadListener = ImageLoadListener.NOP ) { listener.onStart(imageUri, targetImageView) Glide.with(targetImageView.context.applicationContext) .load(imageUri) .diskCacheStrategy(DiskCacheStrategy.ALL) .listener(object : RequestListener<Drawable> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean ): Boolean { listener.onFailure(e, imageUri, targetImageView) listener.onFinish(imageUri, targetImageView) return false } override fun onResourceReady( resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { listener.onSuccess(imageUri, targetImageView) listener.onFinish(imageUri, targetImageView) return false } }) .into(targetImageView) } /** * 画像をロードしてImageViewに表示する。 * * @param imageUri 画像ファイルのURI * @param targetImageView 表示対象のImageView */ fun loadImageIntoView( imageUri: Uri, targetImageView: ImageView, listener: ImageLoadListener = ImageLoadListener.NOP ) { listener.onStart(imageUri, targetImageView) Glide.with(targetImageView.context.applicationContext) .load(imageUri) .diskCacheStrategy(DiskCacheStrategy.ALL) .listener(object : RequestListener<Drawable> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean ): Boolean { listener.onFailure(e, imageUri, targetImageView) listener.onFinish(imageUri, targetImageView) return false } override fun onResourceReady( resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { listener.onSuccess(imageUri, targetImageView) listener.onFinish(imageUri, targetImageView) return false } }) .into(targetImageView) } /** * ユーザーのプロフィール画像をロードしてImageViewに表示する。 * * @param user ユーザー * @param targetImageView 表示対象のImageView */ fun loadProfileImageIntoView( user: User, targetImageView: ImageView, listener: ImageLoadListener = ImageLoadListener.NOP ) { loadImageIntoView(user.profileImageUrl, targetImageView, listener) }
0
null
0
0
8b144501fc42eba6d1faed5ca648e9e592118003
3,428
kotlin-messenger
MIT License
app/src/test/java/ru/claus42/anothertodolistapp/domain/usecases/GetTodoItemListUseCaseTest.kt
klauz42
679,216,403
false
{"Kotlin": 257915}
package ru.claus42.anothertodolistapp.domain.usecases import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import org.junit.Assert.assertTrue import org.junit.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import ru.claus42.anothertodolistapp.domain.models.DataResult import ru.claus42.anothertodolistapp.domain.models.TodoItemRepository class GetTodoItemListUseCaseTest { private val domainItems = generateTodoItems() @Test operator fun invoke() = runTest { val todoItemsRepository: TodoItemRepository = mock<TodoItemRepository> { on { getTodoItems() } doReturn flowOf(DataResult.Success(domainItems)) } val getTodoItemListUseCase = GetTodoItemListUseCase(todoItemsRepository) val result = getTodoItemListUseCase().first() assertTrue(result is DataResult.Success) val list = (result as DataResult.Success).data assertTrue(domainItems == list) } }
0
Kotlin
0
0
5b1a0521dcff700285ba47d23c42266c99b27ca0
1,024
Another-Todo-List-App
MIT License
lib/src/main/java/com/kirkbushman/zammad/utils/Extensions.kt
KirkBushman
200,888,940
false
null
package com.kirkbushman.zammad.utils import com.kirkbushman.zammad.models.base.Creatable import com.kirkbushman.zammad.models.base.Updatable import com.kirkbushman.zammad.utils.Utils.convertStringToDate import java.util.* fun Creatable.createdAtDate(): Date? { return convertStringToDate(createdAt) } fun Updatable.updatedAtDate(): Date? { return convertStringToDate(updatedAt) }
2
Kotlin
5
34
92e27d4e920083da95dfaadae3963a2f211c392b
391
zammad-android
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/digitalprisonreportinglib/controller/model/Count.kt
ministryofjustice
697,333,274
false
{"Kotlin": 295133}
package uk.gov.justice.digital.hmpps.digitalprisonreportinglib.controller.model import io.swagger.v3.oas.annotations.media.Schema data class Count( @Schema(example = "501", description = "The total number of records") val count: Long, )
7
Kotlin
0
3
4f3f710ea7c03b4f82937402e54e03bed5b8bb1d
243
hmpps-digital-prison-reporting-lib
MIT License
app/src/main/java/com/example/swiftbargain/ui/cart/view_model/CartViewModel.kt
ahmedfikry24
814,676,783
false
{"Kotlin": 481653}
package com.example.swiftbargain.ui.cart.view_model import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope import androidx.navigation.toRoute import com.example.swiftbargain.data.local.room.entity.CartProductEntity import com.example.swiftbargain.data.models.CouponCodeDto import com.example.swiftbargain.data.repository.Repository import com.example.swiftbargain.navigation.Cart import com.example.swiftbargain.ui.base.BaseViewModel import com.example.swiftbargain.ui.utils.ContentStatus import com.example.swiftbargain.ui.utils.shared_ui_state.CartProductUiState import com.example.swiftbargain.ui.utils.shared_ui_state.toEntity import com.example.swiftbargain.ui.utils.shared_ui_state.toUiState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class CartViewModel @Inject constructor( savedStateHandle: SavedStateHandle, private val repository: Repository ) : BaseViewModel<CartUiState, CartEvents>(CartUiState()), CartInteractions { private val args = savedStateHandle.toRoute<Cart>() init { getDate() } override fun getDate() { _state.update { it.copy(contentStatus = ContentStatus.LOADING) } tryExecute( { mapOf( PRODUCTS to repository.getAllCartProducts(), COUPONS to repository.getAllCouponCodes() ) }, ::dataSuccess, { dataError() } ) } private fun dataSuccess(data: Map<String, Any>) { val products = (data[PRODUCTS] as List<*>).map { (it as CartProductEntity).toUiState() } val totalPrice = calculateTotalPrice(products) _state.update { value -> value.copy( contentStatus = ContentStatus.VISIBLE, products = products, coupons = (data[COUPONS] as List<*>).map { (it as CouponCodeDto).toUiState() }, productsPrice = totalPrice, totalPrice = totalPrice ) } } private fun dataError() { _state.update { it.copy(contentStatus = ContentStatus.FAILURE) } } override fun onRemoveItem(id: String) { viewModelScope.launch { repository.removeProductFromCart(id) _state.update { value -> value.copy(products = value.products.filterNot { it.id == id }) } } } override fun onClickItem(id: String) { sendEvent(CartEvents.NavigateToProductDetails(id)) } override fun onChangeQuantity(index: Int, quantity: Int) { val coupon = state.value.coupons.find { it.code == state.value.couponCode } _state.update { value -> value.copy( products = value.products.toMutableList().apply { this[index] = value.products[index].copy(orderQuantity = quantity) } ) } _state.update { it.copy( productsPrice = calculateTotalPrice(it.products), totalPrice = calculateTotalPrice(it.products, coupon?.discount?.toInt()) ) } viewModelScope.launch { repository.addProductToCart(state.value.products[index].toEntity()) } } override fun onChangeCouponCode(code: String) { _state.update { it.copy(couponCode = code) } } override fun checkCouponCode() { val coupon = state.value.coupons.find { it.code == state.value.couponCode } _state.update { value -> value.copy( couponCodeError = !value.coupons.any { it.code == value.couponCode }, couponDiscount = coupon?.discount ?: "", totalPrice = calculateTotalPrice(state.value.products, coupon?.discount?.toInt()) ) } } override fun onClickCheckOut() { sendEvent(CartEvents.NavigateToCartCheckOut) } override fun checkClearCart() { if (args.isCartCleared == true) { viewModelScope.launch { repository.deleteAllCartProducts() } _state.update { it.copy(products = listOf()) } } } companion object { private const val PRODUCTS = "products" private const val COUPONS = "coupons" } } private fun calculateTotalPrice(products: List<CartProductUiState>, discount: Int? = null): Int { var totalPrice = 0 products.forEach { totalPrice += it.price.toInt() * it.orderQuantity } if (discount != null) totalPrice -= discount return totalPrice }
0
Kotlin
0
0
bcf6af56ecf14d638b44a78908a0f0c7b41c69df
4,655
SwiftBargain
MIT License
app/src/main/java/com/example/cecd/Models/IndividualECDItem.kt
TillCM
617,893,612
false
null
package com.example.cecd.Models data class IndividualECDItem( val _links: Links, val assigned_user: List<AssignedUser>, val avatar_urls: AvatarUrls, val description: String, val id: Int, val link: String, val meta: List<Any>, val name: String, val slug: String, val url: String )
0
Kotlin
0
0
13d8a9181236323c79adec237be01703bbb58523
320
cecd
MIT License
anko/library/static/commons/src/main/java/dialogs/AndroidSelectors.kt
Kotlin
24,186,761
false
null
/* * Copyright 2016 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. */ @file:Suppress("NOTHING_TO_INLINE", "unused") package org.jetbrains.anko import android.app.Fragment import android.content.Context import android.content.DialogInterface inline fun AnkoContext<*>.selector( title: CharSequence? = null, items: List<CharSequence>, noinline onClick: (DialogInterface, Int) -> Unit ) = ctx.selector(title, items, onClick) @Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.") inline fun Fragment.selector( title: CharSequence? = null, items: List<CharSequence>, noinline onClick: (DialogInterface, Int) -> Unit ) = activity.selector(title, items, onClick) fun Context.selector( title: CharSequence? = null, items: List<CharSequence>, onClick: (DialogInterface, Int) -> Unit ) { with(AndroidAlertBuilder(this)) { if (title != null) { this.title = title } items(items, onClick) show() } }
243
null
1295
15,967
37893764c0f20208c842a466f0fd0159c1e247e2
1,600
anko
Apache License 2.0
app/src/main/java/com/haoge/sample/easyandroid/activities/mvp/login/LoginFragment.kt
easyandroidgroup
132,259,597
false
{"Kotlin": 217162}
package com.haoge.sample.easyandroid.activities.mvp.login import android.os.Bundle import butterknife.OnClick import com.haoge.sample.easyandroid.R import com.haoge.sample.easyandroid.activities.mvp.base.BaseMVPFragment /** * @author haoge on 2018/9/4 */ class LoginFragment: BaseMVPFragment(), LoginView { val presenter = LoginPresenter(this) override fun createPresenters() = arrayOf(presenter) override fun getLayoutId() = R.layout.fragment_login override fun initPage(savedInstanceState: Bundle?) {} @OnClick(R.id.to_register) fun toRegister() { getHostView().toRegisterFragment() } @OnClick(R.id.login) fun onLoginClick() { presenter.login("123456", "123456") } override fun loginSuccess() { getHostView().loginSuccess() } override fun getHostView(): LoginMainView { return getHostActivity() as LoginMainView } }
8
Kotlin
197
1,170
a041668c2b1ba8638aa0bb716074e70660bcaf3d
914
EasyAndroid
Apache License 2.0
core/src/main/kotlin/de/maibornwolff/domainchoreograph/core/api/ResolveDomainDefinition.kt
MaibornWolff
139,985,029
false
{"Kotlin": 168533, "TypeScript": 132987, "JavaScript": 5400, "HTML": 1174, "Dockerfile": 390}
package de.maibornwolff.domainchoreograph.core.api inline fun <reified T : Any> resolveDomainDefinition(vararg params: Any): T { return de.maibornwolff.domainchoreograph.core.processing.resolveDomainDefinition(T::class, params.asList()) } inline fun <reified T : Any> resolveDomainDefinitionWithOptions(options: DomainChoreographyOptions, vararg params: Any): T { return de.maibornwolff.domainchoreograph.core.processing.resolveDomainDefinitionWithOptions(options, T::class, params.asList()) }
16
Kotlin
0
1
863441f0df267dcbf9874c92771e104a8f60fe37
504
domainchoreograph
Apache License 2.0
client-core/src/main/kotlin/org/sinou/pydia/client/ui/login/nav/NavigationState.kt
bsinou
434,248,316
false
null
package org.sinou.pydia.client.ui.login.nav import java.util.UUID /** * State that can be used to trigger navigation. */ sealed class NavigationState { object Idle : NavigationState() /** * @param id is used so that multiple instances of the same route will trigger multiple navigation calls. */ data class NavigateToRoute(val route: String, val id: String = UUID.randomUUID().toString()) : NavigationState() /** * @param staticRoute is the static route to pop to, without parameter replacements. */ data class PopToRoute(val staticRoute: String, val id: String = UUID.randomUUID().toString()) : NavigationState() data class NavigateUp(val id: String = UUID.randomUUID().toString()) : NavigationState() }
0
null
0
1
51a128c49a24eedef1baf2d4f295f14aa799b5d3
772
pydia
Apache License 2.0
kontrollsamtale/application/src/main/kotlin/no/nav/su/se/bakover/kontrollsamtale/application/annuller/AnnullerKontrollsamtaleVedOpphørServiceImpl.kt
navikt
227,366,088
false
{"Kotlin": 9935179, "Shell": 4388, "TSQL": 1233, "Dockerfile": 1209}
package no.nav.su.se.bakover.kontrollsamtale.application.annuller import no.nav.su.se.bakover.common.persistence.SessionContext import no.nav.su.se.bakover.domain.revurdering.opphør.AnnullerKontrollsamtaleVedOpphørService import no.nav.su.se.bakover.kontrollsamtale.application.KontrollsamtaleServiceImpl import no.nav.su.se.bakover.kontrollsamtale.domain.KontrollsamtaleRepo import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.UUID /** * Definerer kontrakten fra behandling til kontrollsamtale. * Ideélt sett bør det heller sendes en hendelse om et nytt stønadsvedtak på saken (sakId). * Også bør kontrollsamtale hente gjeldende vedtak/stønad for saken på nytt og ta en ny avgjørelse basert på dette. */ class AnnullerKontrollsamtaleVedOpphørServiceImpl( private val kontrollsamtaleService: KontrollsamtaleServiceImpl, private val kontrollsamtaleRepo: KontrollsamtaleRepo, ) : AnnullerKontrollsamtaleVedOpphørService { private val log: Logger = LoggerFactory.getLogger(this::class.java) override fun annuller( // TODO jah: Bør være en extension-function: Sak.annullerKontrollsamtale(...), // så lenge ikke kontrollsamtaler ligger som data på saken. // I siste tilfellet bør vi ta i mot en sak. sakId: UUID, sessionContext: SessionContext, ) { // TODO jah: Bør vurdere om vi skal legge kontrollsamtaler på Sak (da kan ikke kontrollsamtale:domain ha referanser til :domain) // TODO jah: Bør hente alle kontrollsamtaler knyttet til saken og gjøre en litt grundigere vurdering per tilfelle. return kontrollsamtaleService.hentNestePlanlagteKontrollsamtale(sakId, sessionContext).fold( { log.info("Trenger ikke annullere kontrollsamtale, siden det er ingen planlagt kontrollsamtale for sakId $sakId") }, { kontrollsamtale -> kontrollsamtale.annuller().map { annullertKontrollSamtale -> kontrollsamtaleRepo.lagre(annullertKontrollSamtale, sessionContext) }.mapLeft { // hentNestePlanlagteKontrollsamtale(..) returnerer kun Kontrollsamtalestatus.PLANLAGT_INNKALLING, // som er en gyldig overgang. Så lenge det ikke endrer seg (tester?) er det trygt å kaste her. throw IllegalStateException("Kunne ikke annullere kontrollsamtale ${kontrollsamtale.id} med status ${kontrollsamtale.status}. Underliggende feil: $it") } }, ) } }
0
Kotlin
1
1
f187a366e1b4ec73bf18f4ebc6a68109494f1c1b
2,536
su-se-bakover
MIT License
app/src/main/java/com/lcyer/swit/di/ViewModelModule.kt
lcyer
449,058,308
false
null
package com.lcyer.swit.di import com.lcyer.swit.ui.bookmark.BookMarkViewModel import com.lcyer.swit.ui.user.UserViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val viewModelModule = module { viewModel { UserViewModel( get(), get(), get() ) } viewModel { BookMarkViewModel( get(), get() ) } }
0
Kotlin
0
0
f1c1844110b5459962b1b3dcbbf9534a20a619f1
441
sample-swit
Apache License 2.0
common-ui/src/main/java/com/skydoves/common_ui/viewholders/ReviewListViewHolder.kt
skydoves
225,837,633
false
null
/* * Designed and developed by 2019 skydoves (Jaewoong Eum) * * 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.skydoves.common_ui.viewholders import android.view.View import com.skydoves.baserecyclerviewadapter.BaseViewHolder import com.skydoves.common_ui.databinding.ItemReviewBinding import com.skydoves.entity.Review /** ReviewListViewHolder is a viewHolder class for binding a [Review] item. */ class ReviewListViewHolder(val view: View) : BaseViewHolder(view) { private lateinit var review: Review private val binding by bindings<ItemReviewBinding>(view) override fun bindData(data: Any) { if (data is Review) { review = data binding.apply { review = data executePendingBindings() } } } override fun onClick(v: View?) = Unit override fun onLongClick(v: View?) = false }
4
Kotlin
52
353
f9ef645bc86a9c13ab01624a7e6d21269c128b31
1,356
GoldMovies
Apache License 2.0
string_processor/src/test/kotlin/org/arnoid/string/processor/blocks/LtTest.kt
arnoid
217,005,361
false
null
package org.arnoid.string.processor.blocks import com.nhaarman.mockitokotlin2.doThrow import com.nhaarman.mockitokotlin2.mock import junit.framework.TestCase.assertEquals import org.arnoid.string.processor.StringProcessor import org.arnoid.string.processor.StringProvider import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers class LtTest { lateinit var stringProcessor: StringProcessor lateinit var stringProviderMock: StringProvider @Before fun before() { stringProcessor = StringProcessor() stringProviderMock = mock { on { get(ArgumentMatchers.anyString()) } doThrow RuntimeException("This should not happened") } } @Test fun testTagLt() { assertEquals(RESULT_STR, stringProcessor.process(INPUT_STR, stringProviderMock)) } companion object { const val INPUT_STR = "\$lt{10}{5} $$ \$lt{5}{10} $$ \$lt{10}{10} $$ \$lt{a}{b} $$ \$lt{b}{a}" const val RESULT_STR = "false \$ true \$ false \$ false \$ false" } }
0
Kotlin
0
6
c3db64a4e90a687a286c59b0736ca280df5e6592
1,044
string.processor
MIT License
nj2k/testData/newJ2k/issues/kt-19296.kt
walltz556
211,568,334
true
null
open class A { interface I { fun f() } } class B : A() class Test { var z: A.I? = null }
0
null
0
1
89d49479abab76ea1d4ffe5e45826f3b076c6f68
109
kotlin
Apache License 2.0
server/src/main/kotlin/com/kamelia/hedera/rest/file/Routes.kt
Black-Kamelia
492,280,011
false
null
package com.kamelia.hedera.rest.file import com.kamelia.hedera.core.Errors import com.kamelia.hedera.core.FileNotFoundException import com.kamelia.hedera.core.response.Response import com.kamelia.hedera.core.response.respond import com.kamelia.hedera.core.response.respondNoSuccess import com.kamelia.hedera.core.response.respondNothing import com.kamelia.hedera.plugins.AuthJwt import com.kamelia.hedera.rest.core.pageable.PageDefinitionDTO import com.kamelia.hedera.util.FileUtils import com.kamelia.hedera.util.adminRestrict import com.kamelia.hedera.util.authenticatedUser import com.kamelia.hedera.util.doWithForm import com.kamelia.hedera.util.getHeader import com.kamelia.hedera.util.getPageParameters import com.kamelia.hedera.util.getParam import com.kamelia.hedera.util.getUUID import com.kamelia.hedera.util.getUUIDOrNull import com.kamelia.hedera.util.proxyRedirect import com.kamelia.hedera.util.respondFile import com.kamelia.hedera.util.respondFileInline import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.routing.* fun Route.filesRoutes() = route("/files") { uploadFileFromToken() authenticate(AuthJwt) { uploadFile() searchFiles() getFilesFormats() // editFile() editFileVisibility() editFileName() editFileCustomLink() removeFileCustomLink() deleteFile() route("/bulk") { editFileVisibilityBulk() deleteBulk() } } authenticate(AuthJwt, optional = true) { getFile() } } fun Route.rawFileRoute() = get("""/m/(?<code>[a-zA-Z0-9]{10})""".toRegex()) { val authedId = call.authenticatedUser?.uuid val code = call.getParam("code") try { FileService.getFileFromCode(code, authedId).ifSuccess { (data) -> checkNotNull(data) { "File not found" } val file = FileUtils.getOrNull(data.owner.id, code) if (file != null) { call.respondFileInline(file, ContentType.parse(data.mimeType)) } else { // TODO notify orphaned file call.proxyRedirect("/") } } } catch (e: FileNotFoundException) { call.proxyRedirect("/") } } fun Route.rawFileCustomLinkRoute() = get("""/c/(?<link>[a-z0-9\-]+)""".toRegex()) { val link = call.getParam("link") try { FileService.getFileFromCustomLink(link).ifSuccess { (data) -> checkNotNull(data) { "File not found" } val file = FileUtils.getOrNull(data.owner.id, data.code) if (file != null) { call.respondFileInline(file, ContentType.parse(data.mimeType)) } else { // TODO notify orphaned file call.proxyRedirect("/") } } } catch (e: FileNotFoundException) { call.proxyRedirect("/") } } private fun Route.uploadFile() = post("/upload") { val userId = call.authenticatedUser!!.uuid call.doWithForm(onFiles = mapOf( "file" to { call.respond(FileService.handleFile(it, userId)) } ), onMissing = { call.respondNoSuccess(Response.badRequest(Errors.Uploads.MISSING_FILE)) }) } private fun Route.uploadFileFromToken() = post("/upload/token") { val authToken = call.getHeader("Upload-Token") call.doWithForm(onFiles = mapOf( "file" to { call.respond(FileService.handleFileWithToken(it, authToken)) } ), onMissing = { call.respondNoSuccess(Response.badRequest(Errors.Uploads.MISSING_FILE)) }) } private fun Route.getFile() = get("/{code}") { val authedId = call.authenticatedUser?.uuid val code = call.getParam("code") FileService.getFileFromCode(code, authedId).ifSuccessOrElse( onSuccess = { (data) -> checkNotNull(data) { "File not found" } val file = FileUtils.getOrNull(data.owner.id, code) if (file != null) { call.respondFile(file, data.name, data.mimeType) } else { // TODO notify orphaned file call.respondNothing(Response.notFound()) } }, onError = { call.respondNothing(Response.notFound()) }, ) } private fun Route.searchFiles() = post<PageDefinitionDTO>("/search/{uuid?}") { body -> val uuid = call.getUUIDOrNull("uuid") val jwtId = call.authenticatedUser!!.uuid val userId = uuid?.apply { if (uuid != jwtId) adminRestrict() } ?: jwtId val (page, pageSize) = call.getPageParameters() call.respond(FileService.getFiles(userId, page, pageSize, body, asOwner = uuid == null)) } private fun Route.getFilesFormats() = get("/formats") { val userId = call.authenticatedUser!!.uuid call.respond(FileService.getFilesFormats(userId)) } private fun Route.editFileVisibility() = put<FileUpdateDTO>("/{uuid}/visibility") { body -> val fileId = call.getUUID("uuid") val userId = call.authenticatedUser!!.uuid call.respond(FileService.updateFileVisibility(fileId, userId, body)) } private fun Route.editFileVisibilityBulk() = post<BulkUpdateVisibilityDTO>("/visibility") { body -> val userId = call.authenticatedUser!!.uuid call.respond(FileService.bulkUpdateFilesVisibility(userId, body)) } private fun Route.editFileName() = put<FileUpdateDTO>("/{uuid}/name") { body -> val fileId = call.getUUID("uuid") val userId = call.authenticatedUser!!.uuid call.respond(FileService.updateFileName(fileId, userId, body)) } private fun Route.editFileCustomLink() = put<FileUpdateDTO>("/{uuid}/custom-link") { body -> val fileId = call.getUUID("uuid") val userId = call.authenticatedUser!!.uuid call.respond(FileService.updateCustomLink(fileId, userId, body)) } private fun Route.removeFileCustomLink() = delete("/{uuid}/custom-link") { val fileId = call.getUUID("uuid") val userId = call.authenticatedUser!!.uuid call.respond(FileService.removeCustomLink(fileId, userId)) } private fun Route.deleteFile() = delete("/{uuid}") { val fileId = call.getUUID("uuid") val userId = call.authenticatedUser!!.uuid call.respond(FileService.deleteFile(fileId, userId)) } private fun Route.deleteBulk() = post<BulkDeleteDTO>("/delete") { body -> val userId = call.authenticatedUser!!.uuid call.respond(FileService.bulkDeleteFiles(body.ids, userId)) }
29
null
2
26
4d03d547047b0c348eb68c76f84bbd39f776914e
6,414
Hedera
Apache License 2.0
sykepenger-model/src/test/kotlin/no/nav/helse/utbetalingstidslinje/ArbeidsgiverUtbetalingerTest.kt
navikt
193,907,367
false
null
package no.nav.helse.utbetalingstidslinje import no.nav.helse.* import no.nav.helse.hendelser.* import no.nav.helse.inspectors.UtbetalingstidslinjeInspektør import no.nav.helse.inspectors.inspektør import no.nav.helse.person.* import no.nav.helse.person.Sykepengegrunnlag.Begrensning.ER_IKKE_6G_BEGRENSET import no.nav.helse.person.etterlevelse.MaskinellJurist import no.nav.helse.person.infotrygdhistorikk.Infotrygdhistorikk import no.nav.helse.person.infotrygdhistorikk.InfotrygdhistorikkElement import no.nav.helse.person.infotrygdhistorikk.Infotrygdperiode import no.nav.helse.testhelpers.* import no.nav.helse.utbetalingstidslinje.ArbeidsgiverRegler.Companion.NormalArbeidstaker import no.nav.helse.økonomi.Inntekt import no.nav.helse.økonomi.Inntekt.Companion.månedlig import no.nav.helse.økonomi.Prosent import no.nav.helse.økonomi.Prosentdel.Companion.prosent import no.nav.helse.økonomi.Økonomi import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import java.time.LocalDate import java.time.LocalDateTime import java.time.YearMonth import java.util.* internal class ArbeidsgiverUtbetalingerTest { private var maksdato: LocalDate? = null private var gjenståendeSykedager: Int? = null private var forbrukteSykedager: Int? = 0 private lateinit var inspektør: UtbetalingstidslinjeInspektør private lateinit var aktivitetslogg: Aktivitetslogg private companion object { val UNG_PERSON_FNR_2018 = "12029240045".somFødselsnummer() val PERSON_67_ÅR_5_JANUAR_FNR_2018 = "05015112345".somFødselsnummer() val PERSON_68_ÅR_1_DESEMBER_2018 = "01125112345".somFødselsnummer() val PERSON_70_ÅR_1_FEBRUAR_2018 = "01024812345".somFødselsnummer() val ORGNUMMER = "888888888" } @Test fun `uavgrenset utbetaling`() { undersøke(UNG_PERSON_FNR_2018, 12.NAV) assertEquals(12, inspektør.size) assertEquals(10, inspektør.navDagTeller) assertEquals(2, inspektør.navHelgDagTeller) assertEquals(12000.0, inspektør.totalUtbetaling()) assertEquals(12.desember, maksdato) assertEquals(238, gjenståendeSykedager) assertTrue(aktivitetslogg.hasActivities()) assertFalse(aktivitetslogg.hasWarningsOrWorse()) } @Test fun `avgrenset betaling pga minimum inntekt`() { val vilkårsgrunnlagElement = VilkårsgrunnlagHistorikk.Grunnlagsdata( skjæringstidspunkt = 1.januar, sykepengegrunnlag = sykepengegrunnlag(1000.månedlig), sammenligningsgrunnlag = sammenligningsgrunnlag(1000.månedlig), avviksprosent = Prosent.prosent(0.0), opptjening = Opptjening.opptjening(emptyList(), 1.januar, MaskinellJurist()), medlemskapstatus = Medlemskapsvurdering.Medlemskapstatus.Ja, harMinimumInntekt = false, vurdertOk = false, meldingsreferanseId = UUID.randomUUID(), vilkårsgrunnlagId = UUID.randomUUID() ) undersøke(UNG_PERSON_FNR_2018, 5.NAV(12), 7.NAV, vilkårsgrunnlagElement = vilkårsgrunnlagElement) assertEquals(12, inspektør.size) assertEquals(0, inspektør.navDagTeller) assertEquals(2, inspektør.navHelgDagTeller) assertEquals(10, inspektør.avvistDagTeller) assertEquals(0.0, inspektør.totalUtbetaling()) assertEquals(26.desember, maksdato) assertEquals(248, gjenståendeSykedager) assertFalse(aktivitetslogg.hasErrorsOrWorse()) } @Test fun `avgrenset betaling pga maksimum inntekt`() { undersøke(UNG_PERSON_FNR_2018, 5.NAV(3500), 7.NAV) assertEquals(12, inspektør.size) assertEquals(10, inspektør.navDagTeller) assertEquals(2, inspektør.navHelgDagTeller) assertEquals(10805.0 + 6000.0, inspektør.totalUtbetaling()) assertEquals(12.desember, maksdato) assertEquals(238, gjenståendeSykedager) assertFalse(aktivitetslogg.hasErrorsOrWorse()) { aktivitetslogg.toString() } } @Test fun `avgrenset betaling pga minimun sykdomsgrad`() { undersøke(UNG_PERSON_FNR_2018, 5.NAV(1200, 19.0), 2.ARB, 5.NAV) assertEquals(12, inspektør.size) assertEquals(5, inspektør.avvistDagTeller) assertEquals(2, inspektør.arbeidsdagTeller) assertEquals(5, inspektør.navDagTeller) assertEquals(6000.0, inspektør.totalUtbetaling()) assertTrue(aktivitetslogg.hasWarningsOrWorse()) } @Test fun `avgrenset betaling pga oppbrukte sykepengedager`() { undersøke(PERSON_67_ÅR_5_JANUAR_FNR_2018, 7.UTELATE, 91.NAV) assertEquals(91, inspektør.size) assertEquals(60, inspektør.navDagTeller) assertEquals(26, inspektør.navHelgDagTeller) assertEquals(5, inspektør.avvistDagTeller) assertEquals(60 * 1200.0, inspektør.totalUtbetaling()) assertEquals(30.mars, maksdato) assertEquals(0, gjenståendeSykedager) assertTrue(aktivitetslogg.hentInfo().contains("Maks antall sykepengedager er nådd i perioden")) assertFalse(aktivitetslogg.hasErrorsOrWorse()) } @Test fun `avgrenset betaling pga oppbrukte sykepengedager i tillegg til beløpsgrenser`() { undersøke(PERSON_67_ÅR_5_JANUAR_FNR_2018, 7.UTELATE, 98.NAV) assertEquals(98, inspektør.size) assertEquals(60, inspektør.navDagTeller) assertEquals(28, inspektør.navHelgDagTeller) assertEquals(10, inspektør.avvistDagTeller) assertEquals((60 * 1200.0), inspektør.totalUtbetaling()) assertEquals(30.mars, maksdato) assertEquals(0, gjenståendeSykedager) assertTrue(aktivitetslogg.hentInfo().contains("Maks antall sykepengedager er nådd i perioden")) assertFalse(aktivitetslogg.hasErrorsOrWorse()) } @Test fun `historiske utbetalingstidslinjer vurdert i 248 grense`() { undersøke( PERSON_67_ÅR_5_JANUAR_FNR_2018, tidslinjeOf(35.UTELATE, 68.NAV), tidslinjeOf(7.UTELATE, 26.NAV) ) assertEquals(68, inspektør.size) assertEquals(40, inspektør.navDagTeller) assertEquals(10, inspektør.avvistDagTeller) assertEquals(40 * 1200.0, inspektør.totalUtbetaling()) assertEquals(30.mars, maksdato) assertEquals(0, gjenståendeSykedager) assertTrue(aktivitetslogg.hentInfo().contains("Maks antall sykepengedager er nådd i perioden")) assertFalse(aktivitetslogg.hasErrorsOrWorse()) } @Test fun `beregn maksdato i et sykdomsforløp som slutter på en fredag`() { undersøke(UNG_PERSON_FNR_2018, 16.AP, 4.NAV) assertEquals(28.desember, maksdato) // 3 dager already paid, 245 left. So should be fredag! assertEquals(245, gjenståendeSykedager) assertTrue(aktivitetslogg.hasActivities()) assertFalse(aktivitetslogg.hasWarningsOrWorse()) } @Test fun `beregn maksdato i et sykdomsforløp med opphold i sykdom`() { undersøke(UNG_PERSON_FNR_2018, 2.ARB, 16.AP, 7.ARB, 8.NAV) assertEquals(8.januar(2019), maksdato) assertEquals(242, gjenståendeSykedager) } @Test fun `beregn maksdato (med rest) der den ville falt på en lørdag`() { //(351.S + 1.F + 1.S) undersøke(UNG_PERSON_FNR_2018, 16.AP, 335.NAV, 1.FRI, 1.NAV) assertEquals(31.desember, maksdato) assertEquals(8, gjenståendeSykedager) } @Test fun `beregn maksdato (med rest) der den ville falt på en søndag`() { //(23.S + 2.F + 1.S) undersøke(UNG_PERSON_FNR_2018, 16.AP, 7.NAV, 2.FRI, 1.NAV) assertEquals(1.januar(2019), maksdato) assertEquals(242, gjenståendeSykedager) } @Test fun `maksdato forskyves av ferie etterfulgt av sykedager`() { //21.S + 3.F + 1.S) undersøke(UNG_PERSON_FNR_2018, 16.AP, 5.NAV, 3.FRI, 1.NAV) assertEquals(2.januar(2019), maksdato) assertEquals(244, gjenståendeSykedager) } @Test fun `maksdato forskyves ikke av ferie på tampen av sykdomstidslinjen`() { //(21.S + 3.F) undersøke(UNG_PERSON_FNR_2018, 16.AP, 5.NAV, 3.FRI) assertEquals(2.januar(2019), maksdato) assertEquals(245, gjenståendeSykedager) } @Test fun `maksdato forskyves ikke av ferie etterfulgt av arbeidsdag på tampen av sykdomstidslinjen`() { //(21.S + 3.F + 1.A) undersøke(UNG_PERSON_FNR_2018, 16.AP, 5.NAV, 3.FRI, 1.ARB) assertEquals(3.januar(2019), maksdato) assertEquals(245, gjenståendeSykedager) } @Test fun `setter maksdato når ingen dager er brukt`() { //(16.S) undersøke(UNG_PERSON_FNR_2018, 16.AP) assertEquals(28.desember, maksdato) assertEquals(248, gjenståendeSykedager) assertEquals(0, forbrukteSykedager) } @Test fun `når sykepengeperioden går over maksdato, så skal utbetaling stoppe ved maksdato`() { //(249.NAV) undersøke(UNG_PERSON_FNR_2018, 16.AP, 349.NAV) assertEquals(28.desember, maksdato) assertEquals(0, gjenståendeSykedager) assertEquals(248, inspektør.navDagTeller) assertTrue(aktivitetslogg.hentInfo().contains("Maks antall sykepengedager er nådd i perioden")) assertFalse(aktivitetslogg.hasWarningsOrWorse()) } @Test fun `når personen fyller 67 blir antall gjenværende dager 60`() { undersøke(PERSON_67_ÅR_5_JANUAR_FNR_2018, 16.AP, 94.NAV) assertEquals(10.april, maksdato) assertEquals(0, gjenståendeSykedager) assertEquals(60, inspektør.navDagTeller) assertTrue(aktivitetslogg.hentInfo().contains("Maks antall sykepengedager er nådd i perioden")) assertFalse(aktivitetslogg.hasWarningsOrWorse()) } @Test fun `når personen fyller 67 og 248 dager er brukt opp`() { undersøke(PERSON_68_ÅR_1_DESEMBER_2018, 16.AP, 366.NAV) assertEquals(28.desember, maksdato) assertEquals(0, gjenståendeSykedager) assertTrue(aktivitetslogg.hentInfo().contains("Maks antall sykepengedager er nådd i perioden")) assertFalse(aktivitetslogg.hasWarningsOrWorse()) } @Test fun `når personen fyller 70 skal det ikke utbetales sykepenger`() { undersøke(PERSON_70_ÅR_1_FEBRUAR_2018, 1.NAV, startdato = 1.februar) assertEquals(31.januar, maksdato) assertEquals(0, gjenståendeSykedager) assertEquals(0, forbrukteSykedager) } private fun undersøke( fnr: Fødselsnummer, vararg utbetalingsdager: Utbetalingsdager, vilkårsgrunnlagElement: VilkårsgrunnlagHistorikk.VilkårsgrunnlagElement? = null, startdato: LocalDate = 1.januar ) { val tidslinje = tidslinjeOf(*utbetalingsdager, startDato = startdato) undersøke(fnr, tidslinje, tidslinjeOf(), vilkårsgrunnlagElement) } private fun undersøke( fnr: Fødselsnummer, arbeidsgiverTidslinje: Utbetalingstidslinje, historiskTidslinje: Utbetalingstidslinje, vilkårsgrunnlagElement: VilkårsgrunnlagHistorikk.VilkårsgrunnlagElement? = null ) { val person = Person("aktørid", fnr, MaskinellJurist()) // seed arbeidsgiver med sykdomshistorikk val førsteDag = arbeidsgiverTidslinje.periode().start val sisteDag = arbeidsgiverTidslinje.periode().endInclusive person.håndter( Sykmelding( meldingsreferanseId = UUID.randomUUID(), fnr = UNG_PERSON_FNR_2018.toString(), aktørId = "", orgnummer = ORGNUMMER, sykeperioder = listOf(Sykmeldingsperiode(førsteDag, sisteDag, 100.prosent)), sykmeldingSkrevet = 1.januar.atStartOfDay(), mottatt = 1.januar.atStartOfDay() ) ) val vilkårsgrunnlagHistorikk = VilkårsgrunnlagHistorikk() vilkårsgrunnlagHistorikk.lagre( 1.januar, vilkårsgrunnlagElement ?: VilkårsgrunnlagHistorikk.Grunnlagsdata( skjæringstidspunkt = 1.januar, sykepengegrunnlag = sykepengegrunnlag(30000.månedlig), sammenligningsgrunnlag = sammenligningsgrunnlag(30000.månedlig), avviksprosent = Prosent.prosent(0.0), opptjening = Opptjening.opptjening(emptyList(), 1.januar, MaskinellJurist()), medlemskapstatus = Medlemskapsvurdering.Medlemskapstatus.Ja, harMinimumInntekt = true, vurdertOk = true, meldingsreferanseId = UUID.randomUUID(), vilkårsgrunnlagId = UUID.randomUUID() ) ) person.håndter( inntektsmelding = Inntektsmelding( meldingsreferanseId = UUID.randomUUID(), refusjon = Inntektsmelding.Refusjon(30000.månedlig, null), orgnummer = ORGNUMMER, fødselsnummer = AbstractPersonTest.UNG_PERSON_FNR_2018.toString(), aktørId = AbstractPersonTest.AKTØRID, førsteFraværsdag = førsteDag, beregnetInntekt = 30000.månedlig, arbeidsgiverperioder = listOf(), arbeidsforholdId = null, begrunnelseForReduksjonEllerIkkeUtbetalt = null, harOpphørAvNaturalytelser = false, mottatt = LocalDateTime.now() ) ) aktivitetslogg = Aktivitetslogg() val infotrygdhistorikk = Infotrygdhistorikk().apply { this.oppdaterHistorikk( InfotrygdhistorikkElement.opprett( oppdatert = LocalDateTime.now(), hendelseId = UUID.randomUUID(), perioder = historiskTidslinje.takeIf(Utbetalingstidslinje::isNotEmpty)?.let { listOf(infotrygdperiodeMockMed(it)) } ?: emptyList(), inntekter = emptyList(), arbeidskategorikoder = emptyMap(), ugyldigePerioder = emptyList(), harStatslønn = false ) ) } ArbeidsgiverUtbetalinger( NormalArbeidstaker, mapOf(person.arbeidsgiver(ORGNUMMER) to object : IUtbetalingstidslinjeBuilder { override fun result() = arbeidsgiverTidslinje override fun fridag(dato: LocalDate) {} override fun arbeidsdag(dato: LocalDate) {} override fun arbeidsgiverperiodedag(dato: LocalDate, økonomi: Økonomi) {} override fun utbetalingsdag(dato: LocalDate, økonomi: Økonomi) {} override fun foreldetDag(dato: LocalDate, økonomi: Økonomi) {} override fun avvistDag(dato: LocalDate, begrunnelse: Begrunnelse) {} }), infotrygdhistorikk, fnr.alder(), null, vilkårsgrunnlagHistorikk, MaskinellJurist() ).also { it.beregn(aktivitetslogg, "88888888", Periode(1.januar, 31.desember(2019))) maksdato = it.maksimumSykepenger.sisteDag() gjenståendeSykedager = it.maksimumSykepenger.gjenståendeDager() forbrukteSykedager = it.maksimumSykepenger.forbrukteDager() } inspektør = person.arbeidsgiver(ORGNUMMER).nåværendeTidslinje().inspektør } private fun infotrygdperiodeMockMed(historiskTidslinje: Utbetalingstidslinje) = object : Infotrygdperiode(historiskTidslinje.periode().start, historiskTidslinje.periode().endInclusive) { override fun accept(visitor: InfotrygdhistorikkVisitor) {} override fun utbetalingstidslinje() = historiskTidslinje } private fun sykepengegrunnlag(inntekt: Inntekt) = Sykepengegrunnlag( arbeidsgiverInntektsopplysninger = listOf(), sykepengegrunnlag = inntekt, grunnlagForSykepengegrunnlag = inntekt, begrensning = ER_IKKE_6G_BEGRENSET, deaktiverteArbeidsforhold = emptyList() ) private fun sammenligningsgrunnlag(inntekt: Inntekt) = Sammenligningsgrunnlag( arbeidsgiverInntektsopplysninger = listOf( ArbeidsgiverInntektsopplysning("orgnummer", Inntektshistorikk.SkattComposite(UUID.randomUUID(), (0 until 12).map { Inntektshistorikk.Skatt.Sammenligningsgrunnlag( dato = LocalDate.now(), hendelseId = UUID.randomUUID(), beløp = inntekt, måned = YearMonth.of(2017, it + 1), type = Inntektshistorikk.Skatt.Inntekttype.LØNNSINNTEKT, fordel = "fordel", beskrivelse = "beskrivelse" ) }) )), ) }
0
null
2
4
a3ba622f138449986fc9fd44e467104a61b95577
16,720
helse-spleis
MIT License
src/main/kotlin/id/walt/model/DidKey.kt
walt-id
392,607,264
false
null
package id.walt.model class DidKey( context: List<String>, id: String, verificationMethod: List<VerificationMethod>? = null, authentication: List<String>? = null, assertionMethod: List<String>? = null, capabilityDelegation: List<String>? = null, capabilityInvocation: List<String>? = null, keyAgreement: List<String>? = null, serviceEndpoint: List<ServiceEndpoint>? = null ) : Did( context, id, verificationMethod, authentication, assertionMethod, capabilityDelegation, capabilityInvocation, keyAgreement, serviceEndpoint ) { constructor(context: String, id: String, verificationMethod: List<VerificationMethod>? = null, authentication: List<String>? = null, assertionMethod: List<String>? = null, capabilityDelegation: List<String>? = null, capabilityInvocation: List<String>? = null, keyAgreement: List<String>? = null, serviceEndpoint: List<ServiceEndpoint>? = null) : this(listOf(context), id, verificationMethod, authentication, assertionMethod, capabilityDelegation, capabilityInvocation, keyAgreement, serviceEndpoint) }
6
Kotlin
7
34
fb96ecb2e02409791fa7aae4126b0094bdcd7c1e
1,178
waltid-ssikit
Apache License 2.0
app/src/main/java/com/horizon/lightkvdemo/ui/MainActivity.kt
msdgwzhy6
138,707,623
true
{"Java": 89286, "Kotlin": 2731}
package com.horizon.lightkvdemo.ui import android.os.Bundle import android.text.TextUtils import android.util.Log import com.horizon.lightkvdemo.R import com.horizon.lightkvdemo.base.BaseActivity import com.horizon.lightkvdemo.config.AppData import kotlinx.android.synthetic.main.activity_main.* class MainActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) printShowTime() val account = AppData.getString(AppData.Keys.ACCOUNT) Log.d(TAG, "account:" + account) if(TextUtils.isEmpty(account)){ AppData.putString(AppData.Keys.ACCOUNT, "<EMAIL>") } val token = AppData.getString(AppData.Keys.TOKEN) Log.d(TAG, "token:" + token) if(TextUtils.isEmpty(token)){ AppData.putString(AppData.Keys.TOKEN, "<PASSWORD>") } val secret = AppData.getArray(AppData.Keys.SECRET) if(secret != null){ Log.d(TAG, "secret:" + String(secret)) }else{ AppData.putArray(AppData.Keys.SECRET, "I love you baby".toByteArray()) } } private fun printShowTime() { val showTime = AppData.getInt(AppData.Keys.SHOW_COUNT) + 1 helloTv.text = getString(R.string.main_tips, showTime, AppData.data().toString()) Log.d(TAG, AppData.data().toString()); AppData.putInt(AppData.Keys.SHOW_COUNT, showTime) } }
0
Java
0
1
bd5ba059917d091e99985c0a190d085ec96d249e
1,494
LightKV
Apache License 2.0
app/src/main/java/com/bereguliak/arscheduler/ui/activity/main/MainNavigator.kt
YuriyBereguliak
177,011,797
false
null
package com.bereguliak.arscheduler.ui.activity.main import android.support.annotation.UiThread import com.bereguliak.arscheduler.model.CalendarLocation @UiThread interface MainNavigator { fun showLoadingScreen() fun showConnectionScreen() fun showCalendarDetailsScreen(calendar: CalendarLocation) fun showArSchedulerScreen() fun showMyCalendarArScheduler(calendar: CalendarLocation) fun showSettingsScreen() }
0
Kotlin
0
2
562dca9b6595baab35f395c5dac386c4720cfce8
435
ArScheduler
MIT License
src/commonMain/kotlin/klox/interpreter/Environment.kt
andrewrlee
423,130,411
false
{"Kotlin": 49848}
package klox.interpreter import klox.interpreter.Interpreter.RuntimeError class Environment(val enclosing: Environment? = null) { private val values = mutableMapOf<String, Any?>() fun define(name: String, value: Any?) = values.put(name, value) operator fun get(name: Token): Any? { if (values.containsKey(name.lexeme)) { return values[name.lexeme] } if (enclosing != null) { return enclosing[name] } throw RuntimeError(name, "Undefined variable: '${name.lexeme}'") } fun assign(name: Token, value: Any?) { if (values.containsKey(name.lexeme)) { values[name.lexeme] = value return } if (enclosing != null) { enclosing.assign(name, value) return } throw RuntimeError(name, "Undefined variable '${name.lexeme}'") } fun getAt(distance: Int, name: String): Any? = ancestor(distance).values[name] fun assignAt(distance: Int, name: Token, value: Any?) { ancestor(distance).values[name.lexeme] = value } private fun ancestor(distance: Int): Environment { var environment = this var i = 0 while (i < distance) { environment = environment.enclosing!! i++ } return environment } }
0
Kotlin
0
0
2a6d2fdbf31c7d7215a8acd79345ff7079e3b6d4
1,345
klox
MIT License
app/src/main/java/com/vultisig/wallet/ui/screens/keysign/KeysignPeerDiscovery.kt
vultisig
789,965,982
false
{"Kotlin": 1481084, "Ruby": 1713}
package com.vultisig.wallet.ui.screens.keysign import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.asFlow import com.vultisig.wallet.R import com.vultisig.wallet.common.Utils import com.vultisig.wallet.data.models.Vault import com.vultisig.wallet.data.models.payload.KeysignPayload import com.vultisig.wallet.presenter.keygen.NetworkPromptOption import com.vultisig.wallet.presenter.keysign.KeysignFlowState import com.vultisig.wallet.presenter.keysign.KeysignFlowViewModel import com.vultisig.wallet.ui.components.MultiColorButton import com.vultisig.wallet.ui.screens.PeerDiscoveryView import com.vultisig.wallet.ui.theme.Theme import timber.log.Timber @Composable internal fun KeysignPeerDiscovery( vault: Vault, keysignPayload: KeysignPayload, viewModel: KeysignFlowViewModel, ) { val selectionState = viewModel.selection.asFlow().collectAsState(initial = emptyList()).value val participants = viewModel.participants.asFlow().collectAsState(initial = emptyList()).value val context = LocalContext.current.applicationContext LaunchedEffect(key1 = viewModel.participants) { viewModel.participants.asFlow().collect { newList -> // add all participants to the selection for (participant in newList) { viewModel.addParticipant(participant) } } } LaunchedEffect(key1 = viewModel.selection) { viewModel.selection.asFlow().collect { newList -> if (vault.signers.isEmpty()) { Timber.e("Vault signers size is 0") return@collect } if (newList.size >= Utils.getThreshold(vault.signers.size)) { // automatically kickoff keysign viewModel.moveToState(KeysignFlowState.KEYSIGN) } } } LaunchedEffect(Unit) { // start mediator server viewModel.setData(vault, context, keysignPayload) } DisposableEffect(Unit) { onDispose { viewModel.stopParticipantDiscovery() } } KeysignPeerDiscovery( selectionState = selectionState, participants = participants, keysignMessage = viewModel.keysignMessage.value, networkPromptOption = viewModel.networkOption.value, onChangeNetwork = { viewModel.changeNetworkPromptOption(it, context) }, onAddParticipant = { viewModel.addParticipant(it) }, onRemoveParticipant = { viewModel.removeParticipant(it) }, onStopParticipantDiscovery = { viewModel.stopParticipantDiscovery() viewModel.moveToState(KeysignFlowState.KEYSIGN) } ) } @Composable internal fun KeysignPeerDiscovery( selectionState: List<String>, participants: List<String>, keysignMessage: String, networkPromptOption: NetworkPromptOption, onChangeNetwork: (NetworkPromptOption) -> Unit = {}, onAddParticipant: (String) -> Unit = {}, onRemoveParticipant: (String) -> Unit = {}, onStopParticipantDiscovery: () -> Unit = {}, ) { Scaffold(bottomBar = { MultiColorButton( text = stringResource(R.string.keysign_peer_discovery_start), backgroundColor = Theme.colors.turquoise600Main, textColor = Theme.colors.oxfordBlue600Main, minHeight = 45.dp, textStyle = Theme.montserrat.subtitle1, disabled = selectionState.size < 2, modifier = Modifier .fillMaxWidth() .padding( vertical = 16.dp, horizontal = 16.dp, ), onClick = onStopParticipantDiscovery, ) }) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .background(Theme.colors.oxfordBlue800) .fillMaxSize() .padding(it) ) { PeerDiscoveryView( selectionState = selectionState, participants = participants, keygenPayloadState = keysignMessage, networkPromptOption = networkPromptOption, onChangeNetwork = onChangeNetwork, onAddParticipant = onAddParticipant, onRemoveParticipant = onRemoveParticipant, ) } } } @Preview @Composable private fun KeysignPeerDiscoveryPreview() { KeysignPeerDiscovery( selectionState = listOf("1", "2"), participants = listOf("1", "2", "3"), keysignMessage = "keysignMessage", networkPromptOption = NetworkPromptOption.LOCAL, ) }
44
Kotlin
2
6
9a24026e09bafb8667f90c8ec7e3e806697e8a08
5,339
vultisig-android
Apache License 2.0
lib/src/test/java/com/what3words/androidwrapper/datasource/text/api/What3WordsV3ServiceTest.kt
what3words
201,899,599
false
{"Gradle": 6, "YAML": 2, "Markdown": 107, "Java Properties": 1, "Shell": 1, "Text": 2, "Ignore List": 2, "Batchfile": 1, "INI": 2, "Proguard": 2, "Kotlin": 99, "JSON": 9, "XML": 1}
package com.what3words.androidwrapper.datasource.text.api import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import com.what3words.androidwrapper.common.extensions.W3WDomainToApiStringExtensions.toQueryMap import com.what3words.androidwrapper.datasource.text.api.di.MappersFactory import com.what3words.androidwrapper.datasource.text.api.error.BadBoundingBoxError import com.what3words.androidwrapper.datasource.text.api.error.BadBoundingBoxTooBigError import com.what3words.androidwrapper.datasource.text.api.error.BadClipToCircleError import com.what3words.androidwrapper.datasource.text.api.error.BadCoordinatesError import com.what3words.androidwrapper.datasource.text.api.error.BadFocusError import com.what3words.androidwrapper.datasource.text.api.error.NetworkError import com.what3words.androidwrapper.datasource.text.api.error.UnknownError import com.what3words.androidwrapper.datasource.text.api.retrofit.W3WV3RetrofitApiClient.executeApiRequestAndHandleResponse import com.what3words.core.types.common.W3WResult import com.what3words.core.types.geometry.W3WCircle import com.what3words.core.types.geometry.W3WCoordinates import com.what3words.core.types.geometry.W3WDistance import com.what3words.core.types.options.W3WAutosuggestOptions import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.SocketPolicy import org.junit.After import org.junit.Before import org.junit.Test import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory class What3WordsV3ServiceTest { private var mockWebServer = MockWebServer() private lateinit var what3WordsV3Service: What3WordsV3Service @Before fun setup() { mockWebServer.start() val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() what3WordsV3Service = Retrofit.Builder() .baseUrl(mockWebServer.url("/")) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(What3WordsV3Service::class.java) } @After fun teardown() { mockWebServer.shutdown() } @Test fun `convert valid coordinates to 3wa should return 3wa`() = runTest { // Arrange val coordinates = "51.521251, 0.203586" val expectedResponseData = """ { "country": "GB", "square": { "southwest": { "lng": -0.203607, "lat": 51.521238 }, "northeast": { "lng": -0.203564, "lat": 51.521265 } }, "nearestPlace": "Bayswater, London", "coordinates": { "lng": -0.203586, "lat": 51.521251 }, "words": "index.home.raft", "language": "en", "map": "https://w3w.co/index.home.raft" } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.convertTo3wa(coordinates, null, null) // Assert assert(response.isSuccessful) assert(response.body()?.words == "index.home.raft") } @Test fun `convert invalid coordinates should return error`() = runTest { // Arrange val invalidCoordinates = "191.521251, 0.203586" val expectedResponseData = """ { "error": { "code": "BadCoordinates", "message": "latitude must be >=-90 and <= 90" } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesConvertTo3waDtoToDomainMapper()) { what3WordsV3Service.convertTo3wa(invalidCoordinates, null, null) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is BadCoordinatesError) } @Test fun `convert valid coordinates with Vietnamese language should return Vietnamese 3wa`() = runTest { // Arrange val coordinates = "51.521251, 0.203586" val language = "vi" val expectedResponseData = """ { "country": "GB", "square": { "southwest": { "lng": -0.203607, "lat": 51.521238 }, "northeast": { "lng": -0.203564, "lat": 51.521265 } }, "nearestPlace": "Luân Đôn", "coordinates": { "lng": -0.203586, "lat": 51.521251 }, "words": "nước yến.nét vẽ.đồ gốm", "language": "vi", "map": "https://w3w.co/n%C6%B0%E1%BB%9Bc+y%E1%BA%BFn.n%C3%A9t+v%E1%BA%BD.%C4%91%E1%BB%93+g%E1%BB%91m" } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.convertTo3wa(coordinates, language, null) // Assert assert(response.isSuccessful) assert(response.body()?.words == "nước yến.nét vẽ.đồ gốm") assert(response.body()?.locale == null) } @Test fun `convert valid coordinates with Kazakh Latin locale should return kk_la 3wa`() = runTest { // Arrange val coordinates = "51.521251, 0.203586" val locale = "kk_la" val expectedResponseData = """ { "country": "GB", "square": { "southwest": { "lng": -0.203607, "lat": 51.521238 }, "northeast": { "lng": -0.203564, "lat": 51.521265 } }, "nearestPlace": "Bayswater, London", "coordinates": { "lng": -0.203586, "lat": 51.521251 }, "words": "otyr.tıredık.säulettı", "language": "kk", "locale": "kk_la", "map": "https://w3w.co/otyr.t%C4%B1red%C4%B1k.s%C3%A4ulett%C4%B1" } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.convertTo3wa(coordinates, null, locale) // Assert assert(response.isSuccessful) assert(response.body()?.words == "otyr.tıredık.säulettı") assert(response.body()?.locale == "kk_la") } @Test fun `convert valid w3a to coordinates should return coordinates`() = runTest { // Arrange val w3a = "index.home.raft" val expectedResponseData = """ { "country": "GB", "square": { "southwest": { "lng": -0.203607, "lat": 51.521238 }, "northeast": { "lng": -0.203564, "lat": 51.521265 } }, "nearestPlace": "Bayswater, London", "coordinates": { "lng": -0.203586, "lat": 51.521251 }, "words": "index.home.raft", "language": "en", "map": "https://w3w.co/index.home.raft" } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.convertToCoordinates(w3a) // Assert assert(response.isSuccessful) assert(response.body()?.coordinates?.lat == 51.521251) assert(response.body()?.coordinates?.lng == -0.203586) } @Test fun `convert null to coordinates should return error`() = runBlocking { // Arrange val w3a = null val expectedResponseData = """ { "error": { "code": "MissingWords", "message": "words must be specified" } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesConvertToCoordinatesResponseMapper()) { what3WordsV3Service.convertToCoordinates(w3a) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is UnknownError) } @Test fun `available language should return list of supported language`() = runTest { // Arrange val expectedResponseData = """ { "languages": [ { "nativeName": "Deutsch", "code": "de", "name": "German" }, { "nativeName": "हिन्दी", "code": "hi", "name": "Hindi" }, { "nativeName": "ລາວ", "code": "lo", "name": "Lao" }, { "nativeName": "Português", "code": "pt", "name": "Portuguese" }, { "nativeName": "Magyar", "code": "hu", "name": "Hungarian" }, { "nativeName": "Українська", "code": "uk", "name": "Ukrainian" }, { "nativeName": "Bahasa Indonesia", "code": "id", "name": "Bahasa Indonesia" }, { "nativeName": "اردو", "code": "ur", "name": "Urdu" }, { "nativeName": "മലയാളം", "code": "ml", "name": "Malayalam" }, { "nativeName": "<NAME>", "code": "mn", "name": "Mongolian", "locales": [ { "nativeName": "<NAME> (Латинаар)", "name": "Mongolian (Latin)", "code": "mn_la" }, { "nativeName": "<NAME> (Криллээр)", "name": "Mongolian (Cyrillic)", "code": "mn_cy" } ] }, { "nativeName": "Afrikaans", "code": "af", "name": "Afrikaans" }, { "nativeName": "मराठी", "code": "mr", "name": "Marathi" }, { "nativeName": "Bahasa Malaysia", "code": "ms", "name": "Bahasa Malaysia" }, { "nativeName": "Ελληνικά", "code": "el", "name": "Greek" }, { "nativeName": "English", "code": "en", "name": "English" }, { "nativeName": "Italiano", "code": "it", "name": "Italian" }, { "nativeName": "አማርኛ", "code": "am", "name": "Amharic" }, { "nativeName": "Español", "code": "es", "name": "Spanish" }, { "nativeName": "中文", "code": "zh", "name": "Chinese", "locales": [ { "nativeName": "中文(繁體)", "name": "Chinese (Traditional)", "code": "zh_tr" }, { "nativeName": "中文(简体)", "name": "Chinese (Simplified)", "code": "zh_si" } ] }, { "nativeName": "Eesti", "code": "et", "name": "Estonian" }, { "nativeName": "العربية", "code": "ar", "name": "Arabic" }, { "nativeName": "Tiếng Việt", "code": "vi", "name": "Vietnamese" }, { "nativeName": "日本語", "code": "ja", "name": "Japanese" }, { "nativeName": "नेपाली", "code": "ne", "name": "Nepali" }, { "nativeName": "فارسی", "code": "fa", "name": "Persian" }, { "nativeName": "isiZulu", "code": "zu", "name": "isiZulu" }, { "nativeName": "Română", "code": "ro", "name": "Romanian" }, { "nativeName": "Nederlands", "code": "nl", "name": "Dutch" }, { "nativeName": "Norsk", "code": "no", "name": "Norwegian" }, { "nativeName": "Suomi", "code": "fi", "name": "Finnish" }, { "nativeName": "Русский", "code": "ru", "name": "Russian" }, { "nativeName": "български", "code": "bg", "name": "Bulgarian" }, { "nativeName": "বাংলা", "code": "bn", "name": "Bengali" }, { "nativeName": "Français", "code": "fr", "name": "French" }, { "nativeName": "සිංහල", "code": "si", "name": "Sinhala" }, { "nativeName": "Slovenčina", "code": "sk", "name": "Slovak" }, { "nativeName": "Català", "code": "ca", "name": "Catalan" }, { "nativeName": "Қазақ тілі", "code": "kk", "name": "Kazakh", "locales": [ { "nativeName": "Қазақ тілі (кирилл)", "name": "Kazakh (Cyrillic)", "code": "kk_cy" }, { "nativeName": "Qazaq tılı (Latyn)", "name": "Kazakh (Latin)", "code": "kk_la" } ] }, { "nativeName": "Bosanski-Crnogorski-Hrvatski-Srpski", "code": "oo", "name": "Bosnian-Croatian-Montenegrin-Serbian", "locales": [ { "nativeName": "Bosanski-Crnogorski-Hrvatski-Srpski (latinica)", "name": "Bosnian-Croatian-Montenegrin-Serbian (Latin)", "code": "oo_la" }, { "nativeName": "Босански-Српски-Хрватски-Црногорски (ћирилица)", "name": "Bosnian-Croatian-Montenegrin-Serbian (Cyrillic)", "code": "oo_cy" } ] }, { "nativeName": "ភាសាខ្មែរ", "code": "km", "name": "Khmer" }, { "nativeName": "ಕನ್ನಡ", "code": "kn", "name": "Kannada" }, { "nativeName": "ଓଡ଼ିଆ", "code": "or", "name": "Odia" }, { "nativeName": "Svenska", "code": "sv", "name": "Swedish" }, { "nativeName": "한국어", "code": "ko", "name": "Korean" }, { "nativeName": "Kiswahili", "code": "sw", "name": "Swahili" }, { "nativeName": "தமிழ்", "code": "ta", "name": "Tamil" }, { "nativeName": "ગુજરાતી", "code": "gu", "name": "Gujarati" }, { "nativeName": "Čeština", "code": "cs", "name": "Czech" }, { "nativeName": "isiXhosa", "code": "xh", "name": "isiXhosa" }, { "nativeName": "ਪੰਜਾਬੀ", "code": "pa", "name": "Punjabi" }, { "nativeName": "తెలుగు", "code": "te", "name": "Telugu" }, { "nativeName": "ไทย", "code": "th", "name": "Thai" }, { "nativeName": "Cymraeg", "code": "cy", "name": "Welsh" }, { "nativeName": "Polski", "code": "pl", "name": "Polish" }, { "nativeName": "Dansk", "code": "da", "name": "Danish" }, { "nativeName": "עברית", "code": "he", "name": "Hebrew" }, { "nativeName": "Türkçe", "code": "tr", "name": "Turkish" } ] } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.availableLanguages() // Assert assert(response.isSuccessful) assert(response.body()?.languages?.size == 57) } @Test fun `Grid section with valid bounding box and format JSON should return what3word grid in JSON format`() = runTest { // Arrange val boundingBox = "52.207988,0.116126,52.208867,0.117540" val expectedResponseData = """ { "lines": [ { "start": { "lng": 0.116126, "lat": 52.208009918068136 }, "end": { "lng": 0.11754, "lat": 52.208009918068136 } }, { "start": { "lng": 0.116126, "lat": 52.20803686934023 }, "end": { "lng": 0.11754, "lat": 52.20803686934023 } } ] } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.gridSection(boundingBox) // Assert assert(response.isSuccessful) assert(response.body()?.lines?.size == 2) assert(response.body()?.lines?.get(0)?.start?.lat == 52.208009918068136) assert(response.body()?.lines?.get(0)?.start?.lng == 0.116126) } @Test fun `Grid section with invalid bounding box should return BadBoundingBoxError`() = runTest { val boundingBox = "172.207988,0.116126,52.208867,0.117540" val expectedResponseData = """ { "error": { "code": "BadBoundingBox", "message": "Invalid bounding-box. Must be lat,lng,lat,lng with -90 <= lat <= 90." } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesGridSectionResponseMapper()) { what3WordsV3Service.gridSection(boundingBox) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is BadBoundingBoxError) } @Test fun `Grid section with too big bounding box should return BadBoundingBoxTooBigError`() { val boundingBox = "0.207988,0.116126,52.208867,0.117540" val expectedResponseData = """ { "error": { "code": "BadBoundingBoxTooBig", "message": "The diagonal of bounding-box may not be > 4km" } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesGridSectionResponseMapper()) { what3WordsV3Service.gridSection(boundingBox) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is BadBoundingBoxTooBigError) } @Test fun `autosuggest with valid input should return list of suggestions`() = runTest { // Arrange val input = "index.home.raf" val expectedResponseData = """ { "suggestions": [ { "country": "GB", "nearestPlace": "Bayswater, London", "words": "index.home.raft", "rank": 1, "language": "en" }, { "country": "US", "nearestPlace": "Prosperity, West Virginia", "words": "indexes.home.raft", "rank": 2, "language": "en" }, { "country": "US", "nearestPlace": "Greensboro, North Carolina", "words": "index.homes.raft", "rank": 3, "language": "en" } ] } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.autosuggest(input, emptyMap()) // Assert assert(response.isSuccessful) assert(response.body()?.suggestions?.size == 3) assert(response.body()?.suggestions?.get(0)?.words == "index.home.raft") } @Test fun `autosuggest with invalid input should return empty suggestions`() = runTest { // Arrange val input = "index.hom" val expectedResponseData = """ { "suggestions": [] } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.autosuggest(input, emptyMap()) // Assert assert(response.isSuccessful) assert(response.body()?.suggestions?.size == 0) } @Test fun `autosuggest with option of 4 n-results should return 4 suggestions`() = runTest { // Arrange val input = "index.home.raf" val options = W3WAutosuggestOptions.Builder().nResults(4).build() val expectedResponseData = """ { "suggestions": [ { "country": "GB", "nearestPlace": "Bayswater, London", "words": "index.home.raft", "rank": 1, "language": "en" }, { "country": "US", "nearestPlace": "Prosperity, West Virginia", "words": "indexes.home.raft", "rank": 2, "language": "en" }, { "country": "US", "nearestPlace": "Greensboro, North Carolina", "words": "index.homes.raft", "rank": 3, "language": "en" }, { "country": "AU", "nearestPlace": "Melville, Western Australia", "words": "index.home.rafts", "rank": 4, "language": "en" } ] } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.autosuggest(input, options.toQueryMap()) // Assert assert(response.isSuccessful) assert(response.body()?.suggestions?.size == 4) } @Test fun `autosuggest with invalid focus option should return BadFocusError`() = runTest { // Arrange val input = "index.home.raf" val options = W3WAutosuggestOptions.Builder().focus(W3WCoordinates(250.842404, 4.361177)).build() val expectedResponseData = """ { "error": { "code": "BadFocus", "message": "lat must be >= -90 and <=90" } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesAutosuggestResponseMapper()) { what3WordsV3Service.autosuggest(input, options.toQueryMap()) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is BadFocusError) } @Test fun `autosuggest with invalid clip to circle option should return BadClipToCircle`() = runTest { // Arrange val input = "index.home.raf" val options = W3WAutosuggestOptions.Builder() .clipToCircle( W3WCircle(W3WCoordinates(250.842404, 4.361177), W3WDistance(1.0)) ).build() val clipToCircle = "250.842404,4.361177" val expectedResponseData = """ { "error": { "code": "BadClipToCircle", "message": "latitudes must be >=-90 and <=90" } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesAutosuggestResponseMapper()) { what3WordsV3Service.autosuggest( input, options.toQueryMap() ) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is BadClipToCircleError) } @Test fun `test request timeout is handled gracefully`() = runTest { val input = "index.home.raf" mockWebServer.enqueue( MockResponse() .setSocketPolicy(SocketPolicy.NO_RESPONSE) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesAutosuggestResponseMapper()) { what3WordsV3Service.autosuggest( input, emptyMap() ) } assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is NetworkError) } }
1
null
2
1
95ab9c58149bff97acb4ae2aa7900489e245b133
33,204
w3w-android-wrapper
MIT License
lib/src/test/java/com/what3words/androidwrapper/datasource/text/api/What3WordsV3ServiceTest.kt
what3words
201,899,599
false
{"Gradle": 6, "YAML": 2, "Markdown": 107, "Java Properties": 1, "Shell": 1, "Text": 2, "Ignore List": 2, "Batchfile": 1, "INI": 2, "Proguard": 2, "Kotlin": 99, "JSON": 9, "XML": 1}
package com.what3words.androidwrapper.datasource.text.api import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import com.what3words.androidwrapper.common.extensions.W3WDomainToApiStringExtensions.toQueryMap import com.what3words.androidwrapper.datasource.text.api.di.MappersFactory import com.what3words.androidwrapper.datasource.text.api.error.BadBoundingBoxError import com.what3words.androidwrapper.datasource.text.api.error.BadBoundingBoxTooBigError import com.what3words.androidwrapper.datasource.text.api.error.BadClipToCircleError import com.what3words.androidwrapper.datasource.text.api.error.BadCoordinatesError import com.what3words.androidwrapper.datasource.text.api.error.BadFocusError import com.what3words.androidwrapper.datasource.text.api.error.NetworkError import com.what3words.androidwrapper.datasource.text.api.error.UnknownError import com.what3words.androidwrapper.datasource.text.api.retrofit.W3WV3RetrofitApiClient.executeApiRequestAndHandleResponse import com.what3words.core.types.common.W3WResult import com.what3words.core.types.geometry.W3WCircle import com.what3words.core.types.geometry.W3WCoordinates import com.what3words.core.types.geometry.W3WDistance import com.what3words.core.types.options.W3WAutosuggestOptions import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.SocketPolicy import org.junit.After import org.junit.Before import org.junit.Test import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory class What3WordsV3ServiceTest { private var mockWebServer = MockWebServer() private lateinit var what3WordsV3Service: What3WordsV3Service @Before fun setup() { mockWebServer.start() val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() what3WordsV3Service = Retrofit.Builder() .baseUrl(mockWebServer.url("/")) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(What3WordsV3Service::class.java) } @After fun teardown() { mockWebServer.shutdown() } @Test fun `convert valid coordinates to 3wa should return 3wa`() = runTest { // Arrange val coordinates = "51.521251, 0.203586" val expectedResponseData = """ { "country": "GB", "square": { "southwest": { "lng": -0.203607, "lat": 51.521238 }, "northeast": { "lng": -0.203564, "lat": 51.521265 } }, "nearestPlace": "Bayswater, London", "coordinates": { "lng": -0.203586, "lat": 51.521251 }, "words": "index.home.raft", "language": "en", "map": "https://w3w.co/index.home.raft" } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.convertTo3wa(coordinates, null, null) // Assert assert(response.isSuccessful) assert(response.body()?.words == "index.home.raft") } @Test fun `convert invalid coordinates should return error`() = runTest { // Arrange val invalidCoordinates = "191.521251, 0.203586" val expectedResponseData = """ { "error": { "code": "BadCoordinates", "message": "latitude must be >=-90 and <= 90" } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesConvertTo3waDtoToDomainMapper()) { what3WordsV3Service.convertTo3wa(invalidCoordinates, null, null) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is BadCoordinatesError) } @Test fun `convert valid coordinates with Vietnamese language should return Vietnamese 3wa`() = runTest { // Arrange val coordinates = "51.521251, 0.203586" val language = "vi" val expectedResponseData = """ { "country": "GB", "square": { "southwest": { "lng": -0.203607, "lat": 51.521238 }, "northeast": { "lng": -0.203564, "lat": 51.521265 } }, "nearestPlace": "Luân Đôn", "coordinates": { "lng": -0.203586, "lat": 51.521251 }, "words": "nước yến.nét vẽ.đồ gốm", "language": "vi", "map": "https://w3w.co/n%C6%B0%E1%BB%9Bc+y%E1%BA%BFn.n%C3%A9t+v%E1%BA%BD.%C4%91%E1%BB%93+g%E1%BB%91m" } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.convertTo3wa(coordinates, language, null) // Assert assert(response.isSuccessful) assert(response.body()?.words == "nước yến.nét vẽ.đồ gốm") assert(response.body()?.locale == null) } @Test fun `convert valid coordinates with Kazakh Latin locale should return kk_la 3wa`() = runTest { // Arrange val coordinates = "51.521251, 0.203586" val locale = "kk_la" val expectedResponseData = """ { "country": "GB", "square": { "southwest": { "lng": -0.203607, "lat": 51.521238 }, "northeast": { "lng": -0.203564, "lat": 51.521265 } }, "nearestPlace": "Bayswater, London", "coordinates": { "lng": -0.203586, "lat": 51.521251 }, "words": "otyr.tıredık.säulettı", "language": "kk", "locale": "kk_la", "map": "https://w3w.co/otyr.t%C4%B1red%C4%B1k.s%C3%A4ulett%C4%B1" } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.convertTo3wa(coordinates, null, locale) // Assert assert(response.isSuccessful) assert(response.body()?.words == "otyr.tıredık.säulettı") assert(response.body()?.locale == "kk_la") } @Test fun `convert valid w3a to coordinates should return coordinates`() = runTest { // Arrange val w3a = "index.home.raft" val expectedResponseData = """ { "country": "GB", "square": { "southwest": { "lng": -0.203607, "lat": 51.521238 }, "northeast": { "lng": -0.203564, "lat": 51.521265 } }, "nearestPlace": "Bayswater, London", "coordinates": { "lng": -0.203586, "lat": 51.521251 }, "words": "index.home.raft", "language": "en", "map": "https://w3w.co/index.home.raft" } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.convertToCoordinates(w3a) // Assert assert(response.isSuccessful) assert(response.body()?.coordinates?.lat == 51.521251) assert(response.body()?.coordinates?.lng == -0.203586) } @Test fun `convert null to coordinates should return error`() = runBlocking { // Arrange val w3a = null val expectedResponseData = """ { "error": { "code": "MissingWords", "message": "words must be specified" } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesConvertToCoordinatesResponseMapper()) { what3WordsV3Service.convertToCoordinates(w3a) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is UnknownError) } @Test fun `available language should return list of supported language`() = runTest { // Arrange val expectedResponseData = """ { "languages": [ { "nativeName": "Deutsch", "code": "de", "name": "German" }, { "nativeName": "हिन्दी", "code": "hi", "name": "Hindi" }, { "nativeName": "ລາວ", "code": "lo", "name": "Lao" }, { "nativeName": "Português", "code": "pt", "name": "Portuguese" }, { "nativeName": "Magyar", "code": "hu", "name": "Hungarian" }, { "nativeName": "Українська", "code": "uk", "name": "Ukrainian" }, { "nativeName": "Bahasa Indonesia", "code": "id", "name": "Bahasa Indonesia" }, { "nativeName": "اردو", "code": "ur", "name": "Urdu" }, { "nativeName": "മലയാളം", "code": "ml", "name": "Malayalam" }, { "nativeName": "<NAME>", "code": "mn", "name": "Mongolian", "locales": [ { "nativeName": "<NAME> (Латинаар)", "name": "Mongolian (Latin)", "code": "mn_la" }, { "nativeName": "<NAME> (Криллээр)", "name": "Mongolian (Cyrillic)", "code": "mn_cy" } ] }, { "nativeName": "Afrikaans", "code": "af", "name": "Afrikaans" }, { "nativeName": "मराठी", "code": "mr", "name": "Marathi" }, { "nativeName": "Bahasa Malaysia", "code": "ms", "name": "Bahasa Malaysia" }, { "nativeName": "Ελληνικά", "code": "el", "name": "Greek" }, { "nativeName": "English", "code": "en", "name": "English" }, { "nativeName": "Italiano", "code": "it", "name": "Italian" }, { "nativeName": "አማርኛ", "code": "am", "name": "Amharic" }, { "nativeName": "Español", "code": "es", "name": "Spanish" }, { "nativeName": "中文", "code": "zh", "name": "Chinese", "locales": [ { "nativeName": "中文(繁體)", "name": "Chinese (Traditional)", "code": "zh_tr" }, { "nativeName": "中文(简体)", "name": "Chinese (Simplified)", "code": "zh_si" } ] }, { "nativeName": "Eesti", "code": "et", "name": "Estonian" }, { "nativeName": "العربية", "code": "ar", "name": "Arabic" }, { "nativeName": "Tiếng Việt", "code": "vi", "name": "Vietnamese" }, { "nativeName": "日本語", "code": "ja", "name": "Japanese" }, { "nativeName": "नेपाली", "code": "ne", "name": "Nepali" }, { "nativeName": "فارسی", "code": "fa", "name": "Persian" }, { "nativeName": "isiZulu", "code": "zu", "name": "isiZulu" }, { "nativeName": "Română", "code": "ro", "name": "Romanian" }, { "nativeName": "Nederlands", "code": "nl", "name": "Dutch" }, { "nativeName": "Norsk", "code": "no", "name": "Norwegian" }, { "nativeName": "Suomi", "code": "fi", "name": "Finnish" }, { "nativeName": "Русский", "code": "ru", "name": "Russian" }, { "nativeName": "български", "code": "bg", "name": "Bulgarian" }, { "nativeName": "বাংলা", "code": "bn", "name": "Bengali" }, { "nativeName": "Français", "code": "fr", "name": "French" }, { "nativeName": "සිංහල", "code": "si", "name": "Sinhala" }, { "nativeName": "Slovenčina", "code": "sk", "name": "Slovak" }, { "nativeName": "Català", "code": "ca", "name": "Catalan" }, { "nativeName": "Қазақ тілі", "code": "kk", "name": "Kazakh", "locales": [ { "nativeName": "Қазақ тілі (кирилл)", "name": "Kazakh (Cyrillic)", "code": "kk_cy" }, { "nativeName": "Qazaq tılı (Latyn)", "name": "Kazakh (Latin)", "code": "kk_la" } ] }, { "nativeName": "Bosanski-Crnogorski-Hrvatski-Srpski", "code": "oo", "name": "Bosnian-Croatian-Montenegrin-Serbian", "locales": [ { "nativeName": "Bosanski-Crnogorski-Hrvatski-Srpski (latinica)", "name": "Bosnian-Croatian-Montenegrin-Serbian (Latin)", "code": "oo_la" }, { "nativeName": "Босански-Српски-Хрватски-Црногорски (ћирилица)", "name": "Bosnian-Croatian-Montenegrin-Serbian (Cyrillic)", "code": "oo_cy" } ] }, { "nativeName": "ភាសាខ្មែរ", "code": "km", "name": "Khmer" }, { "nativeName": "ಕನ್ನಡ", "code": "kn", "name": "Kannada" }, { "nativeName": "ଓଡ଼ିଆ", "code": "or", "name": "Odia" }, { "nativeName": "Svenska", "code": "sv", "name": "Swedish" }, { "nativeName": "한국어", "code": "ko", "name": "Korean" }, { "nativeName": "Kiswahili", "code": "sw", "name": "Swahili" }, { "nativeName": "தமிழ்", "code": "ta", "name": "Tamil" }, { "nativeName": "ગુજરાતી", "code": "gu", "name": "Gujarati" }, { "nativeName": "Čeština", "code": "cs", "name": "Czech" }, { "nativeName": "isiXhosa", "code": "xh", "name": "isiXhosa" }, { "nativeName": "ਪੰਜਾਬੀ", "code": "pa", "name": "Punjabi" }, { "nativeName": "తెలుగు", "code": "te", "name": "Telugu" }, { "nativeName": "ไทย", "code": "th", "name": "Thai" }, { "nativeName": "Cymraeg", "code": "cy", "name": "Welsh" }, { "nativeName": "Polski", "code": "pl", "name": "Polish" }, { "nativeName": "Dansk", "code": "da", "name": "Danish" }, { "nativeName": "עברית", "code": "he", "name": "Hebrew" }, { "nativeName": "Türkçe", "code": "tr", "name": "Turkish" } ] } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.availableLanguages() // Assert assert(response.isSuccessful) assert(response.body()?.languages?.size == 57) } @Test fun `Grid section with valid bounding box and format JSON should return what3word grid in JSON format`() = runTest { // Arrange val boundingBox = "52.207988,0.116126,52.208867,0.117540" val expectedResponseData = """ { "lines": [ { "start": { "lng": 0.116126, "lat": 52.208009918068136 }, "end": { "lng": 0.11754, "lat": 52.208009918068136 } }, { "start": { "lng": 0.116126, "lat": 52.20803686934023 }, "end": { "lng": 0.11754, "lat": 52.20803686934023 } } ] } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.gridSection(boundingBox) // Assert assert(response.isSuccessful) assert(response.body()?.lines?.size == 2) assert(response.body()?.lines?.get(0)?.start?.lat == 52.208009918068136) assert(response.body()?.lines?.get(0)?.start?.lng == 0.116126) } @Test fun `Grid section with invalid bounding box should return BadBoundingBoxError`() = runTest { val boundingBox = "172.207988,0.116126,52.208867,0.117540" val expectedResponseData = """ { "error": { "code": "BadBoundingBox", "message": "Invalid bounding-box. Must be lat,lng,lat,lng with -90 <= lat <= 90." } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesGridSectionResponseMapper()) { what3WordsV3Service.gridSection(boundingBox) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is BadBoundingBoxError) } @Test fun `Grid section with too big bounding box should return BadBoundingBoxTooBigError`() { val boundingBox = "0.207988,0.116126,52.208867,0.117540" val expectedResponseData = """ { "error": { "code": "BadBoundingBoxTooBig", "message": "The diagonal of bounding-box may not be > 4km" } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesGridSectionResponseMapper()) { what3WordsV3Service.gridSection(boundingBox) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is BadBoundingBoxTooBigError) } @Test fun `autosuggest with valid input should return list of suggestions`() = runTest { // Arrange val input = "index.home.raf" val expectedResponseData = """ { "suggestions": [ { "country": "GB", "nearestPlace": "Bayswater, London", "words": "index.home.raft", "rank": 1, "language": "en" }, { "country": "US", "nearestPlace": "Prosperity, West Virginia", "words": "indexes.home.raft", "rank": 2, "language": "en" }, { "country": "US", "nearestPlace": "Greensboro, North Carolina", "words": "index.homes.raft", "rank": 3, "language": "en" } ] } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.autosuggest(input, emptyMap()) // Assert assert(response.isSuccessful) assert(response.body()?.suggestions?.size == 3) assert(response.body()?.suggestions?.get(0)?.words == "index.home.raft") } @Test fun `autosuggest with invalid input should return empty suggestions`() = runTest { // Arrange val input = "index.hom" val expectedResponseData = """ { "suggestions": [] } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.autosuggest(input, emptyMap()) // Assert assert(response.isSuccessful) assert(response.body()?.suggestions?.size == 0) } @Test fun `autosuggest with option of 4 n-results should return 4 suggestions`() = runTest { // Arrange val input = "index.home.raf" val options = W3WAutosuggestOptions.Builder().nResults(4).build() val expectedResponseData = """ { "suggestions": [ { "country": "GB", "nearestPlace": "Bayswater, London", "words": "index.home.raft", "rank": 1, "language": "en" }, { "country": "US", "nearestPlace": "Prosperity, West Virginia", "words": "indexes.home.raft", "rank": 2, "language": "en" }, { "country": "US", "nearestPlace": "Greensboro, North Carolina", "words": "index.homes.raft", "rank": 3, "language": "en" }, { "country": "AU", "nearestPlace": "Melville, Western Australia", "words": "index.home.rafts", "rank": 4, "language": "en" } ] } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(expectedResponseData) ) // Act val response = what3WordsV3Service.autosuggest(input, options.toQueryMap()) // Assert assert(response.isSuccessful) assert(response.body()?.suggestions?.size == 4) } @Test fun `autosuggest with invalid focus option should return BadFocusError`() = runTest { // Arrange val input = "index.home.raf" val options = W3WAutosuggestOptions.Builder().focus(W3WCoordinates(250.842404, 4.361177)).build() val expectedResponseData = """ { "error": { "code": "BadFocus", "message": "lat must be >= -90 and <=90" } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesAutosuggestResponseMapper()) { what3WordsV3Service.autosuggest(input, options.toQueryMap()) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is BadFocusError) } @Test fun `autosuggest with invalid clip to circle option should return BadClipToCircle`() = runTest { // Arrange val input = "index.home.raf" val options = W3WAutosuggestOptions.Builder() .clipToCircle( W3WCircle(W3WCoordinates(250.842404, 4.361177), W3WDistance(1.0)) ).build() val clipToCircle = "250.842404,4.361177" val expectedResponseData = """ { "error": { "code": "BadClipToCircle", "message": "latitudes must be >=-90 and <=90" } } """.trimIndent() mockWebServer.enqueue( MockResponse() .setResponseCode(400) .setBody(expectedResponseData) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesAutosuggestResponseMapper()) { what3WordsV3Service.autosuggest( input, options.toQueryMap() ) } // Assert assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is BadClipToCircleError) } @Test fun `test request timeout is handled gracefully`() = runTest { val input = "index.home.raf" mockWebServer.enqueue( MockResponse() .setSocketPolicy(SocketPolicy.NO_RESPONSE) ) // Act val response = executeApiRequestAndHandleResponse(resultMapper = MappersFactory.providesAutosuggestResponseMapper()) { what3WordsV3Service.autosuggest( input, emptyMap() ) } assert(response is W3WResult.Failure) response as W3WResult.Failure assert(response.error is NetworkError) } }
1
null
2
1
95ab9c58149bff97acb4ae2aa7900489e245b133
33,204
w3w-android-wrapper
MIT License
note/src/main/java/com/example/note_presentation/component/NoteCard.kt
meghdadya
765,069,419
false
{"Kotlin": 90789}
package com.example.note_presentation.component import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer 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.shape.RoundedCornerShape import androidx.compose.material3.OutlinedCard import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.core_ui.DarkGray import com.example.core_ui.LocalSpacing import com.example.core_ui.MediumGray import com.example.note_presentation.note.NoteUiModel import com.example.note_presentation.utils.formatReminderDateTime @OptIn(ExperimentalFoundationApi::class) @Composable fun GridNotesCard( noteModel: NoteUiModel, onClick: () -> Unit ) { val spacing = LocalSpacing.current OutlinedCard( border = BorderStroke(width = 1.dp, MediumGray), modifier = Modifier .padding(10.dp) .fillMaxHeight() .clip(RoundedCornerShape(16.dp)) .combinedClickable(onClick = onClick), ) { Box( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Column( modifier = Modifier .fillMaxWidth() ) { Text( text = noteModel.title, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, fontWeight = FontWeight(500), color = Color.Black ) Spacer(modifier = Modifier.height(spacing.spaceSmall)) Text( text = noteModel.content, fontSize = 12.sp, maxLines = 5, fontWeight = FontWeight(400), overflow = TextOverflow.Ellipsis, color = DarkGray ) Spacer(modifier = Modifier.height(spacing.spaceMedium)) Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Top ) { noteModel.alarm?.let { AlarmLabel(text = it.formatReminderDateTime()) } Spacer(modifier = Modifier.height(spacing.spaceSmall)) TagText(text = noteModel.label) } } } } }
0
Kotlin
0
0
b4cc200c7c67b9b2452fa8bf883e8176a48d795d
3,252
inscribeApp
Apache License 2.0
app/src/main/java/com/example/meditationui/Feature.kt
esipiderman
527,011,578
false
{"Kotlin": 18749}
package com.example.meditationui import androidx.annotation.DrawableRes import androidx.compose.ui.graphics.Color data class Feature( val title :String, @DrawableRes val iconId:Int, val lightColor:Color, val mediumColor:Color, val darkColor:Color, )
0
Kotlin
0
0
05a0c3059014ba0fb0a6b39d2ec3b336af553037
274
meditation_ui
MIT License
Tutorial1-1Basics/src/main/java/com/smarttoolfactory/tutorial1_1basics/chapter4_state/Tutorial4_2_4Stability.kt
SmartToolFactory
326,400,374
false
null
package com.smarttoolfactory.tutorial1_1basics.chapter4_state import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CutCornerShape import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.smarttoolfactory.tutorial1_1basics.ui.components.StyleableTutorialText import com.smarttoolfactory.tutorial1_1basics.ui.components.getRandomColor /* In jetpack Compose stability, not triggering recomposition when inputs of a function hasn't changed, is achieved by using immutable variables or/and using @Immutable or @Stable annotation to make functions skippable as can be seen in detail in articles below. Skippable — when called during recomposition, compose is able to skip the function if all of the parameters are equal with their previous values. Restartable — this function serves as a “scope” where recomposition can start (In other words, this function can be used as a point of entry for where Compose can start re-executing code for recomposition after state changes). Types could be immutable or stable: Immutable — Indicates a type where the value of any properties will never change after the object is constructed, and all methods are referentially transparent. All primitive types (String, Int, Float, etc) are considered immutable. Stable — Indicates a type that is mutable, but the Compose runtime will be notified if and when any public properties or method behavior would yield different results from a previous invocation. Resources https://medium.com/androiddevelopers/jetpack-compose-stability-explained-79c10db270c8 https://chrisbanes.me/posts/composable-metrics/ */ @Preview @Composable fun Tutorial4_2_4Screen() { TutorialContent() } @Composable private fun TutorialContent() { Column( modifier = Modifier.padding(10.dp) ) { StyleableTutorialText( text = "**Stability**, not triggering recomposition when inputs of a " + "function hasn't changed, is achieved" + " by using immutable variables or/and using" + " @Immutable or @Stable annotation to make functions skippable.\n" + "In the example below **UnStableDataClass(var)** is not skippable because of " + "**UnstableComposable(data = unstableData)**. It " + "recompose even if the input doesn't change.", bullets = false ) ComposeScopeSample() } } @Preview @Composable private fun ComposeScopeSample() { var counter by remember { mutableIntStateOf(0) } val unstableData by remember { mutableStateOf(UnStableDataClass(0)) } val stableData by remember { mutableStateOf(StableDataClass(0)) } Column { Button( modifier = Modifier.fillMaxWidth(), onClick = { counter++ }) { Text(text = "Counter: $counter") } Spacer(modifier = Modifier.height(20.dp)) OuterComposable { // This scope never gets recomposed because // Nothing is read here println("Outer SCOPE") MiddleComposable { // This scope is recomposed because counter is read in this scope println("Middle SCOPE") // Unstable Functions get recomposed even when their inputs don't change UnstableComposable(data = unstableData) StableComposable(data = stableData) Counter(text = "Counter $counter") } } } } // 🔥 A class with mutable param is Unstable data class UnStableDataClass(var value: Int) // A class with all of its params immutable is Stable data class StableDataClass(val value: Int) @Composable private fun UnstableComposable(data: UnStableDataClass) { SideEffect { println("🍎 UnstableComposable") } Column( modifier = Modifier .padding(4.dp) .shadow(1.dp, shape = CutCornerShape(topEnd = 8.dp)) .background(getRandomColor()) .fillMaxWidth() .padding(4.dp) ) { Text(text = "UnstableComposable() value: ${data.value}") } } @Composable private fun StableComposable(data: StableDataClass) { SideEffect { println("🍏 StableComposable") } Column( modifier = Modifier .padding(4.dp) .shadow(1.dp, shape = CutCornerShape(topEnd = 8.dp)) .background(getRandomColor()) .fillMaxWidth() .padding(4.dp) ) { Text(text = "StableComposable value(): ${data.value}") } } @Composable private fun OuterComposable( content: @Composable () -> Unit ) { SideEffect { println("OUTER COMPOSABLE") } Column( modifier = Modifier .padding(4.dp) .shadow(1.dp, shape = CutCornerShape(topEnd = 8.dp)) .background(getRandomColor()) .fillMaxWidth() .padding(4.dp) ) { content() } } @Composable private fun MiddleComposable( content: @Composable () -> Unit ) { SideEffect { println("MIDDLE COMPOSABLE") } Column( modifier = Modifier .padding(4.dp) .shadow(1.dp, shape = CutCornerShape(topEnd = 8.dp)) .background(getRandomColor()) .fillMaxWidth() .padding(4.dp) ) { content() } } @Composable private fun Counter( text: String ) { SideEffect { println("Counter()") } Column( modifier = Modifier .padding(4.dp) .shadow(1.dp, shape = CutCornerShape(topEnd = 8.dp)) .background(getRandomColor()) .fillMaxWidth() .padding(4.dp) ) { Text(text = "Counter() text: $text") } }
5
null
312
3,006
efea98b63e63a85b80f7dc1bd4ca6d769e35905d
6,664
Jetpack-Compose-Tutorials
Apache License 2.0
app/src/main/java/com/starry/greenstash/widget/configuration/WidgetConfigActivity.kt
Pool-Of-Tears
500,278,038
false
null
/** * MIT License * * Copyright (c) [2022 - Present] <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.starry.greenstash.widget.configuration import android.appwidget.AppWidgetManager import android.content.Intent import android.os.Bundle import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.surfaceColorAtElevation import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModelProvider import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionResult import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.animateLottieCompositionAsState import com.airbnb.lottie.compose.rememberLottieComposition import com.google.accompanist.systemuicontroller.rememberSystemUiController import com.starry.greenstash.MainActivity import com.starry.greenstash.R import com.starry.greenstash.ui.screens.settings.SettingsViewModel import com.starry.greenstash.ui.screens.settings.ThemeMode import com.starry.greenstash.ui.theme.GreenStashTheme import com.starry.greenstash.ui.theme.greenstashFont import com.starry.greenstash.widget.GoalWidget import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.delay @AndroidEntryPoint class WidgetConfigActivity : AppCompatActivity() { private val viewModel: WidgetConfigViewModel by viewModels() private lateinit var settingsViewModel: SettingsViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) settingsViewModel = ViewModelProvider(this)[SettingsViewModel::class.java] setContent { GreenStashTheme(settingsViewModel = settingsViewModel) { val systemUiController = rememberSystemUiController() systemUiController.setNavigationBarColor( color = MaterialTheme.colorScheme.background, darkIcons = settingsViewModel.getCurrentTheme() == ThemeMode.Light ) systemUiController.setStatusBarColor( color = MaterialTheme.colorScheme.surfaceColorAtElevation(4.dp), darkIcons = settingsViewModel.getCurrentTheme() == ThemeMode.Light ) Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID intent.extras?.let { appWidgetId = it.getInt( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID ) } if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { finish() } else { ConfigScreenContent(viewModel, appWidgetId) } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun ConfigScreenContent(viewModel: WidgetConfigViewModel, appWidgetId: Int) { Scaffold( modifier = Modifier .background(MaterialTheme.colorScheme.background) .fillMaxSize(), topBar = { TopAppBar(modifier = Modifier.fillMaxWidth(), title = { Text( text = stringResource(id = R.string.widget_config_screen_header), maxLines = 1, overflow = TextOverflow.Ellipsis, fontFamily = greenstashFont ) }, navigationIcon = { IconButton(onClick = { // Launch app by calling main activity when user press back button in // widget configuration screen. setResult(RESULT_CANCELED) val appIntent = Intent(this@WidgetConfigActivity, MainActivity::class.java) startActivity(appIntent) finish() }) { Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = null ) } }, colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(4.dp) ) ) } ) { Column(modifier = Modifier.padding(it)) { val allGoals = viewModel.allGoals.observeAsState(listOf()).value if (allGoals.isEmpty()) { var showNoGoalsAnimation by remember { mutableStateOf(false) } LaunchedEffect(key1 = true, block = { delay(200) showNoGoalsAnimation = true }) if (showNoGoalsAnimation) { Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { val compositionResult: LottieCompositionResult = rememberLottieComposition( spec = LottieCompositionSpec.RawRes(R.raw.no_goal_found_lottie) ) val progressAnimation by animateLottieCompositionAsState( compositionResult.value, isPlaying = true, iterations = 1, speed = 1f ) Spacer(modifier = Modifier.weight(1f)) LottieAnimation( composition = compositionResult.value, progress = { progressAnimation }, modifier = Modifier.size(335.dp), enableMergePaths = true ) Text( text = stringResource(id = R.string.no_goal_set), fontWeight = FontWeight.Medium, fontSize = 18.sp, fontFamily = greenstashFont, modifier = Modifier.padding(start = 12.dp, end = 12.dp) ) Spacer(modifier = Modifier.weight(2f)) } } } else { LazyColumn( modifier = Modifier .fillMaxSize() .padding(top = 4.dp) ) { val defCurrency = settingsViewModel.getDefaultCurrencyValue() items(allGoals.size) { idx -> val item = allGoals[idx] val progressPercent = ((item.getCurrentlySavedAmount() / item.goal.targetAmount) * 100).toInt() Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center ) { GoalItem( title = item.goal.title, description = stringResource(id = R.string.goal_widget_desc).format( "$defCurrency${item.getCurrentlySavedAmount()}/$defCurrency${item.goal.targetAmount}" ), progress = progressPercent.toFloat() / 100 ) { viewModel.setWidgetData( widgetId = appWidgetId, goalId = item.goal.goalId, ) { goalItem -> // update widget contents for the first time. GoalWidget().updateWidgetContents( context = this@WidgetConfigActivity, appWidgetId = appWidgetId, goalItem = goalItem ) // set result and finish the activity. val resultValue = Intent() resultValue.putExtra( AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId ) setResult(RESULT_OK, resultValue) finish() } } } } } } } } } @Composable private fun GoalItem(title: String, description: String, progress: Float, onClick: () -> Unit) { Card( modifier = Modifier .fillMaxWidth(0.95f) .padding(top = 4.dp, bottom = 4.dp), colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation( 3.dp ) ), shape = RoundedCornerShape(12.dp), onClick = onClick ) { Row( modifier = Modifier.padding(start = 12.dp, end = 12.dp), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .height(90.dp) .width(90.dp) .padding(10.dp) .clip(CircleShape) .background(MaterialTheme.colorScheme.primary), contentAlignment = Alignment.Center ) { Icon( imageVector = ImageVector.vectorResource(id = R.drawable.ic_widget_config_item), contentDescription = null, tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier .size(40.dp) .padding(top = 4.dp, start = 2.dp) ) } Column(modifier = Modifier.padding(8.dp)) { Text( text = title, fontSize = 20.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, fontFamily = greenstashFont, overflow = TextOverflow.Ellipsis, color = MaterialTheme.colorScheme.onSurface, ) Text( text = description, color = MaterialTheme.colorScheme.onSurface, maxLines = 1, fontFamily = greenstashFont, fontWeight = FontWeight.Medium, fontSize = 14.sp, ) Spacer(modifier = Modifier.height(8.dp)) LinearProgressIndicator( progress = { progress }, modifier = Modifier .fillMaxWidth() .height(10.dp) .clip(RoundedCornerShape(40.dp)), color = MaterialTheme.colorScheme.secondary, ) Spacer(modifier = Modifier.height(8.dp)) } } } } }
9
null
39
477
7b2b3f460378d8ca7b896d724257db13b4789fc5
15,547
GreenStash
MIT License
plumber-android/src/main/java/leakcanary/ViewLocationHolderLeakFix.kt
square
34,824,499
false
null
package leakcanary import android.annotation.SuppressLint import android.app.Activity import android.app.Application import android.os.Build.VERSION import android.os.Bundle import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import leakcanary.AndroidLeakFixes.Companion.checkMainThread import leakcanary.internal.onAndroidXFragmentViewDestroyed import shark.SharkLog /** * @see [AndroidLeakFixes.VIEW_LOCATION_HOLDER]. */ @SuppressLint("NewApi") object ViewLocationHolderLeakFix { private var groupAndOutChildren: Pair<ViewGroup, ArrayList<View>>? = null private var failedClearing = false internal fun applyFix(application: Application) { if (VERSION.SDK_INT != 28) { return } application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks by AndroidLeakFixes.noOpDelegate() { override fun onActivityCreated( activity: Activity, savedInstanceState: Bundle? ) { activity.onAndroidXFragmentViewDestroyed { uncheckedClearStaticPool(application) } } override fun onActivityDestroyed(activity: Activity) { uncheckedClearStaticPool(application) } }) } /** * Clears the ViewGroup.ViewLocationHolder.sPool static pool. */ fun clearStaticPool(application: Application) { checkMainThread() if (VERSION.SDK_INT != 28) { return } uncheckedClearStaticPool(application) } private fun uncheckedClearStaticPool(application: Application) { if (failedClearing) { return } try { if (groupAndOutChildren == null) { val viewGroup = FrameLayout(application) // ViewLocationHolder.MAX_POOL_SIZE = 32 for (i in 0 until 32) { val childView = View(application) viewGroup.addView(childView) } groupAndOutChildren = viewGroup to ArrayList() } val (group, outChildren) = groupAndOutChildren!! group.addChildrenForAccessibility(outChildren) } catch (ignored: Throwable) { SharkLog.d(ignored) { "Failed to clear ViewLocationHolder leak, will not try again." } failedClearing = true } } }
88
null
3838
27,036
5e69400174e40ce2efac2e493f414783723a8067
2,226
leakcanary
Apache License 2.0
compiler/testData/codegen/box/jvmOverloads/defaultsNotAtEnd.kt
JakeWharton
99,388,807
false
null
// TARGET_BACKEND: JVM // WITH_STDLIB class C { @kotlin.jvm.JvmOverloads public fun foo(o: String = "O", i1: Int, k: String = "K", i2: Int): String { return o + k } } fun box(): String { val c = C() val m = c.javaClass.getMethod("foo", Int::class.java, Int::class.java) return m.invoke(c, 1, 2) as String }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
338
kotlin
Apache License 2.0
app/src/test/kotlin/compiler/lowlevel/storage/GlobalVariableStorageTest.kt
brzeczyk-compiler
545,707,939
false
{"Kotlin": 1167879, "C": 4004, "Shell": 3242, "Vim Script": 2238}
package compiler.lowlevel.storage import compiler.ast.Expression import compiler.ast.Program import compiler.ast.Type import compiler.ast.Variable import java.io.PrintWriter import java.io.StringWriter import kotlin.test.Test import kotlin.test.assertEquals class GlobalVariableStorageTest { private fun List<Pair<String, Expression?>>.asVarDefList() = this.map { Program.Global.VariableDefinition( Variable( Variable.Kind.VARIABLE, it.first, Type.Number, it.second ) ) } @Test fun `global variables asm test`() { val definitions = listOf( "no expression" to null, "bool true" to Expression.BooleanLiteral(true), "bool false" to Expression.BooleanLiteral(false), "unit" to Expression.UnitLiteral(), "number" to Expression.NumberLiteral(12347), ).asVarDefList() + Program.Global.VariableDefinition( Variable( Variable.Kind.CONSTANT, "constant", Type.Number, Expression.UnitLiteral() ) ) val program = Program(definitions) val stringWriter = StringWriter() GlobalVariableStorage(program).writeAsm(PrintWriter(stringWriter)) val expected = "globals:\n" + "dq 0x0 ; bool false\n" + "dq 0x1 ; bool true\n" + "dq 0x0 ; no expression\n" + "dq 0x303b ; number\n" + "dq 0x0 ; unit\n" assertEquals(expected, stringWriter.toString()) } }
7
Kotlin
0
2
5917f4f9d0c13c2c87d02246da8ef8394499d33c
1,703
brzeczyk
MIT License
app/src/main/java/io/homeassistant/companion/android/settings/shortcuts/ManageShortcutsViewModel.kt
home-assistant
179,008,173
false
null
package io.homeassistant.companion.android.settings.shortcuts import android.app.Application import android.content.Intent import android.content.pm.ShortcutInfo import android.content.pm.ShortcutManager import android.graphics.Bitmap import android.graphics.PorterDuff import android.graphics.drawable.Drawable import android.graphics.drawable.Icon import android.os.Build import android.util.Log import android.widget.Toast import androidx.annotation.RequiresApi import androidx.appcompat.content.res.AppCompatResources import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.core.content.getSystemService import androidx.core.graphics.drawable.DrawableCompat import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.maltaisn.icondialog.pack.IconPack import com.maltaisn.icondialog.pack.IconPackLoader import com.maltaisn.iconpack.mdi.createMaterialDesignIconPack import dagger.hilt.android.lifecycle.HiltViewModel import io.homeassistant.companion.android.common.R import io.homeassistant.companion.android.common.data.integration.Entity import io.homeassistant.companion.android.common.data.integration.IntegrationRepository import io.homeassistant.companion.android.webview.WebViewActivity import kotlinx.coroutines.launch import javax.inject.Inject @RequiresApi(Build.VERSION_CODES.N_MR1) @HiltViewModel class ManageShortcutsViewModel @Inject constructor( private val integrationUseCase: IntegrationRepository, application: Application ) : AndroidViewModel(application) { val app = application private val TAG = "ShortcutViewModel" private lateinit var iconPack: IconPack private var shortcutManager = application.applicationContext.getSystemService<ShortcutManager>()!! val canPinShortcuts = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && shortcutManager.isRequestPinShortcutSupported var pinnedShortcuts: MutableList<ShortcutInfo> = shortcutManager.pinnedShortcuts private set var dynamicShortcuts: MutableList<ShortcutInfo> = shortcutManager.dynamicShortcuts private set var entities = mutableStateMapOf<String, Entity<*>>() private set data class Shortcut( var id: MutableState<String?>, var selectedIcon: MutableState<Int>, var label: MutableState<String>, var desc: MutableState<String>, var path: MutableState<String>, var type: MutableState<String>, var drawable: MutableState<Drawable?>, var delete: MutableState<Boolean> ) var shortcuts = mutableStateListOf<Shortcut>() private set init { viewModelScope.launch { integrationUseCase.getEntities()?.forEach { entities[it.entityId] = it } } Log.d(TAG, "We have ${dynamicShortcuts.size} dynamic shortcuts") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Log.d(TAG, "Can we pin shortcuts: ${shortcutManager.isRequestPinShortcutSupported}") Log.d(TAG, "We have ${pinnedShortcuts.size} pinned shortcuts") } for (i in 0..5) { shortcuts.add( Shortcut( mutableStateOf(""), mutableStateOf(0), mutableStateOf(""), mutableStateOf(""), mutableStateOf(""), mutableStateOf("lovelace"), mutableStateOf(AppCompatResources.getDrawable(application, R.drawable.ic_stat_ic_notification_blue)), mutableStateOf(false) ) ) } if (dynamicShortcuts.size > 0) { for (i in 0 until dynamicShortcuts.size) setDynamicShortcutData(dynamicShortcuts[i].id, i) } } fun createShortcut(shortcutId: String, shortcutLabel: String, shortcutDesc: String, shortcutPath: String, bitmap: Bitmap? = null, iconId: Int) { Log.d(TAG, "Attempt to add shortcut $shortcutId") val intent = Intent( WebViewActivity.newInstance(getApplication(), shortcutPath).addFlags( Intent.FLAG_ACTIVITY_NEW_TASK ) ) intent.action = shortcutPath intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK) intent.putExtra("iconId", iconId) val shortcut = ShortcutInfo.Builder(getApplication(), shortcutId) .setShortLabel(shortcutLabel) .setLongLabel(shortcutDesc) .setIcon( if (bitmap != null) Icon.createWithBitmap(bitmap) else Icon.createWithResource(getApplication(), R.drawable.ic_stat_ic_notification_blue) ) .setIntent(intent) .build() if (shortcutId.startsWith("shortcut")) { shortcutManager.addDynamicShortcuts(listOf(shortcut)) dynamicShortcuts = shortcutManager.dynamicShortcuts } else { var isNewPinned = true for (item in pinnedShortcuts) { if (item.id == shortcutId) { isNewPinned = false Log.d(TAG, "Updating pinned shortcut: $shortcutId") shortcutManager.updateShortcuts(listOf(shortcut)) Toast.makeText(getApplication(), R.string.shortcut_updated, Toast.LENGTH_SHORT).show() } } if (isNewPinned) { Log.d(TAG, "Requesting to pin shortcut: $shortcutId") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { shortcutManager.requestPinShortcut(shortcut, null) } } } } fun deleteShortcut(shortcutId: String) { shortcutManager.removeDynamicShortcuts(listOf(shortcutId)) dynamicShortcuts = shortcutManager.dynamicShortcuts } fun setPinnedShortcutData(shortcutId: String) { for (item in pinnedShortcuts) { if (item.id == shortcutId) { shortcuts.last().id.value = item.id shortcuts.last().label.value = item.shortLabel.toString() shortcuts.last().desc.value = item.longLabel.toString() shortcuts.last().path.value = item.intent?.action.toString() shortcuts.last().selectedIcon.value = item.intent?.extras?.getInt("iconId").toString().toIntOrNull() ?: 0 if (shortcuts.last().selectedIcon.value != 0) shortcuts.last().drawable.value = getTileIcon(shortcuts.last().selectedIcon.value) if (shortcuts.last().path.value.startsWith("entityId:")) shortcuts.last().type.value = "entityId" else shortcuts.last().type.value = "lovelace" } } } fun setDynamicShortcutData(shortcutId: String, index: Int) { if (dynamicShortcuts.isNotEmpty()) { for (item in dynamicShortcuts) { if (item.id == shortcutId) { Log.d(TAG, "setting ${item.id} data") shortcuts[index].label.value = item.shortLabel.toString() shortcuts[index].desc.value = item.longLabel.toString() shortcuts[index].path.value = item.intent?.action.toString() shortcuts[index].selectedIcon.value = item.intent?.extras?.getInt("iconId").toString().toIntOrNull() ?: 0 if (shortcuts[index].selectedIcon.value != 0) shortcuts[index].drawable.value = getTileIcon(shortcuts[index].selectedIcon.value) if (shortcuts[index].path.value.startsWith("entityId:")) shortcuts[index].type.value = "entityId" else shortcuts[index].type.value = "lovelace" } } } } private fun getTileIcon(tileIconId: Int): Drawable? { val loader = IconPackLoader(getApplication()) iconPack = createMaterialDesignIconPack(loader) iconPack.loadDrawables(loader.drawableLoader) val iconDrawable = iconPack.icons[tileIconId]?.drawable if (iconDrawable != null) { val icon = DrawableCompat.wrap(iconDrawable) icon.setColorFilter(app.resources.getColor(R.color.colorAccent), PorterDuff.Mode.SRC_IN) return icon } return null } fun updatePinnedShortcuts() { pinnedShortcuts = shortcutManager.pinnedShortcuts } }
9
null
498
1,666
b7c6be457e627c006bc26c8676170491d382e9f7
8,693
android
Apache License 2.0
src/main/kotlin/test2/weatherForecast/demo.kt
samorojy
340,891,499
false
null
package test2.weatherForecast import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import java.io.File fun main() { val apiKey = System.getenv("OPENWEATHER_API") val cities = Json.decodeFromString<List<String>>( File( "src/main/resources/test2.weatherForecast/cities.json" ).readText() ) cities.forEach { RequestExecutor().executeCall(RequestCreator().getApi().getWeatherData("metric", it, apiKey)) } }
1
Kotlin
0
0
86f12486bb17a5873d8140d457d470801746a1d6
495
spbu_kotlin_course
Apache License 2.0
feature/users/domain/src/commonMain/kotlin/org/timemates/app/users/usecases/GetUsersUseCase.kt
timemates
575,537,317
false
{"Kotlin": 329102}
package io.timemates.app.users.usecases import io.timemates.app.users.repositories.UsersRepository import io.timemates.sdk.common.exceptions.NotFoundException import io.timemates.sdk.users.profile.types.User import io.timemates.sdk.users.profile.types.value.UserId import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map /** * Use case class for retrieving a user by ID. * * @param repository The repository for user operations. */ class GetUsersUseCase( private val repository: UsersRepository, ) { /** * Executes the use case to retrieve a user with the specified ID. * * @param userId The ID of the user to retrieve. * @return The result of the operation. */ suspend fun execute(userIds: List<UserId>): Flow<Result> { return repository.getUsers(userIds) .map { result -> result.map { Result.Success(it) } .getOrElse { exception: Throwable -> when (exception) { is NotFoundException -> Result.NotFound else -> Result.Failure(exception) } } } } /** * Sealed class representing the result of the use case. */ sealed class Result { /** * Represents a successful result with the retrieved user. * * @param users The retrieved user. */ data class Success(val users: List<User>) : Result() /** * Represents a result indicating that the user was not found. */ object NotFound : Result() /** * Represents any other failure result from server / sdk. * * @param throwable The throwable indicating the failure. */ data class Failure(val throwable: Throwable) : Result() } }
21
Kotlin
0
28
bec7508d38e87149005c57a98f10a0eb4dbd4891
1,882
app
MIT License
flank-scripts/src/main/kotlin/flank/scripts/cli/firebase/UpdateApiCommand.kt
Flank
84,221,974
false
null
package flank.scripts.cli.firebase import com.github.ajalt.clikt.core.CliktCommand import flank.scripts.ops.firebase.updateApiJson object UpdateApiCommand : CliktCommand( name = "update_api", help = "Update api schema" ) { override fun run() { updateApiJson() } }
56
Kotlin
119
643
ee8b46391715807aab555a6e93953177a8429c0f
290
flank
Apache License 2.0
editorkit/src/main/kotlin/com/blacksquircle/ui/editorkit/plugin/shortcuts/Shortcut.kt
massivemadness
608,535,719
false
null
/* * Copyright 2021 Squircle IDE contributors. * * 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.blacksquircle.ui.editorkit.plugin.shortcuts data class Shortcut( val ctrl: Boolean, val shift: Boolean, val alt: Boolean, val keyCode: Int )
45
null
5
5
ff4ca02822671ec25f7da374283b253716ec4509
780
EditorKit
Apache License 2.0
core/src/main/java/be/appwise/core/data/base/TripleTriggerDefaultValue.kt
wisemen-digital
349,150,482
false
{"Kotlin": 255860}
package be.appwise.core.data.base import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData /** * {@link MediatorLiveData} subclass which may observe 3 other {@code LiveData} objects and react on * {@code OnChanged} events from them. And even manages default values to set when no value has been set. * Non nullable variant of {@link TripleTrigger} * * Consider the following scenario: We have a usecase where we have to listen to 3 livedata instances e.g. (searchbar ,loading state and to filter changes). * We can make 3 instances of {@code LiveData}, let's name them * {@code mSearchLive} and {@code mFilterLive}. When the value of either of these {@code LiveData} variables changes it will trigger the associated * Transformations.switchmap. * * <pre> * LiveData<String> mSearchLive = ...; * LiveData<Boolean> mLoading = ...; * LiveData<Filter> mFilterLive = ...; * * <pre> * (search,filter,loading) == pair<A,B,C> but it renames the fields * val objects = Transformations.map(DoubleTrigger(mSearchLive,mFilterLive,mLoading)) { (search,filter)-> * objectDao.findAllQuery(search,filter) * } * </pre> * * @param <A> Type of first LiveData field to listen to and the type of the defaultValue for {@code a} * @param <B> Type of second LiveData field to listen to and the type of the defaultValue for {@code b} * @param <C> Type of second LiveData field to listen to and the type of the defaultValue for {@code c} * @param a First LiveData field to listen to * @param b Second LiveData field to listen to * @param c Third LiveData field to listen to * @param defaultA The default value for {@param a} when it's value is not set * @param defaultB The default value for {@param b} when it's value is not set * @param defaultC The default value for {@param c} when it's value is not set */ class TripleTriggerDefaultValue<A, B,C>(a: LiveData<A>, b: LiveData<B>,c: LiveData<C>, defaultA : A, defaultB : B, defaultC : C) : MediatorLiveData<Triple<A, B, C>>() { init { addSource(a) { value = Triple(it , b.value ?: defaultB , c.value ?: defaultC) } addSource(b) { value = Triple((a.value ?: defaultA) , it, c.value ?: defaultC) } addSource(c) { value = Triple(a.value ?: defaultA ,b.value ?: defaultB, it) } } }
26
Kotlin
5
5
ee5cf97bab926e4262c9ae2227b6a83bcc48305d
2,322
AndroidCore
MIT License
app/src/main/java/com/vincent/recipe_mvvm_jetpack/presentation/theme/Theme.kt
VincentGaoHJ
398,203,841
false
null
package com.vincent.recipe_mvvm_jetpack.presentation.theme import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.ScaffoldState import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.vincent.recipe_mvvm_jetpack.presentation.components.CircularIndeterminateProgressBar import com.vincent.recipe_mvvm_jetpack.presentation.components.DefaultSnackbar private val LightThemeColors = lightColors( primary = ANYUZI500, primaryVariant = ANYUZI600, onPrimary = Black2, secondary = Color.White, secondaryVariant = Teal300, onSecondary = Black2, error = RedErrorDark, onError = RedErrorLight, background = Grey1, onBackground = Black2, surface = Color.White, onSurface = Black2, ) private val DarkThemeColors = darkColors( primary = ANYUZI800, primaryVariant = Color.White, onPrimary = Color.White, secondary = Black1, onSecondary = Color.White, error = RedErrorLight, background = Color.Black, onBackground = Color.White, surface = Black1, // Surface should go slighter than background onSurface = Color.White, ) @ExperimentalComposeUiApi @Composable fun AppTheme( darkTheme: Boolean, displayProgressBar: Boolean, scaffoldState: ScaffoldState, content: @Composable () -> Unit, ) { MaterialTheme( colors = if (darkTheme) DarkThemeColors else LightThemeColors, typography = QuickSandTypography, shapes = AppShapes ) { Box( modifier = Modifier .fillMaxSize() .background(color = if (!darkTheme) Grey1 else Color.Black) ) { content() // whatever at the box below have the higher priority in the display CircularIndeterminateProgressBar( isDisplayed = displayProgressBar, verticalBias = 50.dp ) // Show the snackbar of the app DefaultSnackbar( snackbarHostState = scaffoldState.snackbarHostState, onDismiss = { scaffoldState.snackbarHostState.currentSnackbarData?.dismiss() }, modifier = Modifier.align(Alignment.BottomCenter) ) } } }
0
Kotlin
0
0
a5ccee3774b5077bf715bf798ee52c8e7271d633
2,693
Recipe-MVVM-Jetpack
MIT License
app/src/main/java/ch/admin/foitt/pilotwallet/feature/qrscan/presentation/QrScanPermissionScreen.kt
e-id-admin
775,912,525
false
{"Kotlin": 1521284}
package ch.admin.foitt.pilotwallet.feature.qrscan.presentation import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import ch.admin.foitt.pilotwallet.feature.qrscan.domain.model.PermissionState import ch.admin.foitt.pilotwallet.feature.qrscan.presentation.permission.PermissionBlockedScreenContent import ch.admin.foitt.pilotwallet.feature.qrscan.presentation.permission.PermissionIntroScreenContent import ch.admin.foitt.pilotwallet.feature.qrscan.presentation.permission.PermissionRationalScreenContent import ch.admin.foitt.pilotwallet.platform.preview.WalletComponentPreview import ch.admin.foitt.pilotwallet.platform.utils.LocalActivity import ch.admin.foitt.pilotwallet.theme.PilotWalletTheme import com.ramcosta.composedestinations.annotation.Destination @Composable @Destination fun QrScanPermissionScreen(viewModel: QrScanPermissionViewModel) { val currentActivity = LocalActivity.current val cameraPermissionLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestPermission(), onResult = { permissionsGranted -> viewModel.onCameraPermissionResult( permissionGranted = permissionsGranted, activity = currentActivity, ) }, ) SideEffect { viewModel.setPermissionLauncher(cameraPermissionLauncher) } LaunchedEffect(viewModel) { viewModel.navigateToFirstScreen(currentActivity) } QrScanPermissionScreenContent( permissionState = viewModel.permissionState.collectAsStateWithLifecycle().value, onAllow = viewModel::onCameraPermissionPrompt, onClose = viewModel::onClose, onOpenSettings = viewModel::onOpenSettings, ) } @Composable private fun QrScanPermissionScreenContent( permissionState: PermissionState, onAllow: () -> Unit, onClose: () -> Unit, onOpenSettings: () -> Unit, ) = when (permissionState) { PermissionState.Granted, PermissionState.Initial -> {} PermissionState.Blocked -> PermissionBlockedScreenContent( onClose = onClose, onOpenSettings = onOpenSettings, ) PermissionState.Intro -> PermissionIntroScreenContent( onDeny = onClose, onAllow = onAllow, ) PermissionState.Rationale -> PermissionRationalScreenContent( onDeny = onClose, onAllow = onAllow, ) } @WalletComponentPreview @Composable private fun QrScanPermissionScreenPreview() { PilotWalletTheme { QrScanPermissionScreenContent( permissionState = PermissionState.Intro, onAllow = {}, onClose = {}, onOpenSettings = {}, ) } }
1
Kotlin
1
4
6572b418ec5abc5d94b18510ffa87a1e433a5c82
2,949
eidch-pilot-android-wallet
MIT License
app/src/main/java/com/android/dars/base/TestDialog.kt
denebchorny
218,098,334
false
null
package com.android.dars.base class TestDialog : BaseDialog(){ }
1
null
1
1
df293178a691056937b9243b12893bf4ee47d0c1
68
baseandroid
MIT License
feature-main/src/main/java/com/hoc/flowmvi/ui/main/MainVM.kt
Kotlin-Android-Open-Source
343,622,644
false
null
package com.hoc.flowmvi.ui.main import androidx.lifecycle.viewModelScope import arrow.core.flatMap import com.hoc.flowmvi.domain.usecase.GetUsersUseCase import com.hoc.flowmvi.domain.usecase.RefreshGetUsersUseCase import com.hoc.flowmvi.domain.usecase.RemoveUserUseCase import com.hoc.flowmvi.mvi_base.AbstractMviViewModel import com.hoc081098.flowext.flatMapFirst import com.hoc081098.flowext.startWith import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.filterNot import kotlinx.coroutines.flow.flatMapConcat import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.scan import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.take import timber.log.Timber @FlowPreview @ExperimentalCoroutinesApi class MainVM( private val getUsersUseCase: GetUsersUseCase, private val refreshGetUsers: RefreshGetUsersUseCase, private val removeUser: RemoveUserUseCase, ) : AbstractMviViewModel<ViewIntent, ViewState, SingleEvent>() { override val viewState: StateFlow<ViewState> init { val initialVS = ViewState.initial() viewState = merge( intentFlow.filterIsInstance<ViewIntent.Initial>().take(1), intentFlow.filterNot { it is ViewIntent.Initial } ) .toPartialChangeFlow() .sendSingleEvent() .scan(initialVS) { vs, change -> change.reduce(vs) } .catch { Timber.tag(logTag).e(it, "[MAIN_VM] Throwable: $it") } .stateIn( viewModelScope, SharingStarted.Eagerly, initialVS ) } private fun Flow<PartialChange>.sendSingleEvent(): Flow<PartialChange> { return onEach { change -> val event = when (change) { is PartialChange.GetUser.Error -> SingleEvent.GetUsersError(change.error) is PartialChange.Refresh.Success -> SingleEvent.Refresh.Success is PartialChange.Refresh.Failure -> SingleEvent.Refresh.Failure(change.error) is PartialChange.RemoveUser.Success -> SingleEvent.RemoveUser.Success(change.user) is PartialChange.RemoveUser.Failure -> SingleEvent.RemoveUser.Failure( user = change.user, error = change.error, indexProducer = { viewState.value .userItems .indexOfFirst { it.id == change.user.id } .takeIf { it != -1 } } ) PartialChange.GetUser.Loading -> return@onEach is PartialChange.GetUser.Data -> return@onEach PartialChange.Refresh.Loading -> return@onEach } sendEvent(event) } } private fun Flow<ViewIntent>.toPartialChangeFlow(): Flow<PartialChange> = shareWhileSubscribed().run { val getUserChanges = defer(getUsersUseCase::invoke) .onEach { either -> Timber.d("[MAIN_VM] Emit users.size=${either.map { it.size }}") } .map { result -> result.fold( ifLeft = { PartialChange.GetUser.Error(it) }, ifRight = { PartialChange.GetUser.Data(it.map(::UserItem)) } ) } .startWith(PartialChange.GetUser.Loading) val refreshChanges = refreshGetUsers::invoke .asFlow() .map { result -> result.fold( ifLeft = { PartialChange.Refresh.Failure(it) }, ifRight = { PartialChange.Refresh.Success } ) } .startWith(PartialChange.Refresh.Loading) return merge( filterIsInstance<ViewIntent.Initial>() .log("Intent") .flatMapConcat { getUserChanges }, filterIsInstance<ViewIntent.Refresh>() .filter { viewState.value.let { !it.isLoading && it.error === null } } .log("Intent") .flatMapFirst { refreshChanges }, filterIsInstance<ViewIntent.Retry>() .filter { viewState.value.error != null } .log("Intent") .flatMapFirst { getUserChanges }, filterIsInstance<ViewIntent.RemoveUser>() .log("Intent") .map { it.user } .flatMapMerge { userItem -> flow { userItem .toDomain() .flatMap { removeUser(it) } .let { emit(it) } } .map { result -> result.fold( ifLeft = { PartialChange.RemoveUser.Failure(userItem, it) }, ifRight = { PartialChange.RemoveUser.Success(userItem) }, ) } } ) } } private fun <T> defer(flowFactory: () -> Flow<T>): Flow<T> = flow { emitAll(flowFactory()) }
4
Kotlin
54
95
09d9ef5d45972c2b1f22459ffe07358013fca742
5,037
Jetpack-Compose-MVI-Coroutines-Flow
MIT License
app/src/main/java/com/example/composedemo/ui/activity/viewmode_string_demo/UiText.kt
keyur-n
565,866,258
false
null
package com.example.composedemo.ui.activity.viewmode_string_demo import android.content.Context import androidx.annotation.StringRes import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource sealed interface UiText { data class DynamicString(val value: String) : UiText class StringResource( @StringRes val resId: Int, vararg val args: Any ) : UiText @Composable fun asString(): String { return when (this) { is DynamicString -> value is StringResource -> stringResource(id = resId, *args) } } fun asString2(context: Context): String { return when (this) { is DynamicString -> value is StringResource -> context.getString(resId, *args) } } }
0
Kotlin
0
0
d3e749e8ffb1daf9e2378736ae5411208b4e9458
804
compose-demo
Apache License 2.0
linea/src/commonMain/kotlin/compose/icons/lineaicons/music/NoteMultiple.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.lineaicons.music import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.lineaicons.MusicGroup public val MusicGroup.NoteMultiple: ImageVector get() { if (_noteMultiple != null) { return _noteMultiple!! } _noteMultiple = Builder(name = "NoteMultiple", defaultWidth = 64.0.dp, defaultHeight = 64.0.dp, viewportWidth = 64.0f, viewportHeight = 64.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(18.0f, 55.0f) moveToRelative(-8.0f, 0.0f) arcToRelative(8.0f, 8.0f, 0.0f, true, true, 16.0f, 0.0f) arcToRelative(8.0f, 8.0f, 0.0f, true, true, -16.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(46.0f, 49.0f) moveToRelative(-8.0f, 0.0f) arcToRelative(8.0f, 8.0f, 0.0f, true, true, 16.0f, 0.0f) arcToRelative(8.0f, 8.0f, 0.0f, true, true, -16.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(54.0f, 49.0f) lineToRelative(0.0f, -48.0f) lineToRelative(-28.0f, 6.0f) lineToRelative(0.0f, 48.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(26.0f, 23.0f) lineTo(54.0f, 17.0f) } } .build() return _noteMultiple!! } private var _noteMultiple: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,913
compose-icons
MIT License
snapshot/src/androidMain/kotlin/com/quickbird/snapshot/Diffing+bitmap.kt
QuickBirdEng
517,579,154
false
null
package com.quickbird.snapshot import android.graphics.Bitmap import android.graphics.Color // TODO: Wrap Color fun Diffing.Companion.bitmap(colorDiffing: Diffing<Int>) = Diffing<Bitmap> { first, second -> if (first.asByteArray().contentEquals(second.asByteArray())) null else first.copy(first.config, true).apply { updatePixels { x, y, color -> if (x < second.width && y < second.height) colorDiffing(color, second.getPixel(x, y)) ?: color else color } } } val Diffing.Companion.colorRed get() = Diffing<Int> { first, second -> if (first == second) null else Color.RED } val Diffing.Companion.intMean get() = Diffing<Int> { first, second -> if (first == second) null else first / 2 + second / 2 }
2
Kotlin
2
50
a0e6db75d373b7622333f0c141db9ef7c507d290
818
kotlin-snapshot-testing
MIT License
src/main/kotlin/org/kamiblue/client/util/threads/BackgroundScope.kt
NotMonika
509,752,527
false
{"Kotlin": 1389924, "Java": 110277, "Shell": 15180, "GLSL": 3626}
package org.kamiblue.client.util.threads import kotlinx.coroutines.* import org.kamiblue.client.KamiMod @Suppress("EXPERIMENTAL_API_USAGE") internal object BackgroundScope : CoroutineScope by CoroutineScope(newFixedThreadPoolContext(2, "KAMI Blue Background")) { private val jobs = LinkedHashMap<BackgroundJob, Job?>() private var started = false fun start() { started = true for ((job, _) in jobs) { jobs[job] = startJob(job) } } fun launchLooping(name: String, delay: Long, block: suspend CoroutineScope.() -> Unit): BackgroundJob { return launchLooping(BackgroundJob(name, delay, block)) } fun launchLooping(job: BackgroundJob): BackgroundJob { if (!started) { jobs[job] = null } else { jobs[job] = startJob(job) } return job } fun cancel(job: BackgroundJob) = jobs.remove(job)?.cancel() private fun startJob(job: BackgroundJob): Job { return launch { while (isActive) { try { job.block(this) } catch (e: Exception) { KamiMod.LOG.warn("Error occurred while running background job ${job.name}", e) } delay(job.delay) } } } }
0
Kotlin
0
0
88dc5a7e96ba358898b03681bfdf760e93f94812
1,325
__AntiZhangZongZe__
Do What The F*ck You Want To Public License
app/src/main/java/com/jcl/exam/emapta/data/api/ApiInterface.kt
jaylumba
204,916,908
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 47, "XML": 30, "Java": 2, "C++": 1, "CMake": 1}
package com.jcl.exam.emapta.data.api import com.jcl.exam.emapta.data.api.response.ConvertResponse import io.reactivex.Single import retrofit2.http.GET import retrofit2.http.Path /** * Created by jaylumba on 05/16/2018. */ interface ApiInterface { @GET("currency/commercial/exchange/{fromAmount}-{fromCurrency}/{toCurrency}/latest") fun convert(@Path("fromAmount") fromAmount: String, @Path("fromCurrency") fromCurrency: String, @Path("toCurrency") toCurrency: String): Single<ConvertResponse> }
1
null
1
1
3b3ae7ae32b22b650e9c4c2302f987bc27876393
540
currency-converter-exam
Apache License 2.0
photofilterssdk/src/main/java/com/zomato/photofilters/imageprocessors/subfilters/SaturationSubFilter.kt
PaulHost
207,349,609
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "YAML": 1, "Markdown": 1, "INI": 1, "Proguard": 2, "XML": 10, "Kotlin": 13, "Java": 7, "Makefile": 2, "C++": 1}
package com.zomato.photofilters.imageprocessors.subfilters import android.graphics.Bitmap import com.zomato.photofilters.imageprocessors.ImageProcessor import com.zomato.photofilters.imageprocessors.SubFilter class SaturationSubFilter(val level: Float, override var tag: Any) : SubFilter { // The Level value is float, where level = 1 has no effect on the image override fun process(inputImage: Bitmap): Bitmap { return ImageProcessor.doSaturation(inputImage, level) } }
1
null
1
1
3a17296a90df11bbc36cbaddf84a1794301673a2
497
AndroidPhotoFilters
Apache License 2.0
SIKCronJob/src/main/java/com/sik/cronjob/receivers/CronJobCallback.kt
SilverIceKey
854,500,004
false
{"Kotlin": 10006, "AIDL": 604}
package com.sik.cronjob.receivers import com.sik.cronjob.ICronJobCallback import com.sik.cronjob.managers.CronJobScanner /** * 主进程的 AIDL 回调实现,接收到服务端通知时执行相应的任务。 */ class CronJobCallback : ICronJobCallback.Stub() { override fun onJobTriggered(jobId: Int) { // 获取已注册的方法并执行 val method = CronJobScanner.getMethodById(jobId) val targetObject = CronJobScanner.getTargetById(jobId) method?.let { try { it.invoke(targetObject) // 通过反射调用无参数的 void 方法 } catch (e: Exception) { e.printStackTrace() } } } }
0
Kotlin
0
0
c88c5b55db35b0572bccd9e00b0f7c87c3e23b93
614
SIKCronJob
MIT License
invirt-core/src/test/kotlin/invirt/http4k/JsonTest.kt
resoluteworks
762,239,437
false
{"Kotlin": 263953, "Makefile": 673, "CSS": 8}
package invirt.http4k import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import org.http4k.core.Method import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.with import org.http4k.routing.bind import org.http4k.routing.routes class JsonTest : StringSpec() { init { "json" { data class JsonTestPojo( val name: String, val enabled: Boolean ) val httpHandler = routes( "/test" bind Method.GET to { val lens = jsonLens<JsonTestPojo>() Response(Status.OK).with(lens of JsonTestPojo("<NAME>", false)) } ) httpHandler(Request(Method.GET, "/test")).bodyString() shouldBe """{"name":"<NAME>","enabled":false}""" } } }
0
Kotlin
0
2
d553601cb49e583353734c4b87301e528e06be90
892
invirt
Apache License 2.0
app/src/main/java/com/example/pocitiselfie/FaceContourGraphic.kt
guilhermeestevao
654,260,804
false
null
package com.example.pocitiselfie import android.graphics.* import android.graphics.drawable.shapes.RoundRectShape import android.util.Log import androidx.annotation.ColorInt import com.google.mlkit.vision.face.Face import com.google.mlkit.vision.face.FaceContour class FaceContourGraphic( private val overlay: GraphicOverlay, private val face: Face, private val imageRect: Rect ) : GraphicOverlay.Graphic(overlay) { private val facePositionPaint: Paint private val idPaint: Paint private val boxPaint: Paint init { val selectedColor = Color.WHITE facePositionPaint = Paint() facePositionPaint.color = selectedColor idPaint = Paint() idPaint.color = selectedColor idPaint.textSize = ID_TEXT_SIZE boxPaint = Paint() boxPaint.color = selectedColor boxPaint.style = Paint.Style.STROKE boxPaint.strokeWidth = BOX_STROKE_WIDTH } private fun Canvas.drawFace(facePosition: Int, @ColorInt selectedColor: Int) { val contour = face.getContour(facePosition) val path = Path() contour?.points?.forEachIndexed { index, pointF -> if (index == 0) { path.moveTo( translateX(pointF.x), translateY(pointF.y) ) } path.lineTo( translateX(pointF.x), translateY(pointF.y) ) } val paint = Paint().apply { color = selectedColor style = Paint.Style.STROKE strokeWidth = BOX_STROKE_WIDTH } drawPath(path, paint) } override fun draw(canvas: Canvas?) { val faceBoundingBox = face.boundingBox val rect = calculateRect( imageRect.height().toFloat(), imageRect.width().toFloat(), faceBoundingBox ) // canvas?.drawRect(rect, boxPaint) val border = Paint() val verticalSpacing = overlay.height * 0.2f val horizonralSpacing = overlay.width * 0.1f val rectBounding = RectF(horizonralSpacing, verticalSpacing, (overlay.width - horizonralSpacing), (overlay.height - verticalSpacing)) border.color = Color.parseColor("#FE3386") border.strokeWidth = 10f border.style = Paint.Style.STROKE border.isAntiAlias = true border.isDither = true // border.pathEffect = DashPathEffect(floatArrayOf(45f, 45f), 0f) /* if( faceBoundingBox.left > rectBounding.left && faceBoundingBox.top > rectBounding.top && faceBoundingBox.bottom < rectBounding.bottom && faceBoundingBox.right < rectBounding.right ){ }else{ }*/ if(!rectBounding.contains(rect)){ border.pathEffect = DashPathEffect(floatArrayOf(45f, 45f), 0f) } canvas?.drawRoundRect(rectBounding, 500f, 500f, border) // canvas?.drawRect(rectBounding, boxPaint) /* val contours = face.allContours contours.forEach { it.points.forEach { point -> val px = translateX(point.x) val py = translateY(point.y) canvas?.drawCircle(px, py, FACE_POSITION_RADIUS, facePositionPaint) } }*/ // face // canvas?.drawFace(FaceContour.FACE, Color.BLUE) // left eye /* canvas?.drawFace(FaceContour.LEFT_EYEBROW_TOP, Color.RED) canvas?.drawFace(FaceContour.LEFT_EYE, Color.BLACK) canvas?.drawFace(FaceContour.LEFT_EYEBROW_BOTTOM, Color.CYAN) // right eye canvas?.drawFace(FaceContour.RIGHT_EYE, Color.DKGRAY) canvas?.drawFace(FaceContour.RIGHT_EYEBROW_BOTTOM, Color.GRAY) canvas?.drawFace(FaceContour.RIGHT_EYEBROW_TOP, Color.GREEN) // nose canvas?.drawFace(FaceContour.NOSE_BOTTOM, Color.LTGRAY) canvas?.drawFace(FaceContour.NOSE_BRIDGE, Color.MAGENTA) */ val smile = face.smilingProbability if(smile != null && smile > 0.9) { canvas?.drawFace(FaceContour.LOWER_LIP_BOTTOM, Color.WHITE) canvas?.drawFace(FaceContour.LOWER_LIP_TOP, Color.YELLOW) canvas?.drawFace(FaceContour.UPPER_LIP_BOTTOM, Color.GREEN) canvas?.drawFace(FaceContour.UPPER_LIP_TOP, Color.CYAN) } val blinkLeft = face.leftEyeOpenProbability if(blinkLeft != null && blinkLeft < 0.1){ canvas?.drawFace(FaceContour.RIGHT_EYE, Color.DKGRAY) canvas?.drawFace(FaceContour.RIGHT_EYEBROW_BOTTOM, Color.GRAY) canvas?.drawFace(FaceContour.RIGHT_EYEBROW_TOP, Color.GREEN) } Log.d("FaceContourGraphic", "${face.headEulerAngleX}") // rip } companion object { private const val FACE_POSITION_RADIUS = 4.0f private const val ID_TEXT_SIZE = 30.0f private const val BOX_STROKE_WIDTH = 5.0f } }
0
Kotlin
0
0
58a091eebecf48b219b89423e6c3040c6de3207f
5,002
mlkit-poc-face-detect
Apache License 2.0
pact-jvm-matchers/src/main/kotlin/au/com/dius/pact/matchers/FormPostBodyMatcher.kt
vixplows
172,439,140
false
{"Gradle": 24, "YAML": 4, "Markdown": 25, "INI": 5, "Shell": 1, "Text": 10, "Ignore List": 1, "Batchfile": 1, "Groovy": 226, "Clojure": 5, "Kotlin": 105, "Scala": 72, "Java": 166, "JSON": 630, "XML": 2, "Dockerfile": 1}
package au.com.dius.pact.matchers import au.com.dius.pact.model.HttpPart import au.com.dius.pact.model.isEmpty import au.com.dius.pact.model.isMissing import au.com.dius.pact.model.isNotPresent import au.com.dius.pact.model.isPresent import au.com.dius.pact.model.matchingrules.MatchingRules import au.com.dius.pact.model.valueAsString import au.com.dius.pact.model.orEmpty import mu.KLogging import org.apache.http.NameValuePair import org.apache.http.client.utils.URLEncodedUtils class FormPostBodyMatcher : BodyMatcher { override fun matchBody(expected: HttpPart, actual: HttpPart, allowUnexpectedKeys: Boolean): List<BodyMismatch> { val expectedBody = expected.body val actualBody = actual.body return when { expectedBody.isMissing() -> emptyList() expectedBody.isPresent() && actualBody.isNotPresent() -> listOf(BodyMismatch(expectedBody.orEmpty(), null, "Expected a form post body but was missing")) expectedBody.isEmpty() && actualBody.isEmpty() -> emptyList() else -> { val expectedParameters = URLEncodedUtils.parse(expectedBody.valueAsString(), expected.charset(), '&') val actualParameters = URLEncodedUtils.parse(actualBody.valueAsString(), actual.charset(), '&') compareParameters(expectedParameters, actualParameters, expected.matchingRules, allowUnexpectedKeys) } } } private fun compareParameters( expectedParameters: List<NameValuePair>, actualParameters: List<NameValuePair>, matchingRules: MatchingRules?, allowUnexpectedKeys: Boolean ): List<BodyMismatch> { val expectedMap = expectedParameters.groupBy { it.name } val actualMap = actualParameters.groupBy { it.name } val result = mutableListOf<BodyMismatch>() expectedMap.forEach { if (actualMap.containsKey(it.key)) { it.value.forEachIndexed { index, valuePair -> val path = listOf("$", it.key, index.toString()) if (matchingRules != null && Matchers.matcherDefined("body", path, matchingRules)) { logger.debug { "Matcher defined for form post parameter '${it.key}'[$index]" } result.addAll(Matchers.domatch(matchingRules, "body", path, valuePair.value, actualMap[it.key]!![index].value, BodyMismatchFactory)) } else { logger.debug { "No matcher defined for form post parameter '${it.key}'[$index], using equality" } val actualValues = actualMap[it.key]!! if (actualValues.size <= index) { result.add(BodyMismatch("${it.key}=${valuePair.value}", null, "Expected form post parameter '${it.key}'='${valuePair.value}' but was missing")) } else if (valuePair.value != actualValues[index].value) { result.add(BodyMismatch("${it.key}=${valuePair.value}", "${it.key}=${actualValues[index].value}", "Expected form post parameter '${it.key}'[$index] with value '${valuePair.value}' but was '${actualValues[index].value}'")) } } } } else { result.add(BodyMismatch(it.key, null, "Expected form post parameter '${it.key}' but was missing")) } } if (!allowUnexpectedKeys) { actualMap.entries.forEach { if (!expectedMap.containsKey(it.key)) { val values = it.value.map { it.value } result.add(BodyMismatch(null, "${it.key}=$values", "Received unexpected form post parameter '${it.key}'=${values.map { "'$it'" }}")) } } } return result } companion object : KLogging() }
1
null
1
1
d8c38aec70e56541f9f699c05bcab1ba49a95dae
3,513
pact-jvm
Apache License 2.0
1.0/app/src/main/java/ru/oepak22/simplemusicplayer/screen/playlists/PlayListsActivity.kt
termy1989
560,741,642
false
{"Kotlin": 441269}
package ru.oepak22.simplemusicplayer.screen.playlists import android.annotation.SuppressLint import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.floatingactionbutton.FloatingActionButton import ru.oepak22.simplemusicplayer.MainApp import ru.oepak22.simplemusicplayer.R import ru.oepak22.simplemusicplayer.content.PlayList import ru.oepak22.simplemusicplayer.data.DataOperations import ru.oepak22.simplemusicplayer.data.DataService import ru.oepak22.simplemusicplayer.widget.BaseAdapter import ru.oepak22.simplemusicplayer.widget.EmptyRecyclerView import javax.inject.Inject // класс активности для работы с плейлистами class PlayListsActivity : AppCompatActivity(), PlayListsView, BaseAdapter.OnItemClickListener<PlayList>{ private lateinit var mPlayListsPresenter: PlayListsPresenter // презентер для работы с плейлистами private lateinit var mAdapter: PlayListsAdapter // адаптер списка private lateinit var mButtonAdd: FloatingActionButton // кнопка добавления плейлиста private lateinit var mButtonDel: FloatingActionButton // кнопка удаления плейлиста private var mDialog: AlertDialog? = null // диалоговое сообщение @Inject lateinit var mService: DataOperations // создание активности override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_playlists) // MainApp.sAppComponent.injectPlayListsActivity(this) // инициализация презентера mPlayListsPresenter = PlayListsPresenter(this, mService) // компоненты активности val mRecyclerView: EmptyRecyclerView = findViewById(R.id.playlists_recycler_view) val mEmptyView: View = findViewById(R.id.noplaylists_textview) // настройка списка mRecyclerView.layoutManager = LinearLayoutManager(this) mRecyclerView.mEmptyView = mEmptyView // инициализация адаптера списка mAdapter = PlayListsAdapter(ArrayList(), false) mAdapter.attachToRecyclerView(mRecyclerView) // инициализация кнопок mButtonAdd = findViewById(R.id.fab_add) mButtonDel = findViewById(R.id.fab_del) } // возобновление работы активности override fun onResume() { super.onResume() // установка обработчика нажатия на элемент списка mAdapter.mOnItemClickListener = this // установка обработчиков нажатия на кнопки mButtonAdd.setOnClickListener { addPlaylistDialog() } mButtonDel.setOnClickListener { delPlaylistDialog() } // вывод списка плейлистов mPlayListsPresenter.showPlaylists() } // приостановка работы активности override fun onPause() { super.onPause() mAdapter.mOnItemClickListener = null mButtonAdd.setOnClickListener(null) mButtonDel.setOnClickListener(null) } // уничтожение активности override fun onDestroy() { super.onDestroy() mDialog?.dismiss() } // вывод списка плейлистов override fun showPlaylists(list: ArrayList<PlayList>) { mAdapter.changeDataSet(list) } // вывод пустого пространства override fun showEmptyPlaylists() { mAdapter.clear() } // сообщение об успешном завершении операции override fun showSuccess(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() mPlayListsPresenter.showPlaylists() } // сообщение об ошибке при выполнении операции override fun showError(msg: String) { val builder = AlertDialog.Builder(this) with (builder) { setIcon(R.drawable.ic_message_error) setTitle(R.string.message_error) setMessage(msg) setPositiveButton(R.string.message_ok) { _, _ -> } } mDialog = builder.create() mDialog!!.show() } // нажатие на элемент списка - редактирование override fun onItemClick(item: PlayList) { editPlayDialog(item.mName) } // добавление нового плейлиста @SuppressLint("InflateParams") private fun addPlaylistDialog() { val builder = AlertDialog.Builder(this) val inflater = layoutInflater val dialogLayout = inflater.inflate(R.layout.edit_text_layout, null) val editText = dialogLayout.findViewById<EditText>(R.id.editText) with (builder) { setTitle(R.string.message_add_title) setPositiveButton(R.string.message_ok) { _, _ -> mPlayListsPresenter.addNewPlaylist(editText.text.toString()) } setNegativeButton(R.string.message_cancel) { _, _ -> } setView(dialogLayout) } mDialog = builder.create() mDialog!!.show() } // @SuppressLint("InflateParams") private fun editPlayDialog(oldName: String) { val builder = AlertDialog.Builder(this) val inflater = layoutInflater val dialogLayout = inflater.inflate(R.layout.edit_text_layout, null) val editText = dialogLayout.findViewById<EditText>(R.id.editText) editText.setText(oldName) editText.hint = "New name" with (builder) { setTitle(R.string.message_edit_title) setPositiveButton(R.string.message_ok) { _, _ -> mPlayListsPresenter.editSelectedPlaylist(oldName, editText.text.toString()) } setNegativeButton(R.string.message_cancel) { _, _ -> } setView(dialogLayout) } mDialog = builder.create() mDialog!!.show() } // удаление выбранных плейлистов private fun delPlaylistDialog() { val list = ArrayList<PlayList>() for (item in mAdapter.mItems) { if (item.mSelected) list.add(item) } if (list.size == 0) showError("Please, select at least one item for deleting") else { val builder = AlertDialog.Builder(this) with (builder) { setIcon(R.drawable.ic_message_warning) setTitle(R.string.message_warning) setMessage(R.string.message_sure_delete) setPositiveButton(R.string.message_ok) { _, _ -> mPlayListsPresenter.deleteSelectedPlaylist(list) } setNegativeButton(R.string.message_cancel) { _, _ -> } } mDialog = builder.create() mDialog!!.show() } } }
0
Kotlin
0
1
f9d261b067a1fbbd4fc1fa3c9493aa21f421c032
6,982
SimpleMusicPlayer
Apache License 2.0
src/Day02.kt
daividssilverio
572,944,347
false
{"Kotlin": 10575}
import java.lang.Exception fun main() { /* scoring win = 6 lose = 0 draw = 3 initial strategy (wrong) A, X = Rock (1) B, Y = Paper (2) C, Z = Scissors (3) actual strategy X = lose Y = draw Z = win */ val entries = readInput("Day02_test") val wronglyCalculatedResult = entries.fold(0) { acc, game -> acc + judgeMatch(game) { _, player2 -> player2.minus(23) } } val actualIdealResult = entries.fold(0) { acc, game -> acc + judgeMatch(game) { player1, player2 -> when (player2) { 'X' -> loseTo(player1) 'Z' -> winAgainst(player1) 'Y' -> player1 else -> throw Exception("Invalid game $game $player1, $player2") } } } println(wronglyCalculatedResult) println(actualIdealResult) } private fun Char.scoreValue() = code - 64 private fun winAgainst(game: Char) = when (game) { 'A' -> 'B' 'B' -> 'C' 'C' -> 'A' else -> throw Exception("Invalid hand $game") } private fun loseTo(game: Char) = winAgainst(winAgainst(game)) private val resultMap = mapOf( 0 to 3, // draw -1 to 0, // lose -2 to 6, // win 1 to 6, // win 2 to 0 // lose ) private fun judgeMatch(game: String, strategy: (Char, Char) -> Char): Int { val player1game = game[0] val player2Strategy = game[2] val player2game = strategy(player1game, player2Strategy) return (resultMap[player2game - player1game] ?: throw Exception("unexpected result $player2game - $player1game")) + player2game.scoreValue() }
0
Kotlin
0
0
141236c67fe03692785e0f3ab90248064a1693da
1,624
advent-of-code-kotlin-2022
Apache License 2.0
sdui/src/commonMain/kotlin/dev/helw/playground/sdui/serializer/TypographyTokenSerializer.kt
ahmedre
680,260,539
false
{"Kotlin": 114371, "Swift": 29613, "HTML": 237}
/** * Copyright (c) 2023 <NAME> and <NAME> * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package dev.helw.playground.sdui.serializer import dev.helw.playground.sdui.design.core.TypographyToken import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder object TypographyTokenSerializer : KSerializer<TypographyToken> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("TypographyToken", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: TypographyToken) { encoder.encodeString(value.name) } override fun deserialize(decoder: Decoder): TypographyToken { val tokenString = decoder.decodeString() return TypographyToken.values.find { it.name == tokenString } ?: TypographyToken.Body.Medium } }
0
Kotlin
0
3
d9e02bcf1251834fe34518f7109b21a5ae7960f5
1,129
sdui
MIT License
feature/listaproduto/src/androidTest/java/com/z1/comparaprecos/feature/listaproduto/presentation/screen/ResumoComparacaoListaScreenTest.kt
zero1code
748,829,698
false
{"Kotlin": 441569}
package com.z1.comparaprecos.feature.listaproduto.presentation.screen import androidx.activity.ComponentActivity import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.onRoot import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.test.printToLog import androidx.compose.ui.test.swipeUp import androidx.test.ext.junit.runners.AndroidJUnit4 import com.z1.comparaprecos.common.extensions.getPercentageDifference import com.z1.comparaprecos.common.extensions.toMoedaLocal import com.z1.comparaprecos.common.ui.theme.ComparaPrecosTheme import com.z1.comparaprecos.common.ui.theme.CoralRed import com.z1.comparaprecos.common.ui.theme.MediumSeaGreen import com.z1.comparaprecos.core.common.R import com.z1.comparaprecos.testing.assertTextColor import com.z1.comparaprecos.testing.data.listaProdutoDataTest import com.z1.comparaprecos.testing.data.listaProdutoDataTest2 import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ResumoComparacaoListaScreenTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() private val listaProduto = "Lista compra" to listaProdutoDataTest private val listaProdutoComparada = "Lista compra comparada" to listaProdutoDataTest2 private fun init() { composeTestRule.setContent { ComparaPrecosTheme { ResumoComparacaoListaScreen( listaProduto = listaProduto, listaProdutoComparada = listaProdutoComparada ) } } } @Test fun shouldShowDetailsOfTwoListaCompraSelectedByUser() { //Given - Dado val listaCompraSoma = listaProduto.second.sumOf { it.valorProduto() }.toMoedaLocal() val listaCompraComparadaSoma = listaProdutoComparada.second.sumOf { it.valorProduto() }.toMoedaLocal() //When - Quando init() //Then - Entao composeTestRule.onNodeWithText("Lista compra").assertIsDisplayed() composeTestRule.onNodeWithText("3").assertIsDisplayed() composeTestRule.onNodeWithText("7").assertIsDisplayed() composeTestRule.onNodeWithText(listaCompraSoma).assertIsDisplayed() composeTestRule.onNodeWithText("Lista compra comparada").assertIsDisplayed() composeTestRule.onNodeWithText("4").assertIsDisplayed() composeTestRule.onNodeWithText("8").assertIsDisplayed() composeTestRule.onNodeWithText(listaCompraComparadaSoma).assertIsDisplayed() } @Test fun shouldShowDetailsOfProdutosInSameListaCompra() { //Given - Dado val listaProdutoIgual = listaProduto.second.filter { produto -> listaProdutoComparada.second.any { produtoComparado -> produto.nomeProduto == produtoComparado.nomeProduto } } val listaProdutoComparadaIgual = listaProdutoComparada.second.filter { produtoComparado -> listaProduto.second.any { produto -> produto.nomeProduto == produtoComparado.nomeProduto } } val valorListaAtual = listaProdutoIgual.sumOf { it.valorProduto() } val valorListaComparada = listaProdutoComparadaIgual.sumOf { it.valorProduto() } val diferencaPreco = valorListaAtual.minus(valorListaComparada) val diferencaPorcentagem = valorListaAtual.getPercentageDifference(valorListaComparada) val produtosNaMesmaLista = composeTestRule.activity .getString(R.string.label_desc_somando_produtos_nas_listas, listaProdutoIgual.size) //When - Quando init() //Then - Entao composeTestRule.onNodeWithText(produtosNaMesmaLista).assertIsDisplayed() composeTestRule.onNodeWithText(valorListaAtual.toMoedaLocal()).assertIsDisplayed() composeTestRule.onNodeWithText(valorListaComparada.toMoedaLocal()).assertIsDisplayed() composeTestRule.onNodeWithText(diferencaPreco.toMoedaLocal()).assertIsDisplayed() composeTestRule.onNodeWithText(diferencaPorcentagem, useUnmergedTree = true) .assertIsDisplayed() .assertTextColor(CoralRed) } @Test fun shouldShowDetailsOfAllProdutoInTwoListaCompra() { //Given - Dado val valorListaAtual = listaProduto.second.sumOf { it.valorProduto() } val valorListaComparada = listaProdutoComparada.second.sumOf { it.valorProduto() } val diferencaPreco = valorListaAtual.minus(valorListaComparada) val diferencaPorcentagem = valorListaAtual.getPercentageDifference(valorListaComparada) val somandoTodosOsProdutos = composeTestRule.activity .getString(R.string.label_desc_somando_todos_produtos) //When - Quando init() composeTestRule.onRoot().performTouchInput { swipeUp() } // composeTestRule.onRoot(useUnmergedTree = true).printToLog("currentTree") //Then - Entao composeTestRule.onNodeWithText(somandoTodosOsProdutos).assertIsDisplayed() composeTestRule.onNodeWithText(valorListaAtual.toMoedaLocal()).assertIsDisplayed() composeTestRule.onNodeWithText(valorListaComparada.toMoedaLocal()).assertIsDisplayed() composeTestRule.onNodeWithText(diferencaPreco.toMoedaLocal()).assertIsDisplayed() composeTestRule.onNodeWithText(diferencaPorcentagem, useUnmergedTree = true) .assertIsDisplayed() .assertTextColor(MediumSeaGreen) } }
0
Kotlin
0
0
2ada1d386ea6e42b37a6c86b145d3c35883d3856
5,644
Compara-precos
Apache License 2.0
packages/Manager/src/main/kotlin/nz/govt/eop/freshwater_management_units/services/FreshwaterManagementUnitService.kt
Greater-Wellington-Regional-Council
528,176,417
false
null
package nz.govt.eop.freshwater_management_units.services import mu.KotlinLogging import nz.govt.eop.freshwater_management_units.models.FreshwaterManagementUnit import nz.govt.eop.freshwater_management_units.repositories.FreshwaterManagementUnitRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service @Service class FreshwaterManagementUnitService @Autowired constructor( private val repository: FreshwaterManagementUnitRepository, ) { private val logger = KotlinLogging.logger {} fun findFreshwaterManagementUnitByLatAndLng( lng: Double, lat: Double, srid: Int = FreshwaterManagementUnit.DEFAULT_SRID, ): FreshwaterManagementUnit? { val fmus = repository.findAllByLngLat(lng, lat, srid) if (fmus.count() > 1) { logger.warn { "More than 1 FMUs found for lat: $lat, lng: $lng" } } return fmus.firstOrNull() } fun findFreshwaterManagementUnitById(id: Int): FreshwaterManagementUnit? = repository.findById(id).orElse(null) fun findAllFreshwaterManagementUnits(): List<FreshwaterManagementUnit> { return repository.findAll() } }
14
null
3
5
292ce1c7eb3039957f0774e018832625c7a336d5
1,162
Environmental-Outcomes-Platform
MIT License
Todo/app/src/main/java/com/vad/todovad/presenter/TaskContract.kt
liemvo
198,412,014
false
null
package com.vad.todovad.presenter interface TaskContract { interface Presenter { fun updateTitle(title: String) fun updateDescription(description: String) fun saveTask() } interface View { fun showTaskSaved() fun showTaskError() } }
0
Kotlin
0
0
eb1be4df0a7ce76d78c11139537293d2dcf37df2
294
android_samples
MIT License
src/all/jellyfin/src/eu/kanade/tachiyomi/animeextension/all/jellyfin/Jellyfin.kt
tom2411
406,731,462
true
{"Kotlin": 2528349, "Java": 9693}
package eu.kanade.tachiyomi.animeextension.all.jellyfin import android.app.Application import android.content.Context import android.content.SharedPreferences import android.text.InputType import android.widget.Toast import androidx.preference.EditTextPreference import androidx.preference.ListPreference import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource import eu.kanade.tachiyomi.animesource.model.AnimeFilterList import eu.kanade.tachiyomi.animesource.model.AnimesPage import eu.kanade.tachiyomi.animesource.model.SAnime import eu.kanade.tachiyomi.animesource.model.SEpisode import eu.kanade.tachiyomi.animesource.model.Track import eu.kanade.tachiyomi.animesource.model.Video import eu.kanade.tachiyomi.animesource.online.AnimeHttpSource import eu.kanade.tachiyomi.network.GET import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.boolean import kotlinx.serialization.json.float import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import okhttp3.Dns import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.Jsoup import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import kotlin.math.ceil import kotlin.math.floor class Jellyfin : ConfigurableAnimeSource, AnimeHttpSource() { override val name = "Jellyfin" override val lang = "all" override val supportsLatest = true override val client: OkHttpClient = network.client .newBuilder() .dns(Dns.SYSTEM) .build() private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } override var baseUrl = JFConstants.getPrefHostUrl(preferences) private var username = JFConstants.getPrefUsername(preferences) private var password = JFConstants.getPrefPassword(preferences) private var parentId = JFConstants.getPrefParentId(preferences) private var apiKey = JFConstants.getPrefApiKey(preferences) private var userId = JFConstants.getPrefUserId(preferences) init { login(false) } private fun login(new: Boolean, context: Context? = null): Boolean? { if (apiKey == null || userId == null || new) { baseUrl = JFConstants.getPrefHostUrl(preferences) username = JFConstants.getPrefUsername(preferences) password = <PASSWORD>(preferences) if (username.isEmpty() || password.isEmpty()) { return null } val (newKey, newUid) = runBlocking { withContext(Dispatchers.IO) { JellyfinAuthenticator(preferences, baseUrl, client) .login(username, password) } } if (newKey != null && newUid != null) { apiKey = newKey userId = newUid } else { context?.let { Toast.makeText(it, "Login failed.", Toast.LENGTH_LONG).show() } return false } } return true } // Popular Anime (is currently sorted by name instead of e.g. ratings) override fun popularAnimeRequest(page: Int): Request { if (parentId.isEmpty()) { throw Exception("Select library in the extension settings.") } val startIndex = (page - 1) * 20 val url = "$baseUrl/Users/$userId/Items".toHttpUrl().newBuilder() url.addQueryParameter("api_key", apiKey) url.addQueryParameter("StartIndex", startIndex.toString()) url.addQueryParameter("Limit", "20") url.addQueryParameter("Recursive", "true") url.addQueryParameter("SortBy", "SortName") url.addQueryParameter("SortOrder", "Ascending") url.addQueryParameter("includeItemTypes", "Movie,Series,Season") url.addQueryParameter("ImageTypeLimit", "1") url.addQueryParameter("ParentId", parentId) url.addQueryParameter("EnableImageTypes", "Primary") return GET(url.toString()) } override fun popularAnimeParse(response: Response): AnimesPage { val (list, hasNext) = animeParse(response) return AnimesPage( list.sortedBy { it.title }, hasNext, ) } // Episodes override fun episodeListParse(response: Response): List<SEpisode> { val json = Json.decodeFromString<JsonObject>(response.body!!.string()) val episodeList = mutableListOf<SEpisode>() // Is movie if (json.containsKey("Type")) { val episode = SEpisode.create() val id = json["Id"]!!.jsonPrimitive.content episode.episode_number = 1.0F episode.name = "Movie: " + json["Name"]!!.jsonPrimitive.content episode.setUrlWithoutDomain("/Users/$userId/Items/$id?api_key=$apiKey") episodeList.add(episode) } else { val items = json["Items"]!!.jsonArray for (item in items) { val episode = SEpisode.create() val jsonObj = item.jsonObject val id = jsonObj["Id"]!!.jsonPrimitive.content val epNum = if (jsonObj["IndexNumber"] == null) { null } else { jsonObj["IndexNumber"]!!.jsonPrimitive.float } if (epNum != null) { episode.episode_number = epNum val formattedEpNum = if (floor(epNum) == ceil(epNum)) { epNum.toInt().toString() } else { epNum.toString() } episode.name = "Episode $formattedEpNum: " + jsonObj["Name"]!!.jsonPrimitive.content } else { episode.episode_number = 0F episode.name = jsonObj["Name"]!!.jsonPrimitive.content } episode.setUrlWithoutDomain("/Users/$userId/Items/$id?api_key=$apiKey") episodeList.add(episode) } } return episodeList.reversed() } private fun animeParse(response: Response): AnimesPage { val items = Json.decodeFromString<JsonObject>(response.body!!.string())["Items"]?.jsonArray val animesList = mutableListOf<SAnime>() if (items != null) { for (item in items) { val anime = SAnime.create() val jsonObj = item.jsonObject if (jsonObj["Type"]!!.jsonPrimitive.content == "Season") { val seasonId = jsonObj["Id"]!!.jsonPrimitive.content val seriesId = jsonObj["SeriesId"]!!.jsonPrimitive.content anime.setUrlWithoutDomain("/Shows/$seriesId/Episodes?api_key=$apiKey&SeasonId=$seasonId") // Virtual if show doesn't have any sub-folders, i.e. no seasons if (jsonObj["LocationType"]!!.jsonPrimitive.content == "Virtual") { anime.title = jsonObj["SeriesName"]!!.jsonPrimitive.content anime.thumbnail_url = "$baseUrl/Items/$seriesId/Images/Primary?api_key=$apiKey" } else { anime.title = jsonObj["SeriesName"]!!.jsonPrimitive.content + " " + jsonObj["Name"]!!.jsonPrimitive.content anime.thumbnail_url = "$baseUrl/Items/$seasonId/Images/Primary?api_key=$apiKey" } // If season doesn't have image, fallback to series image if (jsonObj["ImageTags"].toString() == "{}") { anime.thumbnail_url = "$baseUrl/Items/$seriesId/Images/Primary?api_key=$apiKey" } } else if (jsonObj["Type"]!!.jsonPrimitive.content == "Movie") { val id = jsonObj["Id"]!!.jsonPrimitive.content anime.title = jsonObj["Name"]!!.jsonPrimitive.content anime.thumbnail_url = "$baseUrl/Items/$id/Images/Primary?api_key=$apiKey" anime.setUrlWithoutDomain("/Users/$userId/Items/$id?api_key=$apiKey") } else { continue } animesList.add(anime) } } val hasNextPage = (items?.size?.compareTo(20) ?: -1) >= 0 return AnimesPage(animesList, hasNextPage) } // Video urls override fun videoListParse(response: Response): List<Video> { val videoList = mutableListOf<Video>() val item = Json.decodeFromString<JsonObject>(response.body!!.string()) val id = item["Id"]!!.jsonPrimitive.content val sessionResponse = client.newCall( GET( "$baseUrl/Items/$id/PlaybackInfo?userId=$userId&api_key=$apiKey" ) ).execute() val sessionJson = Json.decodeFromString<JsonObject>(sessionResponse.body!!.string()) val sessionId = sessionJson["PlaySessionId"]!!.jsonPrimitive.content val mediaStreams = sessionJson["MediaSources"]!!.jsonArray[0].jsonObject["MediaStreams"]?.jsonArray val subtitleList = mutableListOf<Track>() val prefSub = preferences.getString(JFConstants.PREF_SUB_KEY, "eng")!! val prefAudio = preferences.getString(JFConstants.PREF_AUDIO_KEY, "jpn")!! var audioIndex = 1 var subIndex: Int? = null var width = 1920 var height = 1080 // Get subtitle streams and audio index if (mediaStreams != null) { for (media in mediaStreams) { val index = media.jsonObject["Index"]!!.jsonPrimitive.int val codec = media.jsonObject["Codec"]!!.jsonPrimitive.content val lang = media.jsonObject["Language"] val supportsExternalStream = media.jsonObject["SupportsExternalStream"]!!.jsonPrimitive.boolean val type = media.jsonObject["Type"]!!.jsonPrimitive.content if (type == "Subtitle" && supportsExternalStream) { val subUrl = "$baseUrl/Videos/$id/$id/Subtitles/$index/0/Stream.$codec?api_key=$apiKey" // TODO: add ttf files in media attachment (if possible) val title = media.jsonObject["DisplayTitle"]!!.jsonPrimitive.content if (lang != null) { if (lang.jsonPrimitive.content == prefSub) { try { subtitleList.add(0, Track(subUrl, title)) } catch (e: Error) { subIndex = index } } else { try { subtitleList.add(Track(subUrl, title)) } catch (_: Error) {} } } else { try { subtitleList.add(Track(subUrl, title)) } catch (_: Error) {} } } else if (type == "Subtitle") { if (lang != null) { if (lang.jsonPrimitive.content == prefSub) { subIndex = index } } } if (type == "Audio") { if (lang != null) { if (lang.jsonPrimitive.content == prefAudio) { audioIndex = index } } } if (media.jsonObject["Type"]!!.jsonPrimitive.content == "Video") { width = media.jsonObject["Width"]!!.jsonPrimitive.int height = media.jsonObject["Height"]!!.jsonPrimitive.int } } } // Loop over qualities for (quality in JFConstants.QUALITIES_LIST) { if (width < quality.width && height < quality.height) { val url = "$baseUrl/Videos/$id/stream?static=True&api_key=$apiKey" videoList.add(Video(url, "Best", url)) return videoList.reversed() } else { val url = "$baseUrl/videos/$id/main.m3u8".toHttpUrl().newBuilder() url.addQueryParameter("api_key", apiKey) url.addQueryParameter("VideoCodec", "h264") url.addQueryParameter("AudioCodec", "aac,mp3") url.addQueryParameter("AudioStreamIndex", audioIndex.toString()) subIndex?.let { url.addQueryParameter("SubtitleStreamIndex", it.toString()) } url.addQueryParameter("VideoCodec", "h264") url.addQueryParameter("VideoCodec", "h264") url.addQueryParameter( "VideoBitrate", quality.videoBitrate.toString() ) url.addQueryParameter( "AudioBitrate", quality.audioBitrate.toString() ) url.addQueryParameter("PlaySessionId", sessionId) url.addQueryParameter("TranscodingMaxAudioChannels", "6") url.addQueryParameter("RequireAvc", "false") url.addQueryParameter("SegmentContainer", "ts") url.addQueryParameter("MinSegments", "1") url.addQueryParameter("BreakOnNonKeyFrames", "true") url.addQueryParameter("h264-profile", "high,main,baseline,constrainedbaseline") url.addQueryParameter("h264-level", "51") url.addQueryParameter("h264-deinterlace", "true") url.addQueryParameter("TranscodeReasons", "VideoCodecNotSupported,AudioCodecNotSupported,ContainerBitrateExceedsLimit") try { videoList.add(Video(url.toString(), quality.description, url.toString(), subtitleTracks = subtitleList)) } catch (_: Error) { videoList.add(Video(url.toString(), quality.description, url.toString())) } } } val url = "$baseUrl/Videos/$id/stream?static=True&api_key=$apiKey" videoList.add(Video(url, "Best", url)) return videoList.reversed() } // search override fun searchAnimeParse(response: Response) = animeParse(response) override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList): Request { if (parentId.isEmpty()) { throw Exception("Select library in the extension settings.") } if (query.isBlank()) { throw Exception("Search query blank") } val startIndex = (page - 1) * 20 val url = "$baseUrl/Users/$userId/Items".toHttpUrl().newBuilder() url.addQueryParameter("api_key", apiKey) url.addQueryParameter("StartIndex", startIndex.toString()) url.addQueryParameter("Limit", "20") url.addQueryParameter("Recursive", "true") url.addQueryParameter("SortBy", "SortName") url.addQueryParameter("SortOrder", "Ascending") url.addQueryParameter("includeItemTypes", "Movie,Series,Season") url.addQueryParameter("ImageTypeLimit", "1") url.addQueryParameter("EnableImageTypes", "Primary") url.addQueryParameter("ParentId", parentId) url.addQueryParameter("SearchTerm", query) return GET(url.toString()) } // Details override fun animeDetailsRequest(anime: SAnime): Request { val infoArr = anime.url.split("/").toTypedArray() val id = if (infoArr[1] == "Users") { infoArr[4].split("?").toTypedArray()[0] } else { infoArr[2] } val url = "$baseUrl/Users/$userId/Items/$id".toHttpUrl().newBuilder() url.addQueryParameter("api_key", apiKey) url.addQueryParameter("fields", "Studios") return GET(url.toString()) } override fun animeDetailsParse(response: Response): SAnime { val item = Json.decodeFromString<JsonObject>(response.body!!.string()) val anime = SAnime.create() anime.author = if (item["Studios"]!!.jsonArray.isEmpty()) { "" } else { item["Studios"]!!.jsonArray[0].jsonObject["Name"]!!.jsonPrimitive.content } anime.description = item["Overview"]?.let { Jsoup.parse(it.jsonPrimitive.content.replace("<br>", "br2n")).text().replace("br2n", "\n") } ?: "" if (item["Genres"]!!.jsonArray.isEmpty()) { anime.genre = "" } else { val genres = mutableListOf<String>() for (genre in item["Genres"]!!.jsonArray) { genres.add(genre.jsonPrimitive.content) } anime.genre = genres.joinToString() } anime.status = item["Status"]?.let { if (it.jsonPrimitive.content == "Ended") SAnime.COMPLETED else SAnime.UNKNOWN } ?: SAnime.UNKNOWN if (item["Type"]!!.jsonPrimitive.content == "Season") { val seasonId = item["Id"]!!.jsonPrimitive.content val seriesId = item["SeriesId"]!!.jsonPrimitive.content anime.setUrlWithoutDomain("/Shows/$seriesId/Episodes?api_key=$apiKey&SeasonId=$seasonId") // Virtual if show doesn't have any sub-folders, i.e. no seasons if (item["LocationType"]!!.jsonPrimitive.content == "Virtual") { anime.title = item["SeriesName"]!!.jsonPrimitive.content anime.thumbnail_url = "$baseUrl/Items/$seriesId/Images/Primary?api_key=$apiKey" } else { anime.title = item["SeriesName"]!!.jsonPrimitive.content + " " + item["Name"]!!.jsonPrimitive.content anime.thumbnail_url = "$baseUrl/Items/$seasonId/Images/Primary?api_key=$apiKey" } // If season doesn't have image, fallback to series image if (item["ImageTags"].toString() == "{}") { anime.thumbnail_url = "$baseUrl/Items/$seriesId/Images/Primary?api_key=$apiKey" } } else if (item["Type"]!!.jsonPrimitive.content == "Movie") { val id = item["Id"]!!.jsonPrimitive.content anime.title = item["Name"]!!.jsonPrimitive.content anime.thumbnail_url = "$baseUrl/Items/$id/Images/Primary?api_key=$apiKey" anime.setUrlWithoutDomain("/Users/$userId/Items/$id?api_key=$apiKey") } return anime } // Latest override fun latestUpdatesRequest(page: Int): Request { if (parentId.isEmpty()) { throw Exception("Select library in the extension settings.") } val startIndex = (page - 1) * 20 val url = "$baseUrl/Users/$userId/Items".toHttpUrl().newBuilder() url.addQueryParameter("api_key", apiKey) url.addQueryParameter("StartIndex", startIndex.toString()) url.addQueryParameter("Limit", "20") url.addQueryParameter("Recursive", "true") url.addQueryParameter("SortBy", "DateCreated,SortName") url.addQueryParameter("SortOrder", "Descending") url.addQueryParameter("includeItemTypes", "Movie,Series,Season") url.addQueryParameter("ImageTypeLimit", "1") url.addQueryParameter("ParentId", parentId) url.addQueryParameter("EnableImageTypes", "Primary") return GET(url.toString()) } override fun latestUpdatesParse(response: Response) = animeParse(response) // Filters - not used // settings override fun setupPreferenceScreen(screen: PreferenceScreen) { val mediaLibPref = medialibPreference(screen) screen.addPreference( screen.editTextPreference( JFConstants.HOSTURL_KEY, JFConstants.HOSTURL_TITLE, JFConstants.HOSTURL_DEFAULT, baseUrl, false, "", mediaLibPref ) ) screen.addPreference( screen.editTextPreference( JFConstants.USERNAME_KEY, JFConstants.USERNAME_TITLE, "", username, false, "", mediaLibPref ) ) screen.addPreference( screen.editTextPreference( JFConstants.PASSWORD_KEY, JFConstants.PASSWORD_TITLE, "", password, true, "••••••••", mediaLibPref ) ) screen.addPreference(mediaLibPref) val subLangPref = ListPreference(screen.context).apply { key = JFConstants.PREF_SUB_KEY title = JFConstants.PREF_SUB_TITLE entries = JFConstants.PREF_ENTRIES entryValues = JFConstants.PREF_VALUES setDefaultValue("eng") summary = "%s" setOnPreferenceChangeListener { _, newValue -> val selected = newValue as String val index = findIndexOfValue(selected) val entry = entryValues[index] as String preferences.edit().putString(key, entry).commit() } } screen.addPreference(subLangPref) val audioLangPref = ListPreference(screen.context).apply { key = JFConstants.PREF_AUDIO_KEY title = JFConstants.PREF_AUDIO_TITLE entries = JFConstants.PREF_ENTRIES entryValues = JFConstants.PREF_VALUES setDefaultValue("jpn") summary = "%s" setOnPreferenceChangeListener { _, newValue -> val selected = newValue as String val index = findIndexOfValue(selected) val entry = entryValues[index] as String preferences.edit().putString(key, entry).commit() } } screen.addPreference(audioLangPref) } private abstract class MediaLibPreference(context: Context) : ListPreference(context) { abstract fun reload() } private fun medialibPreference(screen: PreferenceScreen) = ( object : MediaLibPreference(screen.context) { override fun reload() { this.apply { key = JFConstants.MEDIALIB_KEY title = JFConstants.MEDIALIB_TITLE summary = "%s" Thread { try { val mediaLibsResponse = client.newCall( GET("$baseUrl/Users/$userId/Items?api_key=$apiKey") ).execute() val mediaJson = mediaLibsResponse.body?.let { Json.decodeFromString<JsonObject>(it.string()) }?.get("Items")?.jsonArray val entriesArray = mutableListOf<String>() val entriesValueArray = mutableListOf<String>() if (mediaJson != null) { for (media in mediaJson) { entriesArray.add(media.jsonObject["Name"]!!.jsonPrimitive.content) entriesValueArray.add(media.jsonObject["Id"]!!.jsonPrimitive.content) } } entries = entriesArray.toTypedArray() entryValues = entriesValueArray.toTypedArray() } catch (ex: Exception) { entries = emptyArray() entryValues = emptyArray() } }.start() setOnPreferenceChangeListener { _, newValue -> val selected = newValue as String val index = findIndexOfValue(selected) val entry = entryValues[index] as String parentId = entry preferences.edit().putString(key, entry).commit() } } } } ).apply { reload() } private fun PreferenceScreen.editTextPreference(key: String, title: String, default: String, value: String, isPassword: Boolean = false, placeholder: String, mediaLibPref: MediaLibPreference): EditTextPreference { return EditTextPreference(context).apply { this.key = key this.title = title summary = if ((isPassword && value.isNotEmpty()) || (!isPassword && value.isEmpty())) { placeholder } else { value } this.setDefaultValue(default) dialogTitle = title setOnBindEditTextListener { it.inputType = if (isPassword) { InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD } else { InputType.TYPE_CLASS_TEXT } } setOnPreferenceChangeListener { _, newValue -> try { val newValueString = newValue as String val res = preferences.edit().putString(key, newValueString).commit() summary = if ((isPassword && newValueString.isNotEmpty()) || (!isPassword && newValueString.isEmpty())) { placeholder } else { newValueString } val loginRes = login(true, context) if (loginRes == true) { mediaLibPref.reload() } res } catch (e: Exception) { false } } } } }
0
Kotlin
0
0
a327ce14950e5e76359185e643a58301df48be34
26,154
aniyomi-extensions
Apache License 2.0
ExoPlayerAdapter/src/exo-analytics-upto-2_16/java/com/mux/stats/sdk/muxstats/SessionDataBindings.kt
muxinc
141,313,277
false
null
package com.mux.stats.sdk.muxstats import com.google.android.exoplayer2.ExoPlayer import com.google.android.exoplayer2.SimpleExoPlayer import com.google.android.exoplayer2.analytics.AnalyticsListener import com.google.android.exoplayer2.source.hls.HlsManifest import com.mux.stats.sdk.core.model.SessionTag import com.mux.stats.sdk.core.util.MuxLogger import com.mux.stats.sdk.muxstats.exoplayeradapter.MuxPlayerAdapter import com.mux.stats.sdk.muxstats.exoplayeradapter.internal.isHlsExtensionAvailable import com.mux.stats.sdk.muxstats.exoplayeradapter.internal.weak import java.util.regex.Matcher import java.util.regex.Pattern /** * Session Data player binding for Exo versions 2.16 and below. Requires a SimpleExoPlayer otherwise * [bindPlayer] and [unbindPlayer] are no-ops */ private class SessionDataPlayerBinding : MuxPlayerAdapter.PlayerBinding<ExoPlayer> { private var listener: AnalyticsListener? by weak(null) override fun bindPlayer(player: ExoPlayer, collector: MuxStateCollectorBase) { if (isHlsExtensionAvailable() && player is SimpleExoPlayer) { listener = SessionDataListener(player, collector).also { player.addAnalyticsListener(it) } } } override fun unbindPlayer(player: ExoPlayer, collector: MuxStateCollectorBase) { if (player is SimpleExoPlayer) { listener?.let { player.removeAnalyticsListener(it) } } } /** * Listens for timeline changes and updates HLS session data if we're on an HLS stream. * This class should only be instantiated if ExoPlayer's HLS extension is available at runtime * @see [.isHlsExtensionAvailable] */ private class SessionDataListener(player: ExoPlayer, val collector: MuxStateCollectorBase) : AnalyticsListener { private val player by weak(player) companion object { val RX_SESSION_TAG_DATA_ID by lazy { Pattern.compile("DATA-ID=\"(.*)\",") } val RX_SESSION_TAG_VALUES by lazy { Pattern.compile("VALUE=\"(.*)\"") } /** HLS session data tags with this Data ID will be sent to Mux Data */ const val HLS_SESSION_LITIX_PREFIX = "io.litix.data." const val LOG_TAG = "SessionDataListener" } override fun onTimelineChanged(eventTime: AnalyticsListener.EventTime, reason: Int) { player?.let { safePlayer -> val manifest = safePlayer.currentManifest if (manifest is HlsManifest) { collector.onMainPlaylistTags(parseHlsSessionData(manifest.masterPlaylist.tags)) } } } private fun parseHlsSessionData(hlsTags: List<String>): List<SessionTag> { val data: MutableList<SessionTag> = ArrayList() for (tag in filterHlsSessionTags(hlsTags)) { val st: SessionTag = parseHlsSessionTag(tag) if (st.key != null && st.key.contains(HLS_SESSION_LITIX_PREFIX)) { data.add(parseHlsSessionTag(tag)) } } return data } private fun filterHlsSessionTags(rawTags: List<String>) = rawTags.filter { it.substring(1).startsWith("EXT-X-SESSION-DATA") } private fun parseHlsSessionTag(line: String): SessionTag { val dataId: Matcher = RX_SESSION_TAG_DATA_ID.matcher(line) val value: Matcher = RX_SESSION_TAG_VALUES.matcher(line) var parsedDataId: String? = "" var parsedValue: String? = "" if (dataId.find()) { parsedDataId = dataId.group(1)?.replace(HLS_SESSION_LITIX_PREFIX, "") } else { MuxLogger.d(LOG_TAG, "Data-ID not found in session data: $line") } if (value.find()) { parsedValue = value.group(1) } else { MuxLogger.d(LOG_TAG, "Value not found in session data: $line") } return SessionTag(parsedDataId, parsedValue) } } } /** * Creates a listener that listens for timeline changes and updates HLS session data if we're on an * HLS stream. * This class should only be instantiated if ExoPlayer's HLS extension is available at runtime * @see [.isHlsExtensionAvailable] */ @Suppress("unused") // using the receiver to avoid polluting customers' namespace @JvmSynthetic fun MuxStateCollectorBase.createExoSessionDataBinding(): MuxPlayerAdapter.PlayerBinding<ExoPlayer> = SessionDataPlayerBinding()
5
Java
18
21
dd4f951dee3b63ea19899370e6cc7c835a5dd080
4,184
mux-stats-sdk-exoplayer
Apache License 2.0
src/test/kotlin/eZmaxApi/models/CustomEzsignformfielderrortestResponseTest.kt
eZmaxinc
271,950,932
false
{"Kotlin": 6909939}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package eZmaxApi.models import io.kotlintest.shouldBe import io.kotlintest.specs.ShouldSpec import eZmaxApi.models.CustomEzsignformfielderrortestResponse class CustomEzsignformfielderrortestResponseTest : ShouldSpec() { init { // uncomment below to create an instance of CustomEzsignformfielderrortestResponse //val modelInstance = CustomEzsignformfielderrortestResponse() // to test the property `sEzsignformfielderrortestName` - The name of the test should("test sEzsignformfielderrortestName") { // uncomment below to test the property //modelInstance.sEzsignformfielderrortestName shouldBe ("TODO") } // to test the property `sEzsignformfielderrortestDetail` - The detail why the test failed should("test sEzsignformfielderrortestDetail") { // uncomment below to test the property //modelInstance.sEzsignformfielderrortestDetail shouldBe ("TODO") } } }
0
Kotlin
0
0
961c97a9f13f3df7986ea7ba55052874183047ab
1,255
eZmax-SDK-kotlin
MIT License
Softver/api/src/main/kotlin/com/aimelodije/modeli/zahtjevi/MelodijaAzuriranjeZahtjev.kt
ttomasicc
605,710,239
false
null
package com.aimelodije.modeli.zahtjevi import jakarta.validation.constraints.NotBlank import jakarta.validation.constraints.Size data class MelodijaAzuriranjeZahtjev( val umjetnikId: Long = 0, val albumId: Long = 0, val melodijaId: Long = 0, @field:NotBlank(message = "Naziv ne može biti prazan") @field:Size(max = 100, message = "Maksimalna veličina naziva je 100 karaktera") val naziv: String = "" )
0
Kotlin
0
0
865dcdcdc3e171eb8935916f6a2612509cecf586
428
ai-melodije
MIT License
app/src/main/java/eu/zimbelstern/tournant/utils/Converter.kt
Zimbelstern
433,953,023
false
null
package eu.zimbelstern.tournant.utils import androidx.databinding.InverseMethod import eu.zimbelstern.tournant.toStringForCooks import java.text.NumberFormat @Suppress("unused") object Converter { @InverseMethod("hourToTime") @JvmStatic fun timeToHour(@Suppress("UNUSED_PARAMETER") oldValue: Int?, value: Int?): String { return value?.div(60)?.toString() ?: "" } @JvmStatic fun hourToTime(oldValue: Int?, value: String): Int? { val hour = value.toIntOrNull() return if (hour != null) hour * 60 + ((oldValue ?: 0) % 60) else oldValue?.mod(60) } @InverseMethod("minToTime") @JvmStatic fun timeToMin(@Suppress("UNUSED_PARAMETER") oldValue: Int?, value: Int?): String { return value?.mod(60)?.toString() ?: "" } @JvmStatic fun minToTime(oldValue: Int?, value: String): Int? { val min = value.toIntOrNull() return if (min != null) (oldValue ?: 0) / 60 * 60 + min else oldValue?.div(60)?.times(60) } @JvmStatic fun timeToString(value: Int?): String { if (value == null) return "" val hourString = if (value >= 60) timeToHour(0, value) + " h" else null val minString = if (value % 60 != 0) timeToMin(0, value) + " min" else null return listOfNotNull(hourString, minString).joinToString(" ") } @InverseMethod("stringToFloat") @JvmStatic fun floatToString(@Suppress("UNUSED_PARAMETER") oldValue: Float?, value: Float?): String { return value?.toStringForCooks(thousands = false) ?: "" } @JvmStatic fun stringToFloat(oldValue: Float?, value: String): Float? { return if (value.isEmpty()) null else try { NumberFormat.getInstance().parse(value)?.toFloat() } catch (_: Exception) { oldValue } } @InverseMethod("stringToHtml") @JvmStatic fun htmlToString(value: String?): String { return value?.replace("<br/>", "\n") ?: "" } @JvmStatic fun stringToHtml(value: String): String { return value.replace("\n", "<br/>") } }
1
null
4
33
7bc1bc9b9bcfa0adcc4f962a8b21d2afaf604be2
1,884
Tournant
Apache License 2.0
verik-compiler/src/main/kotlin/io/verik/compiler/evaluate/ClusterUnrollTransformerStage.kt
frwang96
269,980,078
false
null
/* * SPDX-License-Identifier: Apache-2.0 */ package io.verik.compiler.evaluate import io.verik.compiler.ast.common.Declaration import io.verik.compiler.ast.element.declaration.common.EDeclaration import io.verik.compiler.ast.element.declaration.common.EFile import io.verik.compiler.ast.element.declaration.common.EProperty import io.verik.compiler.ast.element.declaration.kt.EKtAbstractFunction import io.verik.compiler.ast.element.declaration.kt.EKtClass import io.verik.compiler.ast.element.declaration.kt.EKtValueParameter import io.verik.compiler.ast.element.expression.common.EBlockExpression import io.verik.compiler.ast.element.expression.common.ECallExpression import io.verik.compiler.ast.element.expression.common.EExpression import io.verik.compiler.ast.element.expression.common.EReferenceExpression import io.verik.compiler.ast.element.expression.kt.EFunctionLiteralExpression import io.verik.compiler.common.ExpressionCopier import io.verik.compiler.common.TreeVisitor import io.verik.compiler.constant.ConstantBuilder import io.verik.compiler.constant.ConstantNormalizer import io.verik.compiler.core.common.Core import io.verik.compiler.main.ProjectContext import io.verik.compiler.main.ProjectStage import io.verik.compiler.message.Messages /** * Stage that unrolls cluster properties and cluster value parameters. */ object ClusterUnrollTransformerStage : ProjectStage() { override fun process(projectContext: ProjectContext) { val clusterIndexerVisitor = ClusterIndexerVisitor() projectContext.project.accept(clusterIndexerVisitor) val clusterCallExpressionTransformerVisitor = ClusterCallExpressionTransformerVisitor( clusterIndexerVisitor.propertyClusterMap, clusterIndexerVisitor.valueParameterClusterMap ) projectContext.project.accept(clusterCallExpressionTransformerVisitor) clusterIndexerVisitor.propertyClusterMap.values.flatten().forEach { it.accept(clusterCallExpressionTransformerVisitor) } val clusterDeclarationTransformerVisitor = ClusterDeclarationTransformerVisitor( clusterIndexerVisitor.propertyClusterMap, clusterIndexerVisitor.valueParameterClusterMap ) projectContext.project.accept(clusterDeclarationTransformerVisitor) } private class ClusterIndexerVisitor : TreeVisitor() { val propertyClusterMap = HashMap<EProperty, List<EProperty>>() val valueParameterClusterMap = HashMap<EKtValueParameter, List<EKtValueParameter>>() override fun visitProperty(property: EProperty) { super.visitProperty(property) if (property.type.reference == Core.Vk.C_Cluster) { val initializer = property.initializer if (initializer is ECallExpression && initializer.reference == Core.Vk.F_cluster_Int_Function) { indexProperty(property, initializer) } else { Messages.EXPECTED_CLUSTER_EXPRESSION.on(property) } } } override fun visitKtAbstractFunction(abstractFunction: EKtAbstractFunction) { super.visitKtAbstractFunction(abstractFunction) abstractFunction.valueParameters.forEach { if (it.type.reference == Core.Vk.C_Cluster) { indexValueParameter(it) } } } private fun indexProperty(property: EProperty, expression: ECallExpression) { val functionLiteralExpression = expression.valueArguments[1] as EFunctionLiteralExpression if (functionLiteralExpression.body.statements.size != 1) { Messages.INVALID_CLUSTER_INITIALIZER.on(functionLiteralExpression) return } val size = expression.type.arguments[0].asCardinalValue(expression) val initializer = functionLiteralExpression.body.statements[0] val valueParameter = functionLiteralExpression.valueParameters[0] val copiedProperties = ArrayList<EProperty>() for (index in 0 until size) { val copiedInitializer = ExpressionCopier.deepCopy(initializer) val blockExpression = EBlockExpression.wrap(copiedInitializer) UnrollUtil.substituteValueParameter( blockExpression, valueParameter, ConstantBuilder.buildInt(valueParameter.location, index) ) val copiedProperty = EProperty( location = property.location, endLocation = property.endLocation, name = "${property.name}_$index", type = initializer.type.copy(), annotationEntries = property.annotationEntries, documentationLines = if (index == 0) property.documentationLines else null, initializer = blockExpression.statements[0], isMutable = false, isStatic = false ) copiedProperties.add(copiedProperty) } propertyClusterMap[property] = copiedProperties } private fun indexValueParameter(valueParameter: EKtValueParameter) { val size = valueParameter.type.arguments[0].asCardinalValue(valueParameter) val type = valueParameter.type.arguments[1] val valueParameters = ArrayList<EKtValueParameter>() for (index in 0 until size) { val copiedValueParameter = EKtValueParameter( location = valueParameter.location, name = "${valueParameter.name}_$index", type = type.copy(), annotationEntries = valueParameter.annotationEntries, expression = null, isPrimaryConstructorProperty = valueParameter.isPrimaryConstructorProperty, isMutable = valueParameter.isMutable ) valueParameters.add(copiedValueParameter) } valueParameterClusterMap[valueParameter] = valueParameters } } private class ClusterCallExpressionTransformerVisitor( private val propertyClusterMap: HashMap<EProperty, List<EProperty>>, private val valueParameterClusterMap: HashMap<EKtValueParameter, List<EKtValueParameter>> ) : TreeVisitor() { override fun visitProperty(property: EProperty) { if (property.type.reference != Core.Vk.C_Cluster) { super.visitProperty(property) } } override fun visitCallExpression(callExpression: ECallExpression) { super.visitCallExpression(callExpression) val reference = callExpression.reference val receiver = callExpression.receiver if (reference == Core.Vk.Cluster.F_get_Int && receiver is EReferenceExpression) { transformIndex(callExpression, receiver) } else if (reference is EKtAbstractFunction) { transformValueArguments(callExpression, reference) } } private fun transformIndex(callExpression: ECallExpression, receiver: EReferenceExpression) { val declarations = getClusterDeclarations(receiver.reference) ?: return val constantExpression = callExpression.valueArguments[0] val index = ConstantNormalizer.parseIntOrNull(constantExpression) if (index == null) { Messages.EXPRESSION_NOT_CONSTANT.on(constantExpression) } else if (index < 0 || index >= declarations.size) { Messages.CLUSTER_INDEX_INVALID.on(constantExpression, index) } else { val referenceExpression = EReferenceExpression.of(callExpression.location, declarations[index]) callExpression.replace(referenceExpression) } } private fun transformValueArguments(callExpression: ECallExpression, function: EKtAbstractFunction) { if (function.valueParameters.any { it.type.reference == Core.Vk.C_Cluster }) { val valueArguments = ArrayList<EExpression>() callExpression.valueArguments.zip(function.valueParameters).forEach { (valueArgument, valueParameter) -> if (valueParameter.type.reference == Core.Vk.C_Cluster) { val expressions = transformExpression(valueArgument) ?: return valueArguments.addAll(expressions) } else { valueArguments.add(valueArgument) } } valueArguments.forEach { it.parent = callExpression } callExpression.valueArguments = valueArguments } } private fun transformExpression(expression: EExpression): List<EExpression>? { return if (expression is EReferenceExpression) { val declarations = getClusterDeclarations(expression.reference) ?: return null declarations.map { EReferenceExpression.of(expression.location, it) } } else if (expression is ECallExpression && expression.reference == Core.Vk.Cluster.F_map_Function) { val expressions = transformExpression(expression.receiver!!) ?: return null val functionLiteralExpression = expression.valueArguments[0] as EFunctionLiteralExpression val valueParameter = functionLiteralExpression.valueParameters[0] if (functionLiteralExpression.body.statements.size != 1) return null expressions.map { val copiedExpression = ExpressionCopier.deepCopy(functionLiteralExpression.body.statements[0]) val blockExpression = EBlockExpression.wrap(copiedExpression) UnrollUtil.substituteValueParameter(blockExpression, valueParameter, it) blockExpression.statements[0] } } else null } private fun getClusterDeclarations(reference: Declaration): List<EDeclaration>? { return propertyClusterMap[reference] ?: valueParameterClusterMap[reference] } } private class ClusterDeclarationTransformerVisitor( private val propertyClusterMap: HashMap<EProperty, List<EProperty>>, private val valueParameterClusterMap: HashMap<EKtValueParameter, List<EKtValueParameter>> ) : TreeVisitor() { override fun visitFile(file: EFile) { super.visitFile(file) file.declarations = transformDeclarations(file, file.declarations) } override fun visitKtClass(cls: EKtClass) { super.visitKtClass(cls) cls.declarations = transformDeclarations(cls, cls.declarations) } override fun visitKtAbstractFunction(abstractFunction: EKtAbstractFunction) { super.visitKtAbstractFunction(abstractFunction) val transformedValueParameters = ArrayList<EKtValueParameter>() abstractFunction.valueParameters.forEach { valueParameter -> val valueParameters = valueParameterClusterMap[valueParameter] if (valueParameters != null) { valueParameters.forEach { it.parent = abstractFunction } transformedValueParameters.addAll(valueParameters) } else { transformedValueParameters.add(valueParameter) } } abstractFunction.valueParameters = transformedValueParameters } private fun transformDeclarations( parent: EDeclaration, declarations: List<EDeclaration>, ): ArrayList<EDeclaration> { val transformedDeclarations = ArrayList<EDeclaration>() declarations.forEach { declaration -> val properties = propertyClusterMap[declaration] if (properties != null) { properties.forEach { it.parent = parent } transformedDeclarations.addAll(properties) } else { transformedDeclarations.add(declaration) } } return transformedDeclarations } } }
0
Kotlin
1
33
ee22969235460fd144294bcbcbab0338c638eb92
12,404
verik
Apache License 2.0
app/src/main/java/io/github/lee0701/lboard/dictionary/FlatteningWritableTrieDictionary.kt
Lee0701
177,382,784
false
null
package io.github.lee0701.lboard.dictionary import java.io.DataOutputStream import java.io.File import java.io.FileOutputStream class FlatteningWritableTrieDictionary( val file: File ): EditableTrieDictionary(), WritableDictionary { private fun serialize(node: Node): List<Node> { return node.children.flatMap { serialize(it.value) } + node } override fun read() { if(!file.exists()) file.createNewFile() this.root = Node() val flatDictionary = FlatTrieDictionary(file.readBytes()) flatDictionary.searchPrefix("", Int.MAX_VALUE).forEach { insert(it) } } override fun write() { if(!file.exists()) file.createNewFile() val dos = DataOutputStream(FileOutputStream(file)) val addressMap: MutableMap<Node, Int> = mutableMapOf() var address: Int = 0 val list = serialize(root) list.forEach { node -> addressMap += node to address dos.writeByte(node.words.size) address += 1 node.words.forEach { word -> dos.writeByte(word.pos) dos.writeFloat(word.frequency) address += 5 } dos.writeByte(node.children.size) address += 1 node.children.forEach { entry -> dos.writeShort(entry.key.toInt()) dos.writeInt(addressMap[entry.value] ?: 0) address += 6 } } dos.writeInt(addressMap[list.last()] ?: 0) } }
5
Kotlin
1
1
2befd2f2b1941dd6e02336a468e4f824c6617974
1,538
LBoard
Apache License 2.0
lib/src/main/java/com/kotlin/inaction/reference/getting_started/03_coding_conventions/FunctionNames.kt
jhwsx
167,022,805
false
null
package com.kotlin.inaction.reference.getting_started.`03_coding_conventions` /** * @author wangzhichao * @date 2019/09/17 */ val USER_FIELD_NAME = "UserName" const val MAX_COUNT = 8 abstract class Foo { abstract fun foo() } class FooImpl : Foo() { override fun foo() { println("foo()") } } fun newInstance(): Foo { return FooImpl() } fun main(args: Array<String>) { newInstance() }
1
Kotlin
1
1
1e28292ee86cf8ce42b90c78b1c17cb143801a73
417
KotlinInAction
MIT License
plugin/src/main/kotlin/net/bladehunt/rpp/util/ArchiveUtil.kt
bladehuntmc
863,527,238
false
{"Kotlin": 19843, "Java": 9618}
package net.bladehunt.rpp.util import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.decodeFromStream import kotlinx.serialization.json.encodeToStream import net.bladehunt.rpp.Json import net.bladehunt.rpp.RppExtension import net.bladehunt.rpp.codegen.CodegenConfig import net.bladehunt.rpp.codegen.generateCode import org.gradle.api.Project import java.io.File import java.security.MessageDigest import java.util.regex.Pattern import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream private const val IGNORE_NAME = ".rppignore" private val FONT_MATCHER = Pattern.compile("assets/\\w+/font/\\w+\\.json") internal fun Project.buildResourcePack( extension: RppExtension = extensions.getByName("rpp") as RppExtension ) { val outputName = extension.outputName ?: "resource_pack_${project.version}" val sourceDirectory = File(extension.sourceDirectory) val buildDir = layout.buildDirectory.get().dir("rpp") buildDir.asFile.mkdirs() val outputDir = buildDir.dir("output").asFile generateOutput(sourceDirectory, outputDir, extension) val output = buildDir.file("$outputName.zip").asFile archive(outputDir, output) buildDir.file("$outputName.sha1").asFile.writeText(output.sha1()) val generated = buildDir.dir("generated/java").asFile val codegenConfig: CodegenConfig = sourceDirectory .resolve("codegen.json") .takeIf { it.exists() } ?.inputStream()?.use { Json.decodeFromStream(it) } ?: return generateCode(codegenConfig, sourceDirectory.resolve("assets"), generated) } fun generateOutput( source: File, output: File, extension: RppExtension ) { val minifyJson = extension.minifyJson if (!output.deleteRecursively()) throw IllegalStateException("Failed to clean output") if (!output.mkdir()) throw IllegalStateException("Failed to create output directory") // TODO: update output generation val prefix = source.path val ignoredFiles = arrayListOf<Pattern>() source.walkTopDown().forEach { file -> val cleaned = file.path.removePrefix(prefix).removePrefix("/") if (file.isDirectory) { val ignore = file.resolve(IGNORE_NAME) if (ignore.exists()) { ignore.readLines().forEach lines@{ line -> if (line.startsWith("#") || line.isEmpty()) return@lines val pattern = Globs.toUnixRegexPattern( if (cleaned.isEmpty()) line.removePrefix("/") else "$cleaned/${line.removePrefix("/")}" ) ignoredFiles.add(Pattern.compile(pattern)) } } return@forEach } if (file.name == IGNORE_NAME || file.name == "codegen.json" || ignoredFiles.any { it.matcher(cleaned).matches() }) return@forEach val resolved = output.resolve(cleaned) if (minifyJson && file.extension == "json") { resolved.parentFile.mkdirs() resolved.createNewFile() val obj = file.inputStream().use { stream -> Json.decodeFromStream<JsonObject>(stream) } resolved.outputStream().use { out -> Json.encodeToStream(obj, out) } } else file.copyTo( resolved, true ) } } fun archive(source: File, output: File) { if (!source.exists() || !source.isDirectory) { throw IllegalStateException("Source must exist and be a directory.") } if (!source.resolve("pack.mcmeta").exists()) throw IllegalStateException("Resource pack source must contain pack.mcmeta") ZipOutputStream(output.outputStream().buffered()).use { zos -> source.walkTopDown().forEach { file -> val zipFileName = file.absolutePath.removePrefix(source.absolutePath).removePrefix("/") val entry = ZipEntry( "$zipFileName${(if (file.isDirectory) "/" else "" )}") zos.putNextEntry(entry) if (file.isFile) { file.inputStream().use { fis -> fis.copyTo(zos) } } } } } fun File.sha1(): String = MessageDigest.getInstance("SHA-1").let { sha1 -> inputStream().use { input -> val buffer = ByteArray(8192) var read: Int while (input.read(buffer).also { read = it } != -1) { sha1.update(buffer, 0, read) } } sha1.digest().joinToString("") { "%02x".format(it) } }
0
Kotlin
0
1
d7111ea407ab4de0e6eaa99f9359c731891a4de7
4,483
rpp
MIT License
modules/dsl/sources/GraphQLMarker.kt
fluidsonic
226,815,725
false
null
package io.fluidsonic.graphql @DslMarker @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY, AnnotationTarget.TYPEALIAS) public annotation class GraphQLMarker
1
Kotlin
2
4
3cd09bdd9f54cb6cddec2d6e020b55a022e66f05
234
fluid-graphql
Apache License 2.0
core/src/commonMain/kotlin/pro/respawn/flowmvi/MVIExtDeprecated.kt
respawn-app
477,143,989
false
null
@file:Suppress("DEPRECATION") package pro.respawn.flowmvi import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.supervisorScope import pro.respawn.flowmvi.api.DelicateStoreApi import pro.respawn.flowmvi.api.FlowMVIDSL import pro.respawn.flowmvi.api.Store import pro.respawn.flowmvi.dsl.store import pro.respawn.flowmvi.dsl.subscribe import pro.respawn.flowmvi.dsl.updateState import pro.respawn.flowmvi.dsl.withState import pro.respawn.flowmvi.plugins.recover import pro.respawn.flowmvi.plugins.reduce import pro.respawn.flowmvi.util.withType import kotlin.contracts.InvocationKind import kotlin.contracts.contract import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlin.jvm.JvmName /** * Subscribe to the store using provided scope. * This function is __not__ lifecycle-aware and just uses provided scope for flow collection. */ public fun <S : MVIState, I : MVIIntent, A : MVIAction> MVIView<S, I, A>.subscribe( scope: CoroutineScope, ): Job = with(scope) { subscribe(provider, ::consume, ::render) } /** * Subscribe to the store using provided scope. * This function is __not__ lifecycle-aware and just uses provided scope for flow collection. */ @Deprecated( "Use the new subscribe dsl", ReplaceWith( "this.subscribe(scope, ::consume, ::render)", "pro.respawn.flowmvi.dsl.subscribe" ) ) public fun <S : MVIState, I : MVIIntent, A : MVIAction> MVISubscriber<S, A>.subscribe( provider: MVIProvider<S, I, A>, scope: CoroutineScope ): Job = provider.subscribe(scope, ::consume, ::render) /** * Subscribe to the store using provided scope. * This function is __not__ lifecycle-aware and just uses provided scope for flow collection. */ @FlowMVIDSL @Deprecated( "Use the new subscribe dsl", ReplaceWith( "subscribe(scope, consume, render)", "pro.respawn.flowmvi.dsl.subscribe" ) ) public inline fun <S : MVIState, I : MVIIntent, A : MVIAction> MVIProvider<S, I, A>.subscribe( scope: CoroutineScope, crossinline consume: (action: A) -> Unit, crossinline render: (state: S) -> Unit, ): Job = scope.launch { launch { actions.collect { consume(it) } } launch { states.collect { render(it) } } } /** * Run [block] if current [MVIStore.state] is of type [T], otherwise do nothing. * * **This function will suspend until all previous [MVIStore.withState] invocations are finished.** * @see MVIStore.withState */ @OverloadResolutionByLambdaReturnType @FlowMVIDSL @Deprecated( "Use StateReceiver.withState", ReplaceWith( "this.withState(block)", "pro.respawn.flowmvi.dsl.withState" ) ) public suspend inline fun <reified T : S, S : MVIState> MVIStore<S, *, *>.withState( @BuilderInference crossinline block: suspend T.() -> Unit ) { contract { callsInPlace(block, InvocationKind.AT_MOST_ONCE) } withState { (this as? T)?.let { it.block() } } } /** * Run [block] if current [MVIStore.state] is of type [T], otherwise do nothing. * * **This function will suspend until all previous [MVIStore.withState] invocations are finished.** * @see MVIStore.withState */ @OverloadResolutionByLambdaReturnType @FlowMVIDSL @Deprecated( "Use StateReceiver.withState", ReplaceWith( "this.withState(block)", "pro.respawn.flowmvi.dsl.withState" ) ) public suspend inline fun <reified T : S, S : MVIState> ReducerScope<S, *, *>.withState( @BuilderInference crossinline block: suspend T.() -> Unit ) { contract { callsInPlace(block, InvocationKind.AT_MOST_ONCE) } withState { (this as? T)?.let { it.block() } } } /** * Obtain the current [MVIStore.state] and update it with * the result of [transform] if it is of type [T], otherwise do nothing. * * **This function will suspend until all previous [MVIStore.withState] invocations are finished.** * @see MVIStore.updateState * @see [withState] */ @JvmName("updateStateTyped") @FlowMVIDSL @Deprecated( "Use StateReceiver.updateState", ReplaceWith( "this.updateState(block)", "pro.respawn.flowmvi.dsl.updateState" ) ) public suspend inline fun <reified T : S, S : MVIState> ReducerScope<S, *, *>.updateState( @BuilderInference crossinline transform: suspend T.() -> S ) { contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) } return updateState { withType<T, _> { transform() } } } /** * Obtain the current [MVIStore.state] and update it with * the result of [transform] if it is of type [T], otherwise do nothing. * * **This function will suspend until all previous [MVIStore.updateState] invocations are finished.** * @see MVIStore.updateState * @see [withState] */ @JvmName("updateStateTyped") @FlowMVIDSL @Deprecated( "Use StateReceiver.updateState", ReplaceWith( "this.updateState", "pro.respawn.flowmvi.dsl.updateState" ) ) public suspend inline fun <reified T : S, S : MVIState> MVIStore<S, *, *>.updateState( @BuilderInference crossinline transform: suspend T.() -> S ) { contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) } return updateState { withType<T, _> { transform() } } } /** * A property that returns a [Reduce] lambda using the given [Reducer]. * May be needed to deal with contexts of invocation. */ @Deprecated( "Not needed anymore, use store builders", ReplaceWith("{ with(this as CoroutineScope) { reduce(it) } }", "kotlinx.coroutines.CoroutineScope") ) public inline val <S : MVIState, I : MVIIntent> Reducer<S, I>.reduce: Reduce<S, I, *> get() = { with(this as CoroutineScope) { reduce(it) } } /** * A property that returns a [Recover] lambda using the given [Reducer]. * May be needed to deal with contexts of invocation. */ @Deprecated("Not needed anymore, use store builders", ReplaceWith("{ recover(it) }")) public inline val <S : MVIState> Reducer<S, *>.recover: Recover<S> get() = { recover(it) } /** * A builder function of [MVIStore] */ @OptIn(DelicateStoreApi::class) @Suppress("FunctionName", "TrimMultilineRawString") @Deprecated( "Use store builders", ReplaceWith( """ store(initial) { actionShareBehavior = behavior reduce(reduce) recover { useState { recover(it) } null } } """ ) ) public fun <S : MVIState, I : MVIIntent, A : MVIAction> MVIStore( initial: S, /** * A behavior to be applied when sharing actions * @see ActionShareBehavior */ behavior: ActionShareBehavior = pro.respawn.flowmvi.api.ActionShareBehavior.Distribute(), /** * State to emit when [reduce] throws. * * **Default implementation rethrows the exception** * **The body of this block may be evaluated multiple times in case of concurrent state updates** */ @BuilderInference recover: Recover<S> = { throw it }, /** * Reduce view's intent to a new ui state. * Use [MVIStore.send] for sending side-effects for the view to handle. * Coroutines launched inside [reduce] can fail independently of each other. */ @BuilderInference reduce: Reduce<S, I, A>, ): MutableStore<S, I, A> = store(initial) { actionShareBehavior = behavior reduce(reduce = reduce) recover { useState { recover(it) } null } } as MutableStore<S, I, A> /** * A builder function of [MVIStore] that creates the store lazily. This function does **not** launch the store. * Call [MVIStore.start] yourself as appropriate. * @see MVIStore */ @Suppress("TrimMultilineRawString") @Deprecated( "Use store builders", ReplaceWith( """ store(initial) { reduce(reduce) recover { useState { recover(it) } null } actionShareBehavior = behavior } """ ) ) public fun <S : MVIState, I : MVIIntent, A : MVIAction> lazyStore( initial: S, behavior: ActionShareBehavior = pro.respawn.flowmvi.api.ActionShareBehavior.Distribute(), mode: LazyThreadSafetyMode = LazyThreadSafetyMode.SYNCHRONIZED, @BuilderInference recover: Recover<S> = { throw it }, @BuilderInference reduce: Reduce<S, I, A>, ): Lazy<Store<S, I, A>> = lazy(mode) { MVIStore(initial, behavior, recover, reduce) } /** * A builder function of [MVIStore] that creates, and then launches the store lazily on first access. * @see MVIStore */ @Suppress("TrimMultilineRawString") @Deprecated( "Use store builders", ReplaceWith( """ store(initial) { actionShareBehavior = behavior reduce(reduce) recover { useState { recover(it) } null } } """ ) ) public fun <S : MVIState, I : MVIIntent, A : MVIAction> launchedStore( scope: CoroutineScope, initial: S, behavior: ActionShareBehavior = pro.respawn.flowmvi.api.ActionShareBehavior.Distribute(), mode: LazyThreadSafetyMode = LazyThreadSafetyMode.SYNCHRONIZED, @BuilderInference recover: Recover<S> = { throw it }, @BuilderInference reduce: Reduce<S, I, A> ): Lazy<Store<S, I, A>> = lazy(mode) { MVIStore(initial, behavior, recover, reduce).apply { start(scope) } } /** * Launch a new coroutine using given scope, * and use either provided [recover] block or the [MVIStore]'s recover block. * Exceptions thrown in the [block] or in the nested coroutines will be handled by [recover]. * This function does not update or obtain the state, for that, use [withState] or [updateState] inside [block]. */ @Deprecated("launchRecovering is now an extension on PipelineContext") @FlowMVIDSL public fun CoroutineScope.launchRecovering( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, recover: (Exception) -> Unit = { throw it }, block: suspend CoroutineScope.() -> Unit, ): Job = launch(context, start) { try { supervisorScope(block) } catch (expected: CancellationException) { throw expected } catch (expected: Exception) { recover(expected) } }
0
null
2
75
e6ae55520957b8516a166946a05ef6bc461145bd
10,265
FlowMVI
Apache License 2.0
app/src/main/java/com/moemaair/lictionary/feature_dictionary/presentation/WordInfoItem.kt
moemaair
588,958,264
false
null
package com.moemaair.lictionary.feature_dictionary.presentation import android.annotation.SuppressLint import android.media.AudioManager import android.media.MediaPlayer import android.media.browse.MediaBrowser.MediaItem import androidx.compose.foundation.layout.* import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Search import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.moemaair.lictionary.feature_dictionary.domain.model.WordInfo import kotlinx.coroutines.runBlocking import android.net.Uri import android.widget.ToggleButton import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.runtime.* import com.moemaair.lictionary.R @SuppressLint("RestrictedApi") @Composable fun WordInfoItem( wordInfo: WordInfo, audioIcon: ImageVector, ) { var context = LocalContext.current.applicationContext var mediaPlayer = MediaPlayer() var audioUrl: String? by remember { mutableStateOf("") } val audio = wordInfo.phonetics.forEach{ it -> if (!(it.audio == "")){ audioUrl = it.audio } } var phonetic: String? by remember { mutableStateOf("") } val textPhonetic = wordInfo.phonetics.forEach{it -> phonetic = it.text} Column(modifier = Modifier) { Row(modifier = Modifier.fillMaxSize().padding(top = 20.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start) { //word Text( text = wordInfo.word.toString(), style = MaterialTheme.typography.h2, modifier = Modifier ) //audio icon IconButton(onClick = { mediaPlayer.reset(); mediaPlayer.setDataSource(audioUrl.toString()) mediaPlayer.prepare() mediaPlayer.start() } ) { if((audioUrl?.isNotEmpty() == true)){ Icon(imageVector = audioIcon, contentDescription ="" ) } } } Text(text = phonetic.toString(), fontWeight = FontWeight.Normal) Spacer(modifier = Modifier.height(16.dp)) if(wordInfo.word.length <= 0){ Image(painter = painterResource(id = R.drawable.man), contentDescription = "") } wordInfo.meanings.forEach { meaning -> Text(text = meaning.partOfSpeech, fontWeight = FontWeight.Bold) meaning.definitions.forEachIndexed { i, definition -> Text(text = "${i + 1}. ${definition.definition}") Spacer(modifier = Modifier.height(8.dp)) definition.example?.let { example -> Text(text = "Example: $example", fontWeight = FontWeight.Light, fontStyle = FontStyle.Italic) } definition Spacer(modifier = Modifier.height(8.dp)) } Spacer(modifier = Modifier.height(16.dp)) } } }
0
Kotlin
3
6
098d2a8e0d2dd41248be2134d69e366262a6ebbe
3,680
Lictionary
MIT License
app/src/main/java/nerd/tuxmobil/fahrplan/congress/alarms/AlarmServices.kt
grote
114,628,676
true
{"Gradle": 6, "Markdown": 6, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 2, "YAML": 1, "Kotlin": 75, "XML": 125, "Java": 73, "INI": 1, "Proguard": 2, "Gradle Kotlin DSL": 1, "SVG": 9}
@file:JvmName("AlarmServices") package nerd.tuxmobil.fahrplan.congress.alarms import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import nerd.tuxmobil.fahrplan.congress.extensions.getAlarmManager import nerd.tuxmobil.fahrplan.congress.models.SchedulableAlarm @JvmOverloads fun scheduleEventAlarm(context: Context, alarm: SchedulableAlarm, discardExisting: Boolean = false) { val intent = AlarmReceiver.AlarmIntentBuilder() .setContext(context) .setLectureId(alarm.eventId) .setDay(alarm.day) .setTitle(alarm.eventTitle) .setStartTime(alarm.startTime) .setIsAddAlarm() .build() val requestCode = Integer.parseInt(alarm.eventId) val pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0) val alarmManager = context.getAlarmManager() if (discardExisting) { alarmManager.cancel(pendingIntent) } alarmManager.set(AlarmManager.RTC_WAKEUP, alarm.startTime, pendingIntent) } fun discardEventAlarm(context: Context, alarm: SchedulableAlarm) { val intent = AlarmReceiver.AlarmIntentBuilder() .setContext(context) .setLectureId(alarm.eventId) .setDay(alarm.day) .setTitle(alarm.eventTitle) .setStartTime(alarm.startTime) .setIsDeleteAlarm() .build() val requestCode = Integer.parseInt(alarm.eventId) discardAlarm(context, requestCode, intent) } fun discardAutoUpdateAlarm(context: Context) { val intent = Intent(context, AlarmReceiver::class.java) intent.action = AlarmReceiver.ALARM_UPDATE discardAlarm(context, 0, intent) } private fun discardAlarm(context: Context, requestCode: Int, intent: Intent) { val pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0) context.getAlarmManager().cancel(pendingIntent) }
0
Java
1
3
761d339bf804698760db17ba00990e164f90cff2
1,963
EventFahrplan
Apache License 2.0
src/main/kotlin/command/method/SendCommand.kt
LittleMengBot
378,202,426
false
null
package command.method import ConfigLoader.configCache import LANG import com.github.kotlintelegrambot.Bot import com.github.kotlintelegrambot.entities.ChatId import com.github.kotlintelegrambot.entities.Update import dsl.isChatMember import dsl.replyToText fun sendCommand(bot: Bot, update: Update) { if (update.message!!.chat.type == "private") { val operator = update.message!!.from!! val messageText = update.message!!.text!!.replace("/send ", "") if (operator.isChatMember(bot)) { bot.sendMessage(chatId = ChatId.fromId(configCache!!.group_id), text = messageText).fold({ update.message!!.replyToText(bot, update, LANG["send_success"]!!) }, { update.message!!.replyToText(bot, update, LANG["send_failed"]!!) }) } } }
0
Kotlin
0
3
d458555a45c16edfbc5250344dba8f0858a0dc8c
831
MengProject
Apache License 2.0
reporter/src/main/kotlin/LicenseTextProvider.kt
oss-review-toolkit
107,540,288
false
{"Kotlin": 5110480, "JavaScript": 333852, "Shell": 127273, "HTML": 98970, "Python": 51191, "Haskell": 30438, "FreeMarker": 27693, "CSS": 27239, "Dockerfile": 19565, "Swift": 12129, "Ruby": 10007, "Roff": 7688, "Vim Snippet": 6802, "Scala": 6656, "Starlark": 3270, "Go": 1909, "C++": 882, "Java": 559, "Rust": 280, "Emacs Lisp": 191, "C": 162}
/* * Copyright (C) 2017 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>) * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.ossreviewtoolkit.reporter /** * A provider for license texts. */ interface LicenseTextProvider { /** * Return the license text for the license identified by [licenseId] or null if the license text is not available. */ fun getLicenseText(licenseId: String): String? = getLicenseTextReader(licenseId)?.invoke()?.takeUnless { it.isBlank() } /** * Return a lambda that can read the license text for the license identified by [licenseId] or null if no license * text is available. This is useful if the license text shall not immediately be read from disk. */ fun getLicenseTextReader(licenseId: String): (() -> String)? /** * Return true if a license text for the license identified by [licenseId] is generally available. Note that this * does not necessarily mean that the text is meaningful (i.e. non-blank). */ fun hasLicenseText(licenseId: String): Boolean = getLicenseTextReader(licenseId) != null }
304
Kotlin
309
1,590
ed4bccf37bab0620cc47dbfb6bfea8542164725a
1,741
ort
Apache License 2.0
src/main/kotlin/no/nav/eessi/pensjon/klienter/norg2/Norg2Klient.kt
navikt
178,813,650
false
null
package no.nav.eessi.pensjon.klienter.norg2 import no.nav.eessi.pensjon.metrics.MetricsHelper import no.nav.eessi.pensjon.utils.mapJsonToAny import no.nav.eessi.pensjon.utils.toJson import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.http.MediaType import org.springframework.stereotype.Component import org.springframework.web.client.HttpStatusCodeException import org.springframework.web.client.RestTemplate import javax.annotation.PostConstruct @Component class Norg2Klient(private val proxyOAuthRestTemplate: RestTemplate, @Autowired(required = false) private val metricsHelper: MetricsHelper = MetricsHelper.ForTest()) { constructor(): this(RestTemplate()) private val logger = LoggerFactory.getLogger(Norg2Klient::class.java) private lateinit var hentArbeidsfordeling: MetricsHelper.Metric @PostConstruct fun initMetrics() { hentArbeidsfordeling = metricsHelper.init("hentArbeidsfordeling") } fun hentArbeidsfordelingEnheter(request: Norg2ArbeidsfordelingRequest) : List<Norg2ArbeidsfordelingItem> { return hentArbeidsfordeling.measure { try { val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON val httpEntity = HttpEntity(request.toJson(), headers) logger.info("Kaller NORG med : ${request.toJson()}") val responseEntity = proxyOAuthRestTemplate.exchange( "/api/v1/arbeidsfordeling", HttpMethod.POST, httpEntity, String::class.java) val fordelingEnheter = mapJsonToAny<List<Norg2ArbeidsfordelingItem>>(responseEntity.body!!) logger.debug("fordelsingsEnheter: $fordelingEnheter") fordelingEnheter } catch(ex: HttpStatusCodeException) { logger.error("En feil oppstod under henting av arbeidsfordeling ex: $ex body: ${ex.responseBodyAsString}") throw RuntimeException("En feil oppstod under henting av arbeidsfordeling ex: ${ex.message} body: ${ex.responseBodyAsString}") } catch(ex: Exception) { logger.error("En feil oppstod under henting av arbeidsfordeling ex: $ex") throw RuntimeException("En feil oppstod under henting av arbeidsfordeling ex: ${ex.message}") } } } }
2
null
3
6
ecffc4ad04aa9da50a0a7de401e5b9eb5ea34f95
2,624
eessi-pensjon-journalforing
MIT License
mobile/src/main/java/com/siliconlabs/bledemo/features/configure/advertiser/enums/AdvertisingMode.kt
SiliconLabs
85,345,875
false
null
package com.siliconlabs.bledemo.Advertiser.Enums enum class AdvertisingMode { CONNECTABLE_SCANNABLE, CONNECTABLE_NON_SCANNABLE, NON_CONNECTABLE_SCANNABLE, NON_CONNECTABLE_NON_SCANNABLE; fun isConnectable(): Boolean { return this == CONNECTABLE_SCANNABLE || this == CONNECTABLE_NON_SCANNABLE } fun isScannable(): Boolean { return this == CONNECTABLE_SCANNABLE || this == NON_CONNECTABLE_SCANNABLE } }
20
Kotlin
70
96
501d1a7554593db61325f5ac3aa0865eb616d00b
450
EFRConnect-android
Apache License 2.0
app/src/main/kotlin/net/primal/android/core/compose/feed/note/NoteContent.kt
PrimalHQ
639,579,258
false
{"Kotlin": 2548226}
package net.primal.android.core.compose.feed.note import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Column import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.sp import net.primal.android.R import net.primal.android.core.compose.PrimalClickableText import net.primal.android.core.compose.attachment.model.isMediaAttachment import net.primal.android.core.compose.feed.model.NoteContentUi import net.primal.android.core.compose.feed.model.NoteNostrUriUi import net.primal.android.core.utils.HashtagMatcher import net.primal.android.feed.db.ReferencedPost import net.primal.android.feed.db.ReferencedUser import net.primal.android.theme.AppTheme import net.primal.android.theme.PrimalTheme import net.primal.android.theme.domain.PrimalTheme private const val PROFILE_ID_ANNOTATION_TAG = "profileId" private const val URL_ANNOTATION_TAG = "url" private const val NOTE_ANNOTATION_TAG = "note" private const val HASHTAG_ANNOTATION_TAG = "hashtag" private fun List<NoteNostrUriUi>.filterMentionedPosts() = filter { it.referencedPost != null } private fun List<NoteNostrUriUi>.filterMentionedUsers() = filter { it.referencedUser != null } private fun String.removeUrls(urls: List<String>): String { var newContent = this urls.forEach { newContent = newContent.replace(it, "") } return newContent } private fun String.replaceNostrProfileUrisWithHandles(resources: List<NoteNostrUriUi>): String { var newContent = this resources.forEach { checkNotNull(it.referencedUser) newContent = newContent.replace( oldValue = it.uri, newValue = it.referencedUser.displayUsername, ignoreCase = true, ) } return newContent } private val noteLinkLeftovers = listOf( "https://primal.net/e/ " to "", "https://www.primal.net/e/ " to "", "http://primal.net/e/ " to "", "http://www.primal.net/e/ " to "", "https://primal.net/e/\n" to "", "https://www.primal.net/e/\n" to "", "http://primal.net/e/\n" to "", "http://www.primal.net/e/\n" to "", ) private val profileLinkLeftovers = listOf( "https://primal.net/p/@" to "@", "https://www.primal.net/p/@" to "@", "http://primal.net/p/@" to "@", "http://www.primal.net/p/@" to "@", ) private fun String.clearParsedPrimalLinks(): String { var newContent = this (noteLinkLeftovers + profileLinkLeftovers).forEach { newContent = newContent.replace( oldValue = it.first, newValue = it.second, ignoreCase = false, ) } noteLinkLeftovers.map { it.first.trim() }.toSet().forEach { if (newContent.endsWith(it)) { newContent = newContent.replace( oldValue = it, newValue = "", ) } } return newContent } private const val ELLIPSIZE_THRESHOLD = 500 private fun String.ellipsize(expanded: Boolean, ellipsizeText: String): String { val shouldEllipsize = length > ELLIPSIZE_THRESHOLD return if (expanded || !shouldEllipsize) { this } else { substring(0, ELLIPSIZE_THRESHOLD).plus(" $ellipsizeText") } } @OptIn(ExperimentalFoundationApi::class) @Composable fun NoteContent( modifier: Modifier = Modifier, data: NoteContentUi, expanded: Boolean, onProfileClick: (String) -> Unit, onPostClick: (String) -> Unit, onClick: (Offset) -> Unit, onUrlClick: (String) -> Unit, onHashtagClick: (String) -> Unit, onMediaClick: (String, String) -> Unit, highlightColor: Color = AppTheme.colorScheme.secondary, contentColor: Color = AppTheme.colorScheme.onSurface, referencedNoteContainerColor: Color = AppTheme.extraColorScheme.surfaceVariantAlt1, ) { val seeMoreText = stringResource(id = R.string.feed_see_more) val contentText = remember { renderContentAsAnnotatedString( data = data, expanded = expanded, seeMoreText = seeMoreText, highlightColor = highlightColor, ) } Column( modifier = modifier, ) { if (contentText.isNotEmpty()) { PrimalClickableText( style = AppTheme.typography.bodyMedium.copy( color = contentColor, lineHeight = 20.sp, ), text = contentText, onClick = { position, offset -> contentText.getStringAnnotations( start = position, end = position, ).firstOrNull()?.let { annotation -> when (annotation.tag) { PROFILE_ID_ANNOTATION_TAG -> onProfileClick(annotation.item) URL_ANNOTATION_TAG -> onUrlClick(annotation.item) NOTE_ANNOTATION_TAG -> onPostClick(annotation.item) HASHTAG_ANNOTATION_TAG -> onHashtagClick(annotation.item) } } ?: onClick(offset) }, ) } if (data.attachments.isNotEmpty()) { NoteAttachments( noteId = data.noteId, attachments = data.attachments, onUrlClick = onUrlClick, onMediaClick = onMediaClick, ) } val referencedPostResources = data.nostrUris.filterMentionedPosts() if (referencedPostResources.isNotEmpty()) { ReferencedNotesColumn( postResources = referencedPostResources, expanded = expanded, containerColor = referencedNoteContainerColor, onPostClick = onPostClick, onMediaClick = onMediaClick, ) } } } fun renderContentAsAnnotatedString( data: NoteContentUi, expanded: Boolean, seeMoreText: String, highlightColor: Color, shouldKeepNostrNoteUris: Boolean = false, ): AnnotatedString { val mediaAttachments = data.attachments.filter { it.isMediaAttachment() } val linkAttachments = data.attachments.filterNot { it.isMediaAttachment() } val mentionedPosts = data.nostrUris.filterMentionedPosts() val mentionedUsers = data.nostrUris.filterMentionedUsers() val shouldDeleteLinks = mediaAttachments.isEmpty() && linkAttachments.size == 1 && linkAttachments.first().let { singleLink -> data.content.trim().endsWith(singleLink.url) && (!singleLink.title.isNullOrBlank() || !singleLink.description.isNullOrBlank()) } val refinedContent = data.content .removeUrls(urls = mediaAttachments.map { it.url }) .removeUrls(urls = if (!shouldKeepNostrNoteUris) mentionedPosts.map { it.uri } else emptyList()) .removeUrls(urls = if (shouldDeleteLinks) linkAttachments.map { it.url } else emptyList()) .ellipsize(expanded = expanded, ellipsizeText = seeMoreText) .replaceNostrProfileUrisWithHandles(resources = mentionedUsers) .clearParsedPrimalLinks() .trim() return buildAnnotatedString { append(refinedContent) if (refinedContent.endsWith(seeMoreText)) { addStyle( style = SpanStyle(color = highlightColor), start = refinedContent.length - seeMoreText.length, end = refinedContent.length, ) } data.attachments.filterNot { it.isMediaAttachment() }.map { it.url }.forEach { val startIndex = refinedContent.indexOf(it) if (startIndex >= 0) { val endIndex = startIndex + it.length addStyle( style = SpanStyle(color = highlightColor), start = startIndex, end = endIndex, ) addStringAnnotation( tag = URL_ANNOTATION_TAG, annotation = it, start = startIndex, end = endIndex, ) } } mentionedUsers.forEach { checkNotNull(it.referencedUser) val displayHandle = it.referencedUser.displayUsername val startIndex = refinedContent.indexOf(displayHandle) if (startIndex >= 0) { val endIndex = startIndex + displayHandle.length addStyle( style = SpanStyle(color = highlightColor), start = startIndex, end = endIndex, ) addStringAnnotation( tag = PROFILE_ID_ANNOTATION_TAG, annotation = it.referencedUser.userId, start = startIndex, end = endIndex, ) } } HashtagMatcher(content = refinedContent, hashtags = data.hashtags).matches() .forEach { addStyle( style = SpanStyle(color = highlightColor), start = it.startIndex, end = it.endIndex, ) addStringAnnotation( tag = HASHTAG_ANNOTATION_TAG, annotation = it.value, start = it.startIndex, end = it.endIndex, ) } } } @Preview @Composable fun PreviewPostContent() { PrimalTheme(primalTheme = PrimalTheme.Sunset) { Surface { NoteContent( data = NoteContentUi( noteId = "", content = """ Unfortunately the days of using pseudonyms in metaspace are numbered. #nostr nostr:referencedUser """.trimIndent(), attachments = emptyList(), nostrUris = listOf( NoteNostrUriUi( uri = "nostr:referencedUser", referencedPost = null, referencedUser = ReferencedUser( userId = "nostr:referencedUser", handle = "alex", ), ), ), hashtags = listOf("#nostr"), ), expanded = false, onProfileClick = {}, onPostClick = {}, onClick = {}, onUrlClick = {}, onHashtagClick = {}, onMediaClick = { _, _ -> }, ) } } } @Preview @Composable fun PreviewPostContentWithReferencedPost() { PrimalTheme(primalTheme = PrimalTheme.Sunset) { Surface { NoteContent( data = NoteContentUi( noteId = "", content = """ Unfortunately the days of using pseudonyms in metaspace are numbered. #nostr nostr:referencedPost Or maybe not. nostr:referenced2Post """.trimIndent(), attachments = emptyList(), nostrUris = listOf( NoteNostrUriUi( uri = "nostr:referencedPost", referencedPost = ReferencedPost( postId = "postId", createdAt = 0, content = "This is referenced post.", authorId = "authorId", authorName = "primal", authorAvatarCdnImage = null, authorInternetIdentifier = "<EMAIL>", authorLightningAddress = "<EMAIL>", attachments = emptyList(), nostrUris = emptyList(), ), referencedUser = null, ), NoteNostrUriUi( uri = "nostr:referenced2Post", referencedPost = ReferencedPost( postId = "postId", createdAt = 0, content = "This is referenced post #2.", authorId = "authorId", authorName = "primal", authorAvatarCdnImage = null, authorInternetIdentifier = "<EMAIL>", authorLightningAddress = "<EMAIL>", attachments = emptyList(), nostrUris = emptyList(), ), referencedUser = null, ), ), hashtags = listOf("#nostr"), ), expanded = false, onProfileClick = {}, onPostClick = {}, onClick = {}, onUrlClick = {}, onHashtagClick = {}, onMediaClick = { _, _ -> }, ) } } }
67
Kotlin
12
98
438072af7f67762c71c5dceffa0c83dedd8e2e85
13,968
primal-android-app
MIT License
app/src/main/java/com/dreamsoftware/tvnexa/domain/usecase/impl/HasMultiplesProfilesUseCase.kt
sergio11
328,373,511
false
{"Kotlin": 586066}
package com.dreamsoftware.tvnexa.domain.usecase.impl import com.dreamsoftware.tvnexa.domain.repository.IUserRepository import com.dreamsoftware.tvnexa.domain.usecase.core.BaseUseCase class HasMultiplesProfilesUseCase( private val userRepository: IUserRepository ): BaseUseCase<Boolean>() { override suspend fun onExecuted(): Boolean = userRepository.getProfiles().size > 1 }
0
Kotlin
0
1
30fb84765276b1afcadc27b0ce8ffc15155decc4
392
tvnexa_androidtv
Apache License 2.0
featureweather/src/main/java/weather/feature/weather/WeatherPresenter.kt
weupz
154,643,741
false
null
package weather.feature.weather import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.functions.BiFunction import io.reactivex.functions.Function import io.reactivex.subjects.PublishSubject import org.threeten.bp.Duration import org.threeten.bp.ZonedDateTime import weather.mvi.DefaultPresenter import weather.scheduler.Schedulers import java.util.concurrent.TimeUnit import javax.inject.Inject internal class WeatherPresenter @Inject constructor( private val repository: Repository, private val schedulers: Schedulers ) : DefaultPresenter<State, Event>(), WeatherViewModel { private val subject = PublishSubject.create<Any>() private val retry: Observable<Any> inline get() = subject.filter { it == RETRY } private val toggleUnit: Observable<Any> inline get() = subject.filter { it == TOGGLE_UNIT } override fun retry() { subject.onNext(RETRY) } override fun toggleUnitType() { subject.onNext(TOGGLE_UNIT) } override val states: Flowable<State> = super.states.distinctUntilChanged().observeOn(schedulers.main) private val repeater: Function<Event, Flowable<Event>> = Function { event -> if (event is Event.Success) { val now = ZonedDateTime.now() val load = if (now.isBefore(event.data.nextLoad)) { val delay = Duration.between(now, event.data.nextLoad) Single.timer(delay.seconds, TimeUnit.SECONDS, schedulers.computation) } else { Single.just(Unit) } .zipWith( lifecycleEvents.filter { it == LifecycleEvent.Attach }.firstOrError(), BiFunction { a: Any, _: LifecycleEvent -> a } ) .flatMapPublisher { load() } Flowable.concat(Flowable.just(event), load) } else { Flowable.just(event) } } private fun load(): Flowable<Event> { return repository.load().flatMap(repeater) } override fun createIntents(): Flowable<Event> { val sync = retry.toFlowable(BackpressureStrategy.LATEST) .startWith(Unit) .switchMap { load() } val toggleUnit = toggleUnit.map<Event> { Event.ToggleUnit } .toFlowable(BackpressureStrategy.LATEST) return Flowable.merge(sync, toggleUnit) } override fun compose(events: Flowable<Event>): Flowable<State> { return events.scan(State()) { state, event -> when (event) { Event.ToggleUnit -> { state.copy( unitType = if (state.unitType === State.UnitType.Metric) { State.UnitType.Imperial } else { State.UnitType.Metric } ) } Event.Loading -> { state.copy(loading = true, errorCode = 0, errorMessage = null) } is Event.Success -> { state.copy(loading = false, data = event.data) } is Event.Error -> { state.copy( errorCode = event.code, errorMessage = event.message, loading = false ) } } } } private companion object { private const val RETRY = 1 private const val TOGGLE_UNIT = 2 } }
3
Kotlin
1
0
560272ef568c6f83d3b377a67b8c7ef4ee203673
3,613
weather
MIT License
payment-ws/src/main/kotlin/com/mobilabsolutions/payment/model/PaymentInfoModel.kt
mobilabsolutions
159,817,607
false
null
/* * Copyright © MobiLab Solutions GmbH */ package com.mobilabsolutions.payment.model import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty import javax.validation.Valid /** * @author <a href="mailto:<EMAIL>"><NAME></a> */ @ApiModel(value = "Payment info model") data class PaymentInfoModel( @ApiModelProperty("Alias extra") @field:Valid val extra: AliasExtraModel?, @ApiModelProperty("Psp configuration model") @field:Valid val pspConfig: PspConfigModel? )
1
Kotlin
1
3
7592abdabb7c05a71366634e5b09f4f08a3f0eff
522
stash-sdk-backend
Apache License 2.0
plugins/kotlin/j2k/new/tests/testData/newJ2k/enum/enumValuesWithExternalKotlinLibrary.kt
ingokegel
72,937,917
true
null
import library.kotlin.test.LibraryEnumKt internal class EnumTest { //TODO: Remove after Enum.entries is marked as non-experimental in Kotlin 1.9 @ExperimentalStdlibApi fun libraryTest() { val x = LibraryEnumKt.entries[1] val y = LibraryEnumKt.entries.toTypedArray() } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
303
intellij-community
Apache License 2.0
core/ktx/src/androidTest/java/androidx/core/graphics/BitmapTest.kt
adamfit
148,326,589
false
null
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.graphics import android.graphics.Bitmap import android.graphics.ColorSpace import androidx.test.filters.SdkSuppress import androidx.test.filters.SmallTest import org.junit.Assert.assertEquals import org.junit.Test @SmallTest class BitmapTest { @Test fun create() { val bitmap = createBitmap(7, 9) assertEquals(7, bitmap.width) assertEquals(9, bitmap.height) assertEquals(Bitmap.Config.ARGB_8888, bitmap.config) } @Test fun createWithConfig() { val bitmap = createBitmap(7, 9, config = Bitmap.Config.RGB_565) assertEquals(Bitmap.Config.RGB_565, bitmap.config) } @SdkSuppress(minSdkVersion = 26) @Test fun createWithColorSpace() { val colorSpace = ColorSpace.get(ColorSpace.Named.ADOBE_RGB) val bitmap = createBitmap(7, 9, colorSpace = colorSpace) assertEquals(colorSpace, bitmap.colorSpace) } @Test fun scale() { val b = createBitmap(7, 9).scale(3, 5) assertEquals(3, b.width) assertEquals(5, b.height) } @Test fun applyCanvas() { val p = createBitmap(2, 2).applyCanvas { drawColor(0x40302010) }.getPixel(1, 1) assertEquals(0x40302010, p) } @Test fun getPixel() { val b = createBitmap(2, 2).applyCanvas { drawColor(0x40302010) } assertEquals(0x40302010, b[1, 1]) } @Test fun setPixel() { val b = createBitmap(2, 2) b[1, 1] = 0x40302010 assertEquals(0x40302010, b[1, 1]) } }
0
null
657
2
9e6a7849696fce73bb81005a81b78410bfebc6d6
2,178
platform_frameworks_support
Apache License 2.0
sample/src/main/kotlin/pl/szczodrzynski/fslogin/RealmInfo.kt
szkolny-eu
254,408,975
false
null
package pl.szczodrzynski.fslogin import pl.szczodrzynski.fslogin.realm.RealmData data class RealmInfo( val id: Int, val name: String, val description: String, val icon: String, val screenshot: String, val formFields: List<String>, val realmData: RealmData )
1
Kotlin
0
6
6f40b58cd97a276ef1646e2b93be29009b7dbd1e
288
FSLogin
MIT License
sdk/src/main/java/com/exponea/sdk/view/NotificationsPermissionActivity.kt
exponea
134,699,893
false
null
package com.exponea.sdk.view import android.Manifest import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.exponea.sdk.receiver.NotificationsPermissionReceiver import com.exponea.sdk.util.Logger class NotificationsPermissionActivity : Activity() { private val permissionRequestCode = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { Logger.w(this, "Push notifications permission is not needed") sendBroadcastResult(true) finish() return } val permissionState = ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) if (permissionState == PackageManager.PERMISSION_GRANTED) { Logger.w(this, "Push notifications permission already granted") sendBroadcastResult(true) finish() return } ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), permissionRequestCode ) } private fun sendBroadcastResult(result: Boolean) { val intent = Intent() intent.action = NotificationsPermissionReceiver.ACTION_PERMISSIONS_RESPONSE intent.putExtra(NotificationsPermissionReceiver.ACTION_PERMISSIONS_RESULT_BOOL, result) sendBroadcast(intent) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { Logger.i(this, "Permission got code $requestCode") if (requestCode == permissionRequestCode) { if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { Logger.i(this, "Push notifications permission has been granted") sendBroadcastResult(true) } else { Logger.w(this, "Push notifications permission has been denied") sendBroadcastResult(false) } finish() } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } }
1
null
16
17
f58e80c19dc32581105c398fc08d12d41fd28ae2
2,414
exponea-android-sdk
MIT License
source-code/starter-project/app/src/main/java/com/droidcon/easyinvoice/ui/home/nav/TaxNav.kt
droidcon-academy
731,477,787
false
{"Kotlin": 413294}
/* * Copyright (c) 2022. Droidcon * * 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.droidcon.easyinvoice.ui.home.nav import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import androidx.navigation.navigation import com.droidcon.easyinvoice.ui.AppScreen import com.droidcon.easyinvoice.ui.home.customers.CustomersViewModel import com.droidcon.easyinvoice.ui.home.taxes.ManageTaxes import com.droidcon.easyinvoice.ui.home.taxes.Taxes import com.droidcon.easyinvoice.ui.home.taxes.TaxesViewModel import com.droidcon.easyinvoice.ui.utils.getViewModelInstance fun NavGraphBuilder.taxNav(navController: NavController) { navigation( startDestination = AppScreen.Taxes.Home.route, route = AppScreen.Taxes.route ) { composable(AppScreen.Taxes.Home.route) { val vm = navController.getViewModelInstance<TaxesViewModel>(it, AppScreen.Taxes.route) Taxes(vm, navController) } composable(AppScreen.Taxes.ManageTaxes.route) { val vm = navController.getViewModelInstance<TaxesViewModel>(it, AppScreen.Taxes.route) ManageTaxes(vm, navController) } } }
0
Kotlin
1
0
df32960315a4a501893a478daf4f61ae4149cfb3
1,746
android-room-database-course-materials
Apache License 2.0
tools/shell/src/main/kotlin/net/corda/tools/shell/InteractiveShell.kt
corda
70,137,417
false
null
package net.corda.tools.shell import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.databind.JsonMappingException import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.databind.module.SimpleModule import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator import net.corda.client.jackson.JacksonSupport import net.corda.client.jackson.StringToMethodCallParser import net.corda.client.rpc.CordaRPCClient import net.corda.client.rpc.CordaRPCClientConfiguration import net.corda.client.rpc.CordaRPCConnection import net.corda.client.rpc.GracefulReconnect import net.corda.client.rpc.PermissionException import net.corda.client.rpc.internal.RPCUtils.isShutdownMethodName import net.corda.client.rpc.notUsed import net.corda.core.CordaException import net.corda.core.concurrent.CordaFuture import net.corda.core.contracts.UniqueIdentifier import net.corda.core.flows.FlowLogic import net.corda.core.flows.StateMachineRunId import net.corda.core.internal.Emoji import net.corda.core.internal.VisibleForTesting import net.corda.core.internal.concurrent.doneFuture import net.corda.core.internal.concurrent.openFuture import net.corda.core.internal.createDirectories import net.corda.core.internal.div import net.corda.core.internal.messaging.InternalCordaRPCOps import net.corda.core.internal.packageName_ import net.corda.core.internal.rootCause import net.corda.core.internal.uncheckedCast import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.DataFeed import net.corda.core.messaging.FlowProgressHandle import net.corda.core.messaging.StateMachineUpdate import net.corda.core.messaging.pendingFlowsCount import net.corda.tools.shell.utlities.ANSIProgressRenderer import net.corda.tools.shell.utlities.StdoutANSIProgressRenderer import org.crsh.command.InvocationContext import org.crsh.command.ShellSafety import org.crsh.console.jline.JLineProcessor import org.crsh.console.jline.TerminalFactory import org.crsh.console.jline.console.ConsoleReader import org.crsh.lang.impl.java.JavaLanguage import org.crsh.plugin.CRaSHPlugin import org.crsh.plugin.PluginContext import org.crsh.plugin.PluginLifeCycle import org.crsh.plugin.ServiceLoaderDiscovery import org.crsh.shell.Shell import org.crsh.shell.ShellFactory import org.crsh.shell.impl.command.ExternalResolver import org.crsh.text.Color import org.crsh.text.Decoration import org.crsh.text.RenderPrintWriter import org.crsh.util.InterruptHandler import org.crsh.util.Utils import org.crsh.vfs.FS import org.crsh.vfs.spi.file.FileMountFactory import org.crsh.vfs.spi.url.ClassPathMountFactory import org.slf4j.LoggerFactory import rx.Observable import rx.Subscriber import java.io.FileDescriptor import java.io.FileInputStream import java.io.InputStream import java.io.PrintWriter import java.lang.reflect.GenericArrayType import java.lang.reflect.InvocationTargetException import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.lang.reflect.UndeclaredThrowableException import java.nio.file.Path import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.ExecutionException import java.util.concurrent.Future import kotlin.collections.ArrayList import kotlin.concurrent.thread // TODO: Add command history. // TODO: Command completion. // TODO: Do something sensible with commands that return a future. // TODO: Configure default renderers, send objects down the pipeline, add support for xml output format. // TODO: Add a command to view last N lines/tail/control log4j2 loggers. // TODO: Review or fix the JVM commands which have bitrotted and some are useless. // TODO: Get rid of the 'java' command, it's kind of worthless. // TODO: Fix up the 'dashboard' command which has some rendering issues. // TODO: Resurrect or reimplement the mail plugin. // TODO: Make it notice new shell commands added after the node started. const val STANDALONE_SHELL_PERMISSION = "ALL" @Suppress("MaxLineLength") object InteractiveShell { private val log = LoggerFactory.getLogger(javaClass) private lateinit var makeRPCConnection: (username: String, password: String) -> CordaRPCConnection private lateinit var ops: InternalCordaRPCOps private lateinit var rpcConn: CordaRPCConnection private var shell: Shell? = null private var classLoader: ClassLoader? = null private lateinit var shellConfiguration: ShellConfiguration private var onExit: () -> Unit = {} private const val uuidStringSize = 36 @JvmStatic fun getCordappsClassloader() = classLoader enum class OutputFormat { JSON, YAML } fun startShell(configuration: ShellConfiguration, classLoader: ClassLoader? = null, standalone: Boolean = false) { makeRPCConnection = { username: String, password: String -> val connection = if (standalone) { CordaRPCClient( configuration.hostAndPort, configuration.ssl, classLoader ).start(username, password, gracefulReconnect = GracefulReconnect()) } else { CordaRPCClient( hostAndPort = configuration.hostAndPort, configuration = CordaRPCClientConfiguration.DEFAULT.copy( maxReconnectAttempts = 1 ), sslConfiguration = configuration.ssl, classLoader = classLoader ).start(username, password) } rpcConn = connection connection } launchShell(configuration, standalone, classLoader) } private fun launchShell(configuration: ShellConfiguration, standalone: Boolean, classLoader: ClassLoader? = null) { shellConfiguration = configuration InteractiveShell.classLoader = classLoader val runSshDaemon = configuration.sshdPort != null var runShellInSafeMode = true if (!standalone) { log.info("launchShell: User=${configuration.user} perm=${configuration.permissions}") log.info("Shell: PermitExit= ${configuration.localShellAllowExitInSafeMode}, UNSAFELOCAL=${configuration.localShellUnsafe}") runShellInSafeMode = configuration.permissions?.filter { it.contains(STANDALONE_SHELL_PERMISSION); }?.isEmpty() != false } val config = Properties() if (runSshDaemon) { // Enable SSH access. Note: these have to be strings, even though raw object assignments also work. config["crash.ssh.port"] = configuration.sshdPort?.toString() config["crash.auth"] = "corda" configuration.sshHostKeyDirectory?.apply { val sshKeysDir = configuration.sshHostKeyDirectory.createDirectories() config["crash.ssh.keypath"] = (sshKeysDir / "hostkey.pem").toString() config["crash.ssh.keygen"] = "true" } } ExternalResolver.INSTANCE.addCommand( "output-format", "Commands to inspect and update the output format.", OutputFormatCommand::class.java ) ExternalResolver.INSTANCE.addCommand( "run", "Runs a method from the CordaRPCOps interface on the node.", RunShellCommand::class.java ) ExternalResolver.INSTANCE.addCommand( "flow", "Commands to work with flows. Flows are how you can change the ledger.", FlowShellCommand::class.java ) ExternalResolver.INSTANCE.addCommand( "start", "An alias for 'flow start'", StartShellCommand::class.java ) ExternalResolver.INSTANCE.addCommand( "hashLookup", "Checks if a transaction with matching Id hash exists.", HashLookupShellCommand::class.java ) ExternalResolver.INSTANCE.addCommand( "attachments", "Commands to extract information about attachments stored within the node", AttachmentShellCommand::class.java ) ExternalResolver.INSTANCE.addCommand( "checkpoints", "Commands to extract information about checkpoints stored within the node", CheckpointShellCommand::class.java ) val shellSafety = ShellSafety().apply { setSafeShell(runShellInSafeMode) setInternal(!standalone) setStandAlone(standalone) setAllowExitInSafeMode(configuration.localShellAllowExitInSafeMode || standalone) } shell = ShellLifecycle(configuration.commandsDirectory, shellSafety).start(config, configuration.user, configuration.password) } fun runLocalShell(onExit: () -> Unit = {}) { this.onExit = onExit val terminal = TerminalFactory.create() val consoleReader = ConsoleReader("Corda", FileInputStream(FileDescriptor.`in`), System.out, terminal) val jlineProcessor = JLineProcessor(terminal.isAnsiSupported, shell, consoleReader, System.out) InterruptHandler { jlineProcessor.interrupt() }.install() thread(name = "Command line shell processor", isDaemon = true) { Emoji.renderIfSupported { try { jlineProcessor.run() } catch (e: IndexOutOfBoundsException) { log.warn("Cannot parse malformed command.") } } } thread(name = "Command line shell terminator", isDaemon = true) { // Wait for the shell to finish. jlineProcessor.closed() log.info("Command shell has exited") terminal.restore() onExit.invoke() } } class ShellLifecycle(private val shellCommands: Path, private val shellSafety: ShellSafety) : PluginLifeCycle() { fun start(config: Properties, localUserName: String = "", localUserPassword: String = ""): Shell { val classLoader = this.javaClass.classLoader val classpathDriver = ClassPathMountFactory(classLoader) val fileDriver = FileMountFactory(Utils.getCurrentDirectory()) val extraCommandsPath = shellCommands.toAbsolutePath().createDirectories() val commandsFS = FS.Builder() .register("file", fileDriver) .mount("file:$extraCommandsPath") .register("classpath", classpathDriver) .mount("classpath:/net/corda/tools/shell/") .mount("classpath:/crash/commands/") .build() val confFS = FS.Builder() .register("classpath", classpathDriver) .mount("classpath:/crash") .build() val discovery = object : ServiceLoaderDiscovery(classLoader) { override fun getPlugins(): Iterable<CRaSHPlugin<*>> { // Don't use the Java language plugin (we may not have tools.jar available at runtime), this // will cause any commands using JIT Java compilation to be suppressed. In CRaSH upstream that // is only the 'jmx' command. return super.getPlugins().filterNot { it is JavaLanguage } + CordaAuthenticationPlugin(makeRPCConnection) + CordaDisconnectPlugin() } } val attributes = emptyMap<String, Any>() val context = PluginContext(discovery, attributes, commandsFS, confFS, classLoader) context.refresh() this.config = config start(context) val rpcOps = { username: String, password: String -> makeRPCConnection(username, password).proxy as InternalCordaRPCOps } ops = makeRPCOps(rpcOps, localUserName, localUserPassword) return context.getPlugin(ShellFactory::class.java).create(null, CordaSSHAuthInfo(false, ops, StdoutANSIProgressRenderer), shellSafety) } } fun nodeInfo() = try { ops.nodeInfo() } catch (e: UndeclaredThrowableException) { throw e.cause ?: e } @JvmStatic fun setOutputFormat(outputFormat: OutputFormat) { this.outputFormat = outputFormat } @JvmStatic fun getOutputFormat(): OutputFormat { return outputFormat } fun createYamlInputMapper(rpcOps: CordaRPCOps): ObjectMapper { // Return a standard Corda Jackson object mapper, configured to use YAML by default and with extra // serializers. return JacksonSupport.createDefaultMapper(rpcOps, YAMLFactory(), true).apply { val rpcModule = SimpleModule().apply { addDeserializer(InputStream::class.java, InputStreamDeserializer) addDeserializer(UniqueIdentifier::class.java, UniqueIdentifierDeserializer) } registerModule(rpcModule) } } private fun createOutputMapper(outputFormat: OutputFormat): ObjectMapper { val factory = when(outputFormat) { OutputFormat.JSON -> JsonFactory() OutputFormat.YAML -> YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER) } return JacksonSupport.createNonRpcMapper(factory).apply { // Register serializers for stateful objects from libraries that are special to the RPC system and don't // make sense to print out to the screen. For classes we own, annotations can be used instead. val rpcModule = SimpleModule().apply { addSerializer(Observable::class.java, ObservableSerializer) addSerializer(InputStream::class.java, InputStreamSerializer) } registerModule(rpcModule) disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) enable(SerializationFeature.INDENT_OUTPUT) } } // TODO: A default renderer could be used, instead of an object mapper. See: http://www.crashub.org/1.3/reference.html#_renderers private var outputFormat = OutputFormat.YAML @VisibleForTesting lateinit var latch: CountDownLatch private set /** * Called from the 'flow' shell command. Takes a name fragment and finds a matching flow, or prints out * the list of options if the request is ambiguous. Then parses [inputData] as constructor arguments using * the [runFlowFromString] method and starts the requested flow. Ctrl-C can be used to cancel. */ @JvmStatic fun runFlowByNameFragment(nameFragment: String, inputData: String, output: RenderPrintWriter, rpcOps: CordaRPCOps, ansiProgressRenderer: ANSIProgressRenderer, inputObjectMapper: ObjectMapper = createYamlInputMapper(rpcOps)) { val matches = try { rpcOps.registeredFlows().filter { nameFragment in it }.sortedBy { it.length } } catch (e: PermissionException) { output.println(e.message ?: "Access denied", Decoration.bold, Color.red) return } if (matches.isEmpty()) { output.println("No matching flow found, run 'flow list' to see your options.", Decoration.bold, Color.red) return } else if (matches.size > 1 && matches.find { it.endsWith(nameFragment)} == null) { output.println("Ambiguous name provided, please be more specific. Your options are:") matches.forEachIndexed { i, s -> output.println("${i + 1}. $s", Decoration.bold, Color.yellow) } return } val flowName = matches.find { it.endsWith(nameFragment)} ?: matches.single() val flowClazz: Class<FlowLogic<*>> = if (classLoader != null) { uncheckedCast(Class.forName(flowName, true, classLoader)) } else { uncheckedCast(Class.forName(flowName)) } try { // Show the progress tracker on the console until the flow completes or is interrupted with a // Ctrl-C keypress. val stateObservable = runFlowFromString( { clazz, args -> rpcOps.startTrackedFlowDynamic(clazz, *args) }, inputData, flowClazz, inputObjectMapper ) latch = CountDownLatch(1) ansiProgressRenderer.render(stateObservable, latch::countDown) // Wait for the flow to end and the progress tracker to notice. By the time the latch is released // the tracker is done with the screen. while (!Thread.currentThread().isInterrupted) { try { latch.await() break } catch (e: InterruptedException) { try { rpcOps.killFlow(stateObservable.id) } finally { Thread.currentThread().interrupt() break } } } output.println("Flow completed with result: ${stateObservable.returnValue.get()}") } catch (e: NoApplicableConstructor) { output.println("No matching constructor found:", Decoration.bold, Color.red) e.errors.forEach { output.println("- $it", Decoration.bold, Color.red) } } catch (e: PermissionException) { output.println(e.message ?: "Access denied", Decoration.bold, Color.red) } catch (e: ExecutionException) { // ignoring it as already logged by the progress handler subscriber } finally { InputStreamDeserializer.closeAll() } } class NoApplicableConstructor(val errors: List<String>) : CordaException(this.toString()) { override fun toString() = (listOf("No applicable constructor for flow. Problems were:") + errors).joinToString(System.lineSeparator()) } /** * Tidies up a possibly generic type name by chopping off the package names of classes in a hard-coded set of * hierarchies that are known to be widely used and recognised, and also not have (m)any ambiguous names in them. * * This is used for printing error messages when something doesn't match. */ private fun maybeAbbreviateGenericType(type: Type, extraRecognisedPackage: String): String { val packagesToAbbreviate = listOf("java.", "net.corda.core.", "kotlin.", extraRecognisedPackage) fun shouldAbbreviate(typeName: String) = packagesToAbbreviate.any { typeName.startsWith(it) } fun abbreviated(typeName: String) = if (shouldAbbreviate(typeName)) typeName.split('.').last() else typeName fun innerLoop(type: Type): String = when (type) { is ParameterizedType -> { val args: List<String> = type.actualTypeArguments.map(::innerLoop) abbreviated(type.rawType.typeName) + '<' + args.joinToString(", ") + '>' } is GenericArrayType -> { innerLoop(type.genericComponentType) + "[]" } is Class<*> -> { if (type.isArray) abbreviated(type.simpleName) else abbreviated(type.name).replace('$', '.') } else -> type.toString() } return innerLoop(type) } @JvmStatic fun killFlowById(id: String, output: RenderPrintWriter, rpcOps: CordaRPCOps, inputObjectMapper: ObjectMapper = createYamlInputMapper(rpcOps)) { try { val runId = try { inputObjectMapper.readValue(id, StateMachineRunId::class.java) } catch (e: JsonMappingException) { output.println("Cannot parse flow ID of '$id' - expecting a UUID.", Decoration.bold, Color.red) log.error("Failed to parse flow ID", e) return } //auxiliary validation - workaround for JDK8 bug https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8159339 if (id.length < uuidStringSize) { val msg = "Can not kill the flow. Flow ID of '$id' seems to be malformed - a UUID should have $uuidStringSize characters. " + "Expand the terminal window to see the full UUID value." output.println(msg, Decoration.bold, Color.red) log.warn(msg) return } if (rpcOps.killFlow(runId)) { output.println("Killed flow $runId", Decoration.bold, Color.yellow) } else { output.println("Failed to kill flow $runId", Decoration.bold, Color.red) } } finally { output.flush() } } /** * Given a [FlowLogic] class and a string in one-line Yaml form, finds an applicable constructor and starts * the flow, returning the created flow logic. Useful for lightweight invocation where text is preferable * to statically typed, compiled code. * * See the [StringToMethodCallParser] class to learn more about limitations and acceptable syntax. * * @throws NoApplicableConstructor if no constructor could be found for the given set of types. */ @Throws(NoApplicableConstructor::class) fun <T> runFlowFromString(invoke: (Class<out FlowLogic<T>>, Array<out Any?>) -> FlowProgressHandle<T>, inputData: String, clazz: Class<out FlowLogic<T>>, om: ObjectMapper): FlowProgressHandle<T> { val errors = ArrayList<String>() val parser = StringToMethodCallParser(clazz, om) val nameTypeList = getMatchingConstructorParamsAndTypes(parser, inputData, clazz) try { val args = parser.parseArguments(clazz.name, nameTypeList, inputData) return invoke(clazz, args) } catch (e: StringToMethodCallParser.UnparseableCallException.ReflectionDataMissing) { val argTypes = nameTypeList.map { (_, type) -> type } errors.add("$argTypes: <constructor missing parameter reflection data>") } catch (e: StringToMethodCallParser.UnparseableCallException) { val argTypes = nameTypeList.map { (_, type) -> type } errors.add("$argTypes: ${e.message}") } throw NoApplicableConstructor(errors) } private fun <T> getMatchingConstructorParamsAndTypes(parser: StringToMethodCallParser<FlowLogic<T>>, inputData: String, clazz: Class<out FlowLogic<T>>) : List<Pair<String, Type>> { val errors = ArrayList<String>() val classPackage = clazz.packageName_ lateinit var paramNamesFromConstructor: List<String> for (ctor in clazz.constructors) { // Attempt construction with the given arguments. fun getPrototype(): List<String> { val argTypes = ctor.genericParameterTypes.map { // If the type name is in the net.corda.core or java namespaces, chop off the package name // because these hierarchies don't have (m)any ambiguous names and the extra detail is just noise. maybeAbbreviateGenericType(it, classPackage) } return paramNamesFromConstructor.zip(argTypes).map { (name, type) -> "$name: $type" } } try { paramNamesFromConstructor = parser.paramNamesFromConstructor(ctor) val nameTypeList = paramNamesFromConstructor.zip(ctor.genericParameterTypes) parser.validateIsMatchingCtor(clazz.name, nameTypeList, inputData) return nameTypeList } catch (e: StringToMethodCallParser.UnparseableCallException.MissingParameter) { errors.add("${getPrototype()}: missing parameter ${e.paramName}") } catch (e: StringToMethodCallParser.UnparseableCallException.TooManyParameters) { errors.add("${getPrototype()}: too many parameters") } catch (e: StringToMethodCallParser.UnparseableCallException.ReflectionDataMissing) { val argTypes = ctor.genericParameterTypes.map { it.typeName } errors.add("$argTypes: <constructor missing parameter reflection data>") } catch (e: StringToMethodCallParser.UnparseableCallException) { val argTypes = ctor.genericParameterTypes.map { it.typeName } errors.add("$argTypes: ${e.message}") } } throw NoApplicableConstructor(errors) } // TODO Filtering on error/success when we will have some sort of flow auditing, for now it doesn't make much sense. @JvmStatic fun runStateMachinesView(out: RenderPrintWriter, rpcOps: CordaRPCOps): Any? { val proxy = rpcOps val (stateMachines, stateMachineUpdates) = proxy.stateMachinesFeed() val currentStateMachines = stateMachines.map { StateMachineUpdate.Added(it) } val subscriber = FlowWatchPrintingSubscriber(out) stateMachineUpdates.startWith(currentStateMachines).subscribe(subscriber) var result: Any? = subscriber.future if (result is Future<*>) { if (!result.isDone) { out.cls() out.println("Waiting for completion or Ctrl-C ... ") out.flush() } try { result = result.get() } catch (e: InterruptedException) { subscriber.unsubscribe() Thread.currentThread().interrupt() } catch (e: ExecutionException) { throw e.rootCause } catch (e: InvocationTargetException) { throw e.rootCause } } return result } @JvmStatic fun runAttachmentTrustInfoView( out: RenderPrintWriter, rpcOps: InternalCordaRPCOps ): Any { return AttachmentTrustTable(out, rpcOps.attachmentTrustInfos) } @JvmStatic fun runDumpCheckpoints(rpcOps: InternalCordaRPCOps) { rpcOps.dumpCheckpoints() } @JvmStatic fun runRPCFromString(input: List<String>, out: RenderPrintWriter, context: InvocationContext<out Any>, cordaRPCOps: CordaRPCOps, inputObjectMapper: ObjectMapper): Any? { val cmd = input.joinToString(" ").trim { it <= ' ' } if (cmd.startsWith("startflow", ignoreCase = true)) { // The flow command provides better support and startFlow requires special handling anyway due to // the generic startFlow RPC interface which offers no type information with which to parse the // string form of the command. out.println("Please use the 'flow' command to interact with flows rather than the 'run' command.", Decoration.bold, Color.yellow) return null } else if (cmd.substringAfter(" ").trim().equals("gracefulShutdown", ignoreCase = true)) { return gracefulShutdown(out, cordaRPCOps) } var result: Any? = null try { InputStreamSerializer.invokeContext = context val parser = StringToMethodCallParser(CordaRPCOps::class.java, inputObjectMapper) val call = parser.parse(cordaRPCOps, cmd) result = call.call() var subscription : Subscriber<*>? = null if (result != null && result !== Unit && result !is Void) { val (subs, future) = printAndFollowRPCResponse(result, out, outputFormat) subscription = subs result = future } if (result is Future<*>) { if (!result.isDone) { out.println("Waiting for completion or Ctrl-C ... ") out.flush() } try { result = result.get() } catch (e: InterruptedException) { subscription?.unsubscribe() Thread.currentThread().interrupt() } catch (e: ExecutionException) { throw e.rootCause } catch (e: InvocationTargetException) { throw e.rootCause } } if (isShutdownMethodName(cmd)) { out.println("Called 'shutdown' on the node.\nQuitting the shell now.").also { out.flush() } onExit.invoke() } } catch (e: StringToMethodCallParser.UnparseableCallException) { out.println(e.message, Decoration.bold, Color.red) if (e !is StringToMethodCallParser.UnparseableCallException.NoSuchFile) { out.println("Please try 'run -h' to learn what syntax is acceptable") } } catch (e: Exception) { out.println("RPC failed: ${e.rootCause}", Decoration.bold, Color.red) } finally { InputStreamSerializer.invokeContext = null InputStreamDeserializer.closeAll() } return result } @JvmStatic fun gracefulShutdown(userSessionOut: RenderPrintWriter, cordaRPCOps: CordaRPCOps): Int { var result = 0 // assume it all went well fun display(statements: RenderPrintWriter.() -> Unit) { statements.invoke(userSessionOut) userSessionOut.flush() } try { display { println("Orchestrating a clean shutdown, press CTRL+C to cancel...") println("...enabling draining mode") println("...waiting for in-flight flows to be completed") } val latch = CountDownLatch(1) @Suppress("DEPRECATION") val subscription = cordaRPCOps.pendingFlowsCount().updates .doAfterTerminate(latch::countDown) .subscribe( // For each update. { (completed, total) -> display { println("...remaining: $completed / $total") } }, // On error. { log.error(it.message) throw it }, // When completed. { // This will only show up in the standalone Shell, because the embedded one // is killed as part of a node's shutdown. display { println("...done, quitting the shell now.") } } ) cordaRPCOps.terminate(true) try { latch.await() // Unsubscribe or we hold up the shutdown subscription.unsubscribe() rpcConn.forceClose() onExit.invoke() } catch (e: InterruptedException) { // Cancelled whilst draining flows. So let's carry on from here cordaRPCOps.setFlowsDrainingModeEnabled(false) display { println("...cancelled clean shutdown.") } result = 1 } } catch (e: Exception) { display { println("RPC failed: ${e.rootCause}", Color.red) } result = 1 } finally { InputStreamSerializer.invokeContext = null InputStreamDeserializer.closeAll() } return result; } private fun printAndFollowRPCResponse( response: Any?, out: PrintWriter, outputFormat: OutputFormat ): Pair<PrintingSubscriber?, CordaFuture<Unit>> { val outputMapper = createOutputMapper(outputFormat) val mapElement: (Any?) -> String = { element -> outputMapper.writerWithDefaultPrettyPrinter().writeValueAsString(element) } return maybeFollow(response, mapElement, out) } private class PrintingSubscriber(private val printerFun: (Any?) -> String, private val toStream: PrintWriter) : Subscriber<Any>() { private var count = 0 val future = openFuture<Unit>() init { // The future is public and can be completed by something else to indicate we don't wish to follow // anymore (e.g. the user pressing Ctrl-C). future.then { unsubscribe() } } @Synchronized override fun onCompleted() { toStream.println("Observable has completed") future.set(Unit) } @Synchronized override fun onNext(t: Any?) { count++ toStream.println("Observation $count: " + printerFun(t)) toStream.flush() } @Synchronized override fun onError(e: Throwable) { toStream.println("Observable completed with an error") e.printStackTrace(toStream) future.setException(e) } } private fun maybeFollow( response: Any?, printerFun: (Any?) -> String, out: PrintWriter ): Pair<PrintingSubscriber?, CordaFuture<Unit>> { // Match on a couple of common patterns for "important" observables. It's tough to do this in a generic // way because observables can be embedded anywhere in the object graph, and can emit other arbitrary // object graphs that contain yet more observables. So we just look for top level responses that follow // the standard "track" pattern, and print them until the user presses Ctrl-C var result = Pair<PrintingSubscriber?, CordaFuture<Unit>>(null, doneFuture(Unit)) when { response is DataFeed<*, *> -> { out.println("Snapshot:") out.println(printerFun(response.snapshot)) out.flush() out.println("Updates:") val unsubscribeAndPrint: (Any?) -> String = { resp -> if (resp is StateMachineUpdate.Added) { resp.stateMachineInfo.progressTrackerStepAndUpdates?.updates?.notUsed() } printerFun(resp) } result = printNextElements(response.updates, unsubscribeAndPrint, out) } response is Observable<*> -> { result = printNextElements(response, printerFun, out) } response != null -> { out.println(printerFun(response)) } } return result } private fun printNextElements( elements: Observable<*>, printerFun: (Any?) -> String, out: PrintWriter ): Pair<PrintingSubscriber?, CordaFuture<Unit>> { val subscriber = PrintingSubscriber(printerFun, out) uncheckedCast(elements).subscribe(subscriber) return Pair(subscriber, subscriber.future) } }
61
null
2
3,777
efaf1549a9a4575c104f6849be494eb1f0186df0
35,560
corda
Apache License 2.0
modules/toast/src/androidMain/kotlin/splitties/toast/UnreliableToastApi.kt
LouisCAD
65,558,914
false
{"Gradle Kotlin DSL": 70, "Shell": 3, "Text": 4, "Markdown": 56, "Java Properties": 2, "Ignore List": 67, "Batchfile": 2, "Git Attributes": 1, "EditorConfig": 1, "YAML": 6, "XML": 72, "Kotlin": 299, "INI": 1, "Proguard": 5, "Java": 1, "CSS": 1, "AsciiDoc": 1}
/* * Copyright 2020 <NAME>. Use of this source code is governed by the Apache 2.0 license. */ package splitties.toast @RequiresOptIn( message = "Toasts are never shown if notifications are disabled for your app, " + "and you cannot know in any way if a toast has actually been displayed or not. " + "Consider using a more reliable way to show information to the user such as " + "snackbars, banners or dialogs.", level = RequiresOptIn.Level.WARNING ) annotation class UnreliableToastApi
53
Kotlin
160
2,476
1ed56ba2779f31dbf909509c955fce7b9768e208
523
Splitties
Apache License 2.0
app/src/main/java/com/thkox/homeai/presentation/navigation/WelcomeNavHost.kt
thkox
782,208,937
false
{"Kotlin": 226354}
package com.thkox.homeai.presentation.navigation import android.app.Activity import android.content.Intent import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.thkox.homeai.data.sources.local.SharedPreferencesManager import com.thkox.homeai.presentation.ui.activities.main.MainActivity import com.thkox.homeai.presentation.ui.activities.welcome.screens.EnterServerAddressScreen import com.thkox.homeai.presentation.ui.activities.welcome.screens.TutorialScreen import com.thkox.homeai.presentation.ui.activities.welcome.screens.auth.LoginScreen import com.thkox.homeai.presentation.ui.activities.welcome.screens.auth.RegisterScreen @Composable fun WelcomeNavHost( navController: NavHostController, startDestination: String, sharedPreferencesManager: SharedPreferencesManager ) { NavHost(navController = navController, startDestination = startDestination) { composable("enterServerAddress") { EnterServerAddressScreen( navigateTo = { navController.navigate("login") } ) } composable("login") { LoginScreen( navigateToRegister = { navController.navigate("register") }, navigateToEnterServerAddress = { sharedPreferencesManager.deleteBaseUrl() navController.navigate("enterServerAddress") }, navigateToMain = { navigateToMain(navController) } ) } composable("register") { RegisterScreen( navigateToLogin = { navController.popBackStack() }, navigateToTutorial = { navController.navigate("tutorial") }, ) } composable("tutorial") { TutorialScreen( navigateToMain = { navigateToMain(navController) } ) } } } fun navigateToMain(navController: NavHostController) { val context = navController.context context.startActivity(Intent(context, MainActivity::class.java)) (context as? Activity)?.finish() }
0
Kotlin
0
2
8a6f4239ed53e65f797f438d3326b383c40cc7c2
2,261
home-ai-client
MIT License
app/src/main/java/org/simple/clinic/scheduleappointment/ScheduleAppointmentEffectHandler.kt
simpledotorg
132,515,649
false
null
package org.simple.clinic.scheduleappointment import com.spotify.mobius.rx2.RxMobius import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import dagger.Lazy import io.reactivex.ObservableTransformer import org.simple.clinic.facility.Facility import org.simple.clinic.facility.FacilityRepository import org.simple.clinic.overdue.AppointmentConfig import org.simple.clinic.overdue.AppointmentRepository import org.simple.clinic.overdue.PotentialAppointmentDate import org.simple.clinic.overdue.TimeToAppointment import org.simple.clinic.patient.Patient import org.simple.clinic.patient.PatientRepository import org.simple.clinic.protocol.Protocol import org.simple.clinic.protocol.ProtocolRepository import org.simple.clinic.teleconsultlog.teleconsultrecord.TeleconsultRecordRepository import org.simple.clinic.util.Just import org.simple.clinic.util.None import org.simple.clinic.util.Optional import org.simple.clinic.util.UserClock import org.simple.clinic.util.plus import org.simple.clinic.util.scheduler.SchedulersProvider import org.simple.clinic.util.toNullable import org.simple.clinic.util.toOptional import org.simple.clinic.uuid.UuidGenerator import java.time.LocalDate import java.util.function.Function class ScheduleAppointmentEffectHandler @AssistedInject constructor( private val currentFacility: Lazy<Facility>, private val protocolRepository: ProtocolRepository, private val appointmentRepository: AppointmentRepository, private val patientRepository: PatientRepository, private val facilityRepository: FacilityRepository, private val appointmentConfig: AppointmentConfig, private val userClock: UserClock, private val schedulers: SchedulersProvider, private val uuidGenerator: UuidGenerator, @Assisted private val uiActions: ScheduleAppointmentUiActions, private val teleconsultRecordRepository: TeleconsultRecordRepository ) { @AssistedFactory interface Factory { fun create(uiActions: ScheduleAppointmentUiActions): ScheduleAppointmentEffectHandler } fun build(): ObservableTransformer<ScheduleAppointmentEffect, ScheduleAppointmentEvent> { return RxMobius .subtypeEffectHandler<ScheduleAppointmentEffect, ScheduleAppointmentEvent>() .addTransformer(LoadDefaultAppointmentDate::class.java, loadDefaultAppointmentDate()) .addConsumer(ShowDatePicker::class.java, { uiActions.showManualDateSelector(it.selectedDate) }, schedulers.ui()) .addTransformer(LoadAppointmentFacilities::class.java, loadAppointmentFacility()) .addTransformer(ScheduleAppointmentForPatient::class.java, scheduleAppointmentForPatient()) .addAction(CloseSheet::class.java, uiActions::closeSheet, schedulers.ui()) .addTransformer(LoadPatientDefaulterStatus::class.java, loadPatientDefaulterStatus()) .addTransformer(LoadTeleconsultRecord::class.java, loadTeleconsultRecordDetails()) .addConsumer(GoToTeleconsultStatusSheet::class.java, { uiActions.openTeleconsultStatusSheet(it.teleconsultRecordUuid) }, schedulers.ui()) .addTransformer(ScheduleAppointmentForPatientFromNext::class.java, scheduleAppointmentForPatientFromNext()) .build() } private fun scheduleAppointmentForPatientFromNext(): ObservableTransformer<ScheduleAppointmentForPatientFromNext, ScheduleAppointmentEvent> { return ObservableTransformer { effects -> effects .doOnNext { scheduleAppointment -> appointmentRepository.schedule( patientUuid = scheduleAppointment.patientUuid, appointmentUuid = uuidGenerator.v4(), appointmentDate = scheduleAppointment.scheduledForDate, appointmentType = scheduleAppointment.type, appointmentFacilityUuid = scheduleAppointment.scheduledAtFacility.uuid, creationFacilityUuid = currentFacility.get().uuid ) } .map { AppointmentScheduledForPatientFromNext } } } private fun loadTeleconsultRecordDetails(): ObservableTransformer<LoadTeleconsultRecord, ScheduleAppointmentEvent> { return ObservableTransformer { effects -> effects .observeOn(schedulers.io()) .map { val teleconsultRecord = teleconsultRecordRepository.getPatientTeleconsultRecord(patientUuid = it.patientUuid) TeleconsultRecordLoaded(teleconsultRecord) } } } private fun loadDefaultAppointmentDate(): ObservableTransformer<LoadDefaultAppointmentDate, ScheduleAppointmentEvent> { return ObservableTransformer { effects -> effects .map { currentProtocol(currentFacility.get()) } .map(::defaultTimeToAppointment) .map(::generatePotentialAppointmentDate) .map(::DefaultAppointmentDateLoaded) } } private fun currentProtocol(facility: Facility): Optional<Protocol> { return if (facility.protocolUuid == null) None() else protocolRepository.protocolImmediate(facility.protocolUuid).toOptional() } private fun defaultTimeToAppointment(protocol: Optional<Protocol>): TimeToAppointment { return if (protocol is Just) { TimeToAppointment.Days(protocol.value.followUpDays) } else { appointmentConfig.defaultTimeToAppointment } } private fun generatePotentialAppointmentDate(scheduleAppointmentIn: TimeToAppointment): PotentialAppointmentDate { val today = LocalDate.now(userClock) return PotentialAppointmentDate(today.plus(scheduleAppointmentIn), scheduleAppointmentIn) } private fun loadAppointmentFacility(): ObservableTransformer<LoadAppointmentFacilities, ScheduleAppointmentEvent> { return ObservableTransformer { effects -> effects .observeOn(schedulers.io()) .map { patientRepository.patientImmediate(it.patientUuid) } .map { val assignedFacility = getAssignedFacility(it).toNullable() AppointmentFacilitiesLoaded(assignedFacility, currentFacility.get()) } } } private fun getAssignedFacility(patient: Patient): Optional<Facility> { return Optional .ofNullable(patient.assignedFacilityId) .flatMap(Function { facilityRepository.facility(it) }) } private fun scheduleAppointmentForPatient(): ObservableTransformer<ScheduleAppointmentForPatient, ScheduleAppointmentEvent> { return ObservableTransformer { effects -> effects .doOnNext { scheduleAppointment -> appointmentRepository.schedule( patientUuid = scheduleAppointment.patientUuid, appointmentUuid = uuidGenerator.v4(), appointmentDate = scheduleAppointment.scheduledForDate, appointmentType = scheduleAppointment.type, appointmentFacilityUuid = scheduleAppointment.scheduledAtFacility.uuid, creationFacilityUuid = currentFacility.get().uuid ) } .map { AppointmentScheduled } } } private fun loadPatientDefaulterStatus(): ObservableTransformer<LoadPatientDefaulterStatus, ScheduleAppointmentEvent> { return ObservableTransformer { effects -> effects .map { val isPatientDefaulter = patientRepository.isPatientDefaulter(it.patientUuid) PatientDefaulterStatusLoaded(isPatientDefaulter) } } } }
3
null
73
236
ff699800fbe1bea2ed0492df484777e583c53714
7,413
simple-android
MIT License
shared/src/commonMain/kotlin/io/github/alaksion/unsplashwrapper/platform/httpclient/UnsplashHttpClient.kt
Alaksion
738,783,181
false
{"Kotlin": 61243, "Ruby": 2207}
package io.github.alaksion.unsplashwrapper.platform.httpclient import io.github.alaksion.unsplashwrapper.platform.token.TokenManager import io.github.alaksion.unsplashwrapper.platform.token.TokenManagerImplementation import io.github.alaksion.unsplashwrapper.platform.token.TokenType import io.github.alaksion.unsplashwrapper.platform.error.HttpError import io.github.alaksion.unsplashwrapper.platform.error.Unknown import io.github.alaksion.unsplashwrapper.platform.error.UnsplashRemoteError import io.github.alaksion.unsplashwrapper.sdk.UnsplashSdkConfig import io.ktor.client.HttpClient import io.ktor.client.plugins.ClientRequestException import io.ktor.client.plugins.DefaultRequest import io.ktor.client.plugins.HttpResponseValidator import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.plugins.logging.LogLevel import io.ktor.client.plugins.logging.Logging import io.ktor.client.request.bearerAuth import io.ktor.client.request.header import io.ktor.client.statement.bodyAsText import io.ktor.serialization.kotlinx.json.json import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toPersistentList import kotlinx.serialization.SerializationException import kotlinx.serialization.json.Json internal class UnsplashHttpClient private constructor( private val tokenManager: TokenManager ) { val client = HttpClient() { install(DefaultRequest) { tokenManager.getToken(TokenType.UserToken)?.let { userToken -> bearerAuth(userToken) } ?: header( "Authorization", "Client-ID ${tokenManager.getToken(TokenType.PublicToken)}" ) header("Version", UnsplashSdkConfig.version) } install(Logging) { level = LogLevel.INFO sanitizeHeader { header -> header == "Authorization" } } install(ContentNegotiation) { json( Json { ignoreUnknownKeys = true prettyPrint = true } ) } HttpResponseValidator { handleResponseExceptionWithRequest { cause, _ -> when (cause) { is ClientRequestException -> { val exceptionResponse = cause.response val parseBody = runCatching { Json.decodeFromString<UnsplashRemoteError>( exceptionResponse.call.response.bodyAsText() ) }.fold( onSuccess = { it.errors }, onFailure = { listOf("Unknown Error") } ) throw HttpError( statusCode = exceptionResponse.status.value, errors = parseBody.toPersistentList() ) } else -> throw Unknown( cause = cause, errors = persistentListOf(cause.message.orEmpty()) ) } } } } companion object { val Instance = UnsplashHttpClient( tokenManager = TokenManagerImplementation.Instance ) } }
0
Kotlin
0
0
e8e3b48fb80d62f9e7ce74e252925f2279e3c2e7
3,368
UnsplashWrapper
MIT License
GanAndroidApp/GanClient/src/main/java/com/xattacker/gan/service/SystemService.kt
xattacker
311,286,040
false
{"Swift": 94193, "Kotlin": 59707, "Java": 49457, "C": 12009, "Ruby": 1175, "Objective-C": 451, "Shell": 379, "Batchfile": 134}
package com.xattacker.gan.service import com.xattacker.binary.TypeConverter import com.xattacker.gan.GanAgent import com.xattacker.gan.data.FunctionType import java.util.* class SystemService internal constructor(agent: GanAgent) : ServiceFoundation(agent) { fun getIP(): String? { var ip: String? = null try { val response = send(FunctionType.GET_IP, null) if (response != null && response.result && response.response != null) { ip = String(response.response!!) } } catch (ex: Exception) { ip = null } return ip } fun getSystemTime(): Date? { var time: Date? = null try { val response = send(FunctionType.GET_SYSTEM_TIME, null) if (response != null && response.result && response.response != null) { val timestamp: Long = TypeConverter.byteToLong(response.response!!) time = Date(timestamp) } } catch (ex: Exception) { time = null } return time } }
0
Swift
0
0
b53e4e579eaaad8aaafa896e405bedd16a62d71d
1,179
GanSocket
MIT License
presentation/src/main/java/com/dsm/dms/presentation/di/module/ApiModule.kt
DSM-DMS
203,186,000
false
null
package com.dsm.dms.presentation.di.module import com.dsm.dms.data.remote.* import dagger.Module import dagger.Provides import retrofit2.Retrofit import javax.inject.Singleton @Module class ApiModule { companion object { private val baseUrl = "https://dev-api.dsm-dms.com/" private val mealUrl = "${baseUrl}meal/" private val accountUrl = "${baseUrl}account/" private val applyUrl = "${baseUrl}apply/" private val infoUrl = "${baseUrl}info/" } @Provides @Singleton fun provideMealApi(retrofit: Retrofit.Builder): MealApi = retrofit.baseUrl(mealUrl) .build() .create(MealApi::class.java) @Provides @Singleton fun provideAccountApi(retrofit: Retrofit.Builder): AccountApi = retrofit.baseUrl(accountUrl) .build() .create(AccountApi::class.java) @Provides @Singleton fun provideApplyApi(retrofit: Retrofit.Builder): ApplyApi = retrofit.baseUrl(applyUrl) .build() .create(ApplyApi::class.java) @Provides @Singleton fun provideInfoApi(retrofit: Retrofit.Builder): InfoApi = retrofit.baseUrl(infoUrl) .build() .create(InfoApi::class.java) @Provides @Singleton fun provideBaseApi(retrofit: Retrofit.Builder): BaseApi = retrofit.baseUrl(baseUrl) .build() .create(BaseApi::class.java) }
0
Kotlin
2
14
ae7de227cee270d22a72a4f59090bff07c43f019
1,455
DMS-Android-V4
MIT License
intellij-plugin-verifier/verifier-intellij/src/main/java/com/jetbrains/pluginverifier/reporting/DirectoryBasedPluginVerificationReportage.kt
JetBrains
3,686,654
false
null
/* * Copyright 2000-2020 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.jetbrains.pluginverifier.reporting import com.jetbrains.plugin.structure.base.utils.closeLogged import com.jetbrains.plugin.structure.base.utils.replaceInvalidFileNameCharacters import com.jetbrains.pluginverifier.PluginVerificationResult import com.jetbrains.pluginverifier.PluginVerificationTarget import com.jetbrains.pluginverifier.dependencies.presentation.DependenciesGraphPrettyPrinter import com.jetbrains.pluginverifier.reporting.common.FileReporter import com.jetbrains.pluginverifier.reporting.common.LogReporter import com.jetbrains.pluginverifier.reporting.ignoring.* import com.jetbrains.pluginverifier.repository.PluginInfo import com.jetbrains.pluginverifier.repository.repositories.marketplace.UpdateInfo import org.slf4j.LoggerFactory import java.nio.file.Path import java.nio.file.Paths /** * Creates the following files layout for saving the verification reports: * ``` * <verification-dir>/ * <IDE #1>/ * all-ignored-problems.txt * plugins/ * com.plugin.one/ * 1.0/ * warnings.txt * problems.txt * verification-result.txt * dependencies.txt * ignored-problems.txt * 2.0/ * ... * com.another.plugin/ * 1.5.0/ * ... * <IDE #2>/ * all-ignored-problems.txt * plugins/ * com.third.plugin/ * ... * ``` */ class DirectoryBasedPluginVerificationReportage(private val targetDirectoryProvider: (PluginVerificationTarget) -> Path) : PluginVerificationReportage { private val verificationLogger = LoggerFactory.getLogger("verification") private val messageReporters = listOf(LogReporter<String>(verificationLogger)) private val ignoredPluginsReporters = listOf(IgnoredPluginsReporter(targetDirectoryProvider)) private val allIgnoredProblemsReporter = AllIgnoredProblemsReporter(targetDirectoryProvider) override fun close() { messageReporters.forEach { it.closeLogged() } ignoredPluginsReporters.forEach { it.closeLogged() } allIgnoredProblemsReporter.closeLogged() } override fun logVerificationStage(stageMessage: String) { messageReporters.forEach { it.report(stageMessage) } } override fun logPluginVerificationIgnored( pluginInfo: PluginInfo, verificationTarget: PluginVerificationTarget, reason: String ) { ignoredPluginsReporters.forEach { it.report(PluginIgnoredEvent(pluginInfo, verificationTarget, reason)) } } /** * Creates a directory for reports of the plugin in the verified IDE: * ``` * com.plugin.id/ <- if the plugin is specified by its plugin-id and version * 1.0.0/ * .... * 2.0.0/ * plugin.zip/ <- if the plugin is specified by the local file path * .... * ``` */ private fun createPluginVerificationDirectory(pluginInfo: PluginInfo): Path { val pluginId = pluginInfo.pluginId.replaceInvalidFileNameCharacters() return when (pluginInfo) { is UpdateInfo -> { val version = "${pluginInfo.version} (#${pluginInfo.updateId})".replaceInvalidFileNameCharacters() Paths.get(pluginId, version) } else -> Paths.get(pluginId, pluginInfo.version.replaceInvalidFileNameCharacters()) } } private fun <T> Reporter<T>.useReporter(ts: Iterable<T>) = use { ts.forEach { t -> report(t) } } @Synchronized override fun reportVerificationResult(pluginVerificationResult: PluginVerificationResult) { with(pluginVerificationResult) { val directory = targetDirectoryProvider(verificationTarget) .resolve("plugins") .resolve(createPluginVerificationDirectory(plugin)) reportVerificationDetails(directory, "verification-verdict.txt", listOf(pluginVerificationResult)) { it.verificationVerdict } return when (this) { is PluginVerificationResult.Verified -> { reportVerificationDetails(directory, "warnings.txt", compatibilityWarnings) reportVerificationDetails(directory, "compatibility-problems.txt", compatibilityProblems) reportVerificationDetails(directory, "dependencies.txt", listOf(dependenciesGraph)) { DependenciesGraphPrettyPrinter(it).prettyPresentation() } reportVerificationDetails(directory, "deprecated-usages.txt", deprecatedUsages) reportVerificationDetails(directory, "experimental-api-usages.txt", experimentalApiUsages) reportVerificationDetails(directory, "internal-api-usages.txt", internalApiUsages) reportVerificationDetails(directory, "override-only-usages.txt", overrideOnlyMethodUsages) reportVerificationDetails(directory, "non-extendable-api-usages.txt", nonExtendableApiUsages) reportVerificationDetails(directory, "plugin-structure-warnings.txt", pluginStructureWarnings) val problemIgnoredEvents = ignoredProblems.map { ProblemIgnoredEvent(plugin, verificationTarget, it.key, it.value) } problemIgnoredEvents.forEach { allIgnoredProblemsReporter.report(it) } IgnoredProblemsReporter(directory, verificationTarget).useReporter(problemIgnoredEvents) } is PluginVerificationResult.InvalidPlugin -> { reportVerificationDetails(directory, "plugin-structure-errors.txt", pluginStructureErrors) } is PluginVerificationResult.NotFound -> Unit is PluginVerificationResult.FailedToDownload -> Unit } } } private fun <T> reportVerificationDetails( directory: Path, fileName: String, content: Iterable<T>, lineProvider: (T) -> String = { it.toString() } ) { FileReporter(directory.resolve(fileName), lineProvider).useReporter(content) } }
3
null
44
154
7500c21a7f4c0880b49b312e4a737709429035fc
5,985
intellij-plugin-verifier
Apache License 2.0
idea/idea-frontend-fir/idea-fir-low-level-api/tests/org/jetbrains/kotlin/idea/fir/low/level/api/compiler/based/AbstractCompilerBasedTest.kt
krzema12
312,049,057
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.analysis.low.level.api.fir.compiler.based import com.intellij.mock.MockProject import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.psi.PsiElementFinder import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.ProjectScope import org.jetbrains.kotlin.analysis.providers.KotlinDeclarationProviderFactory import org.jetbrains.kotlin.analysis.providers.KotlinModificationTrackerFactory import org.jetbrains.kotlin.analysis.providers.KotlinModuleInfoProvider import org.jetbrains.kotlin.analysis.providers.KotlinPackageProviderFactory import org.jetbrains.kotlin.analysis.providers.impl.KotlinStaticDeclarationProviderFactory import org.jetbrains.kotlin.analysis.providers.impl.KotlinStaticModificationTrackerFactory import org.jetbrains.kotlin.analysis.providers.impl.KotlinStaticPackageProviderFactory import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.analyzer.ModuleSourceInfoBase import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport import org.jetbrains.kotlin.asJava.finder.JavaElementFinder import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM import org.jetbrains.kotlin.cli.jvm.config.jvmClasspathRoots import org.jetbrains.kotlin.cli.jvm.config.jvmModularRoots import org.jetbrains.kotlin.config.JVMConfigurationKeys import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.fir.DependencyListForCliModule import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.declarations.SealedClassInheritorsProvider import org.jetbrains.kotlin.fir.deserialization.ModuleDataProvider import org.jetbrains.kotlin.fir.session.FirModuleInfoBasedModuleData import org.jetbrains.kotlin.analysis.low.level.api.fir.* import org.jetbrains.kotlin.analysis.low.level.api.fir.api.* import org.jetbrains.kotlin.analysis.low.level.api.fir.test.base.SealedClassInheritorsProviderTestImpl import org.jetbrains.kotlin.analysis.low.level.api.fir.transformers.FirLazyTransformerForIDE import org.jetbrains.kotlin.analysis.api.InvalidWayOfUsingAnalysisSession import org.jetbrains.kotlin.analysis.api.KtAnalysisSessionProvider import org.jetbrains.kotlin.analysis.api.fir.KtFirAnalysisSessionProvider import org.jetbrains.kotlin.light.classes.symbol.IDEKotlinAsJavaFirSupport import org.jetbrains.kotlin.load.kotlin.PackagePartProvider import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices import org.jetbrains.kotlin.test.TestConfiguration import org.jetbrains.kotlin.test.bind import org.jetbrains.kotlin.test.builders.TestConfigurationBuilder import org.jetbrains.kotlin.test.builders.testConfiguration import org.jetbrains.kotlin.test.directives.FirDiagnosticsDirectives import org.jetbrains.kotlin.test.directives.model.DirectivesContainer import org.jetbrains.kotlin.test.frontend.fir.FirOutputArtifact import org.jetbrains.kotlin.test.frontend.fir.getAnalyzerServices import org.jetbrains.kotlin.test.model.* import org.jetbrains.kotlin.test.runners.AbstractKotlinCompilerTest import org.jetbrains.kotlin.test.services.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.TestInfo abstract class AbstractCompilerBasedTest : AbstractKotlinCompilerTest() { private var _disposable: Disposable? = null protected val disposable: Disposable get() = _disposable!! @BeforeEach private fun intiDisposable(testInfo: TestInfo) { _disposable = Disposer.newDisposable("disposable for ${testInfo.displayName}") } @AfterEach private fun disposeDisposable() { _disposable?.let { Disposer.dispose(it) } _disposable = null } final override fun TestConfigurationBuilder.configuration() { globalDefaults { frontend = FrontendKinds.FIR targetPlatform = JvmPlatforms.defaultJvmPlatform dependencyKind = DependencyKind.Source } configureTest() defaultConfiguration(this) useAdditionalService(::TestModuleInfoProvider) usePreAnalysisHandlers(::ModuleRegistrarPreAnalysisHandler.bind(disposable)) } open fun TestConfigurationBuilder.configureTest() {} inner class LowLevelFirFrontendFacade( testServices: TestServices ) : FrontendFacade<FirOutputArtifact>(testServices, FrontendKinds.FIR) { override val directiveContainers: List<DirectivesContainer> get() = listOf(FirDiagnosticsDirectives) override fun analyze(module: TestModule): FirOutputArtifact { val moduleInfoProvider = testServices.moduleInfoProvider val moduleInfo = moduleInfoProvider.getModuleInfo(module.name) val project = testServices.compilerConfigurationProvider.getProject(module) val resolveState = createResolveStateForNoCaching(moduleInfo, project) val allFirFiles = moduleInfo.testFilesToKtFiles.map { (testFile, psiFile) -> testFile to psiFile.getOrBuildFirFile(resolveState) }.toMap() val diagnosticCheckerFilter = if (FirDiagnosticsDirectives.WITH_EXTENDED_CHECKERS in module.directives) { DiagnosticCheckerFilter.EXTENDED_AND_COMMON_CHECKERS } else DiagnosticCheckerFilter.ONLY_COMMON_CHECKERS val analyzerFacade = LowLevelFirAnalyzerFacade(resolveState, allFirFiles, diagnosticCheckerFilter) return LowLevelFirOutputArtifact(resolveState.rootModuleSession, analyzerFacade) } } override fun runTest(filePath: String) { val configuration = testConfiguration(filePath, configuration) if (ignoreTest(filePath, configuration)) { return } val oldEnableDeepEnsure = FirLazyTransformerForIDE.enableDeepEnsure try { FirLazyTransformerForIDE.enableDeepEnsure = true super.runTest(filePath) } finally { FirLazyTransformerForIDE.enableDeepEnsure = oldEnableDeepEnsure } } private fun ignoreTest(filePath: String, configuration: TestConfiguration): Boolean { val modules = configuration.moduleStructureExtractor.splitTestDataByModules(filePath, configuration.directives) if (modules.modules.none { it.files.any { it.isKtFile } }) { return true // nothing to highlight } return false } } class TestModuleInfoProvider(private val testServices: TestServices) : TestService { private val cache = mutableMapOf<String, TestModuleSourceInfo>() fun registerModuleInfo(testModule: TestModule, ktFiles: Map<TestFile, KtFile>) { cache[testModule.name] = TestModuleSourceInfo(testModule, ktFiles, testServices) } fun getModuleInfoByKtFile(ktFile: KtFile): TestModuleSourceInfo = cache.values.first { moduleSourceInfo -> ktFile in moduleSourceInfo.ktFiles } fun getModuleInfo(moduleName: String): TestModuleSourceInfo = cache.getValue(moduleName) } val TestServices.moduleInfoProvider: TestModuleInfoProvider by TestServices.testServiceAccessor() class ModuleRegistrarPreAnalysisHandler( testServices: TestServices, private val parentDisposable: Disposable ) : PreAnalysisHandler(testServices) { private val moduleInfoProvider = testServices.moduleInfoProvider override fun preprocessModuleStructure(moduleStructure: TestModuleStructure) { // todo rework after all modules will have the same Project instance val ktFilesByModule = moduleStructure.modules.associateWith { testModule -> val project = testServices.compilerConfigurationProvider.getProject(testModule) testServices.sourceFileProvider.getKtFilesForSourceFiles(testModule.files, project) } val allKtFiles = ktFilesByModule.values.flatMap { it.values.toList() } ktFilesByModule.forEach { (testModule, ktFiles) -> val project = testServices.compilerConfigurationProvider.getProject(testModule) moduleInfoProvider.registerModuleInfo(testModule, ktFiles) val configurator = FirModuleResolveStateConfiguratorForSingleModuleTestImpl( project, testServices, parentDisposable ) (project as MockProject).registerTestServices(configurator, allKtFiles, testServices) } } } class TestModuleSourceInfo( val testModule: TestModule, val testFilesToKtFiles: Map<TestFile, KtFile>, testServices: TestServices, ) : ModuleInfo, ModuleSourceInfoBase { private val moduleInfoProvider = testServices.moduleInfoProvider val ktFiles = testFilesToKtFiles.values.toSet() val moduleData = FirModuleInfoBasedModuleData(this) override val name: Name get() = Name.identifier(testModule.name) override fun dependencies(): List<ModuleInfo> = testModule.allDependencies .map { moduleInfoProvider.getModuleInfo(it.moduleName) } override val expectedBy: List<ModuleInfo> get() = testModule.dependsOnDependencies .map { moduleInfoProvider.getModuleInfo(it.moduleName) } override fun modulesWhoseInternalsAreVisible(): Collection<ModuleInfo> = testModule.friendDependencies .map { moduleInfoProvider.getModuleInfo(it.moduleName) } override val platform: TargetPlatform get() = testModule.targetPlatform override val analyzerServices: PlatformDependentAnalyzerServices get() = testModule.targetPlatform.getAnalyzerServices() } class FirModuleResolveStateConfiguratorForSingleModuleTestImpl( private val project: Project, testServices: TestServices, private val parentDisposable: Disposable, ) : FirModuleResolveStateConfigurator() { private val compilerConfigurationProvider = testServices.compilerConfigurationProvider private val librariesScope = ProjectScope.getLibrariesScope(project)//todo incorrect? private val sealedClassInheritorsProvider = SealedClassInheritorsProviderTestImpl() override fun createPackagePartsProvider(moduleInfo: ModuleSourceInfoBase, scope: GlobalSearchScope): PackagePartProvider { require(moduleInfo is TestModuleSourceInfo) val factory = compilerConfigurationProvider.getPackagePartProviderFactory(moduleInfo.testModule) return factory(scope) } override fun createModuleDataProvider(moduleInfo: ModuleSourceInfoBase): ModuleDataProvider { require(moduleInfo is TestModuleSourceInfo) val configuration = compilerConfigurationProvider.getCompilerConfiguration(moduleInfo.testModule) return DependencyListForCliModule.build( moduleInfo.name, moduleInfo.platform, moduleInfo.analyzerServices ) { dependencies(configuration.jvmModularRoots.map { it.toPath() }) dependencies(configuration.jvmClasspathRoots.map { it.toPath() }) friendDependencies(configuration[JVMConfigurationKeys.FRIEND_PATHS] ?: emptyList()) sourceDependencies(moduleInfo.moduleData.dependencies) sourceFriendsDependencies(moduleInfo.moduleData.friendDependencies) sourceDependsOnDependencies(moduleInfo.moduleData.dependsOnDependencies) }.moduleDataProvider } override fun getLanguageVersionSettings(moduleInfo: ModuleSourceInfoBase): LanguageVersionSettings { require(moduleInfo is TestModuleSourceInfo) return moduleInfo.testModule.languageVersionSettings } override fun getModuleSourceScope(moduleInfo: ModuleSourceInfoBase): GlobalSearchScope { require(moduleInfo is TestModuleSourceInfo) return TopDownAnalyzerFacadeForJVM.newModuleSearchScope(project, moduleInfo.testFilesToKtFiles.values) } override fun createScopeForModuleLibraries(moduleInfo: ModuleSourceInfoBase): GlobalSearchScope { return librariesScope } override fun createSealedInheritorsProvider(): SealedClassInheritorsProvider { return sealedClassInheritorsProvider } override fun configureSourceSession(session: FirSession) { } } fun MockProject.registerTestServices( configurator: FirModuleResolveStateConfiguratorForSingleModuleTestImpl, allKtFiles: List<KtFile>, testServices: TestServices, ) { registerService( FirModuleResolveStateConfigurator::class.java, configurator ) registerService(FirIdeResolveStateService::class.java) registerService( KotlinModificationTrackerFactory::class.java, KotlinStaticModificationTrackerFactory::class.java ) registerService(KotlinDeclarationProviderFactory::class.java, KotlinStaticDeclarationProviderFactory(allKtFiles)) registerService(KotlinPackageProviderFactory::class.java, KotlinStaticPackageProviderFactory(allKtFiles)) registerService(KotlinModuleInfoProvider::class.java, TestKotlinModuleInfoProvider(testServices)) reRegisterJavaElementFinder(this) } private class TestKotlinModuleInfoProvider(testServices: TestServices): KotlinModuleInfoProvider() { private val moduleInfoProvider = testServices.moduleInfoProvider override fun getModuleInfo(element: KtElement): ModuleInfo { val containingFile = element.containingKtFile return moduleInfoProvider.getModuleInfoByKtFile(containingFile) } } @OptIn(InvalidWayOfUsingAnalysisSession::class) private fun reRegisterJavaElementFinder(project: Project) { PsiElementFinder.EP.getPoint(project).unregisterExtension(JavaElementFinder::class.java) with(project as MockProject) { picoContainer.registerComponentInstance( KtAnalysisSessionProvider::class.qualifiedName, KtFirAnalysisSessionProvider(this) ) picoContainer.unregisterComponent(KotlinAsJavaSupport::class.qualifiedName) picoContainer.registerComponentInstance( KotlinAsJavaSupport::class.qualifiedName, IDEKotlinAsJavaFirSupport(project) ) } @Suppress("DEPRECATION") PsiElementFinder.EP.getPoint(project).registerExtension(JavaElementFinder(project)) }
34
null
2
24
af0c7cfbacc9fa1cc9bec5c8e68847b3946dc33a
14,647
kotlin-python
Apache License 2.0
core/common/src/main/kotlin/com/donghanx/common/extensions/Iterable+Extensions.kt
DonghanX
697,115,187
false
{"Kotlin": 186249}
package com.donghanx.common.extensions @Suppress("NOTHING_TO_INLINE") inline fun <T> Iterable<T>.filterAll(vararg predicates: (T) -> Boolean): List<T> { return filter { element -> predicates.all { it(element) } } }
0
Kotlin
0
0
2aaa7eaab5e383a3f2bb06493b60e640898bbb8e
220
nowinmtg
MIT License
VCL/src/test/java/io/velocitycareerlabs/infrastructure/resources/valid/VCLJwtServiceMock.kt
velocitycareerlabs
525,006,413
false
{"Kotlin": 614928}
/** * Created by <NAME> on 05/09/2023. * * Copyright 2022 Velocity Career Labs inc. * SPDX-License-Identifier: Apache-2.0 */ package io.velocitycareerlabs.infrastructure.resources.valid import io.velocitycareerlabs.api.entities.VCLPublicJwk import io.velocitycareerlabs.api.entities.VCLJwt import io.velocitycareerlabs.api.entities.VCLJwtDescriptor import io.velocitycareerlabs.api.entities.VCLResult import io.velocitycareerlabs.api.jwt.VCLJwtService class VCLJwtServiceMock: VCLJwtService { override fun sign( kid: String?, nonce: String?, jwtDescriptor: VCLJwtDescriptor, completionBlock: (VCLResult<VCLJwt>) -> Unit ) { } override fun verify( jwt: VCLJwt, publicPublic: VCLPublicJwk, completionBlock: (VCLResult<Boolean>) -> Unit ) { } }
0
Kotlin
0
1
daaf7fdd029d6a1cb152fd8506b43b1789fd1b88
830
WalletAndroid
Apache License 2.0