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/example/returnpals/mainMenu/NavHost.kt | BC-CS481-Capstone | 719,299,432 | false | {"Kotlin": 302344, "Java": 58006} | package com.example.returnpals.mainMenu
import android.location.Address
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navigation
import com.example.returnpals.composetools.pickup.AddPackagesScreen
import com.example.returnpals.composetools.pickup.PickupDateScreen
import com.example.returnpals.composetools.pickup.PickupMethodScreen
import com.example.returnpals.composetools.pickup.PricingScreen
import com.example.returnpals.composetools.pickup.ThankYou
import com.example.returnpals.composetools.ConfirmNumber
import com.example.returnpals.composetools.dashboard.HomeDash
import com.example.returnpals.composetools.dashboard.Orders
import com.example.returnpals.composetools.dashboard.Profile
import com.example.returnpals.composetools.dashboard.Settings
import com.example.returnpals.composetools.pickup.ConfirmPickupScreen
import com.example.returnpals.composetools.pickup.SelectAddressScreen
import com.example.returnpals.services.AddressesViewModel
import com.example.returnpals.services.ScheduleReturnViewModel
import java.util.Locale
@Composable
fun AppNavigation(navController: NavController) {
NavHost(
navController = navController as NavHostController,
startDestination = MenuRoutes.Home
) {
composable(MenuRoutes.Home) {
Home(navController)
}
composable(MenuRoutes.About) { About(navController) }
composable(MenuRoutes.Pricing) { Pricing(navController) }
composable(MenuRoutes.Contact) { Contact(navController) }
composable(MenuRoutes.Video) { Video(navController) }
composable(MenuRoutes.SignIn) { SignIn(navController) }
composable(MenuRoutes.FAQ) { FAQ(navController) }
composable(MenuRoutes.Register) { Register(navController)}
navigation(
startDestination = MenuRoutes.HomeDash,
route = "dashboard home"
) {
composable(MenuRoutes.HomeDash) { HomeDash(navController) }
composable(MenuRoutes.Profile) { Profile(navController) }
composable(MenuRoutes.Settings) { Settings(navController) }
composable(MenuRoutes.Orders) { Orders(navController) }
// composable(MenuRoutes.SelectAddress) { SelectAddress(navController) }
// composable(MenuRoutes.PickupDetails) { PickupDetails(navController) }
// composable(MenuRoutes.Label) { Label(navController) }
}
composable(MenuRoutes.ConfirmNumber) { ConfirmNumber(navController) }
navigation(
startDestination = "select_date",
route = MenuRoutes.PickupProcess
) {
composable("select_date") { entry ->
val pickupVM = entry.sharedViewModel<ScheduleReturnViewModel>(navController)
PickupDateScreen(
date = pickupVM.date.value,
onChangeDate = pickupVM::onChangeDate,
isValidDate = pickupVM::isValidDate,
onClickNext = { navController.navigate("select_address") },
onClickBack = { navController.navigate(MenuRoutes.HomeDash) },
)
}
composable("select_address") { entry ->
val pickupVM = entry.sharedViewModel<ScheduleReturnViewModel>(navController)
val addressesVM = entry.sharedViewModel<AddressesViewModel>(navController)
// TODO: retrieve addresses from user account
// TODO: send added addresses to user account
SelectAddressScreen(
selectedAddressId = addressesVM.selectedId.value,
addresses = addressesVM.addresses,
onSelectAddress = { id ->
addressesVM.onSelectAddress(id)
addressesVM.selectedAddress?.let { pickupVM.onChangeAddress(it) }
},
onAddAddress = addressesVM::onAddAddress,
onClickNext = { navController.navigate("select_method") },
onClickBack = { navController.navigate(("select_date")) }
)
}
composable("select_method") { entry ->
val pickupVM = entry.sharedViewModel<ScheduleReturnViewModel>(navController)
PickupMethodScreen(
method = pickupVM.method.value,
onChangeMethod = pickupVM::onChangeMethod,
onClickNext = { navController.navigate("select_pricing") },
onClickBack = { navController.navigate("select_address") },
)
}
composable("select_pricing") { entry ->
val pickupVM = entry.sharedViewModel<ScheduleReturnViewModel>(navController)
PricingScreen(
plan = pickupVM.plan.value,
onChangePlan = pickupVM::onChangePlan,
onClickNext = { navController.navigate("add_labels") },
onClickBack = { navController.navigate("select_method") },
)
}
composable("add_labels") { entry ->
val pickupVM = entry.sharedViewModel<ScheduleReturnViewModel>(navController)
AddPackagesScreen(
packages = pickupVM.packages.toMap(),
onAddLabel = pickupVM::onAddLabel,
onRemoveLabel = pickupVM::onRemoveLabel,
onClickNext = { navController.navigate("confirm") },
onClickBack = { navController.navigate("select_pricing") },
)
}
composable("confirm") { entry ->
val pickupVM = entry.sharedViewModel<ScheduleReturnViewModel>(navController)
ConfirmPickupScreen(
info = pickupVM.info,
onClickNext = {
pickupVM.onSubmit()
navController.navigate("thanks") },
onClickBack = { navController.navigate("add_labels") },
onClickPromoButton = {}
)
}
composable("thanks") { entry ->
val pickupVM = entry.sharedViewModel<ScheduleReturnViewModel>(navController)
ThankYou().drawThankYouUI(
dashBoardButton = {
navController.navigate("dashboard home") {
popUpTo(MenuRoutes.PickupProcess) {
inclusive = true
}
}
}
)
}
}
}
}
// magic https://youtu.be/FIEnIBq7Ups?si=O2ePHcmj0VsmQ7R-
@Composable
inline fun <reified T:ViewModel> NavBackStackEntry.sharedViewModel(navController: NavController): T {
val parentRoute = destination.parent?.route ?: return viewModel()
val parentEntry = remember(this) {
navController.getBackStackEntry(parentRoute)
}
return viewModel(parentEntry)
}
| 24 | Kotlin | 0 | 0 | ce2d93b0edc1a6f17ea9699e56d993c542c26574 | 7,417 | ReturnPalsApp | MIT License |
core/src/main/kotlin/gropius/model/template/SubTemplate.kt | ccims | 487,996,394 | false | null | package gropius.model.template
import com.expediagroup.graphql.generator.annotations.GraphQLDescription
import io.github.graphglue.model.Direction
import io.github.graphglue.model.DomainNode
import io.github.graphglue.model.Node
import io.github.graphglue.model.NodeRelationship
import org.springframework.data.annotation.Transient
@DomainNode
@GraphQLDescription(
"""BaseTemplate which is part of a Template.
Defines templated fields with specific types (defined using JSON schema).
Does not provide any composition features, as composition is handled by the Template it is part of.
"""
)
abstract class SubTemplate<T, P : Template<*, *>, S : SubTemplate<T, P, S>>(
name: String, description: String, templateFieldSpecifications: MutableMap<String, String>
) : BaseTemplate<T, S>(name, description, templateFieldSpecifications) where T : Node, T : TemplatedNode {
companion object {
const val PART_OF = "PART_OF"
}
@NodeRelationship(PART_OF, Direction.OUTGOING)
@GraphQLDescription("The Template this SubTemplate is part of")
val partOf by NodeProperty<P>()
} | 7 | Kotlin | 1 | 0 | a0b0538d1960e920d53bc9dc2d7026dfea49d723 | 1,113 | gropius-backend | MIT License |
src/backend/common/common-web/src/main/kotlin/com/tencent/devops/common/web/mq/alert/AlertLevel.kt | Roy9102 | 211,615,562 | true | {"Kotlin": 5871313, "Vue": 2662255, "JavaScript": 671898, "CSS": 377747, "Go": 119173, "Lua": 111686, "TSQL": 96222, "Shell": 89697, "Java": 71407, "TypeScript": 33693, "HTML": 23525, "Python": 10390, "Batchfile": 1974, "PLSQL": 901} | package com.tencent.devops.common.web.mq.alert
enum class AlertLevel(private val priority: Int) {
LOW(1),
MEDIUM(2),
HIGH(3),
CRITICAL(4);
fun compare(level: AlertLevel): Boolean {
return this.priority >= level.priority
}
} | 0 | Kotlin | 0 | 0 | 61199feb62705fe063d9975badefc80fc7868b2a | 257 | bk-ci | MIT License |
src/main/kotlin/id/walt/webwallet/backend/wallet/CredentialIssuance.kt | walt-id | 410,009,561 | false | null | package id.walt.webwallet.backend.wallet
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache
import com.nimbusds.openid.connect.sdk.token.OIDCTokens
import id.walt.common.VCObjectList
import id.walt.credentials.w3c.VerifiableCredential
import id.walt.credentials.w3c.templates.VcTemplateManager
import id.walt.custodian.Custodian
import id.walt.model.DidMethod
import id.walt.model.DidUrl
import id.walt.model.dif.PresentationDefinition
import id.walt.model.oidc.*
import id.walt.services.context.ContextManager
import id.walt.services.oidc.OIDC4CIService
import id.walt.services.oidc.OIDCUtils
import id.walt.webwallet.backend.auth.UserInfo
import id.walt.webwallet.backend.config.WalletConfig
import id.walt.webwallet.backend.context.WalletContextManager
import io.javalin.http.BadRequestResponse
import io.javalin.http.InternalServerErrorResponse
import mu.KotlinLogging
import java.net.URI
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.time.Duration
import java.time.Instant
import java.util.*
import java.util.concurrent.*
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
data class CredentialIssuanceRequest(
val did: String,
val issuerId: String,
val credentialTypes: List<String>,
val walletRedirectUri: String,
)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
data class CredentialIssuance4PresentationRequest(
val did: String,
val issuerId: String,
val presentationSessionId: String,
val walletRedirectUri: String,
)
data class CrossDeviceIssuanceInitiationRequest(
val oidcUri: String
)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
data class CredentialIssuanceSession(
val id: String,
val issuerId: String,
val credentialTypes: List<String>,
val isPreAuthorized: Boolean,
val isIssuerInitiated: Boolean,
val userPinRequired: Boolean,
@JsonIgnore val nonce: String,
var did: String? = null,
var walletRedirectUri: String? = null,
@JsonIgnore var user: UserInfo? = null,
@JsonIgnore var tokens: OIDCTokens? = null,
@JsonIgnore var lastTokenUpdate: Instant? = null,
@JsonIgnore var tokenNonce: String? = null,
@JsonIgnore var preAuthzCode: String? = null,
@JsonIgnore var opState: String? = null,
@VCObjectList var credentials: List<VerifiableCredential>? = null
) {
companion object {
fun fromIssuanceRequest(credentialIssuanceRequest: CredentialIssuanceRequest): CredentialIssuanceSession {
return CredentialIssuanceSession(
id = UUID.randomUUID().toString(),
issuerId = credentialIssuanceRequest.issuerId,
credentialTypes = credentialIssuanceRequest.credentialTypes,
false, false, false,
nonce = UUID.randomUUID().toString(),
did = credentialIssuanceRequest.did,
walletRedirectUri = credentialIssuanceRequest.walletRedirectUri
)
}
fun fromInitiationRequest(issuanceInitiationRequest: IssuanceInitiationRequest): CredentialIssuanceSession {
return CredentialIssuanceSession(
id = UUID.randomUUID().toString(),
issuerId = issuanceInitiationRequest.issuer_url,
credentialTypes = issuanceInitiationRequest.credential_types,
isPreAuthorized = issuanceInitiationRequest.isPreAuthorized,
isIssuerInitiated = true,
userPinRequired = issuanceInitiationRequest.user_pin_required,
nonce = UUID.randomUUID().toString(),
opState = issuanceInitiationRequest.op_state,
preAuthzCode = issuanceInitiationRequest.pre_authorized_code
)
}
}
}
object CredentialIssuanceManager {
private val log = KotlinLogging.logger { }
val EXPIRATION_TIME = Duration.ofMinutes(5)
val sessionCache = CacheBuilder.newBuilder().expireAfterAccess(EXPIRATION_TIME.seconds, TimeUnit.SECONDS)
.build<String, CredentialIssuanceSession>()
val issuerCache: LoadingCache<String, OIDCProviderWithMetadata> = CacheBuilder.newBuilder().maximumSize(256)
.build(
CacheLoader.from { issuerId -> // find issuer from config
log.debug { "Loading issuer: $issuerId, got: ${WalletConfig.config.issuers[issuerId!!]}" }
(WalletConfig.config.issuers[issuerId!!]
?: OIDCProvider(issuerId, issuerId) // else, assume issuerId is a valid issuer url
).let {
log.debug { "Retrieving metadata endpoint for issuer: ${OIDC4CIService.getMetadataEndpoint(it)}" }
OIDC4CIService.getWithProviderMetadata(it)
}
}
)
val redirectURI: URI
get() = URI.create("${WalletConfig.config.walletApiUrl}/siop/finalizeIssuance")
private fun getPreferredFormat(
credentialTypeId: String,
did: String,
supportedCredentials: Map<String, CredentialMetadata>
): String? {
val preferredByEcosystem = when (DidUrl.from(did).method) {
DidMethod.iota.name -> "ldp_vc"
DidMethod.ebsi.name -> "jwt_vc"
else -> "jwt_vc"
}
log.debug { "Checking if $credentialTypeId is supported (supported: $supportedCredentials)" }
if (supportedCredentials.containsKey(credentialTypeId)) {
log.debug { "Credential $credentialTypeId is supported!" }
log.debug { "Credential: ${supportedCredentials[credentialTypeId]}" }
if (!supportedCredentials[credentialTypeId]!!.formats.containsKey(preferredByEcosystem)) {
log.debug { "Format $preferredByEcosystem is supported (${supportedCredentials[credentialTypeId]!!.formats})" }
// ecosystem preference is explicitly not supported, check if ldp_vc or jwt_vc is
return supportedCredentials[credentialTypeId]!!.formats.keys.firstOrNull { fmt ->
setOf(
"jwt_vc",
"ldp_vc"
).contains(fmt)
}
} else {
log.debug { "Format $preferredByEcosystem is NOT supported (${supportedCredentials[credentialTypeId]!!.formats})" }
}
}
return preferredByEcosystem
}
fun executeAuthorizationStep(session: CredentialIssuanceSession): URI {
val issuer = issuerCache[session.issuerId]
val supportedCredentials = OIDC4CIService.getSupportedCredentials(issuer)
val credentialDetails = session.credentialTypes.map {
CredentialAuthorizationDetails(
credential_type = it,
format = getPreferredFormat(it, session.did!!, supportedCredentials)
)
}
return OIDC4CIService.executePushedAuthorizationRequest(
issuer = issuer,
redirectUri = redirectURI,
credentialDetails = credentialDetails,
nonce = session.nonce,
state = session.id,
wallet_issuer = WalletConfig.config.walletApiUrl,
user_hint = URI.create(WalletConfig.config.walletUiUrl).authority,
op_state = session.opState
) ?: throw InternalServerErrorResponse("Could not execute pushed authorization request on issuer")
}
fun startIssuance(issuanceRequest: CredentialIssuanceRequest, user: UserInfo): URI {
val session = CredentialIssuanceSession.fromIssuanceRequest(issuanceRequest).apply {
this.user = user
}
return executeAuthorizationStep(session).also {
putSession(session)
}
}
fun startIssuanceForPresentation(
issuance4PresentationRequest: CredentialIssuance4PresentationRequest,
user: UserInfo
): URI {
val presentationSession =
CredentialPresentationManager.getPresentationSession(issuance4PresentationRequest.presentationSessionId)
?: throw BadRequestResponse("No presentation session found for this session id")
return startIssuance(
CredentialIssuanceRequest(
did = issuance4PresentationRequest.did,
issuerId = issuance4PresentationRequest.issuerId,
credentialTypes = getIssuerCredentialTypesFor(
presentationSession.sessionInfo.presentationDefinition,
issuance4PresentationRequest.issuerId
),
walletRedirectUri = issuance4PresentationRequest.walletRedirectUri
),
user
)
}
fun startIssuerInitiatedIssuance(issuanceInitiationRequest: IssuanceInitiationRequest): String {
val session = CredentialIssuanceSession.fromInitiationRequest(issuanceInitiationRequest)
putSession(session)
return session.id
}
fun continueIssuerInitiatedIssuance(
sessionId: String,
did: String,
user: UserInfo,
userPin: String?
): CredentialIssuanceSession {
val session = sessionCache.getIfPresent(sessionId) ?: throw BadRequestResponse("Session invalid or not found")
if (!session.isIssuerInitiated) throw BadRequestResponse("Session is not issuer initiated")
session.did = did
session.user = user
putSession(session)
if (session.isPreAuthorized) {
return finalizeIssuance(sessionId, session.preAuthzCode!!, userPin)
}
return session
}
private fun enc(value: String): String = URLEncoder.encode(value, StandardCharsets.UTF_8)
fun finalizeIssuance(id: String, code: String, userPin: String? = null): CredentialIssuanceSession {
val session = sessionCache.getIfPresent(id) ?: throw BadRequestResponse("Session invalid or not found")
val issuer = issuerCache[session.issuerId]
val user = session.user ?: throw BadRequestResponse("Session has not been confirmed by user")
val did = session.did ?: throw BadRequestResponse("No DID assigned to session")
val redirectUriString = if (!session.isPreAuthorized) redirectURI.toString() else null
val tokenResponse =
OIDC4CIService.getAccessToken(issuer, code, redirectUriString, session.isPreAuthorized, userPin)
if (!tokenResponse.indicatesSuccess()) {
return session
}
session.tokens = tokenResponse.toSuccessResponse().oidcTokens
session.lastTokenUpdate = Instant.now()
tokenResponse.customParameters["c_nonce"]?.toString()?.also {
session.tokenNonce = it
}
val supportedCredentials = OIDC4CIService.getSupportedCredentials(issuer)
// log.info { "Supported credentials are: $supportedCredentials" }
ContextManager.runWith(WalletContextManager.getUserContext(user)) {
val custodian = Custodian.getService()
session.credentials = session.credentialTypes.mapNotNull { typeId ->
OIDC4CIService.getCredential(
issuer,
session.tokens!!.accessToken,
typeId,
OIDC4CIService.generateDidProof(issuer, did, session.tokenNonce ?: ""),
format = getPreferredFormat(typeId, did, supportedCredentials)
)
}.onEach {
it.id = it.id ?: UUID.randomUUID().toString()
custodian.storeCredential(it.id!!, it)
}
}
putSession(session)
return session
}
fun getSession(id: String): CredentialIssuanceSession? {
return sessionCache.getIfPresent(id)
}
fun putSession(session: CredentialIssuanceSession) {
sessionCache.put(session.id, session)
}
fun getIssuerWithMetadata(issuerId: String): OIDCProviderWithMetadata {
return issuerCache[issuerId]
}
fun findIssuersFor(presentationDefinition: PresentationDefinition): List<OIDCProvider> {
val matchingTemplates = findMatchingVCTemplates(presentationDefinition)
return WalletConfig.config.issuers.keys.map { issuerCache[it] }.filter { issuer ->
log.info { "Finding issuer for: ${issuer.id} (url = ${issuer.url})" }
val supportedTypeLists = OIDC4CIService.getSupportedCredentials(issuer).values
.flatMap { credentialMetadata -> credentialMetadata.formats.values }
.map { fmt -> fmt.types }
log.info { "Got supported type list: $supportedTypeLists" }
matchingTemplates.map { it.type }.all { reqTypeList ->
supportedTypeLists.any { typeList ->
reqTypeList.size == typeList.size &&
reqTypeList.zip(typeList).all { (x, y) -> x == y }
}
}
}.map {
OIDCProvider(it.id, it.url, it.description) // strip secrets
}
}
private fun findMatchingVCTemplates(presentationDefinition: PresentationDefinition): List<VerifiableCredential> {
return VcTemplateManager.listTemplates()
.map { VcTemplateManager.getTemplate(it.name, true).template!! }
.filter { tmpl ->
presentationDefinition.input_descriptors.any { inputDescriptor ->
OIDCUtils.matchesInputDescriptor(tmpl, inputDescriptor)
}
}
}
private fun getIssuerCredentialTypesFor(presentationDefinition: PresentationDefinition, issuerId: String): List<String> {
val issuer = issuerCache[issuerId]
val reqTypeLists = findMatchingVCTemplates(presentationDefinition).map { it.type }
val supportedCredentials = OIDC4CIService.getSupportedCredentials(issuer)
return supportedCredentials.filter { entry ->
entry.value.formats.values.map { it.types }.any { typeList ->
reqTypeLists.any { reqTypeList ->
reqTypeList.size == typeList.size &&
reqTypeList.zip(typeList).all { (x, y) -> x == y }
}
}
}.map { it.key }
}
}
| 3 | null | 26 | 33 | 4b436214d0e0839a2dba39e2c200938ca1826efc | 14,351 | waltid-walletkit | Apache License 2.0 |
app/src/main/java/com/mobiquity/arnab/weather/database/entity/CityEntity.kt | arnab-kundu | 402,242,019 | false | null | package com.mobiquity.arnab.weather.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
/**
* This class is responsible for creating `accelerometer_log` table in database
*/
@Entity(tableName = "city", indices = [Index(value = ["name"], unique = true)])
data class CityEntity(
@PrimaryKey(autoGenerate = true)
var id: Long = 0,
@ColumnInfo(name = "name")
var name: String = "",
@ColumnInfo(name = "lat")
var lat: Double = 0.0,
@ColumnInfo(name = "lon")
var lon: Double = 0.0,
)
| 1 | null | 1 | 1 | 1c0f62b7f62ca86e3ecb8f9148c17bd03f37166b | 633 | Weather | MIT License |
src/main/java/com/sygic/travel/sdk/places/api/model/ApiUpdateReviewVoteRequest.kt | sygic-travel | 84,565,535 | false | null | package com.sygic.travel.sdk.places.api.model
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
internal class ApiUpdateReviewVoteRequest(
val value: Int
)
| 0 | Kotlin | 1 | 8 | ea7a259fe5f4e712fdb082edf581f05b5ff97baa | 180 | android-sdk | MIT License |
feature-movie-detail/src/main/java/sanchez/sanchez/sergio/feature_movie_detail/di/module/movie/MovieDetailDatabaseModule.kt | sergio11 | 332,195,948 | false | null | package sanchez.sanchez.sergio.feature_movie_detail.di.module.movie
import android.content.Context
import dagger.Module
import dagger.Provides
import io.objectbox.Box
import io.objectbox.BoxStore
import sanchez.sanchez.sergio.feature_movie_detail.BuildConfig
import sanchez.sanchez.sergio.feature_movie_detail.domain.model.Keyword
import sanchez.sanchez.sergio.feature_movie_detail.domain.model.MovieDetail
import sanchez.sanchez.sergio.feature_movie_detail.domain.model.Review
import sanchez.sanchez.sergio.feature_movie_detail.domain.model.Video
import sanchez.sanchez.sergio.feature_movie_detail.persistence.db.mapper.MovieDetailEntityMapper
import sanchez.sanchez.sergio.feature_movie_detail.persistence.db.mapper.MovieKeywordEntityMapper
import sanchez.sanchez.sergio.feature_movie_detail.persistence.db.mapper.MovieReviewEntityMapper
import sanchez.sanchez.sergio.feature_movie_detail.persistence.db.mapper.MovieVideoEntityMapper
import sanchez.sanchez.sergio.feature_movie_detail.persistence.db.model.*
import sanchez.sanchez.sergio.movie_addicts.core.di.scope.PerFragment
import sanchez.sanchez.sergio.movie_addicts.core.persistence.db.ObjectBoxManager
import sanchez.sanchez.sergio.movie_addicts.core.persistence.db.mapper.IEntityToModelMapper
import sanchez.sanchez.sergio.movie_addicts.core.persistence.db.repository.IDBRepository
import sanchez.sanchez.sergio.movie_addicts.core.persistence.db.repository.objectbox.ObjectBoxRepositoryConfiguration
import sanchez.sanchez.sergio.movie_addicts.core.persistence.db.repository.objectbox.SupportObjectBoxRepositoryImpl
/**
* Movie Detail Database Module
*/
@Module
class MovieDetailDatabaseModule {
/**
* Provide Movie Keyword Entity Mapper
*/
@Provides
@PerFragment
fun provideMovieKeywordEntityMapper(): IEntityToModelMapper<KeywordEntity, Keyword>
= MovieKeywordEntityMapper()
/**
* Provide Movie Review Entity Mapper
*/
@Provides
@PerFragment
fun provideMovieReviewEntityMapper(): IEntityToModelMapper<ReviewEntity, Review>
= MovieReviewEntityMapper()
/**
* Provide Movie Video Entity Mapper
*/
@Provides
@PerFragment
fun provideMovieVideoEntityMapper(): IEntityToModelMapper<VideoEntity, Video>
= MovieVideoEntityMapper()
/**
* Provide Movie Detail Entity Mapper
* @param movieKeywordEntityMapper
* @param movieReviewEntityMapper
* @param movieVideoEntityMapper
*/
@Provides
@PerFragment
fun provideMovieDetailEntityMapper(
movieKeywordEntityMapper: IEntityToModelMapper<KeywordEntity, Keyword>,
movieReviewEntityMapper: IEntityToModelMapper<ReviewEntity, Review> ,
movieVideoEntityMapper: IEntityToModelMapper<VideoEntity, Video>
): IEntityToModelMapper<MovieDetailEntity, MovieDetail> = MovieDetailEntityMapper(
movieKeywordEntityMapper, movieReviewEntityMapper,
movieVideoEntityMapper
)
/**
* Provide Box Store
* @param appContext
* @param objectBoxManager
*/
@Provides
@PerFragment
fun provideBoxStore(appContext: Context, objectBoxManager: ObjectBoxManager): BoxStore =
objectBoxManager.getBoxStore(BuildConfig.BOX_STORE_NAME) ?:
MyObjectBox.builder()
.androidContext(appContext)
.name(BuildConfig.BOX_STORE_NAME)
.build().also {
objectBoxManager.registerBoxStore(BuildConfig.BOX_STORE_NAME, it)
}
/**
* Provide Movie Detail DAO
* @param boxStore
*/
@Provides
@PerFragment
fun provideMovieDetailDAO(boxStore: BoxStore): Box<MovieDetailEntity> =
boxStore.boxFor(MovieDetailEntity::class.java)
/**
* Provide Object Box Configuration
*/
@Provides
@PerFragment
fun provideObjectBoxConfiguration(): ObjectBoxRepositoryConfiguration<MovieDetailEntity>
= ObjectBoxRepositoryConfiguration(
maxObjectsAllowed = MAX_OBJECTS_ALLOWED,
objectsExpireInMillis = OBJECTS_EXPIRE_IN_MILLIS,
objectIdProperty = MovieDetailEntity_.id,
savedAtInMillisProperty = MovieDetailEntity_.savedAtInMillis)
/**
* Provide Movie DB Repository
* @param movieDetailDAO
* @param movieDetailEntityMapper
*/
@Provides
@PerFragment
fun provideMovieDBRepository(
movieDetailDAO: Box<MovieDetailEntity>,
movieDetailEntityMapper: IEntityToModelMapper<MovieDetailEntity, MovieDetail>,
objectBoxRepositoryConfiguration: ObjectBoxRepositoryConfiguration<MovieDetailEntity>
): IDBRepository<MovieDetail> =
SupportObjectBoxRepositoryImpl(movieDetailDAO, movieDetailEntityMapper, objectBoxRepositoryConfiguration)
companion object {
private const val MAX_OBJECTS_ALLOWED = 20
private const val OBJECTS_EXPIRE_IN_MILLIS = 86400000 // 24 hours
}
} | 0 | Kotlin | 0 | 6 | eef4f5b03c33f1efd937d546ebdea84c3255d445 | 4,972 | MovieAddicts | MIT License |
src/main/kotlin/io/usoamic/wallet/ui/auth/auth/AuthView.kt | usoamic | 299,967,649 | false | null | package io.usoamic.wallet.ui.auth.auth
import io.usoamic.wallet.extensions.fx.replaceWithSlideLeft
import io.usoamic.wallet.ui.auth.add.AddView
import io.usoamic.wallet.ui.auth.create.CreateView
import io.usoamic.wallet.ui.base.BaseView
import io.usoamic.wallet.values.R
import javafx.geometry.Pos
import javafx.scene.layout.StackPane
import tornadofx.*
class AuthView : BaseView() {
override val root: StackPane = stackpane {
paddingHorizontal = 50.0
vbox(10) {
pane()
alignment = Pos.CENTER
imageview(R.image.IC_USOAMIC) {
fitHeight = 200.0
fitWidth = 200.0
}
label(R.string.APP_NAME) {
vboxConstraints {
marginBottom = 15.0
}
}
button(R.string.ADD_ACCOUNT) {
fitToParentWidth()
action {
replaceWithSlideLeft<AddView>()
}
}
button(R.string.CREATE_ACCOUNT) {
fitToParentWidth()
action {
replaceWithSlideLeft<CreateView>()
}
}
}
}
} | 0 | Kotlin | 1 | 1 | 104257879f1b878930d1cf283385ffb70470b446 | 1,209 | UsoamicWallet-Desktop | MIT License |
library/renetik-android-controller/src/main/java/renetik/android/controller/common/CSNavigationView.kt | renetik | 69,289,476 | false | null | package renetik.android.controller.navigation
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils.loadAnimation
import android.widget.FrameLayout
import renetik.android.controller.R
import renetik.android.controller.base.CSActivity
import renetik.android.controller.base.CSActivityView
import renetik.android.controller.navigation.CSNavigationAnimation.None
import renetik.android.controller.navigation.CSNavigationAnimation.SlideInRight
import renetik.android.controller.navigation.CSNavigationAnimation.SlideOutLeft
import renetik.android.core.kotlin.collections.deleteLast
import renetik.android.core.kotlin.collections.hasKey
import renetik.android.core.kotlin.ifNull
import renetik.android.core.kotlin.isNotNull
import renetik.android.core.kotlin.onNotNull
import renetik.android.core.kotlin.unexpected
import renetik.android.core.lang.CSLayoutRes.Companion.layout
import renetik.android.core.logging.CSLog.logWarnTrace
import renetik.android.ui.extensions.add
import renetik.android.ui.extensions.onGlobalFocus
import renetik.android.ui.extensions.remove
class CSNavigationView : CSActivityView<FrameLayout> {
constructor(activity: CSActivity) : super(activity, layout(R.layout.cs_navigation))
constructor(parent: CSActivityView<out ViewGroup>)
: super(parent, layout(R.layout.cs_navigation))
private val controllersMap = linkedMapOf<String, CSActivityView<*>>()
val controllers get() = controllersMap.values
// WORKAROUND CODE:
// I had issue with EditText after focus when removed by pop,Activity.onBackPressed was never fired again
// Like if some events was go to removed view. This somehow helps I found that when I clear focus
// while still having edittext, problem is not there so this is ugly programmatic workaround
// simulating manual clear focus when closing view .
private var focusedView: View? = null
init {
onGlobalFocus { _, newFocus -> focusedView = newFocus }
}
fun <T : View> push(
controller: CSActivityView<T>,
pushId: String? = null
): CSActivityView<T> {
// logDebug { message(controller) }
val isFullScreen =
(controller as? CSNavigationItem)?.isFullscreenNavigationItem?.value ?: true
current?.showingInPager(!isFullScreen)
controllersMap[pushId ?: controller.toString()] = controller
pushAnimation(controller)
view.add(controller)
controller.showingInPager(true)
controller.lifecycleUpdate()
hideKeyboard()
onViewControllerPush()
return controller
}
fun pop(controller: CSActivityView<*>) {
// logDebug { message(controller) }
controllersMap.remove(controller.toString()).ifNull {
logWarnTrace { "Controller $controller not found in navigation" }
}.elseDo { popController(controller) }
}
fun pop() {
controllersMap.deleteLast().isNotNull { popController(it) }
}
private fun popController(controller: CSActivityView<*>) {
focusedView?.clearFocus()
popAnimation(controller)
controller.showingInPager(false)
view.remove(controller)
current?.showingInPager(true)
hideKeyboard()
onViewControllerPop()
}
fun <T : View> pushAsLast(controller: CSActivityView<T>): CSActivityView<T> {
controllersMap.deleteLast().isNotNull { lastController ->
popAnimation(controller)
view.remove(lastController)
onViewControllerPop()
}
controllersMap[controller.toString()] = controller
pushAnimation(controller)
view.add(controller)
controller.showingInPager(true)
controller.lifecycleUpdate()
hideKeyboard()
onViewControllerPush()
return controller
}
fun <T : View> push(
pushId: String,
controller: CSActivityView<T>
): CSActivityView<T> {
if (controllersMap.hasKey(pushId))
for (lastEntry in controllersMap.entries.reversed()) {
controllersMap.remove(lastEntry.key)
view.remove(lastEntry.value)
onViewControllerPop()
if (lastEntry.key == pushId) break
}
controllersMap[pushId] = controller
pushAnimation(controller)
view.add(controller)
controller.showingInPager(true)
controller.lifecycleUpdate()
hideKeyboard()
onViewControllerPush()
return controller
}
fun <T : View> replace(
oldController: CSActivityView<T>,
newController: CSActivityView<T>
): CSActivityView<T> {
if (current == oldController) return pushAsLast(newController)
val entryOfController = controllersMap.entries.find { it.value == oldController }
?: unexpected("oldController not found in navigation")
oldController.showingInPager(false)
view.remove(oldController)
onViewControllerPop()
controllersMap[entryOfController.key] = newController
val indexIfController = controllersMap.entries.indexOf(entryOfController)
view.addView(newController.view, indexIfController)
newController.showingInPager(true)
newController.lifecycleUpdate()
onViewControllerPush()
return newController
}
private val current get() = controllersMap.values.lastOrNull()
private val currentItem get() = current as? CSNavigationItem
private fun onViewControllerPush() = currentItem.onNotNull { it.onViewControllerPush(this) }
private fun onViewControllerPop() = currentItem.onNotNull { it.onViewControllerPop(this) }
override fun onGoBack(): Boolean {
if (controllers.size > 1) {
if (currentItem?.isNavigationBackPressedAllowed == false) return true
pop()
return false
}
return true
}
private fun pushAnimation(controller: CSActivityView<*>) {
val animation = (controller as? CSNavigationItem)?.pushAnimation ?: SlideInRight
if (animation != None)
controller.view.startAnimation(loadAnimation(this, animation.resource))
}
private fun popAnimation(controller: CSActivityView<*>) {
val animation = (controller as? CSNavigationItem)?.popAnimation ?: SlideOutLeft
if (animation != None)
controller.view.startAnimation(loadAnimation(this, animation.resource))
}
override var navigation: CSNavigationView?
get() = this
set(_) = unexpected()
} | 1 | null | 3 | 4 | 08336d1b88ff0646d3be53fd9f2b8e6a795d05f0 | 6,596 | renetik-android-framework | MIT License |
Android/ghvzApp/app/src/main/java/com/app/playhvz/firebase/viewmodels/PlayerRewardViewModel.kt | google | 95,704,578 | false | null | /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.app.playhvz.firebase.viewmodels
import android.util.Log
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import com.app.playhvz.app.HvzData
import com.app.playhvz.firebase.classmodels.Reward
import com.app.playhvz.firebase.operations.RewardDatabaseOperations
import com.app.playhvz.firebase.utils.DataConverterUtil
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.EventListener
class PlayerRewardViewModel : ViewModel() {
companion object {
private val TAG = PlayerRewardViewModel::class.qualifiedName
}
private var rewardIdList: HvzData<Map<String, Int>> = HvzData(mapOf())
private var rewardList: HvzData<Map<String, Pair<Reward?, Int>>> = HvzData(mapOf())
/** Listens to a player's reward updates and returns a LiveData object. */
fun getPlayersRewards(
lifecycleOwner: LifecycleOwner,
gameId: String,
updatedRewardIdMap: Map<String, Int>
): LiveData<Map<String, Pair<Reward?, Int>>> {
if (!rewardIdList.hasObservers()) {
// Listen to updates to the list of rewards we should observe
rewardIdList.observe(
lifecycleOwner,
androidx.lifecycle.Observer { updatedRewardIds ->
observeRewards(gameId, updatedRewardIds)
})
}
// Diff and update the list of rewards we should observe based on the updated list.
if (rewardIdList.value != null) {
// Remove reward listeners for rewards the user doesn't have anymore.
val removedRewards =
rewardIdList.value!!.keys.toSet().minus(updatedRewardIdMap.keys.toSet())
stopListening(removedRewards)
}
rewardIdList.value = updatedRewardIdMap
return rewardList
}
/** Listens to updates on every chat room the player is a member of. */
private fun observeRewards(
gameId: String,
updatedRewardIdList: Map<String, Int>
) {
for ((rewardId, count) in updatedRewardIdList) {
// Check if count updated.
if (rewardList.value != null && count != rewardList.value!![rewardId]?.second) {
val updatedRewardList = rewardList.value!!.toMutableMap()
updatedRewardList[rewardId] = Pair(updatedRewardList[rewardId]?.first, count)
rewardList.value = updatedRewardList
}
// Listen to reward document updates.
if (rewardId in rewardList.docIdListeners) {
// We're already listening to this reward
continue
}
rewardList.docIdListeners[rewardId] =
RewardDatabaseOperations.getRewardDocumentReference(gameId, rewardId)
.addSnapshotListener(
EventListener<DocumentSnapshot> { snapshot, e ->
if (e != null) {
Log.w(TAG, "Reward listen failed. ", e)
return@EventListener
}
if (snapshot == null || !snapshot.exists()) {
val updatedRewardList = rewardList.value!!.toMutableMap()
updatedRewardList.remove(rewardId)
rewardList.value = updatedRewardList
stopListening(setOf(rewardId))
return@EventListener
}
val updatedReward =
DataConverterUtil.convertSnapshotToReward(snapshot)
val updatedRewardList = rewardList.value!!.toMutableMap()
updatedRewardList[rewardId] = Pair(updatedReward, count)
rewardList.value = updatedRewardList
})
}
}
private fun stopListening(removedIds: Set<String>) {
for (removedId in removedIds) {
if (!rewardList.docIdListeners.containsKey(removedId)) {
continue
}
rewardList.docIdListeners[removedId]?.remove()
rewardList.docIdListeners.remove(removedId)
}
}
} | 37 | Kotlin | 30 | 24 | 9e02fb706af61a336bda852f467a35f49bdcfec7 | 4,936 | playhvz | Apache License 2.0 |
libraries/stdlib/src/kotlin/modules/AllModules.kt | chashnikov | 14,658,474 | false | null | package kotlin.modules
import java.util.ArrayList
object AllModules : ThreadLocal<ArrayList<Module>>() {
override fun initialValue() = ArrayList<Module>()
}
| 0 | null | 0 | 1 | 88a261234860ff0014e3c2dd8e64072c685d442d | 163 | kotlin | Apache License 2.0 |
idea/src/org/jetbrains/kotlin/idea/intentions/ToRawStringLiteralIntention.kt | arrow-kt | 109,678,056 | false | null | /*
* Copyright 2010-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.
*/
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.text.StringUtilRt
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.psi.KtEscapeStringTemplateEntry
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtStringTemplateEntry
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class ToRawStringLiteralIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>(
KtStringTemplateExpression::class.java,
"To raw string literal"
), LowPriorityAction {
override fun isApplicableTo(element: KtStringTemplateExpression): Boolean {
val text = element.text
if (text.startsWith("\"\"\"")) return false // already raw
val escapeEntries = element.entries.filterIsInstance<KtEscapeStringTemplateEntry>()
for (entry in escapeEntries) {
val c = entry.unescapedValue.singleOrNull() ?: return false
if (Character.isISOControl(c) && c != '\n' && c != '\r') return false
}
val converted = convertContent(element)
return !converted.contains("\"\"\"") && !hasTrailingSpaces(converted)
}
override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) {
val startOffset = element.startOffset
val endOffset = element.endOffset
val currentOffset = editor?.caretModel?.currentCaret?.offset ?: startOffset
val text = convertContent(element)
val replaced = element.replaced(KtPsiFactory(element).createExpression("\"\"\"" + text + "\"\"\""))
val offset = when {
startOffset == currentOffset -> startOffset
endOffset == currentOffset -> replaced.endOffset
else -> minOf(currentOffset + 2, replaced.endOffset)
}
editor?.caretModel?.moveToOffset(offset)
}
private fun convertContent(element: KtStringTemplateExpression): String {
val text = buildString {
val entries = element.entries
for ((index, entry) in entries.withIndex()) {
val value = entry.value()
if (value.endsWith("$") && index < entries.size - 1) {
val nextChar = entries[index + 1].value().first()
if (nextChar.isJavaIdentifierStart() || nextChar == '{') {
append("\${\"$\"}")
continue
}
}
append(value)
}
}
return StringUtilRt.convertLineSeparators(text, "\n")
}
private fun hasTrailingSpaces(text: String): Boolean {
var afterSpace = true
for (c in text) {
if ((c == '\n' || c == '\r') && afterSpace) return true
afterSpace = c == ' ' || c == '\t'
}
return false
}
private fun KtStringTemplateEntry.value() = if (this is KtEscapeStringTemplateEntry) this.unescapedValue else text
} | 12 | null | 1 | 43 | d2a24985b602e5f708e199aa58ece652a4b0ea48 | 3,763 | kotlin | Apache License 2.0 |
ultimate/src/org/jetbrains/kotlin/idea/jam/KotlinJamReferenceContributor.kt | gigliovale | 89,726,097 | false | {"Java": 23302590, "Kotlin": 21941511, "JavaScript": 137521, "Protocol Buffer": 56992, "HTML": 49980, "Lex": 18051, "Groovy": 14093, "ANTLR": 9797, "IDL": 7706, "Shell": 5152, "CSS": 4679, "Batchfile": 3721} | package org.jetbrains.kotlin.idea.jam
import com.intellij.codeInsight.completion.CompletionUtil
import com.intellij.jam.JamService
import com.intellij.jam.JamStringAttributeElement
import com.intellij.jam.reflect.JamStringAttributeMeta
import com.intellij.psi.PsiElementRef
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceRegistrar
import com.intellij.util.SmartList
import org.jetbrains.kotlin.asJava.toLightAnnotation
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.references.AbstractKotlinReferenceContributor
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.psiUtil.isPlain
import org.jetbrains.kotlin.psi.psiUtil.parents
// Based on the JamReferenceContributor
class KotlinJamReferenceContributor : AbstractKotlinReferenceContributor() {
@Suppress("UNCHECKED_CAST")
override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) {
registrar.registerMultiProvider<KtStringTemplateExpression> { expression ->
if (!expression.isPlain()) return@registerMultiProvider PsiReference.EMPTY_ARRAY
val argument = expression
.parents
.filterIsInstance<KtValueArgument>()
.firstOrNull() { it.parent?.parent is KtAnnotationEntry } ?: return@registerMultiProvider PsiReference.EMPTY_ARRAY
val annotationEntry = argument.parent.parent as KtAnnotationEntry
val lightAnnotation = (CompletionUtil.getOriginalOrSelf(annotationEntry)).toLightAnnotation()
?: return@registerMultiProvider PsiReference.EMPTY_ARRAY
val service = JamService.getJamService(expression.project)
val annotationMeta = service.getMeta(lightAnnotation)
?: return@registerMultiProvider PsiReference.EMPTY_ARRAY
val attributeName = argument.getArgumentName()?.asName?.asString()
val attribute = annotationMeta.findAttribute(attributeName) as? JamStringAttributeMeta<Any, Any>
?: return@registerMultiProvider PsiReference.EMPTY_ARRAY
val jam = attribute.getJam(PsiElementRef.real(lightAnnotation))
val converter = attribute.converter
when (jam) {
is JamStringAttributeElement<*> -> converter.createReferences(jam as JamStringAttributeElement<Any>)
is List<*> -> {
val list = SmartList<PsiReference>()
for (item in jam) {
val jamElement = item as? JamStringAttributeElement<Any> ?: continue
if (jamElement.psiElement?.unwrapped != expression) continue
list += converter.createReferences(jamElement)
}
list.toTypedArray()
}
else -> PsiReference.EMPTY_ARRAY
}
}
}
}
| 0 | Java | 4 | 6 | ce145c015d6461c840050934f2200dbc11cb3d92 | 3,115 | kotlin | Apache License 2.0 |
presentation/src/main/java/com/x/presentation/ui/composable/NavigationBar.kt | ResulSilay | 469,322,755 | false | {"Kotlin": 403160} | package com.x.presentation.ui.composable
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.navigation.NavController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.x.presentation.navigation.NavigationBarItem
import com.x.presentation.ui.theme.ProvideRippleEffect
import com.x.presentation.ui.theme.Theme
import com.x.presentation.util.getString
@Composable
fun BottomNavigationBar(
barItems: List<NavigationBarItem>,
navController: NavController,
) {
NavigationBar(
containerColor = Theme.colors.surface,
contentColor = contentColorFor(Theme.colors.surface)
) {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
barItems.forEach { item ->
ProvideRippleEffect {
NavigationBarItem(
icon = {
Icon(
imageVector = item.icon,
contentDescription = item.title.getString()
)
},
label = {
Text(
text = item.title.getString()
)
},
selected = currentRoute == item.route,
alwaysShowLabel = false,
onClick = {
navController.navigate(item.route) {
navController.graph.startDestinationRoute?.let { route ->
popUpTo(route) {
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
}
)
}
}
}
}
| 0 | Kotlin | 1 | 14 | 4648b4e6fdbaf60631c9a203cefd51beef370f71 | 2,004 | jenci | Apache License 2.0 |
app/src/test/kotlin/net/yuzumone/sdnmonitor/ExampleUnitTest.kt | yuzumone | 73,555,179 | false | null | package net.yuzumone.sdnmonitor
import org.junit.Test
import org.junit.Assert.*
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
class ExampleUnitTest {
@Test
@Throws(Exception::class)
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | 0 | Kotlin | 0 | 1 | fec09b1b2db0dde88aa98124d37f327abe66d94c | 302 | SDNMonitor | Apache License 2.0 |
src/main/kotlin/de/tweerlei/plumber/pipeline/steps/aggregate/FirstStep.kt | tweerlei | 450,150,451 | false | {"Kotlin": 910444, "Shell": 2267, "Dockerfile": 732} | /*
* Copyright 2022 <NAME> + Buchmeier GbR - http://www.tweerlei.de/
*
* 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 de.tweerlei.plumber.pipeline.steps.aggregate
import de.tweerlei.plumber.pipeline.PipelineParams
import de.tweerlei.plumber.pipeline.steps.ProcessingStep
import de.tweerlei.plumber.worker.Worker
import de.tweerlei.plumber.worker.impl.aggregate.FirstWorker
import org.springframework.stereotype.Service
@Service("firstWorker")
class FirstStep: ProcessingStep {
override val group = "Aggregation"
override val name = "Take first item"
override val description = "Pass only the very first item on to next steps"
override val help = ""
override val options = ""
override val example = """
files-list
find:'^a.*' filter
first
lines-write # result: first file name starting with 'a'
""".trimIndent()
override val argDescription = ""
override val argInterpolated = false
override fun parallelDegreeFor(arg: String) = 1
override fun createWorker(
arg: String,
w: Worker,
predecessorName: String,
params: PipelineParams,
parallelDegree: Int
) =
FirstWorker(w)
}
| 0 | Kotlin | 0 | 2 | 78facf6e0675dee1ff0de976cdb3397744890892 | 1,725 | plumber | Apache License 2.0 |
client/app/src/main/java/com/rh/heji/widget/DividerItemDecorator.kt | RUANHAOANDROID | 324,589,079 | false | null | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hao.heji.widget
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
class DividerItemDecorator(private val mDivider: Drawable) : ItemDecoration() {
override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val dividerLeft = parent.paddingLeft
val dividerRight = parent.width - parent.paddingRight
val childCount = parent.childCount
for (i in 0..childCount - 2) {
val child: View = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val dividerTop: Int = child.bottom + params.bottomMargin
val dividerBottom = dividerTop + mDivider.intrinsicHeight
mDivider.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom)
mDivider.draw(canvas)
}
}
} | 0 | Kotlin | 2 | 7 | 38d7d743b34ac09e08682f00e0442dd6d1e16b49 | 1,621 | heji | Apache License 2.0 |
src/test/resources/examples/enumPolymorphicDiscriminator/models/DiscriminatedChild1.kt | cjbooms | 229,844,927 | false | {"Kotlin": 874094, "Handlebars": 4874} | package examples.enumPolymorphicDiscriminator.models
import com.fasterxml.jackson.`annotation`.JsonProperty
import javax.validation.Valid
import javax.validation.constraints.NotNull
import kotlin.String
import kotlin.collections.List
public data class DiscriminatedChild1(
@param:JsonProperty("inline_obj")
@get:JsonProperty("inline_obj")
@get:Valid
override val inlineObj: ChildDefinitionInlineObj? = null,
@param:JsonProperty("inline_array")
@get:JsonProperty("inline_array")
@get:Valid
override val inlineArray: List<ChildDefinitionInlineArray>? = null,
@param:JsonProperty("inline_enum")
@get:JsonProperty("inline_enum")
override val inlineEnum: ChildDefinitionInlineEnum? = null,
@param:JsonProperty("some_prop")
@get:JsonProperty("some_prop")
public val someProp: String? = null,
@get:JsonProperty("some_enum")
@get:NotNull
@param:JsonProperty("some_enum")
override val someEnum: ChildDiscriminator = ChildDiscriminator.OBJ_ONE_ONLY,
) : ChildDefinition(inlineObj, inlineArray, inlineEnum)
| 33 | Kotlin | 41 | 154 | b95cb5bd8bb81e59eca71e467118cd61a1848b3f | 1,034 | fabrikt | Apache License 2.0 |
app/src/main/java/com/keke125/vaultguard/activity/AuthSettingActivity.kt | keke125 | 784,177,444 | false | {"Kotlin": 347596, "Ruby": 882} | package com.keke125.vaultguard.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_WEAK
import androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.app.ActivityCompat.startActivityForResult
import androidx.fragment.app.FragmentActivity
import com.keke125.vaultguard.R
import com.keke125.vaultguard.model.AppViewModelProvider
import com.keke125.vaultguard.model.BiometricAuthSettingViewModel
import com.keke125.vaultguard.ui.theme.VaultGuardTheme
class AuthSettingActivity : AppCompatActivity() {
private val biometricAuthSettingViewModel: BiometricAuthSettingViewModel by viewModels(
factoryProducer = { AppViewModelProvider.Factory })
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
VaultGuardTheme {
Surface(
modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background
) {
BiometricAuthSettingScreen(this, biometricAuthSettingViewModel)
}
}
}
}
@Deprecated(
"This method has been deprecated in favor of using the Activity Result API\n which brings increased type safety via an {@link ActivityResultContract} and the prebuilt\n contracts for common intents available in\n {@link androidx.activity.result.contract.ActivityResultContracts}, provides hooks for\n testing, and allow receiving results in separate, testable classes independent from your\n activity. Use\n {@link #registerForActivityResult(ActivityResultContract, ActivityResultCallback)}\n with the appropriate {@link ActivityResultContract} and handling the result in the\n {@link ActivityResultCallback#onActivityResult(Object) callback}.",
ReplaceWith(
"super.onActivityResult()", "androidx.appcompat.app.AppCompatActivity"
)
)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 100) {
val biometricManager = BiometricManager.from(this)
biometricAuthSettingViewModel.updateCanAuthenticateWithBiometrics(
when (biometricManager.canAuthenticate(BIOMETRIC_STRONG or BIOMETRIC_WEAK or DEVICE_CREDENTIAL)) {
BiometricManager.BIOMETRIC_SUCCESS -> {
biometricAuthSettingViewModel.updateBiometricEnabled(true)
true
}
BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
false
}
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
false
}
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
Toast.makeText(this, getString(R.string.app_biometric_not_registered), Toast.LENGTH_LONG).show()
false
}
else -> {
false
}
}
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BiometricAuthSettingScreen(context: Context, viewModel: BiometricAuthSettingViewModel) {
val activity = context as? Activity
Scaffold(topBar = {
TopAppBar(colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
titleContentColor = MaterialTheme.colorScheme.primary,
), title = { Text(stringResource(id = R.string.app_security_setting)) }, navigationIcon = {
IconButton(onClick = {
activity?.finish()
}) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, "")
}
})
}) { innerPadding ->
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
.padding(innerPadding)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
val biometricManager = BiometricManager.from(context)
val uiState = viewModel.uiState.collectAsState()
val (isPromptBiometricEnabled, onPromptBiometricEnabledChange) = remember {
mutableStateOf(false)
}
val enrollIntent: Intent = if (Build.VERSION.SDK_INT >= 30) {
Intent(Settings.ACTION_BIOMETRIC_ENROLL).apply {
putExtra(
Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
BIOMETRIC_STRONG or DEVICE_CREDENTIAL or BIOMETRIC_WEAK
)
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Intent(Settings.ACTION_FINGERPRINT_ENROLL)
} else {
Intent(Settings.ACTION_SECURITY_SETTINGS)
}
}
ListItem(headlineContent = { Text(stringResource(id = R.string.app_change_main_pw)) },
modifier = Modifier.clickable {
context.startActivity(Intent(context, ChangeMainPasswordActivity::class.java))
}
)
HorizontalDivider()
ListItem(headlineContent = {
Row(verticalAlignment = Alignment.CenterVertically) {
Switch(checked = uiState.value.isBiometricEnabled, onCheckedChange = {
if (it) {
viewModel.updateCanAuthenticateWithBiometrics(
when (biometricManager.canAuthenticate(BIOMETRIC_STRONG or DEVICE_CREDENTIAL or BIOMETRIC_WEAK)) {
BiometricManager.BIOMETRIC_SUCCESS -> {
Log.d(
"VaultGuard", "App can authenticate using biometrics."
)
viewModel.updateBiometricEnabled(true)
true
}
BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
Log.e(
"VaultGuard",
"No biometric features available on this device."
)
Toast.makeText(
context, context.getString(R.string.app_biometric_unavailable), Toast.LENGTH_LONG
).show()
viewModel.updateBiometricEnabled(false)
false
}
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
Log.e(
"VaultGuard",
"Biometric features are currently unavailable."
)
Toast.makeText(
context, context.getString(R.string.app_biometric_temp_unavailable), Toast.LENGTH_LONG
).show()
viewModel.updateBiometricEnabled(false)
false
}
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
onPromptBiometricEnabledChange(true)
false
}
else -> {
Toast.makeText(context, context.getString(R.string.app_biometric_error), Toast.LENGTH_LONG)
.show()
false
}
}
)
} else {
viewModel.updateBiometricEnabled(false)
}
})
Spacer(modifier = Modifier.padding(horizontal = 8.dp))
Text(text = stringResource(id = R.string.app_use_biometric))
}
})
HorizontalDivider()
when {
isPromptBiometricEnabled -> {
PromptBiometricDialogConfirm(onDismissRequest = {
onPromptBiometricEnabledChange(
false
)
}, onPromptBiometricResultChange = {
startActivityForResult(
context as FragmentActivity, enrollIntent, 100, null
)
}, context = context)
}
}
}
}
}
@Composable
fun PromptBiometricDialogConfirm(
onDismissRequest: () -> Unit, onPromptBiometricResultChange: () -> Unit, context: Context
) {
AlertDialog(icon = {
Icon(Icons.Default.Info, stringResource(id = R.string.app_info))
}, title = {
Text(text = stringResource(id = R.string.app_ask_biometric))
}, text = {
Text(text = stringResource(id = R.string.app_ask_biometric_des))
}, onDismissRequest = {
onDismissRequest()
}, confirmButton = {
TextButton(onClick = {
onPromptBiometricResultChange()
onDismissRequest()
}) {
Text(stringResource(id = R.string.app_confirm))
}
}, dismissButton = {
TextButton(onClick = {
onDismissRequest()
Toast.makeText(context, context.getString(R.string.app_biometric_not_registered), Toast.LENGTH_LONG).show()
}) {
Text(stringResource(id = R.string.app_cancel))
}
})
} | 0 | Kotlin | 0 | 1 | 88dcf6d1ab5de4b5a094f86fa4355a2f6a663415 | 12,368 | VaultGuard | MIT License |
core/repository/src/main/java/city/zouitel/repository/model/Root.kt | City-Zouitel | 576,223,915 | false | {"Kotlin": 491074} | package city.zouitel.repository.model
import androidx.annotation.Keep
@Keep
data class Root(val isDeviceRooted: Boolean)
| 37 | Kotlin | 12 | 94 | 279f774769be23f897c75028f68f93b997a86319 | 123 | JetNote | Apache License 2.0 |
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Boyer_Moore_Algorithm/Boyer_Moore.kt | rajatenzyme | 325,100,742 | false | {"C++": 709855, "Java": 559443, "Python": 397216, "C": 381274, "Jupyter Notebook": 127469, "Go": 123745, "Dart": 118962, "JavaScript": 109884, "C#": 109817, "Ruby": 86344, "PHP": 63402, "Kotlin": 52237, "TypeScript": 21623, "Rust": 20123, "CoffeeScript": 13585, "Julia": 2385, "Shell": 506, "Erlang": 385, "Scala": 310, "Clojure": 189} | /*
Boyer Moore String Matching Algorithm in Kotlin
Author: <NAME> (@darkmatter18)
*/
import java.util.*
internal object Main {
private var NO_OF_CHARACTERS = 256
private fun maxOfAAndB(a: Int, b: Int): Int {
return a.coerceAtLeast(b)
}
private fun badCharacterHeuristic(str: CharArray, size: Int, badcharacter: IntArray) {
// Initialize all elements of bad character as -1
var i = 0
while (i < NO_OF_CHARACTERS) {
badcharacter[i] = -1
i++
}
// Fill the actual value of last occurrence of a character
i = 0
while (i < size) {
badcharacter[str[i].toInt()] = i
i++
}
}
// A pattern searching function
private fun search(text: CharArray, pattern: CharArray) {
val m = pattern.size
val n = text.size
val badCharacterHeuristic = IntArray(NO_OF_CHARACTERS)
// Fill the bad character array by calling the preprocessing function
badCharacterHeuristic(pattern, m, badCharacterHeuristic)
// s is shift of the pattern with respect to text
var s = 0
while (s <= n - m) {
var j = m - 1
// Keep reducing index j of pattern while characters of pattern and text are matching at this shift s
while (j >= 0 && pattern[j] == text[s + j]) j--
// If the pattern is present at current shift, then index j will become -1 after the above loop
s += if (j < 0) {
println("Patterns occur at shift = $s")
// Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern.
// The condition s+m < n is necessary for the case when pattern occurs at the end of text
if (s + m < n) m - badCharacterHeuristic[text[s + m].toInt()] else 1
} else maxOfAAndB(1, j - badCharacterHeuristic[text[s + j].toInt()])
}
}
/* Driver program*/
@JvmStatic
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
var s = sc.nextLine()
val text = s.toCharArray()
s = sc.nextLine()
val pattern = s.toCharArray()
search(text, pattern)
}
}
/*
Sample Input:
AABAACAADAABAABA
AABA
Sample Output:
Patterns occur at shift = 0
Patterns occur at shift = 9
Patterns occur at shift = 12
*/
| 0 | C++ | 0 | 0 | 65a0570153b7e3393d78352e78fb2111223049f3 | 2,414 | Coding-Journey | MIT License |
applications/data-analyzer-server/src/main/kotlin/com/goodboards/app/analyzer/tasks/Wrapper.kt | CSCI-5828-Foundations-Sftware-Engr | 614,026,505 | false | null | package com.goodboards.app.analyzer.tasks
import com.goodboards.app.analyzer.AnalyzerWorkFinder
import com.goodboards.app.analyzer.AnalyzerWorker
object Wrapper {
fun getAnalyzerWorkFinder(): AnalyzerWorkFinder{
return AnalyzerWorkFinder()
}
fun getAnalyzerWorker(): AnalyzerWorker{
return AnalyzerWorker()
}
} | 38 | Kotlin | 1 | 2 | 7b6f00de4f9bd906f1e2d12a414228bd67edbf58 | 345 | slackers | Apache License 2.0 |
app/src/main/java/com/comunidadedevspace/taskbeats/presentation/MainActivity.kt | RenanPdeOliveira | 615,246,251 | false | null | package com.comunidadedevspace.taskbeats.presentation
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import com.comunidadedevspace.taskbeats.R
import com.google.android.material.bottomappbar.BottomAppBar
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.floatingactionbutton.FloatingActionButton
class MainActivity : AppCompatActivity() {
private lateinit var bottomAppBar: BottomAppBar
private lateinit var bottomNavigation: BottomNavigationView
private lateinit var fabAdd: FloatingActionButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bottomAppBar = findViewById(R.id.bottomAppBar)
bottomNavigation = findViewById(R.id.bottomNavigationView)
fabAdd = findViewById(R.id.fabAdd)
bottomNavigation.background = null
bottomNavigation.menu.getItem(1).isEnabled = false
fabAdd.setOnClickListener {
openTaskDetail()
}
val taskListFragment = TaskListFragment.newInstance()
val newsListFragment = NewsListFragment.newInstance()
defautFragment(taskListFragment)
bottomNavigation.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.listButton -> {
showFragment(taskListFragment)
true
}
R.id.newsButton -> {
showFragment(newsListFragment)
true
}
else -> false
}
}
}
private fun openTaskDetail() {
val intent = TaskListDetailActivity.start(this, null)
startActivity(intent)
}
private fun showFragment(fragment: Fragment) {
supportFragmentManager.commit {
replace(R.id.fragmentContainerView, fragment)
setReorderingAllowed(true)
addToBackStack(null)
}
}
private fun defautFragment(fragment: Fragment) {
supportFragmentManager.commit {
replace(R.id.fragmentContainerView, fragment)
setReorderingAllowed(true)
}
}
} | 0 | Kotlin | 0 | 0 | 70b5a624336d696f0ae092e138a0532e3a1cca06 | 2,329 | TaskBeats | The Unlicense |
app/src/main/java/com/herdal/videogamehub/presentation/game_detail/adapter/screenshot/ScreenshotAdapter.kt | herdal06 | 600,232,493 | false | null | package com.herdal.videogamehub.presentation.game_detail.adapter.screenshot
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.herdal.videogamehub.common.base.BaseListAdapter
import com.herdal.videogamehub.databinding.ItemScreenshotBinding
import com.herdal.videogamehub.domain.ui_model.ScreenshotUiModel
class ScreenshotAdapter(
) : BaseListAdapter<ScreenshotUiModel>(
itemsSame = { old, new -> old.id == new.id },
contentsSame = { old, new -> old == new }
) {
override fun onCreateViewHolder(
parent: ViewGroup,
inflater: LayoutInflater,
viewType: Int
): RecyclerView.ViewHolder =
ScreenshotViewHolder(
ItemScreenshotBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is ScreenshotViewHolder -> {
getItem(position)?.let { screenshot -> holder.bind(screenshot) }
}
}
}
} | 0 | Kotlin | 0 | 0 | 590195ced5471f08a58f8d7052a9633bff8c4d68 | 1,157 | VideoGameHub | Apache License 2.0 |
src/jsMain/kotlin/io/dcctech/mafita/frontend/browser/pages/Dashboard.kt | timoterik | 587,234,059 | false | {"Kotlin": 82347, "JavaScript": 856, "HTML": 776, "Dockerfile": 335} | /*
* Copyright © 2022-2023, DCCTech, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.dcctech.mafita.frontend.browser.pages
import io.dcctech.mafita.frontend.browser.resources.appStyles
import zakadabar.core.browser.page.ZkPage
import zakadabar.core.browser.util.plusAssign
object Dashboard : ZkPage() {
override fun onCreate() {
classList += appStyles.home
}
} | 0 | Kotlin | 0 | 0 | 52de5d4146e3da08ca1014abc46a820ad1c2ae00 | 436 | mafita | Apache License 2.0 |
util/src/main/java/com/guerinet/suitcase/util/extensions/ContextExt.kt | aiavci | 144,017,050 | false | null | /*
* Copyright 2016-2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.guerinet.suitcase.util.extensions
import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.LocaleList
import android.support.annotation.ColorRes
import android.support.annotation.DrawableRes
import android.support.customtabs.CustomTabsIntent
import android.support.v4.content.ContextCompat
import com.guerinet.suitcase.util.Device
import java.io.File
import java.util.*
/**
* [Context] extensions
* @author <NAME>
* @since 2.3.0
*/
/**
* Returns a [color] from the resources in a backwards-compatible manner
*/
fun Context.getColorCompat(@ColorRes color: Int) = ContextCompat.getColor(this, color)
/**
* Opens the given [url]
*/
fun Context.openUrl(url: String) {
// Check that http:// or https:// is there
val fullUrl = if (! url.startsWith("http://", true) && ! url.startsWith("https://", true)) {
"http://$url"
} else {
url
}
startActivity(Intent(Intent.ACTION_VIEW).setData(Uri.parse(fullUrl)))
}
/**
* Opens a Chrome custom tab when opening a [url] with a default share option.
* Optionally sets the [toolbarColor] (it's a light grey if none supplied) and uses the Drawable
* [closeButtonId] to set a custom close button (it's a black cross if none supplied)
*/
fun Context.openCustomTab(url: String, @ColorRes toolbarColor: Int? = null,
@DrawableRes closeButtonId: Int? = null) {
// Check that the scheme is present, add it if not
val fullUrl = if (! url.startsWith("http://", true) && ! url.startsWith("https://", true)) {
"http://$url"
} else {
url
}
val builder = CustomTabsIntent.Builder()
.addDefaultShareMenuItem()
if (toolbarColor != null) {
// Set the custom toolbar color if there is one
builder.setToolbarColor(ContextCompat.getColor(this, toolbarColor))
}
if (closeButtonId != null) {
// Set the custom close button icon if there is one
builder.setCloseButtonIcon(BitmapFactory.decodeResource(this.resources, closeButtonId))
}
// Build and launch
builder.build().launchUrl(this, Uri.parse(fullUrl))
}
/**
* Attempts to open the Pdf at the given [path]
* @throws ActivityNotFoundException if no app to open the pdf is found
*/
@Throws(ActivityNotFoundException::class)
fun Context.openPdf(path: Uri) {
// Check if there is a Pdf reader
val packageManager = packageManager
val pdfIntent = Intent(Intent.ACTION_VIEW).setType("application/pdf")
val list = packageManager.queryIntentActivities(pdfIntent, PackageManager.MATCH_DEFAULT_ONLY)
if (list.isNotEmpty()) {
// If there is one, use it
val intent = Intent(Intent.ACTION_VIEW)
.setDataAndType(path, "application/pdf")
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(intent)
} else {
// If not, throw the exception
throw ActivityNotFoundException("No Pdf app found")
}
}
/**
* Opens an app by its [packageName] in the Play Store or in the browser
* (if the Play Store is not found)
*/
fun Context.openPlayStoreApp(packageName: String = this.packageName) {
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName")))
} catch (e: ActivityNotFoundException) {
// If the user does not have the Play Store installed, open it in their browser
openUrl("https://play.google.com/store/app/details?id=$packageName")
}
}
/**
* Returns the resource id for a given [attributeId] to set an attribute programmatically (0 if not
* found)
*/
fun Context.getAttributeResourceId(attributeId: Int): Int {
// Get the attribute in types array form
val typedArray = obtainStyledAttributes(intArrayOf(attributeId))
// Extract the resource Id
val resource = typedArray.getResourceId(0, 0)
// Recycle the typed array
typedArray.recycle()
return resource
}
/**
* Returns the resource Id of the given [type] for the given [id] name
*/
fun Context.getResourceId(type: String, id: String): Int =
resources.getIdentifier(id, type, packageName)
/**
* Returns a file (or folder if [isFolder] is true) with the given [name] and [type] (null if it
* does not have a specific type, defaults to null).
* This will create the file/folder if it doesn't exist already.
*/
fun Context.getFile(isFolder: Boolean, name: String, type: String? = null): File {
val file = File(getExternalFilesDir(type), name)
if (!isFolder && !file.exists()) {
// If it's supposed to be a file and it doesn't exist, create it
file.createNewFile()
} else if (isFolder && (!file.exists() || !file.isDirectory)) {
// If it's supposed to be a folder and it doesn't exist or isn't a folder, create it
file.mkdirs()
}
return file
}
/**
* Returns true if the given [permission] is granted
*/
fun Context.isPermissionGranted(permission: String): Boolean =
ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
/**
* True if the device is connected to the internet, false otherwise
*/
val Context.isConnected: Boolean
get() = (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).isConnected
/**
* Wraps the current context with a [language] change and returns the corresponding [ContextWrapper]
*/
fun Context.wrapWithLanguage(language: String): ContextWrapper {
val locale = Locale(language)
val configuration = resources.configuration
configuration.setLocale(locale)
if (Device.isAtLeastNougat()) {
val localeList = LocaleList(locale)
LocaleList.setDefault(localeList)
configuration.locales = localeList
}
return ContextWrapper(createConfigurationContext(configuration))
}
/**
* Creates a debug String that can be attached to feedback or bug reports. The String contains
* the device model, sdk version, app [versionName], app [versionCode], language, connection type,
* and any [customInfo] passed (defaults to an empty String)
*/
fun Context.getDebugInfo(versionName: String, versionCode: Int, customInfo: String = ""): String {
@SuppressLint("MissingPermission")
val info = (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)
.activeNetworkInfo
val connection = if (info != null) {
"${info.typeName} ${info.subtypeName}"
} else {
"N/A"
}
return "===============" +
"\nDebug Info" +
"\n===============" +
"\nDevice: ${Device.model()}" +
"\nSDK Version: ${Build.VERSION.SDK_INT}" +
"\nApp Version: $versionName" +
"\nBuild Number: $versionCode" +
"\nLanguage: ${Locale.getDefault().language}" +
"\nConnection Type: $connection" +
(if (customInfo.isNotBlank()) "\n$customInfo" else "") +
"\n===============\n\n"
} | 1 | null | 1 | 1 | 491ac5ed2981dbd7f6c60075b1c45134edebed08 | 7,884 | Suitcase | Apache License 2.0 |
app/src/main/java/com/m/coroutines/delay/delay.kt | ma-jian | 164,124,939 | false | null | package com.m.coroutines.delay
import java.util.concurrent.*
import kotlin.coroutines.*
private val executor = Executors.newSingleThreadScheduledExecutor {
Thread(it, "scheduler").apply { isDaemon = true }
}
suspend fun delay(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS): Unit = suspendCoroutine { cont ->
executor.schedule({ cont.resume(Unit) }, time, unit)
}
| 0 | null | 2 | 19 | 0e049e5f2110c6165a4072b18caa9825cbfcbb6f | 379 | MvvmKotlin | Apache License 2.0 |
library/src/main/java/com/schibsted/spain/barista/interaction/BaristaMenuClickInteractions.kt | karadkar | 189,949,935 | false | null | package com.schibsted.spain.barista.interaction
import androidx.annotation.IdRes
import androidx.test.InstrumentationRegistry
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu
import androidx.test.espresso.NoMatchingViewException
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.matcher.RootMatchers.isPlatformPopup
import androidx.test.espresso.matcher.ViewMatchers.withContentDescription
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import android.view.View
import com.schibsted.spain.barista.internal.failurehandler.SpyFailureHandler
import com.schibsted.spain.barista.internal.failurehandler.withFailureHandler
import com.schibsted.spain.barista.internal.matcher.DisplayedMatchers.displayedAnd
import com.schibsted.spain.barista.internal.matcher.HelperMatchers.menuIdMatcher
import org.hamcrest.Matcher
import org.hamcrest.Matchers.hasToString
object BaristaMenuClickInteractions {
@JvmStatic
fun clickMenu(@IdRes id: Int) {
val spyFailureHandler = SpyFailureHandler()
try {
clickDisplayedView(withId(id), spyFailureHandler)
} catch (noMatchingViewException: NoMatchingViewException) {
try {
clickOverflowListMenu(menuIdMatcher(id), spyFailureHandler)
} catch (error: Exception) {
spyFailureHandler.resendFirstError("Could not click on menu id, neither as action or overflow")
}
}
}
@JvmStatic
fun clickMenu(text: String) {
val spyFailureHandler = SpyFailureHandler()
try {
clickDisplayedView(withText(text), spyFailureHandler)
} catch (noMatchingViewException: NoMatchingViewException) {
try {
clickViewWithDescription(text, spyFailureHandler)
} catch (noMatchingViewByTextException: NoMatchingViewException) {
try {
clickOverflowListMenu(hasToString<String>(text), spyFailureHandler)
} catch (error: Exception) {
spyFailureHandler.resendFirstError("Could not click on menu title <$text>, neither as action or overflow")
}
}
}
}
@JvmStatic
fun openMenu() {
openOverflow()
}
private fun clickDisplayedView(matcher: Matcher<View>, spyFailureHandler: SpyFailureHandler) {
onView(displayedAnd(matcher)).withFailureHandler(spyFailureHandler).perform(click())
}
private fun clickViewWithDescription(text: String, spyFailureHandler: SpyFailureHandler) {
onView(displayedAnd(withContentDescription(text))).withFailureHandler(spyFailureHandler).perform(click())
}
private fun clickOverflowListMenu(itemMatcher: Matcher<*>, spyFailureHandler: SpyFailureHandler) {
openOverflow()
withFailureHandler(spyFailureHandler) {
onData(itemMatcher).inRoot(isPlatformPopup()).perform(click())
}
}
private fun openOverflow() {
openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getTargetContext())
}
}
| 1 | null | 1 | 1 | a3a93053bc6f0d90288aa30688e93ee49cba8597 | 3,043 | Barista | Apache License 2.0 |
src/main/kotlin/com/glinboy/cities/service/impl/CountryServiceImpl.kt | GLinBoy | 464,566,966 | false | {"Kotlin": 19353, "Dockerfile": 735} | package com.glinboy.cities.service.impl
import com.glinboy.cities.entity.City
import com.glinboy.cities.projection.Country
import com.glinboy.cities.respository.CityRepository
import com.glinboy.cities.service.CountryService
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
@Service
class CountryServiceImpl(val cityRepository: CityRepository): CountryService {
override fun getAllCountries(pageable: Pageable): Page<Country> =
cityRepository.findDistinctCountry(pageable)
override fun searchCountry(query: String, pageable: Pageable): Page<Country> =
cityRepository.searchCountry(query, pageable)
override fun getCountryCities(isoCode: String, pageable: Pageable): Page<City> =
cityRepository.findAllByIso2OrIso3(isoCode.uppercase(), isoCode.uppercase(), pageable)
} | 14 | Kotlin | 0 | 1 | 4c93863f60be04ed8732b4beaea07338e97372f8 | 894 | world-cities-api | MIT License |
kotlinEx/CollectionsEx.kt | zhihaofans | 160,714,152 | false | null | package com.zhihaofans.Android_Kotlin_Utils.kotlinEx
/**
* Created by zhihaofans on 2018/11/4.
*/
fun MutableMap<String, String>.get(key: String, defaultValve: String): String {
return this[key] ?: defaultValve
}
fun MutableList<*>?.isNullorEmpty(): Boolean {
return this?.isEmpty() ?: true
}
| 0 | Kotlin | 0 | 0 | 2a880af2dfc4cbf26a5672536c0b31f48d3d0259 | 305 | Android-Kotlin-Utils | Apache License 2.0 |
bitlap-common/src/main/kotlin/org/bitlap/common/TimeRange.kt | bitlap | 313,535,150 | false | null | /* Copyright (c) 2023 bitlap.org */
package org.bitlap.common
import org.bitlap.common.utils.Range
import org.joda.time.DateTime
/**
* Desc: Time range utils, startTime and endTime must be specified.
*
* Mail: <EMAIL>
* Created by IceMimosa
* Date: 2021/6/21
*/
class TimeRange private constructor(lower: LeftCut<DateTime>, upper: RightCut<DateTime>) : Range<DateTime>(lower, upper) {
constructor(lower: DateTime, upper: DateTime) : this(LeftCut(lower, BoundType.CLOSE), RightCut(upper, BoundType.CLOSE))
constructor(time: DateTime) : this(time, time)
val startTime = lower.endpoint!!
val endTime = upper.endpoint!!
companion object {
fun of(start: DateTime, end: DateTime, inclusive: Pair<Boolean, Boolean> = true to true): TimeRange {
return when (inclusive) {
true to true -> TimeRange(LeftCut(start, BoundType.CLOSE), RightCut(end, BoundType.CLOSE))
true to false -> TimeRange(LeftCut(start, BoundType.CLOSE), RightCut(end, BoundType.OPEN))
false to true -> TimeRange(LeftCut(start, BoundType.CLOSE), RightCut(end, BoundType.OPEN))
false to false -> TimeRange(LeftCut(start, BoundType.OPEN), RightCut(end, BoundType.OPEN))
else -> TimeRange(start, end)
}
}
}
operator fun component1(): DateTime = lower.endpoint!!
operator fun component2(): DateTime = upper.endpoint!!
fun <R> walkByDayStep(func: (DateTime) -> R): List<R> {
var walkStart = startTime.withTimeAtStartOfDay().let {
if (it.isBefore(startTime) || lower.boundType == BoundType.CLOSE) {
it
} else {
it.plusDays(1)
}
}
val walkEnd = endTime.withTimeAtStartOfDay().let {
if (it.isEqual(endTime) && upper.boundType == BoundType.CLOSE) {
it
} else {
it.plusDays(1)
}
}
val results = mutableListOf<R>()
while (walkStart.isBefore(walkEnd) || walkStart.isEqual(walkEnd)) {
results.add(func.invoke(walkStart))
walkStart = walkStart.plusDays(1)
}
return results
}
}
| 23 | null | 2 | 22 | a83d320073ccf1bd2eb036555fc03d72dddef81b | 2,219 | bitlap | Apache License 2.0 |
app/src/test/java/com/coinninja/coinkeeper/util/crypto/BitcoinUriTest.kt | coinninjadev | 175,276,289 | false | null | package com.coinninja.coinkeeper.util.crypto
import androidx.test.ext.junit.runners.AndroidJUnit4
import app.dropbit.commons.currency.BTCCurrency
import com.coinninja.coinkeeper.util.uri.parameter.BitcoinParameter
import com.coinninja.coinkeeper.util.uri.parameter.BitcoinParameter.AMOUNT
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*
@RunWith(AndroidJUnit4::class)
class BitcoinUriTest {
private fun createBuilder(): BitcoinUri.Builder {
val bitcoinUtil = mock<BitcoinUtil>()
whenever(bitcoinUtil.isValidBTCAddress(any())).thenReturn(true)
return BitcoinUri.Builder(bitcoinUtil)
}
//---------------
// BC1 parsing / building
//---------------
@Test
fun bc1__upper_case_from_builder__add_address() {
val builder = createBuilder()
val address = "BC1Q8JPENEN7X5CLWX9396T3S9Z5LR8YH88ZKKUSJZ"
val uri = builder.setAddress(address).build()
assertThat(uri.toString()).isEqualTo("bitcoin:bc1q8jpenen7x5clwx9396t3s9z5lr8yh88zkkusjz")
assertThat(uri.address).isEqualTo("bc1q8jpenen7x5clwx9396t3s9z5lr8yh88zkkusjz")
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.memo).isEqualTo("")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isTrue()
}
@Test
fun bc1__upper_case_from_builder__parse_uri_string() {
val builder = createBuilder()
val uriString = "bitcoin:bc1q8jpenen7x5clwx9396t3s9z5lr8yh88zkkusjz"
val uri = builder.parse(uriString)
assertThat(uri.toString()).isEqualTo("bitcoin:bc1q8jpenen7x5clwx9396t3s9z5lr8yh88zkkusjz")
assertThat(uri.address).isEqualTo("bc1q8jpenen7x5clwx9396t3s9z5lr8yh88zkkusjz")
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.memo).isEqualTo("")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isTrue()
}
// --------------
// Building
// --------------
@Test
fun builds_from_address__ignores_bad_address() {
val builder = createBuilder()
val address = "35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xaa"
whenever(builder.bitcoinUtil.isValidBTCAddress(address)).thenReturn(false)
val uri = builder.setAddress(address).build()
assertThat(uri.toString()).isEqualTo("bitcoin:")
assertThat(uri.address).isEqualTo("")
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.memo).isEqualTo("")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isFalse()
}
@Test
fun builds_from_address() {
val builder = createBuilder()
val address = "35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa"
val uri = builder.setAddress(address).build()
assertThat(uri.toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.address).isEqualTo("35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.isBip70).isFalse()
assertThat(uri.hasRequiredFee).isFalse()
assertThat(uri.requiredFee).isEqualTo(0.0)
assertThat(uri.isValidPaymentAddress).isTrue()
}
@Test
fun builds_with_amount_param() {
val builder = createBuilder()
val address = "35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa"
val btc = BTCCurrency(1.0)
val parameters = HashMap<BitcoinParameter, String>()
parameters[AMOUNT] = btc.toUriFormattedString()
val uri = builder.setAddress(address).addParameters(parameters).build()
assertThat(uri.toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa?amount=1.00000000")
assertThat(uri.address).isEqualTo("35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.satoshiAmount).isEqualTo(100_000_000)
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isTrue()
}
@Test
fun builds_with_amount() {
val builder = createBuilder()
val address = "35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa"
val uri = builder.setAddress(address).setAmount(BTCCurrency(150_000_000)).build()
assertThat(uri.toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa?amount=1.50000000")
}
@Test
fun builder_can_remove_amount() {
val builder = createBuilder()
val address = "35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa"
val uri = builder.setAddress(address).setAmount(BTCCurrency(150_000_000)).build()
assertThat(uri.toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa?amount=1.50000000")
assertThat(builder.removeAmount().build().toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
}
@Test
fun builder_can_add_a_memo() {
val builder = createBuilder()
val address = "35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa"
val memo = "Hello World"
val uri = builder.setAddress(address).setAmount(BTCCurrency(150_000_000)).setMemo(memo).build()
assertThat(uri.toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa?amount=1.50000000&memo=Hello%2BWorld")
assertThat(uri.address).isEqualTo("35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.satoshiAmount).isEqualTo(150_000_000)
assertThat(uri.memo).isEqualTo("Hello World")
}
@Test
fun builder_can_add_a_required_fee() {
val builder = createBuilder()
val address = "35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa"
val fee: Double = 5.0
val uri = builder.setAddress(address).setAmount(BTCCurrency(150_000_000)).setFee(fee).build()
assertThat(uri.toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa?amount=1.50000000&required_fee=5.0")
assertThat(uri.address).isEqualTo("35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.satoshiAmount).isEqualTo(150_000_000)
assertThat(uri.hasRequiredFee).isTrue()
assertThat(uri.requiredFee).isEqualTo(fee)
}
@Test
fun builder_clear() {
val builder = createBuilder()
val address = "35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa"
val fee: Double = 5.0
builder.setAddress(address).setAmount(BTCCurrency(150_000_000)).setFee(fee).setMemo("foo bar")
assertThat(builder.build().toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa?amount=1.50000000&required_fee=5.0&memo=foo%2Bbar")
assertThat(builder.clear().build().toString()).isEqualTo("bitcoin:")
}
// --------------
// PARSING
// --------------
// Text Globs
@Test
fun parse_just_a_valid_btc_address_and_no_amount_not_a_uri_test() {
val builder = createBuilder()
val sampleURI = "35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa"
val uri = builder.parse(sampleURI)
assertThat(uri.toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.address).isEqualTo("35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.satoshiAmount).isEqualTo(0)
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isTrue()
}
@Test
fun parse_just_a_valid_btc_address_and_no_amount_not_a_uri_test__garbage() {
val builder = createBuilder()
val data = "35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xaa"
whenever(builder.bitcoinUtil.isValidBTCAddress(data)).thenReturn(false)
val uri = builder.parse(data)
assertThat(uri.toString()).isEqualTo("bitcoin:")
assertThat(uri.address).isEqualTo("")
assertThat(uri.satoshiAmount).isEqualTo(0)
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isFalse()
}
@Test
fun parse_a_random_string_that_contains_a_valid_btc_uri_test() {
val builder = createBuilder()
val sampleURI = "Hello, here is my btc request bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa?amount=0.00325. Thanks for sending me the money"
val uri = builder.parse(sampleURI)
assertThat(uri.toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa?amount=0.00325")
assertThat(uri.address).isEqualTo("35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.satoshiAmount).isEqualTo(325_000)
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isTrue()
}
@Test
fun parse_a_random_string_that_contains_a_btc_address_somewhere_in_it_test() {
val sampleURI = "Whats up my man. Here is my btc address 35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa did you need any more information?"
val builder = createBuilder()
val uri = builder.parse(sampleURI)
assertThat(uri.toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.address).isEqualTo("35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.satoshiAmount).isEqualTo(0)
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isTrue()
}
@Test
fun parse_a_random_string_that_contains_a_btc_address_somewhere_in_it_test__segwit() {
val sampleURI = "Whats up my man. Here is my btc address bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu did you need any more information?"
val builder = createBuilder()
val uri = builder.parse(sampleURI)
assertThat(uri.toString()).isEqualTo("bitcoin:bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu")
assertThat(uri.address).isEqualTo("bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu")
assertThat(uri.satoshiAmount).isEqualTo(0)
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isTrue()
}
fun throw_exception_when_parsing_a_string_with_no_btc_data_test() {
val message = "Hello, how are you today?"
val builder = createBuilder()
val uri = builder.parse(message)
assertThat(uri.toString()).isEqualTo("bitcoin:")
assertThat(uri.address).isEqualTo("")
assertThat(uri.satoshiAmount).isEqualTo(0)
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isFalse()
}
@Test
fun parsing_null_is_empty() {
val uri = createBuilder().parse(null)
assertThat(uri.toString()).isEqualTo("bitcoin:")
assertThat(uri.address).isEqualTo("")
assertThat(uri.satoshiAmount).isEqualTo(0)
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isFalse()
}
@Test
fun parsing_empty_string_is_empty() {
val uri = createBuilder().parse(null)
assertThat(uri.toString()).isEqualTo("bitcoin:")
assertThat(uri.address).isEqualTo("")
assertThat(uri.satoshiAmount).isEqualTo(0)
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isFalse()
}
// bitcoin uri
@Test
fun parse_a_valid_btc_uri_with_btc_address() {
val builder = createBuilder()
val sampleURI = "bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa"
val uri = builder.parse(sampleURI)
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.address).isEqualTo("35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isTrue()
}
@Test
fun parse_a_valid_btc_uri_with_btc_address_and_amount_test() {
val builder = createBuilder()
val sampleURI = "bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa?amount=0.00325"
val uri = builder.parse(sampleURI)
assertThat(uri.scheme).isEqualTo("bitcoin")
assertThat(uri.address).isEqualTo("35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa")
assertThat(uri.satoshiAmount).isEqualTo(325_000)
assertThat(uri.toString()).isEqualTo("bitcoin:35t99geKQGdRyJC7fKQ4GeJrV5YvYCo7xa?amount=0.00325")
assertThat(uri.isBip70).isFalse()
assertThat(uri.isValidPaymentAddress).isTrue()
}
// bip 70
@Test
fun parse_a_valid_bip70_with_identifier() {
val builder = createBuilder()
val sampleBip70URI = "bitcoin:?r=https://merchant.com/pay.php?h%3D2a8628fc2fbe"
val uri = builder.parse(sampleBip70URI)
assertThat(uri.isBip70).isTrue()
assertThat(uri.merchantUri.toString()).isEqualTo("https://merchant.com/pay.php?h%3D2a8628fc2fbe")
assertThat(uri.isValidPaymentAddress).isTrue()
}
@Test
fun parse_a_valid_bip70_btc_uri_with_r_parameter() {
val builder = createBuilder()
val sampleURI = "bitcoin:?r=https://merchant.com/pay.php?h%3D2a8628fc2fbe"
val uri = builder.parse(sampleURI)
assertThat(uri.isBip70).isTrue()
assertThat(uri.merchantUri.toString()).isEqualTo("https://merchant.com/pay.php?h%3D2a8628fc2fbe")
assertThat(uri.isValidPaymentAddress).isTrue()
}
@Test
fun parse_a_valid_bip70_url_without_bitcoin_scheme() {
val sampleURI = "https://merchant.com/pay.php?h%3D2a8628fc2fbe"
val builder = createBuilder()
val uri = builder.parse(sampleURI)
assertThat(uri.isBip70).isTrue()
assertThat(uri.merchantUri.toString()).isEqualTo("https://merchant.com/pay.php?h%3D2a8628fc2fbe")
assertThat(uri.isValidPaymentAddress).isTrue()
}
@Test
fun parse_a_valid_bip70_btc_uri_with_request_parameter() {
val sampleURI = "bitcoin:?request=https://merchant.com/pay.php?h%3D2a8628fc2fbe"
val builder = createBuilder()
val uri = builder.parse(sampleURI)
assertThat(uri.isBip70).isTrue()
assertThat(uri.merchantUri.toString()).isEqualTo("https://merchant.com/pay.php?h%3D2a8628fc2fbe")
assertThat(uri.isValidPaymentAddress).isTrue()
}
@Test
fun matches_bip70_when_merchant_on_query_string() {
val sampleURI = "bitcoin:mq7se9wy2egettFxPbmn99cK8v5AFq55Lx?amount=0.11&r=https://merchant.com/pay.php?h%3D2a8628fc2fbe"
val builder = createBuilder()
val uri = builder.parse(sampleURI)
assertThat(uri.merchantUri.toString()).isEqualTo("https://merchant.com/pay.php?h%3D2a8628fc2fbe")
assertThat(uri.isBip70).isTrue()
assertThat(uri.isValidPaymentAddress).isTrue()
}
} | 2 | Kotlin | 0 | 6 | d67d7c0b9cad27db94470231073c5d6cdda83cd0 | 14,974 | dropbit-android | MIT License |
tooling-country/src/commonMain/kotlin/dev/datlag/tooling/country/Mali.kt | DatL4g | 739,165,922 | false | {"Kotlin": 532513} | package dev.datlag.tooling.country
data object Mali : Country {
override val codeAlpha2: Country.Code.Alpha2 = Country.Code.Alpha2("ML")
override val codeAlpha3: Country.Code.Alpha3 = Country.Code.Alpha3("MLI")
override val codeNumeric: Country.Code.Numeric = Country.Code.Numeric(466)
} | 0 | Kotlin | 0 | 3 | e4d2bf45d9d34e80107e9b1558fd982e511ab28c | 301 | tooling | Apache License 2.0 |
components/faphub/dao/network/src/main/java/com/flipperdevices/faphub/dao/network/ktorfit/model/KtorfitBuildState.kt | flipperdevices | 288,258,832 | false | null | package com.flipperdevices.faphub.dao.network.retrofit.model
import com.flipperdevices.faphub.dao.api.model.FapBuildState
import com.flipperdevices.faphub.target.model.FlipperTarget
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
enum class KtorfitBuildState {
@SerialName("READY")
READY,
@SerialName("BUILD_RUNNING")
BUILD_RUNNING,
@SerialName("UNSUPPORTED_APPLICATION")
UNSUPPORTED_APP,
@SerialName("FLIPPER_OUTDATED")
FLIPPER_OUTDATED,
@SerialName("UNSUPPORTED_SDK")
UNSUPPORTED_SDK;
fun toFapBuildState(target: FlipperTarget): FapBuildState = when (this) {
READY -> if (target == FlipperTarget.NotConnected) {
FapBuildState.READY_ON_RELEASE
} else {
FapBuildState.READY
}
BUILD_RUNNING -> FapBuildState.BUILD_RUNNING
UNSUPPORTED_APP -> FapBuildState.UNSUPPORTED_APP
FLIPPER_OUTDATED -> FapBuildState.FLIPPER_OUTDATED
UNSUPPORTED_SDK -> FapBuildState.UNSUPPORTED_SDK
}
}
| 13 | Kotlin | 111 | 786 | b22cbb78b48086718a1ed427111835de7ad230b1 | 1,058 | Flipper-Android-App | MIT License |
codefest-client/src/main/kotlin/codefest/client/MainController.kt | AlmasB | 171,107,917 | false | null | package codefest.client
import javafx.fxml.FXML
import javafx.scene.control.Tab
/**
*
* @author <NAME> (<EMAIL>)
*/
class MainController {
@FXML
private lateinit var tabLeaderboard: Tab
@FXML
private lateinit var leaderboardController: LeaderboardController
fun initialize() {
tabLeaderboard.selectedProperty().addListener { _, _, isSelected ->
if (isSelected) {
leaderboardController.requestLeaderboard()
}
}
}
} | 8 | Kotlin | 4 | 3 | ae1f070e54a9a1eea1aa3135bb8827109d020814 | 500 | CodefestApp | Apache License 2.0 |
app/src/main/java/com/canopas/yourspace/ui/flow/home/space/join/JoinSpaceScreen.kt | canopas | 739,382,039 | false | {"Kotlin": 802726, "JavaScript": 13096, "Ruby": 908} | package com.canopas.yourspace.ui.flow.home.space.join
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.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.canopas.yourspace.R
import com.canopas.yourspace.data.models.space.ApiSpace
import com.canopas.yourspace.ui.component.AppBanner
import com.canopas.yourspace.ui.component.OtpInputField
import com.canopas.yourspace.ui.component.PrimaryButton
import com.canopas.yourspace.ui.theme.AppTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun JoinSpaceScreen() {
val viewModel = hiltViewModel<JoinSpaceViewModel>()
Scaffold(topBar = {
TopAppBar(
colors = TopAppBarDefaults.topAppBarColors(containerColor = AppTheme.colorScheme.surface),
title = {
Text(
text = stringResource(id = R.string.join_space_title),
style = AppTheme.appTypography.header3
)
},
navigationIcon = {
IconButton(onClick = { viewModel.popBackStack() }) {
Icon(
Icons.Default.ArrowBack,
contentDescription = ""
)
}
}
)
}) {
JoinSpaceContent(modifier = Modifier.padding(it))
}
}
@Composable
private fun JoinSpaceContent(modifier: Modifier) {
val viewModel = hiltViewModel<JoinSpaceViewModel>()
val state by viewModel.state.collectAsState()
Column(
modifier
.fillMaxWidth()
.padding(20.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(20.dp))
Text(
text = stringResource(R.string.join_space_title_enter_code),
style = AppTheme.appTypography.header2,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
)
Spacer(modifier = Modifier.height(40.dp))
OtpInputField(pinText = state.inviteCode, onPinTextChange = {
viewModel.onCodeChanged(it)
})
Spacer(modifier = Modifier.height(40.dp))
Text(
text = stringResource(R.string.onboard_space_join_subtitle),
style = AppTheme.appTypography.body1,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
)
Spacer(modifier = Modifier.height(30.dp))
PrimaryButton(
label = stringResource(id = R.string.common_btn_join_space),
onClick = { viewModel.verifyAndJoinSpace() },
enabled = state.inviteCode.length == 6,
showLoader = state.verifying
)
}
if (state.error != null) {
AppBanner(msg = state.error!!) {
viewModel.resetErrorState()
}
}
if (state.errorInvalidInviteCode) {
AppBanner(msg = stringResource(id = R.string.onboard_space_invalid_invite_code)) {
viewModel.resetErrorState()
}
}
if (state.joinedSpace != null) {
JoinedSpacePopup(state.joinedSpace!!) { viewModel.popBackStack() }
}
}
@Composable
fun JoinedSpacePopup(space: ApiSpace, onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = { onDismiss() },
title = {
Text(text = stringResource(id = R.string.common_label_congratulations))
},
text = {
Column(
modifier = Modifier.padding(8.dp)
) {
Text(
text = stringResource(
id = R.string.join_space_success_popup_message,
space.name
)
)
}
},
confirmButton = {
Button(
onClick = {
onDismiss()
}
) {
Text(stringResource(id = R.string.common_btn_ok))
}
}
)
}
| 5 | Kotlin | 3 | 7 | 3ce744ea6663d632b2fff470f9293de72708291d | 5,037 | your-space-android | Apache License 2.0 |
processor/src/main/java/com/attafitamim/room/compound/processor/generator/CompoundGenerator.kt | tamimattafi | 510,142,549 | false | {"Kotlin": 47650} | package com.attafitamim.room.compound.processor.generator
import com.attafitamim.room.compound.processor.data.EntityData
import com.attafitamim.room.compound.processor.data.info.PropertyInfo
import com.attafitamim.room.compound.processor.data.utility.EntityJunction
import com.attafitamim.room.compound.processor.generator.syntax.CONFLICT_STRATEGY
import com.attafitamim.room.compound.processor.generator.syntax.CONFLICT_STRATEGY_REPLACE
import com.attafitamim.room.compound.processor.generator.syntax.CONSTANT_NAME_SEPARATOR
import com.attafitamim.room.compound.processor.generator.syntax.DAO_ANNOTATION
import com.attafitamim.room.compound.processor.generator.syntax.DAO_POSTFIX
import com.attafitamim.room.compound.processor.generator.syntax.DAO_PREFIX
import com.attafitamim.room.compound.processor.generator.syntax.DELETE_ANNOTATION
import com.attafitamim.room.compound.processor.generator.syntax.DELETE_ENTITIES_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.DELETE_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.INSERT_ANNOTATION
import com.attafitamim.room.compound.processor.generator.syntax.INSERT_ENTITIES_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.UPSERT_ANNOTATION
import com.attafitamim.room.compound.processor.generator.syntax.UPSERT_ENTITIES_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.INSERT_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.UPSERT_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.INSTANCE_ACCESS_KEY
import com.attafitamim.room.compound.processor.generator.syntax.LIST_ITEM_POSTFIX
import com.attafitamim.room.compound.processor.generator.syntax.LIST_OF_METHOD
import com.attafitamim.room.compound.processor.generator.syntax.NULLABLE_SIGN
import com.attafitamim.room.compound.processor.generator.syntax.ON_CONFLICT_PARAMETER
import com.attafitamim.room.compound.processor.generator.syntax.PARAMETER_CLOSE_PARENTHESIS
import com.attafitamim.room.compound.processor.generator.syntax.PARAMETER_OPEN_PARENTHESIS
import com.attafitamim.room.compound.processor.generator.syntax.PARAMETER_SEPARATOR
import com.attafitamim.room.compound.processor.generator.syntax.PropertyAccessSyntax
import com.attafitamim.room.compound.processor.generator.syntax.ROOM_PACKAGE
import com.attafitamim.room.compound.processor.generator.syntax.UPDATE_ANNOTATION
import com.attafitamim.room.compound.processor.generator.syntax.UPDATE_ENTITIES_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.UPDATE_METHOD_NAME
import com.attafitamim.room.compound.processor.utils.createAssignSyntax
import com.attafitamim.room.compound.processor.utils.createForEachSyntax
import com.attafitamim.room.compound.processor.utils.createInitializationSyntax
import com.attafitamim.room.compound.processor.utils.createListAdditionSyntax
import com.attafitamim.room.compound.processor.utils.createMethodCallSyntax
import com.attafitamim.room.compound.processor.utils.titleToCamelCase
import com.attafitamim.room.compound.processor.utils.writeToFile
import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.Dependencies
import com.google.devtools.ksp.processing.KSPLogger
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.asClassName
// TODO(Generator): Refactor generator logic and structure
class CompoundGenerator(
private val codeGenerator: CodeGenerator,
private val logger: KSPLogger,
private val options: Map<String, String>
) {
private val isSuspendDao: Boolean get() =
options["suspendDao"] == "true"
private val useDaoPrefix: Boolean get() =
options["useDaoPrefix"] == "true"
private val useDaoPostfix: Boolean get() =
options["useDaoPostfix"] == "true"
fun generateDao(compoundData: EntityData.MainCompound) {
val fileName = buildString {
if (useDaoPrefix) append(DAO_PREFIX)
append(compoundData.typeInfo.className)
if (useDaoPostfix) append(DAO_POSTFIX)
}
val compoundClassName = ClassName(
compoundData.typeInfo.packageName,
compoundData.typeInfo.className
)
val compoundListName = Collection::class.asClassName()
.parameterizedBy(compoundClassName)
val insertFunctionBuilder = FunSpec.builder(INSERT_METHOD_NAME)
.addParameter(compoundData.propertyInfo.name, compoundListName)
val upsertFunctionBuilder = FunSpec.builder(UPSERT_METHOD_NAME)
.addParameter(compoundData.propertyInfo.name, compoundListName)
val updateFunctionBuilder = FunSpec.builder(UPDATE_METHOD_NAME)
.addParameter(compoundData.propertyInfo.name, compoundListName)
val deleteFunctionBuilder = FunSpec.builder(DELETE_METHOD_NAME)
.addParameter(compoundData.propertyInfo.name, compoundListName)
if (isSuspendDao) {
insertFunctionBuilder.addModifiers(KModifier.SUSPEND)
upsertFunctionBuilder.addModifiers(KModifier.SUSPEND)
updateFunctionBuilder.addModifiers(KModifier.SUSPEND)
deleteFunctionBuilder.addModifiers(KModifier.SUSPEND)
}
val listInitializationBlock = createListInitializationBlock(compoundData)
val listMappingBlock = createListMappingBlock(compoundData)
val insertListBlock = createListActionBlock(
compoundData,
INSERT_ENTITIES_METHOD_NAME
)
val upsertListBlock = createListActionBlock(
compoundData,
UPSERT_ENTITIES_METHOD_NAME
)
val updateListBlock = createListActionBlock(
compoundData,
UPDATE_ENTITIES_METHOD_NAME
)
val deleteListBlock = createListActionBlock(
compoundData,
DELETE_ENTITIES_METHOD_NAME
)
val insertAnnotation = createInsertAnnotationSpec()
val insertEntityFunctionBuilder = createEntityActionFunction(
compoundData,
INSERT_ENTITIES_METHOD_NAME,
insertAnnotation
)
val upsertAnnotationClassName = ClassName(ROOM_PACKAGE, UPSERT_ANNOTATION)
val upsertAnnotation = AnnotationSpec.builder(upsertAnnotationClassName).build()
val upsertEntityFunctionBuilder = createEntityActionFunction(
compoundData,
UPSERT_ENTITIES_METHOD_NAME,
upsertAnnotation
)
val updateAnnotationClassName = ClassName(ROOM_PACKAGE, UPDATE_ANNOTATION)
val updateAnnotation = AnnotationSpec.builder(updateAnnotationClassName).build()
val updateEntityFunctionBuilder = createEntityActionFunction(
compoundData,
UPDATE_ENTITIES_METHOD_NAME,
updateAnnotation
)
val deleteAnnotationClassName = ClassName(ROOM_PACKAGE, DELETE_ANNOTATION)
val deleteAnnotation = AnnotationSpec.builder(deleteAnnotationClassName).build()
val deleteEntityFunctionBuilder = createEntityActionFunction(
compoundData,
DELETE_ENTITIES_METHOD_NAME,
deleteAnnotation
)
insertFunctionBuilder
.addCode(listInitializationBlock)
.addCode(listMappingBlock)
.addCode(insertListBlock)
upsertFunctionBuilder
.addCode(listInitializationBlock)
.addCode(listMappingBlock)
.addCode(upsertListBlock)
updateFunctionBuilder
.addCode(listInitializationBlock)
.addCode(listMappingBlock)
.addCode(updateListBlock)
deleteFunctionBuilder
.addCode(listInitializationBlock)
.addCode(listMappingBlock)
.addCode(deleteListBlock)
val listInsertFunction = insertFunctionBuilder.build()
val listUpsertFunction = upsertFunctionBuilder.build()
val listUpdateFunction = updateFunctionBuilder.build()
val listDeleteFunction = deleteFunctionBuilder.build()
val singleInsertFunction = createSingleActionFunction(
compoundClassName,
compoundData.propertyInfo.name,
listInsertFunction,
isSuspendDao,
INSERT_METHOD_NAME
)
val singleUpsertFunction = createSingleActionFunction(
compoundClassName,
compoundData.propertyInfo.name,
listUpsertFunction,
isSuspendDao,
UPSERT_METHOD_NAME
)
val singleUpdateFunction = createSingleActionFunction(
compoundClassName,
compoundData.propertyInfo.name,
listUpdateFunction,
isSuspendDao,
UPDATE_METHOD_NAME
)
val singleDeleteFunction = createSingleActionFunction(
compoundClassName,
compoundData.propertyInfo.name,
listDeleteFunction,
isSuspendDao,
DELETE_METHOD_NAME
)
val daoAnnotation = ClassName(
ROOM_PACKAGE,
DAO_ANNOTATION
)
val interfaceSpec = TypeSpec.interfaceBuilder(fileName)
.addAnnotation(daoAnnotation)
.addFunction(singleInsertFunction)
.addFunction(listInsertFunction)
.addFunction(insertEntityFunctionBuilder)
.addFunction(singleUpsertFunction)
.addFunction(listUpsertFunction)
.addFunction(upsertEntityFunctionBuilder)
.addFunction(singleUpdateFunction)
.addFunction(listUpdateFunction)
.addFunction(updateEntityFunctionBuilder)
.addFunction(singleDeleteFunction)
.addFunction(listDeleteFunction)
.addFunction(deleteEntityFunctionBuilder)
.build()
val fileSpec = FileSpec.builder(compoundData.typeInfo.packageName, fileName)
.addType(interfaceSpec)
.build()
val outputFile = codeGenerator.createNewFile(
Dependencies(aggregating = false),
compoundData.typeInfo.packageName,
fileName
)
fileSpec.writeToFile(outputFile)
}
private fun createEntityActionFunction(
compoundData: EntityData.MainCompound,
actionName: String,
actionAnnotation: AnnotationSpec
): FunSpec {
val functionBuilder = FunSpec.builder(actionName)
.addModifiers(KModifier.ABSTRACT)
.addAnnotation(actionAnnotation)
if (isSuspendDao) functionBuilder.addModifiers(KModifier.SUSPEND)
val presentEntities = HashSet<String>()
fun addActionParameter(packageName: String, className: String) {
val entityName = titleToCamelCase(className)
if (presentEntities.contains(entityName)) return
presentEntities.add(entityName)
val entityClassName = ClassName(packageName, className)
val entityListName = Collection::class.asClassName()
.parameterizedBy(entityClassName)
val parameter = ParameterSpec.builder(entityName, entityListName)
.build()
functionBuilder.addParameter(parameter)
}
fun handleEntity(entityData: EntityData) {
when (entityData) {
is EntityData.MainCompound -> entityData.entities.forEach { childEntity ->
handleEntity(childEntity)
}
is EntityData.Nested -> {
entityData.junction?.let { junction ->
addActionParameter(junction.packageName, junction.className)
}
when (entityData) {
is EntityData.Compound -> entityData.entities.forEach { childEntity ->
handleEntity(childEntity)
}
is EntityData.Entity -> addActionParameter(
entityData.typeInfo.packageName,
entityData.typeInfo.className
)
}
}
}
}
handleEntity(compoundData)
return functionBuilder.build()
}
private fun createListMappingBlock(
compoundData: EntityData.MainCompound
): CodeBlock {
val codeBlockBuilder = CodeBlock.builder()
fun addForEachStatement(
parameter: String,
itemName: String,
isNullable: Boolean = false
) {
val forEachSyntax = createForEachSyntax(parameter, itemName, isNullable)
codeBlockBuilder.beginControlFlow(forEachSyntax)
}
val itemName = createListItemName(compoundData.propertyInfo.name)
addForEachStatement(compoundData.propertyInfo.name, itemName)
fun handleJunction(
entityData: EntityData.Nested,
parents: List<EntityData>,
accessProperties: List<PropertyInfo>,
insideCollection: Boolean = false
) {
val junction = entityData.junction ?: return
val listItemName = createListItemName(entityData.propertyInfo.name)
val junctionClassName = ClassName(junction.packageName, junction.className)
val junctionListName = titleToCamelCase(junction.className)
val entityAccessSyntax = createPropertyAccessSyntax(
accessProperties,
entityData.propertyInfo
)
val listItemPropertyInfo = PropertyInfo(
listItemName,
isNullable = false,
isCollection = false
)
val embeddedParentAccessSyntax = createPreviousEmbeddedEntityAccessSyntax(
parents,
junction.parentColumn
)
val embeddedEntityAccessSyntax = createNextEmbeddedEntityAccessSyntax(
listOf(listItemPropertyInfo),
entityData,
junction.entityColumn
)
val junctionCreationStatement = createEntityJunctionStatement(
junctionListName,
junction,
embeddedParentAccessSyntax,
embeddedEntityAccessSyntax
)
if (entityData.propertyInfo.isCollection && !insideCollection) {
addForEachStatement(
entityAccessSyntax.chain,
listItemName,
entityAccessSyntax.handleNullability
)
codeBlockBuilder.addStatement(junctionCreationStatement, junctionClassName)
.endControlFlow()
} else {
codeBlockBuilder.addStatement(junctionCreationStatement, junctionClassName)
}
}
fun handleEntity(
entityData: EntityData,
parents: List<EntityData> = listOf(),
accessProperties: List<PropertyInfo> = listOf()
) {
when (entityData) {
is EntityData.MainCompound -> entityData.entities.forEach { compoundEntityData ->
handleEntity(
compoundEntityData,
parents + entityData,
accessProperties + entityData.propertyInfo
)
}
is EntityData.Nested -> when(entityData) {
is EntityData.Compound -> {
if (entityData.propertyInfo.isCollection) {
val propertyAccessSyntax = createPropertyAccessSyntax(
accessProperties,
entityData.propertyInfo
)
val listItemName = createListItemName(entityData.propertyInfo.name)
addForEachStatement(
propertyAccessSyntax.chain,
listItemName,
propertyAccessSyntax.handleNullability
)
val listPropertyInfo = PropertyInfo(
listItemName,
isNullable = false,
isCollection = false
)
handleJunction(
entityData,
parents,
accessProperties,
insideCollection = true
)
entityData.entities.forEach { compoundEntityData ->
handleEntity(
compoundEntityData,
parents + entityData,
listOf(listPropertyInfo)
)
}
codeBlockBuilder.endControlFlow()
} else {
handleJunction(
entityData,
parents,
accessProperties,
insideCollection = true
)
entityData.entities.forEach { compoundEntityData ->
handleEntity(
compoundEntityData,
parents + entityData,
accessProperties + entityData.propertyInfo
)
}
}
}
is EntityData.Entity -> {
handleJunction(entityData, parents, accessProperties)
val parameterName = titleToCamelCase(entityData.typeInfo.className)
val propertyAccessSyntax = createPropertyAccessSyntax(
accessProperties,
entityData.propertyInfo
)
val listAdditionSyntax = createListAdditionSyntax(
parameterName,
propertyAccessSyntax,
entityData.propertyInfo.isCollection
)
codeBlockBuilder.addStatement(listAdditionSyntax)
}
}
}
}
handleEntity(compoundData)
return codeBlockBuilder.endControlFlow().build()
}
private fun createPreviousEmbeddedEntityAccessSyntax(
parents: List<EntityData>,
columnName: String
): PropertyAccessSyntax {
val accessParents = parents.map(EntityData::propertyInfo)
val collectionIndex = accessParents.indexOfLast { propertyInfo ->
propertyInfo.isCollection
}.takeIf { index ->
index in 1..parents.size
}
val newAccessParents = if (collectionIndex != null) {
accessParents.subList(collectionIndex, accessParents.size).toMutableList()
} else {
accessParents.toMutableList()
}
when (val parent = parents.last()) {
is EntityData.MainCompound -> {
newAccessParents.add(parent.entities.first(EntityData.Nested::isEmbedded).propertyInfo)
}
is EntityData.Compound -> {
newAccessParents.add(parent.entities.first(EntityData.Nested::isEmbedded).propertyInfo)
}
is EntityData.Entity -> {
// Do nothing, same entity
}
}
val columnPropertyInfo = PropertyInfo(
columnName,
isNullable = false,
isCollection = false
)
return createPropertyAccessSyntax(newAccessParents, columnPropertyInfo)
}
private fun createNextEmbeddedEntityAccessSyntax(
accessParents: List<PropertyInfo>,
entityData: EntityData,
columnName: String
): PropertyAccessSyntax {
val collectionIndex = accessParents.indexOfLast { propertyInfo ->
propertyInfo.isCollection
}.takeIf { index ->
index in 0..accessParents.lastIndex
}
val newAccessParents = if (collectionIndex != null) {
accessParents.toMutableList()
//accessParents.subList(collectionIndex, accessParents.size).toMutableList()
} else {
accessParents.toMutableList()
}
when (entityData) {
is EntityData.MainCompound -> {
newAccessParents.add(entityData.entities.first(EntityData.Nested::isEmbedded).propertyInfo)
}
is EntityData.Compound -> {
newAccessParents.add(entityData.entities.first(EntityData.Nested::isEmbedded).propertyInfo)
}
is EntityData.Entity -> {
// Do nothing, same entity
}
}
val columnInfo = PropertyInfo(
columnName,
isNullable = false,
isCollection = false
)
return createPropertyAccessSyntax(newAccessParents, columnInfo)
}
private fun createListActionBlock(
compoundData: EntityData.MainCompound,
actionMethodName: String
): CodeBlock {
val presentEntities = HashSet<String>()
val codeBlockBuilder = CodeBlock.builder()
val actionMethodCall = buildString {
append(actionMethodName, PARAMETER_OPEN_PARENTHESIS)
}
codeBlockBuilder.addStatement(actionMethodCall)
fun addActionParameter(className: String) {
val entityName = titleToCamelCase(className)
if (presentEntities.contains(entityName)) return
presentEntities.add(entityName)
val parameterWithSeparator = buildString {
append(entityName, PARAMETER_SEPARATOR)
}
codeBlockBuilder.addStatement(parameterWithSeparator)
}
fun handleEntity(entityData: EntityData) {
when (entityData) {
is EntityData.MainCompound -> entityData.entities.forEach(::handleEntity)
is EntityData.Nested -> {
entityData.junction?.let { junction ->
addActionParameter(junction.className)
}
when (entityData) {
is EntityData.Compound -> entityData.entities.forEach(::handleEntity)
is EntityData.Entity -> {
addActionParameter(entityData.typeInfo.className)
}
}
}
}
}
handleEntity(compoundData)
return codeBlockBuilder.addStatement(PARAMETER_CLOSE_PARENTHESIS).build()
}
private fun createListItemName(
listName: String,
): String {
val camelClassName = titleToCamelCase(listName)
return buildString { append(camelClassName, LIST_ITEM_POSTFIX) }
}
private fun createListInitializationBlock(
compoundData: EntityData.MainCompound
): CodeBlock {
val presentEntityLists = HashSet<String>()
val codeBlockBuilder = CodeBlock.builder()
fun addListInitializationStatement(packageName: String, className: String) {
val listName = titleToCamelCase(className)
if (presentEntityLists.contains(listName)) return
presentEntityLists.add(listName)
val entityClassName = ClassName(packageName, className)
val parentSetName = HashSet::class.asClassName().parameterizedBy(entityClassName)
val initializationSyntax = createInitializationSyntax(listName)
codeBlockBuilder.addStatement(initializationSyntax, parentSetName)
}
fun handleEntity(entityData: EntityData) {
when (entityData) {
is EntityData.MainCompound -> entityData.entities.forEach(::handleEntity)
is EntityData.Nested -> {
entityData.junction?.let { junction ->
addListInitializationStatement(junction.packageName, junction.className)
}
when (entityData) {
is EntityData.Compound -> entityData.entities.forEach(::handleEntity)
is EntityData.Entity -> addListInitializationStatement(
entityData.typeInfo.packageName,
entityData.typeInfo.className
)
}
}
}
}
handleEntity(compoundData)
return codeBlockBuilder.build()
}
private fun createPropertyAccessSyntax(
accessProperties: List<PropertyInfo>,
property: PropertyInfo
): PropertyAccessSyntax {
var handleNullability = false
val propertyNameBuilder = StringBuilder()
val propertyAccessBuilder = StringBuilder()
accessProperties.forEach { accessProperty ->
val name = if (accessProperty.isCollection) createListItemName(accessProperty.name)
else accessProperty.name
propertyAccessBuilder.append(name)
propertyNameBuilder.append(name)
handleNullability = handleNullability || accessProperty.isNullable
if (handleNullability) propertyAccessBuilder.append(NULLABLE_SIGN)
propertyAccessBuilder.append(INSTANCE_ACCESS_KEY)
propertyNameBuilder.append(CONSTANT_NAME_SEPARATOR)
}
propertyAccessBuilder.append(property.name)
propertyNameBuilder.append(property.name)
handleNullability = handleNullability || property.isNullable
return PropertyAccessSyntax(
propertyAccessBuilder.toString(),
propertyNameBuilder.toString(),
handleNullability
)
}
private fun createSingleActionFunction(
compoundClassName: ClassName,
parameterName: String,
listActionFunction: FunSpec,
isSuspend: Boolean,
actionName: String
): FunSpec {
val listCreationMethodCall = createMethodCallSyntax(
LIST_OF_METHOD,
parameterName
)
val actionMethodCall = createMethodCallSyntax(
actionName,
listCreationMethodCall
)
val functionBuilder = FunSpec.builder(actionName)
.addParameter(parameterName, compoundClassName)
.addStatement(actionMethodCall, listActionFunction)
if (isSuspend) functionBuilder.addModifiers(KModifier.SUSPEND)
return functionBuilder.build()
}
private fun createEntityJunctionStatement(
junctionListName: String,
junction: EntityJunction,
embeddedParentAccessSyntax: PropertyAccessSyntax,
embeddedEntityAccessSyntax: PropertyAccessSyntax
) = buildString {
val handleNullability = embeddedParentAccessSyntax.handleNullability ||
embeddedEntityAccessSyntax.handleNullability
if (handleNullability) {
append("if (")
if (embeddedParentAccessSyntax.handleNullability) {
append("${embeddedParentAccessSyntax.chain} != null")
if (embeddedEntityAccessSyntax.handleNullability) append(" && ")
}
if (embeddedEntityAccessSyntax.handleNullability) {
append("${embeddedEntityAccessSyntax.chain} != null")
}
append(")\n")
}
append(junctionListName, ".add(\n")
append("%T(\n")
append(junction.junctionParentColumn, " = ", embeddedParentAccessSyntax.chain, ",\n")
append(junction.junctionEntityColumn, " = ", embeddedEntityAccessSyntax.chain, "\n)")
append("\n)")
}
private fun createInsertAnnotationSpec(): AnnotationSpec {
val upsertAnnotationClassName = ClassName(
ROOM_PACKAGE,
INSERT_ANNOTATION
)
val conflictStrategyReplaceName = ClassName(
ROOM_PACKAGE,
listOf(
CONFLICT_STRATEGY,
CONFLICT_STRATEGY_REPLACE
)
)
val onConflictAssignment = createAssignSyntax(ON_CONFLICT_PARAMETER)
return AnnotationSpec.builder(upsertAnnotationClassName)
.addMember(onConflictAssignment, conflictStrategyReplaceName)
.build()
}
} | 0 | Kotlin | 1 | 1 | 90a35682a3e6b706c7a93ac58c722e01b81a811c | 29,174 | android-room-compound | Apache License 2.0 |
processor/src/main/java/com/attafitamim/room/compound/processor/generator/CompoundGenerator.kt | tamimattafi | 510,142,549 | false | {"Kotlin": 47650} | package com.attafitamim.room.compound.processor.generator
import com.attafitamim.room.compound.processor.data.EntityData
import com.attafitamim.room.compound.processor.data.info.PropertyInfo
import com.attafitamim.room.compound.processor.data.utility.EntityJunction
import com.attafitamim.room.compound.processor.generator.syntax.CONFLICT_STRATEGY
import com.attafitamim.room.compound.processor.generator.syntax.CONFLICT_STRATEGY_REPLACE
import com.attafitamim.room.compound.processor.generator.syntax.CONSTANT_NAME_SEPARATOR
import com.attafitamim.room.compound.processor.generator.syntax.DAO_ANNOTATION
import com.attafitamim.room.compound.processor.generator.syntax.DAO_POSTFIX
import com.attafitamim.room.compound.processor.generator.syntax.DAO_PREFIX
import com.attafitamim.room.compound.processor.generator.syntax.DELETE_ANNOTATION
import com.attafitamim.room.compound.processor.generator.syntax.DELETE_ENTITIES_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.DELETE_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.INSERT_ANNOTATION
import com.attafitamim.room.compound.processor.generator.syntax.INSERT_ENTITIES_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.UPSERT_ANNOTATION
import com.attafitamim.room.compound.processor.generator.syntax.UPSERT_ENTITIES_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.INSERT_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.UPSERT_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.INSTANCE_ACCESS_KEY
import com.attafitamim.room.compound.processor.generator.syntax.LIST_ITEM_POSTFIX
import com.attafitamim.room.compound.processor.generator.syntax.LIST_OF_METHOD
import com.attafitamim.room.compound.processor.generator.syntax.NULLABLE_SIGN
import com.attafitamim.room.compound.processor.generator.syntax.ON_CONFLICT_PARAMETER
import com.attafitamim.room.compound.processor.generator.syntax.PARAMETER_CLOSE_PARENTHESIS
import com.attafitamim.room.compound.processor.generator.syntax.PARAMETER_OPEN_PARENTHESIS
import com.attafitamim.room.compound.processor.generator.syntax.PARAMETER_SEPARATOR
import com.attafitamim.room.compound.processor.generator.syntax.PropertyAccessSyntax
import com.attafitamim.room.compound.processor.generator.syntax.ROOM_PACKAGE
import com.attafitamim.room.compound.processor.generator.syntax.UPDATE_ANNOTATION
import com.attafitamim.room.compound.processor.generator.syntax.UPDATE_ENTITIES_METHOD_NAME
import com.attafitamim.room.compound.processor.generator.syntax.UPDATE_METHOD_NAME
import com.attafitamim.room.compound.processor.utils.createAssignSyntax
import com.attafitamim.room.compound.processor.utils.createForEachSyntax
import com.attafitamim.room.compound.processor.utils.createInitializationSyntax
import com.attafitamim.room.compound.processor.utils.createListAdditionSyntax
import com.attafitamim.room.compound.processor.utils.createMethodCallSyntax
import com.attafitamim.room.compound.processor.utils.titleToCamelCase
import com.attafitamim.room.compound.processor.utils.writeToFile
import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.Dependencies
import com.google.devtools.ksp.processing.KSPLogger
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.asClassName
// TODO(Generator): Refactor generator logic and structure
class CompoundGenerator(
private val codeGenerator: CodeGenerator,
private val logger: KSPLogger,
private val options: Map<String, String>
) {
private val isSuspendDao: Boolean get() =
options["suspendDao"] == "true"
private val useDaoPrefix: Boolean get() =
options["useDaoPrefix"] == "true"
private val useDaoPostfix: Boolean get() =
options["useDaoPostfix"] == "true"
fun generateDao(compoundData: EntityData.MainCompound) {
val fileName = buildString {
if (useDaoPrefix) append(DAO_PREFIX)
append(compoundData.typeInfo.className)
if (useDaoPostfix) append(DAO_POSTFIX)
}
val compoundClassName = ClassName(
compoundData.typeInfo.packageName,
compoundData.typeInfo.className
)
val compoundListName = Collection::class.asClassName()
.parameterizedBy(compoundClassName)
val insertFunctionBuilder = FunSpec.builder(INSERT_METHOD_NAME)
.addParameter(compoundData.propertyInfo.name, compoundListName)
val upsertFunctionBuilder = FunSpec.builder(UPSERT_METHOD_NAME)
.addParameter(compoundData.propertyInfo.name, compoundListName)
val updateFunctionBuilder = FunSpec.builder(UPDATE_METHOD_NAME)
.addParameter(compoundData.propertyInfo.name, compoundListName)
val deleteFunctionBuilder = FunSpec.builder(DELETE_METHOD_NAME)
.addParameter(compoundData.propertyInfo.name, compoundListName)
if (isSuspendDao) {
insertFunctionBuilder.addModifiers(KModifier.SUSPEND)
upsertFunctionBuilder.addModifiers(KModifier.SUSPEND)
updateFunctionBuilder.addModifiers(KModifier.SUSPEND)
deleteFunctionBuilder.addModifiers(KModifier.SUSPEND)
}
val listInitializationBlock = createListInitializationBlock(compoundData)
val listMappingBlock = createListMappingBlock(compoundData)
val insertListBlock = createListActionBlock(
compoundData,
INSERT_ENTITIES_METHOD_NAME
)
val upsertListBlock = createListActionBlock(
compoundData,
UPSERT_ENTITIES_METHOD_NAME
)
val updateListBlock = createListActionBlock(
compoundData,
UPDATE_ENTITIES_METHOD_NAME
)
val deleteListBlock = createListActionBlock(
compoundData,
DELETE_ENTITIES_METHOD_NAME
)
val insertAnnotation = createInsertAnnotationSpec()
val insertEntityFunctionBuilder = createEntityActionFunction(
compoundData,
INSERT_ENTITIES_METHOD_NAME,
insertAnnotation
)
val upsertAnnotationClassName = ClassName(ROOM_PACKAGE, UPSERT_ANNOTATION)
val upsertAnnotation = AnnotationSpec.builder(upsertAnnotationClassName).build()
val upsertEntityFunctionBuilder = createEntityActionFunction(
compoundData,
UPSERT_ENTITIES_METHOD_NAME,
upsertAnnotation
)
val updateAnnotationClassName = ClassName(ROOM_PACKAGE, UPDATE_ANNOTATION)
val updateAnnotation = AnnotationSpec.builder(updateAnnotationClassName).build()
val updateEntityFunctionBuilder = createEntityActionFunction(
compoundData,
UPDATE_ENTITIES_METHOD_NAME,
updateAnnotation
)
val deleteAnnotationClassName = ClassName(ROOM_PACKAGE, DELETE_ANNOTATION)
val deleteAnnotation = AnnotationSpec.builder(deleteAnnotationClassName).build()
val deleteEntityFunctionBuilder = createEntityActionFunction(
compoundData,
DELETE_ENTITIES_METHOD_NAME,
deleteAnnotation
)
insertFunctionBuilder
.addCode(listInitializationBlock)
.addCode(listMappingBlock)
.addCode(insertListBlock)
upsertFunctionBuilder
.addCode(listInitializationBlock)
.addCode(listMappingBlock)
.addCode(upsertListBlock)
updateFunctionBuilder
.addCode(listInitializationBlock)
.addCode(listMappingBlock)
.addCode(updateListBlock)
deleteFunctionBuilder
.addCode(listInitializationBlock)
.addCode(listMappingBlock)
.addCode(deleteListBlock)
val listInsertFunction = insertFunctionBuilder.build()
val listUpsertFunction = upsertFunctionBuilder.build()
val listUpdateFunction = updateFunctionBuilder.build()
val listDeleteFunction = deleteFunctionBuilder.build()
val singleInsertFunction = createSingleActionFunction(
compoundClassName,
compoundData.propertyInfo.name,
listInsertFunction,
isSuspendDao,
INSERT_METHOD_NAME
)
val singleUpsertFunction = createSingleActionFunction(
compoundClassName,
compoundData.propertyInfo.name,
listUpsertFunction,
isSuspendDao,
UPSERT_METHOD_NAME
)
val singleUpdateFunction = createSingleActionFunction(
compoundClassName,
compoundData.propertyInfo.name,
listUpdateFunction,
isSuspendDao,
UPDATE_METHOD_NAME
)
val singleDeleteFunction = createSingleActionFunction(
compoundClassName,
compoundData.propertyInfo.name,
listDeleteFunction,
isSuspendDao,
DELETE_METHOD_NAME
)
val daoAnnotation = ClassName(
ROOM_PACKAGE,
DAO_ANNOTATION
)
val interfaceSpec = TypeSpec.interfaceBuilder(fileName)
.addAnnotation(daoAnnotation)
.addFunction(singleInsertFunction)
.addFunction(listInsertFunction)
.addFunction(insertEntityFunctionBuilder)
.addFunction(singleUpsertFunction)
.addFunction(listUpsertFunction)
.addFunction(upsertEntityFunctionBuilder)
.addFunction(singleUpdateFunction)
.addFunction(listUpdateFunction)
.addFunction(updateEntityFunctionBuilder)
.addFunction(singleDeleteFunction)
.addFunction(listDeleteFunction)
.addFunction(deleteEntityFunctionBuilder)
.build()
val fileSpec = FileSpec.builder(compoundData.typeInfo.packageName, fileName)
.addType(interfaceSpec)
.build()
val outputFile = codeGenerator.createNewFile(
Dependencies(aggregating = false),
compoundData.typeInfo.packageName,
fileName
)
fileSpec.writeToFile(outputFile)
}
private fun createEntityActionFunction(
compoundData: EntityData.MainCompound,
actionName: String,
actionAnnotation: AnnotationSpec
): FunSpec {
val functionBuilder = FunSpec.builder(actionName)
.addModifiers(KModifier.ABSTRACT)
.addAnnotation(actionAnnotation)
if (isSuspendDao) functionBuilder.addModifiers(KModifier.SUSPEND)
val presentEntities = HashSet<String>()
fun addActionParameter(packageName: String, className: String) {
val entityName = titleToCamelCase(className)
if (presentEntities.contains(entityName)) return
presentEntities.add(entityName)
val entityClassName = ClassName(packageName, className)
val entityListName = Collection::class.asClassName()
.parameterizedBy(entityClassName)
val parameter = ParameterSpec.builder(entityName, entityListName)
.build()
functionBuilder.addParameter(parameter)
}
fun handleEntity(entityData: EntityData) {
when (entityData) {
is EntityData.MainCompound -> entityData.entities.forEach { childEntity ->
handleEntity(childEntity)
}
is EntityData.Nested -> {
entityData.junction?.let { junction ->
addActionParameter(junction.packageName, junction.className)
}
when (entityData) {
is EntityData.Compound -> entityData.entities.forEach { childEntity ->
handleEntity(childEntity)
}
is EntityData.Entity -> addActionParameter(
entityData.typeInfo.packageName,
entityData.typeInfo.className
)
}
}
}
}
handleEntity(compoundData)
return functionBuilder.build()
}
private fun createListMappingBlock(
compoundData: EntityData.MainCompound
): CodeBlock {
val codeBlockBuilder = CodeBlock.builder()
fun addForEachStatement(
parameter: String,
itemName: String,
isNullable: Boolean = false
) {
val forEachSyntax = createForEachSyntax(parameter, itemName, isNullable)
codeBlockBuilder.beginControlFlow(forEachSyntax)
}
val itemName = createListItemName(compoundData.propertyInfo.name)
addForEachStatement(compoundData.propertyInfo.name, itemName)
fun handleJunction(
entityData: EntityData.Nested,
parents: List<EntityData>,
accessProperties: List<PropertyInfo>,
insideCollection: Boolean = false
) {
val junction = entityData.junction ?: return
val listItemName = createListItemName(entityData.propertyInfo.name)
val junctionClassName = ClassName(junction.packageName, junction.className)
val junctionListName = titleToCamelCase(junction.className)
val entityAccessSyntax = createPropertyAccessSyntax(
accessProperties,
entityData.propertyInfo
)
val listItemPropertyInfo = PropertyInfo(
listItemName,
isNullable = false,
isCollection = false
)
val embeddedParentAccessSyntax = createPreviousEmbeddedEntityAccessSyntax(
parents,
junction.parentColumn
)
val embeddedEntityAccessSyntax = createNextEmbeddedEntityAccessSyntax(
listOf(listItemPropertyInfo),
entityData,
junction.entityColumn
)
val junctionCreationStatement = createEntityJunctionStatement(
junctionListName,
junction,
embeddedParentAccessSyntax,
embeddedEntityAccessSyntax
)
if (entityData.propertyInfo.isCollection && !insideCollection) {
addForEachStatement(
entityAccessSyntax.chain,
listItemName,
entityAccessSyntax.handleNullability
)
codeBlockBuilder.addStatement(junctionCreationStatement, junctionClassName)
.endControlFlow()
} else {
codeBlockBuilder.addStatement(junctionCreationStatement, junctionClassName)
}
}
fun handleEntity(
entityData: EntityData,
parents: List<EntityData> = listOf(),
accessProperties: List<PropertyInfo> = listOf()
) {
when (entityData) {
is EntityData.MainCompound -> entityData.entities.forEach { compoundEntityData ->
handleEntity(
compoundEntityData,
parents + entityData,
accessProperties + entityData.propertyInfo
)
}
is EntityData.Nested -> when(entityData) {
is EntityData.Compound -> {
if (entityData.propertyInfo.isCollection) {
val propertyAccessSyntax = createPropertyAccessSyntax(
accessProperties,
entityData.propertyInfo
)
val listItemName = createListItemName(entityData.propertyInfo.name)
addForEachStatement(
propertyAccessSyntax.chain,
listItemName,
propertyAccessSyntax.handleNullability
)
val listPropertyInfo = PropertyInfo(
listItemName,
isNullable = false,
isCollection = false
)
handleJunction(
entityData,
parents,
accessProperties,
insideCollection = true
)
entityData.entities.forEach { compoundEntityData ->
handleEntity(
compoundEntityData,
parents + entityData,
listOf(listPropertyInfo)
)
}
codeBlockBuilder.endControlFlow()
} else {
handleJunction(
entityData,
parents,
accessProperties,
insideCollection = true
)
entityData.entities.forEach { compoundEntityData ->
handleEntity(
compoundEntityData,
parents + entityData,
accessProperties + entityData.propertyInfo
)
}
}
}
is EntityData.Entity -> {
handleJunction(entityData, parents, accessProperties)
val parameterName = titleToCamelCase(entityData.typeInfo.className)
val propertyAccessSyntax = createPropertyAccessSyntax(
accessProperties,
entityData.propertyInfo
)
val listAdditionSyntax = createListAdditionSyntax(
parameterName,
propertyAccessSyntax,
entityData.propertyInfo.isCollection
)
codeBlockBuilder.addStatement(listAdditionSyntax)
}
}
}
}
handleEntity(compoundData)
return codeBlockBuilder.endControlFlow().build()
}
private fun createPreviousEmbeddedEntityAccessSyntax(
parents: List<EntityData>,
columnName: String
): PropertyAccessSyntax {
val accessParents = parents.map(EntityData::propertyInfo)
val collectionIndex = accessParents.indexOfLast { propertyInfo ->
propertyInfo.isCollection
}.takeIf { index ->
index in 1..parents.size
}
val newAccessParents = if (collectionIndex != null) {
accessParents.subList(collectionIndex, accessParents.size).toMutableList()
} else {
accessParents.toMutableList()
}
when (val parent = parents.last()) {
is EntityData.MainCompound -> {
newAccessParents.add(parent.entities.first(EntityData.Nested::isEmbedded).propertyInfo)
}
is EntityData.Compound -> {
newAccessParents.add(parent.entities.first(EntityData.Nested::isEmbedded).propertyInfo)
}
is EntityData.Entity -> {
// Do nothing, same entity
}
}
val columnPropertyInfo = PropertyInfo(
columnName,
isNullable = false,
isCollection = false
)
return createPropertyAccessSyntax(newAccessParents, columnPropertyInfo)
}
private fun createNextEmbeddedEntityAccessSyntax(
accessParents: List<PropertyInfo>,
entityData: EntityData,
columnName: String
): PropertyAccessSyntax {
val collectionIndex = accessParents.indexOfLast { propertyInfo ->
propertyInfo.isCollection
}.takeIf { index ->
index in 0..accessParents.lastIndex
}
val newAccessParents = if (collectionIndex != null) {
accessParents.toMutableList()
//accessParents.subList(collectionIndex, accessParents.size).toMutableList()
} else {
accessParents.toMutableList()
}
when (entityData) {
is EntityData.MainCompound -> {
newAccessParents.add(entityData.entities.first(EntityData.Nested::isEmbedded).propertyInfo)
}
is EntityData.Compound -> {
newAccessParents.add(entityData.entities.first(EntityData.Nested::isEmbedded).propertyInfo)
}
is EntityData.Entity -> {
// Do nothing, same entity
}
}
val columnInfo = PropertyInfo(
columnName,
isNullable = false,
isCollection = false
)
return createPropertyAccessSyntax(newAccessParents, columnInfo)
}
private fun createListActionBlock(
compoundData: EntityData.MainCompound,
actionMethodName: String
): CodeBlock {
val presentEntities = HashSet<String>()
val codeBlockBuilder = CodeBlock.builder()
val actionMethodCall = buildString {
append(actionMethodName, PARAMETER_OPEN_PARENTHESIS)
}
codeBlockBuilder.addStatement(actionMethodCall)
fun addActionParameter(className: String) {
val entityName = titleToCamelCase(className)
if (presentEntities.contains(entityName)) return
presentEntities.add(entityName)
val parameterWithSeparator = buildString {
append(entityName, PARAMETER_SEPARATOR)
}
codeBlockBuilder.addStatement(parameterWithSeparator)
}
fun handleEntity(entityData: EntityData) {
when (entityData) {
is EntityData.MainCompound -> entityData.entities.forEach(::handleEntity)
is EntityData.Nested -> {
entityData.junction?.let { junction ->
addActionParameter(junction.className)
}
when (entityData) {
is EntityData.Compound -> entityData.entities.forEach(::handleEntity)
is EntityData.Entity -> {
addActionParameter(entityData.typeInfo.className)
}
}
}
}
}
handleEntity(compoundData)
return codeBlockBuilder.addStatement(PARAMETER_CLOSE_PARENTHESIS).build()
}
private fun createListItemName(
listName: String,
): String {
val camelClassName = titleToCamelCase(listName)
return buildString { append(camelClassName, LIST_ITEM_POSTFIX) }
}
private fun createListInitializationBlock(
compoundData: EntityData.MainCompound
): CodeBlock {
val presentEntityLists = HashSet<String>()
val codeBlockBuilder = CodeBlock.builder()
fun addListInitializationStatement(packageName: String, className: String) {
val listName = titleToCamelCase(className)
if (presentEntityLists.contains(listName)) return
presentEntityLists.add(listName)
val entityClassName = ClassName(packageName, className)
val parentSetName = HashSet::class.asClassName().parameterizedBy(entityClassName)
val initializationSyntax = createInitializationSyntax(listName)
codeBlockBuilder.addStatement(initializationSyntax, parentSetName)
}
fun handleEntity(entityData: EntityData) {
when (entityData) {
is EntityData.MainCompound -> entityData.entities.forEach(::handleEntity)
is EntityData.Nested -> {
entityData.junction?.let { junction ->
addListInitializationStatement(junction.packageName, junction.className)
}
when (entityData) {
is EntityData.Compound -> entityData.entities.forEach(::handleEntity)
is EntityData.Entity -> addListInitializationStatement(
entityData.typeInfo.packageName,
entityData.typeInfo.className
)
}
}
}
}
handleEntity(compoundData)
return codeBlockBuilder.build()
}
private fun createPropertyAccessSyntax(
accessProperties: List<PropertyInfo>,
property: PropertyInfo
): PropertyAccessSyntax {
var handleNullability = false
val propertyNameBuilder = StringBuilder()
val propertyAccessBuilder = StringBuilder()
accessProperties.forEach { accessProperty ->
val name = if (accessProperty.isCollection) createListItemName(accessProperty.name)
else accessProperty.name
propertyAccessBuilder.append(name)
propertyNameBuilder.append(name)
handleNullability = handleNullability || accessProperty.isNullable
if (handleNullability) propertyAccessBuilder.append(NULLABLE_SIGN)
propertyAccessBuilder.append(INSTANCE_ACCESS_KEY)
propertyNameBuilder.append(CONSTANT_NAME_SEPARATOR)
}
propertyAccessBuilder.append(property.name)
propertyNameBuilder.append(property.name)
handleNullability = handleNullability || property.isNullable
return PropertyAccessSyntax(
propertyAccessBuilder.toString(),
propertyNameBuilder.toString(),
handleNullability
)
}
private fun createSingleActionFunction(
compoundClassName: ClassName,
parameterName: String,
listActionFunction: FunSpec,
isSuspend: Boolean,
actionName: String
): FunSpec {
val listCreationMethodCall = createMethodCallSyntax(
LIST_OF_METHOD,
parameterName
)
val actionMethodCall = createMethodCallSyntax(
actionName,
listCreationMethodCall
)
val functionBuilder = FunSpec.builder(actionName)
.addParameter(parameterName, compoundClassName)
.addStatement(actionMethodCall, listActionFunction)
if (isSuspend) functionBuilder.addModifiers(KModifier.SUSPEND)
return functionBuilder.build()
}
private fun createEntityJunctionStatement(
junctionListName: String,
junction: EntityJunction,
embeddedParentAccessSyntax: PropertyAccessSyntax,
embeddedEntityAccessSyntax: PropertyAccessSyntax
) = buildString {
val handleNullability = embeddedParentAccessSyntax.handleNullability ||
embeddedEntityAccessSyntax.handleNullability
if (handleNullability) {
append("if (")
if (embeddedParentAccessSyntax.handleNullability) {
append("${embeddedParentAccessSyntax.chain} != null")
if (embeddedEntityAccessSyntax.handleNullability) append(" && ")
}
if (embeddedEntityAccessSyntax.handleNullability) {
append("${embeddedEntityAccessSyntax.chain} != null")
}
append(")\n")
}
append(junctionListName, ".add(\n")
append("%T(\n")
append(junction.junctionParentColumn, " = ", embeddedParentAccessSyntax.chain, ",\n")
append(junction.junctionEntityColumn, " = ", embeddedEntityAccessSyntax.chain, "\n)")
append("\n)")
}
private fun createInsertAnnotationSpec(): AnnotationSpec {
val upsertAnnotationClassName = ClassName(
ROOM_PACKAGE,
INSERT_ANNOTATION
)
val conflictStrategyReplaceName = ClassName(
ROOM_PACKAGE,
listOf(
CONFLICT_STRATEGY,
CONFLICT_STRATEGY_REPLACE
)
)
val onConflictAssignment = createAssignSyntax(ON_CONFLICT_PARAMETER)
return AnnotationSpec.builder(upsertAnnotationClassName)
.addMember(onConflictAssignment, conflictStrategyReplaceName)
.build()
}
} | 0 | Kotlin | 1 | 1 | 90a35682a3e6b706c7a93ac58c722e01b81a811c | 29,174 | android-room-compound | Apache License 2.0 |
app/src/main/java/eu/kanade/presentation/more/settings/screen/SettingsReaderScreen.kt | komikku-app | 743,200,516 | false | {"Kotlin": 5951497} | package eu.kanade.presentation.more.settings.screen
import android.os.Build
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalView
import eu.kanade.presentation.more.settings.Preference
import eu.kanade.tachiyomi.ui.reader.setting.ReaderBottomButton
import eu.kanade.tachiyomi.ui.reader.setting.ReaderOrientation
import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences
import eu.kanade.tachiyomi.ui.reader.setting.ReadingMode
import eu.kanade.tachiyomi.ui.reader.viewer.pager.PagerConfig
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.collections.immutable.toImmutableMap
import tachiyomi.i18n.MR
import tachiyomi.i18n.sy.SYMR
import tachiyomi.presentation.core.i18n.stringResource
import tachiyomi.presentation.core.util.collectAsState
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.text.NumberFormat
object SettingsReaderScreen : SearchableSettings {
@ReadOnlyComposable
@Composable
override fun getTitleRes() = MR.strings.pref_category_reader
@Composable
override fun getPreferences(): List<Preference> {
val readerPref = remember { Injekt.get<ReaderPreferences>() }
// SY -->
val forceHorizontalSeekbar by readerPref.forceHorizontalSeekbar().collectAsState()
// SY <--
return listOf(
Preference.PreferenceItem.ListPreference(
pref = readerPref.defaultReadingMode(),
title = stringResource(MR.strings.pref_viewer_type),
entries = ReadingMode.entries.drop(1)
.associate { it.flagValue to stringResource(it.stringRes) }
.toImmutableMap(),
),
Preference.PreferenceItem.ListPreference(
pref = readerPref.doubleTapAnimSpeed(),
title = stringResource(MR.strings.pref_double_tap_anim_speed),
entries = persistentMapOf(
1 to stringResource(MR.strings.double_tap_anim_speed_0),
500 to stringResource(MR.strings.double_tap_anim_speed_normal),
250 to stringResource(MR.strings.double_tap_anim_speed_fast),
),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPref.showReadingMode(),
title = stringResource(MR.strings.pref_show_reading_mode),
subtitle = stringResource(MR.strings.pref_show_reading_mode_summary),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPref.showNavigationOverlayOnStart(),
title = stringResource(MR.strings.pref_show_navigation_mode),
subtitle = stringResource(MR.strings.pref_show_navigation_mode_summary),
),
// SY -->
Preference.PreferenceItem.SwitchPreference(
pref = readerPref.forceHorizontalSeekbar(),
title = stringResource(SYMR.strings.pref_force_horz_seekbar),
subtitle = stringResource(SYMR.strings.pref_force_horz_seekbar_summary),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPref.landscapeVerticalSeekbar(),
title = stringResource(SYMR.strings.pref_show_vert_seekbar_landscape),
subtitle = stringResource(SYMR.strings.pref_show_vert_seekbar_landscape_summary),
enabled = !forceHorizontalSeekbar,
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPref.leftVerticalSeekbar(),
title = stringResource(SYMR.strings.pref_left_handed_vertical_seekbar),
subtitle = stringResource(SYMR.strings.pref_left_handed_vertical_seekbar_summary),
enabled = !forceHorizontalSeekbar,
),
// SY <--
Preference.PreferenceItem.SwitchPreference(
pref = readerPref.trueColor(),
title = stringResource(MR.strings.pref_true_color),
subtitle = stringResource(MR.strings.pref_true_color_summary),
enabled = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O,
),
/* SY -->
Preference.PreferenceItem.SwitchPreference(
pref = readerPref.pageTransitions(),
title = stringResource(MR.strings.pref_page_transitions),
),
SY <-- */
Preference.PreferenceItem.SwitchPreference(
pref = readerPref.flashOnPageChange(),
title = stringResource(MR.strings.pref_flash_page),
subtitle = stringResource(MR.strings.pref_flash_page_summ),
),
getDisplayGroup(readerPreferences = readerPref),
getReadingGroup(readerPreferences = readerPref),
getPagedGroup(readerPreferences = readerPref),
getWebtoonGroup(readerPreferences = readerPref),
// SY -->
getContinuousVerticalGroup(readerPreferences = readerPref),
// SY <--
getNavigationGroup(readerPreferences = readerPref),
getActionsGroup(readerPreferences = readerPref),
// SY -->
getPageDownloadingGroup(readerPreferences = readerPref),
getForkSettingsGroup(readerPreferences = readerPref),
// SY <--
)
}
@Composable
private fun getDisplayGroup(readerPreferences: ReaderPreferences): Preference.PreferenceGroup {
val fullscreenPref = readerPreferences.fullscreen()
val fullscreen by fullscreenPref.collectAsState()
return Preference.PreferenceGroup(
title = stringResource(MR.strings.pref_category_display),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
pref = readerPreferences.defaultOrientationType(),
title = stringResource(MR.strings.pref_rotation_type),
entries = ReaderOrientation.entries.drop(1)
.associate { it.flagValue to stringResource(it.stringRes) }
.toImmutableMap(),
),
Preference.PreferenceItem.ListPreference(
pref = readerPreferences.readerTheme(),
title = stringResource(MR.strings.pref_reader_theme),
entries = persistentMapOf(
1 to stringResource(MR.strings.black_background),
2 to stringResource(MR.strings.gray_background),
0 to stringResource(MR.strings.white_background),
3 to stringResource(MR.strings.automatic_background),
),
),
Preference.PreferenceItem.SwitchPreference(
pref = fullscreenPref,
title = stringResource(MR.strings.pref_fullscreen),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.cutoutShort(),
title = stringResource(MR.strings.pref_cutout_short),
enabled = fullscreen &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
LocalView.current.rootWindowInsets?.displayCutout != null, // has cutout
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.keepScreenOn(),
title = stringResource(MR.strings.pref_keep_screen_on),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.showPageNumber(),
title = stringResource(MR.strings.pref_show_page_number),
),
),
)
}
@Composable
private fun getReadingGroup(readerPreferences: ReaderPreferences): Preference.PreferenceGroup {
return Preference.PreferenceGroup(
title = stringResource(MR.strings.pref_category_reading),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.skipRead(),
title = stringResource(MR.strings.pref_skip_read_chapters),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.skipFiltered(),
title = stringResource(MR.strings.pref_skip_filtered_chapters),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.skipDupe(),
title = stringResource(MR.strings.pref_skip_dupe_chapters),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.markReadDupe(),
title = stringResource(MR.strings.pref_mark_read_dupe_chapters),
subtitle = stringResource(MR.strings.pref_mark_read_dupe_chapters_summary),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.alwaysShowChapterTransition(),
title = stringResource(MR.strings.pref_always_show_chapter_transition),
),
),
)
}
@Composable
private fun getPagedGroup(readerPreferences: ReaderPreferences): Preference.PreferenceGroup {
val navModePref = readerPreferences.navigationModePager()
val imageScaleTypePref = readerPreferences.imageScaleType()
val dualPageSplitPref = readerPreferences.dualPageSplitPaged()
val rotateToFitPref = readerPreferences.dualPageRotateToFit()
val navMode by navModePref.collectAsState()
val imageScaleType by imageScaleTypePref.collectAsState()
val dualPageSplit by dualPageSplitPref.collectAsState()
val rotateToFit by rotateToFitPref.collectAsState()
return Preference.PreferenceGroup(
title = stringResource(MR.strings.pager_viewer),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
pref = navModePref,
title = stringResource(MR.strings.pref_viewer_nav),
entries = ReaderPreferences.TapZones
.mapIndexed { index, it -> index to stringResource(it) }
.toMap()
.toImmutableMap(),
),
Preference.PreferenceItem.ListPreference(
pref = readerPreferences.pagerNavInverted(),
title = stringResource(MR.strings.pref_read_with_tapping_inverted),
entries = persistentListOf(
ReaderPreferences.TappingInvertMode.NONE,
ReaderPreferences.TappingInvertMode.HORIZONTAL,
ReaderPreferences.TappingInvertMode.VERTICAL,
ReaderPreferences.TappingInvertMode.BOTH,
)
.associateWith { stringResource(it.titleRes) }
.toImmutableMap(),
enabled = navMode != 5,
),
Preference.PreferenceItem.ListPreference(
pref = imageScaleTypePref,
title = stringResource(MR.strings.pref_image_scale_type),
entries = ReaderPreferences.ImageScaleType
.mapIndexed { index, it -> index + 1 to stringResource(it) }
.toMap()
.toImmutableMap(),
),
Preference.PreferenceItem.ListPreference(
pref = readerPreferences.zoomStart(),
title = stringResource(MR.strings.pref_zoom_start),
entries = ReaderPreferences.ZoomStart
.mapIndexed { index, it -> index + 1 to stringResource(it) }
.toMap()
.toImmutableMap(),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.cropBorders(),
title = stringResource(MR.strings.pref_crop_borders),
),
// SY -->
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.pageTransitionsPager(),
title = stringResource(MR.strings.pref_page_transitions),
),
// SY <--
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.landscapeZoom(),
title = stringResource(MR.strings.pref_landscape_zoom),
enabled = imageScaleType == 1,
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.navigateToPan(),
title = stringResource(MR.strings.pref_navigate_pan),
enabled = navMode != 5,
),
Preference.PreferenceItem.SwitchPreference(
pref = dualPageSplitPref,
title = stringResource(MR.strings.pref_dual_page_split),
onValueChanged = {
rotateToFitPref.set(false)
true
},
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.dualPageInvertPaged(),
title = stringResource(MR.strings.pref_dual_page_invert),
subtitle = stringResource(MR.strings.pref_dual_page_invert_summary),
enabled = dualPageSplit,
),
Preference.PreferenceItem.SwitchPreference(
pref = rotateToFitPref,
title = stringResource(MR.strings.pref_page_rotate),
onValueChanged = {
dualPageSplitPref.set(false)
true
},
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.dualPageRotateToFitInvert(),
title = stringResource(MR.strings.pref_page_rotate_invert),
enabled = rotateToFit,
),
),
)
}
@Composable
private fun getWebtoonGroup(readerPreferences: ReaderPreferences): Preference.PreferenceGroup {
val numberFormat = remember { NumberFormat.getPercentInstance() }
val navModePref = readerPreferences.navigationModeWebtoon()
val dualPageSplitPref = readerPreferences.dualPageSplitWebtoon()
val rotateToFitPref = readerPreferences.dualPageRotateToFitWebtoon()
val webtoonSidePaddingPref = readerPreferences.webtoonSidePadding()
val navMode by navModePref.collectAsState()
val dualPageSplit by dualPageSplitPref.collectAsState()
val rotateToFit by rotateToFitPref.collectAsState()
val webtoonSidePadding by webtoonSidePaddingPref.collectAsState()
return Preference.PreferenceGroup(
title = stringResource(MR.strings.webtoon_viewer),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
pref = navModePref,
title = stringResource(MR.strings.pref_viewer_nav),
entries = ReaderPreferences.TapZones
.mapIndexed { index, it -> index to stringResource(it) }
.toMap()
.toImmutableMap(),
),
Preference.PreferenceItem.ListPreference(
pref = readerPreferences.webtoonNavInverted(),
title = stringResource(MR.strings.pref_read_with_tapping_inverted),
entries = persistentListOf(
ReaderPreferences.TappingInvertMode.NONE,
ReaderPreferences.TappingInvertMode.HORIZONTAL,
ReaderPreferences.TappingInvertMode.VERTICAL,
ReaderPreferences.TappingInvertMode.BOTH,
)
.associateWith { stringResource(it.titleRes) }
.toImmutableMap(),
enabled = navMode != 5,
),
Preference.PreferenceItem.SliderPreference(
value = webtoonSidePadding,
title = stringResource(MR.strings.pref_webtoon_side_padding),
subtitle = numberFormat.format(webtoonSidePadding / 100f),
min = ReaderPreferences.WEBTOON_PADDING_MIN,
max = ReaderPreferences.WEBTOON_PADDING_MAX,
onValueChanged = {
webtoonSidePaddingPref.set(it)
true
},
),
Preference.PreferenceItem.ListPreference(
pref = readerPreferences.readerHideThreshold(),
title = stringResource(MR.strings.pref_hide_threshold),
entries = persistentMapOf(
ReaderPreferences.ReaderHideThreshold.HIGHEST to stringResource(MR.strings.pref_highest),
ReaderPreferences.ReaderHideThreshold.HIGH to stringResource(MR.strings.pref_high),
ReaderPreferences.ReaderHideThreshold.LOW to stringResource(MR.strings.pref_low),
ReaderPreferences.ReaderHideThreshold.LOWEST to stringResource(MR.strings.pref_lowest),
),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.cropBordersWebtoon(),
title = stringResource(MR.strings.pref_crop_borders),
),
Preference.PreferenceItem.SwitchPreference(
pref = dualPageSplitPref,
title = stringResource(MR.strings.pref_dual_page_split),
onValueChanged = {
rotateToFitPref.set(false)
true
},
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.dualPageInvertWebtoon(),
title = stringResource(MR.strings.pref_dual_page_invert),
subtitle = stringResource(MR.strings.pref_dual_page_invert_summary),
enabled = dualPageSplit,
),
Preference.PreferenceItem.SwitchPreference(
pref = rotateToFitPref,
title = stringResource(MR.strings.pref_page_rotate),
onValueChanged = {
dualPageSplitPref.set(false)
true
},
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.dualPageRotateToFitInvertWebtoon(),
title = stringResource(MR.strings.pref_page_rotate_invert),
enabled = rotateToFit,
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.webtoonDoubleTapZoomEnabled(),
title = stringResource(MR.strings.pref_double_tap_zoom),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.webtoonDisableZoomOut(),
title = stringResource(MR.strings.pref_webtoon_disable_zoom_out),
),
// SY -->
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.pageTransitionsWebtoon(),
title = stringResource(MR.strings.pref_page_transitions),
),
// SY <--
),
)
}
// SY -->
@Composable
private fun getContinuousVerticalGroup(readerPreferences: ReaderPreferences): Preference.PreferenceGroup {
return Preference.PreferenceGroup(
title = stringResource(MR.strings.vertical_plus_viewer),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.continuousVerticalTappingByPage(),
title = stringResource(SYMR.strings.tap_scroll_page),
subtitle = stringResource(SYMR.strings.tap_scroll_page_summary),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.cropBordersContinuousVertical(),
title = stringResource(MR.strings.pref_crop_borders),
),
),
)
}
// SY <--
@Composable
private fun getNavigationGroup(readerPreferences: ReaderPreferences): Preference.PreferenceGroup {
val readWithVolumeKeysPref = readerPreferences.readWithVolumeKeys()
val readWithVolumeKeys by readWithVolumeKeysPref.collectAsState()
return Preference.PreferenceGroup(
title = stringResource(MR.strings.pref_reader_navigation),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SwitchPreference(
pref = readWithVolumeKeysPref,
title = stringResource(MR.strings.pref_read_with_volume_keys),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.readWithVolumeKeysInverted(),
title = stringResource(MR.strings.pref_read_with_volume_keys_inverted),
enabled = readWithVolumeKeys,
),
),
)
}
@Composable
private fun getActionsGroup(readerPreferences: ReaderPreferences): Preference.PreferenceGroup {
return Preference.PreferenceGroup(
title = stringResource(MR.strings.pref_reader_actions),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.readWithLongTap(),
title = stringResource(MR.strings.pref_read_with_long_tap),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.folderPerManga(),
title = stringResource(MR.strings.pref_create_folder_per_manga),
subtitle = stringResource(MR.strings.pref_create_folder_per_manga_summary),
),
),
)
}
// SY -->
@Composable
private fun getPageDownloadingGroup(readerPreferences: ReaderPreferences): Preference.PreferenceGroup {
return Preference.PreferenceGroup(
title = stringResource(SYMR.strings.page_downloading),
preferenceItems = persistentListOf(
Preference.PreferenceItem.ListPreference(
pref = readerPreferences.preloadSize(),
title = stringResource(SYMR.strings.reader_preload_amount),
subtitle = stringResource(SYMR.strings.reader_preload_amount_summary),
entries = persistentMapOf(
4 to stringResource(SYMR.strings.reader_preload_amount_4_pages),
6 to stringResource(SYMR.strings.reader_preload_amount_6_pages),
8 to stringResource(SYMR.strings.reader_preload_amount_8_pages),
10 to stringResource(SYMR.strings.reader_preload_amount_10_pages),
12 to stringResource(SYMR.strings.reader_preload_amount_12_pages),
14 to stringResource(SYMR.strings.reader_preload_amount_14_pages),
16 to stringResource(SYMR.strings.reader_preload_amount_16_pages),
20 to stringResource(SYMR.strings.reader_preload_amount_20_pages),
),
),
Preference.PreferenceItem.ListPreference(
pref = readerPreferences.readerThreads(),
title = stringResource(SYMR.strings.download_threads),
subtitle = stringResource(SYMR.strings.download_threads_summary),
entries = List(5) { it }.associateWith { it.toString() }.toImmutableMap(),
),
Preference.PreferenceItem.ListPreference(
pref = readerPreferences.cacheSize(),
title = stringResource(SYMR.strings.reader_cache_size),
subtitle = stringResource(SYMR.strings.reader_cache_size_summary),
entries = persistentMapOf(
"50" to "50 MB",
"75" to "75 MB",
"100" to "100 MB",
"150" to "150 MB",
"250" to "250 MB",
"500" to "500 MB",
"750" to "750 MB",
"1000" to "1 GB",
"1500" to "1.5 GB",
"2000" to "2 GB",
"2500" to "2.5 GB",
"3000" to "3 GB",
"3500" to "3.5 GB",
"4000" to "4 GB",
"4500" to "4.5 GB",
"5000" to "5 GB",
),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.aggressivePageLoading(),
title = stringResource(SYMR.strings.aggressively_load_pages),
subtitle = stringResource(SYMR.strings.aggressively_load_pages_summary),
),
),
)
}
@Composable
private fun getForkSettingsGroup(readerPreferences: ReaderPreferences): Preference.PreferenceGroup {
val pageLayout by readerPreferences.pageLayout().collectAsState()
return Preference.PreferenceGroup(
title = stringResource(SYMR.strings.pref_category_fork),
preferenceItems = persistentListOf(
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.readerInstantRetry(),
title = stringResource(SYMR.strings.skip_queue_on_retry),
subtitle = stringResource(SYMR.strings.skip_queue_on_retry_summary),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.preserveReadingPosition(),
title = stringResource(SYMR.strings.preserve_reading_position),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.useAutoWebtoon(),
title = stringResource(SYMR.strings.auto_webtoon_mode),
subtitle = stringResource(SYMR.strings.auto_webtoon_mode_summary),
),
Preference.PreferenceItem.MultiSelectListPreference(
pref = readerPreferences.readerBottomButtons(),
title = stringResource(SYMR.strings.reader_bottom_buttons),
subtitle = stringResource(SYMR.strings.reader_bottom_buttons_summary),
entries = ReaderBottomButton.entries
.associate { it.value to stringResource(it.stringRes) }
.toImmutableMap(),
),
Preference.PreferenceItem.ListPreference(
pref = readerPreferences.pageLayout(),
title = stringResource(SYMR.strings.page_layout),
subtitle = stringResource(SYMR.strings.automatic_can_still_switch),
entries = ReaderPreferences.PageLayouts
.mapIndexed { index, it -> index + 1 to stringResource(it) }
.toMap()
.toImmutableMap(),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.invertDoublePages(),
title = stringResource(SYMR.strings.invert_double_pages),
enabled = pageLayout != PagerConfig.PageLayout.SINGLE_PAGE,
),
Preference.PreferenceItem.ListPreference(
pref = readerPreferences.centerMarginType(),
title = stringResource(SYMR.strings.center_margin),
subtitle = stringResource(SYMR.strings.pref_center_margin_summary),
entries = ReaderPreferences.CenterMarginTypes
.mapIndexed { index, it -> index + 1 to stringResource(it) }
.toMap()
.toImmutableMap(),
),
Preference.PreferenceItem.SwitchPreference(
pref = readerPreferences.cacheArchiveMangaOnDisk(),
title = stringResource(SYMR.strings.cache_archived_manga_to_disk),
subtitle = stringResource(SYMR.strings.cache_archived_manga_to_disk_subtitle),
),
),
)
}
// SY <--
}
| 93 | Kotlin | 97 | 504 | bc460dd3b1edf67d095df0b15c6d1dc39444d5e6 | 29,773 | komikku | Apache License 2.0 |
boat-core/src/main/kotlin/xyz/srclab/common/base/BtLang.kt | srclab-projects | 247,777,997 | false | null | /**
* Boat language utilities.
*/
@file:JvmName("BtLang")
package xyz.srclab.common.base
import xyz.srclab.common.base.JumpPolicy.*
import java.util.concurrent.Callable
import java.util.function.*
/**
* Argument to suppress kotlin compile warn.
*/
const val INAPPLICABLE_JVM_NAME = "INAPPLICABLE_JVM_NAME"
/*
* --------------------------------------------------------------------------------
* Type alias start:
* --------------------------------------------------------------------------------
*/
typealias JavaString = java.lang.String
typealias JavaBoolean = java.lang.Boolean
typealias JavaByte = java.lang.Byte
typealias JavaShort = java.lang.Short
typealias JavaChar = java.lang.Character
typealias JavaInt = java.lang.Integer
typealias JavaLong = java.lang.Long
typealias JavaFloat = java.lang.Float
typealias JavaDouble = java.lang.Double
typealias JavaVoid = java.lang.Void
typealias JavaEnum<T> = java.lang.Enum<T>
typealias JavaFunction<T, R> = java.util.function.Function<T, R>
/*
* --------------------------------------------------------------------------------
* Type alias end.
* --------------------------------------------------------------------------------
*/
/*
* --------------------------------------------------------------------------------
* Java functional interfaces as Kotlin functions start:
* --------------------------------------------------------------------------------
*/
fun <T> Supplier<T>.asKotlinFun(): (() -> T) = { this.get() }
fun IntSupplier.asKotlinFun(): (() -> Int) = { this.asInt }
fun LongSupplier.asKotlinFun(): (() -> Long) = { this.asLong }
fun DoubleSupplier.asKotlinFun(): (() -> Double) = { this.asDouble }
fun <T> Predicate<T>.asKotlinFun(): (T) -> Boolean = { this.test(it) }
fun <T, R> JavaFunction<T, R>.asKotlinFun(): (T) -> R = { this.apply(it) }
fun <T> Consumer<T>.asKotlinFun(): (T) -> Unit = { this.accept(it) }
fun <T, U> BiPredicate<T, U>.asKotlinFun(): (T, U) -> Boolean = { t, u -> this.test(t, u) }
fun <T, U, R> BiFunction<T, U, R>.asKotlinFun(): (T, U) -> R = { t, u -> this.apply(t, u) }
fun <T, U> BiConsumer<T, U>.asKotlinFun(): (T, U) -> Unit = { t, u -> this.accept(t, u) }
fun <R> IntFunction<R>.asKotlinFun(): (Int) -> R = { this.apply(it) }
fun IntToLongFunction.asKotlinFun(): (Int) -> Long = { this.applyAsLong(it) }
fun IntToDoubleFunction.asKotlinFun(): (Int) -> Double = { this.applyAsDouble(it) }
fun <R> LongFunction<R>.asKotlinFun(): (Long) -> R = { this.apply(it) }
fun LongToIntFunction.asKotlinFun(): (Long) -> Int = { this.applyAsInt(it) }
fun LongToDoubleFunction.asKotlinFun(): (Long) -> Double = { this.applyAsDouble(it) }
fun <R> DoubleFunction<R>.asKotlinFun(): (Double) -> R = { this.apply(it) }
fun DoubleToIntFunction.asKotlinFun(): (Double) -> Int = { this.applyAsInt(it) }
fun DoubleToLongFunction.asKotlinFun(): (Double) -> Long = { this.applyAsLong(it) }
fun <T> IndexedPredicate<T>.asKotlinFun(): (Int, T) -> Boolean = { i, t -> this.test(i, t) }
fun <T, R> IndexedFunction<T, R>.asKotlinFun(): (Int, T) -> R = { i, t -> this.apply(i, t) }
fun <T> IndexedConsumer<T>.asKotlinFun(): (Int, T) -> Unit = { i, t -> this.accept(i, t) }
fun <T, U> IndexedBiPredicate<T, U>.asKotlinFun(): (Int, T, U) -> Boolean = { i, t, u -> this.test(i, t, u) }
fun <T, U, R> IndexedBiFunction<T, U, R>.asKotlinFun(): (Int, T, U) -> R = { i, t, u -> this.apply(i, t, u) }
fun <T, U> IndexedBiConsumer<T, U>.asKotlinFun(): (Int, T, U) -> Unit = { i, t, u -> this.accept(i, t, u) }
fun Runnable.asKotlinFun(): () -> Unit = { this.run() }
fun <V> Callable<V>.asKotlinFun(): () -> V = { this.call() }
/*
* --------------------------------------------------------------------------------
* Java functional interfaces as Kotlin functions end:
* --------------------------------------------------------------------------------
*/
/*
* --------------------------------------------------------------------------------
* Kotlin functions as Java functional interfaces start:
* --------------------------------------------------------------------------------
*/
fun <T> (() -> T).asJavaFun(): Supplier<T> = Supplier { this() }
fun <T> (() -> Int).asJavaFun(): IntSupplier = IntSupplier { this() }
fun <T> (() -> Long).asJavaFun(): LongSupplier = LongSupplier { this() }
fun <T> (() -> Double).asJavaFun(): DoubleSupplier = DoubleSupplier { this() }
fun <T> ((T) -> Boolean).asJavaFun(): Predicate<T> = Predicate { this(it) }
fun <T, R> ((T) -> R).asJavaFun(): JavaFunction<T, R> = Function { this(it) }
fun <T> ((T) -> Unit).asJavaFun(): Consumer<T> = Consumer { this(it) }
fun <T, U> ((T, U) -> Boolean).asJavaFun(): BiPredicate<T, U> = BiPredicate { t, u -> this(t, u) }
fun <T, U, R> ((T, U) -> R).asJavaFun(): BiFunction<T, U, R> = BiFunction { t, u -> this(t, u) }
fun <T, U> ((T, U) -> Unit).asJavaFun(): BiConsumer<T, U> = BiConsumer { t, u -> this(t, u) }
fun <R> ((Int) -> R).asJavaFun(): IntFunction<R> = IntFunction { this(it) }
fun ((Int) -> Long).asJavaFun(): IntToLongFunction = IntToLongFunction { this(it) }
fun ((Int) -> Double).asJavaFun(): IntToDoubleFunction = IntToDoubleFunction { this(it) }
fun <R> ((Long) -> R).asJavaFun(): LongFunction<R> = LongFunction { this(it) }
fun ((Long) -> Int).asJavaFun(): LongToIntFunction = LongToIntFunction { this(it) }
fun ((Long) -> Double).asJavaFun(): LongToDoubleFunction = LongToDoubleFunction { this(it) }
fun <R> ((Double) -> R).asJavaFun(): DoubleFunction<R> = DoubleFunction { this(it) }
fun ((Double) -> Int).asJavaFun(): DoubleToIntFunction = DoubleToIntFunction { this(it) }
fun ((Double) -> Long).asJavaFun(): DoubleToLongFunction = DoubleToLongFunction { this(it) }
fun <T> ((Int, T) -> Boolean).asJavaFun(): IndexedPredicate<T> = IndexedPredicate { i, it -> this(i, it) }
fun <T, R> ((Int, T) -> R).asJavaFun(): IndexedFunction<T, R> = IndexedFunction { i, it -> this(i, it) }
fun <T> ((Int, T) -> Unit).asJavaFun(): IndexedConsumer<T> = IndexedConsumer { i, t -> this(i, t) }
fun <T, U> ((Int, T, U) -> Boolean).asJavaFun(): IndexedBiPredicate<T, U> = IndexedBiPredicate() { i, t, u -> this(i, t, u) }
fun <T, U, R> ((Int, T, U) -> R).asJavaFun(): IndexedBiFunction<T, U, R> = IndexedBiFunction { i, t, u -> this(i, t, u) }
fun <T, U> ((Int, T, U) -> Unit).asJavaFun(): IndexedBiConsumer<T, U> = IndexedBiConsumer { i, t, u -> this(i, t, u) }
fun (() -> Any?).asRunnable(): Runnable = Runnable { this() }
fun <R> (() -> R).asCallable(): Callable<R> = Callable { this() }
/*
* --------------------------------------------------------------------------------
* Kotlin functions as Java functional interfaces end:
* --------------------------------------------------------------------------------
*/
/*
* --------------------------------------------------------------------------------
* Extension Java functional interfaces start:
* --------------------------------------------------------------------------------
*/
/**
* Functional interface represents [java.util.function.Predicate] with index.
*/
fun interface IndexedPredicate<T> {
/**
* Tests [t] with [index].
*/
fun test(index: Int, t: T): Boolean
}
/**
* Functional interface represents [java.util.function.Function] with index.
*/
fun interface IndexedFunction<T, R> {
/**
* Applies [t] with [index].
*/
fun apply(index: Int, t: T): R
}
/**
* Functional interface represents [java.util.function.Consumer] with index.
*/
fun interface IndexedConsumer<T> {
/**
* Accepts [t] with [index].
*/
fun accept(index: Int, t: T)
}
/**
* Functional interface represents [java.util.function.BiPredicate] with index.
*/
fun interface IndexedBiPredicate<T, U> {
/**
* Tests [t], [u] with [index].
*/
fun test(index: Int, t: T, u: U): Boolean
}
/**
* Functional interface represents [java.util.function.BiFunction] with index.
*/
fun interface IndexedBiFunction<T, U, R> {
/**
* Applies [t], [u] with [index].
*/
fun apply(index: Int, t: T, u: U): R
}
/**
* Functional interface represents [java.util.function.BiConsumer] with index.
*/
fun interface IndexedBiConsumer<T, U> {
/**
* Accepts [t], [u] with [index].
*/
fun accept(index: Int, t: T, u: U)
}
/*
* --------------------------------------------------------------------------------
* Extension Java functional interfaces end:
* --------------------------------------------------------------------------------
*/
/*
* --------------------------------------------------------------------------------
* Policies start:
* --------------------------------------------------------------------------------
*/
/**
* Policy of jump statement for process control: [CONTINUE], [BREAK], [RETURN] and [GO_ON].
*/
enum class JumpPolicy {
/**
* Stops the current execution of the iteration and proceeds to the next iteration in the loop.
*/
CONTINUE,
/**
* Stops the current loop and breaks out.
*/
BREAK,
/**
* Stops the current execution of the method and returns.
*/
RETURN,
/**
* Goes on the current execution, without stopping.
*/
GO_ON,
;
fun isContinue(): Boolean {
return this == CONTINUE
}
fun isBreak(): Boolean {
return this == BREAK
}
fun isReturn(): Boolean {
lazy { }
return this == RETURN
}
}
/**
* Policy for thread-safe.
*/
enum class ThreadSafePolicy {
/**
* Synchronized.
*/
SYNCHRONIZED,
/**
* Concurrent.
*/
CONCURRENT,
/**
* Thread-local.
*/
THREAD_LOCAL,
/**
* Copy-on-write.
*/
COPY_ON_WRITE,
/**
* No thread-safe.
*/
NONE,
;
}
/*
* --------------------------------------------------------------------------------
* Policies end.
* --------------------------------------------------------------------------------
*/ | 0 | Kotlin | 1 | 4 | a630d2897d5299af34ec17cfe335f3df3221851e | 9,911 | boat | Apache License 2.0 |
nativeVer/src/main/java/com/proxy/shadowsocksrn/ProxyAppsActivity.kt | vmlinz | 50,481,216 | true | {"C": 47424062, "Perl": 4124941, "Makefile": 1235759, "Assembly": 904486, "Shell": 842089, "Groff": 730619, "C++": 711767, "HTML": 398876, "Kotlin": 259743, "DIGITAL Command Language": 189824, "PHP": 147640, "Python": 110912, "Yacc": 105362, "CMake": 83638, "Batchfile": 14801, "XSLT": 11744, "Lex": 10310, "XS": 8638, "eC": 7420, "Java": 1960, "Objective-C": 1886, "Nix": 1224, "JavaScript": 1012, "Visual Basic": 294} | package com.proxy.shadowsocksr
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import android.view.View
import com.orhanobut.hawk.Hawk
import com.proxy.shadowsocksr.adapter.AppsAdapter
import com.proxy.shadowsocksr.adapter.items.AppItem
import com.proxy.shadowsocksr.ui.DialogManager
import java.util.ArrayList
class ProxyAppsActivity : AppCompatActivity(), AppsAdapter.OnItemClickListener
{
private var toolbar: Toolbar? = null
private var rvApps: RecyclerView? = null
private var appsAdapter: AppsAdapter? = null
private var appLst: MutableList<AppItem>? = null
private var proxyApps: ArrayList<String>? = null
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_proxy_apps)
toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val ab = delegate.supportActionBar
ab.setDisplayShowHomeEnabled(true)
ab.setDisplayHomeAsUpEnabled(true)
ab.setSubtitle(R.string.proxy_tip)
rvApps = findViewById(R.id.rv_proxy_apps) as RecyclerView
rvApps!!.layoutManager = LinearLayoutManager(this)
rvApps!!.setHasFixedSize(true)
appLst = ArrayList<AppItem>()
appsAdapter = AppsAdapter(appLst!!)
appsAdapter!!.onItemClickListener = this
rvApps!!.adapter = appsAdapter
//rvApps.setClipToPadding(false);
//rvApps.setPadding(0, 0, 0, ScreenUtil.getNavigationBarSize(this).y);
}
override fun onItemClick(v: View, pos: Int)
{
val ai = appLst!![pos]
if (ai.checked)
{
proxyApps!!.add(ai.pkgname)
}
else
{
proxyApps!!.remove(ai.pkgname)
}
Hawk.put<ArrayList<String>>("PerAppProxy", proxyApps)
}
override fun onResume()
{
super.onResume()
DialogManager.showTipDialog(this, R.string.wait_load_list);
//
Thread(Runnable {
proxyApps = Hawk.get<ArrayList<String>>("PerAppProxy")
//
val pm = packageManager
val i = Intent(Intent.ACTION_MAIN)
i.addCategory(Intent.CATEGORY_LAUNCHER)
val lst = pm.getInstalledApplications(0)
val self = packageName
for (appI in lst)
{
if (appI.uid < 10000 || appI.packageName == self)
{
continue
}
val ai = AppItem(appI.loadIcon(pm), appI.loadLabel(pm).toString(),
appI.packageName, proxyApps!!.contains(appI.packageName))
appLst!!.add(ai)
}
[email protected]({
appsAdapter!!.notifyDataSetChanged()
DialogManager.dismissTipDialog()
})
}).start()
}
override fun onPause()
{
super.onPause()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean
{
if (item.itemId == android.R.id.home)
{
finish()
}
return super.onOptionsItemSelected(item)
}
}
| 0 | C | 1 | 0 | 7b112f91ae554521e126825df8aba19d2ea060af | 3,389 | ShadowsocksRDroid | MIT License |
vector/src/main/java/com/angcyo/VectorKtx.kt | angcyo | 229,037,615 | false | null | package com.angcyo
import android.graphics.Paint
import android.graphics.Path
import com.angcyo.gcode.GCodeWriteHandler
import com.angcyo.library.annotation.Pixel
import com.angcyo.library.component.hawk.LibHawkKeys
import com.angcyo.library.ex.computePathBounds
import com.angcyo.library.ex.toListOf
import com.angcyo.library.model.PointD
import com.angcyo.library.unit.IValueUnit
import com.angcyo.svg.SvgWriteHandler
import com.angcyo.vector.VectorWriteHandler
import java.io.File
import java.io.FileOutputStream
import java.io.StringWriter
/**
* @author <a href="mailto:<EMAIL>">angcyo</a>
* @since 2023/04/12
*/
//region ---GCode---
/**
* 将[Path]转换成GCode字符串内容
* [style]
* [Paint.Style.STROKE]:只输出描边数据
* [Paint.Style.FILL]:只输出填充数据
* [Paint.Style.FILL_AND_STROKE]:同时输出描边和填充数据
* [output] 内容输出的文件路径*/
fun List<Path>.toGCodeContent(
output: File,
style: Paint.Style = Paint.Style.FILL_AND_STROKE,
writeFirst: Boolean = true,
writeLast: Boolean = true,
offsetLeft: Float = 0f, //x偏移的像素
offsetTop: Float = 0f, //y偏移的像素
pathStep: Float = LibHawkKeys._pathAcceptableError, //Path路径的采样步进
autoCnc: Boolean = false, //是否使用自动CNC
fillPathStep: Float = 1f, //填充的线距
fillAngle: Float = 0f, //填充线的角度
): File {
when (style) {
Paint.Style.STROKE -> {
toGCodeStrokeContent(
output,
writeFirst,
writeLast,
offsetLeft,
offsetTop,
pathStep,
autoCnc,
false
)
}
Paint.Style.FILL -> {
toGCodeFillContent(
output,
writeFirst,
writeLast,
offsetLeft,
offsetTop,
pathStep,
autoCnc,
false,
fillPathStep,
fillAngle,
)
}
else -> {
toGCodeStrokeContent(
output,
writeFirst,
writeLast,
offsetLeft,
offsetTop,
pathStep,
autoCnc,
false
)
toGCodeFillContent(
output,
writeFirst,
writeLast,
offsetLeft,
offsetTop,
pathStep,
autoCnc,
true,
fillPathStep,
fillAngle,
)
}
}
return output
}
/**只获取描边的数据*/
fun List<Path>.toGCodeStrokeContent(
output: File,
writeFirst: Boolean = true,
writeLast: Boolean = true,
offsetLeft: Float = 0f, //x偏移的像素
offsetTop: Float = 0f, //y偏移的像素
pathStep: Float = LibHawkKeys._pathAcceptableError, //Path路径的采样步进
autoCnc: Boolean = false, //是否使用自动CNC
append: Boolean = false, //是否是追加写入文本
): File {
//转换成GCode
val gCodeHandler = GCodeWriteHandler()
gCodeHandler.unit = IValueUnit.MM_UNIT
gCodeHandler.isAutoCnc = autoCnc
FileOutputStream(output, append).writer().use { writer ->
gCodeHandler.writer = writer
gCodeHandler.pathStrokeToVector(
this,
writeFirst,
writeLast,
offsetLeft,
offsetTop,
pathStep
)
}
return output
}
/**简单的将[Path]转成GCode
* [lastPoint] 最后一次的点, 如果有*/
fun Path.toGCodeStrokeSingleContent(
lastPoint: PointD? = null,
writeFirst: Boolean = false,
writeLast: Boolean = false,
action: GCodeWriteHandler.() -> Unit = {}
): String {
val gCodeHandler = GCodeWriteHandler()
gCodeHandler.unit = IValueUnit.MM_UNIT
gCodeHandler.isAutoCnc = false
gCodeHandler.action()
//---
StringWriter().use { writer ->
gCodeHandler.writer = writer
lastPoint?.let {
gCodeHandler._pointList.add(
VectorWriteHandler.VectorPoint(
it.x,
it.y,
VectorWriteHandler.POINT_TYPE_NEW
)
)
}
gCodeHandler.pathStrokeToVector(this, writeFirst, writeLast)
return writer.toString()
}
}
/**只获取填充的数据*/
fun List<Path>.toGCodeFillContent(
output: File,
writeFirst: Boolean = true,
writeLast: Boolean = true,
offsetLeft: Float = 0f, //x偏移的像素
offsetTop: Float = 0f, //y偏移的像素
pathStep: Float = LibHawkKeys._pathAcceptableError, //Path路径的采样步进
autoCnc: Boolean = false, //是否使用自动CNC
append: Boolean = false, //是否是追加写入文本
fillPathStep: Float = 1f, //填充的线距
fillAngle: Float = 0f, //填充线的角度
): File {
//转换成GCode
val gCodeHandler = GCodeWriteHandler()
gCodeHandler.unit = IValueUnit.MM_UNIT
gCodeHandler.isAutoCnc = autoCnc
FileOutputStream(output, append).writer().use { writer ->
gCodeHandler.writer = writer
gCodeHandler.pathFillToVector(
this,
writeFirst,
writeLast,
offsetLeft,
offsetTop,
pathStep,
fillPathStep,
fillAngle
)
}
return output
}
//endregion ---GCode---
//region ---SVG---
/**
* 将[Path]转换成SVG字符串内容
* [toGCodeContent]*/
fun List<Path>.toSVGContent(
output: File,
style: Paint.Style = Paint.Style.FILL_AND_STROKE,
offsetLeft: Float = 0f, //x偏移的像素
offsetTop: Float = 0f, //y偏移的像素
pathStep: Float = LibHawkKeys._pathAcceptableError, //Path路径的采样步进
fillPathStep: Float = 1f, //填充的线距
fillAngle: Float = 0f, //填充线的角度
): File {
when (style) {
Paint.Style.STROKE -> {
toSVGStrokeContentVectorStr(
output,
offsetLeft,
offsetTop,
pathStep,
false
)
}
Paint.Style.FILL -> {
toSVGFillContent(
output,
offsetLeft,
offsetTop,
pathStep,
false,
fillPathStep,
fillAngle,
)
}
else -> {
toSVGStrokeContentVectorStr(
output,
offsetLeft,
offsetTop,
pathStep,
false
)
toSVGFillContent(
output,
offsetLeft,
offsetTop,
pathStep,
true,
fillPathStep,
fillAngle,
)
}
}
return output
}
/**只获取描边的数据*/
fun List<Path>.toSVGStrokeContentVectorStr(
output: File,
offsetLeft: Float = 0f, //x偏移的像素
offsetTop: Float = 0f, //y偏移的像素
pathStep: Float = LibHawkKeys.svgTolerance, //Path路径的采样步进
append: Boolean = false, //是否是追加写入文本
wrapSvgXml: Boolean = false, //是否使用svg xml文档格式包裹
): File {
//转换成Svg, 使用像素单位
val svgWriteHandler = SvgWriteHandler()
FileOutputStream(output, append).writer().use { writer ->
svgWriteHandler.writer = writer
svgWriteHandler.gapValue = 1f
svgWriteHandler.gapMaxValue = 1f
if (wrapSvgXml) {
@Pixel val bounds = computePathBounds()
writer.write("""<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" viewBox="${bounds.left} ${bounds.top} ${bounds.right} ${bounds.bottom}">""")
writer.write("""<path stroke="black" fill="none" d="""")
}
svgWriteHandler.pathStrokeToVector(
this,
false,
true,
offsetLeft,
offsetTop,
pathStep
)
if (wrapSvgXml) {
writer.write(""""/></svg>""")
}
}
return output
}
fun Path.toSVGStrokeContentVectorStr(
offsetLeft: Float = 0f,
offsetTop: Float = 0f,
pathStep: Float = LibHawkKeys._pathAcceptableError,
action: (SvgWriteHandler) -> Unit = {}
): String {
return toListOf().toSVGStrokeContentVectorStr(offsetLeft, offsetTop, pathStep, action)
}
fun List<Path>.toSVGStrokeContentVectorStr(
offsetLeft: Float = 0f, //x偏移的像素
offsetTop: Float = 0f, //y偏移的像素
pathStep: Float = LibHawkKeys._pathAcceptableError,
action: (SvgWriteHandler) -> Unit = {}
): String {
val writer = StringWriter()
toSVGStrokeContentVectorStr(writer, offsetLeft, offsetTop, pathStep, action)
return writer.toString()
}
/**[toSVGStrokeContentVectorStr]*/
fun List<Path>.toSVGStrokeContentVectorStr(
writer: Appendable,
offsetLeft: Float = 0f, //x偏移的像素
offsetTop: Float = 0f, //y偏移的像素
pathStep: Float = LibHawkKeys._pathAcceptableError, //Path路径的采样步进
action: (SvgWriteHandler) -> Unit = {}
) {
//转换成Svg, 使用像素单位
val svgWriteHandler = SvgWriteHandler()
svgWriteHandler.writer = writer
svgWriteHandler.gapValue = 1f
svgWriteHandler.gapMaxValue = 1f
action(svgWriteHandler)
svgWriteHandler.pathStrokeToVector(
this,
false,
true,
offsetLeft,
offsetTop,
pathStep
)
}
/**只获取填充的数据*/
fun List<Path>.toSVGFillContent(
output: File,
offsetLeft: Float = 0f, //x偏移的像素
offsetTop: Float = 0f, //y偏移的像素
pathStep: Float = LibHawkKeys._pathAcceptableError, //Path路径的采样步进
append: Boolean = false, //是否是追加写入文本
fillPathStep: Float = 1f, //填充的线距
fillAngle: Float = 0f, //填充线的角度
): File {
//转换成Svg, 使用像素单位
val svgWriteHandler = SvgWriteHandler()
//svgWriteHandler.unit = mmUnit
FileOutputStream(output, append).writer().use { writer ->
svgWriteHandler.writer = writer
svgWriteHandler.gapValue = 1f
svgWriteHandler.gapMaxValue = 1f
svgWriteHandler.pathFillToVector(
this,
false,
true,
offsetLeft,
offsetTop,
pathStep,
fillPathStep,
fillAngle
)
}
return output
}
//endregion ---SVG---
| 0 | null | 6 | 5 | e1aeea2a677b585561879f3cdb0be6b1c6d1d458 | 9,927 | UICore | MIT License |
app/src/main/java/com/example/paging3sample/MainActivity.kt | LiarrDev | 594,680,154 | false | null | package com.example.paging3sample
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.DividerItemDecoration
import com.example.paging3sample.adapter.RepoAdapter
import com.example.paging3sample.adapter.RetryAdapter
import com.example.paging3sample.databinding.ActivityMainBinding
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private val viewModel by lazy { ViewModelProvider(this)[MainViewModel::class.java] }
private val repoAdapter = RepoAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.recycler.adapter = repoAdapter.withLoadStateFooter(
RetryAdapter { repoAdapter.retry() }
)
binding.recycler.addItemDecoration(
DividerItemDecoration(
this,
DividerItemDecoration.VERTICAL
)
)
lifecycleScope.launch {
viewModel.items.collect {
repoAdapter.submitData(it)
}
}
lifecycleScope.launch {
repoAdapter.loadStateFlow.collect {
binding.progressPrepend.isVisible = it.source.prepend is LoadState.Loading
binding.progressAppend.isVisible = it.source.append is LoadState.Loading
if (it.refresh is LoadState.Error) {
Toast.makeText(
this@MainActivity,
"Load Error: ${(it.refresh as LoadState.Error).error.message}",
Toast.LENGTH_SHORT
).show()
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 6b941896e3349325323c05aba32fb8f11998e551 | 1,975 | Paging3Sample | Apache License 2.0 |
simplified-reader-bookmarks-api/src/main/java/org/nypl/simplified/reader/bookmarks/api/ReaderBookmarkServiceType.kt | NYPL-Simplified | 30,199,881 | false | null | package org.nypl.simplified.reader.bookmarks.api
/**
* The reader bookmark service interface.
*/
interface ReaderBookmarkServiceType : AutoCloseable, ReaderBookmarkServiceUsableType {
override fun close()
}
| 109 | null | 21 | 32 | 781e4e2122f1528253a6cf17931083944f91ceba | 214 | Simplified-Android-Core | Apache License 2.0 |
carbon/src/commonMain/kotlin/com/gabrieldrn/carbon/dropdown/base/DropdownPopupContent.kt | gabrieldrn | 707,513,802 | false | {"Kotlin": 782975, "Swift": 4324, "JavaScript": 2279, "Python": 1797, "HTML": 468} | /*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package carbon.compose.dropdown.base
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.selection.selectable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import carbon.compose.Carbon
import carbon.compose.foundation.interaction.FocusIndication
import carbon.compose.foundation.spacing.SpacingScale
import carbon.compose.foundation.text.Text
private val checkmarkSize = 16.dp
/**
* DropdownPopupContent is the composable used to display the popup content of the dropdown. It
* displays a list of options that can be selected.
*
* @param K The type of option keys.
* @param options The list of options to display. The keys are the values that will be returned when
* an option is selected, and the values are the strings that will be displayed in the dropdown.
* @param selectedOption The currently selected option. If null, no option is selected.
* @param colors The colors to use for the dropdown.
* @param componentHeight The height of each option in the dropdown.
* @param onOptionClicked The callback to call when an option is selected.
* @param modifier The modifier to apply to the composable.
*/
@Composable
internal fun <K : Any> DropdownPopupContent(
options: Map<K, DropdownOption>,
selectedOption: K?,
colors: DropdownColors,
componentHeight: Dp,
onOptionClicked: (K) -> Unit,
modifier: Modifier = Modifier,
) {
val focusRequester = remember { FocusRequester() }
val optionEntries = remember(options) {
options.entries.toList()
}
val selectedOptionIndex = remember(optionEntries, selectedOption) {
optionEntries.indexOfFirst { it.key == selectedOption }
}
// Option to focus on when the composition ends.
val compositionEndTargetOption = remember(selectedOption, options) {
selectedOption ?: options.keys.first()
}
LazyColumn(
state = rememberLazyListState(
initialFirstVisibleItemIndex = options.keys.indexOf(compositionEndTargetOption)
),
modifier = modifier
.background(color = colors.menuOptionBackgroundColor)
.testTag(DropdownTestTags.POPUP_CONTENT)
) {
itemsIndexed(optionEntries) { index, optionEntry ->
SideEffect {
if (optionEntry.key == compositionEndTargetOption) {
focusRequester.requestFocus()
}
}
DropdownMenuOption(
option = optionEntry.value,
isSelected = index == selectedOptionIndex,
onOptionClicked = { onOptionClicked(optionEntry.key) },
// Hide divider: first item + when previous item is selected.
showDivider = index != 0 && index - 1 != selectedOptionIndex,
colors = colors,
modifier = Modifier
.fillMaxWidth()
.height(componentHeight)
.then(
if (optionEntry.key == compositionEndTargetOption) {
Modifier.focusRequester(focusRequester)
} else {
Modifier
}
)
)
}
}
}
@Composable
private fun DropdownMenuOption(
option: DropdownOption,
isSelected: Boolean,
colors: DropdownColors,
showDivider: Boolean,
onOptionClicked: () -> Unit,
modifier: Modifier = Modifier,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
) {
val menuOptionBackgroundSelectedColor by colors.menuOptionBackgroundSelectedColor(
isSelected = isSelected
)
val menuOptionTextColor by colors.menuOptionTextColor(
isEnabled = option.enabled,
isSelected = isSelected
)
Box(
modifier = modifier
.selectable(
selected = isSelected,
interactionSource = interactionSource,
indication = FocusIndication(),
enabled = option.enabled,
onClick = onOptionClicked
)
.background(color = menuOptionBackgroundSelectedColor)
.padding(horizontal = SpacingScale.spacing05)
.testTag(DropdownTestTags.MENU_OPTION)
) {
if (showDivider) {
DropdownMenuOptionDivider(
colors.menuOptionBorderColor,
modifier = Modifier
.align(Alignment.TopCenter)
.testTag(DropdownTestTags.MENU_OPTION_DIVIDER)
)
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxSize()
) {
Text(
text = option.value,
style = Carbon.typography.bodyCompact01,
color = menuOptionTextColor,
overflow = TextOverflow.Ellipsis,
maxLines = 1,
modifier = Modifier.weight(1f)
)
if (isSelected) {
Image(
imageVector = dropdownCheckmarkIcon,
contentDescription = null,
colorFilter = ColorFilter.tint(colors.checkmarkIconColor),
modifier = Modifier
.size(checkmarkSize)
.testTag(DropdownTestTags.MENU_OPTION_CHECKMARK)
)
} else {
Spacer(modifier = Modifier.size(checkmarkSize))
}
}
}
}
@Composable
internal fun DropdownMenuOptionDivider(
color: Color,
modifier: Modifier = Modifier
) {
Spacer(
modifier = modifier
.background(color = color)
.height(1.dp)
.fillMaxWidth()
)
}
| 4 | Kotlin | 6 | 59 | a479b1a97702c809a56892518ae9a0ccd6ddd89a | 7,606 | carbon-compose | Apache License 2.0 |
guide/src/test/kotlin/examples/example-traversal-01.kt | arrow-kt | 557,761,845 | false | null | // This file was automatically generated from traversal.md by Knit tool. Do not edit.
package arrow.website.examples.exampleTraversal01
import io.kotest.matchers.shouldBe
import arrow.optics.*
import arrow.optics.dsl.*
@optics data class Person(val name: String, val age: Int, val friends: List<Person>) {
companion object
}
fun List<Person>.happyBirthdayMap(): List<Person> =
map { Person.age.modify(it) { age -> age + 1 } }
fun List<Person>.happyBirthdayOptics(): List<Person> =
Every.list<Person>().age.modify(this) { age -> age + 1 }
fun Person.happyBirthdayFriends(): Person =
copy(
friends = friends.map { friend -> friend.copy(age = friend.age + 1) }
)
fun Person.happyBirthdayFriendsOptics(): Person =
Person.friends.every(Every.list()).age.modify(this) { it + 1 }
| 12 | Kotlin | 8 | 6 | 316abe029d69a0a0a1bbbd4ca569561f72e3fc86 | 796 | arrow-website | Apache License 2.0 |
app/src/main/java/com/zeynelerdi/mackolik/app/App.kt | ZeynelErdiKarabulut | 320,010,103 | false | {"Kotlin": 116012} | package com.zeynelerdi.mackolik.app
import com.zeynelerdi.mackolik.app.initializers.AppInitializers
import com.zeynelerdi.mackolik.di.component.DaggerAppComponent
import dagger.android.AndroidInjector
import dagger.android.DaggerApplication
import javax.inject.Inject
class App : DaggerApplication() {
@Inject
lateinit var initializers: AppInitializers
override fun onCreate() {
super.onCreate()
initializers.init(this)
}
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent.builder().create(this)
}
} | 0 | Kotlin | 0 | 1 | 4b40e57d2193706e15e18dd77fbb459e960f35db | 604 | Mackolik | Apache License 2.0 |
bindings/gtk/gdk4/src/nativeMain/kotlin/org/gtkkn/bindings/gdk/PopupLayout.kt | gtk-kn | 609,191,895 | false | {"Kotlin": 10448515, "Shell": 2740} | // This is a generated file. Do not modify.
package org.gtkkn.bindings.gdk
import kotlinx.cinterop.CPointed
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.reinterpret
import org.gtkkn.extensions.common.asBoolean
import org.gtkkn.extensions.glib.Record
import org.gtkkn.extensions.glib.RecordCompanion
import org.gtkkn.native.gdk.GdkPopupLayout
import org.gtkkn.native.gdk.gdk_popup_layout_copy
import org.gtkkn.native.gdk.gdk_popup_layout_equal
import org.gtkkn.native.gdk.gdk_popup_layout_get_anchor_hints
import org.gtkkn.native.gdk.gdk_popup_layout_get_anchor_rect
import org.gtkkn.native.gdk.gdk_popup_layout_get_rect_anchor
import org.gtkkn.native.gdk.gdk_popup_layout_get_surface_anchor
import org.gtkkn.native.gdk.gdk_popup_layout_new
import org.gtkkn.native.gdk.gdk_popup_layout_ref
import org.gtkkn.native.gdk.gdk_popup_layout_set_anchor_hints
import org.gtkkn.native.gdk.gdk_popup_layout_set_anchor_rect
import org.gtkkn.native.gdk.gdk_popup_layout_set_offset
import org.gtkkn.native.gdk.gdk_popup_layout_set_rect_anchor
import org.gtkkn.native.gdk.gdk_popup_layout_set_shadow_width
import org.gtkkn.native.gdk.gdk_popup_layout_set_surface_anchor
import org.gtkkn.native.gdk.gdk_popup_layout_unref
import kotlin.Boolean
import kotlin.Int
import kotlin.Unit
/**
* The `GdkPopupLayout` struct contains information that is
* necessary position a [[email protected]] relative to its parent.
*
* The positioning requires a negotiation with the windowing system,
* since it depends on external constraints, such as the position of
* the parent surface, and the screen dimensions.
*
* The basic ingredients are a rectangle on the parent surface,
* and the anchor on both that rectangle and the popup. The anchors
* specify a side or corner to place next to each other.
*
* 
*
* For cases where placing the anchors next to each other would make
* the popup extend offscreen, the layout includes some hints for how
* to resolve this problem. The hints may suggest to flip the anchor
* position to the other side, or to 'slide' the popup along a side,
* or to resize it.
*
* 
*
* 
*
* These hints may be combined.
*
* Ultimatively, it is up to the windowing system to determine the position
* and size of the popup. You can learn about the result by calling
* [[email protected]_position_x], [[email protected]_position_y],
* [[email protected]_rect_anchor] and [[email protected]_surface_anchor]
* after the popup has been presented. This can be used to adjust the rendering.
* For example, [[email protected]] changes its arrow position accordingly.
* But you have to be careful avoid changing the size of the popover, or it
* has to be presented again.
*
* ## Skipped during bindings generation
*
* - parameter `dx`: dx: Out parameter is not supported
* - parameter `left`: left: Out parameter is not supported
*/
public class PopupLayout(
pointer: CPointer<GdkPopupLayout>,
) : Record {
public val gdkPopupLayoutPointer: CPointer<GdkPopupLayout> = pointer
/**
* Makes a copy of @layout.
*
* @return a copy of @layout.
*/
public fun copy(): PopupLayout =
gdk_popup_layout_copy(gdkPopupLayoutPointer.reinterpret())!!.run {
PopupLayout(reinterpret())
}
/**
* Check whether @layout and @other has identical layout properties.
*
* @param other another `GdkPopupLayout`
* @return true if @layout and @other have identical layout properties,
* otherwise false.
*/
public fun equal(other: PopupLayout): Boolean =
gdk_popup_layout_equal(
gdkPopupLayoutPointer.reinterpret(),
other.gdkPopupLayoutPointer
).asBoolean()
/**
* Get the `GdkAnchorHints`.
*
* @return the `GdkAnchorHints`
*/
public fun getAnchorHints(): AnchorHints =
gdk_popup_layout_get_anchor_hints(gdkPopupLayoutPointer.reinterpret()).run {
AnchorHints(this)
}
/**
* Get the anchor rectangle.
*
* @return The anchor rectangle
*/
public fun getAnchorRect(): Rectangle =
gdk_popup_layout_get_anchor_rect(gdkPopupLayoutPointer.reinterpret())!!.run {
Rectangle(reinterpret())
}
/**
* Returns the anchor position on the anchor rectangle.
*
* @return the anchor on the anchor rectangle.
*/
public fun getRectAnchor(): Gravity =
gdk_popup_layout_get_rect_anchor(gdkPopupLayoutPointer.reinterpret()).run {
Gravity.fromNativeValue(this)
}
/**
* Returns the anchor position on the popup surface.
*
* @return the anchor on the popup surface.
*/
public fun getSurfaceAnchor(): Gravity =
gdk_popup_layout_get_surface_anchor(gdkPopupLayoutPointer.reinterpret()).run {
Gravity.fromNativeValue(this)
}
/**
* Increases the reference count of @value.
*
* @return the same @layout
*/
public fun ref(): PopupLayout =
gdk_popup_layout_ref(gdkPopupLayoutPointer.reinterpret())!!.run {
PopupLayout(reinterpret())
}
/**
* Set new anchor hints.
*
* The set @anchor_hints determines how @surface will be moved
* if the anchor points cause it to move off-screen. For example,
* %GDK_ANCHOR_FLIP_X will replace %GDK_GRAVITY_NORTH_WEST with
* %GDK_GRAVITY_NORTH_EAST and vice versa if @surface extends
* beyond the left or right edges of the monitor.
*
* @param anchorHints the new `GdkAnchorHints`
*/
public fun setAnchorHints(anchorHints: AnchorHints): Unit =
gdk_popup_layout_set_anchor_hints(gdkPopupLayoutPointer.reinterpret(), anchorHints.mask)
/**
* Set the anchor rectangle.
*
* @param anchorRect the new anchor rectangle
*/
public fun setAnchorRect(anchorRect: Rectangle): Unit =
gdk_popup_layout_set_anchor_rect(
gdkPopupLayoutPointer.reinterpret(),
anchorRect.gdkRectanglePointer
)
/**
* Offset the position of the anchor rectangle with the given delta.
*
* @param dx x delta to offset the anchor rectangle with
* @param dy y delta to offset the anchor rectangle with
*/
public fun setOffset(
dx: Int,
dy: Int,
): Unit = gdk_popup_layout_set_offset(gdkPopupLayoutPointer.reinterpret(), dx, dy)
/**
* Set the anchor on the anchor rectangle.
*
* @param anchor the new rect anchor
*/
public fun setRectAnchor(anchor: Gravity): Unit =
gdk_popup_layout_set_rect_anchor(
gdkPopupLayoutPointer.reinterpret(),
anchor.nativeValue
)
/**
* Sets the shadow width of the popup.
*
* The shadow width corresponds to the part of the computed
* surface size that would consist of the shadow margin
* surrounding the window, would there be any.
*
* @param left width of the left part of the shadow
* @param right width of the right part of the shadow
* @param top height of the top part of the shadow
* @param bottom height of the bottom part of the shadow
* @since 4.2
*/
public fun setShadowWidth(
left: Int,
right: Int,
top: Int,
bottom: Int,
): Unit =
gdk_popup_layout_set_shadow_width(
gdkPopupLayoutPointer.reinterpret(),
left,
right,
top,
bottom
)
/**
* Set the anchor on the popup surface.
*
* @param anchor the new popup surface anchor
*/
public fun setSurfaceAnchor(anchor: Gravity): Unit =
gdk_popup_layout_set_surface_anchor(
gdkPopupLayoutPointer.reinterpret(),
anchor.nativeValue
)
/**
* Decreases the reference count of @value.
*/
public fun unref(): Unit = gdk_popup_layout_unref(gdkPopupLayoutPointer.reinterpret())
public companion object : RecordCompanion<PopupLayout, GdkPopupLayout> {
/**
* Create a popup layout description.
*
* Used together with [[email protected]] to describe how a popup
* surface should be placed and behave on-screen.
*
* @anchor_rect is relative to the top-left corner of the surface's parent.
* @rect_anchor and @surface_anchor determine anchor points on @anchor_rect
* and surface to pin together.
*
* The position of @anchor_rect's anchor point can optionally be offset using
* [[email protected]_offset], which is equivalent to offsetting the
* position of surface.
*
* @param anchorRect the anchor `GdkRectangle` to align @surface with
* @param rectAnchor the point on @anchor_rect to align with @surface's anchor point
* @param surfaceAnchor the point on @surface to align with @rect's anchor point
* @return newly created instance of `GdkPopupLayout`
*/
public fun new(
anchorRect: Rectangle,
rectAnchor: Gravity,
surfaceAnchor: Gravity,
): PopupLayout =
PopupLayout(
gdk_popup_layout_new(
anchorRect.gdkRectanglePointer,
rectAnchor.nativeValue,
surfaceAnchor.nativeValue
)!!.reinterpret()
)
override fun wrapRecordPointer(pointer: CPointer<out CPointed>): PopupLayout =
PopupLayout(pointer.reinterpret())
}
}
| 0 | Kotlin | 0 | 13 | c033c245f1501134c5b9b46212cd153c61f7efea | 9,693 | gtk-kn | Creative Commons Attribution 4.0 International |
app/src/main/java/com/suadahaji/notify/searchnote/SearchFragment.kt | suada-haji | 212,331,094 | false | null | package com.suadahaji.notify.searchnote
import android.app.Activity
import android.app.SearchManager
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.view.*
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.widget.SearchView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.suadahaji.notify.R
import com.suadahaji.notify.database.NotesDatabase
import com.suadahaji.notify.databinding.FragmentSearchNoteBinding
import com.suadahaji.notify.listnotes.NoteClickListener
import com.suadahaji.notify.listnotes.NotesListAdapter
import com.suadahaji.notify.listnotes.NotesListViewModel
import com.suadahaji.notify.listnotes.NotesListViewModelFactory
class SearchFragment : Fragment() {
private lateinit var sharedPref: SharedPreferences
private lateinit var queryText: String
private lateinit var notesListViewModel: NotesListViewModel
private lateinit var adapter: NotesListAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding: FragmentSearchNoteBinding = DataBindingUtil.inflate(
inflater,
R.layout.fragment_search_note, container, false
)
val application = requireNotNull(this.activity).application
val dataSource = NotesDatabase.getInstance(application).noteDao
val viewModelFactory = NotesListViewModelFactory(dataSource, application)
notesListViewModel = ViewModelProviders.of(this, viewModelFactory).get(
NotesListViewModel::class.java
)
sharedPref = activity!!.getSharedPreferences(getString(R.string.search_query), 0)
binding.notesListViewModel = notesListViewModel
binding.setLifecycleOwner(this)
val manager = StaggeredGridLayoutManager(2, 1)
binding.noteList.layoutManager = manager
adapter = NotesListAdapter(NoteClickListener { noteId ->
notesListViewModel.onNoteClicked(noteId)
})
binding.noteList.adapter = adapter
setHasOptionsMenu(true)
notesListViewModel.navigatetoUpdateNote.observe(this, Observer { note ->
note?.let {
this.findNavController().navigate(
SearchFragmentDirections.actionSearchFragmentToEditNote(
note,
getString(R.string.update_note_tag)
)
)
val editor = sharedPref.edit()
editor.putString(getString(R.string.search_query), queryText)
editor.apply()
notesListViewModel.onNoteUpdateNavigated()
}
})
return binding.root
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.search_menu, menu)
val searchView = menu.findItem(R.id.search).actionView as SearchView
searchView.setIconifiedByDefault(true)
searchView.isFocusable = true
searchView.isIconified = false
searchView.clearFocus()
searchView.requestFocusFromTouch()
val searchManager = activity?.getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchView.setSearchableInfo(searchManager.getSearchableInfo(activity?.componentName))
queryText = sharedPref.getString(getString(R.string.search_query), null)!!
if (queryText.isNotEmpty()) {
searchView.setQuery(queryText, false)
loadQuery(queryText)
}
searchView.setOnSearchClickListener {
}
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
if (query != null) {
if (query.isNotEmpty()) loadQuery(query)
if (query.isEmpty()) loadQuery("null")
}
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
if (newText != null) {
if (newText.length > 1) loadQuery(newText)
if (newText.isEmpty()) loadQuery("null")
}
return false
}
})
searchView.setOnCloseListener {
this.findNavController().navigate(
SearchFragmentDirections.actionSearchFragmentToNotesList())
false
}
}
private fun loadQuery(s: String) {
queryText = s
notesListViewModel.searchAllNotes("%$s%")
notesListViewModel.searchNotes.observe(viewLifecycleOwner, Observer {
it?.let {
adapter.submitList(it)
}
})
}
override fun onDestroyView() {
super.onDestroyView()
val input: InputMethodManager =
activity?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
input.hideSoftInputFromWindow(view?.windowToken, 0)
}
} | 0 | Kotlin | 1 | 0 | a4424a2b2540d82c43134f0a10e6a4f22dfc6a77 | 5,380 | Notifyy | Apache License 2.0 |
src/main/kotlin/org/jetbrains/bazel/languages/starlark/psi/base/StarlarkBaseElement.kt | JetBrains | 709,213,338 | false | {"Kotlin": 189384, "Java": 46509, "Starlark": 19013, "Lex": 6398, "Scala": 5748} | package org.jetbrains.bazel.languages.starlark.psi.base
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.bazel.languages.starlark.psi.StarlarkElementVisitor
abstract class StarlarkBaseElement(node: ASTNode) : ASTWrapperPsiElement(node), StarlarkElement {
override fun accept(visitor: PsiElementVisitor) {
if (visitor is StarlarkElementVisitor) {
acceptVisitor(visitor)
} else {
super.accept(visitor)
}
}
protected abstract fun acceptVisitor(visitor: StarlarkElementVisitor)
}
| 0 | Kotlin | 0 | 9 | 94e4a42b40b2109b4710af83acb4c1787a9e4e42 | 608 | intellij-bazel | Apache License 2.0 |
KotlinExample/src/main/kotlin/programmers/basic/Day01/두수의곱/Solution.kt | sangki930 | 467,437,850 | false | {"Kotlin": 22081} | package programmers.basic.Day01.두수의곱
class Solution {
fun solution(num1: Int, num2: Int): Int {
var answer: Int = num1*num2
return answer
}
} | 0 | Kotlin | 0 | 0 | 98ad80d00a38c8f4c54a5bdd0fb5b26bf23a1655 | 166 | Kotlin | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/synthetics/CfnCanaryVisualReferencePropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.synthetics
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Any
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.synthetics.CfnCanary
/**
* Defines the screenshots to use as the baseline for comparisons during visual monitoring
* comparisons during future runs of this canary.
*
* If you omit this parameter, no changes are made to any baseline screenshots that the canary might
* be using already.
*
* Visual monitoring is supported only on canaries running the *syn-puppeteer-node-3.2* runtime or
* later. For more information, see [Visual
* monitoring](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Library_SyntheticsLogger_VisualTesting.html)
* and [Visual monitoring
* blueprint](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Blueprints_VisualTesting.html)
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.synthetics.*;
* VisualReferenceProperty visualReferenceProperty = VisualReferenceProperty.builder()
* .baseCanaryRunId("baseCanaryRunId")
* // the properties below are optional
* .baseScreenshots(List.of(BaseScreenshotProperty.builder()
* .screenshotName("screenshotName")
* // the properties below are optional
* .ignoreCoordinates(List.of("ignoreCoordinates"))
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-visualreference.html)
*/
@CdkDslMarker
public class CfnCanaryVisualReferencePropertyDsl {
private val cdkBuilder: CfnCanary.VisualReferenceProperty.Builder =
CfnCanary.VisualReferenceProperty.builder()
private val _baseScreenshots: MutableList<Any> = mutableListOf()
/**
* @param baseCanaryRunId Specifies which canary run to use the screenshots from as the baseline
* for future visual monitoring with this canary.
* Valid values are `nextrun` to use the screenshots from the next run after this update is made,
* `lastrun` to use the screenshots from the most recent run before this update was made, or the
* value of `Id` in the
* [CanaryRun](https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_CanaryRun.html)
* from any past run of this canary.
*/
public fun baseCanaryRunId(baseCanaryRunId: String) {
cdkBuilder.baseCanaryRunId(baseCanaryRunId)
}
/**
* @param baseScreenshots An array of screenshots that are used as the baseline for comparisons
* during visual monitoring.
*/
public fun baseScreenshots(vararg baseScreenshots: Any) {
_baseScreenshots.addAll(listOf(*baseScreenshots))
}
/**
* @param baseScreenshots An array of screenshots that are used as the baseline for comparisons
* during visual monitoring.
*/
public fun baseScreenshots(baseScreenshots: Collection<Any>) {
_baseScreenshots.addAll(baseScreenshots)
}
/**
* @param baseScreenshots An array of screenshots that are used as the baseline for comparisons
* during visual monitoring.
*/
public fun baseScreenshots(baseScreenshots: IResolvable) {
cdkBuilder.baseScreenshots(baseScreenshots)
}
public fun build(): CfnCanary.VisualReferenceProperty {
if(_baseScreenshots.isNotEmpty()) cdkBuilder.baseScreenshots(_baseScreenshots)
return cdkBuilder.build()
}
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 3,795 | awscdk-dsl-kotlin | Apache License 2.0 |
gto-support-scarlet-actioncable/src/main/java/org/ccci/gto/android/common/scarlet/actioncable/MessageMessageAdapter.kt | CruGlobal | 30,609,844 | false | null | package org.ccci.gto.android.common.scarlet.actioncable
import com.squareup.moshi.Moshi
import com.tinder.scarlet.MessageAdapter
import org.ccci.gto.android.common.scarlet.actioncable.model.Message
import org.ccci.gto.android.common.scarlet.actioncable.model.RawIncomingMessage
import org.ccci.gto.android.common.scarlet.actioncable.model.RawOutgoingMessage
import org.ccci.gto.android.common.scarlet.stringValue
import com.tinder.scarlet.Message as ScarletMessage
internal class MessageMessageAdapter<T>(
private val dataAdapter: MessageAdapter<T>,
moshi: Moshi,
annotations: Array<Annotation> = emptyArray()
) : MessageAdapter<Message<T>> {
private val anyAdapter = moshi.adapter(Any::class.java)
private val incomingMessageAdapter = moshi.adapter(RawIncomingMessage::class.java)
private val outgoingMessageAdapter = moshi.adapter(RawOutgoingMessage::class.java)
private val actionCableChannel = annotations.actionCableChannel
private val serializeDataAsJson = annotations.actionCableSerializeDataAsJson != null
override fun fromMessage(message: ScarletMessage) =
incomingMessageAdapter.fromJson(message.stringValue)!!.let {
it.identifier.require(actionCableChannel)
Message(
it.identifier,
dataAdapter.fromMessage(
when (it.message) {
is String -> it.message
else -> anyAdapter.toJson(it.message)
}
)
)
}
override fun toMessage(data: Message<T>): ScarletMessage {
data.identifier.require(actionCableChannel)
val payload = dataAdapter.toMessage(data.data).stringValue
.let { if (serializeDataAsJson) anyAdapter.fromJson(it)!! else it }
return ScarletMessage.Text(outgoingMessageAdapter.toJson(RawOutgoingMessage(data.identifier, payload)))
}
}
| 4 | Kotlin | 2 | 9 | 9e7da2772e422dbf3f773247cff34533830c0445 | 1,919 | android-gto-support | MIT License |
browser-kotlin/src/jsMain/kotlin/web/media/key/MediaKeyMessageEventInit.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6912722} | // Automatically generated - do not modify!
package web.media.key
import js.buffer.ArrayBuffer
import js.objects.JsPlainObject
import web.events.EventInit
@JsPlainObject
external interface MediaKeyMessageEventInit :
EventInit {
val message: ArrayBuffer
val messageType: MediaKeyMessageType
}
| 0 | Kotlin | 7 | 31 | 79f2034ed9610e4416dfde5b70a0ff06f88210b5 | 307 | types-kotlin | Apache License 2.0 |
src/main/kotlin/com/minskrotterdam/airquality/routes/Routes.kt | dmitrychebayewski | 245,884,429 | false | null | package com.minskrotterdam.airquality.routes
import com.minskrotterdam.airquality.config.API_ENDPOINT
import com.minskrotterdam.airquality.extensions.coroutineHandler
import com.minskrotterdam.airquality.handlers.*
import io.vertx.core.Vertx
import io.vertx.ext.web.Router
val STATIONS_PATH = "$API_ENDPOINT/stations"
val STATIONS_COORDINATES_PATH = "$STATIONS_PATH/coordinates"
val STATION_PATH = "$API_ENDPOINT/station"
val COMPONENTS_PATH = "$API_ENDPOINT/components"
val COMPONENT_FORMULA_PATH = "$API_ENDPOINT/component/info"
val COMPONENT_FORMULA_LIMIT_PATH = "$API_ENDPOINT/component/limit"
val MEASUREMENTS_PATH = "$API_ENDPOINT/measurements"
val MEASUREMENT_STATION_PATH = "$API_ENDPOINT/measurement/station"
val MEASUREMENT_REGION_PATH = "$API_ENDPOINT/measurement/region"
val MEASUREMENT_COMPONENTS_PATH = "$API_ENDPOINT/measurement/components"
class Routes(private val vertx: Vertx) {
fun createRouter(): Router {
val configHandlers = ConfigHandlers()
return Router.router(vertx).apply {
route().handler(configHandlers.corsHandler)
route().handler(configHandlers.bodyHandler)
get(STATIONS_COORDINATES_PATH).coroutineHandler { StationsHandler().getNearestStation(it) }
get("$STATIONS_PATH/:location").coroutineHandler { StationsHandler().stationsHandler(it) }
get("$STATION_PATH/:station_number").coroutineHandler { StationInformationHandler().stationInformationHandler(it) }
get(COMPONENTS_PATH).coroutineHandler { ComponentsHandler().pollutantComponentsHandler(it) }
get("$COMPONENT_FORMULA_PATH/:formula").coroutineHandler { ComponentInformationHandler().pollutantComponentInfoHandler(it) }
get("$COMPONENT_FORMULA_LIMIT_PATH/:formula").coroutineHandler { ComponentInformationHandler().pollutantComponentLimitHandler(it) }
get(MEASUREMENTS_PATH).coroutineHandler { MeasurementsHandler().airMeasurementsHandler(it) }
get("$MEASUREMENT_STATION_PATH/:station_number").coroutineHandler { AggregatedMeasurementsHandler().airMeasurementsHandler(it) }
get("$MEASUREMENT_REGION_PATH/:region").coroutineHandler { AggregatedMeasurementsHandler().aggregatedAirMeasurementsHandler(it) }
get(MEASUREMENT_COMPONENTS_PATH).coroutineHandler { AggregatedComponentsMeasurementHandler().aggregatedComponentsMeasurementHandler(it) }
route("/public/*").handler(configHandlers.staticHandler)
route().handler { configHandlers.otherPageHandler(it) }
}
}
} | 0 | Kotlin | 0 | 0 | 4aef42fff44875a240eccd41f6e72848aaad5d91 | 2,552 | airrotterdam-api | Apache License 2.0 |
app/src/main/java/com/quotes/ui/components/RefreshCta.kt | initishbhatt | 449,224,476 | false | {"Kotlin": 66548} | package com.quotes.ui.components
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.size
import androidx.compose.material.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.quotes.R
import com.quotes.utils.Tags
@Composable
fun RefreshCta(onRefreshButtonClick: () -> Unit) {
val isRotated = remember {
mutableStateOf(false)
}
val angle: Float by animateFloatAsState(
targetValue = if (isRotated.value) 180f else 0f,
animationSpec = tween(
durationMillis = 500,
easing = LinearEasing
),
finishedListener = { isRotated.value = false }
)
IconButton(onClick = {
onRefreshButtonClick()
isRotated.value = !isRotated.value
}) {
Image(
painter = painterResource(id = R.drawable.ic_refresh),
contentDescription = stringResource(R.string.refresh),
modifier = Modifier
.rotate(angle)
.size(64.dp).testTag(Tags.REFRESHCTA)
)
}
}
| 0 | Kotlin | 0 | 4 | aa05f92b4a4f2f0793a9e4588843fffe39b4491a | 1,588 | Quotes | MIT License |
apps/etterlatte-beregning-kafka/src/test/kotlin/no/nav/etterlatte/beregningkafka/MigreringBeregningHendelserRiverTest.kt | navikt | 417,041,535 | false | null | package no.nav.etterlatte.beregningkafka
import io.ktor.client.call.body
import io.ktor.client.statement.HttpResponse
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import kotlinx.coroutines.runBlocking
import no.nav.etterlatte.brev.model.Spraak
import no.nav.etterlatte.libs.common.IntBroek
import no.nav.etterlatte.libs.common.beregning.BeregningDTO
import no.nav.etterlatte.libs.common.beregning.BeregningsMetode
import no.nav.etterlatte.libs.common.beregning.Beregningsperiode
import no.nav.etterlatte.libs.common.beregning.Beregningstype
import no.nav.etterlatte.libs.common.grunnlag.Metadata
import no.nav.etterlatte.libs.common.rapidsandrivers.EVENT_NAME_KEY
import no.nav.etterlatte.libs.common.rapidsandrivers.FEILENDE_STEG
import no.nav.etterlatte.libs.common.rapidsandrivers.FEILMELDING_KEY
import no.nav.etterlatte.libs.common.tidspunkt.Tidspunkt
import no.nav.etterlatte.libs.common.toJson
import no.nav.etterlatte.libs.testdata.grunnlag.AVDOED_FOEDSELSNUMMER
import no.nav.etterlatte.rapidsandrivers.BEHANDLING_ID_KEY
import no.nav.etterlatte.rapidsandrivers.BEREGNING_KEY
import no.nav.etterlatte.rapidsandrivers.EventNames
import no.nav.etterlatte.rapidsandrivers.HENDELSE_DATA_KEY
import no.nav.etterlatte.rapidsandrivers.migrering.AvdoedForelder
import no.nav.etterlatte.rapidsandrivers.migrering.Beregning
import no.nav.etterlatte.rapidsandrivers.migrering.BeregningMeta
import no.nav.etterlatte.rapidsandrivers.migrering.Enhet
import no.nav.etterlatte.rapidsandrivers.migrering.MigreringRequest
import no.nav.etterlatte.rapidsandrivers.migrering.Migreringshendelser
import no.nav.etterlatte.rapidsandrivers.migrering.PesysId
import no.nav.etterlatte.rapidsandrivers.migrering.Trygdetid
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.time.YearMonth
import java.util.UUID
internal class MigreringBeregningHendelserRiverTest {
private val behandlingService = mockk<BeregningService>()
private val inspector = TestRapid().apply { MigreringBeregningHendelserRiver(this, behandlingService) }
private val beregningDTO =
BeregningDTO(
beregningId = UUID.randomUUID(),
behandlingId = UUID.randomUUID(),
type = Beregningstype.BP,
beregningsperioder =
listOf(
Beregningsperiode(
datoFOM = YearMonth.of(2024, 1),
datoTOM = null,
utbetaltBeloep = 2500,
grunnbelop = 100000,
trygdetid = 40,
samletNorskTrygdetid = 40,
grunnbelopMnd = 100000 / 12,
beregningsMetode = BeregningsMetode.NASJONAL,
trygdetidForIdent = null,
),
),
beregnetDato = Tidspunkt.now(),
grunnlagMetadata = Metadata(1234, 1),
overstyrBeregning = null,
)
private val fnr = AVDOED_FOEDSELSNUMMER
private val request =
MigreringRequest(
pesysId = PesysId(1),
enhet = Enhet("4817"),
soeker = fnr,
avdoedForelder = listOf(AvdoedForelder(fnr, Tidspunkt.now())),
dodAvYrkesskade = false,
gjenlevendeForelder = null,
foersteVirkningstidspunkt = YearMonth.now(),
beregning =
Beregning(
brutto = 1500,
netto = 1500,
anvendtTrygdetid = 40,
datoVirkFom = Tidspunkt.now(),
prorataBroek = null,
g = 100_000,
meta =
BeregningMeta(
beregningsMetodeType = "FOLKETRYGD",
resultatType = "",
resultatKilde = "AUTO",
kravVelgType = "",
),
),
trygdetid = Trygdetid(emptyList()),
spraak = Spraak.NN,
)
@BeforeEach
fun setUp() {
every { behandlingService.opprettBeregningsgrunnlag(any(), any()) } returns mockk()
}
@Test
fun `skal beregne etter folketrygd for migrering`() {
val behandlingId = slot<UUID>()
val returnValue =
mockk<HttpResponse>().also {
every {
runBlocking { it.body<BeregningDTO>() }
} returns beregningDTO
}
every { behandlingService.beregn(capture(behandlingId)) } returns returnValue
val melding =
JsonMessage.newMessage(
Migreringshendelser.BEREGN.lagEventnameForType(),
mapOf(
BEHANDLING_ID_KEY to "<KEY>",
HENDELSE_DATA_KEY to request,
),
)
inspector.sendTestMessage(melding.toJson())
assertEquals(UUID.fromString("a9d42eb9-561f-4320-8bba-2ba600e66e21"), behandlingId.captured)
assertEquals(1, inspector.inspektør.size)
val resultat = inspector.inspektør.message(0)
assertEquals(beregningDTO.toJson(), resultat.get(BEREGNING_KEY).toJson())
}
@Test
fun `skal beregne etter EOES for migrering`() {
val behandlingId = slot<UUID>()
val prorataBeregningDTO =
beregningDTO.copy(
beregningsperioder =
listOf(
beregningDTO.beregningsperioder.first().copy(
broek = IntBroek(150, 300),
beregningsMetode = BeregningsMetode.PRORATA,
samletTeoretiskTrygdetid = 40,
samletNorskTrygdetid = 40,
trygdetid = 20,
),
),
)
val returnValue =
mockk<HttpResponse>().also {
every {
runBlocking { it.body<BeregningDTO>() }
} returns prorataBeregningDTO
}
every { behandlingService.beregn(capture(behandlingId)) } returns returnValue
val melding =
JsonMessage.newMessage(
Migreringshendelser.BEREGN.lagEventnameForType(),
mapOf(
BEHANDLING_ID_KEY to "<KEY>",
HENDELSE_DATA_KEY to
request.copy(
beregning =
request.beregning.copy(
prorataBroek = IntBroek(150, 300),
meta =
request.beregning.meta!!.copy(
beregningsMetodeType = "EOS",
),
),
),
),
)
inspector.sendTestMessage(melding.toJson())
val resultat = inspector.inspektør.message(0)
assertTrue(
resultat.get(FEILMELDING_KEY).textValue()
.contains("Vi ønsker ikke å beregne saker med EOS for autmatisk gjenoppretting"),
)
}
@Test
fun `Beregning skal feile hvis beregnet beloep er lavere enn opprinnelig beloep fra Pesys`() {
val behandlingId = slot<UUID>()
val returnValue =
mockk<HttpResponse>().also {
every {
runBlocking { it.body<BeregningDTO>() }
} returns
beregningDTO.copy(
beregningsperioder =
listOf(
beregningDTO.beregningsperioder.first().copy(utbetaltBeloep = 500),
),
)
}
every { behandlingService.beregn(capture(behandlingId)) } returns returnValue
val melding =
JsonMessage.newMessage(
Migreringshendelser.BEREGN.lagEventnameForType(),
mapOf(
BEHANDLING_ID_KEY to "<KEY>",
HENDELSE_DATA_KEY to request,
),
)
inspector.sendTestMessage(melding.toJson())
assertEquals(UUID.fromString("a9d42eb9-561f-4320-8bba-2ba600e66e21"), behandlingId.captured)
assertEquals(1, inspector.inspektør.size)
val resultat = inspector.inspektør.message(0)
assertEquals(EventNames.FEILA.lagEventnameForType(), resultat.get(EVENT_NAME_KEY).textValue())
assertEquals(MigreringBeregningHendelserRiver::class.simpleName, resultat.get(FEILENDE_STEG).textValue())
assertTrue(
resultat.get(FEILMELDING_KEY).textValue()
.contains("Man skal ikke kunne komme dårligere ut på nytt regelverk."),
)
}
@Test
fun `Beregning skal feile hvis ulik trygdetid er benyttet`() {
val behandlingId = slot<UUID>()
val returnValue =
mockk<HttpResponse>().also {
every {
runBlocking { it.body<BeregningDTO>() }
} returns beregningDTO
}
every { behandlingService.beregn(capture(behandlingId)) } returns returnValue
val melding =
JsonMessage.newMessage(
Migreringshendelser.BEREGN.lagEventnameForType(),
mapOf(
BEHANDLING_ID_KEY to "<KEY>",
HENDELSE_DATA_KEY to
request.copy(
beregning =
request.beregning.copy(
anvendtTrygdetid = 35,
),
),
),
)
inspector.sendTestMessage(melding.toJson())
assertEquals(UUID.fromString("a<KEY>"), behandlingId.captured)
assertEquals(1, inspector.inspektør.size)
val resultat = inspector.inspektør.message(0)
assertEquals(EventNames.FEILA.lagEventnameForType(), resultat.get(EVENT_NAME_KEY).textValue())
assertEquals(MigreringBeregningHendelserRiver::class.simpleName, resultat.get(FEILENDE_STEG).textValue())
assertTrue(
resultat.get(FEILMELDING_KEY).textValue()
.contains("Beregning må være basert på samme trygdetid som i Pesys"),
)
}
@Test
fun `Beregning skal feile hvis ulik beregningsmetode er benyttet`() {
val behandlingId = slot<UUID>()
val returnValue =
mockk<HttpResponse>().also {
every {
runBlocking { it.body<BeregningDTO>() }
} returns
beregningDTO.copy(
beregningsperioder =
beregningDTO.beregningsperioder.map {
it.copy(
beregningsMetode = BeregningsMetode.PRORATA,
)
},
)
}
every { behandlingService.beregn(capture(behandlingId)) } returns returnValue
val melding =
JsonMessage.newMessage(
Migreringshendelser.BEREGN.lagEventnameForType(),
mapOf(
BEHANDLING_ID_KEY to "<KEY>",
HENDELSE_DATA_KEY to
request.copy(
beregning =
request.beregning.copy(
meta =
request.beregning.meta!!.copy(
beregningsMetodeType = "FOLKETRYGD",
),
),
),
),
)
inspector.sendTestMessage(melding.toJson())
assertEquals(UUID.fromString("a9d42eb9-561f-4320-8bba-2ba600e66e21"), behandlingId.captured)
assertEquals(1, inspector.inspektør.size)
val resultat = inspector.inspektør.message(0)
assertEquals(EventNames.FEILA.lagEventnameForType(), resultat.get(EVENT_NAME_KEY).textValue())
assertEquals(MigreringBeregningHendelserRiver::class.simpleName, resultat.get(FEILENDE_STEG).textValue())
assertTrue(
resultat.get(FEILMELDING_KEY).textValue()
.contains("Migrerte saker skal benytte samme beregningsmetode som Pesys."),
)
}
}
| 26 | null | 0 | 6 | 028742752b6152cf1fec8ccc1dffd55614a74cb3 | 12,796 | pensjon-etterlatte-saksbehandling | MIT License |
platform/platform-impl/src/com/intellij/ui/dsl/impl/PanelImpl.kt | jmrichardson | 444,361,501 | true | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.impl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.OnePixelDivider
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.SeparatorComponent
import com.intellij.ui.TitledSeparator
import com.intellij.ui.components.Label
import com.intellij.ui.dsl.*
import com.intellij.ui.dsl.Row
import com.intellij.ui.dsl.SpacingConfiguration
import com.intellij.ui.dsl.gridLayout.*
import com.intellij.ui.dsl.gridLayout.builders.RowsGridBuilder
import com.intellij.ui.layout.*
import org.jetbrains.annotations.ApiStatus
import javax.swing.*
import javax.swing.text.JTextComponent
import kotlin.math.min
@ApiStatus.Experimental
internal class PanelImpl(private val dialogPanelConfig: DialogPanelConfig) : CellBaseImpl<Panel>(
dialogPanelConfig), Panel {
companion object {
private val LOG = Logger.getInstance(PanelImpl::class.java)
private val DEFAULT_VERTICAL_GAP_COMPONENTS = setOf(
AbstractButton::class,
JComboBox::class,
JLabel::class,
JSpinner::class,
JTextComponent::class,
TitledSeparator::class
)
}
/**
* Number of [SpacingConfiguration.horizontalIndent] indents before each row in the panel
*/
private var panelContext = PanelContext()
private val rows = mutableListOf<RowImpl>()
override fun enabled(isEnabled: Boolean): PanelImpl {
rows.forEach { it.enabled(isEnabled) }
return this
}
override fun row(label: String, init: Row.() -> Unit): Row {
return row(Label(label), init)
}
override fun row(label: JLabel?, init: Row.() -> Unit): RowImpl {
val result = RowImpl(dialogPanelConfig, panelContext, label)
result.init()
rows.add(result)
return result
}
override fun group(title: String?, independent: Boolean, init: Panel.() -> Unit): Row {
val component = createSeparator(title)
if (independent) {
return row {
val panel = panel {
row {
cell(component)
.horizontalAlign(HorizontalAlign.FILL)
}
}
panel.indent {
init()
}
}.gap(TopGap.GROUP)
}
// todo
return RowImpl(dialogPanelConfig, panelContext)
}
override fun <T> buttonGroup(binding: PropertyBinding<T>, type: Class<T>, init: Panel.() -> Unit) {
dialogPanelConfig.context.addButtonGroup(BindButtonGroup(binding, type))
try {
this.init()
}
finally {
dialogPanelConfig.context.removeLastButtonGroup()
}
}
override fun visible(isVisible: Boolean): PanelImpl {
rows.forEach { it.visible(isVisible) }
return this
}
override fun horizontalAlign(horizontalAlign: HorizontalAlign): PanelImpl {
super.horizontalAlign(horizontalAlign)
return this
}
override fun verticalAlign(verticalAlign: VerticalAlign): PanelImpl {
super.verticalAlign(verticalAlign)
return this
}
override fun resizableColumn(): PanelImpl {
super.resizableColumn()
return this
}
override fun comment(@NlsContexts.DetailedDescription comment: String, maxLineLength: Int): PanelImpl {
super.comment(comment, maxLineLength)
return this
}
override fun gap(rightGap: RightGap): PanelImpl {
super.gap(rightGap)
return this
}
fun build(panel: DialogPanel, grid: JBGrid) {
val maxColumnsCount = getMaxColumnsCount()
val rowsGridBuilder = RowsGridBuilder(panel, grid = grid)
for ((index, row) in rows.withIndex()) {
if (row.cells.isEmpty()) {
LOG.warn("Row should not be empty")
continue
}
row.topGap?.let {
if (index > 0) {
rowsGridBuilder.setRowGaps(RowGaps(top = getRowTopGap(it)))
}
}
when (row.rowLayout) {
RowLayout.INDEPENDENT -> {
val subGrid = rowsGridBuilder.subGrid(width = maxColumnsCount, horizontalAlign = HorizontalAlign.FILL,
verticalAlign = VerticalAlign.FILL, gaps = Gaps(left = row.getIndent()))
val subGridBuilder = RowsGridBuilder(panel, subGrid)
val cells = row.cells
buildRow(cells, row.label != null, 0, cells.size, panel, subGridBuilder)
subGridBuilder.row()
buildCommentRow(cells, 0, cells.size, subGridBuilder)
setLastColumnResizable(subGridBuilder)
rowsGridBuilder.row()
}
RowLayout.LABEL_ALIGNED -> {
buildCell(row.cells[0], true, row.getIndent(), row.cells.size == 1, 1, panel, rowsGridBuilder)
if (row.cells.size > 1) {
val subGrid = rowsGridBuilder.subGrid(width = maxColumnsCount - 1, horizontalAlign = HorizontalAlign.FILL,
verticalAlign = VerticalAlign.FILL)
val subGridBuilder = RowsGridBuilder(panel, subGrid)
val cells = row.cells.subList(1, row.cells.size)
buildRow(cells, false, 0, cells.size, panel, subGridBuilder)
setLastColumnResizable(subGridBuilder)
}
rowsGridBuilder.row()
val commentedCellIndex = getCommentedCellIndex(row.cells)
when {
commentedCellIndex in 0..1 -> {
buildCommentRow(row.cells, row.getIndent(), maxColumnsCount, rowsGridBuilder)
}
commentedCellIndex > 1 -> {
// Always put comment for cells with index more than 1 at second cell because it's hard to implement
// more correct behaviour now. Can be fixed later
buildCommentRow(listOf(row.cells[0], row.cells[commentedCellIndex]), 0, maxColumnsCount, rowsGridBuilder)
}
}
}
RowLayout.PARENT_GRID -> {
buildRow(row.cells, row.label != null, row.getIndent(), maxColumnsCount, panel, rowsGridBuilder)
rowsGridBuilder.row()
buildCommentRow(row.cells, row.getIndent(), maxColumnsCount, rowsGridBuilder)
}
}
row.comment?.let {
val gaps = Gaps(left = row.getIndent(), bottom = dialogPanelConfig.spacing.verticalCommentBottomGap)
rowsGridBuilder.cell(it, maxColumnsCount, gaps = gaps)
rowsGridBuilder.row()
}
}
setLastColumnResizable(rowsGridBuilder)
}
override fun indent(init: Panel.() -> Unit) {
panelContext.indentCount++
try {
this.init()
}
finally {
panelContext.indentCount--
}
}
private fun setLastColumnResizable(builder: RowsGridBuilder) {
if (builder.resizableColumns.isEmpty() && builder.columnsCount > 0) {
builder.resizableColumns = setOf(builder.columnsCount - 1)
}
}
private fun buildRow(cells: List<CellBaseImpl<*>>,
firstCellLabel: Boolean,
firstCellIndent: Int,
maxColumnsCount: Int,
panel: DialogPanel,
builder: RowsGridBuilder) {
for ((cellIndex, cell) in cells.withIndex()) {
val lastCell = cellIndex == cells.size - 1
val width = if (lastCell) maxColumnsCount - cellIndex else 1
val leftGap = if (cellIndex == 0) firstCellIndent else 0
buildCell(cell, firstCellLabel && cellIndex == 0, leftGap, lastCell, width, panel, builder)
}
}
private fun buildCell(cell: CellBaseImpl<*>, rowLabel: Boolean, leftGap: Int, lastCell: Boolean, width: Int,
panel: DialogPanel, builder: RowsGridBuilder) {
val rightGap = getRightGap(cell, lastCell, rowLabel)
when (cell) {
is CellImpl<*> -> {
val insets = cell.component.insets
val visualPaddings = Gaps(top = insets.top, left = insets.left, bottom = insets.bottom, right = insets.right)
val verticalGap = getDefaultVerticalGap(cell.component)
val gaps = Gaps(top = verticalGap, left = leftGap, bottom = verticalGap, right = rightGap)
builder.cell(cell.component, width = width, horizontalAlign = cell.horizontalAlign, verticalAlign = cell.verticalAlign,
resizableColumn = cell.resizableColumn,
gaps = gaps, visualPaddings = visualPaddings)
}
is PanelImpl -> {
// todo visualPaddings
val gaps = Gaps(left = leftGap, right = rightGap)
val subGrid = builder.subGrid(width = width, horizontalAlign = cell.horizontalAlign, verticalAlign = cell.verticalAlign,
gaps = gaps)
cell.build(panel, subGrid)
}
}
}
/**
* Returns default top and bottom gap for [component]
*/
private fun getDefaultVerticalGap(component: JComponent): Int {
return if (DEFAULT_VERTICAL_GAP_COMPONENTS.any { clazz ->
clazz.isInstance(component)
}) dialogPanelConfig.spacing.verticalComponentGap
else 0
}
private fun getMaxColumnsCount(): Int {
return rows.maxOf {
when (it.rowLayout) {
RowLayout.INDEPENDENT -> 1
RowLayout.LABEL_ALIGNED -> min(2, it.cells.size)
RowLayout.PARENT_GRID -> it.cells.size
}
}
}
private fun getRightGap(cell: CellBaseImpl<*>, lastCell: Boolean, rowLabel: Boolean): Int {
val rightGap = cell.rightGap
if (lastCell) {
if (rightGap != null) {
LOG.warn("Right gap is set for last cell and will be ignored: rightGap = $rightGap")
}
return 0
}
if (rightGap != null) {
return when (rightGap) {
RightGap.SMALL -> dialogPanelConfig.spacing.horizontalSmallGap
}
}
return if (rowLabel) dialogPanelConfig.spacing.horizontalSmallGap else dialogPanelConfig.spacing.horizontalDefaultGap
}
/**
* Appends comment (currently one comment for a row is supported, can be fixed later)
*/
private fun buildCommentRow(cells: List<CellBaseImpl<*>>,
firstCellIndent: Int,
maxColumnsCount: Int,
builder: RowsGridBuilder) {
val commentedCellIndex = getCommentedCellIndex(cells)
if (commentedCellIndex < 0) {
return
}
val cell = cells[commentedCellIndex]
val leftIndent = getAdditionalHorizontalIndent(cell) +
if (commentedCellIndex == 0) firstCellIndent else 0
val gaps = Gaps(left = leftIndent, bottom = dialogPanelConfig.spacing.verticalCommentBottomGap)
builder.skip(commentedCellIndex)
builder.cell(cell.comment!!, maxColumnsCount - commentedCellIndex, gaps = gaps)
builder.row()
return
}
private fun getAdditionalHorizontalIndent(cell: CellBaseImpl<*>): Int {
return if (cell is CellImpl<*> && cell.viewComponent is JToggleButton)
dialogPanelConfig.spacing.horizontalToggleButtonIndent
else
0
}
private fun getCommentedCellIndex(cells: List<CellBaseImpl<*>>): Int {
return cells.indexOfFirst { it.comment != null }
}
private fun getRowTopGap(topGap: TopGap): Int {
return when (topGap) {
TopGap.GROUP -> dialogPanelConfig.spacing.verticalGroupTopGap
TopGap.SMALL -> dialogPanelConfig.spacing.verticalSmallTopGap
}
}
private fun createSeparator(@NlsContexts.BorderTitle title: String?): JComponent {
if (title == null) {
return SeparatorComponent(0, OnePixelDivider.BACKGROUND, null)
}
val result = TitledSeparator(title)
result.border = null
return result
}
}
internal class PanelContext(
/**
* Number of [SpacingConfiguration.horizontalIndent] indents before each row in the panel
*/
var indentCount: Int = 0) | 0 | null | 0 | 0 | b1430145bf57376d3f34f4eec87d18b7f9d4e14f | 11,560 | intellij-community | Apache License 2.0 |
practicas/app/src/main/java/com/adrianbalam/practicas/todoapp/TareasAdaptador.kt | adrianbalam | 615,909,656 | false | null | package com.adrianbalam.practicas.todoapp
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.adrianbalam.practicas.R
class TareasAdaptador(
private val itemList: List<TareaMolde>,
private val borrarItem: (Int) -> Unit
) : RecyclerView.Adapter<TareasAdaptador.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_tarea, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (itemList.isNotEmpty()) {
val item = itemList[position]
holder.tvNombreTarea.setText(item.titulo)
holder.tvDescTarea.setText(item.desc)
holder.cvTarea.setOnClickListener {
borrarItem(position)
}
}
}
override fun getItemCount(): Int {
return itemList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvNombreTarea: TextView = itemView.findViewById(R.id.tvNombreTarea)
val tvDescTarea: TextView = itemView.findViewById(R.id.tvDescTarea)
val cvTarea: CardView = itemView.findViewById(R.id.cvTarea)
}
} | 0 | Kotlin | 0 | 0 | 4ad2850741c192e06bf1ced361cf16eee9b4aad6 | 1,430 | EjemploAndroid | MIT License |
platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl
import com.intellij.DynamicBundle
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.impl.ActionMenu
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.wm.IdeFrame
import com.intellij.platform.ide.menu.*
import com.intellij.ui.Gray
import com.intellij.ui.ScreenUtil
import com.intellij.ui.mac.foundation.NSDefaults
import com.intellij.ui.mac.screenmenu.Menu
import com.intellij.ui.plaf.beg.IdeaMenuUI
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.StartupUiUtil
import kotlinx.coroutines.CoroutineScope
import java.awt.Dimension
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.geom.AffineTransform
import javax.swing.*
import javax.swing.border.Border
internal enum class IdeMenuBarState {
EXPANDED,
COLLAPSING,
COLLAPSED,
EXPANDING,
TEMPORARY_EXPANDED;
val isInProgress: Boolean
get() = this == COLLAPSING || this == EXPANDING
}
@Suppress("LeakingThis")
open class IdeMenuBar internal constructor(@JvmField internal val coroutineScope: CoroutineScope,
@JvmField internal val frame: JFrame,
private val explicitMainMenuActionGroup: ActionGroup? = null) : JMenuBar(), ActionAwareIdeMenuBar {
private val menuBarHelper: IdeMenuBarHelper
private val updateGlobalMenuRootsListeners = mutableListOf<Runnable>()
val rootMenuItems: List<ActionMenu>
get() = components.mapNotNull { it as? ActionMenu }
init {
val flavor = if (isFloatingMenuBarSupported) {
FloatingMenuBarFlavor(this)
}
else {
object : IdeMenuFlavor {
override fun updateAppMenu() {
doUpdateAppMenu()
}
}
}
val facade = object : IdeMenuBarHelper.MenuBarImpl {
override val frame: JFrame
get() = [email protected]
override val coroutineScope: CoroutineScope
get() = [email protected]
override val isDarkMenu: Boolean
get() = [email protected]
override val component: JComponent
get() = this@IdeMenuBar
override fun updateGlobalMenuRoots() {
[email protected]()
}
override suspend fun getMainMenuActionGroup(): ActionGroup? = explicitMainMenuActionGroup ?: [email protected]()
}
menuBarHelper = JMenuBasedIdeMenuBarHelper(flavor = flavor, menuBar = facade)
if (IdeFrameDecorator.isCustomDecorationActive()) {
isOpaque = false
}
}
override fun add(menu: JMenu): JMenu {
menu.isFocusable = false
return super.add(menu)
}
override fun getBorder(): Border? {
@Suppress("UNNECESSARY_SAFE_CALL")
val state = menuBarHelper?.flavor?.state ?: IdeMenuBarState.EXPANDED
// avoid moving lines
if (state == IdeMenuBarState.EXPANDING || state == IdeMenuBarState.COLLAPSING) {
return JBUI.Borders.empty()
}
if (IdeFrameDecorator.isCustomDecorationActive()) {
return JBUI.Borders.empty()
}
// fix for a Darcula double border
if (state == IdeMenuBarState.TEMPORARY_EXPANDED && StartupUiUtil.isUnderDarcula) {
return JBUI.Borders.customLine(Gray._75, 0, 0, 1, 0)
}
// save 1px for mouse handler
if (state == IdeMenuBarState.COLLAPSED) {
return JBUI.Borders.emptyBottom(1)
}
val uiSettings = UISettings.getInstance()
return if (uiSettings.showMainToolbar || uiSettings.showNavigationBar) super.getBorder() else null
}
override fun paint(g: Graphics) {
// otherwise, there will be a 1px line on top
if (menuBarHelper.flavor.state != IdeMenuBarState.COLLAPSED) {
super.paint(g)
}
}
override fun doLayout() {
super.doLayout()
menuBarHelper.flavor.layoutClockPanelAndButton()
}
override fun menuSelectionChanged(isIncluded: Boolean) {
menuBarHelper.flavor.jMenuSelectionChanged(isIncluded)
super.menuSelectionChanged(isIncluded)
}
internal val isActivated: Boolean
get() {
val index = selectionModel.selectedIndex
return index != -1 && getMenu(index).isPopupMenuVisible
}
override fun getPreferredSize(): Dimension {
return menuBarHelper.flavor.getPreferredSize(super.getPreferredSize())
}
override fun removeNotify() {
if (ScreenUtil.isStandardAddRemoveNotify(this)) {
menuBarHelper.flavor.suspendAnimator()
}
super.removeNotify()
}
override fun updateMenuActions(forceRebuild: Boolean) {
menuBarHelper.updateMenuActions(forceRebuild)
}
internal open val isDarkMenu: Boolean
get() = SystemInfo.isMacSystemMenu && NSDefaults.isDarkMenuBar()
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
if (isOpaque) {
paintBackground(g)
}
}
fun addUpdateGlobalMenuRootsListener(runnable: Runnable) {
updateGlobalMenuRootsListeners.add(runnable)
}
fun removeUpdateGlobalMenuRootsListener(runnable: Runnable) {
updateGlobalMenuRootsListeners.remove(runnable)
}
private fun paintBackground(g: Graphics) {
if (IdeFrameDecorator.isCustomDecorationActive()) {
val window = SwingUtilities.getWindowAncestor(this)
if (window is IdeFrame && !(window as IdeFrame).isInFullScreen) {
return
}
}
if (StartupUiUtil.isUnderDarcula || StartupUiUtil.isUnderIntelliJLaF()) {
g.color = IdeaMenuUI.getMenuBackgroundColor()
g.fillRect(0, 0, width, height)
}
}
override fun paintChildren(g: Graphics) {
if (menuBarHelper.flavor.state.isInProgress) {
val g2 = g as Graphics2D
val oldTransform = g2.transform
val newTransform = if (oldTransform == null) AffineTransform() else AffineTransform(oldTransform)
newTransform.concatenate(AffineTransform.getTranslateInstance(0.0, (height - super.getPreferredSize().height).toDouble()))
g2.transform = newTransform
super.paintChildren(g2)
g2.transform = oldTransform
}
else if (menuBarHelper.flavor.state != IdeMenuBarState.COLLAPSED) {
super.paintChildren(g)
}
}
open suspend fun getMainMenuActionGroup(): ActionGroup? = explicitMainMenuActionGroup ?: getAndWrapMainMenuActionGroup()
override fun getMenuCount(): Int {
@Suppress("IfThenToElvis", "SENSELESS_COMPARISON")
return if (menuBarHelper == null) 0 else menuBarHelper.flavor.correctMenuCount(super.getMenuCount())
}
internal open fun updateGlobalMenuRoots() {
for (listener in updateGlobalMenuRootsListeners) {
listener.run()
}
}
internal open fun doInstallAppMenuIfNeeded(frame: JFrame) {}
open fun onToggleFullScreen(isFullScreen: Boolean) {}
}
private val LOG: Logger
get() = logger<IdeMenuBar>()
// NOTE: for OSX only
internal fun doUpdateAppMenu() {
if (!Menu.isJbScreenMenuEnabled()) {
return
}
// 1. rename with localized
Menu.renameAppMenuItems(DynamicBundle(IdeMenuBar::class.java, "messages.MacAppMenuBundle"))
//
// 2. add custom new items in AppMenu
//
//Example (add new item after "Preferences"):
//int pos = appMenu.findIndexByTitle("Pref.*");
//int pos2 = appMenu.findIndexByTitle("NewCustomItem");
//if (pos2 < 0) {
// MenuItem mi = new MenuItem();
// mi.setLabel("NewCustomItem", null);
// mi.setActionDelegate(() -> System.err.println("NewCustomItem executes"));
// appMenu.add(mi, pos, true);
//}
}
internal fun installAppMenuIfNeeded(frame: JFrame) {
if (!SystemInfoRt.isLinux) {
return
}
val menuBar = frame.jMenuBar
// must be called when frame is visible (otherwise frame.getPeer() == null)
if (menuBar is IdeMenuBar) {
try {
menuBar.doInstallAppMenuIfNeeded(frame)
}
catch (e: Throwable) {
LOG.warn("cannot install app menu", e)
}
}
else if (menuBar != null) {
LOG.info("The menu bar '$menuBar of frame '$frame' isn't instance of IdeMenuBar")
}
} | 229 | null | 4931 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 8,217 | intellij-community | Apache License 2.0 |
app/src/main/java/me/hufman/androidautoidrive/BackgroundInterruptionDetection.kt | BimmerGestalt | 164,273,785 | false | {"Kotlin": 1839646, "Python": 4131, "HTML": 3912, "Shell": 1732} | package me.hufman.androidautoidrive
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences
import android.os.Handler
import android.os.Looper
/**
* Utility class to determine whether the phone has ever suspended or killed the app in the background
*
* The client should
*/
class BackgroundInterruptionDetection(val preferences: SharedPreferences, val handler: Handler,
val ttl: Long = DEFAULT_TTL, val timeProvider: () -> Long = {System.currentTimeMillis()}) {
companion object {
const val BACKGROUND_PERSISTENCE_NAME = "BackgroundInterruptionDetection.json"
const val DEFAULT_TTL = 10_000L // 10 seconds TTL
const val MINIMUM_RUNNING_TIME = 300_000L // stay alive for a length of time before clearing error counters
fun build(context: Context, handler: Handler? = null,
ttl: Long = DEFAULT_TTL, timeProvider: () -> Long = {System.currentTimeMillis()}): BackgroundInterruptionDetection {
return BackgroundInterruptionDetection(
context.getSharedPreferences(BACKGROUND_PERSISTENCE_NAME, MODE_PRIVATE),
handler ?: Handler(Looper.getMainLooper()),
ttl, timeProvider
)
}
}
val startTime = timeProvider()
var lastTimeAlive: Long = 0
var isAlive: Boolean = false
var detectedSuspended = 0
var detectedKilled = 0
// the initially loaded values, to detect if any problems happened during this run
val startedSuspended: Int
val startedKilled: Int
init {
loadState()
startedSuspended = detectedSuspended
startedKilled = detectedKilled
}
val pollRunnable = Runnable {
pollLoop()
}
private fun pollLoop() {
declareStillAlive()
handler.removeCallbacks(pollRunnable)
handler.postDelayed(pollRunnable, ttl*2/5)
}
private fun declareStillAlive() {
val currentTime = timeProvider()
if (lastTimeAlive > 0 && currentTime - lastTimeAlive > ttl) {
detectedSuspended++
}
lastTimeAlive = currentTime
saveState()
}
private fun loadState() {
lastTimeAlive = preferences.getLong("lastTimeAlive", 0)
detectedSuspended = preferences.getInt("detectedSuspended", 0)
detectedKilled = preferences.getInt("detectedKilled", 0)
}
private fun saveState() {
with(preferences.edit()) {
putLong("lastTimeAlive", lastTimeAlive)
putInt("detectedSuspended", detectedSuspended)
putInt("detectedKilled", detectedKilled)
apply()
}
}
/** Check if a previous app invocation was not stopped safely
*
* Relies on the lastTimeAlive not being changed, so
* this function must be called before start is called
*/
fun detectKilledPreviously() {
if (lastTimeAlive > 0) {
detectedKilled ++
saveState()
}
}
fun start() {
pollLoop()
}
/**
* Immediately cancel any Handler callbacks
*/
fun stop() {
handler.removeCallbacks(pollRunnable)
}
/**
* Remember that we correctly shut down, as opposed to being killed
*/
fun safelyStop() {
handler.removeCallbacks(pollRunnable)
val runningTime = timeProvider() - startTime
lastTimeAlive = 0
if (runningTime > MINIMUM_RUNNING_TIME && detectedSuspended == startedSuspended) {
detectedSuspended = 0
}
if (runningTime > MINIMUM_RUNNING_TIME && detectedKilled == startedKilled) {
detectedKilled = 0
}
saveState()
}
} | 49 | Kotlin | 90 | 546 | ea49ba17a18c353a8ba55f5040e8e4321bf14bd7 | 3,298 | AAIdrive | MIT License |
korio/src/commonMain/kotlin/com/soywiz/korio/util/RangeExt.kt | IgorKey | 185,667,363 | true | {"Kotlin": 817797, "Shell": 1679, "Batchfile": 698, "IDL": 196} | package com.soywiz.korio.util
import kotlin.native.concurrent.SharedImmutable
@SharedImmutable
val LONG_ZERO_TO_MAX_RANGE = 0L..Long.MAX_VALUE
fun IntRange.toLongRange() = this.start.toLong()..this.endInclusive.toLong() | 0 | Kotlin | 0 | 0 | 7c880b77b693b2dbd5c0f29c9b556243a07ef424 | 221 | korio | MIT License |
cryptohash/src/commonMain/kotlin/com/appmattus/crypto/internal/core/Shared.kt | appmattus | 347,486,833 | false | {"Kotlin": 8470456} | /*
* Copyright 2022-2024 Appmattus Limited
*
* 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("TooManyFunctions")
package com.appmattus.crypto.internal.core
import com.appmattus.crypto.internal.bytes.ByteBuffer
/**
* Encode the 32-bit word [value] into the array
* [buf] at offset [off], in little-endian
* convention (least significant byte first).
*
* @param value the value to encode
* @param buf the destination buffer
* @param off the destination offset
*/
internal fun encodeLEInt(value: Int, buf: ByteArray, off: Int) {
buf[off + 0] = value.toByte()
buf[off + 1] = (value ushr 8).toByte()
buf[off + 2] = (value ushr 16).toByte()
buf[off + 3] = (value ushr 24).toByte()
}
/**
* Decode a 32-bit little-endian word from the array [buf]
* at offset [off].
*
* @param buf the source buffer
* @param off the source offset
* @return the decoded value
*/
internal inline fun decodeLEInt(buf: ByteArray, off: Int): Int {
return (buf[off + 3].toInt() and 0xFF shl 24) or
(buf[off + 2].toInt() and 0xFF shl 16) or
(buf[off + 1].toInt() and 0xFF shl 8) or
(buf[off].toInt() and 0xFF)
}
internal inline fun ByteArray.decodeLEShort(off: Int): Short {
return ((this[off + 1].toInt() and 0xFF shl 8) or (this[off].toInt() and 0xFF)).toShort()
}
internal inline fun ByteBuffer.decodeLEInt(off: Int): Int {
return (this[off + 3].toInt() and 0xFF shl 24) or
(this[off + 2].toInt() and 0xFF shl 16) or
(this[off + 1].toInt() and 0xFF shl 8) or
(this[off].toInt() and 0xFF)
}
internal inline fun ByteBuffer.decodeBEInt(off: Int): Int {
return this[off].toInt() and 0xFF shl 24 or
(this[off + 1].toInt() and 0xFF shl 16) or
(this[off + 2].toInt() and 0xFF shl 8) or
(this[off + 3].toInt() and 0xFF)
}
internal inline fun ByteBuffer.decodeLEUInt(off: Int): UInt = decodeLEInt(off).toUInt()
/**
* Decode a 64-bit little-endian integer.
*
* @param buf the source buffer
* @param off the source offset
* @return the decoded integer
*/
internal inline fun decodeLELong(buf: ByteArray, off: Int): Long {
return buf[off + 0].toLong() and 0xFF or
((buf[off + 1].toLong() and 0xFF) shl 8) or
((buf[off + 2].toLong() and 0xFF) shl 16) or
((buf[off + 3].toLong() and 0xFF) shl 24) or
((buf[off + 4].toLong() and 0xFF) shl 32) or
((buf[off + 5].toLong() and 0xFF) shl 40) or
((buf[off + 6].toLong() and 0xFF) shl 48) or
((buf[off + 7].toLong() and 0xFF) shl 56)
}
internal inline fun ByteArray.decodeLEULong(off: Int): ULong = decodeLELong(this, off).toULong()
internal inline fun ByteBuffer.decodeLELong(off: Int): Long {
return this[off + 0].toLong() and 0xFF or
((this[off + 1].toLong() and 0xFF) shl 8) or
((this[off + 2].toLong() and 0xFF) shl 16) or
((this[off + 3].toLong() and 0xFF) shl 24) or
((this[off + 4].toLong() and 0xFF) shl 32) or
((this[off + 5].toLong() and 0xFF) shl 40) or
((this[off + 6].toLong() and 0xFF) shl 48) or
((this[off + 7].toLong() and 0xFF) shl 56)
}
internal inline fun ByteBuffer.decodeLEULong(off: Int): ULong = decodeLELong(off).toULong()
/**
* Encode a 64-bit integer with little-endian convention.
*
* @param [value] the integer to encode
* @param dst the destination buffer
* @param off the destination offset
*/
internal fun encodeLELong(value: Long, dst: ByteArray, off: Int) {
dst[off + 0] = value.toByte()
dst[off + 1] = (value.toInt() ushr 8).toByte()
dst[off + 2] = (value.toInt() ushr 16).toByte()
dst[off + 3] = (value.toInt() ushr 24).toByte()
dst[off + 4] = (value ushr 32).toByte()
dst[off + 5] = (value ushr 40).toByte()
dst[off + 6] = (value ushr 48).toByte()
dst[off + 7] = (value ushr 56).toByte()
}
/**
* Encode the 32-bit word [value] into the array
* [buf] at offset [off], in big-endian
* convention (most significant byte first).
*
* @param value the value to encode
* @param buf the destination buffer
* @param off the destination offset
*/
internal fun encodeBEInt(value: Int, buf: ByteArray, off: Int) {
buf[off + 0] = (value ushr 24).toByte()
buf[off + 1] = (value ushr 16).toByte()
buf[off + 2] = (value ushr 8).toByte()
buf[off + 3] = value.toByte()
}
/**
* Decode a 32-bit big-endian word from the array [buf]
* at offset [off].
*
* @param buf the source buffer
* @param off the source offset
* @return the decoded value
*/
internal fun decodeBEInt(buf: ByteArray, off: Int): Int {
return buf[off].toInt() and 0xFF shl 24 or
(buf[off + 1].toInt() and 0xFF shl 16) or
(buf[off + 2].toInt() and 0xFF shl 8) or
(buf[off + 3].toInt() and 0xFF)
}
/**
* Encode the 64-bit word [value] into the array
* [buf] at offset [off], in big-endian
* convention (most significant byte first).
*
* @param value the value to encode
* @param buf the destination buffer
* @param off the destination offset
*/
internal fun encodeBELong(value: Long, buf: ByteArray, off: Int) {
buf[off + 0] = (value ushr 56).toByte()
buf[off + 1] = (value ushr 48).toByte()
buf[off + 2] = (value ushr 40).toByte()
buf[off + 3] = (value ushr 32).toByte()
buf[off + 4] = (value ushr 24).toByte()
buf[off + 5] = (value ushr 16).toByte()
buf[off + 6] = (value ushr 8).toByte()
buf[off + 7] = value.toByte()
}
/**
* Decode a 64-bit big-endian word from the array [buf]
* at offset [off].
*
* @param buf the source buffer
* @param off the source offset
* @return the decoded value
*/
internal fun decodeBELong(buf: ByteArray, off: Int): Long {
return (buf[off].toLong() and 0xFF) shl 56 or
((buf[off + 1].toLong() and 0xFF) shl 48) or
((buf[off + 2].toLong() and 0xFF) shl 40) or
((buf[off + 3].toLong() and 0xFF) shl 32) or
((buf[off + 4].toLong() and 0xFF) shl 24) or
((buf[off + 5].toLong() and 0xFF) shl 16) or
((buf[off + 6].toLong() and 0xFF) shl 8) or
(buf[off + 7].toLong() and 0xFF)
}
internal fun UInt.reverseByteOrder(): UInt {
return this shl 24 and 0xff000000u or
(this shl 8 and 0x00ff0000u) or
(this shr 8 and 0x0000ff00u) or
(this shr 24 and 0x000000ffu)
}
internal fun ULong.reverseByteOrder(): ULong {
return ((this shl 56) and 0xff00000000000000UL) or
((this shl 40) and 0x00ff000000000000UL) or
((this shl 24) and 0x0000ff0000000000UL) or
((this shl 8) and 0x000000ff00000000UL) or
((this shr 8) and 0x00000000ff000000UL) or
((this shr 24) and 0x0000000000ff0000UL) or
((this shr 40) and 0x000000000000ff00UL) or
((this shr 56) and 0x00000000000000ffUL)
}
internal fun ByteArray.toHexString(): String {
return joinToString("") { (0xFF and it.toInt()).toString(16).padStart(2, '0') }
}
internal fun Int.toHexString(): String = ByteArray(4).also {
encodeBEInt(this, it, 0)
}.toHexString()
internal fun UInt.toHexString(): String = toInt().toHexString()
internal fun Long.toHexString(): String = ByteArray(8).also {
encodeBELong(this, it, 0)
}.toHexString()
internal fun ULong.toHexString(): String = toLong().toHexString()
| 3 | Kotlin | 4 | 79 | 9530b18ae391f95d305e87777dca40faf3efd6ca | 7,947 | crypto | Apache License 2.0 |
app/src/main/java/mcorrea/firstapp/MainActivity.kt | MarcuusCorrea | 810,019,716 | false | {"Kotlin": 2270} | package mcorrea.firstapp
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import mcorrea.firstapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate((layoutInflater))
setContentView(binding.root)
binding.buttonOla.setOnClickListener {
val nome : String = binding.editNome.text.toString()
//binding.textResultado.text = "Olá" + nome
binding.textResultado.text = "Olá ${nome}"
//binding.textResultado.setText("Olá" + nome)
}
// enableEdgeToEdge()
// setContentView(R.layout.activity_main)
// ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
// val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
// v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
// insets
// }
}
} | 0 | Kotlin | 0 | 0 | 6920b8c82e0ad2e43d49c07bcc104b1376a400ae | 1,268 | app_android | MIT License |
lib/kommander-core/src/nativeMain/kotlin/util/executeCommand.kt | mpetuska | 416,476,278 | false | {"Kotlin": 45376, "Shell": 548} | package dev.petuska.kommander.core.util
import kotlinx.cinterop.refTo
import kotlinx.cinterop.toKString
import platform.posix.fgets
import platform.posix.pclose
import platform.posix.popen
internal actual fun executeCommand(cmd: CMD, stdout: (String) -> Unit): Int {
val fp = popen("$cmd", "r") ?: error("Failed to run command: $cmd")
val buffer = ByteArray(4096)
while (true) {
val input = fgets(buffer.refTo(0), buffer.size, fp) ?: break
stdout(input.toKString())
}
return pclose(fp)
}
| 8 | Kotlin | 0 | 3 | 0917eb64aec7add03d842d5685f9bcfda338fffb | 510 | kommander | Apache License 2.0 |
src/nl/hannahsten/texifyidea/util/LatexDistribution.kt | sundermann | 254,633,674 | true | {"Kotlin": 1103466, "Java": 154502, "HTML": 18395, "TeX": 9540, "Lex": 7549, "Python": 967} | package nl.hannahsten.texifyidea.util
import nl.hannahsten.texifyidea.settings.TexifySettings
import java.io.IOException
import java.util.concurrent.TimeUnit
/**
* Represents the LaTeX Distribution of the user, e.g. MikTeX or TeX Live.
*/
class LatexDistribution {
companion object {
private val pdflatexVersionText: String by lazy {
getDistribution()
}
private val dockerImagesText: String by lazy {
runCommand("docker", "image", "ls")
}
/**
* Whether the user is using MikTeX or not.
* This value is lazy, so only computed when first accessed, because it is unlikely that the user will change LaTeX distribution while using IntelliJ.
*/
val isMiktex: Boolean by lazy {
pdflatexVersionText.contains("MiKTeX")
}
/**
* Whether the user is using TeX Live or not.
* This value is only computed once.
*/
val isTexlive: Boolean by lazy {
pdflatexVersionText.contains("TeX Live")
}
/**
* Whether the user does not have MiKTeX or TeX Live, but does have the miktex docker image available.
*/
fun isDockerMiktex() = TexifySettings.getInstance().dockerizedMiktex || (!isMiktex && !isTexlive && dockerImagesText.contains("miktex"))
/**
* Returns year of texlive installation, 0 if it is not texlive.
* Assumes the pdflatex version output contains something like (TeX Live 2019).
*/
val texliveVersion: Int by lazy {
if (!isTexlive) {
0
}
else {
val startIndex = pdflatexVersionText.indexOf("TeX Live")
try {
pdflatexVersionText.substring(startIndex + "TeX Live ".length, startIndex + "TeX Live ".length + "2019".length).toInt()
}
catch (e: NumberFormatException) {
0
}
}
}
/**
* Find the full name of the distribution in use, e.g. TeX Live 2019.
*/
private fun getDistribution(): String {
return parsePdflatexOutput(runCommand("pdflatex", "--version"))
}
private fun runCommand(vararg commands: String): String {
try {
val command = arrayListOf(*commands)
val proc = ProcessBuilder(command)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
// Timeout value
proc.waitFor(10, TimeUnit.SECONDS)
return proc.inputStream.bufferedReader().readText()
}
catch (e: IOException) {
e.printStackTrace()
}
return ""
}
/**
* Parse the output of pdflatex --version and return the distribution.
* Assumes the distribution name is in brackets at the end of the first line.
*/
fun parsePdflatexOutput(output: String): String {
val firstLine = output.split("\n")[0]
val splitLine = firstLine.split("(", ")")
// Get one-to-last entry, as the last one will be empty after the closing )
return if (splitLine.size >= 2) {
splitLine[splitLine.size - 2]
}
else {
""
}
}
}
} | 0 | null | 0 | 0 | 94212466645dfe485e9da0a2f982be9dfd2ffad4 | 3,530 | TeXiFy-IDEA | MIT License |
src/nl/hannahsten/texifyidea/util/LatexDistribution.kt | sundermann | 254,633,674 | true | {"Kotlin": 1103466, "Java": 154502, "HTML": 18395, "TeX": 9540, "Lex": 7549, "Python": 967} | package nl.hannahsten.texifyidea.util
import nl.hannahsten.texifyidea.settings.TexifySettings
import java.io.IOException
import java.util.concurrent.TimeUnit
/**
* Represents the LaTeX Distribution of the user, e.g. MikTeX or TeX Live.
*/
class LatexDistribution {
companion object {
private val pdflatexVersionText: String by lazy {
getDistribution()
}
private val dockerImagesText: String by lazy {
runCommand("docker", "image", "ls")
}
/**
* Whether the user is using MikTeX or not.
* This value is lazy, so only computed when first accessed, because it is unlikely that the user will change LaTeX distribution while using IntelliJ.
*/
val isMiktex: Boolean by lazy {
pdflatexVersionText.contains("MiKTeX")
}
/**
* Whether the user is using TeX Live or not.
* This value is only computed once.
*/
val isTexlive: Boolean by lazy {
pdflatexVersionText.contains("TeX Live")
}
/**
* Whether the user does not have MiKTeX or TeX Live, but does have the miktex docker image available.
*/
fun isDockerMiktex() = TexifySettings.getInstance().dockerizedMiktex || (!isMiktex && !isTexlive && dockerImagesText.contains("miktex"))
/**
* Returns year of texlive installation, 0 if it is not texlive.
* Assumes the pdflatex version output contains something like (TeX Live 2019).
*/
val texliveVersion: Int by lazy {
if (!isTexlive) {
0
}
else {
val startIndex = pdflatexVersionText.indexOf("TeX Live")
try {
pdflatexVersionText.substring(startIndex + "TeX Live ".length, startIndex + "TeX Live ".length + "2019".length).toInt()
}
catch (e: NumberFormatException) {
0
}
}
}
/**
* Find the full name of the distribution in use, e.g. TeX Live 2019.
*/
private fun getDistribution(): String {
return parsePdflatexOutput(runCommand("pdflatex", "--version"))
}
private fun runCommand(vararg commands: String): String {
try {
val command = arrayListOf(*commands)
val proc = ProcessBuilder(command)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
// Timeout value
proc.waitFor(10, TimeUnit.SECONDS)
return proc.inputStream.bufferedReader().readText()
}
catch (e: IOException) {
e.printStackTrace()
}
return ""
}
/**
* Parse the output of pdflatex --version and return the distribution.
* Assumes the distribution name is in brackets at the end of the first line.
*/
fun parsePdflatexOutput(output: String): String {
val firstLine = output.split("\n")[0]
val splitLine = firstLine.split("(", ")")
// Get one-to-last entry, as the last one will be empty after the closing )
return if (splitLine.size >= 2) {
splitLine[splitLine.size - 2]
}
else {
""
}
}
}
} | 0 | null | 0 | 0 | 94212466645dfe485e9da0a2f982be9dfd2ffad4 | 3,530 | TeXiFy-IDEA | MIT License |
android/quest/src/main/java/org/smartregister/fhircore/quest/ui/patient/profile/components/PersonalData.kt | opensrp | 339,242,809 | false | null | /*
* Copyright 2021 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartregister.fhircore.quest.ui.patient.profile.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import java.util.Date
import org.smartregister.fhircore.engine.R
import org.smartregister.fhircore.engine.ui.theme.PersonalDataBackgroundColor
import org.smartregister.fhircore.engine.ui.theme.StatusTextColor
import org.smartregister.fhircore.engine.util.extension.asDdMmm
import org.smartregister.fhircore.engine.util.extension.plusYears
import org.smartregister.fhircore.quest.ui.shared.models.ProfileViewData
@Composable
fun PersonalData(
patientProfileViewData: ProfileViewData.PatientProfileViewData,
modifier: Modifier = Modifier,
) {
Card(elevation = 3.dp, modifier = modifier.fillMaxWidth()) {
Column(modifier = modifier.padding(16.dp)) {
Text(
text = patientProfileViewData.name,
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
if (patientProfileViewData.status != null) {
Text(
text = patientProfileViewData.status,
color = StatusTextColor,
fontSize = 18.sp,
modifier = modifier.padding(vertical = 10.dp)
)
}
if (patientProfileViewData.identifier != null) {
Text(
text = stringResource(R.string.id, patientProfileViewData.identifier),
color = StatusTextColor,
fontSize = 18.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
Spacer(modifier = modifier.height(16.dp))
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier =
modifier.clip(RoundedCornerShape(size = 8.dp)).background(PersonalDataBackgroundColor)
) {
OtherDetailsItem(title = stringResource(R.string.sex), value = patientProfileViewData.sex)
OtherDetailsItem(title = stringResource(R.string.age), value = patientProfileViewData.age)
OtherDetailsItem(
title = stringResource(R.string.dob),
value = patientProfileViewData.dob.asDdMmm()
)
}
}
}
}
@Composable
private fun OtherDetailsItem(title: String, value: String, modifier: Modifier = Modifier) {
Column(modifier = modifier.padding(16.dp)) {
Text(text = title, modifier.padding(bottom = 4.dp), color = StatusTextColor, fontSize = 18.sp)
Text(text = value, fontSize = 18.sp)
}
}
@Composable
@Preview(showBackground = true)
fun PersonalDataPreview() {
val patientProfileData =
ProfileViewData.PatientProfileViewData(
logicalId = "99358357",
name = "<NAME>",
status = "Family Head",
sex = "Female",
age = "48y",
dob = Date().plusYears(-48),
identifier = "123455"
)
PersonalData(patientProfileViewData = patientProfileData)
}
| 158 | Kotlin | 10 | 18 | 9d7044a12ef2726705a3019cb26ab03bc48bc28c | 4,285 | fhircore | Apache License 2.0 |
app/src/main/java/com/etasdemir/ethinspector/ui/search/InvalidSearchScreen.kt | etasdemir | 584,191,764 | false | null | package com.etasdemir.ethinspector.ui.search
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.compose.rememberNavController
import com.etasdemir.ethinspector.R
import com.etasdemir.ethinspector.data.domain_model.AvailableThemes
import com.etasdemir.ethinspector.ui.navigation.NavigationHandler
import com.etasdemir.ethinspector.ui.theme.LocalTheme
@Composable
fun InvalidSearchScreen(
searchedValue: String,
navigationHandler: NavigationHandler
) {
val searchIcon = remember { Icons.Filled.Close }
val isDarkTheme = LocalTheme.current == AvailableThemes.Dark
val searchNotFoundImg = remember {
if (isDarkTheme)
R.drawable.search_not_found_dark
else
R.drawable.search_not_found_light
}
Scaffold(topBar = {
SearchTopBar(
uneditableText = searchedValue,
searchIcon = searchIcon,
navigationHandler = navigationHandler
)
}) {
Column(modifier = Modifier.padding(it)) {
Image(
modifier = Modifier.fillMaxWidth(),
painter = painterResource(id = searchNotFoundImg),
contentDescription = "Search not found",
)
Text(
modifier = Modifier.padding(start = 20.dp, top = 10.dp),
text = stringResource(id = R.string.search_invalid_search_title),
color = MaterialTheme.colorScheme.tertiary,
fontWeight = FontWeight.Bold,
fontSize = 32.sp
)
Text(
modifier = Modifier.padding(top = 5.dp, end = 20.dp, bottom = 20.dp, start = 20.dp),
text = stringResource(id = R.string.search_invalid_search_desc),
color = MaterialTheme.colorScheme.onBackground,
fontSize = 20.sp
)
}
}
}
@Preview
@Composable
fun InvalidSearchScreenPreview() {
val testHost = rememberNavController()
InvalidSearchScreen("Some wrong address", NavigationHandler(testHost))
}
| 0 | null | 0 | 4 | 753c16ebcb2973bdef76078bb391792892187826 | 2,618 | eth-inspector | MIT License |
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/objcexport/MethodBridge.kt | JetBrains | 58,957,623 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.objcexport
import org.jetbrains.kotlin.backend.common.descriptors.allParameters
import org.jetbrains.kotlin.backend.konan.ir.allParameters
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ParameterDescriptor
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.IrValueParameter
internal sealed class TypeBridge
internal object ReferenceBridge : TypeBridge()
internal data class BlockPointerBridge(
val numberOfParameters: Int,
val returnsVoid: Boolean
) : TypeBridge()
internal data class ValueTypeBridge(val objCValueType: ObjCValueType) : TypeBridge()
internal sealed class MethodBridgeParameter
internal sealed class MethodBridgeReceiver : MethodBridgeParameter() {
object Static : MethodBridgeReceiver()
object Factory : MethodBridgeReceiver()
object Instance : MethodBridgeReceiver()
}
internal object MethodBridgeSelector : MethodBridgeParameter()
internal sealed class MethodBridgeValueParameter : MethodBridgeParameter() {
data class Mapped(val bridge: TypeBridge) : MethodBridgeValueParameter()
object ErrorOutParameter : MethodBridgeValueParameter()
data class KotlinResultOutParameter(val bridge: TypeBridge) : MethodBridgeValueParameter()
}
internal data class MethodBridge(
val returnBridge: ReturnValue,
val receiver: MethodBridgeReceiver,
val valueParameters: List<MethodBridgeValueParameter>
) {
sealed class ReturnValue {
object Void : ReturnValue()
object HashCode : ReturnValue()
data class Mapped(val bridge: TypeBridge) : ReturnValue()
sealed class Instance : ReturnValue() {
object InitResult : Instance()
object FactoryResult : Instance()
}
sealed class WithError : ReturnValue() {
object Success : WithError()
data class RefOrNull(val successBridge: ReturnValue) : WithError()
}
}
val paramBridges: List<MethodBridgeParameter> =
listOf(receiver) + MethodBridgeSelector + valueParameters
// TODO: it is not exactly true in potential future cases.
val isInstance: Boolean get() = when (receiver) {
MethodBridgeReceiver.Static,
MethodBridgeReceiver.Factory -> false
MethodBridgeReceiver.Instance -> true
}
}
internal fun MethodBridge.valueParametersAssociated(
descriptor: FunctionDescriptor
): List<Pair<MethodBridgeValueParameter, ParameterDescriptor?>> {
val kotlinParameters = descriptor.allParameters.iterator()
val skipFirstKotlinParameter = when (this.receiver) {
MethodBridgeReceiver.Static -> false
MethodBridgeReceiver.Factory, MethodBridgeReceiver.Instance -> true
}
if (skipFirstKotlinParameter) {
kotlinParameters.next()
}
return this.valueParameters.map {
when (it) {
is MethodBridgeValueParameter.Mapped -> it to kotlinParameters.next()
is MethodBridgeValueParameter.ErrorOutParameter,
is MethodBridgeValueParameter.KotlinResultOutParameter -> it to null
}
}.also { assert(!kotlinParameters.hasNext()) }
}
internal fun MethodBridge.parametersAssociated(
irFunction: IrFunction
): List<Pair<MethodBridgeParameter, IrValueParameter?>> {
val kotlinParameters = irFunction.allParameters.iterator()
return this.paramBridges.map {
when (it) {
is MethodBridgeValueParameter.Mapped, MethodBridgeReceiver.Instance ->
it to kotlinParameters.next()
MethodBridgeReceiver.Static, MethodBridgeSelector, MethodBridgeValueParameter.ErrorOutParameter,
is MethodBridgeValueParameter.KotlinResultOutParameter ->
it to null
MethodBridgeReceiver.Factory -> {
kotlinParameters.next()
it to null
}
}
}.also { assert(!kotlinParameters.hasNext()) }
}
| 163 | null | 625 | 7,100 | 9fb0a75ab17e9d8cddd2c3d1802a1cdd83774dfa | 4,174 | kotlin-native | Apache License 2.0 |
ktorfit-ksp/src/test/kotlin/de/jensklingenberg/ktorfit/reqBuilderExtension/UrlArgumentTextKtTest.kt | Foso | 203,655,484 | false | {"Kotlin": 330650, "Ruby": 2354, "Java": 692, "Swift": 345} | package de.jensklingenberg.ktorfit.reqBuilderExtension
import com.google.devtools.ksp.symbol.KSType
import de.jensklingenberg.ktorfit.model.ParameterData
import de.jensklingenberg.ktorfit.model.ReturnTypeData
import de.jensklingenberg.ktorfit.model.annotations.HttpMethod
import de.jensklingenberg.ktorfit.model.annotations.HttpMethodAnnotation
import de.jensklingenberg.ktorfit.model.annotations.ParameterAnnotation.Path
import de.jensklingenberg.ktorfit.model.annotations.ParameterAnnotation.Url
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.kotlin.mock
class UrlArgumentTextKtTest {
@Test
fun testWithoutUrlAnnotation() {
val parameterData = ParameterData("test1", ReturnTypeData("String", mock<KSType>()))
val params = listOf(parameterData)
val text = getUrlCode(params, HttpMethodAnnotation("posts", HttpMethod.GET), "")
val expected =
"url{\n" +
"takeFrom(_ktorfit.baseUrl + \"posts\")\n" +
"}".trimMargin()
assertEquals(
expected,
text,
)
}
@Test
fun testWithPathAndUrlAnnotation() {
val urlAnnotation = Url
val parameterData =
ParameterData("test1", ReturnTypeData("String", mock<KSType>()), annotations = listOf(urlAnnotation))
val params = listOf(parameterData)
val text = getUrlCode(params, HttpMethodAnnotation("posts", HttpMethod.GET), "")
assertEquals(
"url{\n" +
"takeFrom((_ktorfit.baseUrl.takeIf{ !test1.startsWith(\"http\")} ?: \"\") + \"posts\")\n" +
"}",
text,
)
}
@Test
fun testWithUrlAnnotation() {
val urlAnnotation = Url
val parameterData =
ParameterData("test1", ReturnTypeData("String", mock<KSType>()), annotations = listOf(urlAnnotation))
val params = listOf(parameterData)
val text = getUrlCode(params, HttpMethodAnnotation("", HttpMethod.GET), "")
val expected =
String.format(
"url{\n" +
"takeFrom((_ktorfit.baseUrl.takeIf{ !test1.startsWith(\"http\")} ?: \"\") + \"%s{test1}\")\n" +
"}",
"$",
)
assertEquals(expected, text)
}
@Test
fun testWithoutPathAnnotation() {
val parameterData = ParameterData("test1", ReturnTypeData("String", mock<KSType>()))
val params = listOf(parameterData)
val text = getUrlCode(params, HttpMethodAnnotation("", HttpMethod.GET), "")
assertEquals("url{\ntakeFrom(_ktorfit.baseUrl + \"\")\n}", text)
}
@Test
fun testWithPathAnnotation() {
val path = Path("testValue")
val parameterData =
ParameterData("test1", ReturnTypeData("String", mock<KSType>()), annotations = listOf(path))
val params = listOf(parameterData)
val text = getUrlCode(params, HttpMethodAnnotation("user/{testValue}", HttpMethod.GET), "")
assertEquals(
"""url{
takeFrom(_ktorfit.baseUrl + "user/$/{"$/test1".encodeURLPath()}")
}""".replace("$/", "$"),
text,
)
}
}
| 32 | Kotlin | 40 | 1,558 | 16d3481c25b151e5abb37d7cb2ee4e86c5db9d49 | 3,194 | Ktorfit | Apache License 2.0 |
src/main/kotlin/net/casual/arcade/utils/FastUtils.kt | CasualChampionships | 621,955,934 | false | {"Kotlin": 981165, "Java": 176720, "GLSL": 4396} | package net.casual.arcade.utils
import it.unimi.dsi.fastutil.Pair
public object FastUtils {
public operator fun <A: Any, B> Pair<A, B>.component1(): A {
return this.left()
}
public operator fun <A: Any, B> Pair<A, B>.component2(): B {
return this.right()
}
} | 1 | Kotlin | 1 | 2 | b7fe392b1063cc0977df54e1713097888c5a3aed | 293 | arcade | MIT License |
src/main/kotlin/com/sk/topicWise/slidingwindow/hard/76. Minimum Window Substring.kt | sandeep549 | 262,513,267 | false | null | package com.sk.topicWise.slidingwindow.hard
class Solution76 {
fun minWindow(s: String, t: String): String {
if (s.length < t.length) return ""
val dict = t.toCharArray().groupBy { it }.mapValues { it.value.size }.toMutableMap()
val required = dict.size
var l = 0
var r = 0
var formed = 0
val windowCounts = HashMap<Char, Int>()
var ans = Pair(0, s.length + 1)
while (r < s.length) { // Add one character from the right to the window
var c = s[r]
windowCounts[c] = windowCounts.getOrDefault(c, 0) + 1
if (dict.containsKey(c) && windowCounts[c]!! == dict[c]!!) {
formed++
}
while (l <= r && formed == required) {
if (r - l < ans.second - ans.first) {
ans = Pair(l, r) // save new smallest window
}
c = s[l]
windowCounts[c] = windowCounts[c]!! - 1
if (dict.containsKey(c) && windowCounts[c]!! < dict[c]!!) {
formed--
}
l++
}
r++
}
return if (ans.second - ans.first > s.length) "" else s.substring(ans.first, ans.second + 1)
}
fun minWindow2(s: String, t: String): String {
val map = t.toCharArray().groupBy { it }.mapValues { it.value.size }.toMutableMap()
var l = 0
var r = 0
var start = 0
var distance = Int.MAX_VALUE
var counter = t.length
while (r < s.length) {
val c1 = s[r]
if (map.contains(c1)) {
if (map[c1]!! > 0) counter--
map[c1] = map[c1]!! - 1
}
r++
while (counter == 0) {
if (distance > r - l) {
distance = r - l
start = l
}
val c2 = s[l]
if (map.contains(c2)) {
map[c2] = map[c2]!! + 1
if (map[c2]!! > 0) counter++
}
l++
}
}
return if (distance == Int.MAX_VALUE) "" else s.substring(start, start + distance)
}
}
| 1 | null | 1 | 1 | 67688ec01551e9981f4be07edc11e0ee7c0fab4c | 2,238 | leetcode-answers-kotlin | Apache License 2.0 |
src/main/kotlin/de/menkalian/pisces/RequiresKey.kt | Menkalian | 471,663,267 | false | null | package de.menkalian.pisces
import java.lang.annotation.Inherited
/**
* Annotation zum Festlegen der Features, die in der Config aktiv sein müssen, um diese Komponente zu aktivieren.
* Diese Annotation sollte gemeinsam mit `@Conditional(OnConfigValueCondition::class)` genutzt werden.
*
* @see OnConfigValueCondition
*/
@Repeatable
@Inherited
annotation class RequiresKey(val value: Array<String>) | 0 | Kotlin | 0 | 1 | efc7818da5419ce720cd04878c8aa30809fc35c0 | 404 | pisces | Apache License 2.0 |
src/RequestEngine.kt | PortSwigger | 166,008,413 | false | null | package burp
import java.io.*
import java.net.URL
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.zip.GZIPInputStream
import kotlin.math.ceil
abstract class RequestEngine: IExtensionStateListener {
var start: Long = System.nanoTime()
val failedWords = HashMap<String, AtomicInteger>()
var successfulRequests = AtomicInteger(0)
val userState = HashMap<String, Any>()
var connections = AtomicInteger(0)
val attackState = AtomicInteger(0) // 0 = connecting, 1 = live, 2 = fully queued, 3 = cancelled, 4 = completed
lateinit var completedLatch: CountDownLatch
private val baselines = LinkedList<SafeResponseVariations>()
val retries = AtomicInteger(0)
val permaFails = AtomicInteger(0)
lateinit var outputHandler: OutputHandler
lateinit var requestQueue: LinkedBlockingQueue<Request>
abstract val callback: (Request, Boolean) -> Boolean
abstract var readCallback: ((String) -> Boolean)?
abstract val maxRetriesPerRequest: Int
lateinit var target: URL
private val floodgates = HashMap<String, Floodgate>()
init {
if (attackState.get() == 3) {
throw Exception("You cannot create a new request engine for a cancelled attack")
}
if (Utils.gotBurp) {
Utils.callbacks.registerExtensionStateListener(this)
}
}
override fun extensionUnloaded() {
cancel()
}
fun invokeCallback(req: Request, interesting: Boolean){
try {
req.invokeCallback(interesting)
} catch (ex: Exception){
Utils.out("Error in user-defined callback: $ex")
permaFails.incrementAndGet()
}
}
abstract fun start(timeout: Int = 10)
abstract fun buildRequest(template: String, payloads: List<String?>, learnBoring: Int?, label: String?): Request
fun triggerReadCallback(data: String) {
readCallback?.invoke(data)
}
fun queue(req: String) {
queue(req, emptyList<String>(), 0, null, null, null)
}
fun queue(req: String, payload: String) {
queue(req, listOf(payload), 0, null, null, null)
}
fun queue(template: String, payloads: List<String?>) {
queue(template, payloads, 0, null, null, null)
}
fun queue(template: String, payloads: List<String?>, learnBoring: Int, callback: ((Request, Boolean) -> Boolean)?, gateName: String?, label: String?) {
val noPayload = payloads.isEmpty()
val noMarker = !template.contains("%s")
if (noMarker && !noPayload) {
throw Exception("The request has payloads specified, but no %s injection markers")
}
if (!noMarker && noPayload) {
throw Exception("The request has a %s injection point, but no payloads specified")
}
if (learnBoring != 0 && !Utils.gotBurp) {
throw Exception("Automatic interesting response detection using 'learn=X' isn't support in command line mode.")
}
val request = buildRequest(template, payloads, learnBoring, label)
request.engine = this
request.callback = callback
if (gateName != null) {
synchronized(gateName) {
request.gate = floodgates[gateName] ?: Floodgate()
if (floodgates.containsKey(gateName)) {
floodgates[gateName]!!.addWaiter()
} else {
floodgates[gateName] = request.gate!!
}
if (this is ThreadedRequestEngine && request.gate!!.remaining.get() > this.threads) {
throw Exception("You have queued more gated requests than concurrentConnections, so your attack will deadlock. Consider increasing concurrentConnections")
}
}
}
val state = attackState.get()
if (state > 2) {
throw IllegalStateException("Cannot queue any more items - the attack has finished")
}
var timeout = 1800L
if (state == 0) {
timeout = 1
}
var queued = false
var attempt = 0L
while (!queued && attackState.get() <= 2 && attempt < timeout) {
queued = requestQueue.offer(request, 1, TimeUnit.SECONDS)
attempt += 1
}
if (!queued) {
if (state == 0 && requestQueue.size == 100) {
Utils.out("Looks like a non-streaming attack, unlimiting the queue")
requestQueue = LinkedBlockingQueue(requestQueue)
}
else if (attempt == timeout) {
Utils.out("Timeout queuing request. Aborting.")
this.cancel()
} else {
// the attack has been cancelled so we don't need to do anything
}
}
}
open fun openGate(gateName: String) {
//Utils.out("Opening gate "+gateName)
if (!floodgates.containsKey(gateName)) {
throw Exception("Unrecognised gate name in openGate() invocation")
}
floodgates[gateName]!!.open()
}
open fun showStats(timeout: Int = -1) {
if (attackState.get() == 3) {
return
}
var success = true
attackState.set(2)
if (timeout > 0) {
success = completedLatch.await(timeout.toLong(), TimeUnit.SECONDS)
}
else {
while (completedLatch.count > 0 && !Utils.unloaded && attackState.get() < 3) {
completedLatch.await(10, TimeUnit.SECONDS)
}
}
if (attackState.get() == 3) {
return
}
if (!success) {
Utils.out("Aborting attack due to timeout")
attackState.set(3)
}
else {
Utils.err("Completed attack")
attackState.set(4)
}
showSummary()
}
fun cancel() {
if (Utils.gotBurp && !Utils.unloaded) {
Utils.callbacks.removeExtensionStateListener(this)
}
if (attackState.get() != 3) {
attackState.set(3)
Utils.out("Cancelled attack")
showSummary()
}
}
fun showSummary() {
val duration = System.nanoTime().toFloat() - start
val requests = successfulRequests.get().toFloat()
Utils.err("Sent ${requests.toInt()} requests in ${duration / 1000000000} seconds")
Utils.err(String.format("RPS: %.0f\n", requests / ceil((duration / 1000000000).toDouble())))
}
fun statusString(): String {
val duration = ceil(((System.nanoTime().toFloat() - start) / 1000000000).toDouble()).toInt()
val requests = successfulRequests.get().toFloat()
val nextWord = requestQueue.peek()?.words?.joinToString(separator="/")
val statusString = String.format("Reqs: %d | Queued: %d | Duration: %d | RPS: %.0f | Connections: %d | Retries: %d | Fails: %d | Next: %s", requests.toInt(), requestQueue.count(), duration, requests / duration, connections.get(), retries.get(), permaFails.get(), nextWord)
val state = attackState.get()
return when {
state < 3 -> statusString
state == 3 -> statusString + " | Cancelled"
else -> statusString + " | Completed"
}
}
fun reinvokeCallbacks() {
val reqTable = outputHandler
// if the request engine isn't a table, we can't update the output
if (reqTable is RequestTable) {
val requestsFromTable = reqTable.model.requests
if (requestsFromTable.size == 0) {
return
}
val copy = ArrayList<Request>(requestsFromTable.size)
for (tableReq in requestsFromTable) {
copy.add(tableReq)
}
requestsFromTable.clear()
//reqTable.model.fireTableRowsDeleted(0, requestsFromTable.size)
for (request in copy) {
val interesting = processResponse(request, request.getResponseAsBytes()!!)
callback(request, interesting)
}
reqTable.model.fireTableDataChanged()
//reqTable.repaint()
}
}
fun setOutput(outputHandler: OutputHandler) {
this.outputHandler = outputHandler
}
fun processResponse(req: Request, response: ByteArray): Boolean {
if (!Utils.gotBurp) {
return false
}
val resp = Utils.callbacks.helpers.analyzeResponseVariations(response)
// fixme might screw over the user if they try to add multiple overlapping fingerprints?
for(base in baselines) {
if (invariantsMatch(base, resp)) {
return false
}
}
if (req.learnBoring != 0) {
var base = baselines.getOrNull(req.learnBoring-1)
if (base == null) {
base = SafeResponseVariations()
baselines.add(base)
}
base.updateWith(response)
reinvokeCallbacks()
return false
}
else if (baselines.isEmpty()) {
return true
}
return true
}
fun shouldRetry(req: Request): Boolean {
if (maxRetriesPerRequest < 1) {
permaFails.getAndIncrement()
return false
}
val reqID = req.getRequest().hashCode().toString()
val fails = failedWords[reqID]
if (fails == null){
failedWords[reqID] = AtomicInteger(1)
}
else {
if(fails.incrementAndGet() > maxRetriesPerRequest) {
permaFails.getAndIncrement()
Utils.out("Skipping word due to multiple failures: $reqID")
return false
}
}
retries.getAndIncrement()
return true
}
fun clearErrors() {
failedWords.clear()
}
private fun invariantsMatch(base: SafeResponseVariations, resp: IResponseVariations): Boolean {
val invariants = base.getInvariantAttributes()
for(attribute in invariants) {
if (base.getAttributeValue(attribute) != resp.getAttributeValue(attribute, 0)) {
return false
}
}
return true
}
fun decompress(compressed: ByteArray): String {
if (compressed.isEmpty()) {
return ""
}
val bytesIn = ByteArrayInputStream(compressed)
val unzipped = GZIPInputStream(bytesIn)
val out = ByteArrayOutputStream()
try {
while (true) {
val bytes = ByteArray(1024)
val read = unzipped.read(bytes, 0, 1024)
if (read <= 0) {
break
}
out.write(bytes)
}
} catch (e: IOException) {
Utils.err("GZIP decompression failed - possible partial response")
}
return String(out.toByteArray())
}
}
class SafeResponseVariations {
private val lock = ReentrantReadWriteLock()
private val variations = Utils.callbacks.helpers.analyzeResponseVariations()
fun updateWith(response: ByteArray) {
val writelock = lock.writeLock()
writelock.lock()
variations.updateWith(response)
writelock.unlock()
}
fun getInvariantAttributes(): List<String> {
val readlock = lock.readLock()
readlock.lock()
val invariants = variations.invariantAttributes
readlock.unlock()
return invariants
}
fun getAttributeValue(attribute: String): Int {
return variations.getAttributeValue(attribute, 0)
}
}
| 15 | null | 207 | 967 | 3ed8a545d60b7599ad97b6a1d760f9b4c6c83cd6 | 11,851 | turbo-intruder | Apache License 2.0 |
app/src/main/kotlin/ru/arsich/messenger/ui/views/DialogsLayout.kt | arsich | 101,335,653 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 22, "Kotlin": 33} | package ru.arsich.messenger.ui.views
import android.content.Context
import android.graphics.Paint
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import ru.arsich.messenger.R
class DialogsLayout : ViewGroup {
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) {
initValues(context, attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
initValues(context, attrs)
}
private lateinit var datePaint: Paint
private var horizontalPadding: Int = 0
private var bottomCenterMargin: Int = 0
private var avatarChild: ImageView? = null
private var avatarSize: Int = 0
private var avatarBottomMargin = 0
private var dateChild: TextView? = null
private var dateWidth: Int = 0
private var dateHeight: Int = 0
private var dateText: String = ""
private var dateTextSize: Int = 16
private var titleChild: TextView? = null
private var titleHeight: Int = 0
private var messageChild: TextView? = null
private var messageHeight: Int = 0
private fun initValues(context: Context, attrs: AttributeSet?) {
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.DialogsLayout, 0, 0)
try {
horizontalPadding = a.getDimensionPixelSize(R.styleable.DialogsLayout_vg_horizontalPadding, horizontalPadding)
avatarSize = a.getDimensionPixelSize(R.styleable.DialogsLayout_vg_avatarSize, avatarSize)
dateTextSize = a.getDimensionPixelSize(R.styleable.DialogsLayout_vg_dateTextSize, dateTextSize)
dateText = a.getString(R.styleable.DialogsLayout_vg_dateTextPattern)
bottomCenterMargin = a.getDimensionPixelSize(R.styleable.DialogsLayout_vg_bottomCenterMargin, bottomCenterMargin)
avatarBottomMargin = a.getDimensionPixelSize(R.styleable.DialogsLayout_vg_bottomAvatarMargin, avatarBottomMargin)
} finally {
a.recycle()
}
datePaint = Paint(Paint.ANTI_ALIAS_FLAG)
datePaint.textSize = dateTextSize.toFloat()
dateWidth = datePaint.measureText(dateText).toInt()
}
fun setDateText(text: String) {
dateText = text
dateWidth = datePaint.measureText(dateText).toInt()
dateChild?.text = text
invalidate()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val totalWidth = MeasureSpec.getSize(widthMeasureSpec)
val totalHeight = heightMeasureSpec
if (avatarChild == null) {
avatarChild = findViewById<ImageView>(R.id.avatarView)
}
avatarChild?.measure(MeasureSpec.makeMeasureSpec(avatarSize, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(avatarSize, MeasureSpec.EXACTLY))
if (dateChild == null) {
dateChild = findViewById<TextView>(R.id.dateView)
}
dateChild?.let {
it.measure(MeasureSpec.makeMeasureSpec(dateWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(totalHeight - bottomCenterMargin, MeasureSpec.AT_MOST))
dateHeight = it.measuredHeight
it.text = dateText
}
if (titleChild == null) {
titleChild = findViewById<TextView>(R.id.titleView)
}
titleChild?.let {
val width = totalWidth - dateWidth - horizontalPadding * 3 - avatarSize
it.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(totalHeight - bottomCenterMargin, MeasureSpec.AT_MOST))
titleHeight = it.measuredHeight
// recalculate text (ellipsis end)
it.text = it.text
}
if (messageChild == null) {
messageChild = findViewById<TextView>(R.id.messageView)
}
messageChild?.let {
val width = totalWidth - horizontalPadding * 3 - avatarSize
it.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(bottomCenterMargin, MeasureSpec.AT_MOST))
messageHeight = it.measuredHeight
// recalculate text (ellipsis end)
it.text = it.text
}
setMeasuredDimension(totalWidth, totalHeight)
}
override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {
val totalWidth = measuredWidth
val totalHeight = measuredHeight
avatarChild?.layout(horizontalPadding, totalHeight - avatarBottomMargin - avatarSize,
horizontalPadding + avatarSize, totalHeight - avatarBottomMargin)
dateChild?.layout(totalWidth - horizontalPadding - dateWidth, totalHeight - bottomCenterMargin - dateHeight,
totalWidth - horizontalPadding, totalHeight - bottomCenterMargin)
titleChild?.layout(horizontalPadding * 2 + avatarSize, totalHeight - bottomCenterMargin - titleHeight,
totalWidth - 2 * horizontalPadding - dateWidth, totalHeight - bottomCenterMargin)
messageChild?.layout(horizontalPadding * 2 + avatarSize, totalHeight - bottomCenterMargin,
totalWidth - 2 * horizontalPadding, totalHeight)
}
} | 0 | Kotlin | 0 | 0 | 9630f03aad7d7299f661192de9b74642bb17d13c | 5,391 | messenger | MIT License |
mappings/src/commonTest/kotlin/com/revenuecat/purchases/kmp/mappings/PurchasesAreCompletedByTests.kt | RevenueCat | 758,647,648 | false | {"Kotlin": 391318, "Ruby": 17650, "Swift": 594} | package com.revenuecat.purchases.kmp.mappings
import com.revenuecat.purchases.kmp.models.PurchasesAreCompletedBy
import com.revenuecat.purchases.kmp.models.StoreKitVersion
import kotlin.test.Test
import kotlin.test.assertEquals
class PurchasesAreCompletedByTests {
@Test
fun `toHybridString returns the correct values`() {
val purchasesAreCompletedByMyApp = PurchasesAreCompletedBy.MyApp(StoreKitVersion.DEFAULT)
val myAppHybridString = purchasesAreCompletedByMyApp.toHybridString()
val purchasesAreCompletedByRevenueCat = PurchasesAreCompletedBy.RevenueCat
val revenuecatHybridString = purchasesAreCompletedByRevenueCat.toHybridString()
assertEquals("MY_APP", myAppHybridString)
assertEquals("REVENUECAT", revenuecatHybridString)
}
}
| 6 | Kotlin | 3 | 88 | af9d4f70c0af9a7a346f56dcf34d1ca621c41297 | 800 | purchases-kmp | MIT License |
app/src/main/java/com/github/psm/moviedb/db/model/tv/popular/Tv.kt | Pidsamhai | 371,868,606 | false | {"Kotlin": 243787, "CMake": 1715} | package com.github.psm.moviedb.db.model.tv.popular
import android.os.Parcelable
import androidx.annotation.Keep
import com.github.psm.moviedb.db.model.BaseVoteObject
import com.github.psm.moviedb.db.model.VoteStar
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import kotlinx.parcelize.Parcelize
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Entity
@Keep
@Serializable
@Parcelize
data class Tv(
@SerialName("backdrop_path")
val backdropPath: String? = null,
@SerialName("first_air_date")
val firstAirDate: String? = null,
// @SerialName("genre_ids")
// val genreIds: List<Int>? = null,
@Id(assignable = true)
@SerialName("id")
var id: Long = 0,
@SerialName("name")
val name: String? = null,
// @SerialName("origin_country")
// val originCountry: List<String>? = null,
@SerialName("original_language")
val originalLanguage: String? = null,
@SerialName("original_name")
val originalName: String? = null,
@SerialName("overview")
val overview: String? = null,
@SerialName("popularity")
val popularity: Double? = null,
@SerialName("poster_path")
val posterPath: String? = null,
@SerialName("vote_average")
val voteAverage: Double? = null,
@SerialName("vote_count")
val voteCount: Int? = null
) : Parcelable, BaseVoteObject {
override val voteStar: VoteStar
get() = VoteStar(voteAverage)
} | 1 | Kotlin | 1 | 3 | 6f4e67ee83349604b3396902469f4c3a83a68c3c | 1,464 | movie_db | Apache License 2.0 |
app/src/main/java/com/mobven/extensions/recyclerview/concatadapter/ConcatExampleActivity.kt | mobven | 362,412,001 | false | null | package com.mobven.extensions.recyclerview.concatadapter
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.ConcatAdapter
import com.mobven.extensions.MenuAdapter
import com.mobven.extensions.databinding.ActivityConcatExampleBinding
class ConcatExampleActivity: AppCompatActivity() {
private lateinit var binding: ActivityConcatExampleBinding
private val horizontalFeedAdapter = HorizontalFeedAdapter()
private val horizontalFeedAdapter2 = HorizontalFeedAdapter()
private val menuAdapter = MenuAdapter(listOf("dssad","dsasda","dssad","dsasda","dssad","dsasda","dssad","dsasda"))
private val concatAdapter = ConcatAdapter(
horizontalFeedAdapter,
menuAdapter,
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityConcatExampleBinding.inflate(layoutInflater)
setContentView(binding.root)
horizontalFeedAdapter2.setData(getDummyData())
horizontalFeedAdapter.setData(getDummyData2())
concatAdapter.addAdapter(0,horizontalFeedAdapter2)
binding.rvActivity.adapter = concatAdapter
}
private fun getDummyData() = mutableListOf(
"sil",
"DATA2",
"DATA23",
"DATA34",
"DATA35",
"DATA31",
"DATA10",
"DSADSA",
"WWW",
"dsadsFFadsa",
"UUUU",
"TTTT",
"TTRTRRTRTRTTR"
)
private fun getDummyData2() = mutableListOf(
"sil",
"dsa",
"asd",
"dsa",
"DATA35",
)
}
| 3 | Kotlin | 5 | 37 | 2328e719d6990789430378377610132ec9890f15 | 1,624 | Extensify | MIT License |
src/main/kotlin/com/papsign/ktor/openapigen/annotations/type/number/integer/min/Min.kt | bargergo | 266,487,805 | true | {"Kotlin": 253682} | package com.papsign.ktor.openapigen.annotations.type.number.integer.min
import com.papsign.ktor.openapigen.schema.processor.SchemaProcessorAnnotation
import com.papsign.ktor.openapigen.validation.ValidatorAnnotation
@Target(AnnotationTarget.TYPE, AnnotationTarget.PROPERTY)
@SchemaProcessorAnnotation(MinProcessor::class)
@ValidatorAnnotation(MinProcessor::class)
annotation class Min(val value: Long)
| 0 | null | 0 | 0 | 10f49e3d9b0fa172ae9b5e8c267ccdbc4331c5e6 | 404 | Ktor-OpenAPI-Generator | Apache License 2.0 |
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/ui/representation/ideVersion/sections/IdeRepresentationItem.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.customize.transferSettings.ui.representation.ideVersion.sections
import com.intellij.ide.customize.transferSettings.models.SettingsPreferences
import com.intellij.ide.customize.transferSettings.models.SettingsPreferencesKind
import com.intellij.openapi.observable.properties.AtomicBooleanProperty
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.JBGaps
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import javax.swing.Icon
import javax.swing.JComponent
abstract class IdeRepresentationSection(private val prefs: SettingsPreferences,
final override val key: SettingsPreferencesKind,
private val icon: Icon) : TransferSettingsSection {
protected val _isSelected = AtomicBooleanProperty(prefs[key])
protected open val disabledCheckboxText: String? = null
private val leftGap = 20
private var morePanel: JComponent? = null
private var moreLabel: String = "More.."
val isSelected by _isSelected
init {
_isSelected.afterChange {
prefs[key] = it
}
}
protected abstract fun getContent(): JComponent
final override fun getUI() = panel {
customizeSpacingConfiguration(EmptySpacingConfiguration()) {
row {
icon(icon).verticalAlign(VerticalAlign.TOP).customize(JBGaps(left = 30, right = 30)).applyToComponent {
_isSelected.afterChange {
this.icon = if (it) [email protected] else IconLoader.getDisabledIcon(icon)
}
border = JBUI.Borders.empty()
}
panel {
row {
checkBox(name).bold().bindSelected(_isSelected).applyToComponent {
_isSelected.afterChange {
this.foreground = if (it) UIUtil.getLabelForeground() else UIUtil.getLabelDisabledForeground()
}
}.customize(JBGaps(bottom = 5, top = 5))
label("").visible(false).apply {
applyToComponent { foreground = UIUtil.getLabelDisabledForeground() }
_isSelected.afterChange {
visible(!it)
if (disabledCheckboxText != null && !it) {
component.text = disabledCheckboxText
}
}
}.customize(JBGaps(left = 10))
}.layout(RowLayout.INDEPENDENT)
row {
cell(getContent()).customize(JBGaps(left = leftGap)) // TODO: retrieve size of checkbox and add padding here
}
}.verticalAlign(VerticalAlign.TOP)
}
}
}
protected fun Row.mutableLabel(@NlsContexts.Label text: String) = label(text).applyToComponent {
_isSelected.afterChange {
this.foreground = if (it) UIUtil.getLabelForeground() else UIUtil.getLabelDisabledForeground()
}
}
private fun withMoreLabel(moreLbl: String?, pnl: JComponent) {
morePanel = pnl
moreLbl?.apply { moreLabel = this }
}
private fun withMoreLabel(pnl: JComponent) = withMoreLabel(null, pnl)
protected fun withMoreLabel(moreLbl: String?, pnl: () -> JComponent) = withMoreLabel(moreLbl, pnl())
protected fun withMoreLabel(pnl: (AtomicBooleanProperty) -> JComponent) = withMoreLabel(pnl(_isSelected))
} | 229 | null | 4931 | 15,571 | 92c8aad1c748d6741e2c8e326e76e68f3832f649 | 3,550 | intellij-community | Apache License 2.0 |
src/main/kotlin/g2001_2100/s2006_count_number_of_pairs_with_absolute_difference_k/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994} | package g2001_2100.s2006_count_number_of_pairs_with_absolute_difference_k
// #Easy #Array #Hash_Table #Counting #2023_06_23_Time_186_ms_(100.00%)_Space_37.5_MB_(66.67%)
import kotlin.math.abs
class Solution {
fun countKDifference(nums: IntArray, k: Int): Int {
var pairs = 0
for (i in 0 until nums.size - 1) {
for (j in i + 1 until nums.size) {
if (abs(nums[i] - nums[j]) == k) {
pairs++
}
}
}
return pairs
}
}
| 0 | Kotlin | 20 | 43 | 62708bc4d70ca2bfb6942e4bbfb4c64641e598e8 | 530 | LeetCode-in-Kotlin | MIT License |
car-rental-store/src/main/kotlin/com/lvb/studies/kotlin/api/carstore/controller/CarPostController.kt | Velosofurioso | 636,948,488 | false | null | package com.lvb.studies.kotlin.api.carstore.controller
import com.lvb.studies.kotlin.api.carstore.dto.CarPostDTO
import com.lvb.studies.kotlin.api.carstore.service.carPost.ICarPostService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/sales")
class CarPostController @Autowired constructor(
private val carPostService: ICarPostService
) {
@GetMapping("/car/")
fun getCarSale(): ResponseEntity<List<CarPostDTO>> =
ResponseEntity.status(HttpStatus.FOUND).body(carPostService.getCarSales())
@PutMapping("/car/{id}")
fun changeCarSale(@RequestBody carPostDTO: CarPostDTO, @PathVariable("id") id: String): ResponseEntity<Any> {
carPostService.changeCarSale(carPostDTO, id.toLong())
return ResponseEntity(HttpStatus.OK)
}
@DeleteMapping("/car/{id}")
fun removeCarSale(@PathVariable("id") id: String): ResponseEntity<Any> {
carPostService.removeCarSale(id.toLong())
return ResponseEntity(HttpStatus.OK)
}
} | 0 | Kotlin | 0 | 0 | 21bc34004b70bd5b08fe85fa21b99a1c003012cf | 1,541 | api-car-rental | MIT License |
applications/mobile_app/src/main/kotlin/dev/marlonlom/apps/glucoreo/ui/theme/Theme.kt | marlonlom | 524,531,428 | false | null | /*
* Copyright 2022 Marlonlom
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.marlonlom.apps.glucoreo.ui.theme
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import com.google.accompanist.systemuicontroller.rememberSystemUiController
private val glucoreoDarkColorScheme = darkColorScheme(
primary = Mikado,
onPrimary = Putty,
primaryContainer = Onion,
onPrimaryContainer = Sandwisp,
secondary = Bistre,
onSecondary = Laser,
secondaryContainer = Madras,
onSecondaryContainer = WildRice,
tertiary = Ebony,
onTertiary = LinkWater,
tertiaryContainer = Tuna,
onTertiaryContainer = LinkWater90,
onError = Color.Black,
)
private val glucoreoLightColorScheme = lightColorScheme(
primary = Drover,
onPrimary = Mikado,
primaryContainer = Varden,
onPrimaryContainer = Putty,
secondary = CreamBrulee,
onSecondary = Bistre,
secondaryContainer = BlanchedAlmond,
onSecondaryContainer = Laser,
tertiary = AliceBlue,
onTertiary = Ebony,
tertiaryContainer = AliceBlue90,
onTertiaryContainer = LinkWater,
error = FireBrick,
onError = Color.White,
errorContainer = Bridesmaid,
onErrorContainer = BakersChocolate
)
@Composable
private fun SystemUiControllerColorSetting(
statusBarColor: Color,
useDarkIcons: Boolean = isSystemInDarkTheme()
) {
val systemUiController = rememberSystemUiController()
SideEffect {
systemUiController.setSystemBarsColor(
color = statusBarColor,
darkIcons = !useDarkIcons
)
systemUiController.setStatusBarColor(
color = statusBarColor,
darkIcons = !useDarkIcons
)
}
}
@Suppress("DEPRECATION")
@Composable
fun GlucoreoTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> glucoreoDarkColorScheme
else -> glucoreoLightColorScheme
}
SystemUiControllerColorSetting(colorScheme.primary)
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
shapes = GlucoreoShapes,
content = content
)
}
| 0 | Kotlin | 0 | 0 | 6e05e0ba4ebb7e0b9c9b0cb53f1585e0c91ffaf1 | 3,316 | Glucoreo | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonersearch/services/SearchOperations.kt | ministryofjustice | 256,501,813 | false | null | package uk.gov.justice.digital.hmpps.prisonersearch.services
import org.elasticsearch.index.query.BoolQueryBuilder
import org.elasticsearch.index.query.QueryBuilders
import java.time.LocalDate
fun BoolQueryBuilder.mustWhenPresent(query: String, value: Any?): BoolQueryBuilder {
value.takeIf {
when (it) {
is String -> it.isNotBlank()
else -> true
}
}?.let {
this.must(QueryBuilders.matchQuery(query, it))
}
return this
}
fun BoolQueryBuilder.mustNotWhenPresent(query: String, value: Any?): BoolQueryBuilder {
value.takeIf {
when (it) {
is String -> it.isNotBlank()
else -> true
}
}?.let {
this.mustNot(QueryBuilders.matchQuery(query, it))
}
return this
}
fun BoolQueryBuilder.filterWhenPresent(query: String, value: Any?): BoolQueryBuilder {
value.takeIf {
when (it) {
is String -> it.isNotBlank()
is List<*> -> it.isNotEmpty()
else -> true
}
}?.let {
when (it) {
is List<*> -> this.filter(shouldMatchOneOf(query, it))
else -> this.filter(QueryBuilders.matchQuery(query, it))
}
}
return this
}
fun BoolQueryBuilder.shouldMultiMatch(value: Any?, vararg query: String): BoolQueryBuilder {
value.takeIf {
when (it) {
is String -> it.isNotBlank()
else -> true
}
}?.let {
this.should().add(QueryBuilders.multiMatchQuery(value, *query))
}
return this
}
fun BoolQueryBuilder.must(query: String, value: Any): BoolQueryBuilder {
this.must(QueryBuilders.matchQuery(query, value))
return this
}
fun BoolQueryBuilder.mustWhenTrue(predicate: () -> Boolean, query: String, value: String): BoolQueryBuilder {
value.takeIf { predicate() }?.let {
this.must(QueryBuilders.matchQuery(query, it))
}
return this
}
fun BoolQueryBuilder.mustMultiMatchKeyword(value: Any?, vararg query: String): BoolQueryBuilder {
value.takeIf {
when (it) {
is String -> it.isNotBlank()
else -> true
}
}?.let {
this.must().add(
QueryBuilders.multiMatchQuery(value, *query)
.analyzer("keyword")
)
}
return this
}
fun BoolQueryBuilder.mustMultiMatch(value: Any?, vararg query: String): BoolQueryBuilder {
value.takeIf {
when (it) {
is String -> it.isNotBlank()
else -> true
}
}?.let {
this.must().add(
QueryBuilders.multiMatchQuery(value, *query)
)
}
return this
}
fun BoolQueryBuilder.mustKeyword(value: Any?, query: String): BoolQueryBuilder {
value.takeIf {
when (it) {
is String -> it.isNotBlank()
else -> true
}
}?.let {
return this.must(QueryBuilders.matchQuery(query, value).analyzer("keyword"))
}
return this
}
fun BoolQueryBuilder.mustMatchOneOf(query: String, values: List<Any>): BoolQueryBuilder {
val nestedQuery = QueryBuilders.boolQuery()
values.forEach { nestedQuery.should(QueryBuilders.boolQuery().must(query, it)) }
return this.must(nestedQuery)
}
fun shouldMatchOneOf(query: String, values: List<*>): BoolQueryBuilder {
val nestedQuery = QueryBuilders.boolQuery()
values.forEach { nestedQuery.should(QueryBuilders.matchQuery(query, it)) }
return nestedQuery
}
fun BoolQueryBuilder.mustWhenPresentGender(query: String, value: Any?) =
if (value == "ALL") this else mustWhenPresent(query, value)
fun BoolQueryBuilder.matchesDateRange(earliest: LocalDate?, latest: LocalDate?, vararg query: String): BoolQueryBuilder {
val nestedClauses = QueryBuilders.boolQuery()
query.asList().forEach {
nestedClauses.should().add(QueryBuilders.rangeQuery(it).from(earliest).to(latest))
}
return this.must(nestedClauses)
}
| 3 | null | 3 | 5 | bb3fb21dca2cae2ee10d51c0fa89c10361fa30b7 | 3,612 | prisoner-offender-search | MIT License |
heavy_boot3/src/main/kotlin/net/kotlinx/spring/security/jwt/JwtTokenReadFilter.kt | mypojo | 565,799,715 | false | {"Kotlin": 1352508, "Jupyter Notebook": 13439, "Java": 9531} | package net.kotlinx.spring.security.jwt
import jakarta.servlet.FilterChain
import jakarta.servlet.ServletRequest
import jakarta.servlet.ServletResponse
import jakarta.servlet.http.HttpServletRequest
import mu.KotlinLogging
import net.kotlinx.spring.security.SimpleAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.web.filter.GenericFilterBean
class JwtTokenReadFilter(
/** 로그인 없을때 사용한 디폴트(익명) 사용자 */
private val defaultUser: UserDetails,
/** null이면 jwt 인증이 불가능한것으로 간주한다. */
private val tokenProvider: (String?) -> UserDetails?,
) : GenericFilterBean() {
override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
val auth = (request as HttpServletRequest).getHeader(AUTHORIZATION_HEADER)
tokenProvider(auth)?.let {
log.trace { " -> 인증정보 context에 저장 : $it" }
SecurityContextHolder.getContext().authentication = SimpleAuthenticationToken(it)
} ?: run {
log.trace { " -> 인증정보 없음" }
SecurityContextHolder.getContext().authentication = SimpleAuthenticationToken(defaultUser)
}
chain.doFilter(request, response)
}
companion object {
private val log = KotlinLogging.logger {}
const val AUTHORIZATION_HEADER = "Authorization"
}
} | 0 | Kotlin | 0 | 1 | fb930ed8208165b710de3eff879e1aaa2f154655 | 1,431 | kx_kotlin_support | MIT License |
compiler/testData/codegen/box/reflection/typeOf/js/inlineClasses.kt | JetBrains | 3,432,266 | false | null | // TARGET_BACKEND: JS
// WITH_REFLECT
// KJS_WITH_FULL_RUNTIME
package test
import kotlin.reflect.KType
import kotlin.reflect.typeOf
import kotlin.test.assertEquals
inline class Z(val value: String)
fun check(expected: String, actual: KType) {
assertEquals(expected, actual.toString())
}
fun box(): String {
check("Z", typeOf<Z>())
check("Z?", typeOf<Z?>())
check("Array<Z>", typeOf<Array<Z>>())
check("Array<Z?>", typeOf<Array<Z?>>())
check("UInt", typeOf<UInt>())
check("UInt?", typeOf<UInt?>())
check("ULong?", typeOf<ULong?>())
check("UShortArray", typeOf<UShortArray>())
check("UShortArray?", typeOf<UShortArray?>())
check("Array<UByteArray>", typeOf<Array<UByteArray>>())
check("Array<UByteArray?>?", typeOf<Array<UByteArray?>?>())
return "OK"
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 811 | kotlin | Apache License 2.0 |
navigation/src/main/java/com/rohyme/navigation/homecontainer/friendsScreen/FriendsScreen4.kt | Rohyme | 279,625,101 | false | null | package com.rohyme.navigation.homecontainer.friendsScreen
import com.rohyme.navigation.R
import com.rohyme.navigation.homecontainer.BaseFragment
/**
* Created by rohyme on 7/14/20.
**/
class FriendsScreen4: BaseFragment() {
override var fragmentName: String = "Friends Screen 1"
override var navigationId: Int? = R.id.action_friendsScreen4_to_friendsScreen5
} | 0 | Kotlin | 0 | 0 | ae6f1e58693c840fa432d01962af8f377d59d65a | 371 | TechnivanceSideApp | Apache License 2.0 |
src/main/kotlin/kr/jadekim/redis/lettuce/Redis.kt | jdekim43 | 238,139,395 | false | null | package kr.jadekim.redis.lettuce
import io.lettuce.core.ClientOptions
import io.lettuce.core.RedisClient
import io.lettuce.core.RedisFuture
import io.lettuce.core.RedisURI
import io.lettuce.core.api.StatefulRedisConnection
import io.lettuce.core.api.async.RedisAsyncCommands
import io.lettuce.core.codec.RedisCodec
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection
import io.lettuce.core.resource.DefaultClientResources
import io.lettuce.core.support.AsyncConnectionPoolSupport
import io.lettuce.core.support.BoundedAsyncPool
import io.lettuce.core.support.BoundedPoolConfig
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.future.asDeferred
import kotlinx.coroutines.runBlocking
import java.io.Closeable
import java.util.concurrent.CompletionStage
typealias StringKeyRedis<V> = Redis<String, V>
typealias StringRedis = Redis<String, String>
val LETTUCE_DEFAULT_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 3
abstract class Redis<K, V>(
protected val codec: RedisCodec<K, V>,
executePoolSize: Int = LETTUCE_DEFAULT_POOL_SIZE,
readPoolSize: Int = LETTUCE_DEFAULT_POOL_SIZE
) : Closeable {
private val resourceConfig = DefaultClientResources.create()
private val options = ClientOptions.builder()
.autoReconnect(true)
.build()
private val poolConfig = BoundedPoolConfig.builder()
.minIdle(1)
.testOnAcquire(true)
.testOnCreate(true)
protected val client = RedisClient.create(resourceConfig).apply {
options = [email protected]
}
protected val executePool by lazy {
AsyncConnectionPoolSupport.createBoundedObjectPool(
{ connectForExecute() },
poolConfig.maxIdle(executePoolSize)
.maxTotal(executePoolSize)
.build()
).also { isCreatedExecutePool = true }
}
protected val readPool by lazy {
if (readPoolSize == 0) {
executePool
} else {
AsyncConnectionPoolSupport.createBoundedObjectPool(
{ connectForRead() },
poolConfig.maxIdle(readPoolSize)
.maxTotal(readPoolSize)
.build()
).also { isCreatedReadPool = true }
}
}
private var isCreatedExecutePool = false
private var isCreatedReadPool = false
abstract fun connectForExecute(): CompletionStage<StatefulRedisConnection<K, V>>
abstract fun connectForRead(): CompletionStage<StatefulRedisConnection<K, V>>
abstract fun connectPubSub(): CompletionStage<StatefulRedisPubSubConnection<K, V>>
suspend fun subscribe(queueCapacity: Int = Channel.UNLIMITED): RedisPubSubConnection<K, V> {
val connection = connectPubSub().asDeferred().await()
return RedisPubSubConnection(connection, queueCapacity)
}
override fun close() {
runBlocking { closeAsync() }
}
suspend fun closeAsync() {
if (isCreatedExecutePool) {
executePool.closeAsync().asDeferred().await()
}
if (isCreatedReadPool) {
readPool.closeAsync().asDeferred().await()
}
client.shutdownAsync().asDeferred().await()
}
suspend fun <T> execute(statement: RedisAsyncCommands<K, V>.() -> RedisFuture<T>): T {
return executePool { statement().asDeferred().await() }
}
suspend fun <T> read(statement: RedisAsyncCommands<K, V>.() -> RedisFuture<T>): T {
return readPool { statement().asDeferred().await() }
}
suspend operator fun <T> invoke(
isRead: Boolean = true,
statement: RedisAsyncCommands<K, V>.() -> RedisFuture<T>
): T = execute(statement)
suspend fun pipe(
statement: suspend RedisAsyncCommands<K, V>.(MutableList<RedisFuture<*>>) -> Unit
): List<Any> = executePool {
val commands = mutableListOf<RedisFuture<*>>()
setAutoFlushCommands(false)
statement(commands)
flushCommands()
setAutoFlushCommands(true)
val deferredCommands = commands.map { it.asDeferred() }
.toTypedArray()
awaitAll(*deferredCommands)
}
private suspend operator fun <T> BoundedAsyncPool<StatefulRedisConnection<K, V>>.invoke(
statement: suspend RedisAsyncCommands<K, V>.() -> T
): T {
val connection = acquire().asDeferred().await()
return try {
connection.async().statement()
} finally {
release(connection)
}
}
}
@Suppress("FunctionName")
internal fun RedisURI(
host: String,
port: Int = 6379,
dbIndex: Int = 0,
password: String? = null
) = RedisURI.Builder.redis(host, port).withDatabase(dbIndex)
.apply {
if (password != null) {
withPassword(password)
}
}
.build() | 0 | Kotlin | 0 | 0 | 086437a1fa55731b5a6993c1f19f8e39fd5ebc49 | 4,992 | lettuce-extension | MIT License |
api/src/main/kotlin/kiinse/me/plugins/darkwaterapi/api/commands/DarkCommandManager.kt | kiinse | 518,125,280 | false | {"Kotlin": 284439, "Java": 9392} | package kiinse.me.plugins.darkwaterapi.api.commands
import kiinse.me.plugins.darkwaterapi.api.DarkWaterJavaPlugin
import kiinse.me.plugins.darkwaterapi.api.exceptions.CommandException
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.command.PluginCommand
import org.bukkit.entity.Player
import java.lang.reflect.Method
import java.util.logging.Level
@Suppress("UNUSED")
abstract class DarkCommandManager : CommandExecutor {
protected val plugin: DarkWaterJavaPlugin
protected val failureHandler: CommandFailureHandler
protected val registeredSubCommandTable: MutableMap<String, RegisteredCommand> = HashMap()
protected val registeredMainCommandTable: MutableMap<String, RegisteredCommand> = HashMap()
protected val mainCommandTable: MutableMap<DarkCommand, String> = HashMap()
protected constructor(plugin: DarkWaterJavaPlugin) {
this.plugin = plugin
failureHandler = plugin.darkWaterAPI.commandFailureHandler
}
protected constructor(plugin: DarkWaterJavaPlugin, failureHandler: CommandFailureHandler) {
this.plugin = plugin
this.failureHandler = failureHandler
}
/**
* Registration class commands
*
* @param commandClass A class that inherits from CommandClass and contains command methods
*/
@Throws(CommandException::class)
abstract fun registerCommand(commandClass: DarkCommand): DarkCommandManager
@Throws(CommandException::class)
protected fun registerMainCommand(commandClass: DarkCommand, method: Method): String {
val mainCommand = method.getAnnotation(Command::class.java)
val command = mainCommand.command
register(commandClass, method, plugin.server.getPluginCommand(command), command, mainCommand, true)
return command
}
@Throws(CommandException::class)
protected fun registerMainCommand(darkCommand: DarkCommand): String {
val mainCommand = darkCommand.javaClass.getAnnotation(Command::class.java)
val command = mainCommand.command
register(darkCommand, plugin.server.getPluginCommand(command), mainCommand)
return command
}
@Throws(CommandException::class)
protected fun registerSubCommand(commandClass: DarkCommand, method: Method) {
val annotation = method.getAnnotation(SubCommand::class.java)
val mainCommand = mainCommandTable[commandClass]
if (annotation != null && annotation.command != mainCommand) {
val cmd = mainCommand + " " + annotation.command
register(commandClass, method, plugin.server.getPluginCommand(cmd), cmd, annotation, false)
}
}
@Throws(CommandException::class)
protected fun register(commandClass: DarkCommand, method: Method, pluginCommand: PluginCommand?,
command: String, annotation: Any, isMainCommand: Boolean) {
register(pluginCommand, command)
(if (isMainCommand) registeredMainCommandTable else registeredSubCommandTable)[command] = object : RegisteredCommand(method, commandClass, annotation) {}
plugin.sendLog(Level.CONFIG, "Command '&d$command&6' registered!")
}
@Throws(CommandException::class)
protected fun register(commandClass: DarkCommand, pluginCommand: PluginCommand?, annotation: Command) {
val command = annotation.command
register(pluginCommand, command)
registeredMainCommandTable[command] = object : RegisteredCommand(null, commandClass, annotation) {}
}
@Throws(CommandException::class)
protected fun register(pluginCommand: PluginCommand?, command: String) {
if (registeredSubCommandTable.containsKey(command) || registeredMainCommandTable.containsKey(command)) throw CommandException("Command '$command' already registered!")
if (pluginCommand == null) throw CommandException("Unable to register command command '$command'. Did you put it in plugin.yml?")
pluginCommand.setExecutor(this)
}
@Throws(CommandException::class)
protected fun getMainCommandMethod(darkCommand: Class<out DarkCommand?>): Method {
darkCommand.methods.forEach {
if (it.getAnnotation(Command::class.java) != null) return it
}
val name = darkCommand.name.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
throw CommandException("Main command in class '${name[name.size - 1]}' not found!")
}
protected fun isDisAllowNonPlayer(wrapper: RegisteredCommand, sender: CommandSender, disAllowNonPlayer: Boolean): Boolean {
if (sender !is Player && disAllowNonPlayer) {
failureHandler.handleFailure(CommandFailReason.NOT_PLAYER, sender, wrapper)
return true
}
return false
}
protected fun hasNotPermissions(wrapper: RegisteredCommand, sender: CommandSender, permission: String): Boolean {
if (permission != "" && !sender.hasPermission(permission)) {
failureHandler.handleFailure(CommandFailReason.NO_PERMISSION, sender, wrapper)
return true
}
return false
}
override fun onCommand(sender: CommandSender, command: org.bukkit.command.Command, label: String, args: Array<String>): Boolean {
return onExecute(sender, command, label, args)
}
protected abstract fun onExecute(sender: CommandSender, command: org.bukkit.command.Command, label: String, args: Array<String>): Boolean
} | 0 | Kotlin | 0 | 3 | c96bf839634b87ab44ddcf7faed7576d1c587cf5 | 5,472 | DarkWaterAPI | MIT License |
android/app/src/main/kotlin/com/example/gitee_client_app/MainActivity.kt | baoqiang | 432,944,891 | false | null | package com.example.gitee_client_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | null | 0 | 0 | d0f00a08346c0c81d5b50de378b987220cee4f4b | 133 | flutter-demo | MIT License |
src/test/kotlin/org/sheinbergon/dremio/udf/gis/STDWithinTests.kt | sheinbergon | 479,823,237 | false | {"Java": 205014, "Kotlin": 139786} | package org.sheinbergon.dremio.udf.gis
import org.apache.arrow.vector.holders.Float8Holder
import org.apache.arrow.vector.holders.NullableBitHolder
import org.apache.arrow.vector.holders.NullableVarBinaryHolder
import org.sheinbergon.dremio.udf.gis.spec.GeometryRelationFunSpec
import org.sheinbergon.dremio.udf.gis.util.reset
internal class STDWithinTests : GeometryRelationFunSpec.NullableBitOutput<STDWithin>() {
override val function = STDWithin().apply {
binaryInput1 = NullableVarBinaryHolder()
binaryInput2 = NullableVarBinaryHolder()
distanceInput = Float8Holder()
output = NullableBitHolder()
}
init {
beforeEach {
function.distanceInput.reset()
}
testTrueGeometryRelation(
"Calling ST_DWithin with a distance of 2.0 on 2 given relating LINESTRINGs",
"LINESTRING(0 1,2 2)",
"LINESTRING(2 2,0 1)"
) { function.apply { distanceInput.value = 2.0 } }
testFalseGeometryRelation(
"Calling ST_DWithin with a distance of 0.02 on the given POINT and LINESTRING",
"POINT(0 0)",
"LINESTRING(1 5,0 1)"
) { function.apply { distanceInput.value = 0.02 } }
testNullGeometryRelation(
"Calling ST_DWithin with one or two null geometries",
"POINT(0 0)",
null,
) { function.apply { distanceInput.value = 0.02 } }
}
override val STDWithin.wkbInput1: NullableVarBinaryHolder get() = function.binaryInput1
override val STDWithin.wkbInput2: NullableVarBinaryHolder get() = function.binaryInput2
override val STDWithin.output: NullableBitHolder get() = function.output
}
| 0 | Java | 0 | 23 | 91dc5268662b2925b2adca05061eb05bd9467ded | 1,587 | dremio-udf-gis | Apache License 2.0 |
yandex-mapkit-kmp/src/iosMain/kotlin/ru/sulgik/mapkit/map/IconStyle.ios.kt | SuLG-ik | 813,953,018 | false | {"Kotlin": 121845} | package ru.sulgik.mapkit.map
import YandexMapKit.YMKIconStyle
import platform.Foundation.NSNumber
import platform.Foundation.numberWithBool
import platform.Foundation.numberWithFloat
import platform.Foundation.numberWithInt
fun IconStyle.toNative(): YMKIconStyle {
return YMKIconStyle.iconStyleWithAnchor(
anchor = null,
rotationType = rotationType?.ordinal?.let(NSNumber.Companion::numberWithInt),
zIndex = zIndex?.let(NSNumber.Companion::numberWithFloat),
flat = flat?.let(NSNumber.Companion::numberWithBool),
visible = isVisible?.let(NSNumber.Companion::numberWithBool),
scale = scale?.let(NSNumber.Companion::numberWithFloat),
tappableArea = null,
)
}
fun YMKIconStyle.toCommon(): IconStyle {
return IconStyle(
rotationType = rotationType?.let { RotationType.entries[it.intValue()] },
zIndex = zIndex?.floatValue,
flat = flat?.boolValue,
isVisible = visible?.boolValue,
scale = scale?.floatValue,
)
} | 0 | Kotlin | 0 | 0 | f6ed911d25f5e26a91ca6b2152a8fa74f6639ee8 | 1,019 | yandex-mapkit-kmp | Apache License 2.0 |
annotation/src/main/kotlin/com/github/henryJung/annotation/MapperProperty.kt | henryJung | 614,363,120 | false | null | package com.github.henryJung.annotation
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.BINARY)
annotation class MapperProperty(val alias: String = "") | 0 | Kotlin | 0 | 0 | b5555a4cc127b7120cf491d963da0d6f116f3687 | 170 | Mapper | Apache License 2.0 |
app/src/main/java/com/timilehinaregbesola/mathalarm/presentation/alarmsettings/components/TextWithIcon.kt | t-regbs | 223,649,248 | false | {"Kotlin": 283958} | package com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Notifications
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight.Companion.Normal
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.TextWithIcon.ICON_END_PADDING
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.TextWithIcon.TEXT_FONT_SIZE
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.TextWithIcon.TEXT_WITH_ICON_HORIZONTAL_PADDING
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.TextWithIcon.TEXT_WITH_ICON_TOP_PADDING
@Composable
fun TextWithIcon(
image: ImageVector,
text: String,
modifier: Modifier = Modifier,
onClick: (() -> Unit)? = null,
) {
Row(
modifier = modifier
.padding(
top = TEXT_WITH_ICON_TOP_PADDING,
start = TEXT_WITH_ICON_HORIZONTAL_PADDING,
end = TEXT_WITH_ICON_HORIZONTAL_PADDING,
)
.fillMaxWidth(),
) {
Icon(
modifier = Modifier.padding(end = ICON_END_PADDING),
imageVector = image,
contentDescription = null,
)
Text(
modifier = Modifier.clickable { onClick?.invoke() },
text = text,
fontSize = TEXT_FONT_SIZE,
fontWeight = Normal,
)
}
}
@Preview
@Composable
private fun TextWithIconPreview() {
MaterialTheme {
TextWithIcon(image = Icons.Outlined.Notifications, text = "Notify")
}
}
private object TextWithIcon {
val TEXT_FONT_SIZE = 16.sp
val ICON_END_PADDING = 14.dp
val TEXT_WITH_ICON_TOP_PADDING = 30.dp
val TEXT_WITH_ICON_HORIZONTAL_PADDING = 10.dp
}
| 2 | Kotlin | 2 | 15 | 1cc000f3c8345209b0494efed3274f2a3f8a4373 | 2,421 | MathAlarm | MIT License |
plugins/kotlin/code-insight/structural-search-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/structuralsearch/filters/AlsoMatchVarModifier.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.structuralsearch.filters
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
class AlsoMatchVarModifier : OneStateFilter(
KotlinBundle.lazyMessage("modifier.match.var"),
KotlinBundle.message("modifier.also.match.var"),
CONSTRAINT_NAME
) {
companion object {
const val CONSTRAINT_NAME: @NonNls String = "kotlinAlsoMatchVar"
}
} | 191 | null | 4372 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 560 | intellij-community | Apache License 2.0 |
android/Rental/app/src/main/java/com/project/pradyotprakash/rental/app/composables/AnimatedProgressBar.kt | pradyotprksh | 385,586,594 | false | null | package com.project.pradyotprakash.rental.app.composables
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ProgressIndicatorDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
/**
* An animated progress bar indicator which will be used to show the current progress
* of an action.
*
* @param indicatorProgress Progress completed value
*/
@Composable
fun AnimatedProgressBar(indicatorProgress: Float) {
val animatedProgress = animateFloatAsState(
targetValue = indicatorProgress,
animationSpec = ProgressIndicatorDefaults.ProgressAnimationSpec
).value
LinearProgressIndicator(
progress = animatedProgress,
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(20.dp)),
)
} | 0 | Kotlin | 7 | 9 | e10e007fab12c3d056920741c06ff599a64cca21 | 1,082 | development_learning | MIT License |
colormath/src/commonMain/kotlin/com/github/ajalt/colormath/CssParse.kt | ajalt | 139,778,270 | false | {"Kotlin": 323562, "Python": 4897, "Shell": 1192, "HTML": 324} | package com.github.ajalt.colormath
import com.github.ajalt.colormath.internal.*
import com.github.ajalt.colormath.model.*
import com.github.ajalt.colormath.model.LABColorSpaces.LAB50
import com.github.ajalt.colormath.model.LCHabColorSpaces.LCHab50
import com.github.ajalt.colormath.model.RGBColorSpaces.AdobeRGB
import com.github.ajalt.colormath.model.RGBColorSpaces.BT2020
import com.github.ajalt.colormath.model.RGBColorSpaces.DisplayP3
import com.github.ajalt.colormath.model.RGBColorSpaces.LinearSRGB
import com.github.ajalt.colormath.model.RGBColorSpaces.ROMM_RGB
import com.github.ajalt.colormath.model.XYZColorSpaces.XYZ50
import com.github.ajalt.colormath.model.XYZColorSpaces.XYZ65
import kotlin.jvm.JvmOverloads
import kotlin.math.roundToInt
/**
* Parse a string representing a CSS color value.
*
* @param color The CSS color string to parse
* @param customColorSpaces A list of custom color spaces to recognize in the `color()` function.
* Each pair should be the identifier of the color and its [ColorSpace].
* @throws IllegalArgumentException if the value cannot be parsed
*/
@JvmOverloads // TODO(4.0) remove this
fun Color.Companion.parse(
color: String,
customColorSpaces: Map<String, ColorSpace<*>> = emptyMap(),
): Color {
return parseOrNull(color, customColorSpaces)
?: throw IllegalArgumentException("Invalid color: $color")
}
/**
* Parse a string representing a CSS color value, or return null if the string isn't in a recognized
* format.
*
* @param color The color string to parse
* @param customColorSpaces A list of custom color spaces to recognize in the `color()` function.
* Each pair should be the identifier of the color and its [ColorSpace].
*/
@JvmOverloads // TODO(4.0) remove this
fun Color.Companion.parseOrNull(
color: String,
customColorSpaces: Map<String, ColorSpace<*>> = emptyMap(),
): Color? {
val keywordColor = CssColors.colorsByName[color]
return when {
keywordColor != null -> keywordColor
color.startsWith("#") -> runCatching { RGB(color) }.getOrNull()
else -> {
PATTERNS.RGB_1.matchEntire(color)?.let { rgb(it) }
?: PATTERNS.RGB_2.matchEntire(color)?.let { rgb(it) }
?: PATTERNS.RGB_3.matchEntire(color)?.let { rgb(it) }
?: PATTERNS.RGB_4.matchEntire(color)?.let { rgb(it) }
?: PATTERNS.HSL_1.matchEntire(color)?.let { hsl(it) }
?: PATTERNS.HSL_2.matchEntire(color)?.let { hsl(it) }
?: PATTERNS.LAB.matchEntire(color)?.let { lab(it) }
?: PATTERNS.LCH.matchEntire(color)?.let { lch(it) }
?: PATTERNS.HWB.matchEntire(color)?.let { hwb(it) }
?: PATTERNS.OKLAB.matchEntire(color)?.let { oklab(it) }
?: PATTERNS.OKLCH.matchEntire(color)?.let { oklch(it) }
?: PATTERNS.COLOR.matchEntire(color)?.let { color(it, customColorSpaces) }
}
}
}
// https://www.w3.org/TR/css-color-4/#color-syntax
@Suppress("RegExpUnnecessaryNonCapturingGroup")
private object PATTERNS {
private const val FLOAT = """[+-]?(?:\d+|\d*\.\d+)(?:[eE][+-]?\d+)?"""
private const val NUMBER = """(?:none|$FLOAT)"""
private const val PERCENT = "$FLOAT%"
private const val NUMBER_OR_PERCENT = "(?:none|$FLOAT%?)"
private const val SLASH_ALPHA = """\s*(?:/\s*($NUMBER_OR_PERCENT))?\s*"""
private const val COMMA_ALPHA = """(?:\s*,\s*($NUMBER_OR_PERCENT))?\s*"""
private const val HUE = "$NUMBER(?:deg|grad|rad|turn)?"
val RGB_1 = Regex("""rgba?\(($PERCENT)\s+($PERCENT)\s+($PERCENT)$SLASH_ALPHA\)""")
val RGB_2 = Regex("""rgba?\(($PERCENT)\s*,\s*($PERCENT)\s*,\s*($PERCENT)$COMMA_ALPHA\)""")
val RGB_3 = Regex("""rgba?\(($NUMBER)\s+($NUMBER)\s+($NUMBER)$SLASH_ALPHA\)""")
val RGB_4 = Regex("""rgba?\(($NUMBER)\s*,\s*($NUMBER)\s*,\s*($NUMBER)$COMMA_ALPHA\)""")
val HSL_1 = Regex("""hsla?\(($HUE)\s+($PERCENT)\s+($PERCENT)$SLASH_ALPHA\)""")
val HSL_2 = Regex("""hsla?\(($HUE)\s*,\s*($PERCENT)\s*,\s*($PERCENT)$COMMA_ALPHA\)""")
val LAB = Regex("""lab\(($PERCENT)\s+($NUMBER)\s+($NUMBER)$SLASH_ALPHA\)""")
val LCH = Regex("""lch\(($PERCENT)\s+($NUMBER)\s+($HUE)$SLASH_ALPHA\)""")
val HWB = Regex("""hwb\(($HUE)\s+($PERCENT)\s+($PERCENT)$SLASH_ALPHA\)""")
val OKLAB = Regex("""oklab\(($NUMBER_OR_PERCENT)\s+($NUMBER)\s+($NUMBER)$SLASH_ALPHA\)""")
val OKLCH = Regex("""oklch\(($NUMBER_OR_PERCENT)\s+($NUMBER)\s+($HUE)$SLASH_ALPHA\)""")
val COLOR = Regex(
"""color\(([\w\-]+)\s+($NUMBER_OR_PERCENT(?:\s+$NUMBER_OR_PERCENT)*)$SLASH_ALPHA\)"""
)
}
private fun color(
match: MatchResult,
customColorSpaces: Map<String, ColorSpace<*>>,
): Color? {
val space = when (val name = match.groupValues[1]) {
"srgb" -> SRGB
"srgb-linear" -> LinearSRGB
"display-p3" -> DisplayP3
"a98-rgb" -> AdobeRGB
"prophoto-rgb" -> ROMM_RGB
"rec2020" -> BT2020
"xyz", "xyz-d50" -> XYZ50
"xyz-d65" -> XYZ65
else -> customColorSpaces.entries.firstOrNull { it.key == name }?.value
} ?: return null
val values = match.groupValues[2].split(Regex("\\s+")).map { percentOrNumber(it).clampF() }
val components = FloatArray(space.components.size) { values.getOrElse(it) { 0f } }
components[components.lastIndex] = alpha(match.groupValues[3])
return space.create(components)
}
private fun rgb(match: MatchResult): Color {
val r = percentOrNumber(match.groupValues[1])
val g = percentOrNumber(match.groupValues[2])
val b = percentOrNumber(match.groupValues[3])
val a = alpha(match.groupValues[4])
return if (match.groupValues[1].endsWith("%")) {
RGB(r.clampF(), g.clampF(), b.clampF(), a)
} else {
RGB(r.clampInt() / 255f, g.clampInt() / 255f, b.clampInt() / 255f, a)
}
}
private fun hsl(match: MatchResult): Color {
val h = hue(match.groupValues[1])
val s = percent(match.groupValues[2])
val l = percent(match.groupValues[3])
val a = alpha(match.groupValues[4])
return HSL(h, s.clampF(), l.clampF(), a.clampF())
}
private fun lab(match: MatchResult): Color {
val l = percent(match.groupValues[1])
val a = number(match.groupValues[2])
val b = number(match.groupValues[3])
val alpha = alpha(match.groupValues[4])
return LAB50(l.coerceAtLeast(0f) * 100f, a, b, alpha)
}
private fun lch(match: MatchResult): Color {
val l = percent(match.groupValues[1])
val c = number(match.groupValues[2])
val h = hue(match.groupValues[3])
val a = alpha(match.groupValues[4])
return LCHab50(l.coerceAtLeast(0f) * 100f, c.coerceAtLeast(0f), h, a)
}
private fun hwb(match: MatchResult): Color {
val h = hue(match.groupValues[1])
val w = percent(match.groupValues[2])
val b = percent(match.groupValues[3])
val a = alpha(match.groupValues[4])
return HWB(h, w.clampF(), b.clampF(), a)
}
private fun oklab(match: MatchResult): Color {
val l = percentOrNumber(match.groupValues[1])
val a = number(match.groupValues[2])
val b = number(match.groupValues[3])
val alpha = alpha(match.groupValues[4])
return Oklab(l, a, b, alpha)
}
private fun oklch(match: MatchResult): Color {
val l = percentOrNumber(match.groupValues[1])
val c = number(match.groupValues[2])
val h = hue(match.groupValues[3])
val a = alpha(match.groupValues[4])
return Oklch(l, c, h, a)
}
// CSS uses the "none" keyword for NaN https://www.w3.org/TR/css-color-4/#missing
private fun number(str: String) = if(str == "none") Float.NaN else str.toFloat()
private fun percent(str: String) = str.dropLast(1).toFloat() / 100f
private fun percentOrNumber(str: String) = if (str.endsWith("%")) percent(str) else number(str)
private fun alpha(str: String) = (if (str.isEmpty()) 1f else percentOrNumber(str)).clampF()
/** return degrees in [0, 360] */
private fun hue(str: String): Float {
return when {
str.endsWith("deg") -> str.dropLast(3).toFloat()
str.endsWith("grad") -> str.dropLast(4).toFloat().gradToDeg()
str.endsWith("rad") -> str.dropLast(3).toFloat().radToDeg()
str.endsWith("turn") -> str.dropLast(4).toFloat().turnToDeg()
else -> number(str)
}.normalizeDeg()
}
private fun Float.clampInt(min: Int = 0, max: Int = 255) = roundToInt().coerceIn(min, max)
private fun Float.clampF(min: Float = 0f, max: Float = 1f) = coerceIn(min, max)
| 1 | Kotlin | 19 | 281 | e401329f845d5efe0fb626f9455dd4fa598a8ccd | 8,445 | colormath | MIT License |
bitcoin_ticker/android/app/src/main/kotlin/io/github/vijethph/bitcoin_ticker/MainActivity.kt | vijethph | 372,726,856 | false | {"Dart": 91074, "HTML": 4543, "Swift": 4040, "Kotlin": 1328, "Objective-C": 380} | package io.github.vijethph.bitcoin_ticker
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 1 | b69d509828c82b92499033495fb60c8fa42f8e11 | 138 | FlutterApps | MIT License |
src/main/kotlin/com/zeta/system/controller/MainController.kt | xia5800 | 449,936,024 | false | null | package com.zeta.system.controller
import cn.dev33.satoken.stp.StpUtil
import cn.hutool.core.util.StrUtil
import com.github.xiaoymin.knife4j.annotations.ApiSupport
import com.wf.captcha.SpecCaptcha
import com.zeta.common.cacheKey.CaptchaStringCacheKey
import com.zeta.system.model.entity.SysUser
import com.zeta.system.model.enums.UserStateEnum
import com.zeta.system.model.param.LoginParam
import com.zeta.system.model.result.CaptchaResult
import com.zeta.system.model.result.LoginResult
import com.zeta.system.service.ISysUserService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.ApplicationContext
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import org.zetaframework.base.controller.SuperSimpleController
import org.zetaframework.base.result.ApiResult
import org.zetaframework.core.log.enums.LoginStateEnum
import org.zetaframework.core.log.event.SysLoginEvent
import org.zetaframework.core.log.model.SysLoginLogDTO
import org.zetaframework.core.redis.annotation.Limit
import org.zetaframework.core.utils.ContextUtil
import org.zetaframework.extra.crypto.helper.AESHelper
import javax.servlet.http.HttpServletRequest
/**
* 登录认证
* @author gcc
*/
@ApiSupport(order = 1)
@Api(tags = ["登录认证"])
@RestController
@RequestMapping("/api")
class MainController(
private val applicationContext: ApplicationContext,
private val captchaCacheKey: CaptchaStringCacheKey,
private val aseHelper: AESHelper
): SuperSimpleController<ISysUserService, SysUser>() {
@Value("\${spring.profiles.active:prod}")
private val env: String? = null
/**
* 用户登录
* @param param LoginParam
* @return ApiResult<LoginResult>
*/
@ApiOperation(value = "登录")
@PostMapping("/login")
fun login(@RequestBody @Validated param: LoginParam, request: HttpServletRequest): ApiResult<LoginResult> {
// 验证验证码
val verifyCode = captchaCacheKey.get<String>(param.key)
if (StrUtil.isBlank(verifyCode)) {
return fail("验证码过期")
}
if (!param.code.equals(verifyCode, true)) {
return fail("验证码错误")
}
captchaCacheKey.delete(param.key)
// 查询用户, 因为账号已经判空过了所以这里直接param.account!!
val user = service.getByAccount(param.account!!) ?: return fail("用户不存在")
// 设置用户id,方便记录日志的时候设置创建人。
ContextUtil.setUserId(user.id!!)
// 密码解密
val password = try {
aseHelper.decryptStr(param.password!!)
} catch (e: Exception) {
""
}
// 判断密码
if(!service.comparePassword(password, user.password!!)) {
applicationContext.publishEvent(SysLoginEvent(SysLoginLogDTO.loginFail(
param.account!!, LoginStateEnum.ERROR_PWD, request
)))
// 密码不正确
return fail(LoginStateEnum.ERROR_PWD.desc)
}
// 判断用户状态
if(user.state == UserStateEnum.FORBIDDEN.code) {
applicationContext.publishEvent(SysLoginEvent(SysLoginLogDTO.loginFail(
param.account!!, LoginStateEnum.FAIL, "用户被禁用,无法登录", request
)))
return fail("用户被禁用,无法登录")
}
// 踢人下线并登录
StpUtil.kickout(user.id)
StpUtil.login(user.id)
// 登录日志
applicationContext.publishEvent(SysLoginEvent(SysLoginLogDTO.loginSuccess(param.account!!, request = request)))
// 构造登录返回结果
return success(LoginResult(StpUtil.getTokenName(), StpUtil.getTokenValue()))
}
/**
* 注销登录
* @return ApiResult<Boolean>
*/
@ApiOperation(value = "注销登录")
@GetMapping("/logout")
fun logout(request: HttpServletRequest): ApiResult<Boolean> {
val user = service.getById(StpUtil.getLoginIdAsLong()) ?: return fail("用户异常")
// 登出日志
applicationContext.publishEvent(SysLoginEvent(SysLoginLogDTO.loginFail(
user.account ?: "", LoginStateEnum.LOGOUT, request
)))
// 注销登录
StpUtil.logout()
return success(true)
}
/**
* 图形验证码
*
* 说明:
* 限流规则一分钟十次调用
*/
@Limit(name = "验证码接口限流", count = 10, describe = "您的操作过于频繁,请稍后再试")
@ApiOperation(value = "图形验证码")
@GetMapping("/captcha")
fun captcha(): ApiResult<CaptchaResult> {
val key = System.currentTimeMillis()
// 验证码值缓存到redis, 5分钟有效
val specCaptcha = SpecCaptcha(120, 40, 5)
captchaCacheKey.set(key, specCaptcha.text())
return if ("prod" === env) {
// 如果生产环境,不返回验证码的值
success(CaptchaResult(key, specCaptcha.toBase64()))
} else success(CaptchaResult(key, specCaptcha.toBase64(), specCaptcha.text()))
}
}
| 0 | null | 2 | 8 | 8c138e73e864836ddfa5e3eabf05ec05749fda56 | 4,819 | zeta-kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.