path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/hexogen/collections/MutableList.kt
|
MiloszKrajewski
| 69,406,892
| false
| null |
package hexogen.collections
fun <T> MutableList<T>.swap(x: Int, y: Int) {
val t = this[x]
this[x] = this[y]
this[y] = t
}
fun <T> MutableList<T>.shuffle() {
fun random(range: Int) = Math.floor((Math.random() * range) + 1.0)
for (i in size - 1 downTo 0) swap(i, random(i))
}
fun <T> Sequence<T>.shuffled(): Sequence<T> =
this.toMutableList().apply { shuffle() }.asSequence()
| 0
|
Kotlin
|
0
| 1
|
ea163f49d26ef0651fafb28e0271134be9ea535c
| 405
|
kotlinjs-hexagen
|
MIT License
|
src/main/kotlin/hexogen/collections/MutableList.kt
|
MiloszKrajewski
| 69,406,892
| false
| null |
package hexogen.collections
fun <T> MutableList<T>.swap(x: Int, y: Int) {
val t = this[x]
this[x] = this[y]
this[y] = t
}
fun <T> MutableList<T>.shuffle() {
fun random(range: Int) = Math.floor((Math.random() * range) + 1.0)
for (i in size - 1 downTo 0) swap(i, random(i))
}
fun <T> Sequence<T>.shuffled(): Sequence<T> =
this.toMutableList().apply { shuffle() }.asSequence()
| 0
|
Kotlin
|
0
| 1
|
ea163f49d26ef0651fafb28e0271134be9ea535c
| 405
|
kotlinjs-hexagen
|
MIT License
|
src/test/kotlin/no/nav/brukerdialog/ytelse/omsorgspengermidlertidigalene/api/OmsorgspengerMidlertidigAleneControllerTest.kt
|
navikt
| 585,578,757
| false
|
{"Kotlin": 1385043, "Handlebars": 125407, "Dockerfile": 98}
|
package no.nav.brukerdialog.ytelse.omsorgspengermidlertidigalene.api
import com.fasterxml.jackson.databind.ObjectMapper
import com.ninjasquad.springmockk.MockkBean
import io.mockk.coEvery
import io.mockk.every
import no.nav.brukerdialog.domenetjenester.innsending.InnsendingCache
import no.nav.brukerdialog.domenetjenester.innsending.InnsendingService
import no.nav.brukerdialog.metrikk.MetrikkService
import no.nav.brukerdialog.ytelse.Ytelse
import no.nav.brukerdialog.ytelse.fellesdomene.Barn
import no.nav.brukerdialog.ytelse.omsorgspengermidlertidigalene.api.domene.AnnenForelder
import no.nav.brukerdialog.ytelse.omsorgspengermidlertidigalene.api.domene.Situasjon
import no.nav.brukerdialog.config.JacksonConfiguration
import no.nav.brukerdialog.ytelse.omsorgspengermidlertidigalene.utils.SøknadUtils
import no.nav.brukerdialog.integrasjon.k9selvbetjeningoppslag.BarnService
import no.nav.brukerdialog.utils.CallIdGenerator
import no.nav.brukerdialog.utils.NavHeaders
import no.nav.brukerdialog.utils.TokenTestUtils.mockContext
import no.nav.security.token.support.spring.SpringTokenValidationContextHolder
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.context.annotation.Import
import org.springframework.http.MediaType
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.post
import java.time.LocalDate
import java.util.*
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ExtendWith(SpringExtension::class)
@WebMvcTest(controllers = [OmsorgspengerMidlertidigAleneController::class])
@Import(
JacksonConfiguration::class,
CallIdGenerator::class
)
class OmsorgspengerMidlertidigAleneControllerTest {
@Autowired
private lateinit var mockMvc: MockMvc
@Autowired
lateinit var objectMapper: ObjectMapper
@MockkBean
private lateinit var innsendingService: InnsendingService
@MockkBean
private lateinit var innsendingCache: InnsendingCache
@MockkBean
private lateinit var barnService: BarnService
@MockkBean
private lateinit var springTokenValidationContextHolder: SpringTokenValidationContextHolder
@MockkBean
private lateinit var metrikkService: MetrikkService
@BeforeEach
fun setUp() {
springTokenValidationContextHolder.mockContext()
}
@Test
fun `Innsending av søknad er OK`() {
coEvery { barnService.hentBarn() } returns emptyList()
every { innsendingCache.put(any()) } returns Unit
coEvery { innsendingService.registrer(any(), any()) } returns Unit
every { metrikkService.registrerMottattSøknad(any()) } returns Unit
val defaultSøknad = SøknadUtils.defaultSøknad
mockMvc.post("/omsorgspenger-midlertidig-alene/innsending") {
headers {
set(NavHeaders.BRUKERDIALOG_YTELSE, Ytelse.OMSORGSPENGER_MIDLERTIDIG_ALENE.dialog)
set(NavHeaders.BRUKERDIALOG_GIT_SHA, UUID.randomUUID().toString())
}
contentType = MediaType.APPLICATION_JSON
accept = MediaType.APPLICATION_JSON
content = objectMapper.writeValueAsString(defaultSøknad)
}
.andExpect {
status { isAccepted() }
header { exists(NavHeaders.X_CORRELATION_ID) }
}
}
@Test
fun `Innsending av søknad med feile verdier responderer med bad request`() {
val fødselsdatoIFremtiden = LocalDate.now().plusDays(1)
val jsonPayload = objectMapper.writeValueAsString(
SøknadUtils.defaultSøknad.copy(
annenForelder = AnnenForelder(
navn = "",
fnr = "123ABC",
situasjon = Situasjon.SYKDOM,
situasjonBeskrivelse = "",
periodeOver6Måneder = null,
periodeFraOgMed = LocalDate.parse("2020-01-01"),
periodeTilOgMed = null
),
barn = listOf(
Barn(
navn = "",
norskIdentifikator = "123ABC",
aktørId = null,
fødselsdato = fødselsdatoIFremtiden
)
),
harBekreftetOpplysninger = false,
harForståttRettigheterOgPlikter = false
)
)
mockMvc.post("/omsorgspenger-midlertidig-alene/innsending") {
headers {
set(NavHeaders.BRUKERDIALOG_YTELSE, Ytelse.OMSORGSPENGER_MIDLERTIDIG_ALENE.dialog)
set(NavHeaders.BRUKERDIALOG_GIT_SHA, UUID.randomUUID().toString())
}
contentType = MediaType.APPLICATION_JSON
content = jsonPayload.trimIndent()
}
.andExpect {
status { isBadRequest() }
header { exists(NavHeaders.PROBLEM_DETAILS) }
header { exists(NavHeaders.X_CORRELATION_ID) }
content {
json(
"""
{
"type": "/problem-details/invalid-request-parameters",
"instance": "http://localhost/omsorgspenger-midlertidig-alene/innsending",
"title": "invalid-request-parameters",
"status": 400,
"detail": "Forespørselen inneholder valideringsfeil",
"violations": [
{
"invalidValue": "123ABC",
"parameterName": "omsorgspengerMidlertidigAleneSøknad.barn[0].norskIdentifikator",
"parameterType": "ENTITY",
"reason": "size must be between 11 and 11"
},
{
"invalidValue": "123ABC",
"parameterName": "omsorgspengerMidlertidigAleneSøknad.barn[0].norskIdentifikator",
"parameterType": "ENTITY",
"reason": "'123ABC' matcher ikke tillatt pattern '^\\d+$'"
},
{
"parameterName": "omsorgspengerMidlertidigAleneSøknad.barn[0].fødselsdato",
"parameterType": "ENTITY",
"reason": "Kan ikke være i fremtiden"
},
{
"invalidValue": "",
"parameterName": "omsorgspengerMidlertidigAleneSøknad.barn[0].navn",
"parameterType": "ENTITY",
"reason": "Kan ikke være tomt eller blankt"
},
{
"invalidValue": "123ABC",
"parameterName": "omsorgspengerMidlertidigAleneSøknad.annenForelder.fnr",
"parameterType": "ENTITY",
"reason": "size must be between 11 and 11"
},
{
"invalidValue": "123ABC",
"parameterName": "omsorgspengerMidlertidigAleneSøknad.annenForelder.fnr",
"parameterType": "ENTITY",
"reason": "'123ABC' matcher ikke tillatt pattern '^\\d+$'"
},
{
"invalidValue": "",
"parameterName": "omsorgspengerMidlertidigAleneSøknad.annenForelder.navn",
"parameterType": "ENTITY",
"reason": "Kan ikke være tomt eller blankt"
},
{
"parameterName": "omsorgspengerMidlertidigAleneSøknad.annenForelder.situasjonBeskrivelse",
"parameterType": "ENTITY",
"reason": "Derom 'situasjon' er 'SYKDOM', eller 'ANNET' må 'situasjonBeskrivelse' være satt"
},
{
"invalidValue": false,
"parameterName": "omsorgspengerMidlertidigAleneSøknad.annenForelder.situasjon_innlagt_i_helseinstitusjon_sykdom_eller_annet",
"parameterType": "ENTITY",
"reason": "Derom 'situasjon' er 'INNLAGT_I_HELSEINSTITUSJON', 'SYKDOM', eller 'ANNET' må 'periodeTilOgMed' eller 'periodeOver6Måneder' være satt"
},
{
"invalidValue": false,
"parameterName": "omsorgspengerMidlertidigAleneSøknad.harForståttRettigheterOgPlikter",
"parameterType": "ENTITY",
"reason": "Må ha forstått rettigheter og plikter for å sende inn søknad"
},
{
"invalidValue": false,
"parameterName": "omsorgspengerMidlertidigAleneSøknad.harBekreftetOpplysninger",
"parameterType": "ENTITY",
"reason": "Opplysningene må bekreftes for å sende inn søknad"
},
]
}
""".trimIndent(),
false,
)
}
}
}
}
| 2
|
Kotlin
|
0
| 0
|
c8a49d3867ff40fda6bceabe28a736bbec15d048
| 10,053
|
k9-brukerdialog-prosessering
|
MIT License
|
kalexa-core/src/main/kotlin/com/hp/kalexa/core/intent/HelpIntentHandler.kt
|
HPInc
| 164,478,295
| false
| null |
/*
* Copyright 2018 HP Development Company, L.P.
* SPDX-License-Identifier: MIT
*/
package com.hp.kalexa.core.intent
import com.hp.kalexa.core.util.IntentUtil
import com.hp.kalexa.model.request.AlexaRequest
import com.hp.kalexa.model.request.IntentRequest
import com.hp.kalexa.model.response.AlexaResponse
interface HelpIntentHandler : BaseHandler {
/**
* Handles Help Built In Intent coming from Alexa.
*/
fun onHelpIntent(alexaRequest: AlexaRequest<IntentRequest>): AlexaResponse {
return IntentUtil.helpIntent()
}
}
| 0
|
Kotlin
|
1
| 17
|
e6674eeb24c255aef1859a62a65b805effdc9676
| 556
|
kalexa-sdk
|
MIT License
|
app/src/main/java/com/example/myshoppingapp/di/RepositoryModule.kt
|
dororon78
| 582,514,430
| false
|
{"Kotlin": 101283}
|
package com.example.myshoppingapp.di
import com.example.myshoppingapp.data.externalapp.ExternalAppRepositoryImpl
import com.example.myshoppingapp.data.shoppingitem.ShoppingListRepositoryImpl
import com.example.myshoppingapp.domain.repository.ExternalAppRepository
import com.example.myshoppingapp.domain.repository.ShoppingListRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds
@Singleton
abstract fun bindShoppingListRepository(shoppingListRepositoryImpl: ShoppingListRepositoryImpl): ShoppingListRepository
@Binds
@Singleton
abstract fun bindExternalAppRepository(externalAppRepositoryImpl: ExternalAppRepositoryImpl): ExternalAppRepository
}
| 0
|
Kotlin
|
0
| 0
|
ab07623957af5730bd4efec90c9ff9e5af65f2f4
| 867
|
myShoppingApp
|
MIT License
|
app/src/main/java/evtomak/iu/edu/notesapp/NoteDatabase.kt
|
evan2mak
| 702,564,439
| false
|
{"Kotlin": 16101}
|
package evtomak.iu.edu.notesapp
import android.content.Context
import android.util.Log
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
/**
* Room database for storing notes.
*/
@Database(entities = [Note::class], version = 1, exportSchema = false)
abstract class NoteDatabase : RoomDatabase() {
abstract val noteDao: NoteDao
companion object {
// Singleton instance of the database
@Volatile
private var INSTANCE: NoteDatabase? = null
/**
* Get the singleton instance of the database.
*/
fun getInstance(context: Context): NoteDatabase {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
Log.d("NoteDatabase", "Creating new database instance")
instance = Room.databaseBuilder(
context.applicationContext,
NoteDatabase::class.java,
"note_database"
).build()
INSTANCE = instance
Log.d("NoteDatabase", "Database instance created")
}
else {
Log.d("NoteDatabase", "Reusing existing database instance")
}
return instance
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
952399906fec2352e7979bfbc929f08dd704ed4b
| 1,379
|
NotesApp
|
Apache License 2.0
|
core/src/commonMain/kotlin/pro/respawn/flowmvi/plugins/ReducePlugin.kt
|
respawn-app
| 477,143,989
| false
| null |
package pro.respawn.flowmvi.plugins
import pro.respawn.flowmvi.api.FlowMVIDSL
import pro.respawn.flowmvi.api.MVIAction
import pro.respawn.flowmvi.api.MVIIntent
import pro.respawn.flowmvi.api.MVIState
import pro.respawn.flowmvi.api.PipelineContext
import pro.respawn.flowmvi.api.StorePlugin
import pro.respawn.flowmvi.dsl.StoreBuilder
import pro.respawn.flowmvi.dsl.plugin
/**
* Default name for [reducePlugin].
* This is hardcoded so that multiple [reduce] invocations are not allowed w/o
* explicit consent of the user as most often multiple reducers will conflict with each other.
* Provide your own name if you want to have multiple reducers.
*/
public const val ReducePluginName: String = "ReducePlugin"
/**
* An operation that processes incoming [MVIIntent]s
*/
public typealias Reduce<S, I, A> = suspend PipelineContext<S, I, A>.(intent: I) -> Unit
/**
* Create and install a [reducePlugin].
*
* Name is hardcoded because usually multiple reducers are not used.
*
* Provide your own name if you want to have multiple reducers.
*
* Events will be consumed (not passed along the chain of plugins) if [consume] is true (true by default).
*/
@FlowMVIDSL
public inline fun <S : MVIState, I : MVIIntent, A : MVIAction> StoreBuilder<S, I, A>.reduce(
consume: Boolean = true,
name: String = ReducePluginName,
@BuilderInference crossinline reduce: Reduce<S, I, A>,
): Unit = install(reducePlugin(consume, name, reduce))
/**
* Create a new plugin that simply invokes [StorePlugin.onIntent], processes it and does not change the intent.
*
* To change the intent, either create your own [plugin] or use [PipelineContext] to manage the store.
*
* Name is hardcoded because usually multiple reducers are not used.
*
* Provide your own name if you want to have multiple reducers.
*
* Events will be consumed (not passed along the chain of plugins) if [consume] is true (true by default).
**/
@FlowMVIDSL
public inline fun <S : MVIState, I : MVIIntent, A : MVIAction> reducePlugin(
consume: Boolean = true,
name: String = ReducePluginName,
@BuilderInference crossinline reduce: Reduce<S, I, A>,
): StorePlugin<S, I, A> = plugin {
this.name = name
onIntent {
reduce(it)
it.takeUnless { consume }
}
}
| 10
|
Kotlin
|
2
| 75
|
5636ce54d271b1b3d4925011cee739233a36379d
| 2,272
|
FlowMVI
|
Apache License 2.0
|
sdks/kotlin/treasury/ListTransactionsResponseKt.kt
|
knox-networks
| 595,429,463
| false
|
{"Rust": 17246636, "C++": 6138133, "C#": 3083132, "JavaScript": 2183132, "TypeScript": 1665259, "Kotlin": 1249671}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// NO CHECKED-IN PROTOBUF GENCODE
// source: treasury/v1/treasury.proto
// Generated files should ignore deprecation warnings
@file:Suppress("DEPRECATION")
package treasury;
@kotlin.jvm.JvmName("-initializelistTransactionsResponse")
public inline fun listTransactionsResponse(block: treasury.ListTransactionsResponseKt.Dsl.() -> kotlin.Unit): treasury.TreasuryOuterClass.ListTransactionsResponse =
treasury.ListTransactionsResponseKt.Dsl._create(treasury.TreasuryOuterClass.ListTransactionsResponse.newBuilder()).apply { block() }._build()
/**
* ```
* [Example]
* {
* "contracts": [
* {
* "contract_id": "9628a2d9-f932-41f0-b2da-b9de3103d945",
* "contract_type": "Relay",
* "created": "2022-12-19T16:39:57-08:00",
* "counterparties": [
* "zCounterpartyPublicKeyMultibase58Encoded",
* "zCounterpartyPublicKey2Multibase58Encoded"
* ],
* "memo": "Payment"
* }
* ],
* "totalContracts": 1
* }
* ```
*
* Protobuf type `treasury.ListTransactionsResponse`
*/
public object ListTransactionsResponseKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker
public class Dsl private constructor(
private val _builder: treasury.TreasuryOuterClass.ListTransactionsResponse.Builder
) {
public companion object {
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _create(builder: treasury.TreasuryOuterClass.ListTransactionsResponse.Builder): Dsl = Dsl(builder)
}
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _build(): treasury.TreasuryOuterClass.ListTransactionsResponse = _builder.build()
/**
* An uninstantiable, behaviorless type to represent the field in
* generics.
*/
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
public class ContractsProxy private constructor() : com.google.protobuf.kotlin.DslProxy()
/**
* ```
* List of contracts with status metadata
* ```
*
* `repeated .treasury.ContractSummary contracts = 1;`
*/
public val contracts: com.google.protobuf.kotlin.DslList<treasury.TreasuryOuterClass.ContractSummary, ContractsProxy>
@kotlin.jvm.JvmSynthetic
get() = com.google.protobuf.kotlin.DslList(
_builder.getContractsList()
)
/**
* ```
* List of contracts with status metadata
* ```
*
* `repeated .treasury.ContractSummary contracts = 1;`
* @param value The contracts to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addContracts")
public fun com.google.protobuf.kotlin.DslList<treasury.TreasuryOuterClass.ContractSummary, ContractsProxy>.add(value: treasury.TreasuryOuterClass.ContractSummary) {
_builder.addContracts(value)
}
/**
* ```
* List of contracts with status metadata
* ```
*
* `repeated .treasury.ContractSummary contracts = 1;`
* @param value The contracts to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignContracts")
@Suppress("NOTHING_TO_INLINE")
public inline operator fun com.google.protobuf.kotlin.DslList<treasury.TreasuryOuterClass.ContractSummary, ContractsProxy>.plusAssign(value: treasury.TreasuryOuterClass.ContractSummary) {
add(value)
}
/**
* ```
* List of contracts with status metadata
* ```
*
* `repeated .treasury.ContractSummary contracts = 1;`
* @param values The contracts to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addAllContracts")
public fun com.google.protobuf.kotlin.DslList<treasury.TreasuryOuterClass.ContractSummary, ContractsProxy>.addAll(values: kotlin.collections.Iterable<treasury.TreasuryOuterClass.ContractSummary>) {
_builder.addAllContracts(values)
}
/**
* ```
* List of contracts with status metadata
* ```
*
* `repeated .treasury.ContractSummary contracts = 1;`
* @param values The contracts to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignAllContracts")
@Suppress("NOTHING_TO_INLINE")
public inline operator fun com.google.protobuf.kotlin.DslList<treasury.TreasuryOuterClass.ContractSummary, ContractsProxy>.plusAssign(values: kotlin.collections.Iterable<treasury.TreasuryOuterClass.ContractSummary>) {
addAll(values)
}
/**
* ```
* List of contracts with status metadata
* ```
*
* `repeated .treasury.ContractSummary contracts = 1;`
* @param index The index to set the value at.
* @param value The contracts to set.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("setContracts")
public operator fun com.google.protobuf.kotlin.DslList<treasury.TreasuryOuterClass.ContractSummary, ContractsProxy>.set(index: kotlin.Int, value: treasury.TreasuryOuterClass.ContractSummary) {
_builder.setContracts(index, value)
}
/**
* ```
* List of contracts with status metadata
* ```
*
* `repeated .treasury.ContractSummary contracts = 1;`
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("clearContracts")
public fun com.google.protobuf.kotlin.DslList<treasury.TreasuryOuterClass.ContractSummary, ContractsProxy>.clear() {
_builder.clearContracts()
}
/**
* ```
* Total number of contracts in paginated set
* ```
*
* `uint32 totalContracts = 2;`
*/
public var totalContracts: kotlin.Int
@JvmName("getTotalContracts")
get() = _builder.getTotalContracts()
@JvmName("setTotalContracts")
set(value) {
_builder.setTotalContracts(value)
}
/**
* ```
* Total number of contracts in paginated set
* ```
*
* `uint32 totalContracts = 2;`
*/
public fun clearTotalContracts() {
_builder.clearTotalContracts()
}
}
}
@kotlin.jvm.JvmSynthetic
public inline fun treasury.TreasuryOuterClass.ListTransactionsResponse.copy(block: `treasury`.ListTransactionsResponseKt.Dsl.() -> kotlin.Unit): treasury.TreasuryOuterClass.ListTransactionsResponse =
`treasury`.ListTransactionsResponseKt.Dsl._create(this.toBuilder()).apply { block() }._build()
| 0
|
Rust
|
1
| 0
|
16af58a5dc1e9e51859be4a6e0f6791b7adcb2f2
| 6,279
|
grpc-sdks
|
Apache License 2.0
|
educational-core/src/com/jetbrains/edu/learning/codeforces/ChooseCodeforcesContestLanguagesDialog.kt
|
moglideveloper
| 400,282,632
| true
|
{"Kotlin": 3347347, "HTML": 997457, "Java": 551594, "CSS": 12158, "Python": 5553, "JavaScript": 315}
|
package com.jetbrains.edu.learning.codeforces
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.layout.*
import com.intellij.util.ui.JBUI
import com.jetbrains.edu.coursecreator.getDefaultLanguageId
import javax.swing.JCheckBox
import javax.swing.JComponent
// TODO move text of labels to message bundle
class ChooseCodeforcesContestLanguagesDialog(private val contestInformation: ContestInformation) : DialogWrapper(false) {
private val textLanguageComboBox: ComboBox<TaskTextLanguage> = ComboBox()
private val languageComboBox: ComboBox<String> = ComboBox()
private val doNotShowLanguageDialogCheckBox: JCheckBox = JCheckBox("Do not ask if selected languages are available")
private val comboBoxesWidth: Int = JBUI.scale(130)
init {
title = "Choose Contest Languages"
initTextLanguageComboBox()
initLanguageComboBox()
init()
}
override fun createCenterPanel(): JComponent? = panel {
row {
label("Contest: ${contestInformation.name}")
}
row {
row("Language:") {
textLanguageComboBox()
}
row("Programming language:") {
languageComboBox()
}
row {
doNotShowLanguageDialogCheckBox()
}
}
}
override fun getPreferredFocusedComponent(): JComponent? = languageComboBox
fun selectedTaskTextLanguage(): TaskTextLanguage = textLanguageComboBox.selectedItem as TaskTextLanguage
fun selectedLanguage(): String = languageComboBox.selectedItem as String
fun isDoNotShowLanguageDialog(): Boolean = doNotShowLanguageDialogCheckBox.isSelected
private fun initTextLanguageComboBox() {
TaskTextLanguage.values().forEach {
textLanguageComboBox.addItem(it)
}
val preferableTaskTextLanguage = CodeforcesSettings.getInstance().preferableTaskTextLanguage
if (preferableTaskTextLanguage != null && preferableTaskTextLanguage in TaskTextLanguage.values()) {
textLanguageComboBox.selectedItem = preferableTaskTextLanguage
}
textLanguageComboBox.setMinimumAndPreferredWidth(comboBoxesWidth)
}
private fun initLanguageComboBox() {
contestInformation.availableLanguages.sorted().forEach {
languageComboBox.addItem(it)
}
val preferableLanguage = CodeforcesSettings.getInstance().preferableLanguage
if (preferableLanguage != null && preferableLanguage in contestInformation.availableLanguages) {
languageComboBox.selectedItem = preferableLanguage
}
else {
val defaultLanguageId = getDefaultLanguageId()
if (defaultLanguageId != null) {
languageComboBox.selectedItem = CodeforcesLanguageProvider.getPreferableCodeforcesLanguage(defaultLanguageId)
}
}
languageComboBox.setMinimumAndPreferredWidth(comboBoxesWidth)
}
}
| 0
| null |
0
| 0
|
687e434cb8499476729c055d1e947a31491bb999
| 2,790
|
educational-plugin
|
Apache License 2.0
|
src/main/kotlin/com/github/gbrowser/ui/toolwindow/base/toolwindowUtils.kt
|
edgafner
| 294,787,892
| false
|
{"Kotlin": 118488}
|
package com.github.gbrowser.ui.toolwindow.base
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ex.ToolWindowEx
fun ToolWindow.dontHideOnEmptyContent() {
setToHideOnEmptyContent(false)
(this as? ToolWindowEx)?.emptyText?.text = ""
}
| 11
|
Kotlin
|
16
| 59
|
8a36250d6520eddad561b71ea95cdd69d752e0ba
| 262
|
GBrowser
|
Apache License 2.0
|
covithon/Tech-Warriors/android-app/app/src/main/java/com/example/shoptokapplication/response/registration/User.kt
|
joshsoftware
| 271,242,885
| false
|
{"Ruby": 265290, "HTML": 251842, "JavaScript": 221823, "CSS": 129836, "Kotlin": 110240, "Java": 103846, "Objective-C": 3653, "Starlark": 1932, "Dockerfile": 250}
|
package com.example.shoptokapplication.response.registration
data class User(
val created_at: String,
val device_id: String,
val id: Int,
val is_active: Boolean,
val mobile_number: String,
val name: Any,
val role_id: Int,
val updated_at: String
)
| 83
|
Ruby
|
1
| 0
|
a0d3c99ceea9879abbc1180c0e373c9143af935c
| 279
|
Hackathons
|
MIT License
|
libs/pandautils/src/main/java/com/instructure/pandautils/compose/composables/CanvasThemedTextField.kt
|
instructure
| 179,290,947
| false
|
{"Kotlin": 16415961, "Dart": 4454406, "HTML": 185120, "Ruby": 35686, "Java": 24752, "Shell": 19157, "Groovy": 11717, "JavaScript": 9505, "Objective-C": 7431, "Python": 2438, "CSS": 1356, "Swift": 807, "Dockerfile": 112}
|
/*
* Copyright (C) 2024 - present Instructure, 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.instructure.pandautils.compose.composables
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.instructure.pandautils.R
import kotlinx.coroutines.launch
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class)
@Composable
fun CanvasThemedTextField(
value: TextFieldValue,
onValueChange: (TextFieldValue) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
readOnly: Boolean = false,
textStyle: TextStyle = TextStyle.Default.copy(
color = colorResource(R.color.textDarkest),
fontSize = 16.sp,
fontFamily = FontFamily(Font(R.font.lato_font_family)),
),
keyboardOptions: KeyboardOptions = KeyboardOptions.Default.copy(capitalization = KeyboardCapitalization.Sentences),
keyboardActions: KeyboardActions = KeyboardActions.Default,
singleLine: Boolean = false,
maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE,
minLines: Int = 1,
visualTransformation: VisualTransformation = VisualTransformation.None,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
cursorBrush: Brush = SolidColor(colorResource(id = R.color.textDark)),
placeholder: String? = null,
) {
val bringIntoViewRequester = remember { BringIntoViewRequester() }
val coroutineScope = rememberCoroutineScope()
BasicTextField(
value = value,
onValueChange = {
onValueChange(it)
},
modifier = modifier
.bringIntoViewRequester(bringIntoViewRequester),
enabled = enabled,
readOnly = readOnly,
textStyle = textStyle,
keyboardOptions = keyboardOptions,
keyboardActions = keyboardActions,
singleLine = singleLine,
maxLines = maxLines,
minLines = minLines,
visualTransformation = visualTransformation,
onTextLayout = {
val cursorRect = it.getCursorRect(value.selection.start)
coroutineScope.launch {
bringIntoViewRequester.bringIntoView(cursorRect)
}
},
interactionSource = interactionSource,
cursorBrush = cursorBrush,
decorationBox = { innerTextField ->
if (value.text.isEmpty() && placeholder != null) {
Box {
innerTextField()
Text(
placeholder,
color = colorResource(R.color.textDark),
fontSize = 16.sp,
fontFamily = FontFamily(Font(R.font.lato_font_family)),
)
}
} else {
innerTextField()
}
},
)
}
@Composable
@Preview
fun CanvasThemedTextFieldPreview() {
CanvasThemedTextField(
value = TextFieldValue("Some text"),
onValueChange = {},
modifier = Modifier
.fillMaxWidth()
)
}
| 7
|
Kotlin
|
102
| 127
|
ca6e2aeaeedb851003af5497e64c22e02dbf0db8
| 4,869
|
canvas-android
|
Apache License 2.0
|
buildSrc/src/main/kotlin/Versions.kt
|
KakaoCup
| 370,697,938
| false
| null |
import java.io.File
object Versions {
val kakaoVersion = File("buildsystem/version").readText().trim()
val gmapsVersion = File("buildsystem/gmapsversion").readText().trim()
val kotlin = "1.4.32"
val detekt = "1.17.1"
val dokka = "1.4.32"
val android_gradle = "4.2.1"
val maven = "1.5"
val oss = "4.5.4"
val appcompat = "1.3.0"
val recyclerview = "1.2.0"
val viewpager2 = "1.0.0"
val swiperefresh = "1.1.0"
val annotation = "1.2.0"
val design = "1.3.0"
val espresso = "3.3.0"
val espresso_rules = "1.3.0"
val espresso_runner = "1.3.0"
val junit = "4.13.2"
val junit_ext = "1.1.2"
val gradle_versions = "0.39.0"
val google_maps = "17.0.1"
val google_maps_utils = "2.3.0"
}
object Libraries {
val kotlin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}"
val kotlin_stdlib = "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlin}"
val detekt = "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:${Versions.detekt}"
val dokka = "org.jetbrains.dokka:kotlin-as-java-plugin:${Versions.dokka}"
val dokka_gradle = "org.jetbrains.dokka:dokka-gradle-plugin:${Versions.dokka}"
val android_gradle = "com.android.tools.build:gradle:${Versions.android_gradle}"
val maven = "com.github.dcendents:android-maven-gradle-plugin:${Versions.maven}"
val oss = "org.jfrog.buildinfo:build-info-extractor-gradle:${Versions.oss}"
val appcompat = "androidx.appcompat:appcompat:${Versions.appcompat}"
val googleMaps = "com.google.android.gms:play-services-maps:${Versions.google_maps}"
val googleMapsUtils = "com.google.maps.android:maps-utils-ktx:${Versions.google_maps_utils}"
val recyclerview = "androidx.recyclerview:recyclerview:${Versions.recyclerview}"
val viewpager2 = "androidx.viewpager2:viewpager2:${Versions.viewpager2}"
val swiperefresh = "androidx.swiperefreshlayout:swiperefreshlayout:${Versions.swiperefresh}"
val annotation = "androidx.annotation:annotation:${Versions.annotation}"
val design = "com.google.android.material:material:${Versions.design}"
val espresso_runner = "androidx.test:runner:${Versions.espresso_runner}"
val espresso_rules = "androidx.test:rules:${Versions.espresso_rules}"
val espresso_core = "androidx.test.espresso:espresso-core:${Versions.espresso}"
val espresso_web = "androidx.test.espresso:espresso-web:${Versions.espresso}"
val espresso_contrib = "androidx.test.espresso:espresso-contrib:${Versions.espresso}"
val espresso_intents = "androidx.test.espresso:espresso-intents:${Versions.espresso}"
val junit = "junit:junit:${Versions.junit}"
val junit_ext = "androidx.test.ext:junit:${Versions.junit_ext}"
val gradle_versions = "com.github.ben-manes:gradle-versions-plugin:${Versions.gradle_versions}"
}
object Description {
val mavenGroup = "io.github.kakaocup"
}
| 9
| null |
22
| 267
|
0f98ab56a73c664573eedc4ea8968e2899764c36
| 2,891
|
Kakao
|
Apache License 2.0
|
stratix-demo-webapp/src/main/kotlin/com/stratix/demo/AppConfig.kt
|
ReedNewman
| 185,876,789
| false
| null |
package com.stratix.demo
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.DeserializationFeature
import com.mongodb.*
import com.mongodb.client.MongoDatabase
import io.tekniq.config.*
import org.litote.kmongo.*
import org.litote.kmongo.util.KMongoConfiguration
import org.slf4j.Logger
import org.slf4j.LoggerFactory
object AppConfig : TqChainConfig(
TqEnvConfig(),
TqPropertiesConfig("./config.properties", stopOnFailure = false),
TqPropertiesConfig("/etc/stratix-demo/config.properties", stopOnFailure = false),
TqPropertiesConfig("classpath:/config.properties")
) {
private val logger: Logger = LoggerFactory.getLogger(AppConfig.javaClass)
val mongoClient: MongoClient
val mongo: MongoDatabase
val keyPair: RsaKeyPair by lazy {
get("keyPair") ?: CryptoUtil.generateKeyPair(2048)
.also { save("keyPair", it) }
}
init {
KMongoConfiguration.bsonMapper
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
KMongoConfiguration.extendedJsonMapper
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
val mongoUrl = MongoClientURI(get("database.url") ?: "mongodb://localhost/stratix-demo")
logger.info("Establishing connection to $mongoUrl")
mongoClient = KMongo.createClient(mongoUrl)
mongo = mongoClient.getDatabase(mongoUrl.database ?: "stratix-demo")
}
override fun <T : Any?> getValue(key: String, type: Class<T>?): T? {
if (contains(key)) {
return super.getValue(key, type)
}
return mongo.getCollection("config")
.findOneById(key)?.get("value")
?.let {
KMongoConfiguration.extendedJsonMapper.readValue(it.json, type)
}
}
fun <T> save(key: String, value: T) {
if (contains(key)) {
throw IllegalStateException("Cannot change local override of $key")
}
mongo.getCollection<ConfigValue<T>>("config")
.withWriteConcern(WriteConcern.MAJORITY)
.save(ConfigValue(key, value))
}
fun destroy() {
mongoClient.close()
}
}
private data class ConfigValue<out T>(val _id: String, val value: T)
| 1
|
Kotlin
|
0
| 1
|
5f79ec35fba8a44680b709646a89f480cbbe9ade
| 2,543
|
stratix-demo
|
MIT License
|
vector/src/main/java/im/vector/app/features/settings/devices/GetCurrentSessionCrossSigningInfoUseCase.kt
|
tchapgouv
| 340,329,238
| false
| null |
/*
* Copyright (c) 2022 New Vector Ltd
*
* 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 im.vector.app.features.settings.devices
import im.vector.app.core.di.ActiveSessionHolder
import im.vector.app.features.settings.devices.v2.CurrentSessionCrossSigningInfo
import javax.inject.Inject
class GetCurrentSessionCrossSigningInfoUseCase @Inject constructor(
private val activeSessionHolder: ActiveSessionHolder,
) {
fun execute(): CurrentSessionCrossSigningInfo {
val session = activeSessionHolder.getActiveSession()
val isCrossSigningInitialized = session.cryptoService().crossSigningService().isCrossSigningInitialized()
val isCrossSigningVerified = session.cryptoService().crossSigningService().isCrossSigningVerified()
return CurrentSessionCrossSigningInfo(
deviceId = session.sessionParams.deviceId.orEmpty(),
isCrossSigningInitialized = isCrossSigningInitialized,
isCrossSigningVerified = isCrossSigningVerified
)
}
}
| 75
|
Kotlin
|
6
| 9
|
82fea8dbcfe8c29fb318dc55b65d62e0f131c512
| 1,549
|
tchap-android
|
Apache License 2.0
|
src/main/kotlin/ccaominh/Parser.kt
|
ccaominh
| 231,693,312
| false
| null |
/*
* Copyright 2020-2022 <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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ccaominh
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
private const val FILE_NAME_PREFIX = "file://\$PROJECT_DIR\$/"
private val MAPPER: ObjectMapper = XmlMapper(JacksonXmlModule().apply { setDefaultUseWrapper(false) })
.registerKotlinModule()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
@Throws(JsonParseException::class)
fun parseReport(xml: String): Report {
return MAPPER.readValue(xml, Report::class.java)
}
data class Report(
@JsonProperty("problem")
val problems: List<Problem>
) {
fun getSummary(levels: Set<String>): List<String> {
return problems
.filter { p -> p.getSeverity() in levels }
.map { p -> p.getSummary() }
}
}
data class Problem(
val file: String,
val line: Int? = null,
val module: String? = null,
@JacksonXmlProperty(localName = "package")
val packageName: String,
@JacksonXmlProperty(localName = "entry_point")
val entryPoint: EntryPoint,
@JacksonXmlProperty(localName = "problem_class")
val problemClass: ProblemClass,
@JacksonXmlElementWrapper
val hints: List<Hint>? = null, // Jackson deserializes empty list as null: https://git.io/JeCnd
val description: String
) {
fun getSeverity(): String {
return problemClass.severity
}
fun getSummary(): String {
val location = if (line == null) {
entryPoint.fullyQualifiedName
} else {
"${file.substring((FILE_NAME_PREFIX.length))}:${line}"
}
return "[${problemClass.severity}] ${location} -- ${description}"
}
}
data class EntryPoint(
@JacksonXmlProperty(isAttribute = true, localName = "TYPE")
val type: String,
@JacksonXmlProperty(isAttribute = true, localName = "FQNAME")
val fullyQualifiedName: String
)
@JacksonXmlRootElement(localName = "problem_class")
data class ProblemClass(
@JacksonXmlProperty(isAttribute = true)
val severity: String,
@JacksonXmlProperty(isAttribute = true, localName = "attribute_key")
val attributeKey: String
) {
// "lazyinit" is the suggested workaround for jackson-module-kotlin bug with @JacksonXmlText:
// https://github.com/FasterXML/jackson-module-kotlin/issues/138
@JacksonXmlText
lateinit var value: String
private set
constructor(severity: String, attributeKey: String, value: String) : this(severity, attributeKey) {
this.value = value
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ProblemClass
if (severity != other.severity) return false
if (attributeKey != other.attributeKey) return false
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
var result = severity.hashCode()
result = 31 * result + attributeKey.hashCode()
result = 31 * result + value.hashCode()
return result
}
override fun toString(): String {
return "ProblemClass(severity='$severity', attributeKey='$attributeKey', value='$value')"
}
}
@JacksonXmlRootElement(localName = "hint")
data class Hint(
@JacksonXmlProperty(isAttribute = true)
val value: String
)
| 1
|
Kotlin
|
1
| 2
|
f89445144886fe86fe5c8ec744c97312d3ebbc88
| 4,554
|
intellij-inspect
|
Apache License 2.0
|
canvas/src/main/java/com/angcyo/canvas/items/data/DataTextItem.kt
|
angcyo
| 229,037,615
| false
| null |
package com.angcyo.canvas.items.data
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.widget.LinearLayout
import com.angcyo.canvas.Strategy
import com.angcyo.canvas.data.*
import com.angcyo.canvas.graphics.TextGraphicsParser
import com.angcyo.canvas.graphics.lineTextList
import com.angcyo.library.annotation.MM
import com.angcyo.library.annotation.Pixel
import com.angcyo.library.component.FontManager
import com.angcyo.library.ex.*
import com.angcyo.library.unit.toMm
import com.angcyo.library.unit.toPixel
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.tan
/**
* 文本数据item
* @author <a href="mailto:<EMAIL>">angcyo</a>
* @since 2022/09/22
*/
class DataTextItem(bean: CanvasProjectItemBean) : DataItem(bean) {
companion object {
//---
/**字体样式, 无*/
const val TEXT_STYLE_NONE = 0x00
/**字体样式, 加粗*/
const val TEXT_STYLE_BOLD = 0x01
/**字体样式, 斜体*/
const val TEXT_STYLE_ITALIC = 0x02
/**字体样式, 下划线*/
const val TEXT_STYLE_UNDER_LINE = 0x04
/**字体样式, 删除线*/
const val TEXT_STYLE_DELETE_LINE = 0x08
//---
/**斜体的倾斜角度*/
const val ITALIC_SKEW = -0.25f
}
//region ---方法---
/**更新画笔属性*/
fun updatePaint(): Paint {
val loadTypefaceInfo = FontManager.loadTypefaceInfo(dataBean.fontFamily)
val typefaceInfo = loadTypefaceInfo ?: FontManager.getSystemFontList().firstOrNull()
itemPaint.let {
//删除线
it.isStrikeThruText = dataBean.linethrough
//下划线
it.isUnderlineText = dataBean.underline
it.isFakeBoldText = dataBean.isBold()
it.textSkewX = if (dataBean.isItalic()) ITALIC_SKEW else 0f
//it.typeface = item.textTypeface
it.textAlign = dataBean.textAlign.toPaintAlign()
it.style = dataBean.paintStyle.toPaintStyle()
it.textSize = dataBean.fontSize.toPixel()
it.color = dataBean.textColor?.toColor() ?: Color.BLACK
typefaceInfo?.typeface?.let { typeface ->
itemPaint.typeface = typeface
}
}
return itemPaint
}
/**获取当前文本对应的宽高, 像素值*/
@Pixel
fun getTextWidth(text: String = dataBean.text ?: "", paint: Paint = updatePaint()): Float =
calcTextWidth(text, paint)
/**获取当前文本对应的宽高, 像素值*/
@Pixel
fun getTextHeight(text: String = dataBean.text ?: "", paint: Paint = updatePaint()): Float =
calcTextHeight(text, paint)
/**计算多行文本的宽度*/
@Pixel
fun calcTextWidth(text: String, paint: Paint = itemPaint): Float {
var result = 0f
val lineTextList = text.lineTextList()
if (dataBean.orientation == LinearLayout.HORIZONTAL) {
//横向排列
lineTextList.forEach { lineText ->
var lineWidth = 0f
lineText.forEach {
//一个字一个字的宽度
lineWidth += measureTextWidth("$it", paint)
}
lineWidth += dataBean.charSpacing.toPixel() * (lineText.length - 1)
result = max(result, lineWidth)
}
} else {
//纵向排列
lineTextList.forEach { lineText ->
var lineMax = 0f
lineText.forEach {
lineMax = max(measureTextWidth("$it", paint), lineMax)
}
result += lineMax
}
result += dataBean.lineSpacing.toPixel() * (lineTextList.size - 1)
}
return result
}
/**计算多行文本的高度*/
@Pixel
fun calcTextHeight(text: String, paint: Paint = itemPaint): Float {
var result = 0f
val lineTextList = text.lineTextList()
if (dataBean.orientation == LinearLayout.HORIZONTAL) {
//横向排列
lineTextList.forEach { lineText ->
result += measureTextHeight(lineText, paint)
}
result += dataBean.lineSpacing.toPixel() * (lineTextList.size - 1)
} else {
//纵向排列
lineTextList.forEach { lineText ->
var lineHeight = 0f
lineText.forEach {
//一个字一个字的高度
lineHeight += measureTextHeight("$it", paint)
}
lineHeight += dataBean.charSpacing.toPixel() * (lineText.length - 1)
result = max(result, lineHeight)
}
}
return result
}
//temp
val _textMeasureBounds = Rect()
var _skewWidth: Float = 0f
/**单行文本字符的宽度*/
fun measureTextWidth(text: String, paint: Paint = itemPaint): Float {
if (dataBean.isCompactText) {
if (text.isBlank()) {
//空格
val textWidth = paint.textWidth(text).toInt()
_textMeasureBounds.set(0, 0, textWidth, textWidth)
} else {
paint.textBounds(text, _textMeasureBounds)
}
}
val textWidth = if (dataBean.isCompactText) {
_textMeasureBounds.width().toFloat()
} else {
paint.textWidth(text)
}
//画笔的宽度
val paintWidth = paint.strokeWidth
//倾斜的宽度
_skewWidth = if (paint.textSkewX != 0f) {
tan(paint.textSkewX.absoluteValue) * (_textMeasureBounds.height() / 3)
//paint.getTextBounds(drawText ?: "", 0, drawText?.length ?: 0, tempRect)
//(tempRect.width() - width).toInt()
//0f
} else {
0f
}
return textWidth + _skewWidth + paintWidth
}
/**单个文本字符的高度*/
fun measureTextHeight(text: String, paint: Paint = itemPaint): Float {
if (dataBean.isCompactText) {
if (text.isBlank()) {
//空格
val textWidth = paint.textWidth(text).toInt()
_textMeasureBounds.set(0, 0, textWidth, textWidth)
} else {
paint.textBounds(text, _textMeasureBounds)
}
}
return if (dataBean.isCompactText) {
_textMeasureBounds.height().toFloat()
} else {
paint.textHeight()
}
}
/**下沉的距离*/
fun measureTextDescent(text: String, paint: Paint = itemPaint): Float {
return if (dataBean.isCompactText) {
paint.textBounds(text).bottom.toFloat()
} else {
paint.descent()
}
}
//endregion ---方法---
//region ---可恢复的操作---
/**紧凑/宽松文本*/
fun updateTextCompact(
compactText: Boolean,
renderer: DataItemRenderer,
strategy: Strategy = Strategy.normal
) {
val old = dataBean.isCompactText
if (old == compactText) {
return
}
renderer.canvasView.getCanvasUndoManager().addAndRedo(strategy, {
dataBean.isCompactText = old
updateRenderItem(renderer)
}) {
dataBean.isCompactText = compactText
updateRenderItem(renderer)
}
}
/**更新字体*/
fun updateTextTypeface(
typeface: Typeface?,
renderer: DataItemRenderer,
strategy: Strategy = Strategy.normal
) {
val typefaceInfo = if (typeface == null) {
FontManager.getSystemFontList().firstOrNull()
} else {
FontManager.loadTypefaceInfo(typeface)
}
updateTextTypeface(typefaceInfo?.name, renderer, strategy)
}
/**更新字体*/
fun updateTextTypeface(
name: String?,
renderer: DataItemRenderer,
strategy: Strategy = Strategy.normal
) {
val old = dataBean.fontFamily
if (old == name) {
return
}
renderer.canvasView.getCanvasUndoManager().addAndRedo(strategy, {
dataBean.fontFamily = old
updateRenderItem(renderer)
}) {
dataBean.fontFamily = name
updateRenderItem(renderer)
}
}
/**更新文本样式*/
fun updateTextStyle(
style: Int,
enable: Boolean,
renderer: DataItemRenderer,
strategy: Strategy = Strategy.normal
) {
val old = dataBean.textStyle()
val newValue = if (enable) {
old.add(style)
} else {
old.remove(style)
}
if (old == newValue) {
return
}
renderer.canvasView.getCanvasUndoManager().addAndRedo(strategy, {
dataBean.setTextStyle(old)
updateRenderItem(renderer)
}) {
dataBean.setTextStyle(newValue)
updateRenderItem(renderer)
}
}
/**更新画笔绘制文本时的对齐方式*/
fun updatePaintAlign(
align: Paint.Align,
renderer: DataItemRenderer,
strategy: Strategy = Strategy.normal
) {
val old = dataBean.textAlign
val new = align.toAlignString()
if (old == new) {
return
}
renderer.canvasView.getCanvasUndoManager().addAndRedo(strategy, {
dataBean.textAlign = old
updateRenderItem(renderer)
}) {
dataBean.textAlign = new
updateRenderItem(renderer)
}
}
/**更新字体大小*/
fun updateTextSize(
@Pixel
textSize: Float,
renderer: DataItemRenderer,
strategy: Strategy = Strategy.normal
) {
val old = dataBean.fontSize.toPixel()
val new = textSize
if (old == new) {
return
}
@MM
val oldWidth = dataBean.width
val oldHeight = dataBean.height
val oldScaleX = dataBean.scaleX
val oldScaleY = dataBean.scaleY
renderer.canvasView.getCanvasUndoManager().addAndRedo(strategy, {
dataBean.fontSize = old.toMm()
dataBean.width = oldWidth
dataBean.height = oldHeight
dataBean.scaleX = oldScaleX
dataBean.scaleY = oldScaleY
updateRenderItem(renderer)
}) {
dataBean.fontSize = new.toMm()
//清空宽高, 使用文本自身的宽高
dataBean.width = null
dataBean.height = null
dataBean.scaleX = null
dataBean.scaleY = null
updateRenderItem(renderer)
}
}
/**更新字间距*/
fun updateTextWordSpacing(
@Pixel
wordSpacing: Float,
renderer: DataItemRenderer,
strategy: Strategy = Strategy.normal
) {
val old = dataBean.charSpacing.toPixel()
val new = wordSpacing
if (old == new) {
return
}
renderer.canvasView.getCanvasUndoManager().addAndRedo(strategy, {
dataBean.charSpacing = old.toMm()
updateRenderItem(renderer)
}) {
dataBean.charSpacing = new.toMm()
updateRenderItem(renderer)
}
}
/**更新行间距*/
fun updateTextLineSpacing(
@Pixel
lineSpacing: Float,
renderer: DataItemRenderer,
strategy: Strategy = Strategy.normal
) {
val old = dataBean.lineSpacing.toPixel()
val new = lineSpacing
if (old == new) {
return
}
renderer.canvasView.getCanvasUndoManager().addAndRedo(strategy, {
dataBean.lineSpacing = old.toMm()
updateRenderItem(renderer)
}) {
dataBean.lineSpacing = new.toMm()
updateRenderItem(renderer)
}
}
/**更新文本排列方向, 同时改变宽高*/
fun updateTextOrientation(
orientation: Int,
renderer: DataItemRenderer,
strategy: Strategy = Strategy.normal
) {
val old = dataBean.orientation
val new = orientation
if (old == new) {
return
}
val drawText = dataBean.text ?: ""
@MM
val oldWidth = dataBean._width
val oldHeight = dataBean._height
dataBean.orientation = new
@MM
val newWidth = calcTextWidth(drawText).toMm()
val newHeight = calcTextHeight(drawText).toMm()
renderer.canvasView.getCanvasUndoManager().addAndRedo(strategy, {
dataBean.width = oldWidth
dataBean.height = oldHeight
dataBean.orientation = old
updateRenderItem(renderer)
}) {
dataBean.width = newWidth
dataBean.height = newHeight
dataBean.orientation = new
updateRenderItem(renderer)
}
}
/**更新文本*/
fun updateText(
text: String?,
type: Int,
renderer: DataItemRenderer,
strategy: Strategy = Strategy.normal
) {
val oldText = dataBean.text
val oldType = dataBean.mtype
if (oldText == text && oldType == type) {
return
}
@MM
val oldWidth = dataBean.width
val oldHeight = dataBean.height
val oldScaleX = dataBean.scaleX
val oldScaleY = dataBean.scaleY
renderer.canvasView.getCanvasUndoManager().addAndRedo(strategy, {
dataBean.text = oldText
dataBean.mtype = oldType
TextGraphicsParser().updateRotateOffset(this)
dataBean.width = oldWidth
dataBean.height = oldHeight
dataBean.scaleX = oldScaleX
dataBean.scaleY = oldScaleY
updateRenderItem(renderer)
}) {
dataBean.text = text
dataBean.mtype = type
TextGraphicsParser().updateRotateOffset(this)
dataBean.width = null
dataBean.height = null
dataBean.scaleX = null
dataBean.scaleY = null
updateRenderItem(renderer)
}
}
//endregion ---可恢复的操作---
}
| 0
|
Kotlin
|
4
| 3
|
3b120da88d3998d96b229c0773f8bd15604a5dd6
| 13,749
|
UICore
|
MIT License
|
app/src/main/java/app/storytel/candidate/com/repositories/NetworkBoundResource.kt
|
Orofu
| 343,555,172
| false
| null |
package app.storytel.candidate.com.repositories
import androidx.lifecycle.*
import app.storytel.candidate.com.network.Resource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import retrofit2.Response
import java.lang.Exception
import kotlin.coroutines.resume
/**
* This class provides a [LiveData] containing a [Resource] that is backed by both the Room database
* and the network.
*/
abstract class NetworkBoundResource<ResultType, RequestType> {
private val result: LiveData<Resource<ResultType>> = fetchResult()
private fun fetchResult(forceFetch: Boolean = false): LiveData<Resource<ResultType>> {
return liveData(Dispatchers.IO) {
emit(Resource.loading<ResultType>())
val dbSource = loadFromDb().map {
Resource.success(it)
}
val mediator: MediatorLiveData<Resource<ResultType>> = MediatorLiveData()
emitSource(mediator)
val data = withContext(Dispatchers.Main.immediate) {
suspendCancellableCoroutine<ResultType?> { continuation ->
mediator.addSource(dbSource) {
continuation.resume(it.data)
mediator.removeSource(dbSource)
}
continuation.invokeOnCancellation {
mediator.removeSource(dbSource)
}
}
}
if (forceFetch || shouldFetch(data)) {
try {
val response = createCall()
if (response.isSuccessful) {
val body = response.body()
// If the body is empty, or the response code is 204, there is no need
// to save the data to the db since its empty.
if (body != null && response.code() != 204) {
saveCallResult(body)
emitSource(dbSource)
}
} else {
val msg = response.errorBody()?.string()
val errorMsg = if (msg.isNullOrEmpty()) response.message() else msg
emit(Resource.error<ResultType>(errorMsg, data))
}
} catch (e: Exception) {
// TODO: This could be handled better with adding an interceptor to retrofit
// and throw NoNetworkConnection.
onFetchFailed()
emit(Resource.error<ResultType>(e.message ?: e.toString(), data))
}
} else {
emitSource(dbSource)
}
}
}
/**
* Called when fetching the data from the network failed.
*/
protected open fun onFetchFailed() {}
/**
* Returns this [NetworkBoundResource] as a [LiveData].
*/
fun asLiveData() = result
/**
* Saves the result from the network call.
*/
protected abstract fun saveCallResult(item: RequestType)
/**
* Checks if the data should be fetched from the network.
*/
protected abstract fun shouldFetch(data: ResultType?): Boolean
/**
* Loads the data from the database.
*/
protected abstract fun loadFromDb(): LiveData<ResultType>
/**
* Creates the network call to be invoked.
*/
protected abstract suspend fun createCall(): Response<RequestType>
}
| 0
|
Kotlin
|
0
| 0
|
6bb98aaf16bf9bd1b15f5e991341ff324a1e7590
| 3,534
|
StorytelJobCandidate
|
Apache License 2.0
|
intellij-plugin-verifier/verifier-core/src/main/java/com/jetbrains/pluginverifier/verifiers/filter/ApiUsageFilter.kt
|
JetBrains
| 3,686,654
| false
|
{"Kotlin": 2524497, "Java": 253600, "CSS": 1454, "JavaScript": 692}
|
/*
* Copyright 2000-2024 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.jetbrains.pluginverifier.verifiers.filter
import com.jetbrains.pluginverifier.results.reference.ClassReference
import com.jetbrains.pluginverifier.results.reference.FieldReference
import com.jetbrains.pluginverifier.verifiers.VerificationContext
import com.jetbrains.pluginverifier.verifiers.resolution.ClassFile
import com.jetbrains.pluginverifier.verifiers.resolution.ClassFileMember
import com.jetbrains.pluginverifier.verifiers.resolution.ClassUsageType
import com.jetbrains.pluginverifier.verifiers.resolution.Field
import com.jetbrains.pluginverifier.verifiers.resolution.Method
import org.objectweb.asm.tree.AbstractInsnNode
interface ApiUsageFilter {
fun allow(
invokedMethod: Method,
invocationInstruction: AbstractInsnNode,
callerMethod: Method,
context: VerificationContext
): Boolean = false
fun allow(
classReference: ClassReference,
invocationTarget: ClassFile,
caller: ClassFileMember,
usageType: ClassUsageType,
context: VerificationContext
): Boolean = false
fun allow(
fieldReference: FieldReference,
resolvedField: Field,
callerMethod: Method,
context: VerificationContext
): Boolean = false
}
| 6
|
Kotlin
|
38
| 178
|
4deec2e4e08c9ee4ce087697ef80b8b327703548
| 1,366
|
intellij-plugin-verifier
|
Apache License 2.0
|
src/main/kotlin/venus/assembler/pseudos/SLTZ.kt
|
ics-jku
| 470,084,492
| false
| null |
package venus.assembler.pseudos
import venus.assembler.AssemblerPassTwo
import venus.assembler.LineTokens
import venus.assembler.PseudoWriter
/** Writes pseudoinstruction `sltz rd, rs` */
object SLTZ : PseudoWriter() {
override operator fun invoke(args: LineTokens, state: AssemblerPassTwo): List<LineTokens> {
checkArgsLength(args, 3)
return listOf(listOf("slt", args[1], args[2], "x0"))
}
}
| 1
| null |
1
| 4
|
429d323b98a33db67074e44f164c8d1044f406de
| 419
|
venus
|
MIT License
|
app-api/src/main/kotlin/dfialho/yaem/app/api/Transaction.kt
|
dfialho
| 152,736,972
| false
| null |
package dfialho.yaem.app.api
import dfialho.yaem.app.api.serializers.InstantSerializer
import kotlinx.serialization.Serializable
import java.time.Instant
@Serializable
data class Transaction(
val amount: Double,
val receiver: ID,
val sender: ID? = null,
val description: String = "",
@Serializable(with = InstantSerializer::class) val timestamp: Instant = Instant.now(),
val id: ID = randomID()
)
| 2
|
Kotlin
|
0
| 0
|
a9acc5b14a269021be68425abd8350d245728a33
| 423
|
yaem
|
MIT License
|
app/src/main/java/com/example/notesapp/NoteAdapter.kt
|
magacek
| 702,648,551
| false
|
{"Kotlin": 11971}
|
package com.example.notesapp
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
/**
* Adapter for displaying a list of notes in a RecyclerView.
* Provides functionality for clicking on a note title and deleting a note.
*
* @param onTitleClick Callback function for when a note title is clicked.
* @param onDeleteClick Optional callback function for when the delete button of a note is clicked.
*
* @author <NAME>
*/
class NoteAdapter(
private val onTitleClick: (Note) -> Unit,
private val onDeleteClick: ((Note) -> Unit)? = null
) : ListAdapter<Note, NoteAdapter.NoteViewHolder>(NoteDiffCallback()) {
inner class NoteViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
private val titleTextView: TextView = itemView.findViewById(R.id.titleTextView)
private val deleteButton: ImageButton = itemView.findViewById(R.id.deleteButton)
fun bind(note: Note) {
titleTextView.text = note.title
itemView.setOnClickListener { onTitleClick(note) }
deleteButton.setOnClickListener { onDeleteClick?.invoke(note) }
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val view = layoutInflater.inflate(R.layout.note_item, parent, false)
return NoteViewHolder(view)
}
override fun onBindViewHolder(holder: NoteViewHolder, position: Int) {
val note = getItem(position)
holder.bind(note)
}
class NoteDiffCallback : DiffUtil.ItemCallback<Note>() {
override fun areItemsTheSame(oldItem: Note, newItem: Note): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Note, newItem: Note): Boolean {
return oldItem == newItem
}
}
}
| 0
|
Kotlin
|
0
| 0
|
cc5ba11360679865e939069788685657d9c6e3d7
| 2,137
|
NotesApp
|
Apache License 2.0
|
app/src/main/java/com/videochat/presentation/model/UiState.kt
|
atakanozkan
| 850,938,910
| false
|
{"Kotlin": 128837, "Java": 33555}
|
package com.videochat.domain.model
sealed class UiState {
object NoChange : UiState()
object Loading : UiState()
object Success : UiState()
data class Error(val message: String) : UiState()
}
| 0
|
Kotlin
|
0
| 1
|
e3b19616d2d10d395d3ab78895ea1c2cc0ccad58
| 210
|
videochatapp
|
MIT License
|
sample/src/androidTest/java/info/hannes/logcat/ToFileTest.kt
|
AppDevNext
| 172,229,474
| false
| null |
package info.hannes.logcat
import android.Manifest
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import androidx.test.rule.GrantPermissionRule
import com.moka.lib.assertions.MatchOperator
import com.moka.lib.assertions.RecyclerViewItemCountAssertion
import com.moka.utils.Screenshot
import info.hannes.logcat.ui.LogfileActivity
import org.hamcrest.Matchers.allOf
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SdkSuppress(minSdkVersion = 18)
class ToFileTest {
@get:Rule
var mActivityTestRule = ActivityScenarioRule(LogfileActivity::class.java)
@get:Rule
val grantPermissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
@Test
fun logFileBasicTest() {
onView(allOf(withContentDescription("Timber Logfile"),
withParent(withId(info.hannes.logcat.ui.R.id.action_bar)),
isDisplayed()))
val recycler = onView(withId(info.hannes.logcat.ui.R.id.log_recycler))
recycler.check(ViewAssertions.matches(isDisplayed()))
recycler.check(RecyclerViewItemCountAssertion(2, MatchOperator.GREATER_EQUAL))
// Screenshot is too fast. It generates black screens
Thread.sleep(300)
Screenshot.takeScreenshot("End")
}
}
| 4
|
Kotlin
|
2
| 4
|
c79886a62e4821da581aa2da910bfb47e2c1fb4f
| 1,660
|
Logcat
|
Apache License 2.0
|
kanvas/src/commonTest/kotlin/svg/SvgTests.kt
|
JuulLabs
| 202,805,795
| false
| null |
package com.juul.krayon.kanvas.svg
import com.juul.krayon.color.black
import com.juul.krayon.color.blue
import com.juul.krayon.color.green
import com.juul.krayon.color.lime
import com.juul.krayon.color.red
import com.juul.krayon.color.white
import com.juul.krayon.kanvas.Clip
import com.juul.krayon.kanvas.Font
import com.juul.krayon.kanvas.Paint
import com.juul.krayon.kanvas.Paint.Gradient.Stop
import com.juul.krayon.kanvas.Paint.Stroke.Dash.Pattern
import com.juul.krayon.kanvas.serif
import com.juul.krayon.kanvas.withClip
import com.juul.krayon.kanvas.xml.ScientificFormatter
import kotlin.test.Test
import kotlin.test.assertEquals
class SvgTests {
// TODO: Break this up into smaller, distinct tests.
@Test
fun output() {
val expected = """
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1e2 1e2">
<defs>
<linearGradient id="g0" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1e2" y2="1e2">
<stop offset="0%" stop-color="#ffffff" />
<stop offset="100%" stop-color="#000000" />
</linearGradient>
</defs>
<path d="M0,0l100,100h-100z" fill="url(#g0)" />
<defs>
<radialGradient id="g1" gradientUnits="userSpaceOnUse" cx="5e1" cy="5e1" r="7e1">
<stop offset="0%" stop-color="#ffffff" />
<stop offset="100%" stop-color="#000000" />
</radialGradient>
</defs>
<path d="M0,0h100v100z" stroke-dasharray="2 1" stroke-width="1px" stroke="#00ff00" fill="url(#g1)" />
<circle cx="1.6e1" cy="8.4e1" r="8" fill="#000000" />
<defs>
<clipPath id="c0">
<rect x="1.6e1" y="1.6e1" width="6.8e1" height="6.8e1" />
</clipPath>
</defs>
<g clip-path="url(#c0)">
<line x1="0" y1="1e2" x2="1e2" y2="0" stroke-width="2px" stroke="#ff0000" />
</g>
<text x="5e1" y="5e1" text-anchor="middle" font-family=""Times New Roman", serif" font-size="1.6e1px" fill="#0000ff">
Example
</text>
<path d="M -9.18485e-15 0 A 5e1 5e1 0 0 1 5e1 5e1" stroke-width="1px" stroke="#00ff00" fill="#008000" />
<path d="M 5e1 5e1 A 2.5e1 2.5e1 0 0 1 5e1 1e2" stroke-dasharray="2 1" stroke-width="1px" stroke="#00ff00" fill="none" />
</svg>
""".trimIndent()
val actual = run {
val svg = SvgKanvas(width = 100f, height = 100f, ScientificFormatter(precision = 6))
val blackFill = Paint.Fill(black)
val redStroke = Paint.Stroke(red, width = 2f)
val greenFillAndStroke = Paint.FillAndStroke(
Paint.Fill(green),
Paint.Stroke(lime, width = 1f)
)
val dashedGreenStroke = Paint.Stroke(lime, width = 1f, dash = Pattern(2f, 1f))
val linearGradientPaint = Paint.Gradient.Linear(0f, 0f, 100f, 100f, Stop(0f, white), Stop(1f, black))
val radialGradientPaint = Paint.Gradient.Radial(50f, 50f, 70f, Stop(0f, white), Stop(1f, black))
val blueText = Paint.Text(blue, size = 16f, Paint.Text.Alignment.Center, Font("Times New Roman", serif))
svg.drawPath(PathString("M0,0l100,100h-100z"), linearGradientPaint)
svg.drawPath(PathString("M0,0h100v100z"), Paint.GradientAndStroke(radialGradientPaint, dashedGreenStroke))
svg.drawCircle(16f, 84f, 8f, blackFill)
svg.withClip(Clip.Rect(16f, 16f, 84f, 84f)) {
drawLine(0f, 100f, 100f, 0f, redStroke)
}
svg.drawText("Example", 50f, 50f, blueText)
svg.drawArc(-50f, 0f, 50f, 100f, 270f, 90f, greenFillAndStroke) // Quarter circle from top-left to center
svg.drawArc(25f, 50f, 75f, 100f, 270f, 180f, dashedGreenStroke) // Half circle from center to bottom
svg.build()
}
assertEquals(expected, actual)
}
}
| 9
|
Kotlin
|
1
| 8
|
ba3e9d8849d48b67b70422cbcf3e5c7c4bf6e8f6
| 4,071
|
krayon
|
Apache License 2.0
|
app/src/test/java/org/simple/clinic/monthlyreports/list/MonthlyReportsUiRendererTest.kt
|
simpledotorg
| 132,515,649
| false
|
{"Kotlin": 6129044, "Shell": 1660, "HTML": 545}
|
package org.simple.clinic.monthlyreports.list
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoMoreInteractions
import org.junit.Test
import org.simple.sharedTestCode.TestData
import java.util.UUID
class MonthlyReportsUiRendererTest {
private val ui = mock<MonthlyReportsUi>()
private val uiRenderer = MonthlyReportsUiRenderer(ui)
private val defaultModel = MonthlyReportsModel.default()
@Test
fun `when monthly reports is loaded, then render ui`() {
// given
val questionnaireResponse = TestData.questionnaireResponse(
uuid = UUID.fromString("43d8c0b3-3341-4147-9a08-aac27e7f721f")
)
val model = defaultModel
.monthlyReportsLoaded(listOf(questionnaireResponse))
// when
uiRenderer.render(model)
// then
verify(ui).displayMonthlyReports(listOf(questionnaireResponse))
verifyNoMoreInteractions(ui)
}
@Test
fun `when current facility loaded, then set facility title`() {
// given
val facility = TestData.facility(
uuid = UUID.fromString("d05d20cf-858b-432a-a312-f402681e56b3"),
name = "PHC Simple"
)
val model = defaultModel
.currentFacilityLoaded(facility)
// when
uiRenderer.render(model)
// then
verify(ui).setFacility(facility.name)
verifyNoMoreInteractions(ui)
}
}
| 4
|
Kotlin
|
73
| 236
|
ff699800fbe1bea2ed0492df484777e583c53714
| 1,359
|
simple-android
|
MIT License
|
NFC-EMV-Adaptor/src/test/java/com/github/shham12/nfc_emv_adaptor/iso7816emv/parser/IssuerPublicKeyDecoderTest.kt
|
SHHam12
| 814,926,240
| false
|
{"Kotlin": 170269, "Java": 6264}
|
package com.github.shham12.nfc_emv_adaptor.iso7816emv.parser
import com.github.shham12.nfc_emv_adaptor.iso7816emv.impl.CaPublicKey
import com.github.shham12.nfc_emv_adaptor.iso7816emv.model.EMVTransactionRecord
import com.github.shham12.nfc_emv_adaptor.parser.IssuerPublicKeyDecoder
import com.github.shham12.nfc_emv_adaptor.util.BytesUtils.bytesToString
import com.github.shham12.nfc_emv_adaptor.util.BytesUtils.toByteArray
import org.junit.Assert.*
import org.junit.Test
class IssuerPublicKeyDecoderTest {
@Test
fun testRetrievalIssuerPublicKey() {
// Sample data
val emvRecord = EMVTransactionRecord()
emvRecord.addEMVTagValue("90", ("20DF7FF4B9968169B50DABED606B2FA12A0A26ED0A9791F5FE16965AC3A3AC60924B" +
"A722A7EA668D40C79A7A8F519949A2E7059CCD4685C16465084A47AA71192ABEF7D45AAE2513501D81BA" +
"150A6C533B02026C275888DA3E2D62C1554ED49BC9BECABF24387B1BDE7A06E9861B6CC0F0DACCC00139" +
"3D4E4CB976EBB3C2FC0165D4A32C0CB99BD8549B8295026620D028204524ACED3379558490450D21B6A0" +
"62204FAF5160FE24CF5AC5F2D9B20533").toByteArray())
emvRecord.addEMVTagValue("92", "8FC44EE8B5ECB266790274EEF50A9F6BD598C58C444508E6DF9AB7A5028DE7DEB5DA6BDB".toByteArray())
emvRecord.addEMVTagValue("9F32", "03".toByteArray())
emvRecord.addEMVTagValue("5A", "374245002751005F".toByteArray())
emvRecord.addEMVTagValue("82", "19C0".toByteArray())
val caPublicKey = CaPublicKey(
rid = "A000000025",
index = "C9",
exponent = "03",
modulus = "B362DB5733C15B8797B8ECEE55CB1A371F760E0BEDD3715BB270424FD4EA26062C38C3F4AAA3732A83D36EA8E9602F6683EECC6BAFF63DD2D49014BDE4D6D603CD744206B05B4BAD0C64C63AB3976B5C8CAAF8539549F5921C0B700D5B0F83C4E7E946068BAAAB5463544DB18C63801118F2182EFCC8A1E85E53C2A7AE839A5C6A3CABE73762B70D170AB64AFC6CA482944902611FB0061E09A67ACB77E493D998A0CCF93D81A4F6C0DC6B7DF22E62DB"
)
// Execute
val result = IssuerPublicKeyDecoder.retrievalIssuerPublicKeyModulus(emvRecord, caPublicKey)
// Validate
assertNotNull(result)
// Add more assertions as needed to validate the returned result
val issuerPublicKeyModulus = "CAFACCC90D61D0469BFE90FB93EC91CFC778A4BAB22377D361D7FA536D85AB3D8546B26CE145A096462BF08247773FDAA4818D5B90789A4DFDDC148D520AA75C3775E4F2E0CD240536FDF05E90DD0C6CB2EC25B85B4480F64B6852C7B71D152C461D18E25571FE6C2069840EFBCDEF880F7EF8B0FB7C3E2B89C95F003F977A337B82C10EFF4E27A55A757C628FC44EE8B5ECB266790274EEF50A9F6BD598C58C444508E6DF9AB7A5028DE7DEB5DA6BDB"
assertEquals(issuerPublicKeyModulus, bytesToString(result).uppercase())
}
}
| 0
|
Kotlin
|
2
| 5
|
982c0d0ba7a3e7ce910142b9fb2ce9c8ce6b618d
| 2,687
|
NFC-EMV-Adaptor
|
MIT License
|
src/commonTest/kotlin/org/angproj/aux/pipe/PullBinaryTest.kt
|
angelos-project
| 677,039,667
| false
|
{"Kotlin": 1007119, "Python": 196308}
|
/**
* Copyright (c) 2024 by <NAME> <<EMAIL>>.
*
* This software is available under the terms of the MIT license. Parts are licensed
* under different terms if stated. The legal terms are attached to the LICENSE file
* and are made available on:
*
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*
* Contributors:
* <NAME> - initial implementation
*/
package org.angproj.aux.pipe
import org.angproj.aux.io.DataSize
import org.angproj.aux.io.PumpReader
import org.angproj.aux.io.Segment
import org.angproj.aux.io.TypeSize
import org.angproj.aux.mem.Default
import org.angproj.aux.utf.writeGlyphAt
import org.angproj.aux.util.Reify
import org.angproj.aux.util.chunkLoop
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertFailsWith
import kotlin.time.measureTime
class BinaryReader(private val half: Boolean = false) : PumpReader {
override fun read(data: Segment): Int {
//if(half) if (this.data.remaining < (this.data.size / 2)) data.limit /= 2
var index = chunkLoop<Reify>(0, data.limit, TypeSize.long) {
data.setLong(it, Random.nextLong())
}
index = chunkLoop<Reify>(index, data.limit, TypeSize.byte) {
data.setByte(it, Random.nextInt().toByte())
}
return index
}
}
class PullBinaryTest {
/**
* The goal is to pull all data from the TextSource.
* */
@Test
fun testStreamPull() {
val readable = PullPipe<BinaryType>(
Default,
PumpSource(BinaryReader()),
DataSize._1K,
DataSize._1K
).getSink()
var count = 0
readable.readByte()
val time = measureTime {
do {
val cp = readable.readLong()
count += 8
} while(count < 3000)
}
println(time)
//assertContentEquals(copy, canvas)
//assertFailsWith<UnsupportedOperationException> { readable.readGlyph() }
TODO("Make correctly.")
}
@Test
fun testStreamPullClose() {
val text = latinLL + greekLL + chineseLL
val copy = text.encodeToByteArray()
val canvas = ByteArray(copy.size)
var pos = 0
val readable = Pipe.buildTextPullPipe(StringReader(text)) // PullPipe(Default, PumpSource<TextType>(StringReader(text))).getSink()
do {
val cp = readable.readGlyph()
pos += canvas.writeGlyphAt(pos, cp)
} while(pos < canvas.size / 2)
readable.close()
assertFailsWith<UnsupportedOperationException> { readable.readGlyph() }
TODO("Make correctly.")
}
}
| 0
|
Kotlin
|
0
| 0
|
b8102e24b565edc0adbd459a68d7e2e08e46669c
| 2,667
|
angelos-project-aux
|
MIT License
|
sample/wallet/src/main/kotlin/com/reown/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalViewModel.kt
|
reown-com
| 851,466,242
| false
|
{"Kotlin": 2055654, "Java": 4294, "Shell": 1676}
|
package com.reown.sample.wallet.ui.routes.dialog_routes.session_proposal
import androidx.lifecycle.ViewModel
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.ktx.Firebase
import com.reown.sample.wallet.domain.WCDelegate
import com.reown.sample.wallet.ui.common.peer.PeerUI
import com.reown.sample.wallet.ui.common.peer.toPeerUI
import com.reown.walletkit.client.Wallet
import com.reown.walletkit.client.WalletKit
import timber.log.Timber
class SessionProposalViewModel : ViewModel() {
val sessionProposal: SessionProposalUI? = generateSessionProposalUI()
fun approve(proposalPublicKey: String, onSuccess: (String) -> Unit = {}, onError: (Throwable) -> Unit = {}) {
val proposal = WalletKit.getSessionProposals().find { it.proposerPublicKey == proposalPublicKey }
if (proposal != null) {
try {
Timber.d("Approving session proposal: $proposalPublicKey")
val sessionNamespaces = WalletKit.generateApprovedNamespaces(sessionProposal = proposal, supportedNamespaces = walletMetaData.namespaces)
val approveProposal = Wallet.Params.SessionApprove(proposerPublicKey = proposal.proposerPublicKey, namespaces = sessionNamespaces)
WalletKit.approveSession(approveProposal,
onError = { error ->
Firebase.crashlytics.recordException(error.throwable)
WCDelegate.sessionProposalEvent = null
onError(error.throwable)
},
onSuccess = {
WCDelegate.sessionProposalEvent = null
onSuccess(proposal.redirect)
})
} catch (e: Exception) {
Firebase.crashlytics.recordException(e)
WCDelegate.sessionProposalEvent = null
onError(e)
}
} else {
onError(Throwable("Cannot approve session proposal, it has expired. Please try again."))
}
}
fun reject(proposalPublicKey: String, onSuccess: (String) -> Unit = {}, onError: (Throwable) -> Unit = {}) {
val proposal = WalletKit.getSessionProposals().find { it.proposerPublicKey == proposalPublicKey }
if (proposal != null) {
try {
val rejectionReason = "Reject Session"
val reject = Wallet.Params.SessionReject(
proposerPublicKey = proposal.proposerPublicKey,
reason = rejectionReason
)
WalletKit.rejectSession(reject,
onSuccess = {
WCDelegate.sessionProposalEvent = null
onSuccess(proposal.redirect)
},
onError = { error ->
Firebase.crashlytics.recordException(error.throwable)
WCDelegate.sessionProposalEvent = null
onError(error.throwable)
})
} catch (e: Exception) {
Firebase.crashlytics.recordException(e)
WCDelegate.sessionProposalEvent = null
onError(e)
}
} else {
onError(Throwable("Cannot reject session proposal, it has expired. Please try again."))
}
}
private fun generateSessionProposalUI(): SessionProposalUI? {
return if (WCDelegate.sessionProposalEvent != null) {
val (proposal, context) = WCDelegate.sessionProposalEvent!!
SessionProposalUI(
peerUI = PeerUI(
peerIcon = proposal.icons.firstOrNull().toString(),
peerName = proposal.name,
peerDescription = proposal.description,
peerUri = proposal.url,
),
namespaces = proposal.requiredNamespaces,
optionalNamespaces = proposal.optionalNamespaces,
peerContext = context.toPeerUI(),
redirect = proposal.redirect,
pubKey = proposal.proposerPublicKey
)
} else null
}
}
| 6
|
Kotlin
|
1
| 8
|
893084b3df91b47daa77f8f964e37f84a02843b1
| 4,180
|
reown-kotlin
|
Apache License 2.0
|
schema-kenerator-reflection/src/main/kotlin/io/github/smiley4/schemakenerator/reflection/steps.kt
|
SMILEY4
| 729,430,513
| false
|
{"Kotlin": 478582}
|
package io.github.smiley4.schemakenerator.reflection
import io.github.smiley4.schemakenerator.core.data.BaseTypeData
import io.github.smiley4.schemakenerator.core.data.Bundle
import io.github.smiley4.schemakenerator.core.data.PrimitiveTypeData
import io.github.smiley4.schemakenerator.core.data.PropertyType
import io.github.smiley4.schemakenerator.reflection.data.EnumConstType
import io.github.smiley4.schemakenerator.reflection.steps.ReflectionAnnotationSubTypeStep
import io.github.smiley4.schemakenerator.reflection.steps.ReflectionTypeProcessingStep
import io.github.smiley4.schemakenerator.reflection.steps.ReflectionTypeProcessingStep.Companion.DEFAULT_PRIMITIVE_TYPES
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.typeOf
/**
* See [ReflectionAnnotationSubTypeStep]
*/
fun KType.collectSubTypes(maxRecursionDepth: Int = 10): Bundle<KType> {
return ReflectionAnnotationSubTypeStep(
maxRecursionDepth = maxRecursionDepth
).process(this)
}
class ReflectionTypeProcessingStepConfig {
internal var customProcessors = mutableMapOf<KClass<*>, () -> BaseTypeData>()
/**
* Whether to include getters as members of classes (see [PropertyType.GETTER]).
*/
var includeGetters: Boolean = false
/**
* Whether to include weak getters as members of classes (see [PropertyType.WEAK_GETTER]).
*/
var includeWeakGetters: Boolean = false
/**
* Whether to include functions as members of classes (see [PropertyType.FUNCTION]).
*/
var includeFunctions: Boolean = false
/**
* Whether to include hidden (e.g. private) members
*/
var includeHidden: Boolean = false
/**
* Whether to include static members
*/
var includeStatic: Boolean = false
/**
* The list of types that are considered "primitive types" and returned as [PrimitiveTypeData]
*/
var primitiveTypes: Collection<KClass<*>> = DEFAULT_PRIMITIVE_TYPES
/**
* Whether to use toString for enum values or the declared name
*/
var enumConstType: EnumConstType = EnumConstType.NAME
/**
* Add a custom processor for the given type that overwrites the default behaviour
*/
fun customProcessor(type: KClass<*>, processor: () -> BaseTypeData) {
customProcessors[type] = processor
}
/**
* Add a custom processor for the given type that overwrites the default behaviour
*/
inline fun <reified T> customProcessor(noinline processor: () -> BaseTypeData) {
customProcessor(typeOf<T>().classifier!! as KClass<*>, processor)
}
/**
* Add custom processors for given type that overwrites the default behaviour
*/
fun customProcessors(processors: Map<KClass<*>, () -> BaseTypeData>) {
customProcessors.putAll(processors)
}
}
/**
* See [ReflectionTypeProcessingStep]
*/
fun KType.processReflection(configBlock: ReflectionTypeProcessingStepConfig.() -> Unit = {}): Bundle<BaseTypeData> {
val config = ReflectionTypeProcessingStepConfig().apply(configBlock)
return ReflectionTypeProcessingStep(
includeGetters = config.includeGetters,
includeWeakGetters = config.includeWeakGetters,
includeFunctions = config.includeFunctions,
includeHidden = config.includeHidden,
includeStatic = config.includeStatic,
primitiveTypes = config.primitiveTypes,
customProcessors = config.customProcessors,
enumConstType = config.enumConstType
).process(this)
}
/**
* See [ReflectionTypeProcessingStep]
*/
fun Bundle<KType>.processReflection(configBlock: ReflectionTypeProcessingStepConfig.() -> Unit = {}): Bundle<BaseTypeData> {
val config = ReflectionTypeProcessingStepConfig().apply(configBlock)
return ReflectionTypeProcessingStep(
includeGetters = config.includeGetters,
includeWeakGetters = config.includeWeakGetters,
includeFunctions = config.includeFunctions,
includeHidden = config.includeHidden,
includeStatic = config.includeStatic,
primitiveTypes = config.primitiveTypes,
customProcessors = config.customProcessors,
enumConstType = config.enumConstType
).process(this)
}
| 0
|
Kotlin
|
0
| 0
|
d141cdeeaeca34165bf8302cae69054f3f9dd2da
| 4,241
|
schema-kenerator
|
Apache License 2.0
|
src/main/kotlin/io/demo/paymentsystem/dao/mapper/UserMapper.kt
|
AnkBurov
| 183,963,890
| false
| null |
package io.demo.paymentsystem.dao.mapper
import io.demo.paymentsystem.api.User
import org.jdbi.v3.core.mapper.RowMapper
import org.jdbi.v3.core.statement.StatementContext
import java.sql.ResultSet
object UserMapper : RowMapper<User> {
override fun map(rs: ResultSet, ctx: StatementContext): User {
return User(id = rs.getLong("USER.ID"),
firstName = rs.getString("USER.FIRST_NAME"),
lastName = rs.getString("USER.LAST_NAME")
)
}
}
| 0
|
Kotlin
|
0
| 0
|
e8da12a5ab60b29478d7c694dbd3ad627c2b2592
| 488
|
yet-another-payment-system
|
Apache License 2.0
|
plugins/package-search/maven/src/com/jetbrains/packagesearch/intellij/plugin/maven/MavenPackageVersionRangeInspection.kt
|
ingokegel
| 72,937,917
| true
| null |
/*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.maven
import com.intellij.psi.PsiFile
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyDeclarationIndexes
import com.jetbrains.packagesearch.intellij.plugin.extensibility.PackageUpdateInspection
import org.jetbrains.idea.maven.utils.MavenUtil
internal class MavenPackageUpdateInspection : PackageUpdateInspection() {
override fun getStaticDescription(): String = PackageSearchBundle.message("packagesearch.inspection.upgrade.description.maven")
override fun selectPsiElementIndex(dependencyDeclarationIndexes: DependencyDeclarationIndexes): Int? {
return dependencyDeclarationIndexes.versionStartIndex
}
override fun shouldCheckFile(file: PsiFile) = MavenUtil.isPomFile(file.project, file.virtualFile)
}
| 214
| null |
4829
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 1,657
|
intellij-community
|
Apache License 2.0
|
app/src/tv/kotlin/app/newproj/lbrytv/ui/guidance/GuidedStepSupportFragment.kt
|
linimin
| 434,503,024
| false
| null |
/*
* MIT License
*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package app.newproj.lbrytv.ui.guidance
import androidx.annotation.IdRes
import androidx.leanback.app.GuidedStepSupportFragment
import androidx.leanback.widget.GuidedAction
fun GuidedStepSupportFragment.updateAction(id: Long, update: (GuidedAction) -> Unit) {
findActionById(id)?.let {
update(it)
notifyActionChanged(findActionPositionById(id))
}
}
fun GuidedStepSupportFragment.updateAction(@IdRes id: Int, update: (GuidedAction) -> Unit) {
updateAction(id.toLong(), update)
}
fun GuidedStepSupportFragment.updateButtonAction(id: Long, update: (GuidedAction) -> Unit) {
findButtonActionById(id)?.let {
update(it)
notifyButtonActionChanged(findButtonActionPositionById(id))
}
}
fun GuidedStepSupportFragment.updateButtonAction(@IdRes id: Int, update: (GuidedAction) -> Unit) {
updateButtonAction(id.toLong(), update)
}
fun GuidedStepSupportFragment.findSubActionById(subActionId: Long): GuidedAction? =
actions.flatMap { it.subActions ?: emptyList() }.find { it.id == subActionId }
fun GuidedStepSupportFragment.findSubActionById(@IdRes subActionId: Int): GuidedAction? =
findSubActionById(subActionId.toLong())
fun GuidedStepSupportFragment.findSubActionById(
parentActionId: Long,
subActionId: Long,
): GuidedAction? =
findActionById(parentActionId)?.subActions?.find { it.id == subActionId }
fun GuidedStepSupportFragment.findSubActionById(
@IdRes parentActionId: Int,
@IdRes subActionId: Int,
): GuidedAction? = findSubActionById(parentActionId.toLong(), subActionId.toLong())
fun GuidedStepSupportFragment.findActionById(@IdRes id: Int): GuidedAction? =
findActionById(id.toLong())
fun GuidedAction.Builder.id(@IdRes id: Int): GuidedAction.Builder = id(id.toLong())
| 7
|
Kotlin
|
3
| 23
|
75bed7e7bae0b1ddaa2b5356b82dbec62c25776e
| 2,899
|
lbry-androidtv
|
MIT License
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/ssm/CfnMaintenanceWindowTaskLoggingInfoPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION")
package cloudshift.awscdk.dsl.services.ssm
import cloudshift.awscdk.common.CdkDslMarker
import software.amazon.awscdk.services.ssm.CfnMaintenanceWindowTask
import kotlin.String
/**
* The `LoggingInfo` property type specifies information about the Amazon S3 bucket to write
* instance-level logs to.
*
* `LoggingInfo` is a property of the
* [AWS::SSM::MaintenanceWindowTask](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html)
* resource.
*
*
* `LoggingInfo` has been deprecated. To specify an Amazon S3 bucket to contain logs, instead use
* the `OutputS3BucketName` and `OutputS3KeyPrefix` options in the `TaskInvocationParameters`
* structure. For information about how Systems Manager handles these options for the supported
* maintenance window task types, see [AWS ::SSM::MaintenanceWindowTask
* MaintenanceWindowRunCommandParameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.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.ssm.*;
* LoggingInfoProperty loggingInfoProperty = LoggingInfoProperty.builder()
* .region("region")
* .s3Bucket("s3Bucket")
* // the properties below are optional
* .s3Prefix("s3Prefix")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-logginginfo.html)
*/
@CdkDslMarker
public class CfnMaintenanceWindowTaskLoggingInfoPropertyDsl {
private val cdkBuilder: CfnMaintenanceWindowTask.LoggingInfoProperty.Builder =
CfnMaintenanceWindowTask.LoggingInfoProperty.builder()
/**
* @param region The AWS Region where the S3 bucket is located.
*/
public fun region(region: String) {
cdkBuilder.region(region)
}
/**
* @param s3Bucket The name of an S3 bucket where execution logs are stored.
*/
public fun s3Bucket(s3Bucket: String) {
cdkBuilder.s3Bucket(s3Bucket)
}
/**
* @param s3Prefix The Amazon S3 bucket subfolder.
*/
public fun s3Prefix(s3Prefix: String) {
cdkBuilder.s3Prefix(s3Prefix)
}
public fun build(): CfnMaintenanceWindowTask.LoggingInfoProperty = cdkBuilder.build()
}
| 1
|
Kotlin
|
0
| 0
|
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 2,627
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
android/beagle/src/test/java/br/com/zup/beagle/engine/renderer/ui/ListViewRendererTest.kt
|
thosantunes
| 269,216,984
| true
|
{"Kotlin": 1067509, "Swift": 638142, "C++": 262909, "Objective-C": 58562, "Java": 26545, "Ruby": 17188, "Shell": 1780, "C": 1109}
|
/*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 br.com.zup.beagle.engine.renderer.ui
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import br.com.zup.beagle.BaseTest
import br.com.zup.beagle.engine.renderer.RootView
import br.com.zup.beagle.view.BeagleFlexView
import br.com.zup.beagle.view.ViewFactory
import br.com.zup.beagle.widget.ui.ListDirection
import br.com.zup.beagle.widget.ui.ListView
import io.mockk.Runs
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.just
import io.mockk.slot
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class ListViewRendererTest : BaseTest() {
@MockK
private lateinit var context: Context
@MockK
private lateinit var rootView: RootView
@MockK
private lateinit var viewFactory: ViewFactory
@MockK
private lateinit var widget: ListView
@MockK
private lateinit var recyclerView: RecyclerView
@MockK
private lateinit var beagleFlexView: BeagleFlexView
private val layoutManagerSlot = slot<LinearLayoutManager>()
private lateinit var listViewRenderer: ListViewRenderer
override fun setUp() {
super.setUp()
listViewRenderer = ListViewRenderer(widget, viewFactory)
every { beagleFlexView.addView(any()) } just Runs
every { viewFactory.makeRecyclerView(context) } returns recyclerView
every { recyclerView.layoutManager = capture(layoutManagerSlot) } just Runs
every { recyclerView.adapter = any() } just Runs
every { widget.direction } returns ListDirection.VERTICAL
every { widget.rows } returns listOf()
every { rootView.getContext() } returns context
every { recyclerView.context } returns context
}
@Test
fun build_should_return_a_BeagleFlexView_instance() {
val view = listViewRenderer.build(rootView)
assertTrue(view is RecyclerView)
}
@Test
fun build_should_set_orientation_VERTICAL() {
// Given
every { widget.direction } returns ListDirection.VERTICAL
// When
listViewRenderer.build(rootView)
// Then
assertEquals(RecyclerView.VERTICAL, layoutManagerSlot.captured.orientation)
}
@Test
fun build_should_set_orientation_HORIZONTAL() {
// Given
every { widget.direction } returns ListDirection.HORIZONTAL
// When
listViewRenderer.build(rootView)
// Then
assertEquals(RecyclerView.HORIZONTAL, layoutManagerSlot.captured.orientation)
}
}
| 0
| null |
0
| 1
|
046531e96d0384ae2917b0fd790f09d1a8142912
| 3,225
|
beagle
|
Apache License 2.0
|
src/test/kotlin/no/nav/familie/ef/iverksett/økonomi/UtbetalingsoppdragGeneratorTest.kt
|
navikt
| 357,821,728
| false
| null |
package no.nav.familie.ef.iverksett.økonomi
import no.nav.familie.ef.iverksett.iverksetting.domene.AndelTilkjentYtelse
import no.nav.familie.ef.iverksett.iverksetting.domene.TilkjentYtelse
import no.nav.familie.ef.iverksett.iverksetting.domene.TilkjentYtelseMedMetaData
import no.nav.familie.ef.iverksett.økonomi.utbetalingsoppdrag.UtbetalingsoppdragGenerator.lagTilkjentYtelseMedUtbetalingsoppdrag
import no.nav.familie.kontrakter.ef.felles.StønadType
import no.nav.familie.kontrakter.ef.felles.TilkjentYtelseStatus
import no.nav.familie.kontrakter.ef.iverksett.Periodetype
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.catchThrowable
import org.junit.jupiter.api.Test
import org.opentest4j.AssertionFailedError
import org.opentest4j.ValueWrapper
import java.time.LocalDate
import java.util.UUID
internal class UtbetalingsoppdragGeneratorTest {
@Test
fun csvTest() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/Sekvens1.csv"))
}
@Test
fun `Revurdering med 0 beløp beholder periodId til neste behandling med periode med beløp`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/revurdering_med_0beløp.csv"))
}
@Test
fun `Revurdering med 0 beløp beholder periodId når man har flere perioder`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/revurdering_med_0beløp_flere_perioder.csv"))
}
@Test
fun `Førstegangsbehandling med 0 i beløp, med revurderinger med 0 i beløp`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/førstegangsbehandling_med_0beløp_revurderinger_med_0beløp.csv"))
}
@Test
fun `Har en periode og får en endring mitt i perioden`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/1_periode_får_en_endring_i_perioden.csv"))
}
@Test
fun `Har to perioder og får en endring i første perioden`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/2_perioder_får_en_endring_i_første_perioden.csv"))
}
@Test
fun `Har to perioder og får en endring som har startdato før første perioden`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/2_perioder_får_ny_periode_før_første_periode.csv"))
}
@Test
fun `Har to perioder og får en endring for start og sluttdatot i andre perioden`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/2_perioder_får_en_endring_i_andre_perioden.csv"))
}
@Test
fun `Har tre perioder og får en endring i første perioden`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/3_perioder_får_en_endring_i_første_perioden.csv"))
}
@Test
fun `Har tre perioder og får en endring i andre perioden`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/3_perioder_får_en_endring_i_andre_perioden.csv"))
}
@Test
fun `Har en perioder, legger til en ny periode som er lik den forrige`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/1_periode_får_en_lik_periode.csv"))
}
@Test
fun `Har en perioder, legger til en andre`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/1_periode_får_en_ny_perioden.csv"))
}
@Test
fun `Har to perioder, legger til en tredje, endrer på den andre`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/2_perioder_får_ny_periode_og_endring_i_andre_perioden.csv"))
}
@Test
fun `Har en periode og får ett opphør`() {
TestOppdragRunner.run(javaClass.getResource("/oppdrag/1_periode_får_ett_opphør.csv"))
}
@Test
fun `Har 2 perioder og får en endring på andre perioden men har feil behandlingId i testen`() {
val catchThrowable = catchThrowable {
TestOppdragRunner.run(javaClass.getResource(
"/oppdrag/2_periode_får_en_endring_i_andre_perioden_feiler_pga_feil_behandling_id.csv"))
}
assertThat(catchThrowable)
.hasMessageContaining("Feiler for gruppe med indeks 1 ==> ")
.isInstanceOf(AssertionFailedError::class.java)
assertExpectedOgActualErLikeUtenomFeltSomFeiler(catchThrowable, "kildeBehandlingId")
}
@Test
fun `Har 2 perioder og får en endring på andre perioden men har feil periodeId i testen`() {
val catchThrowable = catchThrowable {
TestOppdragRunner.run(javaClass.getResource(
"/oppdrag/2_periode_får_en_endring_i_andre_perioden_feiler_pga_feil_periode_id.csv"))
}
assertThat(catchThrowable)
.hasMessageContaining("Feiler for gruppe med indeks 1 ==> ")
.isInstanceOf(AssertionFailedError::class.java)
assertExpectedOgActualErLikeUtenomFeltSomFeiler(catchThrowable, "periodeId")
}
@Test
fun `Andeler med behandlingId, periodeId og forrigePeriodeId blir oppdaterte i lagTilkjentYtelseMedUtbetalingsoppdrag`() {
val behandlingA = UUID.randomUUID()
val behandlingB = UUID.randomUUID()
val andel1 = opprettAndel(2,
LocalDate.of(2020, 1, 1),
LocalDate.of(2020, 12, 31)) // endres ikke, beholder kildeBehandlingId
val andel2 = opprettAndel(2, LocalDate.of(2021, 1, 1), LocalDate.of(2021, 12, 31)) // endres i behandling b
val andel3 = opprettAndel(2, LocalDate.of(2022, 1, 1), LocalDate.of(2022, 12, 31)) // ny i behandling b
val førsteTilkjentYtelse =
lagTilkjentYtelseMedUtbetalingsoppdrag(opprettTilkjentYtelseMedMetadata(behandlingA, andel1, andel2))
assertFørsteBehandling(førsteTilkjentYtelse, behandlingA)
val nyePerioder = opprettTilkjentYtelseMedMetadata(behandlingB,
andel1,
andel2.copy(tilOgMed = andel2.tilOgMed.minusMonths(2)),
andel3)
val utbetalingsoppdragB = lagTilkjentYtelseMedUtbetalingsoppdrag(nyePerioder, førsteTilkjentYtelse)
assertThatAndreBehandlingIkkeEndrerPåKildeBehandlingIdPåAndel1(utbetalingsoppdragB, behandlingA, behandlingB)
}
private fun assertExpectedOgActualErLikeUtenomFeltSomFeiler(catchThrowable: Throwable?,
feltSomSkalFiltreres: String) {
val assertionFailedError = catchThrowable as AssertionFailedError
val actual = filterAwayBehandlingId(assertionFailedError.actual, feltSomSkalFiltreres)
val expected = filterAwayBehandlingId(assertionFailedError.expected, feltSomSkalFiltreres)
assertThat(actual).isEqualTo(expected)
}
private fun filterAwayBehandlingId(valueWrapper: ValueWrapper, feltSomSkalFiltreres: String) =
valueWrapper.stringRepresentation
.split("\n")
.filterNot { it.contains(feltSomSkalFiltreres) }
.joinToString("\n")
private fun assertThatAndreBehandlingIkkeEndrerPåKildeBehandlingIdPåAndel1(utbetalingsoppdragB: TilkjentYtelse,
behandlingA: UUID?,
behandlingB: UUID?) {
assertAndel(andelTilkjentYtelse = utbetalingsoppdragB.andelerTilkjentYtelse[0],
expectedPeriodeId = 1,
expectedForrigePeriodeId = null,
expectedKildeBehandlingId = behandlingA)
assertAndel(andelTilkjentYtelse = utbetalingsoppdragB.andelerTilkjentYtelse[1],
expectedPeriodeId = 3,
expectedForrigePeriodeId = 2,
expectedKildeBehandlingId = behandlingB)
assertAndel(andelTilkjentYtelse = utbetalingsoppdragB.andelerTilkjentYtelse[2],
expectedPeriodeId = 4,
expectedForrigePeriodeId = 3,
expectedKildeBehandlingId = behandlingB)
}
private fun assertFørsteBehandling(førsteTilkjentYtelse: TilkjentYtelse,
behandlingA: UUID?) {
assertAndel(andelTilkjentYtelse = førsteTilkjentYtelse.andelerTilkjentYtelse[0],
expectedPeriodeId = 1,
expectedForrigePeriodeId = null,
expectedKildeBehandlingId = behandlingA)
assertAndel(andelTilkjentYtelse = førsteTilkjentYtelse.andelerTilkjentYtelse[1],
expectedPeriodeId = 2,
expectedForrigePeriodeId = 1,
expectedKildeBehandlingId = behandlingA)
}
private fun assertAndel(andelTilkjentYtelse: AndelTilkjentYtelse,
expectedPeriodeId: Long?,
expectedForrigePeriodeId: Long?,
expectedKildeBehandlingId: UUID?) {
assertThat(andelTilkjentYtelse.periodeId).isEqualTo(expectedPeriodeId)
assertThat(andelTilkjentYtelse.forrigePeriodeId).isEqualTo(expectedForrigePeriodeId)
assertThat(andelTilkjentYtelse.kildeBehandlingId).isEqualTo(expectedKildeBehandlingId)
}
private fun opprettAndel(beløp: Int, stønadFom: LocalDate, stønadTom: LocalDate) =
lagAndelTilkjentYtelse(beløp = beløp,
periodetype = Periodetype.MÅNED,
fraOgMed = stønadFom,
tilOgMed = stønadTom,
periodeId = 100, // overskreves
forrigePeriodeId = 100, // overskreves
kildeBehandlingId = UUID.randomUUID()) // overskreves
private fun opprettTilkjentYtelseMedMetadata(behandlingId: UUID,
vararg andelTilkjentYtelse: AndelTilkjentYtelse) =
TilkjentYtelseMedMetaData(tilkjentYtelse = TilkjentYtelse(id = UUID.randomUUID(),
utbetalingsoppdrag = null,
status = TilkjentYtelseStatus.OPPRETTET,
andelerTilkjentYtelse = andelTilkjentYtelse.toList()),
personIdent = "1",
behandlingId = behandlingId,
eksternBehandlingId = 1,
stønadstype = StønadType.OVERGANGSSTØNAD,
eksternFagsakId = 1,
saksbehandlerId = "VL",
vedtaksdato = LocalDate.of(2021, 5, 12)
)
}
| 12
|
Kotlin
|
0
| 0
|
9785e50dc2f1dbc65ef4ab60e23282504f7a85b0
| 10,859
|
familie-ef-iverksett
|
MIT License
|
src/test/enhetstester/kotlin/no/nav/familie/ba/sak/kjerne/beregning/BeregningTestUtils.kt
|
navikt
| 224,639,942
| false
| null |
package no.nav.familie.ba.sak.kjerne.beregning
import no.nav.familie.kontrakter.felles.oppdrag.Opphør
import no.nav.familie.kontrakter.felles.oppdrag.Utbetalingsoppdrag
import no.nav.familie.kontrakter.felles.oppdrag.Utbetalingsperiode
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.UUID
fun lagTestUtbetalingsoppdragForFGBMedToBarn(
personIdent: String,
fagsakId: String,
behandlingId: Long,
vedtakDato: LocalDate,
datoFomBarn1: LocalDate,
datoFomBarn2: LocalDate,
datoTomBarn1: LocalDate,
datoTomBarn2: LocalDate,
): Utbetalingsoppdrag {
return Utbetalingsoppdrag(
Utbetalingsoppdrag.KodeEndring.NY,
"BA",
fagsakId,
UUID.randomUUID().toString(),
"SAKSBEHANDLERID",
LocalDateTime.now(),
listOf(
Utbetalingsperiode(
false,
null,
1,
null,
vedtakDato,
"BATR",
datoFomBarn1,
datoTomBarn1,
BigDecimal(1054),
Utbetalingsperiode.SatsType.MND,
personIdent,
behandlingId,
),
Utbetalingsperiode(
false,
null,
2,
null,
vedtakDato,
"BATR",
datoFomBarn2,
datoTomBarn2,
BigDecimal(1054),
Utbetalingsperiode.SatsType.MND,
personIdent,
behandlingId,
),
),
)
}
fun lagTestUtbetalingsoppdragForOpphørMedToBarn(
personIdent: String,
fagsakId: String,
behandlingId: Long,
vedtakDato: LocalDate,
datoFomBarn1: LocalDate,
datoFomBarn2: LocalDate,
datoTomBarn1: LocalDate,
datoTomBarn2: LocalDate,
opphørFom: LocalDate,
): Utbetalingsoppdrag {
return Utbetalingsoppdrag(
Utbetalingsoppdrag.KodeEndring.NY,
"BA",
fagsakId,
UUID.randomUUID().toString(),
"SAKSBEHANDLERID",
LocalDateTime.now(),
listOf(
Utbetalingsperiode(
true,
Opphør(opphørFom),
1,
null,
vedtakDato,
"BATR",
datoFomBarn1,
datoTomBarn1,
BigDecimal(1054),
Utbetalingsperiode.SatsType.MND,
personIdent,
behandlingId,
),
Utbetalingsperiode(
true,
Opphør(opphørFom),
2,
null,
vedtakDato,
"BATR",
datoFomBarn2,
datoTomBarn2,
BigDecimal(1054),
Utbetalingsperiode.SatsType.MND,
personIdent,
behandlingId,
),
),
)
}
fun lagTestUtbetalingsoppdragForRevurderingMedToBarn(
personIdent: String,
fagsakId: String,
behandlingId: Long,
forrigeBehandlingId: Long,
vedtakDato: LocalDate,
opphørFomBarn1: LocalDate,
revurderingFomBarn1: LocalDate,
datoFomBarn1: LocalDate,
datoTomBarn1: LocalDate,
opphørFomBarn2: LocalDate,
revurderingFomBarn2: LocalDate,
datoFomBarn2: LocalDate,
datoTomBarn2: LocalDate,
): Utbetalingsoppdrag {
return Utbetalingsoppdrag(
Utbetalingsoppdrag.KodeEndring.NY,
"BA",
fagsakId,
UUID.randomUUID().toString(),
"SAKSBEHANDLERID",
LocalDateTime.now(),
listOf(
Utbetalingsperiode(
true,
Opphør(opphørFomBarn1),
1,
null,
vedtakDato,
"BATR",
datoFomBarn1,
datoTomBarn1,
BigDecimal(1054),
Utbetalingsperiode.SatsType.MND,
personIdent,
forrigeBehandlingId,
),
Utbetalingsperiode(
false,
null,
3,
1,
vedtakDato,
"BATR",
revurderingFomBarn1,
datoTomBarn1,
BigDecimal(1054),
Utbetalingsperiode.SatsType.MND,
personIdent,
behandlingId,
),
Utbetalingsperiode(
true,
Opphør(opphørFomBarn2),
2,
null,
vedtakDato,
"BATR",
datoFomBarn2,
datoTomBarn2,
BigDecimal(1054),
Utbetalingsperiode.SatsType.MND,
personIdent,
forrigeBehandlingId,
),
Utbetalingsperiode(
false,
null,
4,
2,
vedtakDato,
"BATR",
revurderingFomBarn2,
datoTomBarn2,
BigDecimal(1054),
Utbetalingsperiode.SatsType.MND,
personIdent,
behandlingId,
),
),
)
}
| 8
|
Kotlin
|
1
| 9
|
7b881e34cc5c5b689a407ca62e922efacf983520
| 5,283
|
familie-ba-sak
|
MIT License
|
app/src/main/java/com/study/riseof/shopkotlin/activity/BaseActivity.kt
|
MyAndroidProjects
| 175,351,219
| false
| null |
package com.study.riseof.shopkotlin.activity
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import android.view.WindowManager
abstract class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(getActivityLayout())
setActionBar()
getValuesFromIntent()
getValuesFromSaveInstanceState(savedInstanceState)
}
override fun onStart() {
super.onStart()
setStatusBarColor()
setPresenterAndNavigationManager()
setClickListeners()
}
override fun onStop() {
nullifyPresenterAndNavigationManager()
super.onStop()
}
protected abstract fun getActivityLayout(): Int
protected abstract fun nullifyPresenterAndNavigationManager()
protected abstract fun setClickListeners()
protected abstract fun setPresenterAndNavigationManager()
protected abstract fun getValuesFromIntent()
protected abstract fun getValuesFromSaveInstanceState(savedInstanceState: Bundle?)
protected abstract fun getToolbarView(): Toolbar
protected abstract fun menuButtonHomeSelected()
private fun setActionBar() {
setSupportActionBar(getToolbarView())
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(com.study.riseof.shopkotlin.R.drawable.ic_baseline_menu_24px)
}
private fun setStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val window = this.window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
@Suppress("DEPRECATION")
window.statusBarColor = resources.getColor(com.study.riseof.shopkotlin.R.color.status_bar)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
menuButtonHomeSelected()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
| 0
|
Kotlin
|
0
| 0
|
4157bd92b6c755213ab2754a71ba24e269ce5c2b
| 2,228
|
ShopKotlin
|
MIT License
|
app/src/main/java/com/eyther/lumbridge/usecase/user/mortgage/SaveUserMortgage.kt
|
ruialmeida51
| 249,223,684
| false
|
{"Kotlin": 687400}
|
package com.eyther.lumbridge.usecase.user.mortgage
import com.eyther.lumbridge.domain.repository.user.UserRepository
import com.eyther.lumbridge.mapper.user.toDomain
import com.eyther.lumbridge.model.user.UserMortgageUi
import javax.inject.Inject
class SaveUserMortgage @Inject constructor(
private val userRepository: UserRepository
) {
suspend operator fun invoke(userMortgageUi: UserMortgageUi) =
userRepository.saveUserMortgage(userMortgageUi.toDomain())
}
| 8
|
Kotlin
|
0
| 7
|
8e35f83c34e4b29eae1b048d3fda6aaa81b04858
| 479
|
lumbridge-android
|
MIT License
|
domain/src/main/java/com/eyther/lumbridge/domain/repository/shopping/ShoppingRepository.kt
|
ruialmeida51
| 249,223,684
| false
|
{"Kotlin": 904675}
|
package com.eyther.lumbridge.domain.repository.shopping
import com.eyther.lumbridge.data.datasource.shopping.local.ShoppingLocalDataSource
import com.eyther.lumbridge.domain.mapper.shopping.toCached
import com.eyther.lumbridge.domain.mapper.shopping.toDomain
import com.eyther.lumbridge.domain.model.shopping.ShoppingList
import com.eyther.lumbridge.shared.di.model.Schedulers
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.withContext
import javax.inject.Inject
class ShoppingRepository @Inject constructor(
private val shoppingLocalDataSource: ShoppingLocalDataSource,
private val schedulers: Schedulers
) {
val shoppingListFlow = shoppingLocalDataSource
.shoppingListFlow
.mapNotNull { it.toDomain() }
suspend fun saveShoppingList(shoppingList: ShoppingList) = withContext(schedulers.io) {
shoppingLocalDataSource.saveShoppingList(shoppingList.toCached())
}
suspend fun deleteShoppingListById(shoppingList: Long) = withContext(schedulers.io) {
shoppingLocalDataSource.deleteShoppingListById(shoppingList)
}
suspend fun getShoppingListById(shoppingList: Long): ShoppingList? = withContext(schedulers.io) {
shoppingLocalDataSource.getShoppingListById(shoppingList)?.toDomain()
}
}
| 6
|
Kotlin
|
0
| 7
|
5dd18b22448b2435f0238cccfc11a6826f200748
| 1,284
|
lumbridge-android
|
MIT License
|
common/collection/src/test/kotlin/com/curtislb/adventofcode/common/collection/MinAndMaxTest.kt
|
curtislb
| 226,797,689
| false
| null |
package com.curtislb.adventofcode.common.collection
import kotlin.math.abs
import kotlin.test.assertEquals
import kotlin.test.assertNull
import org.junit.jupiter.api.Test
/**
* Tests [minAndMaxByOrNull] and [minAndMaxOfOrNull].
*/
class MinAndMaxTest {
@Test
fun testMinAndMaxByOrNull() {
assertNull(emptyList<Int>().minAndMaxByOrNull { it })
assertEquals(MinMax(0, 0), listOf(0).minAndMaxByOrNull { it })
assertEquals(MinMax(5, 5), listOf(5).minAndMaxByOrNull { it })
assertEquals(MinMax(5, 5), listOf(5).minAndMaxByOrNull { -it })
assertEquals(MinMax(-1, -1), listOf(-1).minAndMaxByOrNull { it })
assertEquals(MinMax(-1, -1), listOf(-1).minAndMaxByOrNull { it * 2 })
assertEquals(MinMax(1, 2), listOf(1, 2).minAndMaxByOrNull { it })
assertEquals(MinMax(2, 1), listOf(1, 2).minAndMaxByOrNull { -it })
assertEquals(
MinMax(-76, 29),
listOf(29, 7, -76, -58, -17).minAndMaxByOrNull { it }
)
assertEquals(
MinMax(7, -76),
listOf(29, 7, -76, -58, -17).minAndMaxByOrNull { abs(it) }
)
assertEquals(
MinMax(-76, -17),
listOf(29, 7, -76, -58, -17).minAndMaxByOrNull { element ->
if (element > 0) element - 50 else element
}
)
}
@Test
fun testMinAndMaxOfOrNull() {
assertNull(emptyList<Int>().minAndMaxOfOrNull { it })
assertEquals(MinMax(0, 0), listOf(0).minAndMaxOfOrNull { it })
assertEquals(MinMax(5, 5), listOf(5).minAndMaxOfOrNull { it })
assertEquals(MinMax(-5, -5), listOf(5).minAndMaxOfOrNull { -it })
assertEquals(MinMax(-1, -1), listOf(-1).minAndMaxOfOrNull { it })
assertEquals(MinMax(-2, -2), listOf(-1).minAndMaxOfOrNull { it * 2 })
assertEquals(MinMax(1, 2), listOf(1, 2).minAndMaxOfOrNull { it })
assertEquals(MinMax(-2, -1), listOf(1, 2).minAndMaxOfOrNull { -it })
assertEquals(MinMax(-76, 29), listOf(29, 7, -76, -58, -17).minAndMaxOfOrNull { it })
assertEquals(
MinMax(7, 76),
listOf(29, 7, -76, -58, -17).minAndMaxOfOrNull { abs(it) }
)
assertEquals(
MinMax(-26, 33),
listOf(29, 7, -76, -58, -17).minAndMaxOfOrNull { element ->
if (element < 0) element + 50 else element
}
)
}
}
| 0
|
Kotlin
|
1
| 1
|
e9ef1f42e245d730edeb0ebec57de515992d84e5
| 2,412
|
AdventOfCode
|
MIT License
|
services/hanke-service/src/test/kotlin/fi/hel/haitaton/hanke/factory/ApplicationAttachmentFactory.kt
|
City-of-Helsinki
| 300,534,352
| false
|
{"Kotlin": 1358730, "Python": 61622, "Mustache": 60127, "Shell": 26923, "Batchfile": 5169, "Dockerfile": 967, "PLpgSQL": 555}
|
package fi.hel.haitaton.hanke.factory
import fi.hel.haitaton.hanke.attachment.DUMMY_DATA
import fi.hel.haitaton.hanke.attachment.USERNAME
import fi.hel.haitaton.hanke.attachment.application.ApplicationAttachmentContentService
import fi.hel.haitaton.hanke.attachment.common.ApplicationAttachmentEntity
import fi.hel.haitaton.hanke.attachment.common.ApplicationAttachmentMetadata
import fi.hel.haitaton.hanke.attachment.common.ApplicationAttachmentRepository
import fi.hel.haitaton.hanke.attachment.common.ApplicationAttachmentType
import fi.hel.haitaton.hanke.attachment.common.ApplicationAttachmentType.MUU
import fi.hel.haitaton.hanke.attachment.common.AttachmentContent
import fi.hel.haitaton.hanke.currentUserId
import java.time.OffsetDateTime
import java.util.UUID
import org.springframework.http.MediaType.APPLICATION_PDF_VALUE
import org.springframework.stereotype.Component
@Component
class ApplicationAttachmentFactory(
private val applicationAttachmentRepository: ApplicationAttachmentRepository,
private val attachmentContentService: ApplicationAttachmentContentService,
) {
fun saveAttachment(applicationId: Long): ApplicationAttachmentEntity {
val attachment =
applicationAttachmentRepository.save(createEntity(applicationId = applicationId))
attachmentContentService.save(attachment.id!!, DUMMY_DATA)
return attachment
}
companion object {
val defaultAttachmentId: UUID = UUID.fromString("5cba3a76-28ad-42aa-b7e6-b5c1775be81a")
val CREATED_AT: OffsetDateTime = OffsetDateTime.parse("2023-11-09T10:03:55+02:00")
const val FILE_NAME = "file.pdf"
fun createEntity(
id: UUID = defaultAttachmentId,
fileName: String = FILE_NAME,
contentType: String = APPLICATION_PDF_VALUE,
blobLocation: String? = null,
createdByUserId: String = USERNAME,
createdAt: OffsetDateTime = CREATED_AT,
attachmentType: ApplicationAttachmentType = MUU,
applicationId: Long,
): ApplicationAttachmentEntity =
ApplicationAttachmentEntity(
id = id,
fileName = fileName,
contentType = contentType,
blobLocation = blobLocation,
createdByUserId = createdByUserId,
createdAt = createdAt,
attachmentType = attachmentType,
applicationId = applicationId,
)
fun createMetadata(
attachmentId: UUID = defaultAttachmentId,
fileName: String = FILE_NAME,
createdBy: String = currentUserId(),
createdAt: OffsetDateTime = OffsetDateTime.now(),
applicationId: Long = 1L,
attachmentType: ApplicationAttachmentType = MUU,
): ApplicationAttachmentMetadata =
ApplicationAttachmentMetadata(
id = attachmentId,
fileName = fileName,
createdByUserId = createdBy,
createdAt = createdAt,
applicationId = applicationId,
attachmentType = attachmentType
)
fun createContent(
fileName: String = FILE_NAME,
contentType: String = APPLICATION_PDF_VALUE,
bytes: ByteArray = DUMMY_DATA,
) = AttachmentContent(fileName = fileName, contentType = contentType, bytes = bytes)
}
}
| 12
|
Kotlin
|
5
| 3
|
05499819c5fceb1f7b2616886a2abbf18f36a5dc
| 3,436
|
haitaton-backend
|
MIT License
|
ocpi-toolkit-2.2.1/src/main/kotlin/com/izivia/ocpi/toolkit/modules/cdr/domain/SignedData.kt
|
IZIVIA
| 497,830,391
| false
| null |
package com.izivia.ocpi.toolkit.modules.cdr.domain
import com.izivia.ocpi.toolkit.annotations.Partial
import com.izivia.ocpi.toolkit.common.CiString
/**
* This class contains all the information of the signed data. Which encoding method is used, if needed, the public key and a list of
signed values.
* @property encodingMethod The name of the encoding used in the SignedData field. This is the
name given to the encoding by a company or group of companies. See
note below.
* @property encodingMethodVersion Version of the EncodingMethod (when applicable)
* @property publicKey Public key used to sign the data, base64 encoded.
* @property signedValues One or more signed values.
* @property url URL that can be shown to an EV driver. This URL gives the EV driver
the possibility to check the signed data from a charging session.
*/
@Partial
data class SignedData(
val encodingMethod: CiString,
val encodingMethodVersion: Int? = null,
val publicKey: CiString? = null,
val signedValues: List<SignedValue>,
val url: CiString? = null
)
| 19
| null |
8
| 24
|
8e9f7a873242046bad248bce6c0d9296e02999dc
| 1,063
|
ocpi-toolkit
|
MIT License
|
crunchycalendar/src/main/java/ru/cleverpumpkin/calendar/extension/ContextExtenison.kt
|
CleverPumpkin
| 134,849,459
| false
|
{"Kotlin": 141160}
|
package ru.cleverpumpkin.calendar.extension
import android.content.Context
import android.util.TypedValue
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.annotation.AnimRes
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
fun Context.spToPix(spValue: Float): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, resources.displayMetrics)
}
fun Context.dpToPix(dpValue: Float): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, resources.displayMetrics)
}
@ColorInt
fun Context.getColorInt(@ColorRes colorRes: Int): Int {
return ContextCompat.getColor(this, colorRes)
}
fun Context.loadAnim(@AnimRes animResId: Int): Animation {
return AnimationUtils.loadAnimation(this, animResId)
}
| 14
|
Kotlin
|
45
| 610
|
8da96a51863a2b03490e86638131289209361482
| 876
|
CrunchyCalendar
|
MIT License
|
Chapter3/app/src/androidTest/java/com/favedish/testing/assertion/ViewWaiter.kt
|
bpbpublications
| 533,628,168
| false
| null |
package com.favedish.testing.assertion
import android.view.View
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.IdlingResourceTimeoutException
import androidx.test.espresso.matcher.ViewMatchers.isRoot
import com.favedish.testing.action.NoAction
import com.favedish.testing.idlingresource.ViewIdlingResource
import org.hamcrest.Matcher
import org.junit.Assert.fail
fun waitForViews(timeoutMilliseconds: Long = 60L, vararg viewMatchers: Matcher<View>) {
val viewIdlingResource =
ViewIdlingResource(viewMatchers = viewMatchers, timeoutMilliseconds = timeoutMilliseconds)
val idlingRegistry = IdlingRegistry.getInstance()
idlingRegistry.register(viewIdlingResource)
try {
onView(isRoot()).perform(NoAction())
} catch (timeout: IdlingResourceTimeoutException) {
fail("Waiting for views timed out.")
} finally {
idlingRegistry.unregister(viewIdlingResource)
}
}
| 0
|
Kotlin
|
5
| 7
|
cd85b9fb89e307ad4977bcdb63121aa906f19427
| 992
|
Clean-Architecture-for-Android
|
MIT License
|
compose/ui/ui-test-junit4/src/desktopMain/kotlin/androidx/compose/ui/test/ComposeTest.desktop.kt
|
JetBrains
| 351,708,598
| false
| null |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test
import androidx.compose.runtime.Composable
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.ui.ComposeScene
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.node.RootForTest
import androidx.compose.ui.platform.InfiniteAnimationPolicy
import androidx.compose.ui.semantics.SemanticsNode
import androidx.compose.ui.test.junit4.MainTestClockImpl
import androidx.compose.ui.test.junit4.UncaughtExceptionHandler
import androidx.compose.ui.test.junit4.isOnUiThread
import androidx.compose.ui.text.input.EditCommand
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.yield
import kotlin.coroutines.cancellation.CancellationException
import org.jetbrains.skia.Surface
@ExperimentalTestApi
@OptIn(InternalTestApi::class)
actual fun runComposeUiTest(effectContext: CoroutineContext, block: ComposeUiTest.() -> Unit) {
DesktopComposeUiTest(effectContext).runTest(block)
}
/**
* @param effectContext The [CoroutineContext] used to run the composition. The context for
* `LaunchedEffect`s and `rememberCoroutineScope` will be derived from this context.
*/
@InternalTestApi
@ExperimentalTestApi
@OptIn(ExperimentalComposeUiApi::class, ExperimentalCoroutinesApi::class)
class DesktopComposeUiTest(
effectContext: CoroutineContext = EmptyCoroutineContext
) : ComposeUiTest {
override val density = Density(1f, 1f)
private val coroutineDispatcher = UnconfinedTestDispatcher()
private val testScope = TestScope(coroutineDispatcher)
override val mainClock: MainTestClock =
MainTestClockImpl(coroutineDispatcher.scheduler, frameDelayMillis = 16L)
private val uncaughtExceptionHandler = UncaughtExceptionHandler()
private val infiniteAnimationPolicy = object : InfiniteAnimationPolicy {
override suspend fun <R> onInfiniteOperation(block: suspend () -> R): R {
if (mainClock.autoAdvance) {
throw CancellationException("Infinite animations are disabled on tests")
}
return block()
}
}
private val coroutineContext =
effectContext +
coroutineDispatcher +
uncaughtExceptionHandler +
infiniteAnimationPolicy
private val surface = Surface.makeRasterN32Premul(1024, 768)
lateinit var scene: ComposeScene
private val testOwner = DesktopTestOwner()
private val testContext = createTestContext(testOwner)
fun <R> runTest(block: ComposeUiTest.() -> R): R {
scene = runOnUiThread(::createUi)
try {
return block()
} finally {
// call runTest instead of deprecated cleanupTestCoroutines()
testScope.runTest { }
runOnUiThread(scene::close)
uncaughtExceptionHandler.throwUncaught()
}
}
private fun renderNextFrame() = runOnUiThread {
scene.render(
surface.canvas,
mainClock.currentTime * 1_000_000
)
if (mainClock.autoAdvance) {
mainClock.advanceTimeByFrame()
}
}
private fun createUi() = ComposeScene(
density = density,
coroutineContext = coroutineContext,
invalidate = { }
).apply {
constraints = Constraints(maxWidth = surface.width, maxHeight = surface.height)
}
private fun isIdle() =
!Snapshot.current.hasPendingChanges() &&
!scene.hasInvalidations()
override fun waitForIdle() {
// always check even if we are idle
uncaughtExceptionHandler.throwUncaught()
while (!isIdle()) {
renderNextFrame()
uncaughtExceptionHandler.throwUncaught()
}
}
override suspend fun awaitIdle() {
// always check even if we are idle
uncaughtExceptionHandler.throwUncaught()
while (!isIdle()) {
renderNextFrame()
uncaughtExceptionHandler.throwUncaught()
yield()
}
}
override fun <T> runOnUiThread(action: () -> T): T {
return androidx.compose.ui.test.junit4.runOnUiThread(action)
}
override fun <T> runOnIdle(action: () -> T): T {
// We are waiting for idle before and AFTER `action` to guarantee that changes introduced
// in `action` are propagated to components. In Android's version, it's executed in the
// Main thread which has similar effects.
waitForIdle()
return action().also { waitForIdle() }
}
override fun waitUntil(timeoutMillis: Long, condition: () -> Boolean) {
val startTime = System.nanoTime()
while (!condition()) {
renderNextFrame()
if (System.nanoTime() - startTime > timeoutMillis * NanoSecondsPerMilliSecond) {
throw ComposeTimeoutException(
"Condition still not satisfied after $timeoutMillis ms"
)
}
}
}
override fun registerIdlingResource(idlingResource: IdlingResource) {
// TODO: implement
}
override fun unregisterIdlingResource(idlingResource: IdlingResource) {
// TODO: implement
}
override fun setContent(composable: @Composable () -> Unit) {
if (isOnUiThread()) {
scene.setContent(content = composable)
} else {
runOnUiThread {
scene.setContent(content = composable)
}
// Only wait for idleness if not on the UI thread. If we are on the UI thread, the
// caller clearly wants to keep tight control over execution order, so don't go
// executing future tasks on the main thread.
waitForIdle()
}
}
override fun onNode(
matcher: SemanticsMatcher,
useUnmergedTree: Boolean
): SemanticsNodeInteraction {
return SemanticsNodeInteraction(testContext, useUnmergedTree, matcher)
}
override fun onAllNodes(
matcher: SemanticsMatcher,
useUnmergedTree: Boolean
): SemanticsNodeInteractionCollection {
return SemanticsNodeInteractionCollection(testContext, useUnmergedTree, matcher)
}
private inner class DesktopTestOwner : TestOwner {
override fun sendTextInputCommand(node: SemanticsNode, command: List<EditCommand>) {
TODO()
}
override fun sendImeAction(node: SemanticsNode, actionSpecified: ImeAction) {
TODO()
}
override fun <T> runOnUiThread(action: () -> T): T {
return this@DesktopComposeUiTest.runOnUiThread(action)
}
override fun getRoots(atLeastOneRootExpected: Boolean): Set<RootForTest> {
return this@DesktopComposeUiTest.scene.roots
}
override val mainClock get() =
this@DesktopComposeUiTest.mainClock
}
}
@ExperimentalTestApi
actual sealed interface ComposeUiTest : SemanticsNodeInteractionsProvider {
actual val density: Density
actual val mainClock: MainTestClock
actual fun <T> runOnUiThread(action: () -> T): T
actual fun <T> runOnIdle(action: () -> T): T
actual fun waitForIdle()
actual suspend fun awaitIdle()
actual fun waitUntil(timeoutMillis: Long, condition: () -> Boolean)
actual fun registerIdlingResource(idlingResource: IdlingResource)
actual fun unregisterIdlingResource(idlingResource: IdlingResource)
actual fun setContent(composable: @Composable () -> Unit)
}
| 30
| null |
950
| 59
|
e18ad812b77fc8babb00aacfcea930607b0794b5
| 8,442
|
androidx
|
Apache License 2.0
|
app/src/main/java/com/jokopriyono/jonews/data/response/Article.kt
|
jokopriyono
| 183,607,038
| false
| null |
package com.jokopriyono.jonews.data.response
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Article(
@SerializedName("author")
val author: String?,
@SerializedName("content")
val content: String?,
@SerializedName("description")
val description: String?,
@SerializedName("publishedAt")
val publishedAt: String,
@SerializedName("source")
val source: Source,
@SerializedName("title")
val title: String,
@SerializedName("url")
val url: String,
@SerializedName("urlToImage")
val urlToImage: String?,
@SerializedName("category")
var category: String?
) : Parcelable
| 0
|
Kotlin
|
0
| 0
|
c02f28609aca282a9a018cefe36733d4d86ac910
| 727
|
JoNews
|
Apache License 2.0
|
core/bluetooth/src/main/kotlin/edu/stanford/spezi/core/bluetooth/data/model/BLEServiceEvent.kt
|
StanfordSpezi
| 787,513,636
| false
|
{"Kotlin": 1195675, "Ruby": 1769, "Shell": 212}
|
package edu.stanford.spezi.core.bluetooth.data.model
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
/**
* Represents events emitted by the Bluetooth Low Energy (BLE) service.
*/
sealed interface BLEServiceEvent {
/**
* Represents a generic error event.
*
* @property cause The cause of the error.
*/
data class GenericError(val cause: Throwable) : BLEServiceEvent
/**
* Represents an event indicating that scanning has failed.
*
* @property errorCode The error code associated with the scanning failure.
*/
data class ScanningFailed(val errorCode: Int) : BLEServiceEvent
/**
* Represents an event indicating that connection to a device has been established.
*
* @property device The Bluetooth device that is connected.
*/
data class Connected(val device: BLEDevice) : BLEServiceEvent
/**
* Represents an event indicating that a device is disconnected.
*
* @property device The Bluetooth device that is disconnected.
*/
data class Disconnected(val device: BLEDevice) : BLEServiceEvent
/**
* Represents an event indicating that a device has been discovered
*/
data class DeviceDiscovered(val device: BluetoothDevice) : BLEServiceEvent
/**
* Event indicating that a BLE device was paired.
* @property device BLE device
*/
data class DevicePaired(val device: BluetoothDevice) : BLEServiceEvent
/**
* Event indicating that a BLE device was paired.
* @property device BLE device
*/
data class DeviceUnpaired(val device: BluetoothDevice) : BLEServiceEvent
/**
* Represents a characteristic changed event
*
* @property device The Bluetooth device for which the characteristic changed
* @property gatt the bluetooth gatt profile
* @property characteristic Changed characteristic
* @property value Changed data
*/
data class CharacteristicChanged(
val device: BLEDevice,
val gatt: BluetoothGatt,
val characteristic: BluetoothGattCharacteristic,
val value: ByteArray,
) : BLEServiceEvent {
override fun equals(other: Any?): Boolean {
if (other !is CharacteristicChanged) return false
return this === other ||
(device == other.device &&
gatt == other.gatt &&
characteristic == other.characteristic &&
value.contentEquals(other.value))
}
override fun hashCode(): Int {
var result = device.hashCode()
result = 31 * result + gatt.hashCode()
result = 31 * result + characteristic.hashCode()
result = 31 * result + value.contentHashCode()
return result
}
}
data class ServiceDiscovered(
val device: BluetoothDevice,
val gatt: BluetoothGatt,
val status: Int,
) : BLEServiceEvent
}
| 16
|
Kotlin
|
2
| 8
|
9eae0b52bc631fa171b4873a739baddad8fe4b2c
| 3,047
|
SpeziKt
|
MIT License
|
app/src/main/java/org/oppia/android/app/testing/DrawableBindingAdaptersTestActivity.kt
|
oppia
| 148,093,817
| false
| null |
package org.oppia.android.app.testing
import android.os.Bundle
import org.oppia.android.R
import org.oppia.android.app.activity.ActivityComponentImpl
import org.oppia.android.app.activity.InjectableAppCompatActivity
/** Test activity for [org.oppia.android.app.databinding.DrawableBindingAdapters]. */
class DrawableBindingAdaptersTestActivity : InjectableAppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activityComponent as ActivityComponentImpl).inject(this)
setContentView(R.layout.test_drawable_binding_adapter_activity)
}
}
| 537
| null |
412
| 229
|
7fd290d68f0440d926f2d443dbd7bfb28ab20547
| 610
|
oppia-android
|
Apache License 2.0
|
compiler/testData/codegen/box/inference/pcla/issues/kt47989a.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// ISSUE: KT-47989
// IGNORE_LIGHT_ANALYSIS
// IGNORE_BACKEND: ANY
// REASON: red code (see corresponding diagnostic test)
fun box(): String {
build {
object: TypeSourceInterface {
override fun produceTargetType() = getTypeVariable()
}
}
return "OK"
}
class TargetType
interface TypeSourceInterface {
fun produceTargetType(): TargetType
}
class Buildee<TV> {
fun getTypeVariable(): TV = storage
private var storage: TV = TargetType() as TV
}
fun <PTV> build(instructions: Buildee<PTV>.() -> Unit): Buildee<PTV> {
return Buildee<PTV>().apply(instructions)
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 622
|
kotlin
|
Apache License 2.0
|
compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/platform/style/ShaderBrushSpan.android.kt
|
androidx
| 256,589,781
| false
| null |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.platform.style
import android.graphics.Shader
import android.text.TextPaint
import android.text.style.CharacterStyle
import android.text.style.UpdateAppearance
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.isUnspecified
import androidx.compose.ui.graphics.ShaderBrush
import androidx.compose.ui.text.platform.setAlpha
/**
* A span that applies [ShaderBrush] to TextPaint after receiving a specified size
*/
internal class ShaderBrushSpan(
val shaderBrush: ShaderBrush,
val alpha: Float
) : CharacterStyle(), UpdateAppearance {
var size: Size = Size.Unspecified
private var cachedShader: Pair<Size, Shader>? = null
override fun updateDrawState(textPaint: TextPaint) {
textPaint.setAlpha(alpha)
if (size.isUnspecified) return
val finalCachedShader = cachedShader
val shader = if (finalCachedShader == null || finalCachedShader.first != size) {
// if cached shader is not initialized or the size has changed, recreate the shader
shaderBrush.createShader(size)
} else {
// reuse the earlier created shader
finalCachedShader.second
}
textPaint.shader = shader
cachedShader = size to shader
}
}
| 22
| null |
843
| 4,781
|
a835d49996cd80daedf55cb5f72455eaa1f5b096
| 1,915
|
androidx
|
Apache License 2.0
|
app/src/main/java/com/mioamorefsm/features/lead/api/GetLeadRegProvider.kt
|
DebashisINT
| 524,006,838
| false
| null |
package com.mioamorefsm.features.lead.api
import com.mioamorefsm.features.NewQuotation.api.GetQuotListRegRepository
import com.mioamorefsm.features.NewQuotation.api.GetQutoListApi
object GetLeadRegProvider {
fun provideList(): GetLeadListRegRepository {
return GetLeadListRegRepository(GetLeadListApi.create())
}
}
| 0
|
Kotlin
|
0
| 0
|
b18c8515f404ca5e51c60c85c22676ef77712104
| 333
|
SwitzFood
|
Apache License 2.0
|
src/Day1.kt
|
jrmacgill
| 573,065,109
| false
| null |
fun main(args: Array<String>) {
val lines = object {}.javaClass.getResourceAsStream("dayOne.txt")?.bufferedReader()?.readLines()
var count = 0
var max = -1
var index = 0
var counts = mutableListOf<Int>()
lines?.forEach {
if (it.isEmpty()) {
counts.add(count)
count = 0
} else {
val num = it.toInt()
count += num
}
}
println(counts.sortedDescending().take(3).sum())
}
| 0
|
Kotlin
|
0
| 3
|
3dcd590f971b6e9c064b444139d6442df034355b
| 471
|
aoc-2022-kotlin
|
Apache License 2.0
|
glucose/src/main/java/com/desugar/glucose/renderer/opengl/OpenGLRendererAPI.kt
|
desugar-64
| 585,358,949
| false
| null |
package com.desugar.glucose.renderer.opengl
import android.opengl.GLES31
import android.util.Log
import com.desugar.glucose.renderer.RendererAPI
import com.desugar.glucose.renderer.VertexArray
import dev.romainguy.kotlin.math.Float4
class OpenGLRendererAPI : RendererAPI {
override fun init() {
// LOG
Log.d(TAG, "vendor: " + GLES31.glGetString(GLES31.GL_VENDOR))
Log.d(TAG, "renderer: " + GLES31.glGetString(GLES31.GL_RENDERER))
Log.d(TAG, "version: " + GLES31.glGetString(GLES31.GL_VERSION))
GLES31.glEnable(GLES31.GL_BLEND)
GLES31.glBlendFunc(GLES31.GL_SRC_ALPHA, GLES31.GL_ONE_MINUS_SRC_ALPHA)
GLES31.glEnable(GLES31.GL_DEPTH_TEST)
}
override fun setClearColor(color: Float4) {
GLES31.glClearColor(color.r, color.g, color.b, color.a)
}
override fun clear() {
GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT or GLES31.GL_DEPTH_BUFFER_BIT)
}
override fun drawIndexed(vertexArray: VertexArray, indexCount: Int) {
GLES31.glDrawElements(
GLES31.GL_TRIANGLES,
if (indexCount == 0) requireNotNull(vertexArray.indexBuffer).count else indexCount,
GLES31.GL_UNSIGNED_INT,
0
)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
}
override fun setViewPort(x: Int, y: Int, width: Int, height: Int) {
GLES31.glViewport(x, y, width, height)
}
override fun disableDepthTest() {
GLES31.glDisable(GLES31.GL_DEPTH_TEST)
}
companion object {
private const val TAG = "OpenGLRendererAPI"
}
}
| 0
|
Kotlin
|
0
| 0
|
f510d661aae5db723b6b2975ededb59a57f82cdd
| 1,595
|
android-opengl-renderer
|
Apache License 2.0
|
project-practice-problems/src/kiz/learnwithvel/problems/ab_decision/Calculator.kt
|
vel02
| 261,988,454
| false
|
{"Text": 1, "Ignore List": 59, "Markdown": 1, "XML": 511, "Kotlin": 200, "Java": 8, "Gradle": 25, "Java Properties": 16, "Shell": 8, "Batchfile": 8, "Proguard": 8}
|
package kiz.learnwithvel.problems.ab_decision
fun main() {
var firstNumber = 0
var secondNumber = 0
println("Enter two numbers: ")
firstNumber = readLine()!!.toInt()
secondNumber = readLine()!!.toInt()
print("Enter an operator (+, -, *, /): ")
val operator = readLine()!!.toCharArray()[0]
val result = when (operator) {
'+' -> firstNumber + secondNumber
'-' -> firstNumber - secondNumber
'*' -> firstNumber * secondNumber
'/' -> if (secondNumber >= 0) firstNumber / secondNumber
else secondNumber / firstNumber
else -> 0
}
println("$firstNumber $operator $secondNumber = $result")
}
| 1
| null |
1
| 1
|
7644d1911ff35fda44e45b1486bcce5d790fe7c0
| 675
|
learn-kotlin-android
|
MIT License
|
feature-governance-impl/src/main/java/io/novafoundation/nova/feature_governance_impl/presentation/delegation/delegation/revoke/confirm/RevokeDelegationConfirmViewModel.kt
|
novasamatech
| 415,834,480
| false
| null |
package io.novafoundation.nova.feature_governance_impl.presentation.delegation.delegation.revoke.confirm
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import io.novafoundation.nova.common.base.BaseViewModel
import io.novafoundation.nova.common.mixin.api.Validatable
import io.novafoundation.nova.common.mixin.hints.ResourcesHintsMixinFactory
import io.novafoundation.nova.common.resources.ResourceManager
import io.novafoundation.nova.common.utils.Event
import io.novafoundation.nova.common.utils.event
import io.novafoundation.nova.common.utils.firstLoaded
import io.novafoundation.nova.common.utils.flowOf
import io.novafoundation.nova.common.utils.multiResult.PartialRetriableMixin
import io.novafoundation.nova.common.utils.withSafeLoading
import io.novafoundation.nova.common.validation.ValidationExecutor
import io.novafoundation.nova.common.validation.progressConsumer
import io.novafoundation.nova.feature_account_api.domain.interfaces.SelectedAccountUseCase
import io.novafoundation.nova.feature_account_api.presenatation.account.wallet.WalletModel
import io.novafoundation.nova.feature_account_api.presenatation.account.wallet.WalletUiUseCase
import io.novafoundation.nova.feature_account_api.presenatation.actions.ExternalActions
import io.novafoundation.nova.feature_governance_api.domain.delegation.delegate.label.DelegateLabelUseCase
import io.novafoundation.nova.feature_governance_impl.R
import io.novafoundation.nova.feature_governance_impl.data.GovernanceSharedState
import io.novafoundation.nova.feature_governance_impl.domain.delegation.delegation.revoke.RevokeDelegationsInteractor
import io.novafoundation.nova.feature_governance_impl.domain.delegation.delegation.revoke.validations.RevokeDelegationValidationPayload
import io.novafoundation.nova.feature_governance_impl.domain.delegation.delegation.revoke.validations.RevokeDelegationValidationSystem
import io.novafoundation.nova.feature_governance_impl.domain.delegation.delegation.revoke.validations.handleRevokeDelegationValidationFailure
import io.novafoundation.nova.feature_governance_impl.presentation.GovernanceRouter
import io.novafoundation.nova.feature_governance_impl.presentation.delegation.delegate.common.DelegateMappers
import io.novafoundation.nova.feature_governance_impl.presentation.delegation.delegate.common.formatDelegationsOverviewOrNull
import io.novafoundation.nova.feature_governance_impl.presentation.delegation.delegation.create.common.revokeDelegationHints
import io.novafoundation.nova.feature_governance_impl.presentation.track.TrackDelegationModel
import io.novafoundation.nova.feature_governance_impl.presentation.track.TrackFormatter
import io.novafoundation.nova.feature_wallet_api.domain.AssetUseCase
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.fee.FeeLoaderMixin
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.fee.WithFeeLoaderMixin
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.fee.create
import io.novafoundation.nova.runtime.state.chain
import io.novafoundation.nova.runtime.state.chainAsset
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class RevokeDelegationConfirmViewModel(
private val router: GovernanceRouter,
private val feeLoaderMixinFactory: FeeLoaderMixin.Factory,
private val externalActions: ExternalActions.Presentation,
private val governanceSharedState: GovernanceSharedState,
private val walletUiUseCase: WalletUiUseCase,
private val selectedAccountUseCase: SelectedAccountUseCase,
private val interactor: RevokeDelegationsInteractor,
private val trackFormatter: TrackFormatter,
private val assetUseCase: AssetUseCase,
private val payload: RevokeDelegationConfirmPayload,
private val validationSystem: RevokeDelegationValidationSystem,
private val validationExecutor: ValidationExecutor,
private val resourceManager: ResourceManager,
private val resourcesHintsMixinFactory: ResourcesHintsMixinFactory,
private val delegateFormatters: DelegateMappers,
private val delegateLabelUseCase: DelegateLabelUseCase,
private val partialRetriableMixinFactory: PartialRetriableMixin.Factory
) : BaseViewModel(),
Validatable by validationExecutor,
WithFeeLoaderMixin,
ExternalActions by externalActions {
val partialRetriableMixin = partialRetriableMixinFactory.create(this)
private val assetFlow = assetUseCase.currentAssetFlow()
.shareInBackground()
override val originFeeMixin: FeeLoaderMixin.Presentation = feeLoaderMixinFactory.create(assetFlow)
val hintsMixin = resourcesHintsMixinFactory.revokeDelegationHints(viewModelScope)
val walletModel: Flow<WalletModel> = walletUiUseCase.selectedWalletUiFlow()
.shareInBackground()
val currentAddressModelFlow = selectedAccountUseCase.selectedAddressModelFlow { governanceSharedState.chain() }
.shareInBackground()
private val _showNextProgress = MutableStateFlow(false)
val showNextProgress: Flow<Boolean> = _showNextProgress
val delegateLabelModel = flowOf { delegateLabelUseCase.getDelegateLabel(payload.delegateId) }
.map { delegateFormatters.formatDelegateLabel(it.accountId, it.metadata, it.onChainIdentity?.display, governanceSharedState.chain()) }
.withSafeLoading()
.shareInBackground()
private val _showTracksEvent = MutableLiveData<Event<List<TrackDelegationModel>>>()
val showTracksEvent: LiveData<Event<List<TrackDelegationModel>>> = _showTracksEvent
private val revokeDelegationData = interactor.revokeDelegationDataFlow(payload.trackIds)
.shareInBackground()
private val trackDelegationModelsFlow = revokeDelegationData
.map { data ->
val chainAsset = governanceSharedState.chainAsset()
data.delegations.map { (track, delegation) ->
delegateFormatters.formatTrackDelegation(delegation, track, chainAsset)
}
}
.shareInBackground()
val tracksSummary = revokeDelegationData.map {
val chainAsset = governanceSharedState.chainAsset()
trackFormatter.formatTracksSummary(it.delegations.keys, chainAsset)
}.shareInBackground()
val undelegatingPeriod = revokeDelegationData
.map { resourceManager.formatDuration(it.undelegatingPeriod, estimated = false) }
.withSafeLoading()
.shareInBackground()
val userDelegation = revokeDelegationData.map {
val chainAsset = governanceSharedState.chainAsset()
delegateFormatters.formatDelegationsOverviewOrNull(it.delegationsOverview, chainAsset)
}.shareInBackground()
init {
loadFee()
}
fun accountClicked() = launch {
val addressModel = currentAddressModelFlow.first()
val type = ExternalActions.Type.Address(addressModel.address)
externalActions.showExternalActions(type, governanceSharedState.chain())
}
fun delegateClicked() = launch {
val address = delegateLabelModel.firstLoaded().address
val type = ExternalActions.Type.Address(address)
externalActions.showExternalActions(type, governanceSharedState.chain())
}
fun tracksClicked() = launch {
val trackModels = trackDelegationModelsFlow.first()
_showTracksEvent.value = trackModels.event()
}
fun confirmClicked() = launch {
val asset = assetFlow.first()
val fee = originFeeMixin.awaitFee()
val validationPayload = RevokeDelegationValidationPayload(fee, asset)
validationExecutor.requireValid(
validationSystem = validationSystem,
payload = validationPayload,
validationFailureTransformer = { handleRevokeDelegationValidationFailure(it, resourceManager) },
progressConsumer = _showNextProgress.progressConsumer(),
) {
performDelegate()
}
}
fun backClicked() {
router.back()
}
private fun loadFee() = launch {
originFeeMixin.loadFeeV2(
coroutineScope = coroutineScope,
feeConstructor = { interactor.calculateFee(payload.trackIds) },
onRetryCancelled = {}
)
}
private fun performDelegate() = launch {
val result = withContext(Dispatchers.Default) {
interactor.revokeDelegations(payload.trackIds)
}
partialRetriableMixin.handleMultiResult(
multiResult = result,
onSuccess = {
showMessage(resourceManager.getString(R.string.common_transaction_submitted))
router.backToYourDelegations()
},
progressConsumer = _showNextProgress.progressConsumer(),
onRetryCancelled = { router.backToYourDelegations() }
)
}
}
| 14
| null |
6
| 9
|
dea9f1144c1cbba1d876a9bb753f8541da38ebe0
| 9,034
|
nova-wallet-android
|
Apache License 2.0
|
app/src/main/java/com/example/project_04_flixster_part_02/TvShowAdapter.kt
|
TosnEula
| 547,660,654
| false
|
{"Kotlin": 9136}
|
package com.example.project_04_flixster_part_02
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
const val SHOW_EXTRA = "SHOW_EXTRA"
private const val TAG = "TvShowAdapter"
class TvShowAdapter(private val context: Context, private val tvShows: List<TvShow>) :
RecyclerView.Adapter<TvShowAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.movies_main_page, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
//Get the individual article and bind to holder
val tvShow = tvShows[position]
holder.bind(tvShow)
}
override fun getItemCount() = tvShows.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener {
private val showImageView = itemView.findViewById<ImageView>(R.id.showImage)
private val showNameTextView = itemView.findViewById<TextView>(R.id.showName)
private val showRatingTextView = itemView.findViewById<TextView>(R.id.showRating)
init {
itemView.setOnClickListener(this)
}
//A helper method to help set up the onBindViewHolder method
fun bind(tvShow: TvShow) {
showNameTextView.text = tvShow.showName
showRatingTextView.text = "Rating: " + tvShow.voteAverage.toString() + "/10"
Glide.with(context)
.load(tvShow.mediaImageUrl)
.into(showImageView)
}
override fun onClick(p0: View?) {
// Get selected show
val article = tvShows[absoluteAdapterPosition]
// Navigate to Details screen and pass selected show
val intent = Intent(context, ShowDetail::class.java)
intent.putExtra(SHOW_EXTRA, article)
context.startActivity(intent)
}
}
}
| 2
|
Kotlin
|
0
| 0
|
b2940c8038e9411f328a8e528d98dbaeee2b6c19
| 2,227
|
Project_04_Flixster_Part_02
|
Apache License 2.0
|
wear/compose/compose-material/benchmark/src/androidTest/java/androidx/wear/compose/material/benchmark/PositionIndicatorBenchmark.kt
|
androidx
| 256,589,781
| false
| null |
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material.benchmark
import androidx.compose.animation.core.snap
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.testutils.LayeredComposeTestCase
import androidx.compose.testutils.assertNoPendingChanges
import androidx.compose.testutils.benchmark.ComposeBenchmarkRule
import androidx.compose.testutils.benchmark.benchmarkToFirstPixel
import androidx.compose.testutils.setupContent
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.wear.compose.foundation.lazy.ScalingLazyColumn
import androidx.wear.compose.foundation.lazy.ScalingLazyListState
import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.PositionIndicator
import androidx.wear.compose.material.PositionIndicatorDefaults
import androidx.wear.compose.material.PositionIndicatorState
import androidx.wear.compose.material.PositionIndicatorVisibility
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class SimplePositionIndicatorBenchmark {
@get:Rule
val benchmarkRule = ComposeBenchmarkRule()
private val defaultPositionIndicatorCaseFactory = {
SimplePositionIndicatorBenchmarkTestCase(animate = false)
}
@Test
fun changeFraction() {
benchmarkRule.changePositionBenchmark {
SimplePositionIndicatorBenchmarkTestCase(
targetFraction = 0.5f,
animate = false
)
}
}
@Test
fun changeFractionAndSizeFraction_hide() {
benchmarkRule.changePositionBenchmark {
SimplePositionIndicatorBenchmarkTestCase(
targetFraction = 0.5f,
targetSizeFraction = 0.5f,
targetVisibility = PositionIndicatorVisibility.Hide,
animate = false
)
}
}
@Test
fun changeFractionAndSizeFraction_autoHide() {
benchmarkRule.changePositionBenchmark {
SimplePositionIndicatorBenchmarkTestCase(
targetFraction = 0.5f,
targetSizeFraction = 0.5f,
targetVisibility = PositionIndicatorVisibility.AutoHide,
animate = false
)
}
}
@Test
fun changeFraction_withAnimation() {
benchmarkRule.changePositionBenchmark {
SimplePositionIndicatorBenchmarkTestCase(
targetFraction = 0.5f,
animate = true
)
}
}
@Test
fun changeFractionAndSizeFraction_hide_withAnimation() {
benchmarkRule.changePositionBenchmark {
SimplePositionIndicatorBenchmarkTestCase(
targetFraction = 0.5f,
targetSizeFraction = 0.5f,
targetVisibility = PositionIndicatorVisibility.Hide,
animate = true
)
}
}
@Test
fun changeFractionAndSizeFraction_autoHide_withAnimation() {
benchmarkRule.changePositionBenchmark {
SimplePositionIndicatorBenchmarkTestCase(
targetFraction = 0.5f,
targetSizeFraction = 0.5f,
targetVisibility = PositionIndicatorVisibility.AutoHide,
animate = true
)
}
}
@Test
fun firstPixel() {
benchmarkRule.benchmarkToFirstPixel(defaultPositionIndicatorCaseFactory)
}
}
@LargeTest
@RunWith(AndroidJUnit4::class)
class PositionIndicatorWithScalingLazyColumnBenchmark {
@get:Rule
val benchmarkRule = ComposeBenchmarkRule()
@Test
fun positionIndicator_withScalingLazyColumn_withScroll() {
benchmarkRule.changePositionBenchmark {
PositionIndicatorWithScalingLazyColumnBenchmarkTestCase(true)
}
}
@Test
fun positionIndicator_withScalingLazyColumn_noScroll() {
benchmarkRule.changePositionBenchmark {
PositionIndicatorWithScalingLazyColumnBenchmarkTestCase(false)
}
}
}
internal class SimplePositionIndicatorBenchmarkTestCase(
val targetFraction: Float? = null,
val targetSizeFraction: Float? = null,
val targetVisibility: PositionIndicatorVisibility? = null,
val animate: Boolean
) : PositionIndicatorBenchmarkTestCase() {
private lateinit var positionFraction: MutableState<Float>
private lateinit var sizeFraction: MutableState<Float>
private lateinit var visibility: MutableState<PositionIndicatorVisibility>
override fun onChange() {
runBlocking {
targetFraction?.let { positionFraction.value = targetFraction }
targetSizeFraction?.let { sizeFraction.value = targetSizeFraction }
targetVisibility?.let { visibility.value = targetVisibility }
}
}
@Composable
override fun MeasuredContent() {
positionFraction = remember { mutableFloatStateOf(0f) }
sizeFraction = remember { mutableFloatStateOf(.1f) }
visibility = remember { mutableStateOf(PositionIndicatorVisibility.Show) }
val state = remember {
CustomPositionIndicatorState(
_positionFraction = { positionFraction.value },
sizeFraction = { sizeFraction.value },
visibility = { visibility.value })
}
PositionIndicator(
state = state,
indicatorHeight = 50.dp,
indicatorWidth = 4.dp,
paddingHorizontal = 5.dp,
fadeInAnimationSpec = if (animate)
PositionIndicatorDefaults.visibilityAnimationSpec
else
snap(),
fadeOutAnimationSpec = if (animate)
PositionIndicatorDefaults.visibilityAnimationSpec
else
snap(),
positionAnimationSpec = if (animate)
PositionIndicatorDefaults.positionAnimationSpec
else
snap()
)
}
@Composable
override fun ContentWrappers(content: @Composable () -> Unit) {
MaterialTheme {
content()
}
}
}
internal class PositionIndicatorWithScalingLazyColumnBenchmarkTestCase(
private val withScroll: Boolean = false
) : PositionIndicatorBenchmarkTestCase() {
private lateinit var slcState: ScalingLazyListState
override fun onChange() {
runBlocking {
if (withScroll) slcState.scrollToItem(30)
}
}
@Composable
override fun MeasuredContent() {
slcState = rememberScalingLazyListState()
Box(modifier = Modifier.fillMaxSize()) {
ScalingLazyColumn(
state = slcState,
) {
items(50) {
// By changing the size we can also change the size of the PositionIndicator,
// which will allow us to better measure all parts of PositionIndicator math.
val height = it.dp
Box(
modifier = Modifier
.fillMaxWidth()
.height(height)
)
}
}
PositionIndicator(
scalingLazyListState = slcState,
fadeInAnimationSpec = snap(),
fadeOutAnimationSpec = snap(),
positionAnimationSpec = snap()
)
}
}
@Composable
override fun ContentWrappers(content: @Composable () -> Unit) {
MaterialTheme {
content()
}
}
}
internal abstract class PositionIndicatorBenchmarkTestCase : LayeredComposeTestCase() {
abstract fun onChange()
}
private class CustomPositionIndicatorState(
private val _positionFraction: () -> Float,
private val sizeFraction: () -> Float,
private val visibility: () -> PositionIndicatorVisibility
) : PositionIndicatorState {
override val positionFraction: Float
get() = _positionFraction()
override fun sizeFraction(scrollableContainerSizePx: Float): Float = sizeFraction()
override fun visibility(scrollableContainerSizePx: Float): PositionIndicatorVisibility =
visibility()
}
internal fun ComposeBenchmarkRule.changePositionBenchmark(
caseFactory: () -> PositionIndicatorBenchmarkTestCase
) {
runBenchmarkFor(caseFactory) {
runOnUiThread {
disposeContent()
}
measureRepeatedOnUiThread {
runWithTimingDisabled {
setupContent()
assertNoPendingChanges()
}
getTestCase().onChange()
doFrame()
runWithTimingDisabled {
disposeContent()
}
}
}
}
| 29
| null |
937
| 5,321
|
98b929d303f34d569e9fd8a529f022d398d1024b
| 9,916
|
androidx
|
Apache License 2.0
|
core-data/src/main/java/io/agapps/core/data/repository/VehicleRepositoryImpl.kt
|
AlexMGreen
| 484,774,505
| false
| null |
package io.agapps.core.data.repository
import com.github.ajalt.timberkt.Timber
import io.agapps.common.result.Result
import io.agapps.core.database.dao.VehicleDao
import io.agapps.core.database.model.MotTestEntity
import io.agapps.core.database.model.RfrAndCommentEntity
import io.agapps.core.database.model.VehicleEntity
import io.agapps.core.database.model.toDomain
import io.agapps.core.model.MotTest
import io.agapps.core.model.ReasonForRejectionAndComment
import io.agapps.core.model.Vehicle
import io.agapps.core.network.MotHistoryNetworkSource
import io.agapps.core.network.model.MotHistoryDto
import io.agapps.core.network.model.MotTestDto
import io.agapps.core.network.model.RfrAndCommentDto
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class VehicleRepositoryImpl @Inject constructor(
private val motHistoryNetworkSource: MotHistoryNetworkSource,
private val vehicleDao: VehicleDao,
) : VehicleRepository {
override fun getVehicle(registrationNumber: String): Flow<Vehicle?> {
return vehicleDao.getVehicleByRegistrationNumber(registrationNumber.uppercase()).distinctUntilChanged().map {
Timber.d { "Retrieved vehicle from db: $it" }
it?.toDomain()
}
}
override suspend fun updateVehicle(registrationNumber: String) {
Timber.d { "Updating vehicle from API: $registrationNumber" }
val result = motHistoryNetworkSource.getMotHistory(registrationNumber)
if (result is Result.Success) {
Timber.d { "API response successful, saving vehicle in DB: $registrationNumber" }
vehicleDao.insertVehicle(result.data.toEntity())
}
}
private fun MotHistoryDto.toEntity() = VehicleEntity(
registrationNumber = registration.uppercase(),
make = make,
model = model,
primaryColour = primaryColour,
fuelType = fuelType,
engineSizeCc = engineSize,
manufactureDate = manufactureDate,
motTests = motTests?.map { it.toEntity() }
)
private fun MotTestDto.toEntity() = MotTestEntity(
completedDate = completedDate,
expiryDate = expiryDate,
motTestNumber = motTestNumber,
odometerUnit = odometerUnit,
odometerResultType = odometerResultType,
odometerValue = odometerValue,
rfrAndComments = rfrAndComments.map { it.toEntity() },
testResult = testResult,
)
private fun RfrAndCommentDto.toEntity() = RfrAndCommentEntity(
dangerous = dangerous,
text = text,
type = type,
)
// TODO: Combine with DVLA Vehicle Enquiry Service API info?
private fun MotHistoryDto.toDomain() = Vehicle(
registration,
make,
model,
primaryColour,
fuelType,
engineSize,
manufactureDate,
motTests = this.motTests?.map { it.toDomain() }
)
private fun MotTestDto.toDomain() = MotTest(
completedDate,
expiryDate,
motTestNumber,
odometerUnit,
odometerValue,
odometerResultType,
reasonForRejectionAndComment = rfrAndComments.map { it.toDomain() },
testResult
)
private fun RfrAndCommentDto.toDomain() = ReasonForRejectionAndComment(
dangerous,
text,
type
)
}
| 0
|
Kotlin
|
0
| 0
|
fc190a765d904f9ff18f0720ba9b7398edc6d29b
| 3,397
|
mot-checker
|
Apache License 2.0
|
InstaTask/app/src/main/java/com/example/instatask/ui/app/Navigation/NavScreens.kt
|
linpeterk
| 472,551,243
| false
| null |
package com.example.instatask.ui.app.Navigation
import com.example.instatask.R
sealed class NavScreens(var route: String, var icon: Int, var title: String) {
object TaskBoard : NavScreens("TaskBoard", R.drawable.jobimageone, "Gigs")
object SkillBoard : NavScreens("SkillBoard", R.drawable.professionalimagefive, "Pro")
object WhenJob : NavScreens("WhenJob", R.drawable.toilet, "WhenJob")
object Books : NavScreens("books", R.drawable.ic_sea_icon, "Earnings")
object Profile : NavScreens("Profile", R.drawable.profileimagetwo, "Pro-file")
object WhenSkill: NavScreens("WhenSkill", R.drawable.ic_sea_icon, "WhenSkill")
object PostTask: NavScreens("PostTask", R.drawable.taskimagethree, "Post Gig")
object Gig: NavScreens("Gig", R.drawable.gigimageone, "Gigs")
object Landing: NavScreens("Landing", R.drawable.ic_sea_icon, "Landing")
object Login: NavScreens("Login", R.drawable.ic_sea_icon, "Login")
object Signup: NavScreens("Signup", R.drawable.ic_sea_icon, "Signup")
object JobAccepted: NavScreens("JobAccepted", R.drawable.ic_sea_icon, "JobAccepted")
// object Interm: NavScreens("Interm", R.drawable.ic_sea_icon, "Interm")
}
| 0
|
Kotlin
|
0
| 0
|
fd9fd4723b8180a5b19e40bb43ae822e1418b0ff
| 1,185
|
Insta-Task
|
Apache License 2.0
|
data/src/main/java/com/arjuj/data/di/DataModules.kt
|
arjunmehtaa
| 426,723,003
| false
|
{"Kotlin": 69080}
|
package com.arjuj.data.di
import com.arjuj.data.repository.Repository
import com.arjuj.data.room.RoomPokemonDatabase
import com.arjuj.data.room.RoomPokemonRepository
import com.arjuj.domain.repository.RepositoryInterface
import com.arjuj.domain.repository.RoomRepositoryInterface
import org.koin.android.ext.koin.androidApplication
import org.koin.dsl.module
val dataModule = module {
factory<RepositoryInterface> { Repository() }
factory<RoomRepositoryInterface> { RoomPokemonRepository(RoomPokemonDatabase.getDatabase(androidApplication()).roomPokemonDao()) }
}
| 1
|
Kotlin
|
1
| 18
|
6435d31ba7f2f386b97c9a808ede0a0ee68d7de5
| 575
|
PokeFacts
|
Apache License 2.0
|
sdk/adaptive/src/androidTest/java/com/ibm/security/verifysdk/adaptive/test/RemoteMockAdaptive.kt
|
ibm-security-verify
| 430,929,749
| false
| null |
/*
* Copyright contributors to the IBM Security Verify Adaptive SDK for Android project
*/
package com.ibm.security.verifysdk.adaptive.test
import com.github.kittinunf.fuel.httpPost
import com.github.kittinunf.result.failure
import com.github.kittinunf.result.success
import com.ibm.security.verifysdk.adaptive.AdaptiveContext
import com.ibm.security.verifysdk.adaptive.AdaptiveDelegate
import com.ibm.security.verifysdk.adaptive.AdaptiveResult
import com.ibm.security.verifysdk.adaptive.AllowAssessmentResult
import com.ibm.security.verifysdk.adaptive.AllowedFactor
import com.ibm.security.verifysdk.adaptive.AssessmentStatusType
import com.ibm.security.verifysdk.adaptive.DenyAssessmentResult
import com.ibm.security.verifysdk.adaptive.EnrolledFactor
import com.ibm.security.verifysdk.adaptive.Factor
import com.ibm.security.verifysdk.adaptive.FactorEvaluation
import com.ibm.security.verifysdk.adaptive.GenerateResult
import com.ibm.security.verifysdk.adaptive.PasswordEvaluation
import com.ibm.security.verifysdk.adaptive.RequiresAssessmentResult
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
class RemoteMockAdaptive : AdaptiveDelegate {
private val address: String = "http://<your_ip_address>:3000"
override fun assessment(
sessionId: String,
evaluationContext: String,
completion: (Result<AdaptiveResult>) -> Unit
) {
val bodyJson =
"{\"sessionId\": \"$sessionId\", \"evaluationContext\": \"$evaluationContext\"}"
"$address/assessments".httpPost().body(bodyJson).header("Content-Type", "application/json")
.response { request, response, result ->
result.failure { completion(Result.failure(it)) }
result.success {
val responseJson = JSONObject(String(response.data))
completion(
when (responseJson.get("status")) {
AssessmentStatusType.allow -> {
val token = responseJson.get("token").toString()
Result.success(AllowAssessmentResult(token = token))
}
AssessmentStatusType.requires -> {
val transactionId = responseJson.get("transactionId").toString()
when {
responseJson.has("allowedFactors") -> {
val factorsJson =
responseJson.get("allowedFactors") as JSONArray
val allowedFactors =
List(factorsJson.length()) { factorString ->
val factorType = Factor.from(
factorsJson.getJSONObject(factorString)
.get("type").toString()
)
AllowedFactor(type = factorType)
}
Result.success(
RequiresAssessmentResult(
transactionId = transactionId,
factors = allowedFactors
)
)
}
responseJson.has("enrolledFactors") -> {
val factorsJson =
responseJson.get("enrolledFactors") as JSONArray
val allowedFactors =
List(factorsJson.length()) { factorString ->
val enrollment =
factorsJson.getJSONObject(factorString)
val factor =
Factor.from(enrollment.getString("type"))
val id = enrollment.getString("id")
val validated = enrollment.getBoolean("validated")
val enabled = enrollment.getBoolean("enabled")
val attributes =
enrollment.getJSONObject("attributes")
val attributesMap = attributes.keys().asSequence()
.associateWith { key ->
attributes[key] as String
}
EnrolledFactor(
type = factor,
id = id,
validated = validated,
enabled = enabled,
attributes = attributesMap
)
}
Result.success(
RequiresAssessmentResult(
transactionId = transactionId,
factors = allowedFactors
)
)
}
else -> {
Result.failure(JSONException("Neither \"allowedFactors\" or \"enrolledFactors\" found in requires response."))
}
}
}
else -> Result.success(DenyAssessmentResult())
}
)
}
}
}
override fun generate(
enrollmentId: String,
transactionId: String,
factor: Factor,
completion: (Result<GenerateResult>) -> Unit
) {
// val mockService = LocalMockAdaptiveService(returnType = this.testType);
// mockService.performGeneration(factor = factor.type, transactionId = transactionId) { result ->
// result.onFailure { completion(Result.failure(it)) }
// result.onSuccess {
// when (factor.type) {
// Factor.EMAIL_OTP, Factor.SMS_OTP -> {
// val responseJson = JSONObject(it!!)
// val correlation = responseJson.get("correlation") as String
// completion(Result.success(OtpGenerateResult(correlation = correlation)))
// }
// else -> completion(Result.success(OtpGenerateResult(correlation = null)))
// }
// }
// }
}
override fun evaluate(
evaluation: FactorEvaluation,
evaluationContext: String,
completion: (Result<AdaptiveResult>) -> Unit
) {
if (evaluation !is PasswordEvaluation) {
completion(Result.failure(Exception("Remote mock test only supports password evaluation.")))
}
val passwordEvaluation = evaluation as PasswordEvaluation
val bodyJson =
"{\"sessionId\": \"${AdaptiveContext.sessionId}\", \"evaluationContext\": \"$evaluationContext\", \"transactionId\":\"${passwordEvaluation.transactionId}\", \"username\":\"${passwordEvaluation.username}\", \"password\":\"${<PASSWORD>}\"}"
"$address/evaluations/password".httpPost().body(bodyJson)
.header("Content-Type", "application/json").response { request, response, result ->
result.failure { completion(Result.failure(it)) }
result.success {
val responseJson = JSONObject(String(response.data))
completion(
when (responseJson.get("status")) {
AssessmentStatusType.allow -> {
val token = responseJson.get("token").toString()
Result.success(AllowAssessmentResult(token = token))
}
AssessmentStatusType.requires -> {
val transactionId = responseJson.get("transactionId").toString()
when {
responseJson.has("allowedFactors") -> {
val factorsJson =
responseJson.get("allowedFactors") as JSONArray
val allowedFactors =
List(factorsJson.length()) { factorString ->
val factorType = Factor.from(
factorsJson.getJSONObject(factorString)
.get("type")
.toString()
)
AllowedFactor(type = factorType)
}
Result.success(
RequiresAssessmentResult(
transactionId = transactionId,
factors = allowedFactors
)
)
}
responseJson.has("enrolledFactors") -> {
val factorsJson =
responseJson.get("enrolledFactors") as JSONArray
val allowedFactors =
List(factorsJson.length()) { factorString ->
val enrollment = factorsJson.getJSONObject(factorString)
val factor =
Factor.from(enrollment.getString("type"))
val id = enrollment.getString("id")
val validated = enrollment.getBoolean("validated")
val enabled = enrollment.getBoolean("enabled")
val attributes = enrollment.getJSONObject("attributes")
val attributesMap = attributes.keys().asSequence()
.associateWith { key ->
attributes[key] as String
}
EnrolledFactor(
type = factor,
id = id,
validated = validated,
enabled = enabled,
attributes = attributesMap
)
}
Result.success(
RequiresAssessmentResult(
transactionId = transactionId,
factors = allowedFactors
)
)
}
else -> {
Result.failure(JSONException("Neither \"allowedFactors\" or \"enrolledFactors\" found in requires response."))
}
}
}
else -> Result.success(DenyAssessmentResult())
}
)
}
}
}
}
| 0
|
Kotlin
|
1
| 1
|
fd09a6d0c6586059e5d1cd00451b32dfbfe6e36a
| 12,924
|
verify-sdk-android
|
MIT License
|
octicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/octicons/octicons/Sliders24.kt
|
walter-juan
| 868,046,028
| false
| null |
package com.woowla.compose.icon.collections.octicons.octicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.octicons.Octicons
public val Octicons.Sliders24: ImageVector
get() {
if (_sliders24 != null) {
return _sliders24!!
}
_sliders24 = Builder(name = "Sliders24", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(11.0f, 18.25f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, -0.75f)
horizontalLineToRelative(8.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f)
horizontalLineToRelative(-8.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.75f, -0.75f)
close()
moveTo(3.0f, 6.25f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, -0.75f)
horizontalLineToRelative(7.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f)
horizontalLineToRelative(-7.5f)
arcTo(0.75f, 0.75f, 0.0f, false, true, 3.0f, 6.25f)
close()
moveTo(16.0f, 12.25f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, -0.75f)
horizontalLineToRelative(3.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f)
horizontalLineToRelative(-3.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.75f, -0.75f)
close()
moveTo(8.75f, 16.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, 0.75f)
verticalLineToRelative(3.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.5f, 0.0f)
verticalLineToRelative(-3.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, -0.75f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(3.0f, 18.25f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, -0.75f)
horizontalLineToRelative(4.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f)
horizontalLineToRelative(-4.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.75f, -0.75f)
close()
moveTo(3.0f, 12.25f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, -0.75f)
horizontalLineToRelative(8.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f)
horizontalLineToRelative(-8.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.75f, -0.75f)
close()
moveTo(16.75f, 10.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, 0.75f)
verticalLineToRelative(3.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.5f, 0.0f)
verticalLineToRelative(-3.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, -0.75f)
close()
moveTo(14.0f, 6.25f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, -0.75f)
horizontalLineToRelative(5.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f)
horizontalLineToRelative(-5.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.75f, -0.75f)
close()
moveTo(11.25f, 4.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, 0.75f)
verticalLineToRelative(3.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.5f, 0.0f)
verticalLineToRelative(-3.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, -0.75f)
close()
}
}
.build()
return _sliders24!!
}
private var _sliders24: ImageVector? = null
| 0
| null |
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 4,968
|
compose-icon-collections
|
MIT License
|
analysis/analysis-api-impl-base/src/org/jetbrains/kotlin/analysis/api/impl/base/lifetime/KaBaseLifetimeTracker.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.impl.base.lifetime
import com.intellij.openapi.project.Project
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.lifetime.KtLifetimeToken
import org.jetbrains.kotlin.analysis.providers.lifetime.KaLifetimeTracker
internal class KaBaseLifetimeTracker : KaLifetimeTracker {
private val lifetimeOwnersStack = ThreadLocal.withInitial<PersistentList<KtLifetimeToken>> { persistentListOf() }
override val currentToken: KtLifetimeToken? get() = lifetimeOwnersStack.get().lastOrNull()
fun beforeEnteringAnalysis(session: KtAnalysisSession) {
lifetimeOwnersStack.set(lifetimeOwnersStack.get().add(session.token))
}
fun afterLeavingAnalysis(session: KtAnalysisSession) {
val stack = lifetimeOwnersStack.get()
val last = stack.last()
check(last == session.token)
lifetimeOwnersStack.set(stack.removeAt(stack.lastIndex))
}
companion object {
fun getInstance(project: Project): KaBaseLifetimeTracker =
KaLifetimeTracker.getInstance(project) as? KaBaseLifetimeTracker
?: error("Expected ${KaBaseLifetimeTracker::class.simpleName} to be registered for ${KaLifetimeTracker::class.simpleName}.")
}
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,604
|
kotlin
|
Apache License 2.0
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/EnvelopeBulk.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.EnvelopeBulk: ImageVector
get() {
if (_envelopeBulk != null) {
return _envelopeBulk!!
}
_envelopeBulk = Builder(name = "EnvelopeBulk", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(20.0f, 6.0f)
horizontalLineToRelative(-1.0f)
verticalLineToRelative(-2.0f)
curveToRelative(0.0f, -2.206f, -1.794f, -4.0f, -4.0f, -4.0f)
lineTo(7.0f, 0.0f)
curveTo(4.794f, 0.0f, 3.0f, 1.794f, 3.0f, 4.0f)
verticalLineToRelative(5.0f)
curveToRelative(0.0f, 0.739f, 0.201f, 1.431f, 0.552f, 2.025f)
curveToRelative(-1.995f, 0.223f, -3.552f, 1.92f, -3.552f, 3.975f)
verticalLineToRelative(5.0f)
curveToRelative(0.0f, 2.206f, 1.794f, 4.0f, 4.0f, 4.0f)
lineTo(12.0f, 24.0f)
curveToRelative(2.206f, 0.0f, 4.0f, -1.794f, 4.0f, -4.0f)
verticalLineToRelative(-1.0f)
horizontalLineToRelative(4.0f)
curveToRelative(2.206f, 0.0f, 4.0f, -1.794f, 4.0f, -4.0f)
verticalLineToRelative(-5.0f)
curveToRelative(0.0f, -2.206f, -1.794f, -4.0f, -4.0f, -4.0f)
close()
moveTo(5.0f, 4.0f)
curveToRelative(0.0f, -1.103f, 0.897f, -2.0f, 2.0f, -2.0f)
lineTo(15.0f, 2.0f)
curveToRelative(1.103f, 0.0f, 2.0f, 0.897f, 2.0f, 2.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-5.0f)
curveToRelative(-2.206f, 0.0f, -4.0f, 1.794f, -4.0f, 4.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(-1.0f)
curveToRelative(-1.103f, 0.0f, -2.0f, -0.897f, -2.0f, -2.0f)
lineTo(5.0f, 4.0f)
close()
moveTo(12.0f, 13.0f)
curveToRelative(0.179f, 0.0f, 0.353f, 0.024f, 0.518f, 0.068f)
lineToRelative(-3.523f, 3.522f)
curveToRelative(-0.527f, 0.527f, -1.446f, 0.527f, -1.975f, 0.0f)
lineToRelative(-3.526f, -3.526f)
curveToRelative(0.161f, -0.042f, 0.331f, -0.065f, 0.505f, -0.065f)
lineTo(12.0f, 12.999f)
close()
moveTo(14.0f, 20.0f)
curveToRelative(0.0f, 1.103f, -0.897f, 2.0f, -2.0f, 2.0f)
lineTo(4.0f, 22.0f)
curveToRelative(-1.103f, 0.0f, -2.0f, -0.897f, -2.0f, -2.0f)
verticalLineToRelative(-5.0f)
curveToRelative(0.0f, -0.184f, 0.025f, -0.361f, 0.072f, -0.53f)
lineToRelative(3.535f, 3.535f)
curveToRelative(0.642f, 0.642f, 1.495f, 0.995f, 2.402f, 0.995f)
reflectiveCurveToRelative(1.761f, -0.354f, 2.402f, -0.995f)
lineToRelative(3.522f, -3.522f)
curveToRelative(0.044f, 0.165f, 0.068f, 0.338f, 0.068f, 0.517f)
verticalLineToRelative(5.0f)
close()
moveTo(22.0f, 15.0f)
curveToRelative(0.0f, 1.103f, -0.897f, 2.0f, -2.0f, 2.0f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(-2.0f)
curveToRelative(0.0f, -2.206f, -1.794f, -4.0f, -4.0f, -4.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -1.103f, 0.897f, -2.0f, 2.0f, -2.0f)
horizontalLineToRelative(8.0f)
curveToRelative(1.103f, 0.0f, 2.0f, 0.897f, 2.0f, 2.0f)
verticalLineToRelative(5.0f)
close()
moveTo(20.0f, 11.0f)
curveToRelative(0.0f, 0.552f, -0.448f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.448f, -1.0f, -1.0f)
reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f)
reflectiveCurveToRelative(1.0f, 0.448f, 1.0f, 1.0f)
close()
}
}
.build()
return _envelopeBulk!!
}
private var _envelopeBulk: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 5,079
|
icons
|
MIT License
|
compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/intermediate/ArrayAccessAssignmentReceiver.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.psi2ir.intermediate
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrStatementOrigin
import org.jetbrains.kotlin.ir.expressions.impl.IrBlockImpl
import org.jetbrains.kotlin.ir.expressions.impl.inlineStatement
import org.jetbrains.kotlin.ir.expressions.isAssignmentOperatorWithResult
import org.jetbrains.kotlin.psi2ir.generators.CallGenerator
import org.jetbrains.kotlin.types.KotlinType
import java.lang.AssertionError
class ArrayAccessAssignmentReceiver(
private val irArray: IrExpression,
private val irIndices: List<IrExpression>,
private val indexedGetCall: CallBuilder?,
private val indexedSetCall: CallBuilder?,
private val callGenerator: CallGenerator,
private val startOffset: Int,
private val endOffset: Int,
private val origin: IrStatementOrigin
) : AssignmentReceiver {
private val kotlinType: KotlinType =
indexedGetCall?.run { descriptor.returnType!! } ?: indexedSetCall?.run { descriptor.valueParameters.last().type }
?: throw AssertionError("Array access should have either indexed-get call or indexed-set call")
override fun assign(withLValue: (LValue) -> IrExpression): IrExpression {
val hasResult = origin.isAssignmentOperatorWithResult()
val resultType = if (hasResult) kotlinType else callGenerator.context.builtIns.unitType
val irResultType = callGenerator.translateType(resultType)
val irBlock = IrBlockImpl(startOffset, endOffset, irResultType, origin)
val irArrayValue = callGenerator.scope.createTemporaryVariableInBlock(callGenerator.context, irArray, irBlock, "array")
val irIndexValues = irIndices.mapIndexed { i, irIndex ->
callGenerator.scope.createTemporaryVariableInBlock(callGenerator.context, irIndex, irBlock, "index$i")
}
indexedGetCall?.fillArrayAndIndexArguments(irArrayValue, irIndexValues)
indexedSetCall?.fillArrayAndIndexArguments(irArrayValue, irIndexValues)
val irLValue = LValueWithGetterAndSetterCalls(
callGenerator,
indexedGetCall, indexedSetCall,
callGenerator.translateType(kotlinType),
startOffset, endOffset, origin
)
irBlock.inlineStatement(withLValue(irLValue))
return irBlock
}
override fun assign(value: IrExpression): IrExpression {
if (indexedSetCall == null) throw AssertionError("Array access without indexed-get call")
indexedSetCall.setExplicitReceiverValue(OnceExpressionValue(irArray))
irIndices.forEachIndexed { i, irIndex ->
indexedSetCall.irValueArgumentsByIndex[i] = irIndex
}
indexedSetCall.lastArgument = value
return callGenerator.generateCall(startOffset, endOffset, indexedSetCall, IrStatementOrigin.EQ)
}
private fun CallBuilder.fillArrayAndIndexArguments(arrayValue: IntermediateValue, indexValues: List<IntermediateValue>) {
setExplicitReceiverValue(arrayValue)
indexValues.forEachIndexed { i, irIndexValue ->
irValueArgumentsByIndex[i] = irIndexValue.load()
}
}
}
| 12
| null |
1
| 43
|
d2a24985b602e5f708e199aa58ece652a4b0ea48
| 3,772
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/net/aquadc/mike/plugin/android/UnsupportedFeatureInspection.kt
|
Miha-x64
| 194,734,584
| false
| null |
package net.aquadc.mike.plugin.android
import com.android.tools.idea.util.androidFacet
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiAnonymousClass
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiTypeParameter
import com.intellij.psi.search.ProjectScope
import com.siyeh.ig.callMatcher.CallMatcher
import net.aquadc.mike.plugin.FunctionCallVisitor
import net.aquadc.mike.plugin.NamedLocalQuickFix
import net.aquadc.mike.plugin.PsiType_INT
import net.aquadc.mike.plugin.UastInspection
import net.aquadc.mike.plugin.test
import org.jetbrains.android.augment.ResourceLightField
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UDeclaration
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.UImportStatement
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.UParenthesizedExpression
import org.jetbrains.uast.UReferenceExpression
import org.jetbrains.uast.UVariable
import org.jetbrains.uast.UastCallKind
import org.jetbrains.uast.getContainingUClass
import org.jetbrains.uast.toUElement
import org.jetbrains.uast.toUElementOfType
import org.jetbrains.uast.tryResolve
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
/**
* @author <NAME>
*/
class UnsupportedFeatureInspection : UastInspection() {
override fun uVisitor(
holder: ProblemsHolder, isOnTheFly: Boolean
): AbstractUastNonRecursiveVisitor = object : FunctionCallVisitor() {
override fun visitDeclaration(node: UDeclaration): Boolean {
// detect android.app.Activity#onCreate(android.os.Bundle, android.os.PersistableBundle)
if (node is UMethod && node.name == "onCreate" && node.uastParameters.size == 2) {
node.sourcePsi?.project?.let { proj ->
val fac = JavaPsiFacade.getInstance(proj)
val aaa = fac.findClass("android.app.Activity", ProjectScope.getLibrariesScope(proj))
if (aaa != null && node.getContainingUClass()?.isInheritor(aaa, true) == true &&
node.uastParameters[0].typeReference?.getQualifiedName() == "android.os.Bundle" &&
node.uastParameters[1].typeReference?.getQualifiedName() == "android.os.PersistableBundle") {
// TODO check for persistableMode=persistAcrossReboots in the manifest
node.uastParameters[1].sourcePsi?.let { pbpSrc ->
holder.registerProblem(
pbpSrc,
"Method onCreate(Bundle, PersistableBundle) will only be called if persistableMode=persistAcrossReboots in the Manifest.",
ProblemHighlightType.WEAK_WARNING,
object : NamedLocalQuickFix("Remove parameter") {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
descriptor.psiElement?.delete()
}
}
)
}
}
}
}
return true
}
override fun visitImportStatement(node: UImportStatement): Boolean {
val psi = (node.sourcePsi as? KtImportDirective)
if (psi != null && psi.importPath?.pathStr?.startsWith("kotlinx.android.synthetic") == true) {
holder.registerProblem(
psi.importedReference ?: psi,
"Kotlin Android Extensions are deprecated",
ProblemHighlightType.LIKE_DEPRECATED,
)
}
return true
}
override fun visitCallExpr(
node: UExpression, src: PsiElement, kind: UastCallKind, operator: String?,
declaringClassFqn: String, receiver: UExpression?, methodName: String, valueArguments: List<UExpression>,
): Boolean {
(node as? UCallExpression)?.let { checkListenerSupport(it, src) }
checkObtainStyled(src, declaringClassFqn, methodName, valueArguments)
return true
}
private fun checkListenerSupport(node: UCallExpression, src: PsiElement) {
src.containingFile?.androidFacet?.androidMinSdk()?.apiLevel?.takeIf { it < 26 } ?: return
val className = (node.receiverType as? PsiClassType)?.resolve()?.qualifiedName ?: return
if (className == "android.widget.VideoView" && View_setOnClickListener.test(src))
holder.registerProblem(
node.methodIdentifier?.sourcePsi ?: src,
"VideoView click listener does not work before SDK 26",
// clicks were ignored by not calling super:
// https://github.com/aosp-mirror/platform_frameworks_base/blob/lollipop-mr1-release/core/java/android/widget/VideoView.java#L661
)
else if (className == "androidx.recyclerview.widget.RecyclerView" && View_setOnClickListener.test(src))
holder.registerProblem(
node.methodIdentifier?.sourcePsi ?: src,
"RecyclerView click listener does not work"
// clicks are ignored by not calling super:
// https://android.googlesource.com/platform/frameworks/support/+/64cde70e6cbe6ec9b743786aad419a854b18d89f/recyclerview/recyclerview/src/main/java/androidx/recyclerview/widget/RecyclerView.java#3709
)
}
private fun checkObtainStyled(src: PsiElement, declaringClassFqn: String, method: String, args: List<UExpression>) {
if (declaringClassFqn == "android.content.Context" && method == "obtainStyledAttributes") {
val attrs = (args.singleOrNull() ?: args.getOrNull(1) ?: return)
attrs.intArrayElementExpressions()?.takeIf { it.size > 1 }?.let { attrExprs ->
val attrValues = attrExprs.evaluateIntElements() //^ 0..1-sized arrays are always sorted
var prev = attrValues.first()
if (prev != Long.MIN_VALUE) {
for (i in 1 until attrValues.size) {
val curr = attrValues[i]
if (curr == Long.MIN_VALUE) break
if (curr < prev) {
val prevSrc = attrExprs[i - 1].sourcePsi?.takeIf { it.containingFile == src.containingFile }
val currSrc = attrExprs[i].sourcePsi?.takeIf { it.containingFile == src.containingFile }
if (prevSrc != null && currSrc != null) {
holder.registerProblem(holder.manager.createProblemDescriptor(
prevSrc, currSrc,
"Context.obtainStyledAttributes() needs a sorted array. " +
"Swap these elements",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly
))
} else {
holder.registerProblem(
src,
"Context.obtainStyledAttributes() needs a sorted array. " +
"Swap elements at ${i-1} and $i",
)
}
break
}
prev = curr
}
}
}
}
}
private fun UExpression.intArrayElementExpressions(): List<UExpression>? {
var expr = this
val log = Logger.getInstance(UnsupportedFeatureInspection::class.java)
while (true) {
expr = when (expr) {
is UParenthesizedExpression -> expr.expression
is UCallExpression ->
when (expr.kind) {
UastCallKind.METHOD_CALL -> {
if (expr.methodName == "intArrayOf" && expr.receiver == null)
return expr.valueArguments
else {
val resolved = expr.tryResolve()
return expr.sourcePsi?.let { log.error("$it | ${expr.javaClass} | ${resolved?.javaClass}"); null }
}
}
UastCallKind.CONSTRUCTOR_CALL ->
return expr.sourcePsi?.let { log.error("$it | ${expr.javaClass}"); null }
else -> {
if (expr.returnType == INT_ARRAY)
return expr.valueArguments
else
return expr.sourcePsi?.let { log.error("$it | ${expr.javaClass}"); null }
}
}
is UReferenceExpression -> {
val srcRef = expr.resolve() ?: return null // IDK WTF is this
if (srcRef is ResourceLightField) return null // trust R.styleable order
val referrent = srcRef.toUElement()
(referrent as? UVariable)?.uastInitializer
?: ((referrent as? UMethod)?.sourcePsi as? KtProperty)?.initializer
?.toUElementOfType<UExpression>()?.also { expr = it }
?: return expr.sourcePsi?.let { log.error("$it | ${expr.javaClass} | $srcRef | $referrent"); null }
}
else -> {
return expr.sourcePsi?.let { log.error("$it | ${expr.javaClass}"); null }
}
}
}
}
private fun List<UExpression>.evaluateIntElements(): LongArray = LongArray(size) {
(get(it).evaluate() as? Int)?.toLong() ?: Long.MIN_VALUE
}
override fun visitClass(node: UClass): Boolean {
node.sourcePsi?.let { src ->
if (src !is PsiTypeParameter && // <T extends Drawable> void lol() {}
node.javaPsi.isDrawable() &&
node.methods.none { it.name == "getConstantState" && it.uastParameters.isEmpty() }
) {
holder.registerProblem(
(src as? PsiAnonymousClass)?.firstChild // new [Drawable]() {
?: (src as? KtObjectDeclaration)?.firstChild // [object] : Drawable() {
?: (src as? PsiClass)?.nameIdentifier // public final class [BadDrawable] {
?: (src as? KtClass)?.nameIdentifier // class [BadDrawable] {
?: src, // dafuq
"A Drawable class should override getConstantState(). " +
"Absent ConstantState may lead to crashes; " +
"inherited ConstantState guarantees caching bugs when inflated from resources.",
ProblemHighlightType.WEAK_WARNING,
)
}
}
return super.visitClass(node)
}
private fun PsiClass.isDrawable(): Boolean =
superClass?.qualifiedName == "android.graphics.drawable.Drawable" ||
superClass?.isDrawable() == true
}
private companion object {
private val View_setOnClickListener =
CallMatcher.instanceCall("android.view.View", "setOnClickListener")
.parameterTypes("android.view.View.OnClickListener")
private val INT_ARRAY = PsiType_INT.createArrayType()
}
}
| 21
|
Kotlin
|
6
| 25
|
029dd1eed9bf8841cf5a537ae728baa50f2560db
| 12,659
|
Mikes_IDEA_extensions
|
Apache License 2.0
|
packages/replay-android/android-library/replay-android/src/main/java/com/replay/android/WebAppInterface.kt
|
edbentley
| 260,674,431
| false
| null |
package com.replay.android
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.webkit.JavascriptInterface
import java.io.FileNotFoundException
class WebAppInterface(private val replayContext: ReplayActivity) {
@JavascriptInterface
fun bridge(
id: String,
message: String,
message2: String,
message3: String,
message4: String,
message5: String
) {
when {
id == "__internalReplayClipboardCopy" -> copy(id, message)
id.startsWith("__internalReplayStorageGetItem") -> getItem(id, message)
id.startsWith("__internalReplayStorageRemoveItem") -> removeItem(id, message)
id.startsWith("__internalReplayStorageSetItem") -> setItem(id, message, message2)
id == "__internalReplayAlertOk" ->
replayContext.showOkDialog(message) { replayContext.jsBridge(id, "") }
id == "__internalReplayAlertOkCancel" ->
replayContext.showOkCancelDialog(message) { replayContext.jsBridge(id, if (it) { "true" } else { "false" }) }
else -> {
replayContext.onJsCallback(id, message, message2, message3, message4, message5)
}
}
}
// -- Clipboard
private fun copy(messageId: String, text: String) {
val clipboard = replayContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText("Copy", text)
clipboard.setPrimaryClip(clip);
replayContext.jsBridge(messageId, "")
}
// -- Storage
private fun getItem(messageId: String, key: String) {
Thread {
try {
replayContext.openFileInput(key).bufferedReader().use { text ->
val value = text.readText()
replayContext.jsBridge(messageId, "{ value: `${value}` }")
}
} catch (e: Exception) {
when (e) {
is FileNotFoundException -> replayContext.jsBridge(messageId, "{ value: null }")
else -> replayContext.jsBridge(messageId, "{ error: `${e.localizedMessage}` }")
}
}
}.start()
}
private fun removeItem(messageId: String, key: String) {
Thread {
try {
val didDelete = replayContext.deleteFile(key)
if (didDelete) {
replayContext.jsBridge(messageId, "")
} else {
replayContext.jsBridge(messageId, "`Couldn't delete file`")
}
} catch (e: Exception) {
replayContext.jsBridge(messageId, "`${e.localizedMessage}`")
}
}.start()
}
private fun setItem(messageId: String, key: String, value: String) {
Thread {
try {
replayContext.openFileOutput(key, Context.MODE_PRIVATE).use { output ->
output.write(value.toByteArray())
replayContext.jsBridge(messageId, "")
}
} catch (e: Exception) {
replayContext.jsBridge(messageId, "`${e.localizedMessage}`")
}
}.start()
}
}
| 9
|
TypeScript
|
8
| 293
|
457c666fe9868ec31026273966ac27e33ebae94e
| 3,291
|
replay
|
MIT License
|
plugins/kotlin/idea/tests/testData/intentions/addNamesInCommentToJavaCallArguments/partialNameComments2.kt
|
ingokegel
| 72,937,917
| true
| null |
fun test(j: Java) {
j.test<caret>(/* foo = */ 1, 2, /* baz = */ 3)
}
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 72
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/jhb/crosswordScan/ui/common/CrosswordAppUiState.kt
|
jhb123
| 621,945,622
| false
| null |
package com.jhb.crosswordScan.ui.common
data class CrosswordAppUiState(
val pageTitle : String,
val darkMode : Boolean = false,
val puzzleSearchShown : Boolean = false
)
| 9
|
Kotlin
|
0
| 2
|
17c8919b06729e7ae7bcbd0a2e7e7e333b5a7f12
| 183
|
crossword-scan-app
|
MIT License
|
test-echo/def/src/commonMain/kotlin/test/echo/def/def.kt
|
kotlin-everywhere
| 368,894,676
| false
| null |
package test.echo.def
import org.kotlin.everywhere.net.Kenet
class Def : Kenet() {
val echo by c<String, String>()
}
| 4
|
Kotlin
|
9
| 13
|
087fed6fead77d7ec2fc087608ae3095efd3d852
| 122
|
kenet
|
MIT License
|
meistercharts-canvas/src/commonMain/kotlin/com/meistercharts/canvas/DevicePixelRatioSupport.kt
|
Neckar-IT
| 599,079,962
| false
|
{"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114}
|
/**
* Copyright 2023 Neckar IT GmbH, Mössingen, Germany
*
* 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.meistercharts.canvas
import it.neckar.open.observable.ObservableDouble
import it.neckar.open.observable.ReadOnlyObservableDouble
import it.neckar.logging.Logger
import it.neckar.logging.LoggerFactory
import it.neckar.logging.debug
/**
* Contains methods related to the device pixel ratio.
*/
class DevicePixelRatioSupport {
private val logger: Logger = LoggerFactory.getLogger("com.meistercharts.canvas.DevicePixelRatioSupport")
/**
* The device pixel ratio
*/
val devicePixelRatioProperty: ReadOnlyObservableDouble = ObservableDouble(1.0).also {
it.consumeImmediately {
logger.debug { "devicePixelRatio set to $it" }
}
}
/**
* The device pixel ratio
*/
val devicePixelRatio: Double by devicePixelRatioProperty
/**
* Updates the device pixel ratio.
* This method will only be called from the LayerSupport
*/
fun updateDevicePixelRatio(devicePixelRatio: Double) {
(devicePixelRatioProperty as ObservableDouble).value = devicePixelRatio
}
}
| 3
|
Kotlin
|
3
| 5
|
ed849503e845b9d603598e8d379f6525a7a92ee2
| 1,633
|
meistercharts
|
Apache License 2.0
|
idea/testData/multiModuleLineMarker/transitive/base_common/common.kt
|
JakeWharton
| 99,388,807
| true
| null |
expect fun <lineMarker descr="Has actuals in JVM">foo</lineMarker>(): Int
| 0
|
Kotlin
|
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 73
|
kotlin
|
Apache License 2.0
|
sources/js/values/BackgroundRepeat.kt
|
cybernetics
| 323,978,300
| true
|
{"Kotlin": 245088}
|
@file:Suppress("NOTHING_TO_INLINE")
package io.fluidsonic.css
// FIXME support multiple values
public external interface BackgroundRepeat : CssValue {
@Suppress("INLINE_EXTERNAL_DECLARATION", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", "WRONG_BODY_OF_EXTERNAL_DECLARATION")
public companion object {
@CssDsl
public inline val noRepeat: BackgroundRepeat
get() = Axis.noRepeat
@CssDsl
public inline val repeat: BackgroundRepeat
get() = Axis.repeat
@CssDsl
public inline val repeatX: BackgroundRepeat
get() = unsafe("repeat-x")
@CssDsl
public inline val repeatY: BackgroundRepeat
get() = unsafe("repeat-y")
@CssDsl
public inline val round: BackgroundRepeat
get() = Axis.round
@CssDsl
public inline val space: BackgroundRepeat
get() = Axis.space
public inline fun unsafe(value: String): BackgroundRepeat =
CssValue.unsafe(value)
public inline fun variable(name: String): Variable =
CssVariable.unsafe(name)
public inline fun with(x: Axis, y: Axis): BackgroundRepeat =
unsafe("$x $y")
}
public interface Axis : BackgroundRepeat {
@Suppress("INLINE_EXTERNAL_DECLARATION", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", "WRONG_BODY_OF_EXTERNAL_DECLARATION")
public companion object {
@CssDsl
public inline val noRepeat: Axis
get() = unsafe("no-repeat")
@CssDsl
public inline val repeat: Axis
get() = unsafe("repeat")
@CssDsl
public inline val round: Axis
get() = unsafe("round")
@CssDsl
public inline val space: Axis
get() = unsafe("space")
public inline fun unsafe(value: String): Axis =
CssValue.unsafe(value)
}
}
public interface Variable : BackgroundRepeat, CssVariable<BackgroundRepeat>
}
@CssDsl
public inline fun CssDeclarationBlockBuilder.backgroundRepeat(value: BackgroundRepeat) {
property(backgroundRepeat, value)
}
@CssDsl
public inline fun CssDeclarationBlockBuilder.backgroundRepeat(x: BackgroundRepeat.Axis, y: BackgroundRepeat.Axis) {
backgroundRepeat(BackgroundRepeat.with(x, y))
}
@Suppress("unused")
public inline val CssProperties.backgroundRepeat: CssProperty<BackgroundRepeat>
get() = CssProperty.unsafe("background-repeat")
| 0
| null |
0
| 0
|
65b9463c57be79f8fcb5e5083df6907340388826
| 2,178
|
fluid-css
|
Apache License 2.0
|
preview/src/main/java/com/unagit/composeplayground/view_preview/OrderView.kt
|
mirokolodii
| 713,840,306
| false
| null |
package com.unagit.composeplayground.view_preview
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import com.unagit.composeplayground.common.R.string
import com.unagit.composeplayground.common.color
import com.unagit.composeplayground.common.dpToPx
import com.unagit.composeplayground.common.drawable
import com.unagit.composeplayground.preview.R
import com.unagit.composeplayground.preview.databinding.ViewOrderBinding
import com.unagit.composeplayground.view_preview.Status.COMPLETE
import com.unagit.composeplayground.view_preview.Status.DRAFT
import com.unagit.composeplayground.view_preview.Status.IN_PROGRESS
class OrderView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {
private val binding = ViewOrderBinding.inflate(LayoutInflater.from(context), this)
init {
setPadding(context.dpToPx(16))
background = context.drawable(R.drawable.background_info_view)
}
fun init(status: Status, items: Map<String, String>) {
initItems(items)
initLabel(status)
initButton(status)
}
private fun initItems(items: Map<String, String>) {
var topViewId = binding.title.id
items.forEach { item ->
val textView = TextView(context).apply {
id = generateViewId()
text = context.getString(string.item_description, item.key, item.value)
setTextColor(context.color(R.color.primary))
setTextAppearance(R.style.TextNormal)
}
addView(textView)
setConstraints(view = textView, topViewId = topViewId)
topViewId = textView.id
}
}
private fun initLabel(status: Status) {
@StringRes val text: Int
@ColorRes val backgroundColorRes: Int
@DrawableRes val iconRes: Int
when (status) {
DRAFT -> {
text = string.draft
backgroundColorRes = R.color.draft
iconRes = R.drawable.ic_line_circle
}
IN_PROGRESS -> {
text = string.in_progress
backgroundColorRes = R.color.in_progress
iconRes = R.drawable.ic_arrow_circle_right
}
COMPLETE -> {
text = string.complete
backgroundColorRes = R.color.complete
iconRes = R.drawable.ic_check_circle
}
}
binding.apply {
label.text = context.getString(text)
label.backgroundTintList = ColorStateList.valueOf(context.color(backgroundColorRes))
label.setCompoundDrawablesWithIntrinsicBounds(iconRes, 0, 0, 0)
}
}
private fun initButton(status: Status) = when (status) {
DRAFT -> binding.button.text = context.getString(string.create)
IN_PROGRESS -> binding.button.text = context.getString(string.open)
COMPLETE -> binding.button.isVisible = false
}
private fun setConstraints(view: View, topViewId: Int) {
val constraintSet = ConstraintSet().apply {
clone(this@OrderView)
connect(view.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START)
connect(view.id, ConstraintSet.TOP, topViewId, ConstraintSet.BOTTOM, context.dpToPx(8))
}
constraintSet.applyTo(this)
}
}
enum class Status {
DRAFT, IN_PROGRESS, COMPLETE
}
@Preview
@Composable
fun CustomViewPreview(
@PreviewParameter(ViewStateProvider::class) params: PreviewParams,
) {
AndroidView(
modifier = Modifier
.fillMaxWidth()
.background(Color.White)
.padding(8.dp),
factory = { context ->
OrderView(context).apply {
init(params.status, params.items)
}
},
)
}
class ViewStateProvider : PreviewParameterProvider<PreviewParams> {
override val values: Sequence<PreviewParams> = buildList {
Status.entries.forEachIndexed { index, status ->
add(PreviewParams(status = status, items = previewItems[index]))
}
}.asSequence()
}
class PreviewParams(
val status: Status,
val items: Map<String, String>,
)
private val previewItems = listOf(
mapOf(
"Dimension" to "34x12x8",
),
mapOf(
"Display" to "6.4 inches",
"Resolution" to "1080x2340"
),
mapOf(
"OS" to "Android 10",
"Main camera" to "50 MP, f/1.8",
"Selfie camera" to "32 MP, f/2.2",
),
)
| 0
| null |
0
| 1
|
b425bfe561855dd6ed50e464ed1bf06f59a77842
| 5,533
|
AndroidComposePlayground
|
Apache License 2.0
|
app/src/main/java/com/snakydesign/clock/ClockActivity.kt
|
adibfara
| 245,678,172
| false
| null |
package com.snakydesign.clock
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.Composable
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import androidx.ui.animation.Transition
import androidx.ui.core.Alignment
import androidx.ui.core.Draw
import androidx.ui.core.Text
import androidx.ui.core.setContent
import androidx.ui.geometry.Offset
import androidx.ui.graphics.Canvas
import androidx.ui.graphics.Color
import androidx.ui.graphics.Paint
import androidx.ui.graphics.PaintingStyle
import androidx.ui.layout.*
import androidx.ui.material.MaterialTheme
import androidx.ui.material.darkColorPalette
import androidx.ui.text.TextStyle
import androidx.ui.tooling.preview.Preview
import androidx.ui.unit.*
import java.util.*
import kotlin.math.ceil
import kotlin.math.cos
import kotlin.math.floor
import kotlin.math.sin
class ClockActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
DefaultPreview()
}
}
}
}
@Preview
@Composable
fun DefaultPreview() {
MaterialTheme() {
Stack() {
ComposeClock()
Align(alignment = Alignment.BottomLeft) {
Column {
Text(
modifier = LayoutPadding(Dp(16f)),
text = "Compose Clock",
style = TextStyle(Color.White)
)
Text(
modifier = LayoutPadding(Dp(16f)),
text = "github.com/adibfara/ComposeClock",
style = TextStyle(Color.White, TextUnit.Companion.Sp(12f))
)
}
}
}
}
}
| 1
|
Kotlin
|
31
| 371
|
ab0b3a275313e6e06ccce96bc59bea976e84c1d0
| 1,858
|
ComposeClock
|
Apache License 2.0
|
examples/sample-protoc-plugin/src/main/kotlin/App.kt
|
Dogacel
| 674,802,209
| false
| null |
import custom.pkg.protos.Node
import custom.pkg.protos.NodeStatus
import kotlinx.serialization.encodeToHexString
import kotlinx.serialization.protobuf.ProtoBuf
fun main() {
val myNode =
Node(
id = 100,
name = "Network Node",
tags = listOf("fast", "reliable"),
attributes =
mapOf(
"ip" to "192.168.1.1",
"host" to "9000",
),
status = NodeStatus.ACTIVE,
next =
Node(
id = 200,
name = "Network Node 2",
),
)
println(myNode)
ProtoBuf.encodeToHexString(myNode).also { println(it) }
}
| 12
| null |
1
| 6
|
01de3fd0448d51b01b751d6547dbf27a36dc34bc
| 726
|
kotlinx-protobuf-gen
|
Apache License 2.0
|
libs/pandautils/src/main/java/com/instructure/pandautils/room/appdatabase/entities/DashboardFileUploadEntity.kt
|
instructure
| 179,290,947
| false
|
{"Kotlin": 16415961, "Dart": 4454406, "HTML": 185120, "Ruby": 35686, "Java": 24752, "Shell": 19157, "Groovy": 11717, "JavaScript": 9505, "Objective-C": 7431, "Python": 2438, "CSS": 1356, "Swift": 807, "Dockerfile": 112}
|
package com.instructure.pandautils.room.appdatabase.entities
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class DashboardFileUploadEntity(
@PrimaryKey
val workerId: String,
val userId: Long,
val title: String?,
val subtitle: String?,
val courseId: Long?,
val assignmentId: Long?,
val attemptId: Long?,
val folderId: Long?
)
| 7
|
Kotlin
|
102
| 127
|
ca6e2aeaeedb851003af5497e64c22e02dbf0db8
| 390
|
canvas-android
|
Apache License 2.0
|
app/src/main/java/ru/beryukhov/coffeegram/model/NavigationStore.kt
|
phansier
| 274,754,270
| false
|
{"Kotlin": 186562, "Ruby": 4091, "Makefile": 1267, "Swift": 584, "Shell": 227}
|
package ru.beryukhov.coffeegram.model
import kotlinx.coroutines.flow.MutableStateFlow
import org.threeten.bp.LocalDate
import org.threeten.bp.YearMonth
import ru.beryukhov.coffeegram.store_lib.InMemoryStore
class NavigationStore(val yearMonth: YearMonth = YearMonth.now()) : InMemoryStore<NavigationIntent, NavigationState>(
initialState = NavigationState.TablePage(yearMonth = yearMonth)
) {
private val currentYearMonth = MutableStateFlow(YearMonth.now())
override suspend fun handleIntent(intent: NavigationIntent): NavigationState {
return when (intent) {
is NavigationIntent.OpenCoffeeListPage -> NavigationState.CoffeeListPage(
LocalDate.of(
currentYearMonth.value.year,
currentYearMonth.value.month,
intent.dayOfMonth
)
)
is NavigationIntent.SetYearMonth -> NavigationState.TablePage(
setYearMonth(yearMonth = intent.yearMonth)
)
NavigationIntent.ReturnToTablePage -> NavigationState.TablePage(currentYearMonth.value)
NavigationIntent.ToSettingsPage -> NavigationState.SettingsPage
}
}
private fun setYearMonth(yearMonth: YearMonth): YearMonth {
currentYearMonth.value = yearMonth
return currentYearMonth.value
}
}
sealed interface NavigationIntent {
data class OpenCoffeeListPage(val dayOfMonth: Int) : NavigationIntent
data class SetYearMonth(val yearMonth: YearMonth) : NavigationIntent
object ReturnToTablePage : NavigationIntent
object ToSettingsPage : NavigationIntent
}
sealed interface NavigationState {
class TablePage(val yearMonth: YearMonth) : NavigationState
data class CoffeeListPage(val date: LocalDate) : NavigationState
object SettingsPage : NavigationState
}
| 3
|
Kotlin
|
26
| 394
|
4a8cd1dda4be461a83319da4821eb6d86dab9d20
| 1,855
|
Coffeegram
|
Apache License 2.0
|
app/src/main/java/com/jesusrojo/firebasedemo/messaging/MessagingActivity.kt
|
jesusrojo
| 404,888,869
| false
|
{"Kotlin": 77465, "Java": 51180}
|
package com.jesusrojo.firebasedemo.messaging
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import androidx.annotation.NonNull
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.jesusrojo.firebasedemo.databinding.MessagingActivityBinding
import com.jesusrojo.firebasedemo.util.DebugHelp
class MessagingActivity : AppCompatActivity() {
private val myTag = javaClass.simpleName
private lateinit var messagingHelp: MessagingHelp
lateinit var broadcastReceiver: BroadcastReceiver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// UI
val binding = MessagingActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.subscribeButton.setOnClickListener { subscribeToTopic() }
binding.logTokenButton.setOnClickListener { getRegToken() }
// MESSAGING
messagingHelp = MessagingHelp(this){ textUi -> updateUi(binding, textUi) }
messagingHelp.onCreate()
initBroadCastReceiver()
}
override fun onResume() {
super.onResume()
messagingHelp.onResume()
val filter = IntentFilter(MyFirebaseMessagingService.INTENT_ACTION_SEND_MESSAGE)
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, filter)
}
override fun onPause() {
super.onPause()
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
}
private fun initBroadCastReceiver() {
broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
DebugHelp.l(myTag, "onReceive ##")
val msg =
intent.getStringExtra(MyFirebaseMessagingService.INTENT_ACTION_SEND_MESSAGE_PARAM_KEY)
if (msg != null && msg.isNotEmpty()){
showAlertDialog(msg)
} else {
showAlertDialog("FCM message received is empty")
}
}
}
}
private fun getRegToken() {
messagingHelp.getRegToken()
}
private fun subscribeToTopic() {
messagingHelp.subscribeToTopic()
}
//UI
private fun updateUi(binding: MessagingActivityBinding, textUi: String) {
binding.tvMessaging.text = textUi
}
private fun showAlertDialog(message: String) {
AlertDialog.Builder(this)
.setMessage(message)
.setTitle("FirebaseDemo")
.setPositiveButton("OK"){_, _ -> }
.create()
.show()
}
}
| 0
|
Kotlin
|
0
| 0
|
236ed00770398622fe8eeeb8e42663de53d8eb50
| 2,862
|
FirebaseDemo
|
Apache License 2.0
|
src/main/kotlin/com/example/App.kt
|
bastman
| 261,739,082
| false
| null |
/*
* This Kotlin source file was generated by the Gradle 'init' task.
*/
package com.example
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
class App:CliktCommand(help="do sth.") {
private val from by option("-f", "--from", help = "from").required()
private val to by option("-t", "--to", help = "to").required()
override fun run() {
echo("hello from $from to $to")
}
}
fun main(args: Array<String>) {
App().main(args)
}
| 2
|
Kotlin
|
0
| 0
|
ad7aa2e62fb3482e4cca15b1f926fc6cd406a700
| 570
|
kotlin-jdeploy-playground
|
ISC License
|
src/main/kotlin/com/example/App.kt
|
bastman
| 261,739,082
| false
| null |
/*
* This Kotlin source file was generated by the Gradle 'init' task.
*/
package com.example
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
class App:CliktCommand(help="do sth.") {
private val from by option("-f", "--from", help = "from").required()
private val to by option("-t", "--to", help = "to").required()
override fun run() {
echo("hello from $from to $to")
}
}
fun main(args: Array<String>) {
App().main(args)
}
| 2
|
Kotlin
|
0
| 0
|
ad7aa2e62fb3482e4cca15b1f926fc6cd406a700
| 570
|
kotlin-jdeploy-playground
|
ISC License
|
src/main/kotlin/g0701_0800/s0770_basic_calculator_iv/Solution.kt
|
javadev
| 190,711,550
| false
| null |
package g0701_0800.s0770_basic_calculator_iv
// #Hard #String #Hash_Table #Math #Stack #Recursion
// #2023_03_10_Time_222_ms_(100.00%)_Space_39.2_MB_(100.00%)
import java.util.Collections
import java.util.Stack
class Solution {
internal inner class Node {
var mem: MutableMap<List<String>, Int> = HashMap()
fun update(cur: List<String>, cnt: Int) {
Collections.sort(cur)
mem[cur] = mem.getOrDefault(cur, 0) + cnt
}
fun add(cur: Node): Node {
val ans = Node()
for (key1 in mem.keys) {
ans.update(key1, mem[key1]!!)
}
for (key2 in cur.mem.keys) {
ans.update(key2, cur.mem[key2]!!)
}
return ans
}
fun sub(cur: Node): Node {
val ans = Node()
for (key1 in mem.keys) {
ans.update(key1, mem[key1]!!)
}
for (key2 in cur.mem.keys) {
ans.update(key2, -cur.mem[key2]!!)
}
return ans
}
fun mul(cur: Node): Node {
val ans = Node()
for (key1 in mem.keys) {
for (key2 in cur.mem.keys) {
val next: MutableList<String> = ArrayList()
next.addAll(key1)
next.addAll(key2)
ans.update(next, mem[key1]!! * cur.mem[key2]!!)
}
}
return ans
}
fun evaluate(vars: Map<String?, Int>): Node {
val ans = Node()
for (cur in mem.keys) {
var cnt = mem[cur]!!
val free: MutableList<String> = ArrayList()
for (tmp in cur) {
if (vars.containsKey(tmp)) {
cnt *= vars[tmp]!!
} else {
free.add(tmp)
}
}
ans.update(free, cnt)
}
return ans
}
fun toList(): List<String> {
val ans: MutableList<String> = ArrayList()
val keys: List<List<String>> = ArrayList(mem.keys)
Collections.sort(
keys
) { a: List<String>, b: List<String> ->
if (a.size != b.size) {
return@sort b.size - a.size
}
for (i in a.indices) {
if (a[i].compareTo(b[i]) != 0) {
return@sort a[i].compareTo(b[i])
}
}
0
}
for (key in keys) {
if (mem[key] == 0) {
continue
}
var cur = "" + mem[key].toString()
for (data in key) {
cur += "*"
cur += data
}
ans.add(cur)
}
return ans
}
}
private fun make(cur: String): Node {
val ans: Node = Node()
val tmp: MutableList<String> = ArrayList()
if (Character.isDigit(cur[0])) {
ans.update(tmp, Integer.valueOf(cur))
} else {
tmp.add(cur)
ans.update(tmp, 1)
}
return ans
}
private fun getNext(expression: String, start: Int): Int {
var end = start
while (end < expression.length && Character.isLetterOrDigit(expression[end])) {
end++
}
return end - 1
}
private fun getPriority(a: Char): Int {
if (a == '+' || a == '-') {
return 1
} else if (a == '*') {
return 2
}
return 0
}
private fun helper(numS: Stack<Node>, ops: Stack<Char>): Node {
val b = numS.pop()
val a = numS.pop()
val op = ops.pop()
if (op == '*') {
return a.mul(b)
} else if (op == '+') {
return a.add(b)
}
return a.sub(b)
}
fun basicCalculatorIV(expression: String?, evalvarS: Array<String?>?, evalintS: IntArray?): List<String> {
val ans: List<String> = ArrayList()
if (expression.isNullOrEmpty() || evalvarS == null || evalintS == null) {
return ans
}
val vars: MutableMap<String?, Int> = HashMap()
for (i in evalvarS.indices) {
vars[evalvarS[i]] = evalintS[i]
}
val n = expression.length
val numS = Stack<Node>()
val ops = Stack<Char>()
var i = 0
while (i < n) {
val a = expression[i]
if (Character.isLetterOrDigit(a)) {
val end = getNext(expression, i)
val cur = expression.substring(i, end + 1)
i = end
val now = make(cur)
numS.add(now)
} else if (a == '(') {
ops.add(a)
} else if (a == ')') {
while (ops.peek() != '(') {
numS.add(helper(numS, ops))
}
ops.pop()
} else if (a == '+' || a == '-' || a == '*') {
while (ops.isNotEmpty() && getPriority(ops.peek()) >= getPriority(a)) {
numS.add(helper(numS, ops))
}
ops.add(a)
}
i++
}
while (ops.isNotEmpty()) {
numS.add(helper(numS, ops))
}
return numS.peek().evaluate(vars).toList()
}
}
| 1
| null |
6
| 43
|
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
| 5,522
|
LeetCode-in-Kotlin
|
MIT License
|
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/back/moon/Yachiyo.kt
|
qwewqa
| 390,928,568
| false
| null |
package xyz.qwewqa.relive.simulator.core.presets.dress.back.moon
import xyz.qwewqa.relive.simulator.core.presets.condition.MoonOnlyCondition
import xyz.qwewqa.relive.simulator.core.presets.dress.generated.dress4050016
import xyz.qwewqa.relive.simulator.core.stage.Act
import xyz.qwewqa.relive.simulator.core.stage.actor.ActType
import xyz.qwewqa.relive.simulator.core.stage.actor.CountableBuff
import xyz.qwewqa.relive.simulator.core.stage.autoskill.new
import xyz.qwewqa.relive.simulator.core.stage.buff.BuffCategory
import xyz.qwewqa.relive.simulator.core.stage.buff.CriticalUpBuff
import xyz.qwewqa.relive.simulator.core.stage.buff.DexterityUpBuff
import xyz.qwewqa.relive.simulator.core.stage.dress.blueprint
import xyz.qwewqa.relive.simulator.core.stage.passive.*
val CourtChampionYachiyo = dress4050016(
name = "<NAME>",
acts = listOf(
ActType.Act1.blueprint("Strike of Brilliance") {
Act {
targetBack().act {
attack(
modifier = values1,
hitCount = 1,
)
}
targetSelf().act {
addBrilliance(values2)
}
}
},
ActType.Act2.blueprint("Courage Strike") {
// TODO: Count. cleanse
Act {
targetBack().act {
attack(
modifier = values1,
hitCount = 1,
)
}
}
},
ActType.Act3.blueprint("Encouraging Strike") {
Act {
targetBack().act {
attack(
modifier = values1,
hitCount = 1,
)
}
targetAllyAoe().act {
addBrilliance(values2)
}
}
},
ActType.ClimaxAct.blueprint("Ranbu Strike") {
Act {
targetSelf().act {
applyCountableBuff(
effect = CountableBuff.Revive,
count = times1,
)
applyBuff(
effect = DexterityUpBuff,
value = values2,
turns = times2,
)
applyBuff(
effect = CriticalUpBuff,
value = values3,
turns = times3,
)
}
targetAoe().act {
dispelTimed(BuffCategory.Positive)
}
targetAnyRandom(10).act {
attack(
modifier = values5,
hitCount = 10,
)
applyCountableBuff(
CountableBuff.Daze,
chance = 33,
)
}
}
},
),
autoSkills = listOf(
listOf(
SelfReviveBuffPassive.new(50, 1),
SelfFortitudeBuffPassive.new(time = 4),
),
listOf(
TeamHpUpPassive.new(30),
),
listOf(
DexterityPassive.new(30),
),
),
unitSkill = ActCritical50UnitSkill + MoonOnlyCondition,
)
| 0
| null |
11
| 7
|
70e1cfaee4c2b5ab4deff33b0e4fd5001c016b74
| 3,402
|
relight
|
MIT License
|
layout-inspector/testSrc/com/android/tools/idea/layoutinspector/runningdevices/ToggleLayoutInspectorActionTest.kt
|
JetBrains
| 60,701,247
| false
|
{"Kotlin": 43855938, "Java": 36698280, "HTML": 1216565, "Starlark": 735324, "C++": 216476, "Python": 101594, "C": 71515, "Lex": 66026, "NSIS": 58516, "AIDL": 32502, "Shell": 28591, "CMake": 21034, "JavaScript": 18437, "Batchfile": 7774, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
|
/*
* Copyright (C) 2023 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.android.tools.idea.layoutinspector.runningdevices
import com.android.testutils.MockitoKt.any
import com.android.testutils.MockitoKt.mock
import com.android.testutils.MockitoKt.whenever
import com.android.tools.idea.streaming.AbstractDisplayView
import com.android.tools.idea.streaming.DISPLAY_VIEW_KEY
import com.android.tools.idea.streaming.SERIAL_NUMBER_KEY
import com.android.tools.idea.streaming.STREAMING_CONTENT_PANEL_KEY
import com.android.tools.idea.streaming.emulator.EmulatorViewRule
import com.google.common.truth.Truth.assertThat
import com.intellij.ide.ui.customization.CustomActionsSchema
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.EdtRule
import com.intellij.testFramework.RunsInEdt
import com.intellij.testFramework.replaceService
import com.intellij.util.ui.components.BorderLayoutPanel
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import javax.swing.JPanel
@RunsInEdt
class ToggleLayoutInspectorActionTest {
@get:Rule
val edtRule = EdtRule()
@get:Rule
val applicationRule = ApplicationRule()
@get:Rule
val displayViewRule = EmulatorViewRule()
private lateinit var fakeLayoutInspectorManager: FakeLayoutInspectorManager
private lateinit var displayView: AbstractDisplayView
private lateinit var tab1: TabInfo
@Before
fun setUp() {
tab1 = TabInfo(TabId("tab1"), JPanel(), JPanel(), displayViewRule.newEmulatorView())
// replace ToolWindowManager with fake one
displayViewRule.project.replaceService(
ToolWindowManager::class.java,
FakeToolWindowManager(displayViewRule.project, listOf(tab1)),
displayViewRule.testRootDisposable
)
displayView = displayViewRule.newEmulatorView()
// replace CustomActionsSchema with mocked one
val mockCustomActionSchema = mock<CustomActionsSchema>()
whenever(mockCustomActionSchema.getCorrectedAction(any())).thenAnswer { getFakeAction() }
ApplicationManager.getApplication().replaceService(CustomActionsSchema::class.java, mockCustomActionSchema, displayViewRule.testRootDisposable)
// replace LayoutInspectorManager with fake one
fakeLayoutInspectorManager = FakeLayoutInspectorManager()
displayViewRule.project.replaceService(LayoutInspectorManager::class.java, fakeLayoutInspectorManager, displayViewRule.testRootDisposable)
}
@Test
fun testActionPerformedTogglesLayoutInspector() {
val toggleLayoutInspectorAction = ToggleLayoutInspectorAction()
val fakeActionEvent = toggleLayoutInspectorAction.getFakeActionEvent()
toggleLayoutInspectorAction.actionPerformed(fakeActionEvent)
assertThat(fakeLayoutInspectorManager.toggleLayoutInspectorInvocations).isEqualTo(1)
assertThat(fakeLayoutInspectorManager.isEnabled).isTrue()
toggleLayoutInspectorAction.actionPerformed(fakeActionEvent)
assertThat(fakeLayoutInspectorManager.toggleLayoutInspectorInvocations).isEqualTo(2)
assertThat(fakeLayoutInspectorManager.isEnabled).isFalse()
}
private fun AnAction.getFakeActionEvent(): AnActionEvent {
val contentPanelContainer = JPanel()
val contentPanel = BorderLayoutPanel()
contentPanelContainer.add(contentPanel)
val dataContext = DataContext {
when (it) {
CommonDataKeys.PROJECT.name -> displayViewRule.project
SERIAL_NUMBER_KEY.name -> "serial_number"
STREAMING_CONTENT_PANEL_KEY.name -> contentPanel
DISPLAY_VIEW_KEY.name -> displayView
else -> null
}
}
return AnActionEvent.createFromAnAction(this, null, "", dataContext)
}
private fun getFakeAction(): AnAction {
return object : AnAction() {
override fun actionPerformed(e: AnActionEvent) { }
}
}
private class FakeLayoutInspectorManager : LayoutInspectorManager {
var isEnabled = false
var toggleLayoutInspectorInvocations = 0
override fun addStateListener(listener: LayoutInspectorManager.StateListener) { }
override fun enableLayoutInspector(tabId: TabId, enable: Boolean) {
toggleLayoutInspectorInvocations += 1
isEnabled = enable
}
override fun isEnabled(tabId: TabId) = isEnabled
}
}
| 2
|
Kotlin
|
230
| 876
|
9c0a89784cca3c01ab99cf251b71a26cdb87cc47
| 5,096
|
android
|
Apache License 2.0
|
ScooterSharing/app/src/main/java/dk/itu/moapd/scootersharing/tokj/Model/Scooter.kt
|
tkjelds
| 592,353,450
| false
| null |
/**
* MIT License
Copyright (c) 2023 <NAME> <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package dk.itu.moapd.scootersharing.tokj.Model
import java.text.SimpleDateFormat
import java.util.Date
/**
* A data class of a Scooter.
*
* This is only used for storing data, and providing a simple toString method.
* @param name Represents the name of the scooter
* @param location Represents the location of the scooter
*/
data class Scooter(val name: String, var location: String, var timestamp: Long) {
/**
* @return Returns a formated string the of the scooter.
*/
override fun toString(): String {
return "ScooterId = $name , ScooterLocation = $location, TimeStamp = ${convertLongToTime()}."
}
fun convertLongToTime(): String {
val date = Date(this.timestamp)
val format = SimpleDateFormat("yyyy.MM.dd HH:mm")
return format.format(date)
}
}
| 0
|
Kotlin
|
0
| 0
|
044365481265611f0eab7ad443a5d4738180ab1e
| 1,898
|
MOAPD23
|
MIT License
|
src/HTMLBuilder/src/kotlinx/html/HtmlHead.kt
|
JetBrains
| 7,543,871
| false
| null |
package kotlinx.html
fun HTML.head(init: HEAD.() -> Unit) = build(HEAD(this), init)
fun HEAD.title(init: TITLE.() -> Unit = { }) = build(TITLE(this), init)
fun HEAD.title(text: String) {
build(TITLE(this), { +text })
}
fun HEAD.link(href: Link, rel: String = "stylesheet", mimeType: String = "text/css", content: _LINK.() -> Unit = { }) {
val tag = build(_LINK(this), content)
tag.href = href
tag.rel = rel
tag.mimeType = mimeType
}
fun HEAD.meta(name: String, content: String) {
val tag = build(META(this), { })
tag.name = name
tag.content = content
}
fun HEAD.base(href: String, target: String) {
val tag = build(BASE(this), { })
tag.href = href
tag.target = target
}
fun HtmlTag.script(src: Link, mimeType: String = "text/javascript") {
val tag = build(SCRIPTSRC(this), { })
tag.src = src
tag.mimeType = mimeType
}
fun HtmlTag.javascript(src: Link) = script(src, "text/javascript")
fun HtmlTag.javascript(content: SCRIPTBLOCK.() -> Unit) = script("text/javascript", content)
fun HtmlTag.script(mimeType: String = "text/javascript", content: SCRIPTBLOCK.() -> Unit) {
val tag = build(SCRIPTBLOCK(this), content)
tag.mimeType = mimeType
}
class HEAD(containingTag: HTML) : HtmlTag(containingTag, "head") {
}
class META(containingTag: HEAD) : HtmlTag(containingTag, "meta") {
public var name: String by Attributes.name
public var content: String by StringAttribute("content")
}
class BASE(containingTag: HEAD) : HtmlTag(containingTag, "base") {
public var href: String by StringAttribute("href")
public var target: String by StringAttribute("target")
}
class _LINK(containingTag: HEAD) : HtmlTag(containingTag, "link", RenderStyle._empty) {
public var href: Link by Attributes.href
public var rel: String by Attributes.rel
public var mimeType: String by Attributes.mimeType
{
rel = "stylesheet"
mimeType = "text/css"
}
}
class SCRIPTSRC(containingTag: HtmlTag) : HtmlTag(containingTag, "script") {
public var src: Link by Attributes.src
public var mimeType: String by Attributes.mimeType
{
mimeType = "text/javascript"
}
}
class SCRIPTBLOCK(containingTag: HtmlTag) : HtmlTag(containingTag, "script") {
public var mimeType: String by Attributes.mimeType
{
mimeType = "text/javascript"
}
}
class TITLE(containingTag: HEAD) : HtmlTag(containingTag, "title") {
}
| 4
| null |
70
| 77
|
45dbdaadf2676eaede6e77068a1ad20010629ed1
| 2,435
|
kara
|
Apache License 2.0
|
src/main/kotlin/io/zhudy/duic/server/Application.kt
|
xcorp1986
| 128,421,929
| true
|
{"Kotlin": 89327, "Vue": 58575, "JavaScript": 9039, "HTML": 764, "CSS": 34}
|
package io.zhudy.duic.server
import com.auth0.jwt.algorithms.Algorithm
import io.zhudy.duic.Config
import org.springframework.boot.Banner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration
import org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration
import org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration
import org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration
import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
import org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.runApplication
import org.springframework.cache.concurrent.ConcurrentMapCacheManager
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
import org.springframework.data.mongodb.MongoDbFactory
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper
import org.springframework.data.mongodb.core.convert.MappingMongoConverter
import org.springframework.data.mongodb.core.convert.MongoCustomConversions
import org.springframework.data.mongodb.core.mapping.MongoMappingContext
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
/**
* @author <NAME> (<EMAIL>)
*/
@SpringBootApplication(exclude = [
RestTemplateAutoConfiguration::class,
ErrorWebFluxAutoConfiguration::class,
CodecsAutoConfiguration::class,
PersistenceExceptionTranslationAutoConfiguration::class,
TransactionAutoConfiguration::class,
ValidationAutoConfiguration::class])
@ComponentScan("io.zhudy.duic")
@EnableConfigurationProperties(Config::class)
@EnableReactiveMongoRepositories
class Application {
@Bean
fun mongoConverter(factory: MongoDbFactory): MappingMongoConverter {
val dbRefResolver = DefaultDbRefResolver(factory)
val conversions = MongoCustomConversions(emptyList<Any>())
val mappingContext = MongoMappingContext()
mappingContext.setSimpleTypeHolder(conversions.simpleTypeHolder)
mappingContext.afterPropertiesSet()
val converter = MappingMongoConverter(dbRefResolver, mappingContext)
converter.setCustomConversions(conversions)
converter.typeMapper = DefaultMongoTypeMapper(null)
converter.afterPropertiesSet()
return converter
}
@Bean
fun passwordEncoder() = BCryptPasswordEncoder()
@Bean
fun jwtAlgorithm(config: Config): Algorithm = Algorithm.HMAC256(Config.jwt.secret)
@Bean
fun cacheManager() = ConcurrentMapCacheManager()
companion object {
@JvmStatic
fun main(args: Array<String>) {
runApplication<Application>(*args) {
setBannerMode(Banner.Mode.LOG)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
05a6b3ce48b2ad57e8ff281eb176b31a5ed5c4c4
| 3,157
|
duic
|
Apache License 2.0
|
LoggingManager.kt
|
Couchbase-Ecosystem
| 849,511,380
| false
|
{"Kotlin": 19031}
|
package cbl.js.kotiln
import com.couchbase.lite.*
import java.util.EnumSet
object LoggingManager {
fun setLogLevel(logDomain: String, logLevel: Int) {
when (logDomain) {
"ALL" -> Database.log.console.domains = LogDomain.ALL_DOMAINS
"DATABASE" -> Database.log.console.domains = EnumSet.of(LogDomain.DATABASE)
"NETWORK" -> Database.log.console.domains = EnumSet.of(LogDomain.NETWORK)
"QUERY" -> Database.log.console.domains = EnumSet.of(LogDomain.QUERY)
"REPLICATOR" -> Database.log.console.domains = EnumSet.of(LogDomain.REPLICATOR)
}
val loggingValue = getLogLevel(logLevel)
Database.log.console.level = loggingValue
}
fun getLogLevel(logLevelValue: Int): LogLevel {
when (logLevelValue) {
0 -> return LogLevel.DEBUG
1 -> return LogLevel.VERBOSE
2 -> return LogLevel.INFO
3 -> return LogLevel.WARNING
4 -> return LogLevel.ERROR
5 -> return LogLevel.NONE
}
return LogLevel.DEBUG
}
}
| 0
|
Kotlin
|
0
| 0
|
238673472986f81e3d5a458379f1bbfdbd986feb
| 1,088
|
cbl-js-kotlin
|
Apache License 2.0
|
LoggingManager.kt
|
Couchbase-Ecosystem
| 849,511,380
| false
|
{"Kotlin": 19031}
|
package cbl.js.kotiln
import com.couchbase.lite.*
import java.util.EnumSet
object LoggingManager {
fun setLogLevel(logDomain: String, logLevel: Int) {
when (logDomain) {
"ALL" -> Database.log.console.domains = LogDomain.ALL_DOMAINS
"DATABASE" -> Database.log.console.domains = EnumSet.of(LogDomain.DATABASE)
"NETWORK" -> Database.log.console.domains = EnumSet.of(LogDomain.NETWORK)
"QUERY" -> Database.log.console.domains = EnumSet.of(LogDomain.QUERY)
"REPLICATOR" -> Database.log.console.domains = EnumSet.of(LogDomain.REPLICATOR)
}
val loggingValue = getLogLevel(logLevel)
Database.log.console.level = loggingValue
}
fun getLogLevel(logLevelValue: Int): LogLevel {
when (logLevelValue) {
0 -> return LogLevel.DEBUG
1 -> return LogLevel.VERBOSE
2 -> return LogLevel.INFO
3 -> return LogLevel.WARNING
4 -> return LogLevel.ERROR
5 -> return LogLevel.NONE
}
return LogLevel.DEBUG
}
}
| 0
|
Kotlin
|
0
| 0
|
238673472986f81e3d5a458379f1bbfdbd986feb
| 1,088
|
cbl-js-kotlin
|
Apache License 2.0
|
plugin/src/main/kotlin/com/supercilex/gradle/versions/tasks/ComputeVersionCode.kt
|
SUPERCILEX
| 241,978,640
| false
| null |
package com.supercilex.gradle.versions.tasks
import com.supercilex.gradle.versions.internal.safeCreateNewFile
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.submit
import org.gradle.util.VersionNumber
import org.gradle.workers.WorkAction
import org.gradle.workers.WorkParameters
import org.gradle.workers.WorkerExecutor
import javax.inject.Inject
@CacheableTask
internal abstract class ComputeVersionCode @Inject constructor(
private val executor: WorkerExecutor
) : DefaultTask() {
@get:Input
abstract val versionCodeOffset: Property<Long>
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFile
abstract val commitCountFile: RegularFileProperty
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFile
abstract val tagListFile: RegularFileProperty
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFile
abstract val gitDescribeFile: RegularFileProperty
@get:OutputFile
abstract val versionCodeFile: RegularFileProperty
@TaskAction
fun computeVersions() {
executor.noIsolation().submit(Computer::class) {
offset.set(versionCodeOffset)
commitCount.set(commitCountFile)
tagList.set(tagListFile)
gitDescribe.set(gitDescribeFile)
versionCode.set(versionCodeFile)
}
}
abstract class Computer : WorkAction<Computer.Params> {
override fun execute() {
val commitCountFileContents = parameters.commitCount.get().asFile.readText()
val tagListFileContents = parameters.tagList.get().asFile.readText()
val gitDescribeFileContents = parameters.gitDescribe.get().asFile.readText()
val tags = tagListFileContents.split("\n")
val minorTags = tags.map { VersionNumber.parse(it) }.filter { it.micro == 0 }
val isCleanlyOnTag = gitDescribeFileContents
.removePrefix(tags.lastOrNull().orEmpty()).take(1).length xor 1
val offset = parameters.offset.get()
val commitCount = commitCountFileContents.toLong()
val minorTagsCount = minorTags.size
val hotfixSpacing = (minorTagsCount - isCleanlyOnTag).coerceAtLeast(0) * 100
val versionCode = (offset + commitCount + minorTagsCount + hotfixSpacing).toString()
parameters.versionCode.get().asFile.safeCreateNewFile().writeText(versionCode)
}
interface Params : WorkParameters {
val offset: Property<Long>
val commitCount: RegularFileProperty
val tagList: RegularFileProperty
val gitDescribe: RegularFileProperty
val versionCode: RegularFileProperty
}
}
}
| 0
|
Kotlin
|
3
| 15
|
3c48abdf9cdceac685f0119579865e429fe3b329
| 3,097
|
version-orchestrator
|
Apache License 2.0
|
src/main/java/info/movito/themoviedbapi/model/NetworkMovie.kt
|
afterroot
| 515,607,935
| true
|
{"INI": 2, "Proguard": 1, "Shell": 1, "EditorConfig": 1, "Markdown": 3, "JSON": 3, "Git Attributes": 1, "Batchfile": 1, "Text": 1, "Gradle": 1, "Ignore List": 1, "Java": 72, "Kotlin": 67, "XML": 1, "YAML": 2}
|
/*
* Copyright (c) 2014, <NAME>
* All rights reserved.
*/
package info.movito.themoviedbapi.model
import com.afterroot.tmdbapi.model.Genre
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonTypeInfo
import info.movito.themoviedbapi.TmdbMovies
import info.movito.themoviedbapi.Types
import info.movito.themoviedbapi.model.core.IdElement
import info.movito.themoviedbapi.model.core.MovieKeywords
import info.movito.themoviedbapi.model.core.ResultsPage
import info.movito.themoviedbapi.model.keywords.Keyword
import info.movito.themoviedbapi.model.people.PersonCast
import info.movito.themoviedbapi.model.people.PersonCrew
@JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
data class NetworkMovie(
@JsonProperty("adult") val adult: Boolean? = null,
@JsonProperty("backdrop_path") val backdropPath: String? = null,
@JsonProperty("belongs_to_collection") val belongsToCollection: Collection? = null,
@JsonProperty("budget") val budget: Int? = null,
@JsonProperty("genres")
val genres: List<Genre>? = null,
@JsonProperty("genre_ids")
val genreIds: List<Int>? = null,
@JsonProperty("homepage")
val homepage: String? = null,
@JsonProperty("imdb_id")
val imdbId: String? = null,
@JsonProperty("original_language")
val originalLanguage: String? = null,
@JsonProperty("original_title")
val originalTitle: String? = null,
@JsonProperty("overview")
val overview: String? = null,
@JsonProperty("popularity")
val popularity: Double? = null,
@JsonProperty("poster_path")
val posterPath: String? = null,
@JsonProperty("production_companies")
val productionCompanies: List<ProductionCompany>? = null,
@JsonProperty("production_countries")
val productionCountries: List<ProductionCountry>? = null,
@JsonProperty("release_date")
val releaseDate: String? = null,
@JsonProperty("revenue")
val revenue: Long? = null,
@JsonProperty("runtime")
val runtime: Int? = null,
@JsonProperty("spoken_languages")
val spokenLanguages: List<Language>? = null,
@JsonProperty("status")
val status: String? = null,
@JsonProperty("tagline")
val tagline: String? = null,
@JsonProperty("title")
val title: String? = null,
@JsonProperty("video")
val video: Boolean? = null,
@JsonProperty("vote_average")
val voteAverage: Double? = null,
@JsonProperty("vote_count")
val voteCount: Int? = null,
@JsonProperty("rating")
var userRating: Float = 0f,
// Appendable responses
@JsonProperty("alternative_titles")
var alternativeTitles: MoviesAlternativeTitles? = null,
@JsonProperty("credits")
var credits: Credits? = null,
@JsonProperty("images")
var images: MovieImages? = null,
@JsonProperty("keywords")
var keywords: MovieKeywords? = null,
@JsonProperty("release_dates")
var releases: TmdbMovies.ReleaseInfoResults? = null,
@JsonProperty("videos")
var videos: Video.Results? = null,
@JsonProperty("translations")
var translations: MovieTranslations? = null,
@JsonProperty("similar")
var similarMovies: ResultsPage<NetworkMovie>? = null,
@JsonProperty("recommendations")
val recommendedMovies: ResultsPage<NetworkMovie>? = null,
@JsonProperty("reviews")
var reviews: ResultsPage<Reviews>? = null,
@JsonProperty("lists")
var lists: ResultsPage<MovieList>? = null,
) : IdElement(), Multi {
override val mediaType: Multi.MediaType
get() = Multi.MediaType.MOVIE
fun alternativeTitles(): List<AlternativeTitle>? = alternativeTitles?.titles
fun cast(): List<PersonCast>? = credits?.cast
fun crew(): List<PersonCrew>? = credits?.crew
fun images(vararg artworkTypes: ArtworkType?): List<Artwork>? = images?.getAll(*artworkTypes)
fun keywords(): List<Keyword>? = keywords?.keywords
fun releases(): List<ReleaseInfo>? = releases?.results
fun videos(): List<Video>? = videos?.videos
fun year(): String? = releaseDate?.substring(0, 4)
companion object {
fun type(): Int {
return Types.MOVIE
}
}
}
| 10
|
Java
|
0
| 0
|
acd954ac3cc211193bda4d90addd22deb672cc4c
| 4,154
|
themoviedbapi
|
BSD 2-Clause with views sentence
|
src/main/java/info/movito/themoviedbapi/model/NetworkMovie.kt
|
afterroot
| 515,607,935
| true
|
{"INI": 2, "Proguard": 1, "Shell": 1, "EditorConfig": 1, "Markdown": 3, "JSON": 3, "Git Attributes": 1, "Batchfile": 1, "Text": 1, "Gradle": 1, "Ignore List": 1, "Java": 72, "Kotlin": 67, "XML": 1, "YAML": 2}
|
/*
* Copyright (c) 2014, <NAME>
* All rights reserved.
*/
package info.movito.themoviedbapi.model
import com.afterroot.tmdbapi.model.Genre
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonTypeInfo
import info.movito.themoviedbapi.TmdbMovies
import info.movito.themoviedbapi.Types
import info.movito.themoviedbapi.model.core.IdElement
import info.movito.themoviedbapi.model.core.MovieKeywords
import info.movito.themoviedbapi.model.core.ResultsPage
import info.movito.themoviedbapi.model.keywords.Keyword
import info.movito.themoviedbapi.model.people.PersonCast
import info.movito.themoviedbapi.model.people.PersonCrew
@JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
data class NetworkMovie(
@JsonProperty("adult") val adult: Boolean? = null,
@JsonProperty("backdrop_path") val backdropPath: String? = null,
@JsonProperty("belongs_to_collection") val belongsToCollection: Collection? = null,
@JsonProperty("budget") val budget: Int? = null,
@JsonProperty("genres")
val genres: List<Genre>? = null,
@JsonProperty("genre_ids")
val genreIds: List<Int>? = null,
@JsonProperty("homepage")
val homepage: String? = null,
@JsonProperty("imdb_id")
val imdbId: String? = null,
@JsonProperty("original_language")
val originalLanguage: String? = null,
@JsonProperty("original_title")
val originalTitle: String? = null,
@JsonProperty("overview")
val overview: String? = null,
@JsonProperty("popularity")
val popularity: Double? = null,
@JsonProperty("poster_path")
val posterPath: String? = null,
@JsonProperty("production_companies")
val productionCompanies: List<ProductionCompany>? = null,
@JsonProperty("production_countries")
val productionCountries: List<ProductionCountry>? = null,
@JsonProperty("release_date")
val releaseDate: String? = null,
@JsonProperty("revenue")
val revenue: Long? = null,
@JsonProperty("runtime")
val runtime: Int? = null,
@JsonProperty("spoken_languages")
val spokenLanguages: List<Language>? = null,
@JsonProperty("status")
val status: String? = null,
@JsonProperty("tagline")
val tagline: String? = null,
@JsonProperty("title")
val title: String? = null,
@JsonProperty("video")
val video: Boolean? = null,
@JsonProperty("vote_average")
val voteAverage: Double? = null,
@JsonProperty("vote_count")
val voteCount: Int? = null,
@JsonProperty("rating")
var userRating: Float = 0f,
// Appendable responses
@JsonProperty("alternative_titles")
var alternativeTitles: MoviesAlternativeTitles? = null,
@JsonProperty("credits")
var credits: Credits? = null,
@JsonProperty("images")
var images: MovieImages? = null,
@JsonProperty("keywords")
var keywords: MovieKeywords? = null,
@JsonProperty("release_dates")
var releases: TmdbMovies.ReleaseInfoResults? = null,
@JsonProperty("videos")
var videos: Video.Results? = null,
@JsonProperty("translations")
var translations: MovieTranslations? = null,
@JsonProperty("similar")
var similarMovies: ResultsPage<NetworkMovie>? = null,
@JsonProperty("recommendations")
val recommendedMovies: ResultsPage<NetworkMovie>? = null,
@JsonProperty("reviews")
var reviews: ResultsPage<Reviews>? = null,
@JsonProperty("lists")
var lists: ResultsPage<MovieList>? = null,
) : IdElement(), Multi {
override val mediaType: Multi.MediaType
get() = Multi.MediaType.MOVIE
fun alternativeTitles(): List<AlternativeTitle>? = alternativeTitles?.titles
fun cast(): List<PersonCast>? = credits?.cast
fun crew(): List<PersonCrew>? = credits?.crew
fun images(vararg artworkTypes: ArtworkType?): List<Artwork>? = images?.getAll(*artworkTypes)
fun keywords(): List<Keyword>? = keywords?.keywords
fun releases(): List<ReleaseInfo>? = releases?.results
fun videos(): List<Video>? = videos?.videos
fun year(): String? = releaseDate?.substring(0, 4)
companion object {
fun type(): Int {
return Types.MOVIE
}
}
}
| 10
|
Java
|
0
| 0
|
acd954ac3cc211193bda4d90addd22deb672cc4c
| 4,154
|
themoviedbapi
|
BSD 2-Clause with views sentence
|
ftc-2021-2022-offseason/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/hardware/CustomElement.kt
|
QubeRomania
| 491,215,964
| false
|
{"Java": 210390, "Kotlin": 52111}
|
package org.firstinspires.ftc.teamcode.hardware
import com.qualcomm.robotcore.hardware.*
import org.firstinspires.ftc.teamcode.hardware.Outtake.Companion.servo1Close
import org.firstinspires.ftc.teamcode.hardware.Outtake.Companion.servo1Open
import org.firstinspires.ftc.teamcode.hardware.Outtake.Companion.servo2Close
class CustomElement(hwMap: HardwareMap) {
val servoClaw = hwMap.servo["customServo1"] ?: throw Exception("Failed to find servo customElementServo1")
val servoArm = hwMap.servo["customServo2"] ?: throw Exception("Failed to find servo customElementServo2")
companion object {
const val servoOpenClaw = 0.60
const val servoCloseClaw = 0.80
const val servoOpenArm = 0.60
const val servoCloseArm = 0.80
const val modifier = 0.03
}
var position = servoCloseClaw
private fun openServoClaw() {
setServoPositionsClaw(servoOpenClaw)
}
fun openServoArm() {
setServoPositionsArm(servoOpenArm)
}
fun closeServoClaw() {
setServoPositionsClaw(servoCloseClaw)
}
fun closeServoArm() {
setServoPositionsArm(servoCloseArm)
}
fun openClaw() {
openServoClaw()
}
fun openArm() {
openServoArm()
}
fun closeClaw() {
closeServoClaw()
}
fun closeArm() {
closeServoArm()
}
fun setServoPositionsClaw(pos: Double) {
servoClaw.position = pos
}
fun setServoPositionsArm(pos: Double) {
servoArm.position = pos
}
fun moveOneUp()
{
position = servoArm.position
position += modifier
if(position > servoCloseArm)
position = servoCloseArm
servoArm.position = position
}
fun moveOneDown()
{
position = servoArm.position
position -= modifier
if(position < servoOpenArm)
position = servoOpenArm
servoArm.position = position
}
fun stop() {
closeClaw()
closeArm()
}
}
| 1
| null |
1
| 1
|
6a19b7460d416fa4bddf442b7ef4dcf539c7ae9b
| 2,023
|
ftc-2021-2022-offseason
|
Apache License 2.0
|
library/src/main/java/com/zhuiyun/library/utils/ByteUtils.kt
|
zhuiyun
| 480,677,598
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 2, "Proguard": 2, "Kotlin": 55, "XML": 55, "INI": 1, "Java": 33}
|
package com.zhuiyun.library.utils
/**
* @author: yun
* @date: 2022/4/12 0012 13
*/
object ByteUtils {
/**
* 十六进制转十进制
*/
fun hextoInt(s: String): Int {
return s.toInt(16)
}
/**
* byte转int
*/
fun byteArrayInt2(low: Byte, high: Byte): Int {
return (high.toInt() and (0xff shl 8) or (low.toInt() and 0xff))
}
/**
* byte 转 int
*/
fun byteArrayLong4(value1: Byte, value2: Byte, value3: Byte, value4: Byte): Long {
return (value1 + value2 * 256 + value3 * 256 * 256 + value4 * 256 * 256 * 256).toLong()
}
/**
* byte[]转String
*/
fun bytesToHexString(src: ByteArray?): String? {
val stringBuilder = StringBuilder("")
if (src == null || src.isEmpty()) {
return null
}
for (i in src.indices) {
val v: Int = src[i].toInt() and 0xFF
val hv = Integer.toHexString(v)
if (hv.length < 2) {
stringBuilder.append(0)
}
stringBuilder.append(hv)
}
return stringBuilder.toString()
}
/**
* ascii码的byte转int
*/
fun hextoInt(byte1: Byte, byte2: Byte): Int? {
return bytesToHex(byte1, byte2)?.toInt(16)
}
/**
* 字节数组转16进制
* @param
* @return 转换后的Hex字符串
*/
fun bytesToHex(byte1: Byte, byte2: Byte): String? {
val sb = StringBuffer()
val hex = Integer.toHexString(byte1.toInt() and 0xFF)
if (hex.length < 2) {
sb.append(0)
} else {
sb.append(hex)
}
val hex2 = Integer.toHexString(byte2.toInt() and 0xFF)
if (hex2.length < 2) {
sb.append(0)
} else {
sb.append(hex2)
}
return sb.toString()
}
/**
* Hex转byte[],两种情况,Hex长度为奇数最后一个字符会被舍去
*/
fun hexTobytes(hex: String): ByteArray? {
return if (hex.isEmpty()) {
null
} else {
val result = ByteArray(hex.length / 2)
var j = 0
var i = 0
while (i < hex.length) {
result[j++] = hex.substring(i, i + 2).toInt(16).toByte()
i += 2
}
result
}
}
fun intToHexString(hex: Int): String? {
return Integer.toHexString(hex)
}
/**
* 有符号的hex转int
* @param byte1
* @param byte2
* @return
*/
fun signedHextoInt(byte1: Byte, byte2: Byte): Int {
return Math.abs(
if (bytesToHex(byte1, byte2)!!.toInt(16) >= 32768) bytesToHex(byte1, byte2)!!
.toInt(16) - 65536 else bytesToHex(byte1, byte2)!!.toInt(16)
)
}
fun signedIntToHex(data: Int): String? {
return if (data > 0) {
Integer.toHexString(data)
} else {
Integer.toHexString(65536 - data)
}
}
}
| 0
|
Java
|
0
| 2
|
d6452d76653c4e3456041d222d1e081e34624cb1
| 2,909
|
UtilLibrary
|
Apache License 2.0
|
android/app/src/main/java/com/jovial/corpsblog/MainActivity.kt
|
zathras
| 73,012,336
| false
|
{"Shell": 5, "Text": 3, "Ignore List": 3, "Git Attributes": 1, "EditorConfig": 1, "Markdown": 13, "JSON": 3, "Kotlin": 67, "Java": 19, "SVG": 16, "XML": 18, "CSS": 16, "JavaScript": 18, "Gradle": 3, "Java Properties": 2, "Batchfile": 1, "Proguard": 1, "JAR Manifest": 1, "HTML": 12}
|
package com.jovial.corpsblog
import android.Manifest
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.ActionBar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import com.jovial.blog.Site
import com.jovial.blog.model.BlogConfig
import com.jovial.os.OSBrowser
import com.jovial.os.Stdout
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.PrintStream
import java.nio.charset.StandardCharsets
import java.util.prefs.Preferences
import android.content.Intent
import android.content.ActivityNotFoundException
import android.net.Uri
import android.webkit.WebView
open private class ViewLookup {
protected fun<T: View> AppCompatActivity.findView(id: Int) : T = findViewById<T>(id)!!
}
class MainActivity : AppCompatActivity() {
private enum class Prefs(val key: String, val default: String) {
SRC_DIR("src_dir", "/sdcard"),
DEST_DIR("dest_dir", "/sdcard");
fun getString(p: SharedPreferences?) : String = p?.getString(key, default) ?: default
fun putString(p: SharedPreferences?, value: String) {
if (p != null) {
with (p.edit()) {
putString(key, value)
commit()
}
}
}
}
private val ui by lazy {
object : ViewLookup() {
val srcDirButton : Button = findView(R.id.srcDirButton)
val srcDirText : TextView = findView(R.id.srcDirText)
val destDirButton : Button = findView(R.id.destDirButton)
val destDirText : TextView = findView(R.id.destDirText)
val publishButton : Button = findView(R.id.publishButton)
val cleanButton : Button = findView(R.id.cleanButton)
val mailButton : Button = findView(R.id.mailButton)
val viewButton : Button = findView(R.id.viewButton)
val outputText : TextView = findView(R.id.outputText)
val outputTextSV : ScrollView = findView(R.id.outputTextSV)
}
}
private enum class RequestID (
val onGranted : (MainActivity) -> Unit
) {
STARTUP( { _ ->
// Do nothing
} ),
SET_SRC_DIR( { activity ->
activity.launchChooseDirectoryDialog(activity.ui.srcDirText, Prefs.SRC_DIR)
}),
SET_DEST_DIR( { activity ->
activity.launchChooseDirectoryDialog(activity.ui.destDirText, Prefs.DEST_DIR)
})
}
private fun launchChooseDirectoryDialog(toSet: TextView, prefToSet: Prefs) {
val dialog = DirectoryChooserDialog(this) { dir: String ->
toSet.text = dir
prefToSet.putString(prefs, dir)
}
dialog.newFolderEnabled = true
dialog.chooseDirectory()
}
private val logListener = { line: String ->
// Note that initial contents of ui.outputText was set at the moment
// we added the listener
runOnUiThread {
ui.outputText.append(line)
ui.outputTextSV.post {
ui.outputTextSV.scrollTo(0, ui.outputText.height)
}
}
}
private var prefs : SharedPreferences? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
OSBrowser.addContext(applicationContext)
val actionBar = supportActionBar!!
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME or ActionBar.DISPLAY_USE_LOGO or ActionBar.DISPLAY_SHOW_TITLE)
actionBar.setLogo(R.mipmap.peace_corps_logo)
setContentView(R.layout.activity_main)
requestPermissions(RequestID.STARTUP)
ui.srcDirButton.setOnClickListener {
requestPermissions(RequestID.SET_SRC_DIR)
}
prefs = getPreferences(MODE_PRIVATE)
ui.srcDirText.text = Prefs.SRC_DIR.getString(prefs)
ui.destDirText.text = Prefs.DEST_DIR.getString(prefs)
ui.destDirButton.setOnClickListener {
requestPermissions(RequestID.SET_DEST_DIR)
}
ui.publishButton.setOnClickListener {
runCorpsblog {
Stdout.println()
generateSite(true)
Stdout.println("Done site generation.")
}
}
ui.cleanButton.setOnClickListener {
runCorpsblog {
Stdout.println()
val site = generateSite(false)
site.deleteStrayFiles()
Stdout.println("Done cleanup.")
}
}
ui.mailButton.setOnClickListener {
runCorpsblog {
Stdout.println()
val site = generateSite(true)
val mgr = site.mailchimpManager
if (mgr == null) {
Stdout.println("NOTE: Mailchimp not configured.")
} else {
mgr.generateNotifications(site)
}
val ifttt = site.iftttManager
if (ifttt == null) {
Stdout.println("NOTE: IFTTT not configured.")
} else {
ifttt.generateNotifications(site)
}
Stdout.println("Done mailing.")
}
}
ui.viewButton.setOnClickListener {
val index = File(ui.destDirText.text.toString(), "index.html")
if (!index.exists()) {
Toast.makeText(
this, "${index.absolutePath} does not exist.", Toast.LENGTH_LONG
).show()
} else {
val intent = Intent(this, ViewBlog::class.java)
intent.putExtra("url", index.toURI().toURL().toString())
startActivity(intent)
}
}
ui.outputText.text = Stdout.addListener(logListener)
logListener("") // Scroll to end
}
private fun generateSite(publish: Boolean) : Site {
val inputDir=File(ui.srcDirText.text.toString())
val blogConfig = BlogConfig(File(inputDir, "corpsblog.config"))
val site = Site(
inputDir=File(ui.srcDirText.text.toString()).canonicalFile,
outputDir=File(ui.destDirText.text.toString()).canonicalFile,
blogConfig = blogConfig,
publishYT=publish
)
site.generate()
site.printNotes()
if (site.hasErrors()) {
site.printErrors()
}
return site
}
private fun setEnabled(enabled: Boolean) {
ui.srcDirButton.isEnabled = enabled
ui.destDirButton.isEnabled = enabled
ui.publishButton.isEnabled = enabled
ui.cleanButton.isEnabled = enabled
ui.mailButton.isEnabled = enabled
ui.viewButton.isEnabled = enabled
}
private fun runCorpsblog(task: () -> Unit) {
setEnabled(false)
val t = Thread({
try {
task()
} catch (t: Throwable) {
val baos = ByteArrayOutputStream()
PrintStream(baos, true, "UTF-8").use { ps -> t.printStackTrace(ps) }
Stdout.println(String(baos.toByteArray())) // Android charset guaranteed to be utf8
t.printStackTrace() // logcat
} finally {
runOnUiThread {
setEnabled(true)
}
}
},"corpsblog task");
t.start()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) : Boolean {
if (item.itemId == R.id.main_menu_quit) {
System.exit(0)
return true // not reached
}
return super.onOptionsItemSelected(item)
}
private fun hasPermission(permission: String) : Boolean =
ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
private fun requestPermissions(id: RequestID) {
if (hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
&& hasPermission(Manifest.permission.INTERNET))
{
id.onGranted(this)
} else {
ActivityCompat.requestPermissions(this, arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.INTERNET
), id.ordinal)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
val granted = permissions.size == 2 && grantResults.all { it == PackageManager.PERMISSION_GRANTED }
if (granted) {
RequestID.values()[requestCode].onGranted(this)
} else if (requestCode == RequestID.STARTUP.ordinal) {
Toast.makeText(
this, "I'll run anyway, but I'll ask for permissions later.",
Toast.LENGTH_LONG
).show()
}
}
override fun onDestroy() {
super.onDestroy()
OSBrowser.removeContext(applicationContext)
Stdout.removeListener(logListener)
}
}
| 1
| null |
1
| 1
|
f3124403377480bfed27e86b645f445dccc86445
| 9,440
|
corpsblog
|
MIT License
|
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/declarations/IrErrorDeclaration.kt
|
JetBrains
| 3,432,266
| 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.ir.declarations
import org.jetbrains.kotlin.ir.visitors.IrElementTransformer
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
abstract class IrErrorDeclaration : IrDeclarationBase() {
override fun <R, D> accept(visitor: IrElementVisitor<R, D>, data: D): R =
visitor.visitErrorDeclaration(this, data)
override fun <D> acceptChildren(visitor: IrElementVisitor<Unit, D>, data: D) {
// no children
}
override fun <D> transformChildren(transformer: IrElementTransformer<D>, data: D) {
// no children
}
}
| 125
| null |
4903
| 39,894
|
0ad440f112f353cd2c72aa0a0619f3db2e50a483
| 1,186
|
kotlin
|
Apache License 2.0
|
increase-kotlin-core/src/test/kotlin/com/increase/api/services/blocking/simulations/AccountStatementServiceTest.kt
|
Increase
| 614,596,742
| false
| null |
// File generated from our OpenAPI spec by Stainless.
package com.increase.api.services.blocking.simulations
import com.increase.api.TestServerExtension
import com.increase.api.client.okhttp.IncreaseOkHttpClient
import com.increase.api.models.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(TestServerExtension::class)
class AccountStatementServiceTest {
@Test
fun callCreate() {
val client =
IncreaseOkHttpClient.builder()
.baseUrl(TestServerExtension.BASE_URL)
.apiKey("test-api-key")
.build()
val accountStatementService = client.simulations().accountStatements()
val accountStatement =
accountStatementService.create(
SimulationAccountStatementCreateParams.builder().accountId("string").build()
)
println(accountStatement)
accountStatement.validate()
}
}
| 1
| null |
0
| 5
|
dc1361d08cb41ff45817c2e7638f53356f15cf8e
| 965
|
increase-kotlin
|
Apache License 2.0
|
app/src/main/java/de/jepfa/yapm/usecase/vault/ShareVaultUseCase.kt
|
jenspfahl
| 378,141,282
| false
| null |
package de.jepfa.yapm.usecase.vault
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import androidx.core.net.toUri
import de.jepfa.yapm.R
import de.jepfa.yapm.service.PreferenceService
import de.jepfa.yapm.service.io.TempFileService
import de.jepfa.yapm.service.io.VaultExportService
import de.jepfa.yapm.service.secret.SaltService
import de.jepfa.yapm.ui.SecureActivity
import de.jepfa.yapm.usecase.UseCase
import de.jepfa.yapm.usecase.UseCaseOutput
import de.jepfa.yapm.util.Constants
import de.jepfa.yapm.util.toastText
import java.util.*
object ShareVaultUseCase: UseCase<ShareVaultUseCase.Input, Uri?, SecureActivity> {
data class Input(val includeMasterKey: Boolean,
val includeSettings: Boolean)
override fun execute(input: Input, activity: SecureActivity): UseCaseOutput<Uri?> {
activity.masterSecretKey?.let{ key ->
var tempFile = TempFileService.createTempFile(activity, getBackupFileName(activity))
val success =
VaultExportService.createVaultFile(
activity,
activity.getApp(),
input.includeMasterKey, input.includeSettings, tempFile.toUri())
if (success) {
val uri = TempFileService.getContentUriFromFile(activity, tempFile)
return UseCaseOutput(uri)
}
}
return UseCaseOutput(false, null)
}
fun startShareActivity(uri: Uri?, activity: SecureActivity) {
if (uri != null) {
val shareIntent = Intent()
shareIntent.action = Intent.ACTION_SEND
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
shareIntent.setDataAndType(uri, activity.contentResolver.getType(uri))
shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
shareIntent.putExtra(
Intent.EXTRA_SUBJECT,
getSubject(activity)
)
val receiver = object: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
context?.let {
context.unregisterReceiver(this)
PreferenceService.putCurrentDate(PreferenceService.DATA_VAULT_EXPORTED_AT, activity)
val upIntent = Intent(activity.intent)
activity.navigateUpTo(upIntent)
}
}
}
val shareAction = "de.jepfa.yapm.share.SHARE_ACTION_" + UUID.randomUUID().toString()
val receiverIntent = Intent(shareAction)
activity.registerReceiver(receiver, IntentFilter(shareAction))
val intentSender = PendingIntent
.getBroadcast(activity, 0, receiverIntent, PendingIntent.FLAG_IMMUTABLE)
.intentSender
activity.startActivity(
Intent.createChooser(
shareIntent,
activity.getString(R.string.send_to),
intentSender
)
)
return
}
toastText(activity, R.string.cannot_share_vault)
}
fun getBackupFileName(context: Context): String {
val currentDate = Constants.SDF_D_INTERNATIONAL.format(Date())
val vaultId = SaltService.getVaultId(context)
return "anotherpassvault-${vaultId}-${currentDate}.json"
}
fun getSubject(context: Context): String {
val currentDate = Constants.SDF_D_INTERNATIONAL.format(Date())
val vaultId = SaltService.getVaultId(context)
return "ANOTHERpass vault '${vaultId}' backup from $currentDate"
}
}
| 6
| null |
3
| 6
|
a5e9828f3b1ed36f293bdebae2e784365e067c62
| 3,820
|
ANOTHERpass
|
MIT License
|
app/src/main/java/exh/util/SearchOverride.kt
|
smokeofc
| 178,956,464
| true
|
{"Kotlin": 1564131, "Java": 131258, "Shell": 522}
|
package exh.util
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.model.MangasPage
import exh.GalleryAddEvent
import exh.GalleryAdder
import rx.Observable
private val galleryAdder by lazy {
GalleryAdder()
}
/**
* A version of fetchSearchManga that supports URL importing
*/
fun Source.urlImportFetchSearchManga(query: String, fail: () -> Observable<MangasPage>) =
when {
query.startsWith("http://") || query.startsWith("https://") -> {
Observable.fromCallable {
val res = galleryAdder.addGallery(query, false, id)
MangasPage((if(res is GalleryAddEvent.Success)
listOf(res.manga)
else
emptyList()), false)
}
}
else -> fail()
}
| 0
|
Kotlin
|
0
| 2
|
7b9e2de475e672b4b8635f3e1b6102db57533a35
| 853
|
TachiyomiEH
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.