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
kotlin-mui-icons/src/main/generated/mui/icons/material/AddLocationAltSharp.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/AddLocationAltSharp") package mui.icons.material @JsName("default") external val AddLocationAltSharp: SvgIconComponent
12
Kotlin
5
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
202
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/eyther/lumbridge/usecase/expenses/UpdateDetailedExpenseUseCase.kt
ruialmeida51
249,223,684
false
{"Kotlin": 698923}
package com.eyther.lumbridge.usecase.expenses import com.eyther.lumbridge.domain.model.expenses.ExpensesCategoryTypes import com.eyther.lumbridge.domain.repository.expenses.ExpensesRepository import com.eyther.lumbridge.mapper.expenses.toDomain import com.eyther.lumbridge.model.expenses.ExpensesDetailedUi import javax.inject.Inject class UpdateDetailedExpenseUseCase @Inject constructor( private val expensesRepository: ExpensesRepository ){ suspend operator fun invoke( expensesDetailedUi: ExpensesDetailedUi, categoryType: ExpensesCategoryTypes ) { expensesRepository.updateExpensesDetail( expensesDetailed = expensesDetailedUi.toDomain(), categoryType = categoryType ) } }
6
Kotlin
0
7
f2d2fe4383e446b94c06e156aae1b9a83dab3409
752
lumbridge-android
MIT License
litho-it/src/main/java/com/facebook/litho/widget/RootComponentWithTreePropsSpec.kt
facebook
80,179,724
false
{"Kotlin": 5825848, "Java": 5578851, "C++": 616537, "Starlark": 198527, "JavaScript": 29060, "C": 25074, "Shell": 8243, "CSS": 5558, "CMake": 4783, "Objective-C": 4012}
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.widget import com.facebook.litho.Component import com.facebook.litho.ComponentContext import com.facebook.litho.Row import com.facebook.litho.annotations.LayoutSpec import com.facebook.litho.annotations.OnCreateLayout import com.facebook.litho.annotations.OnCreateTreeProp import com.facebook.litho.annotations.Prop @LayoutSpec object RootComponentWithTreePropsSpec { @JvmStatic @OnCreateTreeProp fun onCreateTreeProp(c: ComponentContext): A = A() @JvmStatic @OnCreateLayout fun onCreateLayout( c: ComponentContext, @Prop(optional = true) shouldNotUpdateState: Boolean ): Component = Row.create(c) .key("Row") .child( if (shouldNotUpdateState) Text.create(c).text("hello world") else ChildComponentWithStateUpdate.create(c)) .child(NestedTreeParentComponent.create(c).key("NestedTreeParentComponent").flexGrow(1f)) .build() class A }
88
Kotlin
765
7,703
8bde23649ae0b1c594b9bdfcb4668feb7d8a80c0
1,584
litho
Apache License 2.0
test-utils/testData/api/declarationPackageName.kt
google
297,744,725
false
{"Kotlin": 2173589, "Shell": 5321, "Java": 3893}
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // TEST PROCESSOR: DeclarationPackageNameProcessor // EXPECTED: // <no name>:J1 // <no name>:J1.<init> // <no name>:J2 // <no name>:J2.<init> // <no name>:K1 // <no name>:K1.<init> // <no name>:K2 // <no name>:K2.<init> // lib:H1 // lib:H1.<init> // test.java.pack:C // test.java.pack:C.<init> // test.java.pack:Inner // test.java.pack:Inner.<init> // test.java.pack:Nested // test.java.pack:Nested.<init> // test.pack:Inner // test.pack:Inner.<init> // test.pack:Inner.innerFoo // test.pack:InnerLocal // test.pack:InnerLocal.<init> // test.pack:Nested // test.pack:Nested.<init> // test.pack:Nested.nestedFoo // test.pack:Outer // test.pack:Outer.<init> // test.pack:Outer.Foo // test.pack:Val // test.pack:a // test.pack:innerVal // test.pack:nestedVal // END // MODULE: module1 // FILE: H1.kt package lib class H1 // FILE: K1.kt class K1 // FILE: J1.java class J1 { } // MODULE: main(module1) // FILE: K2.kt class K2 // FILE: J2.java class J2 { } // FILE: a.kt package test.pack class Outer { val Val fun Foo() {} inner class Inner { val innerVal: Int fun innerFoo() { class InnerLocal } } class Nested { private val nestedVal: Int fun nestedFoo() { val a = 1 } } } //FILE: test/java/pack/C.java package test.java.pack; public class C { class Inner { } static class Nested {} }
370
Kotlin
268
2,854
a977fb96b05ec9c3e15b5a0cf32e8e7ea73ab3b3
2,081
ksp
Apache License 2.0
vector/src/main/java/im/vector/app/features/home/room/detail/composer/link/SetLinkViewModel.kt
tchapgouv
340,329,238
false
null
/* * Copyright (c) 2021 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.home.room.detail.composer.link import com.airbnb.mvrx.MavericksViewModelFactory import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import im.vector.app.core.di.MavericksAssistedViewModelFactory import im.vector.app.core.di.hiltMavericksViewModelFactory import im.vector.app.core.platform.VectorViewModel class SetLinkViewModel @AssistedInject constructor( @Assisted private val initialState: SetLinkViewState, ) : VectorViewModel<SetLinkViewState, SetLinkAction, SetLinkViewEvents>(initialState) { @AssistedFactory interface Factory : MavericksAssistedViewModelFactory<SetLinkViewModel, SetLinkViewState> { override fun create(initialState: SetLinkViewState): SetLinkViewModel } companion object : MavericksViewModelFactory<SetLinkViewModel, SetLinkViewState> by hiltMavericksViewModelFactory() override fun handle(action: SetLinkAction) = when (action) { is SetLinkAction.LinkChanged -> handleLinkChanged(action.newLink) is SetLinkAction.Save -> handleSave(action.link, action.text) } private fun handleLinkChanged(newLink: String) = setState { copy(saveEnabled = newLink != initialLink.orEmpty()) } private fun handleSave( link: String, text: String ) = if (initialState.isTextSupported) { _viewEvents.post(SetLinkViewEvents.SavedLinkAndText(link, text)) } else { _viewEvents.post(SetLinkViewEvents.SavedLink(link)) } }
4
null
6
9
82fea8dbcfe8c29fb318dc55b65d62e0f131c512
2,149
tchap-android
Apache License 2.0
buildSrc/src/main/kotlin/Versions.kt
appmattus
337,162,396
false
null
/* * Copyright 2021 Appmattus Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ object Versions { const val kotlin = "1.5.0" const val androidGradlePlugin = "4.2.0" const val detektGradlePlugin = "1.16.0" const val gradleVersionsPlugin = "0.36.0" const val markdownlintGradlePlugin = "0.6.0" const val gradleMavenPublishPlugin = "0.15.1" const val dokkaPlugin = "1.4.32" const val coil = "1.2.1" const val coroutines = "1.5.0-RC" const val coroutinesNative = "1.5.0-RC-native-mt" const val groupie = "2.9.0" const val orbitMvi = "3.1.1" const val desugar = "1.1.1" const val leakCanary = "2.7" object AndroidX { const val appCompat = "1.2.0" const val constraintLayout = "2.1.0-alpha2" const val fragment = "1.3.3" const val lifecycle = "2.3.1" const val navigation = "2.3.5" const val vectorDrawable = "1.1.0" } object Google { val dagger = "2.35.1" val material = "1.3.0" } }
0
Kotlin
2
1
9f42a1eac08c5a57305b851c6b76c58e9550f91a
1,538
multiplatform-utils
Apache License 2.0
Android-Kotlin-Demo-App/src/main/java/com/applovin/apps/kotlindemoapp/interstitials/InterstitialBasicIntegrationActivity.kt
mamunur34
179,533,096
true
{"Gradle": 3, "Markdown": 1, "Text": 1, "Ignore List": 2, "Proguard": 2, "XML": 49, "Java": 43, "Kotlin": 37}
package com.applovin.apps.kotlindemoapp.interstitials import android.os.Bundle import com.applovin.adview.AppLovinInterstitialAd import com.applovin.adview.AppLovinInterstitialAdDialog import com.applovin.apps.kotlindemoapp.AdStatusActivity import com.applovin.apps.kotlindemoapp.R import com.applovin.sdk.AppLovinAd import com.applovin.sdk.AppLovinAdDisplayListener import com.applovin.sdk.AppLovinAdLoadListener import com.applovin.sdk.AppLovinAdClickListener import com.applovin.sdk.AppLovinAdVideoPlaybackListener import com.applovin.sdk.AppLovinErrorCodes import com.applovin.sdk.AppLovinSdk import kotlinx.android.synthetic.main.activity_interstitial_basic_integration.* import java.lang.ref.WeakReference class InterstitialBasicIntegrationActivity : AdStatusActivity(), AppLovinAdLoadListener, AppLovinAdDisplayListener, AppLovinAdClickListener, AppLovinAdVideoPlaybackListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_interstitial_basic_integration) adStatusTextView = status_label val interstitialAdDialog = AppLovinInterstitialAd.create(AppLovinSdk.getInstance(this), this) showButton.setOnClickListener { showButton.isEnabled = false log("Showing...") // // Optional: Set ad load, ad display, ad click, and ad video playback callback listeners // interstitialAdDialog.setAdLoadListener(this) interstitialAdDialog.setAdDisplayListener(this) interstitialAdDialog.setAdClickListener(this) interstitialAdDialog.setAdVideoPlaybackListener(this) // This will only ever be used if you have video ads enabled. interstitialAdDialog.show() } } // // Ad Load Listener // override fun adReceived(appLovinAd: AppLovinAd) { log("Interstitial loaded") showButton.isEnabled = true } override fun failedToReceiveAd(errorCode: Int) { // Look at AppLovinErrorCodes.java for list of error codes log("Interstitial failed to load with error code " + errorCode) showButton.isEnabled = true } // // Ad Display Listener // override fun adDisplayed(appLovinAd: AppLovinAd) { log("Interstitial Displayed") } override fun adHidden(appLovinAd: AppLovinAd) { log("Interstitial Hidden") } // // Ad Click Listener // override fun adClicked(appLovinAd: AppLovinAd) { log("Interstitial Clicked") } // // Ad Video Playback Listener // override fun videoPlaybackBegan(appLovinAd: AppLovinAd) { log("Video Started") } override fun videoPlaybackEnded(appLovinAd: AppLovinAd, percentViewed: Double, wasFullyViewed: Boolean) { log("Video Ended") } }
0
Java
0
0
c4baa754edf1a1aec4706bc3888e2518dc7f2f60
2,911
Android-SDK-Demo
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/CfnCodeDeployBlueGreenAdditionalOptionsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.CfnCodeDeployBlueGreenAdditionalOptions @Generated public fun buildCfnCodeDeployBlueGreenAdditionalOptions(initializer: @AwsCdkDsl CfnCodeDeployBlueGreenAdditionalOptions.Builder.() -> Unit): CfnCodeDeployBlueGreenAdditionalOptions = CfnCodeDeployBlueGreenAdditionalOptions.Builder().apply(initializer).build()
1
Kotlin
0
0
e9a0ff020b0db2b99e176059efdb124bf822d754
487
aws-cdk-kt
Apache License 2.0
app/src/main/java/org/simple/clinic/drugs/selection/custom/drugfrequency/SelectDrugFrequencyDialog.kt
simpledotorg
132,515,649
false
{"Kotlin": 6129044, "Shell": 1660, "HTML": 545}
package org.simple.clinic.drugs.selection.custom.drugfrequency import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.os.Parcelable import androidx.appcompat.app.AppCompatDialogFragment import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.parcelize.IgnoredOnParcel import kotlinx.parcelize.Parcelize import org.simple.clinic.R import org.simple.clinic.di.injector import org.simple.clinic.drugs.search.DrugFrequency import org.simple.clinic.drugs.selection.custom.drugfrequency.country.DrugFrequencyLabel import org.simple.clinic.navigation.v2.Router import org.simple.clinic.navigation.v2.ScreenKey import org.simple.clinic.navigation.v2.Succeeded import org.simple.clinic.util.unsafeLazy import javax.inject.Inject class SelectDrugFrequencyDialog : AppCompatDialogFragment() { companion object { fun readDrugFrequency(result: Succeeded): DrugFrequency? { return (result.result as SelectedDrugFrequency).drugFrequency } } @Inject lateinit var router: Router @Inject lateinit var drugFrequencyToLabelMap: Map<DrugFrequency?, DrugFrequencyLabel> private val screenKey: Key by unsafeLazy { ScreenKey.key(this) } override fun onAttach(context: Context) { super.onAttach(context) context.injector<Injector>().inject(this) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val drugFrequencies = drugFrequencyToLabelMap.keys.toList() val drugFrequencyLabels = drugFrequencyToLabelMap.values.map { it.label } val selectedValueIndex = drugFrequencies.indexOf(screenKey.drugFrequency) return MaterialAlertDialogBuilder(requireContext()) .setTitle(getString(R.string.custom_drug_entry_sheet_frequency)) .setSingleChoiceItems(drugFrequencyLabels.toTypedArray(), selectedValueIndex) { _, indexSelected -> router.popWithResult(Succeeded(SelectedDrugFrequency(drugFrequencies[indexSelected]))) } .setPositiveButton(getString(R.string.custom_drug_entry_sheet_frequency_dialog_done)) { _, _ -> router.pop() } .create() } override fun onCancel(dialog: DialogInterface) { backPressed() super.onCancel(dialog) } private fun backPressed() { requireActivity().onBackPressed() } @Parcelize data class Key( val drugFrequency: DrugFrequency?, override val analyticsName: String = "Drug Frequency Dialog" ) : ScreenKey() { @IgnoredOnParcel override val type = ScreenType.Modal override fun instantiateFragment() = SelectDrugFrequencyDialog() } interface Injector { fun inject(target: SelectDrugFrequencyDialog) } @Parcelize data class SelectedDrugFrequency(val drugFrequency: DrugFrequency?) : Parcelable }
13
Kotlin
73
236
ff699800fbe1bea2ed0492df484777e583c53714
2,822
simple-android
MIT License
app/src/main/java/com/example/juliocatano/weatherappkotlin/domain/commands/Commands.kt
juliocatano
117,374,172
false
null
package com.example.juliocatano.weatherappkotlin.domain.commands /** * Created by juliocatano on 11/2/17. */ public interface Command<out T> { fun execute(): T }
0
Kotlin
0
0
ec5c2d9f81d6fb791f6655670a5e440c7956ab9e
168
kotlin_antonio_leiva_book
Apache License 2.0
app/src/main/java/com/rarms/stocks/performance/ui/charts/ChartUtils.kt
russelarms
407,309,318
false
{"Kotlin": 48851}
package com.rarms.stocks.performance.ui.charts import com.github.mikephil.charting.charts.BarLineChartBase import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.components.Legend import com.github.mikephil.charting.components.XAxis import com.github.mikephil.charting.components.YAxis import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter import com.github.mikephil.charting.utils.ColorTemplate import com.rarms.stocks.performance.util.PercentageAxisValueFormatter val CHART_COLORS = intArrayOf( ColorTemplate.MATERIAL_COLORS[0], ColorTemplate.MATERIAL_COLORS[1], ColorTemplate.MATERIAL_COLORS[2] ) fun BarLineChartBase<*>.prepareChart() { this.setDrawGridBackground(true) this.description.isEnabled = true this.setDrawBorders(true) // set x values this.xAxis.setDrawAxisLine(true) this.xAxis.position = XAxis.XAxisPosition.BOTTOM this.xAxis.setDrawGridLines(true) this.xAxis.valueFormatter = DefaultAxisValueFormatter(3) // set y values this.axisLeft.isEnabled = true this.axisRight.isEnabled = false this.axisLeft.valueFormatter = when (this) { is LineChart -> PercentageAxisValueFormatter() else -> DefaultAxisValueFormatter(4) } this.axisLeft.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART) this.axisLeft.spaceTop = 15f // enable touch gestures this.setTouchEnabled(true) // enable scaling and dragging this.isDragEnabled = true this.setScaleEnabled(true) // if disabled, scaling can be done on x- and y-axis separately this.setPinchZoom(false) val l = this.legend l.verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM l.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT l.orientation = Legend.LegendOrientation.HORIZONTAL l.setDrawInside(false) l.form = Legend.LegendForm.SQUARE l.formSize = 9f l.textSize = 11f l.xEntrySpace = 4f }
0
Kotlin
0
1
e3878577b8eecd0766a87c56681526b34a7457ee
1,972
StocksChartsApp
MIT License
library/src/main/java/com/telefonica/tweaks/TweaksContract.kt
Telefonica
446,507,209
false
{"Kotlin": 60052}
package com.telefonica.tweaks import kotlinx.coroutines.flow.Flow interface TweaksContract { fun <T> getTweakValue(key: String): Flow<T?> fun <T> getTweakValue(key: String, defaultValue: T): Flow<T> suspend fun <T> getTweak(key: String): T? suspend fun <T> getTweak(key: String, defaultValue: T): T suspend fun <T> setTweakValue(key: String, value: T) suspend fun clearValue(key: String) }
0
Kotlin
1
15
4f89d4a98950348ba4c48e1698d928a0efd4c987
424
tweaks
Apache License 2.0
app/src/main/java/com/stevesoltys/seedvault/transport/backup/KVBackupPlugin.kt
weblate
294,738,767
true
{"Kotlin": 525098, "Java": 103}
package com.stevesoltys.seedvault.transport.backup import android.content.pm.PackageInfo import java.io.IOException import java.io.OutputStream interface KVBackupPlugin { /** * Get quota for key/value backups. */ fun getQuota(): Long // TODO consider using a salted hash for the package name (and key) to not leak it to the storage server /** * Return true if there are records stored for the given package. */ @Throws(IOException::class) fun hasDataForPackage(packageInfo: PackageInfo): Boolean /** * This marks the beginning of a backup operation. * * Make sure that there is a place to store K/V pairs for the given package. * E.g. file-based plugins should a create a directory for the package, if none exists. */ @Throws(IOException::class) fun ensureRecordStorageForPackage(packageInfo: PackageInfo) /** * Return an [OutputStream] for the given package and key * which will receive the record's encrypted value. */ @Throws(IOException::class) fun getOutputStreamForRecord(packageInfo: PackageInfo, key: String): OutputStream /** * Delete the record for the given package identified by the given key. */ @Throws(IOException::class) fun deleteRecord(packageInfo: PackageInfo, key: String) /** * Remove all data associated with the given package. */ @Throws(IOException::class) fun removeDataOfPackage(packageInfo: PackageInfo) }
0
null
0
1
fa5ec01106b4761e7a0a2557cbc2ee98edab0b40
1,494
seedvault
Apache License 2.0
kotlinify-core/src/test/kotlin/io/t28/kotlinify/interceptor/kotlinx/SerializableInterceptorTest.kt
t28hub
455,777,193
false
{"Kotlin": 298071}
/* * Copyright (c) 2022 Tatsuya Maki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.t28.kotlinify.interceptor.jackson import com.fasterxml.jackson.annotation.JsonIgnoreProperties import io.t28.kotlinify.assertThat import io.t28.kotlinify.lang.impl.TypeElementImpl import io.t28.kotlinify.lang.TypeKind.CLASS import io.t28.kotlinify.lang.annotation import org.junit.jupiter.api.Test internal class JsonIgnorePropertiesInterceptorTest { @Test fun `intercept should add @JsonIgnoreProperties`() { // Arrange val type = TypeElementImpl( name = "Example", kind = CLASS ) // Act val actual = JsonIgnorePropertiesInterceptor.intercept(type) // Assert assertThat(actual).apply { hasName("Example") isClass() annotations().hasSize(1) annotationAt(0).apply { hasType<JsonIgnoreProperties>() members().hasSize(1) memberAt(0).isEqualTo( """ |ignoreUnknown = true """.trimMargin() ) } } } @Test fun `intercept should skip when type has @JsonIgnoreProperties`() { // Arrange val type = TypeElementImpl( name = "Example", kind = CLASS, annotations = listOf( annotation<JsonIgnoreProperties>() ) ) // Act val actual = JsonIgnorePropertiesInterceptor.intercept(type) // Assert assertThat(actual).isEqualTo(type) } }
11
Kotlin
0
0
8ff0f747db97690658a8fc7526766c7e5699de3a
2,153
kotlinify
Apache License 2.0
websockt/src/main/kotlin/com/divpundir/websockt/WebSockt.kt
divyanshupundir
628,227,475
false
null
package com.divpundir.websockt public object WebSockt
0
Kotlin
0
0
98a9369759bda8f598408974ecad25401f68bbfc
55
websockt
Apache License 2.0
app/src/main/java/net/beatwaves/homecontrol/DeviceCoroutineScope.kt
sbergen
213,025,679
false
null
package net.beatwaves.homecontrol import kotlinx.coroutines.* import java.io.Closeable import kotlin.coroutines.CoroutineContext class DeviceCoroutineScope constructor(private val status: DeviceStatus) : Closeable { private lateinit var parentJob: Job private lateinit var scope: CoroutineScope private val coroutineContext: CoroutineContext get() = parentJob + Dispatchers.Default init { buildCrContext() } private fun buildCrContext() { parentJob = Job() scope = CoroutineScope(coroutineContext) } override fun close() { coroutineContext.cancel() } val crErrorHandler = CoroutineExceptionHandler { _, exception -> status.busy.postValue(false) status.error.postValue(exception.message) buildCrContext() } fun runAction(block: suspend CoroutineScope.() -> Unit) { status.busy.postValue(true) status.error.postValue("") scope.launch(crErrorHandler) { block() status.busy.postValue(false) } } fun <T> async(block: suspend CoroutineScope.() -> T): Deferred<T> = scope.async(crErrorHandler, CoroutineStart.DEFAULT, block) }
0
Kotlin
1
1
61af4c5ae77e1eee054dfeaa11a98d27d3f11b97
1,213
AndroidAVControl
MIT License
kotlin-multiplatform/src/commonTest/kotlin/com/ricoh360/thetaclient/repository/options/BluetoothPowerTest.kt
ricohapi
592,574,011
false
{"Kotlin": 1609244, "Dart": 492637, "TypeScript": 416630, "Swift": 259732, "Objective-C": 16087, "Java": 7432, "Ruby": 4903, "JavaScript": 2959, "CSS": 1552, "Objective-C++": 1152, "Shell": 573, "HTML": 565, "C": 103}
package com.ricoh360.thetaclient.repository.options import com.goncalossilva.resources.Resource import com.ricoh360.thetaclient.CheckRequest import com.ricoh360.thetaclient.MockApiClient import com.ricoh360.thetaclient.ThetaRepository import com.ricoh360.thetaclient.transferred.BluetoothPower import com.ricoh360.thetaclient.transferred.Options import io.ktor.client.request.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.utils.io.* import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import kotlin.test.* @OptIn(ExperimentalCoroutinesApi::class) class BluetoothPowerTest { private val endpoint = "http://192.168.1.1:80/" @BeforeTest fun setup() { MockApiClient.status = HttpStatusCode.OK } @AfterTest fun teardown() { MockApiClient.status = HttpStatusCode.OK } /** * Get option bluetoothPower. */ @Test fun getOptionBluetoothPowerTest() = runTest { val optionNames = listOf( ThetaRepository.OptionNameEnum.BluetoothPower ) val stringOptionNames = listOf( "_bluetoothPower" ) MockApiClient.onRequest = { request -> // check request CheckRequest.checkGetOptions(request, stringOptionNames) ByteReadChannel(Resource("src/commonTest/resources/options/option_bluetooth_power_on.json").readText()) } val thetaRepository = ThetaRepository(endpoint) val options = thetaRepository.getOptions(optionNames) assertEquals(options.bluetoothPower, ThetaRepository.BluetoothPowerEnum.ON) } /** * Set option bluetoothPower. */ @Test fun setOptionBluetoothPowerTest() = runTest { val value = Pair(ThetaRepository.BluetoothPowerEnum.ON, BluetoothPower.ON) MockApiClient.onRequest = { request -> // check request CheckRequest.checkSetOptions(request, bluetoothPower = value.second) ByteReadChannel(Resource("src/commonTest/resources/setOptions/set_options_done.json").readText()) } val thetaRepository = ThetaRepository(endpoint) val options = ThetaRepository.Options( bluetoothPower = value.first ) thetaRepository.setOptions(options) } /** * Convert ThetaRepository.Options to Options. */ @Test fun convertOptionBluetoothPowerTest() = runTest { val values = listOf( Pair(ThetaRepository.BluetoothPowerEnum.ON, BluetoothPower.ON), Pair(ThetaRepository.BluetoothPowerEnum.OFF, BluetoothPower.OFF), ) values.forEach { val orgOptions = Options( _bluetoothPower = it.second ) val options = ThetaRepository.Options(orgOptions) assertEquals(options.bluetoothPower, it.first, "bluetoothPower ${it.second}") } values.forEach { val orgOptions = ThetaRepository.Options( bluetoothPower = it.first ) val options = orgOptions.toOptions() assertEquals(options._bluetoothPower, it.second, "bluetoothPower ${it.second}") } } }
9
Kotlin
9
9
71923eec9b8b85c137e92733edebac6b1eae001a
3,229
theta-client
MIT License
JetStreamCompose/jetstream/src/main/java/com/google/jetstream/presentation/screens/movies/MoviesScreenViewModel.kt
android
192,011,831
false
{"Kotlin": 904366, "Java": 783880, "Python": 72375, "TypeScript": 47533, "HTML": 9379, "JavaScript": 6342, "CSS": 5928}
/* * Copyright 2023 Google LLC * * 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.google.jetstream.presentation.screens.movies import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.jetstream.data.entities.MovieList import com.google.jetstream.data.repositories.MovieRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class MoviesScreenViewModel @Inject constructor( movieRepository: MovieRepository ) : ViewModel() { val uiState = combine( movieRepository.getMoviesWithLongThumbnail(), movieRepository.getPopularFilmsThisWeek(), ) { (movieList, popularFilmsThisWeek) -> MoviesScreenUiState.Ready(movieList = movieList, popularFilmsThisWeek = popularFilmsThisWeek) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = MoviesScreenUiState.Loading ) } sealed interface MoviesScreenUiState { object Loading: MoviesScreenUiState data class Ready(val movieList: MovieList, val popularFilmsThisWeek: MovieList): MoviesScreenUiState }
46
Kotlin
325
986
fc5dcc0ec50da71e188b72fc4ff6ddca39b57402
1,797
tv-samples
Apache License 2.0
components/keyedit/impl/src/main/java/com/flipperdevices/keyedit/impl/fragment/KeyEditFragment.kt
flipperdevices
288,258,832
false
null
package com.flipperdevices.keyedit.impl.fragment import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import com.flipperdevices.core.ktx.android.withArgs import com.flipperdevices.core.ui.fragment.ComposeFragment import com.flipperdevices.core.ui.ktx.LocalRouter import com.flipperdevices.keyedit.impl.composable.ComposableEditScreen import com.flipperdevices.keyedit.impl.model.EditableKey import com.flipperdevices.keyedit.impl.viewmodel.KeyEditViewModel import tangle.viewmodel.fragment.tangleViewModel const val EXTRA_EDITABLE_KEY = "editable_key" const val EXTRA_TITLE_KEY = "title_key" class KeyEditFragment : ComposeFragment() { private val viewModel by tangleViewModel<KeyEditViewModel>() @Composable override fun RenderView() { val router = LocalRouter.current val state by viewModel.getEditState().collectAsState() val title = remember { arguments?.getString(EXTRA_TITLE_KEY) } ComposableEditScreen( viewModel, title = title, state = state, onBack = router::exit, onSave = { viewModel.onSave { router.exit() } } ) } companion object { fun getInstance(editableKey: EditableKey, title: String?): KeyEditFragment { return KeyEditFragment().withArgs { putParcelable(EXTRA_EDITABLE_KEY, editableKey) putString(EXTRA_TITLE_KEY, title) } } } }
9
Kotlin
78
552
f4cb3af8f6980abd999f4c841d4530b713314462
1,587
Flipper-Android-App
MIT License
app/src/main/java/com/lockscreen/hanmo/lockscreenkotlinexample/lockscreen/util/LockScreen.kt
hanmolee
151,202,935
false
null
package com.lockscreen.test.lockscreenkotlinexample.lockscreen.util import android.app.ActivityManager import android.content.Context import android.content.Intent import android.os.Build import com.lockscreen.test.lockscreenkotlinexample.LockScreenApplication import com.lockscreen.test.lockscreenkotlinexample.lockscreen.service.LockScreenService /** * 잠금화면 Service를 관리하는 Class * Created by hanmo on 2018. 10. 2.. */ object LockScreen { fun active() { LockScreenApplication.applicationContext()?.run { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(Intent(this, LockScreenService::class.java)) } else { startService(Intent(this, LockScreenService::class.java)) } } } fun deActivate() { LockScreenApplication.applicationContext()?.run { stopService(Intent(this, LockScreenService::class.java)) } } fun getLockScreenStatus() : Boolean { val lockScreenPreferences = LockScreenApplication.applicationContext()?.run { getSharedPreferences("LockScreenStatus", Context.MODE_PRIVATE) } return lockScreenPreferences?.getBoolean("LockScreenStatus", false)!! } val isActive: Boolean get() = LockScreenApplication.applicationContext()?.let { isMyServiceRunning(LockScreenService::class.java) } ?: kotlin.run { false } private fun isMyServiceRunning(serviceClass: Class<*>): Boolean { val manager = LockScreenApplication.applicationContext()?.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (service in manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.name == service.service.className) { return true } } return false } }
6
Kotlin
0
5
f209e5a872ae12142e38662458ae46d613b56398
1,892
LockScreenKotlinExample
Apache License 2.0
android/app/src/main/kotlin/com/example/input_international_multi/MainActivity.kt
deiniresendiz
356,296,718
false
{"Dart": 380597, "HTML": 1539, "Swift": 404, "Kotlin": 142, "Objective-C": 38}
package com.example.input_international_multi import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
8b2ecad0c8278a76cde6dfa54a78176f5facd297
142
input_international_multi
MIT License
app/src/main/java/com/example/businessscout/data/BussinessCollectionDao.kt
gamaVI
741,208,618
false
{"Kotlin": 34817}
package com.example.businessscout.data import androidx.room.Dao import androidx.room.Insert import androidx.room.Query @Dao interface BussinessCollectionDao { @Insert fun insertCollection(collection: BussinessCollection) @Query("SELECT * FROM BussinessCollection") fun getAllCollections(): List<BussinessCollection> @Query("DELETE FROM BussinessCollection WHERE id = :id") fun deleteCollection(id: Int) // update @Query("UPDATE BussinessCollection SET collectionName = :collectionName, colorHex = :colorHex WHERE id = :id") fun updateCollection(id: Int, collectionName: String, colorHex: String) }
0
Kotlin
0
0
7486729c02106829928c83367da391ca46f7ec4d
645
rooms-demo
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/repository/AppointmentAttendeeSearchRepository.kt
ministryofjustice
533,838,017
false
{"Kotlin": 3382122, "Shell": 11425, "Dockerfile": 1478}
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository import org.springframework.data.jpa.repository.Query import org.springframework.stereotype.Repository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.AppointmentAttendeeSearch @Repository interface AppointmentAttendeeSearchRepository : ReadOnlyRepository<AppointmentAttendeeSearch, Long> { @Query( value = "FROM AppointmentAttendeeSearch aas " + "WHERE aas.appointmentSearch.appointmentId IN :appointmentIds", ) fun findByAppointmentIds(appointmentIds: List<Long>): List<AppointmentAttendeeSearch> }
4
Kotlin
0
1
6622e38d880783c0d901fa79aa10aee364f4c5e2
619
hmpps-activities-management-api
MIT License
beanmodule/src/main/java/com/apm29/beanmodule/beans/one/Icons.kt
apm29
102,709,720
false
null
package com.apm29.beanmodule.beans.one data class Icons(val night: String = "", val day: String = "")
1
null
1
2
862cd263248b0506c1f850eecc05880c3ce34aac
119
kotlinapp
Apache License 2.0
src/main/kotlin/com/daveme/chocolateCakePHP/strings.kt
dmeybohm
95,393,362
false
null
package com.daveme.chocolateCakePHP fun String.startsWithUppercaseCharacter(): Boolean = this.isNotEmpty() && Character.isUpperCase(this[0]) fun String.chopFromEnd(end: String): String = if (end == "" || !this.endsWith(end)) this else this.substring(0, this.length - end.length) fun String.isControllerClass(): Boolean = this.contains("Controller") || this.contains("\\Cake\\Controller\\Controller") fun String.controllerBaseName(): String? = if (!endsWith("Controller")) null else substring(0, length - "Controller".length)
8
Kotlin
0
13
2aedc8d9487ebd670e29a993e54dec135f302ea2
593
chocolate-cakephp
MIT License
src/main/kotlin/com/nibado/projects/advent/y2017/Day07.kt
nielsutrecht
47,550,570
false
{"Maven POM": 1, "Text": 132, "Ignore List": 2, "HTML": 1, "Markdown": 1, "Kotlin": 208, "Java": 20, "INI": 1, "Scala": 19}
package com.nibado.projects.advent.y2017 import com.nibado.projects.advent.Day import com.nibado.projects.advent.resourceLines val regex = Regex("([a-z]{4,8}) \\(([0-9]+)\\)( -> ([a-z ,]+))?") object Day07 : Day { val tree: Tree by lazy { parseTree(resourceLines(2017, 7)) } override fun part1() = tree.name override fun part2() = walk(tree).toString() } fun walk(tree: Tree): Int { if (!tree.balanced()) { val result = tree.children().map { walk(it) }.maxOrNull() if (tree.children().map { it.balanced() }.count { it } == tree.children().size) { val groups = tree.children().groupBy { it.sum() } val wrongTree = groups.values.first { it.size == 1 }.first() val correctTree = groups.values.first { it.size > 1 }.first() return wrongTree.weight - (wrongTree.sum() - correctTree.sum()) } return result!! } return Int.MIN_VALUE } fun parseTree(lines: List<String>): Tree { val input = lines.map { parse(it) }.toList() val programs = input.map { it.name to Tree(it.name, it.weight, null) }.toMap() input.flatMap { a -> a.programs.map { p -> Pair(a.name, p) } }.forEach { programs[it.first]!!.nodes[it.second] = programs[it.second]!! programs[it.second]!!.parent = programs[it.first]!! } return programs.values.filter { it.parent == null }.first() } fun parse(line: String): ProgramOutput { val result = regex.matchEntire(line)!! val name = result.groups.get(1)!!.value val weight = result.groups.get(2)!!.value.toInt() val programs = if (result.groups.get(4) == null) listOf() else result.groups.get(4)!!.value.split(", ").toList() return ProgramOutput(name, weight, programs) } data class ProgramOutput(val name: String, val weight: Int, val programs: List<String>) data class Tree(val name: String, val weight: Int, var parent: Tree?) { val nodes: MutableMap<String, Tree> = mutableMapOf() fun children() = nodes.values fun sum(): Int = weight + nodes.values.map { it.sum() }.sum() fun balanced() = nodes.values.map { it.sum() }.toSet().size == 1 }
1
Kotlin
0
16
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
2,139
adventofcode
MIT License
app/src/main/java/com/sample/githubconnect/models/database/AppDatabase.kt
chetan-AD
315,594,185
false
null
package com.sample.githubconnect.models.database import androidx.room.Database import androidx.room.RoomDatabase import com.sample.githubconnect.models.database.daos.UsersDao import com.sample.githubconnect.models.entities.User @Database(entities = [User::class], version = 1, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract val usersDao: UsersDao }
0
Kotlin
0
1
8c3c08e2c803717c9a0d6e7e88b86bc1c0d1d708
384
GithubConnect
Apache License 2.0
library/src/main/java/dev/jameido/easypic/OnPickResultListener.kt
Jameido
95,787,445
false
{"Kotlin": 43899}
package dev.jameido.easypic /** * Created by <NAME> on 24/05/2018. */ interface OnPickResultListener { fun onPicPickSuccess(result: PickerResult) fun onPicPickFailure(exception: Exception) }
0
Kotlin
1
3
4fbc59fd7aa9a5558029c276e1035887ca1ced79
204
easypic-android
MIT License
nebulosa-time/src/main/kotlin/nebulosa/time/Spline.kt
tiagohm
568,578,345
false
{"Kotlin": 2712371, "TypeScript": 513759, "HTML": 249483, "JavaScript": 120539, "SCSS": 11332, "Python": 2817, "Makefile": 445}
package nebulosa.time interface Spline<T> { val lower: T val upper: T val width: T operator fun get(index: Int): T val derivative: Spline<T> fun compute(value: Double): Double }
29
Kotlin
2
4
723ede857d8fbf608562e93030719ae26dd0aad1
209
nebulosa
MIT License
app/src/main/java/at/marki/daggerino/worker/Worker1.kt
markini
260,060,195
false
null
package at.marki.daggerino.worker import android.content.Context import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.Worker import androidx.work.WorkerParameters import at.marki.daggerino.tools.TimeLogger import dagger.android.HasAndroidInjector import timber.log.Timber import javax.inject.Inject class Worker1(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { init { val injector = appContext.applicationContext as HasAndroidInjector injector.androidInjector().inject(this) } @Inject lateinit var timeLogger: TimeLogger override fun doWork(): Result { Timber.e("Worker 1 Running") timeLogger.logCurrentTime() return Result.success() } companion object { fun startWorker(context: Context?) { if (context == null) return val worker1Request = OneTimeWorkRequestBuilder<Worker1>().build() WorkManager.getInstance(context).enqueue(worker1Request) } } }
0
Kotlin
0
0
b65502a51c88347d60f0a22d0fcfc8409792c318
1,073
Daggerino
MIT License
src/test/kotlin/cc/ekblad/toml/parser/TableArrayTests.kt
valderman
426,810,086
false
{"Kotlin": 235023, "Shell": 99}
package cc.ekblad.toml.parser import cc.ekblad.toml.TomlValue import cc.ekblad.toml.UnitTest import java.time.LocalDate import kotlin.test.Test import kotlin.test.assertEquals class TableArrayTests : UnitTest { @Test fun `can parse simple table array`() { val expr = """ [[foo]] bar = 1 [[foo]] bar = 2 baz = 'qwe' [[bar]] bar = 3 [[foo]] [[foo]] bar = 4 """.trimIndent() val expected = TomlValue.Map( "foo" to TomlValue.List( TomlValue.Map("bar" to TomlValue.Integer(1)), TomlValue.Map("bar" to TomlValue.Integer(2), "baz" to TomlValue.String("qwe")), TomlValue.Map(), TomlValue.Map("bar" to TomlValue.Integer(4)), ), "bar" to TomlValue.List( TomlValue.Map("bar" to TomlValue.Integer(3)), ) ) assertEquals(expected, TomlValue.from(expr)) } @Test fun `can parse dotted key table array`() { val expr = """ [[foo.bar]] baz = 1 """.trimIndent() val expected = TomlValue.Map( "foo" to TomlValue.Map( "bar" to TomlValue.List( TomlValue.Map("baz" to TomlValue.Integer(1)) ) ) ) assertEquals(expected, TomlValue.from(expr)) } @Test fun `can define complex document with table arrays`() { val expr = """ [[fruits]] name = "apple" [fruits.physical] # subtable color = "red" shape = "round" [[fruits.varieties]] # nested array of tables name = "red delicious" [[fruits.varieties]] name = "<NAME>" [[fruits]] name = "banana" [[fruits.varieties]] name = "plantain" """.trimIndent() val expected = TomlValue.Map( "fruits" to TomlValue.List( TomlValue.Map( "name" to TomlValue.String("apple"), "physical" to TomlValue.Map( "color" to TomlValue.String("red"), "shape" to TomlValue.String("round") ), "varieties" to TomlValue.List( TomlValue.Map("name" to TomlValue.String("<NAME>")), TomlValue.Map("name" to TomlValue.String("<NAME>")) ) ), TomlValue.Map( "name" to TomlValue.String("banana"), "varieties" to TomlValue.List( TomlValue.Map("name" to TomlValue.String("plantain")) ) ) ) ) assertEquals(expected, TomlValue.from(expr)) } @Test fun `can add sub-table array of already defined table`() { val expr = """ [foo] baz = 2 [[foo.bar]] baz = 1 """.trimIndent() val expected = TomlValue.Map( "foo" to TomlValue.Map( "baz" to TomlValue.Integer(2), "bar" to TomlValue.List( TomlValue.Map("baz" to TomlValue.Integer(1)) ) ) ) assertEquals(expected, TomlValue.from(expr)) } @Test fun `can extend last item of array table`() { val expr = """ [[foo]] baz = "asd" [[foo]] baz = 2011-11-11 [foo.bar] baz = "qwe" """.trimIndent() val expected = TomlValue.Map( "foo" to TomlValue.List( TomlValue.Map( "baz" to TomlValue.String("asd"), ), TomlValue.Map( "bar" to TomlValue.Map( "baz" to TomlValue.String("qwe") ), "baz" to TomlValue.LocalDate(LocalDate.of(2011, 11, 11)), ) ) ) assertEquals(expected, TomlValue.from(expr)) } @Test fun `can't overwrite table array`() { assertDocumentParseError( """ [[fruits]] name = "apple" [[fruits.varieties]] name = "<NAME>" # INVALID: This table conflicts with the previous array of tables [fruits.varieties] name = "<NAME>" """.trimIndent() ) } @Test fun `throws on whitespace between double brackets`() { assertDocumentParseError("[ [foo]]") assertDocumentParseError("[[foo] ]") assertDocumentParseError("[ [foo] ]") } @Test fun `throws on extending non-table array`() { assertDocumentParseError( """ foo = [] [[foo]] """.trimIndent() ) assertDocumentParseError( """ [foo] [[foo]] """.trimIndent() ) assertDocumentParseError( """ [[foo]] [foo] """.trimIndent() ) assertDocumentParseError( """ foo = 123 [[foo]] """.trimIndent() ) assertDocumentParseError( """ foo.bar = 1 [[foo]] """.trimIndent() ) assertDocumentParseError( """ [[foo.bar]] [foo] bar = 1 """.trimIndent() ) assertDocumentParseError( """ [fruits.physical] color = "red" shape = "round" [[fruits.physical]] color = "green" """.trimIndent() ) assertDocumentParseError( """ [fruit.physical] # subtable, but to which parent element should it belong? color = "red" shape = "round" [[fruit]] # parser must throw an error upon discovering that "fruit" is # an array rather than a table name = "apple" """.trimIndent() ) } }
10
Kotlin
2
71
a036e7c0f16e342ed4f285ebc66e9fac902cd469
6,596
4koma
MIT License
samples/android/camerakit-sample-full/src/main/java/com/snap/camerakit/sample/CatFactRemoteApiService.kt
Snapchat
381,521,879
false
null
package com.snap.camerakit.sample import com.snap.camerakit.common.Consumer import com.snap.camerakit.lenses.LensesComponent import com.snap.camerakit.lenses.toInternalServerErrorResponse import com.snap.camerakit.lenses.toSuccessResponse import java.io.IOException import java.net.HttpURLConnection import java.net.URL /** * Example implementation of [LensesComponent.RemoteApiService] which receives requests from lenses that use the * [Remote Service Module](https://docs.snap.com/lens-studio/references/guides/lens-features/remote-apis/remote-service-module) * feature. The remote API spec ID in [Factory.supportedApiSpecIds] is provided for demo and testing purposes - * CameraKit user applications are expected to define their own specs for any remote API that they are interested to * communicate with. Please reach out to CameraKit support team at https://docs.snap.com/snap-kit/support * to find out more on how to define and use this feature. */ internal object CatFactRemoteApiService : LensesComponent.RemoteApiService { private const val BASE_URL = "https://catfact.ninja" private const val HEADER_ACCEPT = "Accept" object Factory : LensesComponent.RemoteApiService.Factory { override val supportedApiSpecIds: Set<String> = setOf("03d765c5-20bd-4495-9a27-30629649cf57") override fun createFor(lens: LensesComponent.Lens): LensesComponent.RemoteApiService = CatFactRemoteApiService } override fun process( request: LensesComponent.RemoteApiService.Request, onResponse: Consumer<LensesComponent.RemoteApiService.Response> ): LensesComponent.RemoteApiService.Call { return when (val endpointId = request.endpointId) { "fact" -> { var connection: HttpURLConnection? = null try { val url = URL("$BASE_URL/$endpointId") connection = (url.openConnection() as HttpURLConnection).apply { setRequestProperty(HEADER_ACCEPT, MIME_TYPE_JSON) doOutput = false } val body = connection.inputStream.readBytes() onResponse.accept(request.toSuccessResponse(body = body)) } catch (e: IOException) { onResponse.accept(request.toInternalServerErrorResponse()) } finally { connection?.disconnect() } LensesComponent.RemoteApiService.Call.Answered } else -> LensesComponent.RemoteApiService.Call.Ignored } } override fun close() { // no-op } }
0
null
34
99
e7fe6005c3addce34b1d61f97ae08d64728252af
2,660
camera-kit-reference
MIT License
src/test/kotlin/org/bullet/TraditionalSudokuTest.kt
jonckvanderkogel
261,028,690
false
null
package org.bullet import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class TraditionalSudokuTest { @Test fun testCorrectMovesGenerated() { val sudokuSolver = SudokuSolver(TraditionalSudoku()) val moves = sudokuSolver.solve().sortedBy { it.cell.id } assertEquals(2, moves[0].value) assertEquals(9, moves[1].value) assertEquals(5, moves[2].value) assertEquals(6, moves[3].value) assertEquals(4, moves[4].value) assertEquals(7, moves[5].value) assertEquals(8, moves[6].value) assertEquals(1, moves[7].value) assertEquals(3, moves[8].value) assertEquals(6, moves[9].value) assertEquals(3, moves[10].value) assertEquals(8, moves[11].value) assertEquals(2, moves[12].value) assertEquals(1, moves[13].value) assertEquals(5, moves[14].value) assertEquals(4, moves[15].value) assertEquals(7, moves[16].value) assertEquals(9, moves[17].value) assertEquals(1, moves[18].value) assertEquals(4, moves[19].value) assertEquals(7, moves[20].value) assertEquals(9, moves[21].value) assertEquals(3, moves[22].value) assertEquals(8, moves[23].value) assertEquals(2, moves[24].value) assertEquals(5, moves[25].value) assertEquals(6, moves[26].value) assertEquals(8, moves[27].value) assertEquals(7, moves[28].value) assertEquals(6, moves[29].value) assertEquals(4, moves[30].value) assertEquals(5, moves[31].value) assertEquals(1, moves[32].value) assertEquals(3, moves[33].value) assertEquals(9, moves[34].value) assertEquals(2, moves[35].value) assertEquals(3, moves[36].value) assertEquals(1, moves[37].value) assertEquals(2, moves[38].value) assertEquals(7, moves[39].value) assertEquals(6, moves[40].value) assertEquals(9, moves[41].value) assertEquals(5, moves[42].value) assertEquals(8, moves[43].value) assertEquals(4, moves[44].value) assertEquals(9, moves[45].value) assertEquals(5, moves[46].value) assertEquals(4, moves[47].value) assertEquals(8, moves[48].value) assertEquals(2, moves[49].value) assertEquals(3, moves[50].value) assertEquals(7, moves[51].value) assertEquals(6, moves[52].value) assertEquals(1, moves[53].value) assertEquals(4, moves[54].value) assertEquals(2, moves[55].value) assertEquals(9, moves[56].value) assertEquals(5, moves[57].value) assertEquals(7, moves[58].value) assertEquals(6, moves[59].value) assertEquals(1, moves[60].value) assertEquals(3, moves[61].value) assertEquals(8, moves[62].value) assertEquals(7, moves[63].value) assertEquals(6, moves[64].value) assertEquals(1, moves[65].value) assertEquals(3, moves[66].value) assertEquals(8, moves[67].value) assertEquals(2, moves[68].value) assertEquals(9, moves[69].value) assertEquals(4, moves[70].value) assertEquals(5, moves[71].value) assertEquals(5, moves[72].value) assertEquals(8, moves[73].value) assertEquals(3, moves[74].value) assertEquals(1, moves[75].value) assertEquals(9, moves[76].value) assertEquals(4, moves[77].value) assertEquals(6, moves[78].value) assertEquals(2, moves[79].value) assertEquals(7, moves[80].value) } }
0
Kotlin
0
0
3a46b1fab61a78ed037e14aca68a20e81e55c6fd
3,634
sudoku-solver
The Unlicense
poko-compiler-plugin/src/test/resources/data/OuterClass.kt
drewhamilton
243,601,035
false
null
package data @Suppress("unused") class OuterClass { data class Nested( val value: String ) }
6
Kotlin
3
99
3d433f1851085076efc88ce8e9cfcbce8d8ba841
110
Poko
Apache License 2.0
src/main/kotlin/site/liangbai/lbapi/util/ClassUtil.kt
Liangbai2333
846,688,168
false
{"Kotlin": 122537}
package site.liangbai.lbapi.util fun findClassOrNull(clazz: String): Class<*>? { return try { Class.forName(clazz) } catch (e: ClassNotFoundException) { null } }
0
Kotlin
0
0
d10ef178a7cd31845a99b51b25ccf222303afa52
190
LBAPI
Creative Commons Zero v1.0 Universal
src/main/kotlin/coffee/cypher/hexbound/feature/construct/command/ConstructCommand.kt
Cypher121
569,248,192
false
{"Kotlin": 172761, "Java": 13563, "GLSL": 2732}
package coffee.cypher.hexbound.feature.construct.command import coffee.cypher.hexbound.feature.construct.command.execution.ConstructCommandContext import coffee.cypher.hexbound.init.HexboundData import coffee.cypher.kettle.scheduler.TaskContext import com.mojang.serialization.Codec import kotlinx.serialization.Serializable import net.minecraft.server.world.ServerWorld import net.minecraft.text.Text interface ConstructCommand<C : ConstructCommand<C>> { fun getType(): Type<C> fun display(world: ServerWorld): Text suspend fun TaskContext<out ConstructCommandContext>.execute() data class Type<C : ConstructCommand<C>>( val codec: Codec<C> ) } @Serializable class NoOpCommand : ConstructCommand<NoOpCommand> { override fun getType() = HexboundData.ConstructCommandTypes.NO_OP override fun display(world: ServerWorld): Text { return Text.translatable("hexbound.construct.command.no_op") } override suspend fun TaskContext<out ConstructCommandContext>.execute() { } }
2
Kotlin
3
2
dd1e93bb95221790f2ca7b3c20332c70fd5ae3f4
1,032
hexbound
MIT License
app/src/main/java/com/example/flowsexemple/MainActivity.kt
gitdaniellopes
574,623,412
false
null
package com.example.flowsexemple import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.Button import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import com.example.flowsexemple.ui.UserViewModel import com.example.flowsexemple.ui.theme.FlowsExempleTheme class MainActivity : ComponentActivity() { private val userViewModel by viewModels<UserViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { FlowsExempleTheme { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Button( onClick = { userViewModel.startGenerate() } ) { Text(text = "Start Export") } } if (userViewModel.isLoading) { Dialog( onDismissRequest = {} ) { Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(15.dp), horizontalAlignment = Alignment.CenterHorizontally ) { CircularProgressIndicator( color = Color.White ) Text( text = "Progressing user data (${userViewModel.processState} %) ...", color = Color.White, style = MaterialTheme.typography.body1 ) } } } } } } }
0
Kotlin
0
0
6ff0b5188ff05988aa4c1572cc88bd6049b4ef94
2,552
FlowsOperators
MIT License
src/main/kotlin/ru/resprojects/vqct/ImageUtils.kt
mrResident
125,758,915
false
null
/* MIT License Copyright (c) 2018 Aleksandr 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 ru.resprojects.vqct import mu.KotlinLogging import org.im4java.core.ImageCommand import org.im4java.core.ConvertCmd import org.im4java.core.IdentifyCmd import org.im4java.core.CompositeCmd import org.im4java.core.CompareCmd import org.im4java.core.IMOperation import org.im4java.process.ArrayListErrorConsumer import org.im4java.process.ArrayListOutputConsumer import org.openqa.selenium.Dimension import java.awt.Toolkit import java.io.File import java.io.FileNotFoundException /** * @author <NAME> aka mrResident */ private val logger = KotlinLogging.logger {} /** * ImageMagick utilities */ private enum class CommandType { CONVERT, IDENTIFY, COMPOSITECMD, COMPARE } /** * ImgaeMagick tools. * @param settings program settings */ class IMUtils(private val settings: ProgramSettings) { /** * Getting IM utilities. * @param commandType ImageMagick utilities * @return IM command */ private fun getImageCommand(commandType: CommandType): ImageCommand { try { val imPath = settings.getImageMagick().absolutePath val imageCommand = when (commandType) { CommandType.CONVERT -> ConvertCmd(false) CommandType.IDENTIFY -> IdentifyCmd(false) CommandType.COMPOSITECMD -> CompositeCmd(false) CommandType.COMPARE -> CompareCmd(false) } imageCommand.searchPath = imPath return imageCommand } catch (err: FileNotFoundException) { throw FileNotFoundException("${err.message}. ImageMagick v 6.x.x is not found! For download ImageMagick please visit https://legacy.imagemagick.org/script/download.php") } } /** * Getting info from graphic file. * @param imageFile graphic file * @return image information */ fun getImageInfo(imageFile: File): ImageInfo { if (!imageFile.exists()) { throw FileNotFoundException("Image file ${imageFile.absolutePath} not found!") } try { val operation = IMOperation() operation.format("%w,%h,%Q,%m") operation.addImage() val identyfyCmd = getImageCommand(CommandType.IDENTIFY) val output = ArrayListOutputConsumer() identyfyCmd.setOutputConsumer(output) identyfyCmd.run(operation, imageFile.absolutePath) val list = mutableListOf<String>() list.addAll(output.output[0].split(",")) list.add(imageFile.absolutePath) return ImageInfo(list) } catch (err: Exception) { throw IllegalStateException("Error while reading image file ${imageFile.absolutePath}. ${err.message}") } } /** * Cropping input image image. For more information see IM manual https://www.imagemagick.org/Usage/crop/#crop * @param inputImage input image that needes cropping * @param outputImage output cropping image * @param dimension dimension (part or all image) for cropping * @param x count of pixels for cropping * @param y count of pixels for cropping * @return false if appeared error while image cropping */ fun cropImage(inputImage: File, outputImage: File, dimension: Dimension, x: Int, y: Int): Boolean { if (!inputImage.exists()) { throw FileNotFoundException("Input file ${inputImage.absolutePath} not found!") } return try { val operation = IMOperation() operation.addImage(inputImage.absolutePath) operation.crop(dimension.getWidth(), dimension.getHeight(), x, y) operation.p_repage() operation.addImage(outputImage.absolutePath) val convert = getImageCommand(CommandType.CONVERT) convert.run(operation) true } catch (err: Exception) { logger.error(err) { "Error while cropping image: ${err.message}" } false } } /** * Trimming input image image. For more information see IM manual https://www.imagemagick.org/Usage/crop/#trim * @param inputImage input image that needes trimming * @param outputImage output trimmed image * @return false if appeared error while image trimming */ fun trimImage(inputImage: File, outputImage: File): Boolean { if (!inputImage.exists()) { throw FileNotFoundException("Input file ${inputImage.absolutePath} not found!") } return try { val operation = IMOperation() operation.addImage(inputImage.absolutePath) operation.trim() operation.p_repage() operation.addImage(outputImage.absolutePath) val convert = getImageCommand(CommandType.CONVERT) convert.run(operation) true } catch (err: Exception) { logger.error(err) { "Error while trimming image: ${err.message}" } false } } /** * Resizing input image file. For more information see IM manual https://www.imagemagick.org/Usage/resize/#resize * @param inputImage input image that needes resizing * @param outputImage output resized image * @param width new image width * @param height new image height * @return false if appeared error while image resized */ fun resizeImage(inputImage: File, outputImage: File, width: Int, height: Int): Boolean { if (!inputImage.exists()) { throw FileNotFoundException("Input file ${inputImage.absolutePath} not found!") } return try { val operation = IMOperation() operation.addImage(inputImage.absolutePath) operation.resize(width, height) operation.addImage(outputImage.absolutePath) val convert = getImageCommand(CommandType.CONVERT) convert.run(operation) true } catch (err: Exception) { logger.error(err) { "Error while resizing image: ${err.message}" } false } } /** * Comparing two image. For more information see IM manual https://www.imagemagick.org/Usage/compare/ * @param inputImage_1 first image for comparing * @param inputImage_2 second image for comparing * @param outputImage output image with comparing result * @return absolute error count, number of different pixels */ fun compareImage(inputImage_1: File, inputImage_2: File, outputImage: File): Int { if (!inputImage_1.exists()) { throw FileNotFoundException("Input file ${inputImage_1.absolutePath} not found!") } if (!inputImage_2.exists()) { throw FileNotFoundException("Input file ${inputImage_2.absolutePath} not found!") } val operation = IMOperation() val compareCmd = getImageCommand(CommandType.COMPARE) val error = ArrayListErrorConsumer() compareCmd.setErrorConsumer(error) operation.metric("ae") operation.fuzz(settings.getImFuzz(), true) operation.addImage(inputImage_1.absolutePath) operation.addImage(inputImage_2.absolutePath) operation.addImage(outputImage.absolutePath) val isEquals = try { compareCmd.run(operation) true } catch (err: Exception) { false } return if (!isEquals) { if (!error.output.isEmpty()) { try { error.output[0].toInt() } catch (err: NumberFormatException) { -1 } } else { -1 } } else { 0 } } } /** * Image file information. * @param inputData image information (returned from IM) */ data class ImageInfo(private val inputData: List<String>) { /** * Image size (width and height). */ val imageSize: Dimension /** * Image compression quality. */ val imageQuality: Double /** * Image file format. */ val imageFormat: String /** * Image file. */ val imageFile: File init { try { imageSize = Dimension(inputData[0].toInt(), inputData[1].toInt()) imageQuality = inputData[2].toDouble() imageFormat = inputData[3] imageFile = File(inputData[4]) } catch (err: Exception) { throw IllegalStateException("Can't get image info.") } } } /** * Return current screen resolution. */ fun getCurrentScreenResolution(): Dimension { return Dimension(Toolkit.getDefaultToolkit().screenSize.width, Toolkit.getDefaultToolkit().screenSize.height) }
0
Kotlin
0
0
ad8308624ae6c2a119203f623fb69180d10629f1
9,797
vqct
MIT License
app/src/main/java/com/lloydsbyte/careeradvr_ai/history/HistoryViewModel.kt
Jeremyscell82
742,598,615
false
{"Kotlin": 248987}
package com.lloydsbyte.careeradvr_ai.history import androidx.lifecycle.ViewModel import com.lloydsbyte.database.AppDatabase import com.lloydsbyte.database.models.ChatHeaderModel import com.lloydsbyte.database.models.ChatModel import io.reactivex.Flowable class HistoryViewModel: ViewModel() { fun getChatHistory(appDatabase: AppDatabase): Flowable<List<ChatHeaderModel>> { //Gets the headers from the db return appDatabase.chatHistoryDao().getConversationHeaders() } /** ViewModel Section for the conversation Page **/ var convoHeaderModel: ChatHeaderModel? = null var convoCarbonCopy: List<ChatModel> = emptyList() fun getConversation(appDatabase: AppDatabase, convoId: Long): Flowable<List<ChatModel>> { //Gets the headers from the db return appDatabase.chatHistoryDao().getConversation(convoId) } }
0
Kotlin
0
0
0694c4a9e47b3708e82745e3391c509d826fd69f
868
CareerAdvr_AI
Apache License 2.0
atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupDelivery.kt
input-output-hk
564,174,099
false
{"Kotlin": 610965, "Gherkin": 1987, "ANTLR": 1440, "JavaScript": 375}
package io.iohk.atala.prism.walletsdk.prismagent.protocols.pickup import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor import io.iohk.atala.prism.walletsdk.domain.models.Message import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType final class PickupDelivery @Throws(PrismAgentError.InvalidMessageType::class) constructor(fromMessage: Message) { var id: String var type = ProtocolType.PickupDelivery.value val attachments: Array<AttachmentDescriptor> init { if (fromMessage.piuri != ProtocolType.PickupDelivery.value) { throw PrismAgentError.InvalidMessageType( type = fromMessage.piuri, shouldBe = ProtocolType.PickupDelivery.value ) } this.id = fromMessage.id this.attachments = fromMessage.attachments } }
2
Kotlin
0
5
444511c14a438f6b6487c5cb7ece3cdd1f6be5d4
920
atala-prism-wallet-sdk-kmm
Apache License 2.0
kt/godot-library/src/main/kotlin/godot/gen/godot/VisualShaderNodeBooleanParameter.kt
utopia-rise
289,462,532
false
null
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT", "RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate") package godot import godot.`annotation`.GodotBaseType import godot.core.VariantType.BOOL import godot.core.VariantType.NIL import godot.core.memory.TransferContext import kotlin.Boolean import kotlin.Int import kotlin.Suppress /** * A boolean parameter to be used within the visual shader graph. * * Translated to `uniform bool` in the shader language. */ @GodotBaseType public open class VisualShaderNodeBooleanParameter : VisualShaderNodeParameter() { /** * Enables usage of the [defaultValue]. */ public var defaultValueEnabled: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODEBOOLEANPARAMETER_IS_DEFAULT_VALUE_ENABLED, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODEBOOLEANPARAMETER_SET_DEFAULT_VALUE_ENABLED, NIL) } /** * A default value to be assigned within the shader. */ public var defaultValue: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODEBOOLEANPARAMETER_GET_DEFAULT_VALUE, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODEBOOLEANPARAMETER_SET_DEFAULT_VALUE, NIL) } public override fun new(scriptIndex: Int): Boolean { callConstructor(ENGINECLASS_VISUALSHADERNODEBOOLEANPARAMETER, scriptIndex) return true } public companion object }
60
null
28
412
fe7379a450ed32ad069f3b672709a2520b86f092
2,204
godot-kotlin-jvm
MIT License
idea/tests/testData/search/annotations/testAnnotationsOnPropertiesAndParameters.kt
JetBrains
278,369,660
false
null
data class TestClass1(@java.lang.Deprecated val pctorfield: Int) { constructor(@java.lang.Deprecated param: Int, param2: String) : this(param) } class TestClass2( @param:java.lang.Deprecated val deprecatedParamField: Int, @field:java.lang.Deprecated val deprecatedField: Int, @java.lang.Deprecated constructorParam: Int ) { fun foo(@java.lang.Deprecated functionParam) {} } // ANNOTATION: java.lang.Deprecated // SEARCH: field:deprecatedField // SEARCH: field:deprecatedParamField // SEARCH: field:pctorfield // SEARCH: method:component1 // SEARCH: method:getDeprecatedField // SEARCH: method:getDeprecatedParamField // SEARCH: method:getPctorfield // SEARCH: param:constructorParam // SEARCH: param:deprecatedField // SEARCH: param:deprecatedParamField // SEARCH: param:pctorfield // SEARCH: param:functionParam // SEARCH: param:param
0
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
858
intellij-kotlin
Apache License 2.0
ast-model/src/org/jetbrains/dukat/astModel/statements/AssignmentStatementModel.kt
Kotlin
159,510,660
false
{"Kotlin": 2656818, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333}
package org.jetbrains.dukat.astModel.statements import org.jetbrains.dukat.astModel.expressions.ExpressionModel data class AssignmentStatementModel( val left: ExpressionModel, val right: ExpressionModel, override val metaDescription: String? = null ) : StatementModel
244
Kotlin
42
535
d50b9be913ce8a2332b8e97fd518f1ec1ad7f69e
293
dukat
Apache License 2.0
itreader/app/src/main/java/com/softkare/itreader/fragments/CatalogFragment.kt
UNIZAR-30226-2022-06
462,706,769
false
{"Kotlin": 110962, "Java": 16499}
package com.softkare.itreader.fragments import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.softkare.itreader.R import com.softkare.itreader.adapter.bookAdapter import com.softkare.itreader.backend.Libro import com.softkare.itreader.backend.ListaLibros import com.softkare.itreader.backend.MyApiEndpointInterface import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class CatalogFragment : Fragment() { lateinit var list : List<Libro> lateinit var list2 : ListaLibros var sublist : MutableList<Libro> = mutableListOf() var isLoading = false var limit = 5 lateinit var adapter: bookAdapter lateinit var layoutManager : LinearLayoutManager lateinit var contexto : Context override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_catalog,container,false) val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerBooks) val pb = view.findViewById<Button>(R.id.progress_bar) list = listOf() sublist = mutableListOf() var page = 1 contexto = requireContext() recyclerView.layoutManager = LinearLayoutManager(context) conseguir_lista(recyclerView,pb,view,page) pb.setOnClickListener{ page++ conseguir_lista(recyclerView,pb,view,page) } return view } private fun conseguir_lista(recyclerView: RecyclerView, pb: Button, view: View, page: Int) { val retrofit = Retrofit.Builder() .baseUrl(MyApiEndpointInterface.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() val service = retrofit.create(MyApiEndpointInterface::class.java) service.libroList(page).enqueue(object : Callback<ListaLibros> { override fun onResponse(call: Call<ListaLibros>, response: Response<ListaLibros>) { if (response.body() != null) { list2 = response.body()!! sublist.addAll(list2.results) list = sublist recyclerView.adapter = bookAdapter(list) pb.setVisibility(View.VISIBLE); } else { Toast.makeText(requireContext(),"No hay más libros para cargar", Toast.LENGTH_SHORT).show() pb.setVisibility(View.GONE); } } override fun onFailure(call: Call<ListaLibros>, t: Throwable) { println("FALLO REGISTRO") } }) } }
0
Kotlin
1
1
8def93df5e38152092acdab330de475eb6018648
3,029
Mobile-FrontEnd
MIT License
src/main/kotlin/_0079_WordSearch.kt
ryandyoon
664,493,186
false
null
// https://leetcode.com/problems/word-search fun exist(board: Array<CharArray>, word: String): Boolean { val visited = Array(board.size) { BooleanArray(board.first().size) } for (row in board.indices) { for (col in board.first().indices) { if (dfs(row = row, col = col, index = 0, word = word, board = board, visited = visited)) { return true } } } return false } fun dfs( row: Int, col: Int, index: Int, word: String, board: Array<CharArray>, visited: Array<BooleanArray> ): Boolean { if (visited[row][col] || board[row][col] != word[index]) return false if (index == word.lastIndex) return true visited[row][col] = true if (board.valid(row - 1, col) && dfs(row - 1, col, index + 1, word, board, visited)) return true if (board.valid(row + 1, col) && dfs(row + 1, col, index + 1, word, board, visited)) return true if (board.valid(row, col - 1) && dfs(row, col - 1, index + 1, word, board, visited)) return true if (board.valid(row, col + 1) && dfs(row, col + 1, index + 1, word, board, visited)) return true visited[row][col] = false return false } private fun Array<CharArray>.valid(row: Int, col: Int): Boolean { return row >= 0 && row <= this.lastIndex && col >= 0 && col <= this.first().lastIndex }
0
Kotlin
0
0
7f75078ddeb22983b2521d8ac80f5973f58fd123
1,343
leetcode-kotlin
MIT License
app/src/main/java/com/ihfazh/yonotifme/feeds/ui/feeddetail/FeedDetailViewModel.kt
ihfazhillah
378,676,829
false
null
package com.ihfazh.yonotifme.feeds.ui.feeddetail import androidx.lifecycle.* import com.ihfazh.yonotifme.feeds.domain.models.Item import com.ihfazh.yonotifme.feeds.usecases.DetailFeedUseCase import com.ihfazh.yonotifme.feeds.usecases.ListFeedUseCase import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class FeedDetailViewModel @Inject constructor( private val useCase: DetailFeedUseCase ): ViewModel() { val feedId = MutableLiveData("") val feedDetail = Transformations.switchMap(feedId){ LiveDataReactiveStreams.fromPublisher(useCase.detail(it)) } }
0
Kotlin
0
0
d6796792f65bba3b1e968a2784ca12513fcae7aa
618
yonotifme
MIT License
app/src/main/java/com/andreiliphd/asteroidradar/main/MainViewModel.kt
andreiliphd
384,741,627
false
null
package com.andreiliphd.asteroidradar.main import android.app.Application import android.os.Build import android.util.Log import androidx.lifecycle.* import androidx.work.* import com.andreiliphd.asteroidradar.database.Asteroid import com.andreiliphd.asteroidradar.database.AsteroidDatabaseDao import com.andreiliphd.asteroidradar.database.AsteroidRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.* import java.util.concurrent.TimeUnit class MainViewModel( val database: AsteroidDatabaseDao, application: Application ) : AndroidViewModel(application) { private var asteroid = MutableLiveData<Asteroid?>() lateinit var asteroids: LiveData<MutableList<Asteroid>> init { initializeasteroid() } private val _navigateToAsteroid = MutableLiveData<Asteroid>() val navigateToAsteroid get() = _navigateToAsteroid fun onAsteroidClicked(asteroid: Asteroid) { Log.i("click_listener", "Clicked on asteroid " + asteroid.toString()) _navigateToAsteroid.value = asteroid } fun onAsteroidNavigated() { _navigateToAsteroid.value = null } private fun initializeasteroid() { val updateDatabase = OneTimeWorkRequestBuilder<AsteroidRepository>().build() WorkManager.getInstance().enqueue(updateDatabase) val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.UNMETERED) .setRequiresCharging(true) .setRequiresBatteryNotLow(true) .setRequiresStorageNotLow(true) .apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { setRequiresDeviceIdle(true) } }.build() val repeatingRequest = PeriodicWorkRequestBuilder<AsteroidRepository>(1, TimeUnit.DAYS) .setConstraints(constraints) .build() WorkManager.getInstance().enqueueUniquePeriodicWork( AsteroidRepository.WORK_NAME, ExistingPeriodicWorkPolicy.KEEP, repeatingRequest) viewModelScope.launch { Log.i("seven-days", database.getPeriod(Date(Calendar.getInstance().timeInMillis), Date(Calendar.getInstance().timeInMillis + 7 * 24 * 3600 * 1000)).toString()) asteroids = database.getPeriod(Date(Calendar.getInstance().timeInMillis), Date(Calendar.getInstance().timeInMillis + 7 * 24 * 3600 * 1000)) } } /** * Handling the case of the stopped app or forgotten recording, * the start and end times will be the same.j * * If the start time and end time are not the same, then we do not have an unfinished * recording. */ private suspend fun getasteroidFromDatabase(): Asteroid? { //return withContext(Dispatchers.IO) { val asteroid = database.getToasteroid() return asteroid //} } private suspend fun clear() { withContext(Dispatchers.IO) { database.clear() } } private suspend fun update(asteroid: Asteroid) { withContext(Dispatchers.IO) { database.update(asteroid) } } private suspend fun insert(asteroid: Asteroid) { withContext(Dispatchers.IO) { database.insert(asteroid) } } }
0
Kotlin
0
0
b3a2e03e694a839e92b1e1b21ad28b0c41a52d09
3,394
dmitry-nasa-asteroid-explorer
MIT License
src/main/kotlin/com/msousa/estate/dto/SellerDTO.kt
Michael-Silva-de-Sousa
551,706,603
false
null
package com.msousa.estate.dto import com.fasterxml.jackson.annotation.JsonProperty import com.msousa.estate.modules.saller.Seller import java.util.* data class SellerDTO( @JsonProperty("sellerId") val sellerId: UUID?, @JsonProperty("name") val name: String, @JsonProperty("email") val email: String, @JsonProperty("telephone1") val telephone1: String, @JsonProperty("telephone2") val telephone2: String?, @JsonProperty("properties") val properties: List<PropertyDTO> ) { constructor(seller: Seller, properties: List<PropertyDTO>) : this( seller.sellerId, seller.name, seller.email, seller.telephone1, seller.telephone2, properties ) }
0
Kotlin
0
0
da9294149d5ed248dfb8e4969bbdbd668b031815
747
estate
Apache License 2.0
discovery/src/main/java/com/bestbuy/discovery/data/model/Product.kt
anil-gudigar
813,031,770
false
{"Kotlin": 91519}
package com.bestbuy.discovery.data.model import com.bestbuy.stylekit.ui.toDoubleOrZero import com.bestbuy.stylekit.ui.toStringOrEmpty import com.google.gson.annotations.SerializedName data class Product( @SerializedName("accessories") var accessories: List<String?>?, @SerializedName("accessoriesImage") var accessoriesImage: String?, @SerializedName("activationCharge") var activationCharge: String?, @SerializedName("active") var active: Boolean?, @SerializedName("activeUpdateDate") var activeUpdateDate: String?, @SerializedName("addToCartUrl") var addToCartUrl: String?, @SerializedName("affiliateAddToCartUrl") var affiliateAddToCartUrl: String?, @SerializedName("affiliateUrl") var affiliateUrl: String?, @SerializedName("albumLabel") var albumLabel: String?, @SerializedName("albumTitle") var albumTitle: String?, @SerializedName("alternateCategories") var alternateCategories: Any?, @SerializedName("alternateViewsImage") var alternateViewsImage: String?, @SerializedName("angleImage") var angleImage: String?, @SerializedName("artistId") var artistId: String?, @SerializedName("artistName") var artistName: String?, @SerializedName("aspectRatio") var aspectRatio: String?, @SerializedName("backViewImage") var backViewImage: String?, @SerializedName("bestSellingRank") var bestSellingRank: String?, @SerializedName("bundledIn") var bundledIn: List<String?>?, @SerializedName("buybackPlans") var buybackPlans: List<String?>?, @SerializedName("carrierModelNumber") var carrierModelNumber: String?, @SerializedName("carrierPlan") var carrierPlan: String?, @SerializedName("carrierPlans") var carrierPlans: List<String?>?, @SerializedName("carriers") var carriers: List<String?>?, @SerializedName("categoryPath") var categoryPath: List<CategoryPath?>?, @SerializedName("classId") var classId: Int?, @SerializedName("class") var classX: String?, @SerializedName("clearance") var clearance: Boolean?, @SerializedName("color") var color: String?, @SerializedName("condition") var condition: String?, @SerializedName("contracts") var contracts: List<String?>?, @SerializedName("crossSell") var crossSell: List<String?>?, @SerializedName("customerReviewAverage") var customerReviewAverage: Double?, @SerializedName("customerReviewCount") var customerReviewCount: Int?, @SerializedName("customerTopRated") var customerTopRated: Boolean?, @SerializedName("department") var department: String?, @SerializedName("departmentId") var departmentId: Int?, @SerializedName("depth") var depth: String?, @SerializedName("description") var description: String?, @SerializedName("devices") var devices: List<String?>?, @SerializedName("digital") var digital: Boolean?, @SerializedName("dollarSavings") var dollarSavings: Double?, @SerializedName("earlyTerminationFees") var earlyTerminationFees: List<String?>?, @SerializedName("energyGuideImage") var energyGuideImage: String?, @SerializedName("esrbRating") var esrbRating: String?, @SerializedName("familyIndividualCode") var familyIndividualCode: String?, @SerializedName("format") var format: String?, @SerializedName("freeShipping") var freeShipping: Boolean?, @SerializedName("freeShippingEligible") var freeShippingEligible: Boolean?, @SerializedName("frequentlyPurchasedWith") var frequentlyPurchasedWith: List<String?>?, @SerializedName("friendsAndFamilyPickup") var friendsAndFamilyPickup: Boolean?, @SerializedName("fulfilledBy") var fulfilledBy: String?, @SerializedName("genre") var genre: String?, @SerializedName("height") var height: String?, @SerializedName("homeDelivery") var homeDelivery: Boolean?, @SerializedName("image") var image: String?, @SerializedName("images") var images: List<Image?>?, @SerializedName("inStoreAvailability") var inStoreAvailability: Boolean?, @SerializedName("inStoreAvailabilityText") var inStoreAvailabilityText: String?, @SerializedName("inStoreAvailabilityUpdateDate") var inStoreAvailabilityUpdateDate: String?, @SerializedName("inStorePickup") var inStorePickup: Boolean?, @SerializedName("includedItemList") var includedItemList: List<IncludedItem?>?, @SerializedName("itemUpdateDate") var itemUpdateDate: String?, @SerializedName("largeFrontImage") var largeFrontImage: String?, @SerializedName("largeImage") var largeImage: String?, @SerializedName("leftViewImage") var leftViewImage: String?, @SerializedName("lengthInMinutes") var lengthInMinutes: String?, @SerializedName("linkShareAffiliateAddToCartUrl") var linkShareAffiliateAddToCartUrl: String?, @SerializedName("linkShareAffiliateUrl") var linkShareAffiliateUrl: String?, @SerializedName("listingId") var listingId: String?, @SerializedName("lists") var lists: List<String?>?, @SerializedName("longDescription") var longDescription: String?, @SerializedName("lowPriceGuarantee") var lowPriceGuarantee: Boolean?, @SerializedName("manufacturer") var manufacturer: String?, @SerializedName("marketplace") var marketplace: String?, @SerializedName("mediaCount") var mediaCount: String?, @SerializedName("mediumImage") var mediumImage: String?, @SerializedName("members") var members: List<String?>?, @SerializedName("minutePrice") var minutePrice: String?, @SerializedName("mobileUrl") var mobileUrl: String?, @SerializedName("modelNumber") var modelNumber: String?, @SerializedName("monoStereo") var monoStereo: String?, @SerializedName("monthlyRecurringCharge") var monthlyRecurringCharge: String?, @SerializedName("monthlyRecurringChargeGrandTotal") var monthlyRecurringChargeGrandTotal: String?, @SerializedName("mpaaRating") var mpaaRating: String?, @SerializedName("name") var name: String?, @SerializedName("new") var new: Boolean?, @SerializedName("numberOfPlayers") var numberOfPlayers: String?, @SerializedName("onSale") var onSale: Boolean?, @SerializedName("onlineAvailability") var onlineAvailability: Boolean?, @SerializedName("onlineAvailabilityText") var onlineAvailabilityText: String?, @SerializedName("onlineAvailabilityUpdateDate") var onlineAvailabilityUpdateDate: String?, @SerializedName("orderable") var orderable: String?, @SerializedName("originalReleaseDate") var originalReleaseDate: String?, @SerializedName("outletCenter") var outletCenter: String?, @SerializedName("parentalAdvisory") var parentalAdvisory: String?, @SerializedName("percentSavings") var percentSavings: String?, @SerializedName("planCategory") var planCategory: String?, @SerializedName("planFeatures") var planFeatures: List<String?>?, @SerializedName("planPrice") var planPrice: String?, @SerializedName("planType") var planType: String?, @SerializedName("platform") var platform: String?, @SerializedName("plot") var plot: String?, @SerializedName("preowned") var preowned: Boolean?, @SerializedName("priceRestriction") var priceRestriction: String?, @SerializedName("priceUpdateDate") var priceUpdateDate: String?, @SerializedName("priceWithPlan") var priceWithPlan: List<String?>?, @SerializedName("productFamilies") var productFamilies: List<String?>?, @SerializedName("productId") var productId: String?, @SerializedName("productTemplate") var productTemplate: String?, @SerializedName("productVariations") var productVariations: Any?, @SerializedName("proposition65WarningMessage") var proposition65WarningMessage: String?, @SerializedName("proposition65WarningType") var proposition65WarningType: String?, @SerializedName("protectionPlanDetails") var protectionPlanDetails: List<String?>?, @SerializedName("protectionPlanHighPrice") var protectionPlanHighPrice: String?, @SerializedName("protectionPlanLowPrice") var protectionPlanLowPrice: String?, @SerializedName("protectionPlanTerm") var protectionPlanTerm: String?, @SerializedName("protectionPlanType") var protectionPlanType: String?, @SerializedName("protectionPlans") var protectionPlans: List<String?>?, @SerializedName("quantityLimit") var quantityLimit: Int?, @SerializedName("regularPrice") var regularPrice: Double?, @SerializedName("relatedProducts") var relatedProducts: List<String?>?, @SerializedName("releaseDate") var releaseDate: String?, @SerializedName("remoteControlImage") var remoteControlImage: String?, @SerializedName("requiredParts") var requiredParts: Any?, @SerializedName("rightViewImage") var rightViewImage: String?, @SerializedName("salePrice") var salePrice: Any?, @SerializedName("salesRankLongTerm") var salesRankLongTerm: String?, @SerializedName("salesRankMediumTerm") var salesRankMediumTerm: String?, @SerializedName("salesRankShortTerm") var salesRankShortTerm: String?, @SerializedName("score") var score: String?, @SerializedName("screenFormat") var screenFormat: String?, @SerializedName("secondaryMarket") var secondaryMarket: String?, @SerializedName("sellerId") var sellerId: String?, @SerializedName("shipping") var shipping: List<Shipping?>?, @SerializedName("shippingCost") var shippingCost: Any?, @SerializedName("shippingLevelsOfService") var shippingLevelsOfService: List<ShippingLevelsOfService?>?, @SerializedName("shippingRestrictions") var shippingRestrictions: String?, @SerializedName("shippingWeight") var shippingWeight: Double?, @SerializedName("shortDescription") var shortDescription: String?, @SerializedName("sku") var sku: Int?, @SerializedName("softwareAge") var softwareAge: String?, @SerializedName("softwareGrade") var softwareGrade: String?, @SerializedName("softwareNumberOfPlayers") var softwareNumberOfPlayers: String?, @SerializedName("source") var source: String?, @SerializedName("specialOrder") var specialOrder: Boolean?, @SerializedName("spin360Url") var spin360Url: String?, @SerializedName("startDate") var startDate: String?, @SerializedName("studio") var studio: String?, @SerializedName("studioLive") var studioLive: String?, @SerializedName("subclass") var subclass: String?, @SerializedName("subclassId") var subclassId: Int?, @SerializedName("techSupportPlans") var techSupportPlans: List<String?>?, @SerializedName("technologyCode") var technologyCode: String?, @SerializedName("theatricalReleaseDate") var theatricalReleaseDate: String?, @SerializedName("thumbnailImage") var thumbnailImage: String?, @SerializedName("topViewImage") var topViewImage: String?, @SerializedName("tradeInValue") var tradeInValue: String?, @SerializedName("type") var type: String?, @SerializedName("upc") var upc: String?, @SerializedName("url") var url: String?, @SerializedName("validFrom") var validFrom: String?, @SerializedName("validUntil") var validUntil: String?, @SerializedName("warrantyLabor") var warrantyLabor: String?, @SerializedName("warrantyParts") var warrantyParts: String?, @SerializedName("weight") var weight: String?, @SerializedName("width") var width: String? ){ fun getSalesPrice():String{ return "$ " + salePrice.toStringOrEmpty() } fun getCustomDollarSaving():String{ return "SAVE $ " + dollarSavings.toStringOrEmpty() } fun getCustomerAverageReview(): Float { return (customerReviewAverage?: 0.0).toFloat() } fun getCustomCustomerReviewCount(): String { return "("+(customerReviewCount?: "0")+")" } fun getSoldOutline(): String { return if (onlineAvailability == true) "Available" else "Sold Out Online" } }
0
Kotlin
0
0
edc24dad26977c00cb6d27aa0af4b969ff0eb504
12,443
BestBuy
Apache License 2.0
connectors/dkif/src/main/kotlin/no/nav/amt/tiltak/connectors/dkif/DkifConnector.kt
navikt
393,356,849
false
null
package no.nav.amt.tiltak.connectors.dkif interface DkifConnector { fun hentBrukerKontaktinformasjon(fnr: String): Kontaktinformasjon } data class Kontaktinformasjon( val epost: String?, val telefonnummer: String?, )
2
Kotlin
1
1
ad2ec946853949301c530fdf364adf69ae8eb09d
224
amt-tiltak
MIT License
app/src/main/java/com/hl/baseproject/TestActivity2.kt
Heart-Beats
473,996,742
false
{"Kotlin": 1393280, "Java": 40623, "HTML": 2897, "AIDL": 1581}
package com.hl.baseproject import android.content.Intent import android.os.Bundle import com.hl.baseproject.databinding.ActivityTest2Binding import com.hl.bitmaputil.toBitmap import com.hl.ui.utils.onClick import com.hl.uikit.toast import com.hl.utils.PaletteUtil import com.hl.utils.registerReceiver class TestActivity2 : com.hl.ui.base.ViewBindingBaseActivity<ActivityTest2Binding>() { companion object { const val TEST_ACTION = "com.hl.action.test" } @Deprecated("Deprecated in Java") override fun onBackPressed() { setResult(RESULT_OK, Intent().apply { this.putExtra("data", "我是测试2页面数据") }) super.onBackPressed() } override fun ActivityTest2Binding.onViewCreated(savedInstanceState: Bundle?) { [email protected](TEST_ACTION) { _, intent -> if (intent.action == TEST_ACTION) { toast("我收到测试广播啦") } } uikitToolbar.title = "测试长度测试长度测试长度测试长度测试长度测试长度测试长度" uikitToolbar.addRightActionText("按钮1") { sendBroadcast(Intent(TEST_ACTION)) } radioGroup.setOnCheckedChangeListener { _, checkedId -> if (checkedId == radioButtonDark.id) { contentLayout.setBackgroundResource(R.drawable.dark_image) } else { contentLayout.setBackgroundResource(R.drawable.light_image) } } radioGroup.check(radioButtonDark.id) testPalette.onClick { contentLayout.toBitmap()?.run { PaletteUtil.getColorFromBitmap(this) { rgb, _, _, isLight -> toast("是否为深色的图片 == ${!isLight}") immersionBar?.apply { statusBarColorInt(rgb) statusBarDarkFont(isLight) }?.init() } } } } }
1
Kotlin
3
2
7d297415585c0919845d928f8df0804ebe3c2b90
1,571
BaseProject
Apache License 2.0
react-table-kotlin/src/jsMain/kotlin/tanstack/table/core/StringOrTemplateHeader.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! @file:Suppress( "NOTHING_TO_INLINE", ) package tanstack.table.core sealed external interface StringOrTemplateHeader<TData : RowData, TValue> /* string | ColumnDefTemplate<HeaderContext<TData, TValue>> */ inline fun <TData : RowData, TValue> StringOrTemplateHeader( source: String, ): StringOrTemplateHeader<TData, TValue> = source.unsafeCast<StringOrTemplateHeader<TData, TValue>>() inline fun <TData : RowData, TValue> StringOrTemplateHeader( source: ColumnDefTemplate<HeaderContext<TData, TValue>>, ): StringOrTemplateHeader<TData, TValue> = source.unsafeCast<StringOrTemplateHeader<TData, TValue>>()
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
672
types-kotlin
Apache License 2.0
kotlin/goi/src/main/kotlin/net/paploo/goi/persistence/anki/vocabulary/VocabularyWriter.kt
paploo
526,415,165
false
{"Kotlin": 546703, "Ruby": 153592, "Java": 50625, "ANTLR": 2824, "CSS": 1827, "PLpgSQL": 274}
package net.paploo.goi.persistence.anki.vocabulary import net.paploo.goi.persistence.common.CsvFormats import org.apache.commons.csv.CSVFormat import org.apache.commons.csv.CSVPrinter import java.io.FileWriter import java.nio.file.Path internal class VocabularyWriter : suspend (Path, List<VocabularyCsvRecord>) -> Result<Unit> { val format: CSVFormat = CsvFormats.anki override suspend fun invoke(filePath: Path, records: List<VocabularyCsvRecord>): Result<Unit> = Result.runCatching { FileWriter(filePath.toFile()) }.map { writer -> CSVPrinter(writer, format) }.map { printer -> printer.use { directives.forEach { (key, value) -> it.printComment("${key}:${value}") } records.forEach { record -> it.printRecord(record.toRow()) } } } private val directives: List<Pair<String, String>> by lazy { listOf( "separator" to "Comma", "deck" to "日本語 Vocab", "notetype" to "日本語 Vocab", "tags column" to headers.size.toString(), "columns" to headers.joinToString(","), ) } private val headers: List<String> by lazy { VocabularyCsvRecord.Field.entries.map { it.headerName } } }
3
Kotlin
0
0
2e079167ab823f78315898eb5509af1b947f4c38
1,365
goi
MIT License
taxiql-query-engine/src/test/java/com/orbitalhq/models/functions/FunctionDiscoveryTest.kt
orbitalapi
541,496,668
false
{"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337}
package com.orbitalhq.models.functions import org.junit.Test class FunctionDiscoveryTest { @Test fun `nulls from concat are ignored`() { } }
9
TypeScript
10
292
2be59abde0bd93578f12fc1e2ecf1f458a0212ec
154
orbital
Apache License 2.0
kafka-flow-client/src/main/kotlin/kafka/flow/utils/Logger.kt
Jeff-Gillot
379,021,992
false
null
package kafka.flow.utils import org.slf4j.Logger import org.slf4j.LoggerFactory public inline fun <reified T> T.logger(): Logger = LoggerFactory.getLogger(T::class.java)
0
Kotlin
2
5
1551f25a3874eeaed9d532cc27a2249c389aaebd
171
kafka-flow
MIT License
verik-importer/src/main/kotlin/io/verik/importer/ast/element/declaration/ECompanionObject.kt
frwang96
269,980,078
false
null
/* * SPDX-License-Identifier: Apache-2.0 */ package io.verik.importer.ast.element.declaration import io.verik.importer.common.Visitor import io.verik.importer.message.SourceLocation /** * Element that represents a Kotlin companion object declaration. */ class ECompanionObject( override val location: SourceLocation, override var declarations: ArrayList<EDeclaration> ) : EContainerDeclaration() { override val name = "Companion" override var signature: String? = null init { declarations.forEach { it.parent = this } } override fun accept(visitor: Visitor) { visitor.visitCompanionObject(this) } }
0
Kotlin
1
33
ee22969235460fd144294bcbcbab0338c638eb92
657
verik
Apache License 2.0
announcer/src/main/java/com/smokelaboratory/announcer/Announcement.kt
smokelaboratory
316,990,954
false
null
package com.smokelaboratory.announcer /** * a parent class for values to announced * extend this class for all announcement data-holder classes */ abstract class Announcement
0
Kotlin
0
1
7c87e1bb0e158749e942ca9509f9150be53a206f
178
announcer
Apache License 2.0
app/src/main/java/com/yangbw/libtest/ui/viewmodel/SetViewModel.kt
yangbangwei
287,162,841
false
null
package com.yangbw.libtest.ui.viewmodel import com.library.common.mvvm.BaseViewModel import com.yangbw.libtest.api.ApiService /** * @author yangbw * @date */ class SetViewModel : BaseViewModel<ApiService>()
0
Kotlin
3
10
5625a45c95b9945446df388dcd229f271d3e619c
212
MvvmLib
Apache License 2.0
kaadin-core/src/test/kotlin/ch/frankel/kaadin/interaction/ButtonTest.kt
nfrankel
67,986,056
false
null
/* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.frankel.kaadin.interaction import ch.frankel.kaadin.button import ch.frankel.kaadin.disable import ch.frankel.kaadin.enable import ch.frankel.kaadin.horizontalLayout import com.vaadin.server.FontAwesome.* import com.vaadin.ui.* import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.Test class ButtonTest { @Test fun `button should be added to layout`() { val layout = horizontalLayout { button() } assertThat(layout.componentCount).isEqualTo(1) val component = layout.getComponent(0) assertThat(component).isNotNull.isInstanceOf(Button::class.java) } @Test(dependsOnMethods = ["button should be added to layout"]) fun `button should display a specific caption`() { val caption = "Hello world" val layout = horizontalLayout { button(caption) } val button = getButton(layout) assertThat(button.caption).isEqualTo(caption) } @Test(dependsOnMethods = ["button should be added to layout"]) fun `button should display a specific icon`() { val icon = AMAZON val layout = horizontalLayout { button(icon = icon) } val button = getButton(layout) assertThat(button.icon).isSameAs(icon) } @Test(dependsOnMethods = ["button should be added to layout"]) fun `button should display a specific caption and icon`() { val caption = "Hello world" val icon = AMAZON val layout = horizontalLayout { button(caption, icon) } val button = getButton(layout) assertThat(button.caption).isEqualTo(caption) assertThat(button.icon).isSameAs(icon) } @Test(dependsOnMethods = ["button should be added to layout"]) fun `button should react on a specific click listener`() { var clicked = false val layout = horizontalLayout { button(onClick = { clicked = true }) } val button = getButton(layout) button.click() assertThat(clicked).isTrue } @Test(dependsOnMethods = ["button should be added to layout"]) fun `button should be configurable in the lambda`() { val data = "dummy" val caption = "Hello world" val layout = horizontalLayout { button { this.caption = caption this.data = data } } val button = getButton(layout) assertThat(button.data).isEqualTo(data) assertThat(button.caption).isEqualTo(caption) } @Test(dependsOnMethods = ["button should be added to layout"]) fun `disable button should set its enabled property to false`() { val layout = horizontalLayout { button { disable() } } val button = getButton(layout) assertThat(button.isEnabled).isEqualTo(false) } @Test(dependsOnMethods = ["button should be added to layout"]) fun `enable button should set its enabled property to true()`() { val layout = horizontalLayout { button { isEnabled = false enable() } } val button = getButton(layout) assertThat(button.isEnabled).isEqualTo(true) } private fun getButton(layout: HorizontalLayout) = layout.getComponent(0) as Button }
3
Kotlin
12
45
0d45069d10605da60253059ced4ffedc740de133
3,997
kaadin
Apache License 2.0
app/src/main/java/io/github/lucasfsc/html2pdfapp/MainActivity.kt
amansatija
362,066,346
true
{"Kotlin": 8446}
package io.github.lucasfsc.html2pdfapp import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log import io.github.lucasfsc.html2pdf.Html2Pdf import io.github.lucasfsc.html2pdfapp.R import java.io.File import java.net.URI class MainActivity : AppCompatActivity(), Html2Pdf.OnCompleteConversion { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d("Tag",""+externalCacheDir+File.separator+"temp.pdf") try {//Impl example val converter = Html2Pdf.Companion.Builder() .context(this) .html("<p> Your awesome HTML string here! </p>") .file(File(""+externalCacheDir+File.separator+"temp.pdf")) .build() //can be called with a callback to warn the user converter.convertToPdf(this) //or without a callback converter.convertToPdf() } catch (e: Exception) { e.printStackTrace() } } override fun onSuccess() { //do your thing } override fun onFailed(error: Exception?) { //do your thing error?.printStackTrace() } }
0
Kotlin
0
1
57771ce84de6811aab93ac2354809d1601b64877
1,267
Html2Pdf
MIT License
kotlin-styled-next/src/test/kotlin/test/AtRulesTest.kt
JetBrains
93,250,841
false
null
package test import kotlinx.css.* import react.Props import react.dom.div import react.fc import runTest import styled.css import styled.styledDiv import styled.styledSpan import kotlin.test.Test import kotlin.test.assertEquals /** * Check every public interface function in [CssBuilder] */ class AtRulesTest : TestBase() { @Test fun supports() = runTest { val query = "(color: $firstColor)" val styledComponent = fc<Props> { styledDiv { css { supports(query) { "div" { color = firstColor } } } div {} } } val element = clearAndInject(styledComponent) assertEquals(firstColor.toString(), element.childAt(0).color()) assertCssInjected("@supports $query", "color" to firstColor.toString()) } @Test fun fontFace() = runTest { val styledComponent = fc<Props> { styledDiv { css { fontFace { fontFamily = "Roboto" } } } } clearAndInject(styledComponent) assertCssInjected("@font-face", "font-family" to "Roboto") } @Test fun retina() = runTest { val styledComponent = fc<Props> { styledDiv { css { fontSize = 15.px retina { fontSize = 18.px } } } } clearAndInject(styledComponent) assertCssInjected( "@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi)", "font-size" to "18px" ) } @Test fun media() = runTest { val query = "only screen and (max-width: 600px)" val styledComponent = fc<Props> { styledSpan { css { media(query) { textTransform = TextTransform.capitalize } } } } clearAndInject(styledComponent) assertCssInjected( "@media $query", "text-transform" to "capitalize", ) } }
12
null
145
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
2,335
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/nqmgaming/furniture/presentation/main/profile/ProfileScreen.kt
nqmgaming
803,271,824
false
{"Kotlin": 323752}
package com.nqmgaming.furniture.presentation.main.profile import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.Logout import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import com.nqmgaming.furniture.R import com.nqmgaming.furniture.R.drawable import com.nqmgaming.furniture.core.components.AlertDialogComponent import com.nqmgaming.furniture.presentation.Screen import com.nqmgaming.furniture.presentation.main.profile.componets.ItemProfile import com.nqmgaming.furniture.core.theme.BlackText import com.nqmgaming.furniture.core.theme.PrimaryColor import com.nqmgaming.furniture.core.theme.gelasioFont import com.nqmgaming.furniture.core.theme.nunitoSansFont import com.nqmgaming.furniture.util.SharedPrefUtils @Composable fun ProfileScreen(navController: NavController = rememberNavController()) { val openAlertDialog = remember { mutableStateOf(false) } val context = LocalContext.current val email = SharedPrefUtils.getString(context, "email") val name = SharedPrefUtils.getString(context, "name") LazyColumn( modifier = Modifier.padding(start = 16.dp, end = 16.dp) ) { item { Row( modifier = Modifier .fillMaxWidth() .padding(vertical = 20.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Icon( painter = painterResource(id = drawable.ic_search), contentDescription = stringResource( id = R.string.search ), modifier = Modifier.weight(1f) ) Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .weight(10f) .padding(5.dp) ) { Text( text = stringResource(id = R.string.profile).uppercase(), style = TextStyle( fontSize = 18.sp, fontWeight = FontWeight.ExtraBold, lineHeight = 25.sp, fontFamily = gelasioFont, color = PrimaryColor ) ) } Icon( painter = painterResource(id = drawable.ic_logout), contentDescription = stringResource( id = R.string.cart ), modifier = Modifier .weight(1f) .padding(5.dp) .clickable { openAlertDialog.value = true } ) } } item { Row { Image( painter = painterResource(id = R.drawable.avatar_sample), contentDescription = "Profile", modifier = Modifier .size(80.dp) .clip(CircleShape) .border( BorderStroke(4.dp, Color.Yellow), CircleShape ), contentScale = ContentScale.FillWidth ) Spacer(modifier = Modifier.width(20.dp)) Column { Text( text = "$name", style = TextStyle( fontFamily = nunitoSansFont, color = BlackText, fontSize = 20.sp, lineHeight = 27.sp, fontWeight = FontWeight.ExtraBold ), modifier = Modifier .padding(vertical = 10.dp), textAlign = TextAlign.Start, maxLines = 1, overflow = TextOverflow.Ellipsis ) Text( text = "$email", style = TextStyle( fontFamily = nunitoSansFont, color = BlackText, fontSize = 14.sp, lineHeight = 20.sp, fontWeight = FontWeight.Bold ), textAlign = TextAlign.Start, modifier = Modifier.padding(bottom = 20.dp) ) } } } item { Spacer(modifier = Modifier.height(20.dp)) } item { ItemProfile( title = "My Orders", subtitle = "Check your orders", onClick = { navController.navigate(Screen.OrderScreen.route) } ) } item { ItemProfile( title = "Shipping Addresses", subtitle = "Manage your shipping addresses", onClick = { } ) } item { ItemProfile( title = "Payment Methods", subtitle = "Manage your payment methods", onClick = { } ) } item { ItemProfile( title = "My reviews", subtitle = "Check your reviews", onClick = { } ) } item { ItemProfile( title = "Settings", subtitle = "Notification, Password, FAQ, Contact", onClick = { } ) } } if (openAlertDialog.value) { AlertDialogComponent( onDismissRequest = { openAlertDialog.value = false }, onConfirmation = { openAlertDialog.value = false SharedPrefUtils.clear(context) navController.navigate(Screen.OnboardingScreen.route) { popUpTo(navController.graph.id) { inclusive = true } launchSingleTop = true restoreState = true } }, dialogTitle = R.string.log_out, dialogText = R.string.logout_message, icon = Icons.AutoMirrored.Filled.Logout ) } } @Preview(showSystemUi = true) @Composable fun ProfileScreenPreview() { ProfileScreen() }
0
Kotlin
0
1
1c14c70be1f64a188d98e674f7cedf5433a98f30
8,368
furniture-shopping-asm
MIT License
app/src/main/java/com/sametb/hoopsinsight/domain/repo/IDataStoreOperations.kt
samet-byte
751,375,299
false
{"Kotlin": 148842}
package com.sametb.hoopsinsight.domain.repo import kotlinx.coroutines.flow.Flow /* * Hoops Insight.com.sametb.hoopsinsight.repo * Created by <NAME> * on 2.02.2024 at 3:41 PM * Copyright (c) 2024 UNITED WORLD. All rights reserved. */ interface IDataStoreOperations { suspend fun saveOnBoardingState(completed: Boolean) fun readOnBoardingState(): Flow<Boolean> }
0
Kotlin
0
0
bdf00710204396bfd2025d9eb7006bd64e801554
373
Android-JetpackCompose-HoopsInsight
CNRI Python License
src/main/java/dev/blachut/svelte/lang/psi/SvelteCodeInjectionHostImpl.kt
tiatin
197,381,823
true
{"Kotlin": 58750, "Lex": 5037, "Java": 390}
package dev.blachut.svelte.lang.psi import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.LiteralTextEscaper import com.intellij.psi.PsiLanguageInjectionHost import com.intellij.psi.impl.source.tree.LeafElement import com.intellij.psi.impl.source.tree.injected.InjectionBackgroundSuppressor open class SvelteCodeInjectionHostImpl(node: ASTNode) : SveltePsiElementImpl(node), PsiLanguageInjectionHost, InjectionBackgroundSuppressor { override fun updateText(text: String): PsiLanguageInjectionHost { val valueNode = node.firstChildNode assert(valueNode is LeafElement) (valueNode as LeafElement).replaceWithText(text) return this } override fun createLiteralTextEscaper(): LiteralTextEscaper<out PsiLanguageInjectionHost> { return SvelteLiteralTextEscaper(this) } override fun isValidHost(): Boolean { return true } } class SvelteLiteralTextEscaper(host: SvelteCodeInjectionHostImpl) : LiteralTextEscaper<SvelteCodeInjectionHostImpl>(host) { override fun isOneLine(): Boolean = false override fun getOffsetInHost(offsetInDecoded: Int, rangeInsideHost: TextRange): Int { return rangeInsideHost.startOffset + offsetInDecoded } override fun decode(rangeInsideHost: TextRange, outChars: StringBuilder): Boolean { outChars.append(myHost.text, rangeInsideHost.startOffset, rangeInsideHost.endOffset) return true } }
0
Kotlin
0
1
49b45ddbad47b64162426855a1b53a256c8c6bf8
1,478
svelte-intellij
MIT License
platform/lang-impl/src/com/intellij/profile/codeInspection/ui/DescriptionEditorPane.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.profile.codeInspection.ui import com.intellij.codeEditor.printing.HTMLTextPainter import com.intellij.codeInsight.hint.HintUtil import com.intellij.lang.Language import com.intellij.lang.LanguageUtil import com.intellij.openapi.fileTypes.PlainTextLanguage import com.intellij.openapi.project.DefaultProjectFactory import com.intellij.psi.PsiFileFactory import com.intellij.ui.HintHint import com.intellij.ui.JBColor import com.intellij.util.ui.HTMLEditorKitBuilder import com.intellij.util.ui.StartupUiUtil import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jsoup.Jsoup import java.awt.Color import java.awt.Point import java.io.IOException import java.io.StringReader import javax.swing.JEditorPane import javax.swing.text.html.HTMLEditorKit open class DescriptionEditorPane : JEditorPane(UIUtil.HTML_MIME, EMPTY_HTML) { init { isEditable = false isOpaque = false editorKit = HTMLEditorKitBuilder().withGapsBetweenParagraphs().withoutContentCss().build() val css = (this.editorKit as HTMLEditorKit).styleSheet css.addRule("a {overflow-wrap: anywhere;}") css.addRule("pre {padding:10px;}") } override fun getBackground(): Color = JBColor.PanelBackground companion object { const val EMPTY_HTML: String = "<html><body></body></html>" } } /** * Parses the input HTML [text] and displays its content. * * @param text The HTML content as a [String] to be displayed in the [JEditorPane]. * @throws RuntimeException if an exception occurs while parsing or displaying the HTML content. */ fun JEditorPane.readHTML(text: String) { val document = Jsoup.parse(text) for (pre in document.select("pre")) { if ("editor-background" !in pre.classNames()) pre.addClass("editor-background") } try { read(StringReader(document.html()), null) } catch (e: IOException) { throw RuntimeException(e) } } /** * Parses the input HTML [text] and displays its content. * Adds highlighting for code fragments wrapped in `<pre><code>` elements. * Specify the `lang` parameter on `code` elements to override the default language. * If the language is not provided or unrecognized, it will default to plain text. * * @param text The HTML content as a [String] to be displayed in the [JEditorPane]. * @param language The optional ID of the programming language to be used in code fragments. * @throws RuntimeException if an exception occurs while parsing or displaying the HTML content. */ fun JEditorPane.readHTMLWithCodeHighlighting(text: String, language: String?) { var lang = Language.findLanguageByID(language) ?: PlainTextLanguage.INSTANCE val document = Jsoup.parse(text) // IDEA-318323 if (text.contains("<body>\n<p>")) { document.select("body > :first-child").first()?.tagName("div") } document.select("pre code").forEach { codeSnippet -> if (codeSnippet.hasAttr("lang")) lang = LanguageUtil.findRegisteredLanguage(codeSnippet.attr("lang")) ?: lang val defaultProject = DefaultProjectFactory.getInstance().defaultProject val psiFileFactory = PsiFileFactory.getInstance(defaultProject) val defaultFile = psiFileFactory.createFileFromText(PlainTextLanguage.INSTANCE, "") val content = codeSnippet.wholeText() .trimIndent() .trimEnd() .replaceIndent(" ") var snippet: String try { val file = psiFileFactory.createFileFromText(lang, "") ?: defaultFile snippet = HTMLTextPainter.convertCodeFragmentToHTMLFragmentWithInlineStyles(file, content) } catch (e: IllegalStateException) { snippet = HTMLTextPainter.convertCodeFragmentToHTMLFragmentWithInlineStyles(defaultFile, content) } codeSnippet.parent()?.html( snippet.removePrefix("<pre>").removeSuffix("</pre>").trimMargin() ) } document.select("pre").forEach { it.addClass("editor-background") } try { read(StringReader(document.html()), null) } catch (e: IOException) { throw RuntimeException(e) } } @ApiStatus.ScheduledForRemoval @Deprecated(message = "HTMl conversion is handled in JEditorPane.readHTML") fun JEditorPane.toHTML(text: @Nls String?, miniFontSize: Boolean): String { val hintHint = HintHint(this, Point(0, 0)) hintHint.setFont(if (miniFontSize) UIUtil.getLabelFont(UIUtil.FontSize.SMALL) else StartupUiUtil.labelFont) return HintUtil.prepareHintText(text!!, hintHint) }
251
null
5079
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
4,552
intellij-community
Apache License 2.0
plugins/kotlin/idea/tests/testData/findUsages/libraryUsages/findLibraryFunctionUsages/kotlinMethodUsages/kotlinMethodUsages.0.kt
ingokegel
72,937,917
true
null
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtNamedFunction // OPTIONS: usages // PSI_ELEMENT_AS_TITLE: "fun processRequest(): String" package client import server.*; class Client { public fun foo() { Server().<caret>processRequest() ServerEx().processRequest() } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
288
intellij-community
Apache License 2.0
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/elementlist/Book.kt
Tickaroo
46,920,047
false
null
/* * Copyright (C) 2015 <NAME> * Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.annotationprocessing.elementlist import com.tickaroo.tikxml.annotation.Attribute import com.tickaroo.tikxml.annotation.PropertyElement import com.tickaroo.tikxml.annotation.Xml import com.tickaroo.tikxml.annotationprocessing.DateConverter import java.util.Date /** * @author <NAME> */ @Xml class Book { @Attribute var id: Int = 0 @PropertyElement var author: String? = null @PropertyElement var title: String? = null @PropertyElement var genre: String? = null @PropertyElement(name = "publish_date", converter = DateConverter::class) var publishDate: Date? = null @PropertyElement var price: Double = 0.toDouble() @PropertyElement var description: String? = null override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Book) return false val book = other as Book? if (id != book!!.id) return false if (java.lang.Double.compare(book.price, price) != 0) return false if (if (author != null) author != book.author else book.author != null) return false if (if (title != null) title != book.title else book.title != null) return false if (if (genre != null) genre != book.genre else book.genre != null) return false if (if (publishDate != null) publishDate != book.publishDate else book.publishDate != null) { return false } return if (description != null) description == book.description else book.description == null } override fun hashCode(): Int { var result: Int val temp: Long result = id result = 31 * result + if (author != null) author!!.hashCode() else 0 result = 31 * result + if (title != null) title!!.hashCode() else 0 result = 31 * result + if (genre != null) genre!!.hashCode() else 0 result = 31 * result + if (publishDate != null) publishDate!!.hashCode() else 0 temp = java.lang.Double.doubleToLongBits(price) result = 31 * result + (temp xor temp.ushr(32)).toInt() result = 31 * result + if (description != null) description!!.hashCode() else 0 return result } }
47
null
46
420
cd5d868cf5988c66755f9ff6da043abc27a0fa6f
2,848
tikxml
Apache License 2.0
android/versioned-abis/expoview-abi46_0_0/src/main/java/abi46_0_0/expo/modules/sensors/services/GyroscopeService.kt
expo
65,750,241
false
null
// Copyright 2015-present 650 Industries. All rights reserved. package abi46_0_0.expo.modules.sensors.services import android.content.Context import android.hardware.Sensor import abi46_0_0.expo.modules.interfaces.sensors.services.GyroscopeServiceInterface import abi46_0_0.expo.modules.core.interfaces.InternalModule class GyroscopeService(context: Context?) : SubscribableSensorService(context), InternalModule, GyroscopeServiceInterface { override val sensorType: Int = Sensor.TYPE_GYROSCOPE override fun getExportedInterfaces(): List<Class<*>> { return listOf<Class<*>>(GyroscopeServiceInterface::class.java) } }
454
null
3947
19,768
af47d96ef6e73a5bced7ec787fea430905f072d6
630
expo
MIT License
spinnerlibrary/src/main/java/com/sugarya/footer/interfaces/IFooterMode.kt
Sugarya
139,695,344
false
null
package com.sugarya.footer.interfaces /** * Footer View 下拉筛选动画模式 */ interface IFooterMode { var mFooterMode: FooterMode? }
1
null
2
11
354c8106ced7bb32862bb94cb7be200b6a289d2e
131
SpinnerLayout
Apache License 2.0
app-ui-catalog/src/main/java/app/k9mail/ui/catalog/ui/common/drawer/DrawerContent.kt
thunderbird
1,326,671
false
{"Kotlin": 4766001, "Java": 2159946, "Shell": 2768, "AIDL": 1946}
package app.k9mail.ui.catalog.ui.common.drawer import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.withStyle import app.k9mail.core.ui.compose.designsystem.organism.drawer.ModalDrawerSheet import app.k9mail.core.ui.compose.designsystem.organism.drawer.NavigationDrawerDivider import app.k9mail.core.ui.compose.designsystem.organism.drawer.NavigationDrawerHeadline import app.k9mail.core.ui.compose.designsystem.organism.drawer.NavigationDrawerItem import app.k9mail.ui.catalog.ui.CatalogContract.Theme import app.k9mail.ui.catalog.ui.CatalogContract.ThemeVariant import app.k9mail.ui.catalog.ui.next @Suppress("LongParameterList", "LongMethod") @Composable fun DrawerContent( closeDrawer: () -> Unit, theme: Theme, themeVariant: ThemeVariant, onThemeChanged: () -> Unit, onThemeVariantChanged: () -> Unit, onNavigateToAtoms: () -> Unit, onNavigateToMolecules: () -> Unit, onNavigateToOrganisms: () -> Unit, modifier: Modifier = Modifier, ) { ModalDrawerSheet( modifier = modifier, ) { NavigationDrawerHeadline( title = "Design system", ) NavigationDrawerItem( label = "Atoms", selected = false, onClick = { closeDrawer() onNavigateToAtoms() }, ) NavigationDrawerItem( label = "Molecules", selected = false, onClick = { closeDrawer() onNavigateToMolecules() }, ) NavigationDrawerItem( label = "Organisms", selected = false, onClick = { closeDrawer() onNavigateToOrganisms() }, ) NavigationDrawerDivider() NavigationDrawerHeadline( title = "Theme", ) NavigationDrawerItem( label = buildAnnotatedString { append("Change to ") withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) { append(theme.next().displayName) } append(" theme") }, selected = false, onClick = { closeDrawer() onThemeChanged() }, ) NavigationDrawerItem( label = buildAnnotatedString { append("Change to ") withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) { append(themeVariant.next().displayName) } append(" theme variant") }, selected = false, onClick = { closeDrawer() onThemeVariantChanged() }, ) } }
846
Kotlin
2467
9,969
8b3932098cfa53372d8a8ae364bd8623822bd74c
2,987
thunderbird-android
Apache License 2.0
fabric/src/main/kotlin/org/valkyrienskies/mod/fabric/client/ValkyrienSkiesModFabricClient.kt
ValkyrienSkies
331,809,833
false
null
package org.valkyrienskies.mod.fabric.client import net.fabricmc.api.ClientModInitializer import org.valkyrienskies.mod.fabric.common.VSFabricNetworking /** * This class only runs on the client, used to initialize client only code. See [ClientModInitializer] for more details. */ class ValkyrienSkiesModFabricClient : ClientModInitializer { override fun onInitializeClient() { VSFabricNetworking.registerClientPacketHandlers() } }
1
Java
1
15
11a779e2cbbe353f3723aae5f599dc3aec64b74b
451
Valkyrien-Skies-2
Apache License 2.0
server/src/main/java/org/apollo/plugins/music/Song.kt
Meteor-377
697,711,716
false
{"Gradle Kotlin DSL": 6, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Java": 509, "Java Properties": 1, "Kotlin": 58, "XML": 8}
package org.apollo.plugins.music import org.apollo.game.model.Position open class Song(val id: Int, val regions: Array<Position>)
0
Java
0
0
09d81c9212f48bf15ec50e25a4f59df54417b1e2
131
server
BSD Zero Clause License
src/main/kotlin/icurves/network/NetworkEdge.kt
svenlinker
100,699,121
false
null
package icurves.network /** * * * @author Almas Baimagambetov ([email protected]) */ class NetworkEdge { }
0
Kotlin
0
0
daadeeac6ab9a66cf92021b2d0daa1a6a59d8e2b
112
GroupNet
Apache License 2.0
buildSrc/src/test/kotlin/com/example/forgery/ConflictForgeryFactory.kt
DataDog
219,536,756
false
null
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.example.forgery import com.example.model.Conflict import fr.xgouchet.elmyr.Forge import fr.xgouchet.elmyr.ForgeryFactory internal class ConflictForgeryFactory : ForgeryFactory<Conflict> { override fun getForgery(forge: Forge): Conflict { return Conflict( type = forge.aNullable { Conflict.Type( aNullable { anAlphabeticalString() } ) }, user = forge.aNullable { Conflict.User( name = aNullable { anAlphabeticalString() }, type = aNullable() ) } ) } }
33
Kotlin
39
86
bcf0d12fd978df4e28848b007d5fcce9cb97df1c
912
dd-sdk-android
Apache License 2.0
app/src/main/java/com/jime/stu/ui/photo/CameraViewModel.kt
huyuanhao
262,023,085
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 106, "Java": 16, "Kotlin": 111, "INI": 1}
package com.jime.stu.ui.photo import com.aleyn.mvvm.base.BaseViewModel import com.aleyn.mvvm.event.Message import com.blankj.utilcode.util.LogUtils import com.jime.stu.utils.InjectorUtil /** * @author PC * @date 2020/06/01 18:05 */ class CameraViewModel : BaseViewModel() { private val homeRepository by lazy { InjectorUtil.getHomeRepository() } fun uploadUrl(url:String) { launchOnlyresult( { homeRepository.uploadUrl(url) }, { defUI.msgEvent.postValue(Message(1, obj = it)) }) } fun save(url:String,etypeInt:Int,title:String,mode:String){ launchOnlyresult({homeRepository.save(url,etypeInt,title,mode)},{ LogUtils.e("事件上报成功:url="+ url +"etypeInt="+ etypeInt +"title="+ title +"mode="+ mode) },{ LogUtils.e("事件上报失败:url="+ url +"etypeInt="+ etypeInt +"title="+ title +"mode="+ mode) },{},false) } }
1
null
1
1
927e3fe0ff3a66f85341d130dc76146382511747
934
footballs
Apache License 2.0
clouddriver-scattergather/src/main/kotlin/com/netflix/spinnaker/clouddriver/scattergather/ResponseReducer.kt
madhusarma
218,766,347
false
{"Gradle": 42, "Slim": 1, "TOML": 1, "CODEOWNERS": 1, "Java Properties": 1, "Markdown": 14, "Shell": 6, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "YAML": 17, "Text": 3, "Java": 1296, "JSON": 17, "Groovy": 1812, "XML": 8, "Kotlin": 99, "INI": 1, "Protocol Buffer": 6, "desktop": 1}
/* * Copyright 2018 Netflix, 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.netflix.spinnaker.clouddriver.scattergather import okhttp3.Response /** * Reduces a list of [Response]s to a single response representation. * * TODO(rz): Refactor to not expose OkHttp3. When we add support for local-scattering, we'll want all existing reducers * to automatically support the new execution path. Would also be handy because we could later add support * for other backends like redis, pubsub, kafka, etc. */ interface ResponseReducer { fun reduce(responses: List<Response>): ReducedResponse }
1
null
1
1
d1a1dfa3d1f539243ce5fd5d584d011f735b6728
1,148
clouddriver
Apache License 2.0
base/src/test/kotlin-jvm/rmg/apps/cards/base/model/MultipleChoiceQuestionSpec.kt
rmgrimm
91,530,687
false
null
package rmg.apps.cards.base.model import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.then import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.subject.SubjectSpek import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue object MultipleChoiceQuestionSpec: SubjectSpek<MultipleChoiceQuestion>({ describe("a multiple choice question") { val locale = Locale(lang = "eng") val answerOptions = (1..5).map { WrittenWord(locale, it.toString()) } val correctAnswerIndex = 0 val incorrectAnswerIndex = 1 val questionSignified = Signified(Signified.Type.NOUN, listOf(answerOptions[correctAnswerIndex])) val handler = mock<Question.() -> Unit>() beforeEachTest { reset(handler) } subject { MultipleChoiceQuestion( questionSignified = questionSignified, answerSignifiers = answerOptions, handler = handler) } it("should not show answered initially") { assertFalse { subject.isAnswered } } it("should not have any correct/incorrect value") { assertNull(subject.isCorrect) } on("selecting a correct answer") { subject.selectedIndex = correctAnswerIndex it("should call the handler") { then(handler).should().invoke(eq(subject)) } it("should show answered") { assertTrue { subject.isAnswered } } it("should indicate correct") { assertTrue { subject.isCorrect!! } } } on("selecting an incorrect answer") { subject.selectedIndex = incorrectAnswerIndex it("should call the handler") { then(handler).should().invoke(eq(subject)) } it("should show answered") { assertTrue { subject.isAnswered } } it("should indicate that the answer is incorrect") { assertFalse { subject.isCorrect!! } } } } })
0
Kotlin
1
1
7189dabb97892aa9bb314c83924d8f2484df0e00
2,307
cards
MIT License
StateBasics/app/src/main/java/com/lbarqueira/statebasics/MainActivity.kt
lbarqueira
407,323,122
false
null
package com.lbarqueira.statebasics import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.core.view.WindowCompat import androidx.lifecycle.ViewModel import com.lbarqueira.statebasics.ui.theme.StateBasicsTheme import com.google.accompanist.insets.ProvideWindowInsets import com.google.accompanist.insets.statusBarsPadding /** * A ViewModel extracts _state_ from the UI and defines _events_ that can update it. * Note: If this ViewModel was also used by the View system, it would be better to continue using LiveData. */ class HelloViewModel : ViewModel() { // We will explore using mutableStateOf in viewModel and see how it simplifies state code // compared to LiveData<String> when targeting Compose. // The MutableState class is a single value holder whose reads and writes are observed by Compose. // By specifying private set, we're restricting writes to this state object // to a private setter only visible inside the ViewModel. // state: name var name: MutableState<String> = mutableStateOf("") private set // onNameChanged is an event we're defining that the UI can invoke // (events flow up from UI) // event: onNameChanged fun onNameChanged(newName: String) { name.value = newName } } class MainActivity : ComponentActivity() { private val helloViewModel by viewModels<HelloViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) setContent { StateBasicsTheme { ProvideWindowInsets { // A surface container using the 'background' color from the theme Surface( color = MaterialTheme.colors.background, modifier = Modifier.fillMaxSize() ) { HelloScreen(modifier = Modifier.statusBarsPadding(), helloViewModel) } } } } } } // This composable will be a bridge between the state stored in our ViewModel and the // HelloInput composable. @Composable private fun HelloScreen(modifier: Modifier = Modifier, helloViewModel: HelloViewModel) { // helloViewModel follows the Lifecycle as the Activity or Fragment that calls this // composable function. // The event passed to HelloInput use the Kotlin lambda syntax // HelloInput(name = name, onNameChange = { helloViewModel.onNameChanged(it) }) // Alternatively, you can also generate a lambda that calls a single method using the method reference syntax. HelloInput( modifier = modifier, name = helloViewModel.name.value, onNameChange = helloViewModel::onNameChanged ) } @Composable private fun HelloInput( modifier: Modifier = Modifier, name: String, onNameChange: (String) -> Unit ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { TextGroup( "Top Text", modifier = modifier.fillMaxWidth(), style = MaterialTheme.typography.h3, textAlign = TextAlign.Center, ) Box( modifier = modifier .background(Color.Magenta) .fillMaxWidth() .weight(1f) ) Text(name) TextField( value = name, onValueChange = onNameChange, label = { Text("Label") } ) Box( modifier = modifier .background(Color.Magenta) .fillMaxWidth() .weight(1f) ) TextGroup( "Bottom Text", modifier = modifier.fillMaxWidth(), style = MaterialTheme.typography.h3, textAlign = TextAlign.Center, ) } } @Composable private fun TextGroup( text: String, style: TextStyle, textAlign: TextAlign?, modifier: Modifier = Modifier, ) { Box( modifier = modifier .background(Color.Yellow) .fillMaxWidth() ) { Text( text = text, modifier = modifier, style = style, textAlign = textAlign ) } }
0
Kotlin
0
1
8869ead876186eba3362e5defdfe69ed189771ba
4,806
Jetpack-Compose-Learnings
MIT License
app/src/main/java/app/odapplications/bitstashwallet/core/managers/SystemInfoManager.kt
bitstashco
220,133,996
false
null
package app.odapplications.bitstashwallet.core.managers import android.app.Activity import android.app.KeyguardManager import androidx.biometric.BiometricManager import androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS import app.odapplications.bitstashwallet.BuildConfig import app.odapplications.bitstashwallet.core.App import app.odapplications.bitstashwallet.core.ISystemInfoManager class SystemInfoManager : ISystemInfoManager { override val appVersion: String = BuildConfig.VERSION_NAME private val biometricManager = BiometricManager.from(App.instance) override val isSystemLockOff: Boolean get() { val keyguardManager = App.instance.getSystemService(Activity.KEYGUARD_SERVICE) as KeyguardManager return !keyguardManager.isDeviceSecure } override val biometricAuthSupported: Boolean get() = biometricManager.canAuthenticate() == BIOMETRIC_SUCCESS }
3
null
3
11
64c242dbbcb6b4df475a608b1edb43f87e5091fd
931
BitStash-Android-Wallet
MIT License
app/src/main/java/org/p2p/wallet/striga/user/StrigaStorageContract.kt
p2p-org
306,035,988
false
null
package org.p2p.wallet.striga.user import org.p2p.core.utils.MillisSinceEpoch import org.p2p.wallet.kyc.model.StrigaKycStatusBanner import org.p2p.wallet.striga.user.model.StrigaUserStatusDetails import org.p2p.wallet.striga.wallet.models.StrigaCryptoAccountDetails import org.p2p.wallet.striga.wallet.models.StrigaFiatAccountDetails import org.p2p.wallet.striga.wallet.models.StrigaUserWallet interface StrigaStorageContract { var userStatus: StrigaUserStatusDetails? var userWallet: StrigaUserWallet? var fiatAccount: StrigaFiatAccountDetails? var cryptoAccount: StrigaCryptoAccountDetails? var smsExceededVerificationAttemptsMillis: MillisSinceEpoch var smsExceededResendAttemptsMillis: MillisSinceEpoch fun hideBanner(banner: StrigaKycStatusBanner) fun isBannerHidden(banner: StrigaKycStatusBanner): Boolean fun clear() }
7
Kotlin
16
27
6997865894f3ec1ec3df54225b7b2936e7acd399
866
key-app-android
MIT License
oneone/src/main/java/com/gapps/oneone/screens/menu/core/MenuPresenter.kt
TalbotGooday
204,948,092
false
null
package com.gapps.oneone.screens.menu.core import android.content.Context import com.gapps.oneone.OneOne internal class MenuPresenter : MenuContract.Presenter { override lateinit var view: MenuContract.View private lateinit var context: Context override fun create(context: Context) { this.context = context if (context is MenuContract.View) { this.view = context } } override fun saveNewLoggerUrl(newUrl: String) { OneOne.setLoggerBaseUrl(newUrl, true) } override fun destroy() { } }
0
Kotlin
0
0
9aa549666526e54d4460f9b6086f1b65732fe8fd
510
OneOne
Apache License 2.0
gui/src/main/kotlin/com/briarcraft/gui/UserInterfaceListener.kt
toddharrison
581,553,858
false
null
package com.briarcraft.gui import com.briarcraft.gui.api.UserInterfaceHolder import com.briarcraft.gui.api.UserInterfaceView import com.briarcraft.gui.api.ViewUpdateEvent import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.inventory.* import org.bukkit.event.player.PlayerAttemptPickupItemEvent @Suppress("unused") class UserInterfaceListener: Listener { @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) fun openUserInterface(event: InventoryOpenEvent) { val view = event.view if (view is UserInterfaceView) { view.getHandler().onOpen(view) view.getHandler().onUpdate(view, null) } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false) fun handleUserInterfaceClickEvents(event: InventoryClickEvent) { val view = event.view if (view is UserInterfaceView) { event.isCancelled = true // Ignore troublesome actions if (event.click == ClickType.DROP || event.click == ClickType.CONTROL_DROP || event.click == ClickType.NUMBER_KEY || event.click == ClickType.SWAP_OFFHAND ) return val updateViewEvent: ViewUpdateEvent? = when { event.slotType == InventoryType.SlotType.OUTSIDE -> view.getHandler().onClickOutside(view, event) event.slotType == InventoryType.SlotType.QUICKBAR -> view.navPanel.executeAction(event) ?: view.getHandler().onClickQuickBar(view, event) event.clickedInventory == event.view.topInventory -> view.topPanel.executeAction(event) ?: view.getHandler().onClickTop(view, event) event.clickedInventory == event.view.bottomInventory -> view.midPanel.executeAction(event) ?: view.getHandler().onClickBottom(view, event) else -> { Plugin.logger.warning("Unhandled UI click: ${event.whoClicked.name} ${event.click} ${event.action} ${event.slotType} ${event.slot} ${event.rawSlot}") return } } if (updateViewEvent != null) { view.getHandler().onUpdate(view, updateViewEvent) } } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false) fun preventDragAndDropInUserInterface(event: InventoryDragEvent) { if (event.inventory.holder is UserInterfaceHolder) { event.isCancelled = true } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false) fun preventPickingUpItemsWhenInUserInterface(event: PlayerAttemptPickupItemEvent) { if (event.player.openInventory.topInventory.holder is UserInterfaceHolder) { event.isCancelled = true } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) fun closeUserInterface(event: InventoryCloseEvent) { val view = event.view if (view is UserInterfaceView) { view.getHandler().onClose(view) // Restore player inventory by sending refresh packet to player val player = event.player as Player player.server.scheduler.runTask(Plugin) { -> player.updateInventory() } } } }
1
Kotlin
1
4
d75ea526a8920507601845ddcefe033883be962e
3,494
BriarCode
MIT License
src/main/kotlin/eu/ha3/dataswimming/tree/TreeRequiresAnElementException.kt
Hurricaaane
103,999,908
false
null
package eu.ha3.dataswimming.tree class TreeRequiresAnElementException : RuntimeException()
0
Kotlin
0
0
c6a92ef32d46a2190bfab5c6e1e7eeadecde4f4d
91
dataswimming-kotlin
MIT License
app/src/main/java/com/postliu/wanandroid/ui/collect/CollectScreen.kt
PostLiu
556,601,336
false
{"Kotlin": 156946}
package com.postliu.wanandroid.ui.collect import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.lazy.LazyListState import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.ListItem import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Favorite import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import androidx.paging.compose.items import com.jeremyliao.liveeventbus.LiveEventBus import com.postliu.wanandroid.WanSharedViewModel import com.postliu.wanandroid.common.BaseConstants import com.postliu.wanandroid.utils.GsonUtils import com.postliu.wanandroid.common.Routes import com.postliu.wanandroid.common.collectAsStateWithLifecycle import com.postliu.wanandroid.common.sharedViewModel import com.postliu.wanandroid.model.entity.CollectArticleEntity import com.postliu.wanandroid.model.entity.WebData import com.postliu.wanandroid.ui.theme.WanAndroidTheme import com.postliu.wanandroid.widgets.RefreshPagingList import com.postliu.wanandroid.widgets.TopDefaultAppBar @OptIn(ExperimentalLifecycleComposeApi::class) fun NavGraphBuilder.userCollect(navController: NavController) { composable(Routes.Collect) { navBackStackEntry -> val sharedViewModel: WanSharedViewModel = navBackStackEntry.sharedViewModel(navController) val viewModel: UserCollectViewModel = hiltViewModel() val viewState = viewModel.viewState val isRefresh = viewState.isRefresh val reLoginState by LiveEventBus.get<Boolean>(BaseConstants.RE_LOGIN) .collectAsStateWithLifecycle(initialValue = false) val article = viewState.article.collectAsLazyPagingItems() val lazyListState = if (article.itemCount > 0) viewModel.lazyListState else LazyListState() DisposableEffect(key1 = Unit, effect = { viewModel.dispatch(CollectAction.FetchData) onDispose { } }) UserCollectPage(lazyListState = lazyListState, article = article, isRefresh = isRefresh, onRefresh = { viewModel.dispatch(CollectAction.Refresh) }, reLoginState = reLoginState, popBackStack = { navController.popBackStack() }, toLogin = { navController.navigate(Routes.Login) }, unCollect = { id, originId -> viewModel.dispatch(CollectAction.UnCollect(id, originId)) }, toDetails = { val webData = WebData(title = it.title, url = it.link) sharedViewModel.webData = webData navController.navigate(Routes.ArticleDetails) }) } } @Composable fun UserCollectPage( lazyListState: LazyListState, article: LazyPagingItems<CollectArticleEntity>, isRefresh: Boolean, onRefresh: () -> Unit = {}, reLoginState: Boolean, popBackStack: () -> Unit = {}, toLogin: () -> Unit = {}, unCollect: (Int, Int) -> Unit = { _, _ -> }, toDetails: (CollectArticleEntity) -> Unit = {} ) { Scaffold(modifier = Modifier.fillMaxSize(), topBar = { TopDefaultAppBar(title = { Text(text = "我的收藏") }, navigationIcon = { IconButton(onClick = { popBackStack() }) { Icon(imageVector = Icons.Default.ArrowBack, contentDescription = null) } }) }, bottomBar = { AnimatedVisibility(visible = reLoginState) { Box(modifier = Modifier.fillMaxWidth()) { TextButton(onClick = toLogin) { Text(text = "未登录,点击去登录") } } } }) { paddingValues -> RefreshPagingList( lazyPagingItems = article, isRefreshing = isRefresh, onRefresh = onRefresh, paddingValues = paddingValues, listState = lazyListState ) { items(article) { entity -> entity?.let { CollectArticleItem( collectArticle = it, unCollect = { id, originId -> unCollect.invoke(id, originId) }, toDetails = toDetails ) } } } } } @OptIn(ExperimentalMaterialApi::class) @Composable private fun CollectArticleItem( collectArticle: CollectArticleEntity, unCollect: (Int, Int) -> Unit = { _, _ -> }, toDetails: (CollectArticleEntity) -> Unit = {} ) { ListItem(modifier = Modifier .fillMaxWidth() .clickable { toDetails(collectArticle) } .background(MaterialTheme.colors.background), singleLineSecondaryText = true, secondaryText = { Text(text = collectArticle.author) }, trailing = { IconButton(onClick = { unCollect.invoke(collectArticle.id, collectArticle.originId) }) { Icon( imageVector = Icons.Default.Favorite, contentDescription = null, tint = Color.Red ) } }, text = { Text( text = collectArticle.title, style = MaterialTheme.typography.body1, fontWeight = FontWeight.Bold ) }) } @Preview @Composable fun CollectArticlePreview() { WanAndroidTheme { val json = "{\n" + " \"author\": \"zsml2016\",\n" + " \"chapterId\": 358,\n" + " \"chapterName\": \"项目基础功能\",\n" + " \"courseId\": 13,\n" + " \"desc\": \"现在的绝大数APP特别是类似淘宝京东等这些大型APP都有文字轮播界面,实现循环轮播多个广告词等功能,而TextBannerView已经实现了这些功能,只需几行代码集成,便可实现水平或垂直轮播文字。\",\n" + " \"envelopePic\": \"http://wanandroid.com/resources/image/pc/default_project_img.jpg\",\n" + " \"id\": 132179,\n" + " \"link\": \"http://www.wanandroid.com/blog/show/2382\",\n" + " \"niceDate\": \"2020-05-11 10:11\",\n" + " \"origin\": \"\",\n" + " \"originId\": 3453,\n" + " \"publishTime\": 1589163090000,\n" + " \"title\": \"Android文字轮播控件 TextBannerView\",\n" + " \"userId\": 41641,\n" + " \"visible\": 0,\n" + " \"zan\": 0\n" + " }" val articleEntity = with(GsonUtils) { fromJson(json, CollectArticleEntity::class.java) } CollectArticleItem(collectArticle = articleEntity) } }
0
Kotlin
0
2
26b30b3499e19d066b3ab74054a735c64d1f4792
7,706
WanAndroid
MIT License
src/main/kotlin/org/vitrivr/cottontail/client/iterators/Tuple.kt
vitrivr
170,489,332
false
null
package org.vitrivr.cottontail.client.iterators import org.vitrivr.cottontail.client.language.basics.Type import org.vitrivr.cottontail.grpc.CottontailGrpc import java.util.* /** * A [Tuple] as returned by the [TupleIterator]. * * @author <NAME> * @version 1.2.0 */ abstract class Tuple(val raw: CottontailGrpc.QueryResponseMessage.Tuple) { /** Internal list of values. */ private val values: Array<Any?> = Array(raw.dataCount) { it -> val data = raw.dataList[it] when (data.dataCase) { CottontailGrpc.Literal.DataCase.BOOLEANDATA -> data.booleanData CottontailGrpc.Literal.DataCase.INTDATA -> data.intData CottontailGrpc.Literal.DataCase.LONGDATA -> data.longData CottontailGrpc.Literal.DataCase.FLOATDATA -> data.floatData CottontailGrpc.Literal.DataCase.DOUBLEDATA -> data.doubleData CottontailGrpc.Literal.DataCase.DATEDATA -> Date(data.dateData.utcTimestamp) CottontailGrpc.Literal.DataCase.STRINGDATA -> data.stringData CottontailGrpc.Literal.DataCase.COMPLEX32DATA -> data.complex32Data.real to data.complex32Data.imaginary CottontailGrpc.Literal.DataCase.COMPLEX64DATA -> data.complex64Data.real to data.complex64Data.imaginary CottontailGrpc.Literal.DataCase.VECTORDATA -> { val vector = data.vectorData when (vector.vectorDataCase) { CottontailGrpc.Vector.VectorDataCase.FLOATVECTOR -> FloatArray(vector.floatVector.vectorCount) { vector.floatVector.getVector(it) } CottontailGrpc.Vector.VectorDataCase.DOUBLEVECTOR -> DoubleArray(vector.doubleVector.vectorCount) { vector.doubleVector.getVector(it) } CottontailGrpc.Vector.VectorDataCase.INTVECTOR -> IntArray(vector.intVector.vectorCount) { vector.intVector.getVector(it) } CottontailGrpc.Vector.VectorDataCase.LONGVECTOR -> LongArray(vector.longVector .vectorCount) { vector.longVector.getVector(it) } CottontailGrpc.Vector.VectorDataCase.BOOLVECTOR -> BooleanArray(vector.boolVector.vectorCount) { vector.boolVector.getVector(it) } CottontailGrpc.Vector.VectorDataCase.COMPLEX32VECTOR -> Array(vector.complex32Vector.vectorCount) { vector.complex32Vector.getVector(it).real to vector.complex32Vector.getVector(it).imaginary} CottontailGrpc.Vector.VectorDataCase.COMPLEX64VECTOR -> Array(vector.complex64Vector.vectorCount) { vector.complex64Vector.getVector(it).real to vector.complex64Vector.getVector(it).imaginary} else -> UnsupportedOperationException("Vector data of type ${vector.vectorDataCase} is not supported by TupleIterator.") } } CottontailGrpc.Literal.DataCase.DATA_NOT_SET -> null else -> UnsupportedOperationException("Data of type ${data.dataCase} is not supported by TupleIterator.") } } abstract fun nameForIndex(index: Int): String abstract fun indexForName(name: String): Int abstract fun type(name: String): Type abstract fun type(index: Int): Type fun size() = this.values.size operator fun get(name: String) = this.values[indexForName(name)] operator fun get(index: Int): Any? = this.values[index] fun asBoolean(index: Int): Boolean? { val value = this.values[index] return if (value is Boolean) { value } else { null } } abstract fun asBoolean(name: String): Boolean? fun asByte(index: Int): Byte? { val value = this.values[index] return if (value is Byte) { value } else { null } } abstract fun asByte(name: String): Byte? fun asShort(index: Int): Short? { val value = this.values[index] return if (value is Short) { value } else { null } } abstract fun asShort(name: String): Short? fun asInt(index: Int): Int? { val value = this.values[index] return if (value is Int) { value } else { null } } abstract fun asInt(name: String): Int? fun asLong(index: Int): Long? { val value = this.values[index] return if (value is Long) { value } else { null } } abstract fun asLong(name: String): Long? fun asFloat(index: Int): Float? { val value = this.values[index] return if (value is Float) { value } else { null } } abstract fun asFloat(name: String): Float? fun asDouble(index: Int): Double? { val value = this.values[index] return if (value is Double) { value } else { null } } abstract fun asDouble(name: String): Double? fun asBooleanVector(index: Int): BooleanArray? { val value = this.values[index] return if (value is BooleanArray) { value } else { null } } abstract fun asBooleanVector(name: String): BooleanArray? fun asIntVector(index: Int): IntArray? { val value = this.values[index] return if (value is IntArray) { value } else { null } } abstract fun asIntVector(name: String): IntArray? fun asLongVector(index: Int): LongArray? { val value = this.values[index] return if (value is LongArray) { value } else { null } } abstract fun asLongVector(name: String): LongArray? fun asFloatVector(index: Int): FloatArray? { val value = this.values[index] return if (value is FloatArray) { value } else { null } } abstract fun asFloatVector(name: String): FloatArray? fun asDoubleVector(index: Int): DoubleArray? { val value = this.values[index] return if (value is DoubleArray) { value } else { null } } abstract fun asDoubleVector(name: String): DoubleArray? fun asString(index: Int): String? { val value = this.values[index] return if (value is String) { value } else { null } } abstract fun asString(name: String): String? fun asDate(index: Int): Date? { val value = this.values[index] return if (value is Date) { value } else { null } } abstract fun asDate(name: String): Date? override fun toString(): String = this.values.joinToString(", ") { it?.toString() ?: "<null>" } }
2
Kotlin
2
4
80e3855e082e3df1db1618651b76972d7a725c06
6,220
cottontaildb-proto
MIT License
libraries/smokes/data/src/main/java/com/feragusper/smokeanalytics/libraries/smokes/data/SmokeRepositoryImpl.kt
feragusper
679,444,925
false
{"Kotlin": 257666, "Ruby": 645}
package com.feragusper.smokeanalytics.libraries.smokes.data import com.feragusper.smokeanalytics.libraries.architecture.domain.extensions.firstInstantThisMonth import com.feragusper.smokeanalytics.libraries.architecture.domain.extensions.lastInstantToday import com.feragusper.smokeanalytics.libraries.architecture.domain.extensions.timeAfter import com.feragusper.smokeanalytics.libraries.architecture.domain.extensions.toDate import com.feragusper.smokeanalytics.libraries.architecture.domain.extensions.toLocalDateTime import com.feragusper.smokeanalytics.libraries.smokes.data.SmokeRepositoryImpl.FirestoreCollection.Companion.SMOKES import com.feragusper.smokeanalytics.libraries.smokes.data.SmokeRepositoryImpl.FirestoreCollection.Companion.USERS import com.feragusper.smokeanalytics.libraries.smokes.domain.Smoke import com.feragusper.smokeanalytics.libraries.smokes.domain.SmokeRepository import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.Query.Direction import kotlinx.coroutines.tasks.await import java.time.LocalDateTime import javax.inject.Inject import javax.inject.Singleton /** * Implementation of [SmokeRepository] that interacts with Firebase Firestore to perform CRUD operations * on smoke data for the authenticated user. * * @property firebaseFirestore The instance of [FirebaseFirestore] for database operations. * @property firebaseAuth The instance of [FirebaseAuth] for authentication details. */ @Singleton class SmokeRepositoryImpl @Inject constructor( private val firebaseFirestore: FirebaseFirestore, private val firebaseAuth: FirebaseAuth, ) : SmokeRepository { /** * Constants for Firestore collection paths. */ interface FirestoreCollection { companion object { const val USERS = "users" const val SMOKES = "smokes" } } override suspend fun addSmoke(date: LocalDateTime) { smokesQuery().add(SmokeEntity(date.toDate())).await() } override suspend fun editSmoke(id: String, date: LocalDateTime) { smokesQuery() .document(id) .set(SmokeEntity(date.toDate())) .await() } override suspend fun deleteSmoke(id: String) { smokesQuery() .document(id) .delete() .await() } override suspend fun fetchSmokes(date: LocalDateTime?): List<Smoke> { val smokes = smokesQuery() .whereGreaterThanOrEqualTo( SmokeEntity::date.name, (date?.toLocalDate()?.atStartOfDay() ?: firstInstantThisMonth()).toDate() ) .whereLessThan( SmokeEntity::date.name, (date?.plusDays(1)?.toLocalDate()?.atStartOfDay() ?: lastInstantToday()).toDate() ) .orderBy(Smoke::date.name, Direction.DESCENDING) .get() .await() return smokes.documents.mapIndexedNotNull { index, document -> Smoke( id = document.id, date = document.getDate(), timeElapsedSincePreviousSmoke = document.getDate() .timeAfter(smokes.documents.getOrNull(index + 1)?.getDate()), ) } } /** * Helper method to retrieve the Firestore collection reference for the current user's smokes. * * @throws IllegalStateException if the user is not logged in. * @return The Firestore collection reference. */ private fun smokesQuery() = firebaseAuth.currentUser?.uid?.let { firebaseFirestore.collection("$USERS/$it/$SMOKES") } ?: throw IllegalStateException("User not logged in") /** * Extension function to convert a Firestore [DocumentSnapshot] to a [LocalDateTime]. * * @throws IllegalStateException if the date is not found in the document. * @return The [LocalDateTime] representation of the date. */ private fun DocumentSnapshot.getDate() = getDate(Smoke::date.name)?.toLocalDateTime() ?: throw IllegalStateException("Date not found") }
2
Kotlin
0
0
77aaaa6c7fde9fdb2dff9a2cdf3548e30813e004
4,205
SmokeAnalytics
Apache License 2.0
src/main/kotlin/org/myteer/novel/utils/ReflectionUtils.kt
myteer
435,773,999
false
{"Kotlin": 631442, "CSS": 50750}
/* * Copyright (c) 2021 MTSoftware * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UNCHECKED_CAST") package org.myteer.novel.utils import java.util.stream.Stream object ReflectionUtils { fun <T> constructObject(clazz: Class<T>, args: Array<out Any>): T { val constructorParamTypes = Stream.of(*args).map { it.javaClass }.toArray() as Array<out Class<*>> val constructor = clazz.getDeclaredConstructor(*constructorParamTypes) constructor.isAccessible = true return constructor.newInstance() } fun <T> constructObject(clazz: Class<T>): T { val constructor = clazz.getDeclaredConstructor() constructor.isAccessible = true return constructor.newInstance() } fun <T> tryConstructObject(clazz: Class<T>): T? { return try { constructObject(clazz) } catch (ignored: Throwable) { null } } }
0
Kotlin
0
0
6bea86cbc2b2408303175f0558262092a9562bb2
1,462
novel
Apache License 2.0
tests/src/androidTest/java/com/dbflow5/models/OneToManyModelTest.kt
agrosner
24,161,015
false
null
package com.dbflow5.models import com.dbflow5.BaseUnitTest import com.dbflow5.TestDatabase import com.dbflow5.config.database import com.dbflow5.query.select import com.dbflow5.structure.delete import com.dbflow5.structure.exists import com.dbflow5.structure.save import org.junit.Assert.* import org.junit.Test class OneToManyModelTest : BaseUnitTest() { @Test fun testOneToManyModel() { database(TestDatabase::class) { db -> var testModel2 = TwoColumnModel("Greater", 4) testModel2.save(db) testModel2 = TwoColumnModel("Lesser", 1) testModel2.save(db) // assert we save var oneToManyModel = OneToManyModel("HasOrders") oneToManyModel.save(db) assertTrue(oneToManyModel.exists(db)) // assert loading works as expected. oneToManyModel = (select from OneToManyModel::class).requireSingle(db) assertNotNull(oneToManyModel.getRelatedOrders(db)) assertTrue(!oneToManyModel.getRelatedOrders(db).isEmpty()) // assert the deletion cleared the variable oneToManyModel.delete(db) assertFalse(oneToManyModel.exists(db)) assertNull(oneToManyModel.orders) // assert singular relationship was deleted. val list = (select from TwoColumnModel::class).queryList(db) assertTrue(list.size == 1) } } }
38
null
613
4,865
e1b6211dac6ddc0aa0c1c9a76a116478ccf92b86
1,446
DBFlow
MIT License
app/src/main/java/eu/kanade/presentation/browse/components/SourceFeedDialogs.kt
scb261
381,944,147
false
null
package eu.kanade.presentation.browse.components import androidx.compose.material3.AlertDialog import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import eu.kanade.tachiyomi.R @Composable fun SourceFeedAddDialog( onDismissRequest: () -> Unit, name: String, addFeed: () -> Unit, ) { AlertDialog( onDismissRequest = onDismissRequest, confirmButton = { TextButton(onClick = addFeed) { Text(text = stringResource(R.string.action_add)) } }, dismissButton = { TextButton(onClick = onDismissRequest) { Text(text = stringResource(R.string.action_cancel)) } }, title = { Text(text = stringResource(R.string.feed)) }, text = { Text(text = stringResource(R.string.feed_add, name)) }, ) } @Composable fun SourceFeedDeleteDialog( onDismissRequest: () -> Unit, deleteFeed: () -> Unit, ) { AlertDialog( onDismissRequest = onDismissRequest, confirmButton = { TextButton(onClick = deleteFeed) { Text(text = stringResource(R.string.action_delete)) } }, dismissButton = { TextButton(onClick = onDismissRequest) { Text(text = stringResource(R.string.action_cancel)) } }, title = { Text(text = stringResource(R.string.feed)) }, text = { Text(text = stringResource(R.string.feed_delete)) }, ) }
1
null
0
7
5a3a2084cbfff68c4187ea55ad6b8fd7be2796b7
1,685
TachiyomiSY
Apache License 2.0
korge/src/commonMain/kotlin/com/soywiz/korge/debug/ObservableProperty.kt
korlibs
80,095,683
false
null
package com.soywiz.korge.debug import com.soywiz.korio.async.* import com.soywiz.korui.* class ObservableProperty<T>( val name: String, val internalSet: (T) -> Unit, val internalGet: () -> T, ) { val onChange = Signal<T>() fun forceUpdate(value: T) { internalSet(value) onChange(value) } fun forceRefresh() { //println("forceRefresh: $value") //forceUpdate(value) onChange(value) } var value: T get() = internalGet() set(value) { if (this.value != value) { forceUpdate(value) } } override fun toString(): String = "ObservableProperty($name, $value)" } interface ObservablePropertyHolder<T> { val prop: ObservableProperty<T> } fun UiComponent.findObservableProperties(out: ArrayList<ObservableProperty<*>> = arrayListOf()): List<ObservableProperty<*>> { if (this is ObservablePropertyHolder<*>) { out.add(prop) } if (this is UiContainer) { forEachChild { it.findObservableProperties(out) } } return out }
102
Kotlin
64
1,192
7fa8c9981d09c2ac3727799f3925363f1af82f45
1,116
korge
Apache License 2.0
Kotlin/sumCalc.kt
sancta-simplicitas
226,485,352
false
{"Scala": 822, "Rust": 516, "Kotlin": 204}
fun main() { while (true) { readLine()!!.splitToSequence(" ").mapNotNull { it.toDoubleOrNull() }.sum().let { if (it % 1 == 0.0) it.toInt() else it }.let(::println) } }
0
Scala
0
2
c6032427bef39fe1f636e2dda6266c1bdf1fafca
204
MasterPiece
MIT License
library/src/main/java/com/larryhsiao/aura/view/recyclerview/slider/DotDimensions.kt
LarryHsiao
127,721,131
false
null
package com.larryhsiao.aura.view.recyclerview.slider /** * Object for maintain dot dimensions. */ internal class DotDimensions( count: Int, private val dotSize: Int, private val dotSpacing: Int, private val dotBound: Int, private val dotSizes: Map<Byte, Int>, private val targetScrollListener: TargetScrollListener? = null ) { internal var dots: ByteArray = ByteArray(count) internal var selectedIndex = 0 private var scrollAmount = 0 init { if (count > 0) { dots[0] = 6 } if (count <= SIZE_THRESHOLD) { (1 until count).forEach { i -> dots[i] = 5 } } else { (1..3).forEach { i -> dots[i] = 5 } dots[4] = 4 if (count > SIZE_THRESHOLD) { dots[5] = 2 } (SIZE_THRESHOLD + 1 until count).forEach { i -> dots[i] = 0 } } } internal fun dots() = dots.joinToString("") fun dotSizeFor(size: Byte) = dotSizes[size] ?: 0 fun selectNext() { if (selectedIndex >= dots.size - 1) { return } ++selectedIndex if (dots.size <= SIZE_THRESHOLD) { selectNextSmall() } else { selectNextLarge() } } fun selectPrevious() { if (selectedIndex == 0) { return } --selectedIndex if (dots.size <= SIZE_THRESHOLD) { selectPreviousSmall() } else { selectPreviousLarge() } } private fun selectNextSmall() { dots[selectedIndex] = 6 dots[selectedIndex - 1] = 5 } private fun selectNextLarge() { selectNextSmall() // no more than 3 5's in a row backward if (selectedIndex > 3 && dots[selectedIndex - 1] == 5.toByte() && dots[selectedIndex - 2] == 5.toByte() && dots[selectedIndex - 3] == 5.toByte() && dots[selectedIndex - 4] == 5.toByte()) { dots[selectedIndex - 4] = 4 if (selectedIndex - 5 >= 0) { dots[selectedIndex - 5] = 2 (selectedIndex - 6 downTo 0) .takeWhile { dots[it] != 0.toByte() } .forEach { dots[it] = 0 } } } // 6 must be around 3 or higher if (selectedIndex + 1 < dots.size && dots[selectedIndex + 1] < 3) { dots[selectedIndex + 1] = 3 // set the next one to 1 if any if (selectedIndex + 2 < dots.size && dots[selectedIndex + 2] < 1) { dots[selectedIndex + 2] = 1 } } // Scroll to keep the selected dot within bound val endBound = selectedIndex * (dotSize + dotSpacing) + dotSize if (endBound > dotBound) { scrollAmount = endBound - dotBound targetScrollListener?.scrollToTarget(scrollAmount) } } private fun selectPreviousSmall() { dots[selectedIndex] = 6 dots[selectedIndex + 1] = 5 } private fun selectPreviousLarge() { selectPreviousSmall() // no more than 3 5's in a row backward if (selectedIndex < dots.size - 4 && dots[selectedIndex + 1] == 5.toByte() && dots[selectedIndex + 2] == 5.toByte() && dots[selectedIndex + 3] == 5.toByte() && dots[selectedIndex + 4] == 5.toByte()) { dots[selectedIndex + 4] = 4 if (selectedIndex + 5 < dots.size) { dots[selectedIndex + 5] = 2 (selectedIndex + 6 until dots.size) .takeWhile { dots[it] != 0.toByte() } .forEach { i -> dots[i] = 0 } } } // 6 must be around 3 or higher if (selectedIndex - 1 >= 0 && dots[selectedIndex - 1] < 3) { dots[selectedIndex - 1] = 3 // set the next one to 1 if any if (selectedIndex - 2 >= 0 && dots[selectedIndex - 2] < 1) { dots[selectedIndex - 2] = 1 } } // Scroll to keep the selected dot within bound val startBound = selectedIndex * (dotSize + dotSpacing) if (startBound < scrollAmount) { scrollAmount = selectedIndex * (dotSize + dotSpacing) targetScrollListener?.scrollToTarget(scrollAmount) } } interface TargetScrollListener { fun scrollToTarget(target: Int) } companion object { private const val SIZE_THRESHOLD = 5 } }
9
Kotlin
2
1
fb00fe41a2b32dbbd9fcc88d0fcd8d531c9b0638
4,542
Aura
MIT License
projects/KtorApplications/ktor-client/ktor-client-core/src/io/ktor/client/call/HttpClientCall.kt
seungmanlee
127,453,229
true
{"Text": 680, "Markdown": 1247, "Gradle": 123, "Shell": 59, "Ignore List": 305, "Batchfile": 38, "XML": 288, "Java Properties": 43, "Kotlin": 581, "INI": 3, "Java": 13, "Proguard": 6, "JSON": 1057, "HTML": 2613, "JavaScript": 7548, "CMake": 1, "Makefile": 71, "C++": 42, "JAR Manifest": 61, "SQL": 31, "Motorola 68K Assembly": 14, "CSS": 47, "robots.txt": 2, "SVG": 2, "Fluent": 2, "FreeMarker": 12, "Maven POM": 9, "YAML": 253, "JSON with Comments": 36, "Handlebars": 3, "CoffeeScript": 6, "Python": 66, "EJS": 50, "Git Config": 2, "Emacs Lisp": 4, "Option List": 4, "Roff Manpage": 74, "Roff": 3, "TextMate Properties": 1, "Diff": 8, "EditorConfig": 14, "HAProxy": 1, "Git Attributes": 2, "Public Key": 17, "GLSL": 1, "ActionScript": 4, "C": 127, "M4Sugar": 2, "Gnuplot": 2, "LiveScript": 2, "Pug": 1, "DTrace": 1}
package io.ktor.client.call import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.response.* import io.ktor.content.* import java.io.* import java.util.concurrent.atomic.* import kotlin.reflect.* import kotlin.reflect.full.* class HttpRequestContext(val client: HttpClient, val request: HttpRequest) class HttpClientCall private constructor( private val client: HttpClient ) : Closeable { private val received = AtomicBoolean(false) lateinit var request: HttpRequest private set lateinit var response: HttpResponse private set suspend fun receive(expectedType: KClass<*>): Any { if (response::class.isSubclassOf(expectedType)) return response if (!received.compareAndSet(false, true)) throw DoubleReceiveException(this) val subject = HttpResponseContainer(expectedType, response.receiveContent()) val result = client.responsePipeline.execute(this, subject).response if (!result::class.isSubclassOf(expectedType)) throw NoTransformationFound(result::class, expectedType) return result } override fun close() { response.close() } companion object { suspend fun create(requestBuilder: HttpRequestBuilder, client: HttpClient): HttpClientCall { val call = HttpClientCall(client) call.request = client.createRequest(requestBuilder, call) val context = HttpRequestContext(client, call.request) val content = client.requestPipeline.execute(context, requestBuilder.body) as? OutgoingContent ?: error("") call.response = call.request.execute(content) return call } } } suspend fun HttpClient.call(block: HttpRequestBuilder.() -> Unit = {}): HttpClientCall = HttpClientCall.create(HttpRequestBuilder().apply(block), this) suspend inline fun <reified T> HttpClientCall.receive(): T = receive(T::class) as T class DoubleReceiveException(call: HttpClientCall) : IllegalStateException() { override val message: String = "Request already received: $call" } class NoTransformationFound(from: KClass<*>, to: KClass<*>) : UnsupportedOperationException() { override val message: String? = "No transformation found: $from -> $to" }
0
JavaScript
0
0
b2c0fc6d192648c8ec0bb0a538840a57ac69d65b
2,272
ktor
Apache License 2.0
experimental/examples/minesweeper/src/commonMain/kotlin/BoardView.kt
JetBrains
293,498,508
false
null
import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @Composable fun BoardView(game: GameController) = with(GameStyles) { Column { for (row in 0 until game.rows) { Row(verticalAlignment = Alignment.CenterVertically) { for (column in 0 until game.columns) { val cell = game.cellAt(row, column)!! Box( modifier = Modifier.size(cellSize, cellSize) .background(color = getCellColor(cell)) .border(width = cellBorderWidth, color = borderColor) .gameInteraction( open = { game.openCell(cell) }, flag = { game.toggleFlag(cell) }, seek = { game.openNotFlaggedNeighbors(cell) } ) ) { if (cell.isOpened) { if (cell.hasBomb) { Mine() } else if (cell.bombsNear > 0) { OpenedCell(cell) } } else if (cell.isFlagged) { Flag() } } } } } } } private fun GameStyles.getCellColor(cell: Cell): Color = if (cell.isOpened) openedCellColor else closedCellColor
934
Kotlin
826
9,090
97266a0ac8c0d7a8ad8d19ead1c925751a00ff1c
1,864
compose-jb
Apache License 2.0
compiler/fir/analysis-tests/testData/resolve/kt41984.kt
JetBrains
3,432,266
false
null
// ISSUE: KT-41984 // FILE: A.java import org.jetbrains.annotations.NotNull; public abstract class A<T, V> { @NotNull public abstract String take(@NotNull V value); @NotNull public abstract String takeInv(@NotNull Inv<@NotNull V> value); } // FILE: main.kt class Inv<T> open <!ABSTRACT_CLASS_MEMBER_NOT_IMPLEMENTED!>class B<!><V> : A<Any, V>() { <!NOTHING_TO_OVERRIDE!>override<!> fun take(value: V): String { return "" } <!NOTHING_TO_OVERRIDE!>override<!> fun takeInv(value: Inv<V>): String = "" } fun test_1(b: B<Int>, x: Int, inv: Inv<Int>) { b.<!OVERLOAD_RESOLUTION_AMBIGUITY!>take<!>(x) b.<!NONE_APPLICABLE!>take<!>(null) b.<!OVERLOAD_RESOLUTION_AMBIGUITY!>takeInv<!>(inv) }
7
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
737
kotlin
Apache License 2.0
app/src/main/java/com/gggames/hourglass/presentation/endround/ChangeRoundDialogFragment.kt
giladgotman
252,945,764
false
null
package com.gggames.hourglass.presentation.endround import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.appcompat.app.AppCompatActivity import com.gggames.hourglass.R import com.gggames.hourglass.model.Round import com.gggames.hourglass.model.Team import com.gggames.hourglass.model.roundIdToName import com.gggames.hourglass.presentation.gameon.GameScreenContract import com.gggames.hourglass.presentation.onboarding.ViewPagerFragment import com.gggames.hourglass.presentation.onboarding.ViewPagerFragmentAdapter import com.gggames.hourglass.utils.rx.EventEmitter import com.gggames.hourglass.utils.rx.ViewEventEmitter import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialogFragment import kotlinx.android.synthetic.main.fragment_round_change.* class ChangeRoundDialogFragment : BottomSheetDialogFragment(), EventEmitter<GameScreenContract.UiEvent> by ViewEventEmitter() { private lateinit var onDismissBlock: () -> Unit fun show(activity: AppCompatActivity) { show(activity.supportFragmentManager, this.javaClass.simpleName) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = inflater.inflate(R.layout.fragment_round_change, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { val currentRound: Round = it.getParcelable(KEY_CURR_ROUND)!! val teams = it.getParcelableArray(KEY_TEAMS) as Array<Team>? ?: emptyArray() initializeCarouselViewPager(currentRound, teams.toList()) button_ready.setOnClickListener { if (view_pager_carousel.currentItem == 0) { view_pager_carousel.setCurrentItem(1, true) button_ready.text = getString(R.string.change_round_next_round_cta) } else { dismiss() } } } } fun setOnDismiss(block: () -> Unit) { onDismissBlock = block } override fun onDismiss(dialog: DialogInterface) { super.onDismiss(dialog) GameScreenContract.UiEvent.RoundOverDialogDismissed.emit() onDismissBlock() } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) setupBottomSheet(dialog) return dialog } private fun setupBottomSheet(dialog: Dialog) { dialog.setOnShowListener { val bottomSheet = dialog.findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet) val behavior: BottomSheetBehavior<*> = BottomSheetBehavior.from(bottomSheet!!) behavior.isHideable = true behavior.state = BottomSheetBehavior.STATE_EXPANDED } } private fun initializeCarouselViewPager( currentRound: Round, teamsWithScore: List<Team> ) { val nextRoundId = currentRound.roundNumber + 1 val roundName = roundIdToName(nextRoundId) val carouselItems: List<ViewPagerFragment> = listOf( ViewPagerFragment(EndRoundDialogFragment(), Bundle().apply { putParcelable(KEY_CURR_ROUND, currentRound) putParcelableArray(KEY_TEAMS, teamsWithScore.toTypedArray()) }), ViewPagerFragment( NextRoundDialogFragment(), NextRoundDialogFragment.createArgs(nextRoundId, roundName, currentRound.turn) ) ) // view_pager_carousel.setPageTransformer { page, position -> // page.alpha = 0f // page.visibility = View.VISIBLE // // // Start Animation for a short period of time // page.animate() // .alpha(1f).duration = 300 // } view_pager_carousel.isUserInputEnabled = false view_pager_carousel.adapter = ViewPagerFragmentAdapter(requireActivity().supportFragmentManager, lifecycle, carouselItems) if (carouselItems.size > 1) { view_pager_carousel.offscreenPageLimit = carouselItems.size - 1 } } companion object { fun newInstance( prevRound: Round, roundOver: Boolean, teamsWithScore: List<Team> ): ChangeRoundDialogFragment { return ChangeRoundDialogFragment() .apply { isCancelable = true arguments = Bundle().apply { putParcelable(KEY_CURR_ROUND, prevRound) putBoolean(KEY_ROUND_OVER, roundOver) putParcelableArray(KEY_TEAMS, teamsWithScore.toTypedArray()) } } } } } val KEY_CURR_ROUND = "KEY_CURR_ROUND" val KEY_TEAMS = "KEY_TEAMS" val KEY_ROUND_OVER = "KEY_ROUND_OVER"
25
Kotlin
0
0
0f0fa11fbe1131387148e4d6d1b7d85c23d6e5f0
5,236
celebs
MIT License
core/src/main/java/com/alamkanak/weekview/NowLineDrawer.kt
shykero
281,661,222
true
{"Kotlin": 246954}
package com.alamkanak.weekview import android.graphics.Canvas import com.alamkanak.weekview.Constants.MINUTES_PER_HOUR import kotlin.math.max internal class NowLineDrawer( private val config: WeekViewConfigWrapper ) : Drawer { override fun draw( drawingContext: DrawingContext, canvas: Canvas ) { if (config.showNowLine.not()) { return } val startPixel = drawingContext .dateRangeWithStartPixels .filter { (date, _) -> date.isToday } .map { (_, startPixel) -> startPixel } .firstOrNull() ?: return canvas.drawLine(startPixel) } private fun Canvas.drawLine(startPixel: Float) { val top = config.headerHeight + config.currentOrigin.y val now = now() val portionOfDay = (now.hour - config.minHour) + now.minute / MINUTES_PER_HOUR val portionOfDayInPixels = portionOfDay * config.hourHeight val verticalOffset = top + portionOfDayInPixels val startX = max(startPixel, config.timeColumnWidth) val endX = startPixel + config.totalDayWidth drawLine(startX, verticalOffset, endX, verticalOffset, config.nowLinePaint) if (config.showNowLineDot) { drawDot(startPixel, verticalOffset) } } private fun Canvas.drawDot(startPixel: Float, lineStartY: Float) { val dotRadius = config.nowDotPaint.strokeWidth val actualStartPixel = max(startPixel, config.timeColumnWidth) val fullLineWidth = config.totalDayWidth val actualEndPixel = startPixel + fullLineWidth val currentlyDisplayedWidth = actualEndPixel - actualStartPixel val currentlyDisplayedPortion = currentlyDisplayedWidth / fullLineWidth val adjustedRadius = currentlyDisplayedPortion * dotRadius drawCircle(actualStartPixel, lineStartY, adjustedRadius, config.nowDotPaint) } }
0
null
0
0
c5b74af74415d560e54240546e2ea7dd798bb2be
1,929
Android-Week-View
Apache License 2.0
lib/src/test/kotlin/org/hravemzdy/legalios/service/Service_Legalios_Example_01_Health_05_FactorCompoundTest.kt
infohravemzdy
425,931,709
false
{"Kotlin": 1039271}
package org.hravemzdy.legalios.service import com.github.michaelbull.result.* import org.hravemzdy.legalios.TestDecParams import org.hravemzdy.legalios.TestDecScenario import org.hravemzdy.legalios.service.errors.HistoryResultError import org.hravemzdy.legalios.interfaces.IBundleProps import org.hravemzdy.legalios.interfaces.IPropsHealth import org.hravemzdy.legalios.service.types.Period import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertEquals class Service_Legalios_Example_01_Health_05_FactorCompoundTest : Spek({ val testList = listOf( TestDecScenario("2010", listOf( TestDecParams( "2010-1", 2010, 1, 2010, 1, 13.50 ), TestDecParams( "2010-2", 2010, 2, 2010, 2, 13.50 ), TestDecParams( "2010-3", 2010, 3, 2010, 3, 13.50 ), TestDecParams( "2010-4", 2010, 4, 2010, 4, 13.50 ), TestDecParams( "2010-5", 2010, 5, 2010, 5, 13.50 ), TestDecParams( "2010-6", 2010, 6, 2010, 6, 13.50 ), TestDecParams( "2010-7", 2010, 7, 2010, 7, 13.50 ), TestDecParams( "2010-8", 2010, 8, 2010, 8, 13.50 ), TestDecParams( "2010-9", 2010, 9, 2010, 9, 13.50 ), TestDecParams( "2010-10", 2010, 10, 2010, 10, 13.50 ), TestDecParams( "2010-11", 2010, 11, 2010, 11, 13.50 ), TestDecParams( "2010-12", 2010, 12, 2010, 12, 13.50 ), )), TestDecScenario("2011", listOf( TestDecParams( "2011-1", 2011, 1, 2011, 1, 13.50 ), TestDecParams( "2011-2", 2011, 2, 2011, 2, 13.50 ), TestDecParams( "2011-3", 2011, 3, 2011, 3, 13.50 ), TestDecParams( "2011-4", 2011, 4, 2011, 4, 13.50 ), TestDecParams( "2011-5", 2011, 5, 2011, 5, 13.50 ), TestDecParams( "2011-6", 2011, 6, 2011, 6, 13.50 ), TestDecParams( "2011-7", 2011, 7, 2011, 7, 13.50 ), TestDecParams( "2011-8", 2011, 8, 2011, 8, 13.50 ), TestDecParams( "2011-9", 2011, 9, 2011, 9, 13.50 ), TestDecParams( "2011-10", 2011, 10, 2011, 10, 13.50 ), TestDecParams( "2011-11", 2011, 11, 2011, 11, 13.50 ), TestDecParams( "2011-12", 2011, 12, 2011, 12, 13.50 ), )), TestDecScenario("2012", listOf( TestDecParams( "2012-1", 2012, 1, 2012, 1, 13.50 ), TestDecParams( "2012-2", 2012, 2, 2012, 2, 13.50 ), TestDecParams( "2012-3", 2012, 3, 2012, 3, 13.50 ), TestDecParams( "2012-4", 2012, 4, 2012, 4, 13.50 ), TestDecParams( "2012-5", 2012, 5, 2012, 5, 13.50 ), TestDecParams( "2012-6", 2012, 6, 2012, 6, 13.50 ), TestDecParams( "2012-7", 2012, 7, 2012, 7, 13.50 ), TestDecParams( "2012-8", 2012, 8, 2012, 8, 13.50 ), TestDecParams( "2012-9", 2012, 9, 2012, 9, 13.50 ), TestDecParams( "2012-10", 2012, 10, 2012, 10, 13.50 ), TestDecParams( "2012-11", 2012, 11, 2012, 11, 13.50 ), TestDecParams( "2012-12", 2012, 12, 2012, 12, 13.50 ), )), TestDecScenario("2013", listOf( TestDecParams( "2013-1", 2013, 1, 2013, 1, 13.50 ), TestDecParams( "2013-2", 2013, 2, 2013, 2, 13.50 ), TestDecParams( "2013-3", 2013, 3, 2013, 3, 13.50 ), TestDecParams( "2013-4", 2013, 4, 2013, 4, 13.50 ), TestDecParams( "2013-5", 2013, 5, 2013, 5, 13.50 ), TestDecParams( "2013-6", 2013, 6, 2013, 6, 13.50 ), TestDecParams( "2013-7", 2013, 7, 2013, 7, 13.50 ), TestDecParams( "2013-8", 2013, 8, 2013, 8, 13.50 ), TestDecParams( "2013-9", 2013, 9, 2013, 9, 13.50 ), TestDecParams( "2013-10", 2013, 10, 2013, 10, 13.50 ), TestDecParams( "2013-11", 2013, 11, 2013, 11, 13.50 ), TestDecParams( "2013-12", 2013, 12, 2013, 12, 13.50 ), )), TestDecScenario("2014", listOf( TestDecParams( "2014-1", 2014, 1, 2014, 1, 13.50 ), TestDecParams( "2014-2", 2014, 2, 2014, 2, 13.50 ), TestDecParams( "2014-3", 2014, 3, 2014, 3, 13.50 ), TestDecParams( "2014-4", 2014, 4, 2014, 4, 13.50 ), TestDecParams( "2014-5", 2014, 5, 2014, 5, 13.50 ), TestDecParams( "2014-6", 2014, 6, 2014, 6, 13.50 ), TestDecParams( "2014-7", 2014, 7, 2014, 7, 13.50 ), TestDecParams( "2014-8", 2014, 8, 2014, 8, 13.50 ), TestDecParams( "2014-9", 2014, 9, 2014, 9, 13.50 ), TestDecParams( "2014-10", 2014, 10, 2014, 10, 13.50 ), TestDecParams( "2014-11", 2014, 11, 2014, 11, 13.50 ), TestDecParams( "2014-12", 2014, 12, 2014, 12, 13.50 ), )), TestDecScenario("2015", listOf( TestDecParams( "2015-1", 2015, 1, 2015, 1, 13.50 ), TestDecParams( "2015-2", 2015, 2, 2015, 2, 13.50 ), TestDecParams( "2015-3", 2015, 3, 2015, 3, 13.50 ), TestDecParams( "2015-4", 2015, 4, 2015, 4, 13.50 ), TestDecParams( "2015-5", 2015, 5, 2015, 5, 13.50 ), TestDecParams( "2015-6", 2015, 6, 2015, 6, 13.50 ), TestDecParams( "2015-7", 2015, 7, 2015, 7, 13.50 ), TestDecParams( "2015-8", 2015, 8, 2015, 8, 13.50 ), TestDecParams( "2015-9", 2015, 9, 2015, 9, 13.50 ), TestDecParams( "2015-10", 2015, 10, 2015, 10, 13.50 ), TestDecParams( "2015-11", 2015, 11, 2015, 11, 13.50 ), TestDecParams( "2015-12", 2015, 12, 2015, 12, 13.50 ), )), TestDecScenario("2016", listOf( TestDecParams( "2016-1", 2016, 1, 2016, 1, 13.50 ), TestDecParams( "2016-2", 2016, 2, 2016, 2, 13.50 ), TestDecParams( "2016-3", 2016, 3, 2016, 3, 13.50 ), TestDecParams( "2016-4", 2016, 4, 2016, 4, 13.50 ), TestDecParams( "2016-5", 2016, 5, 2016, 5, 13.50 ), TestDecParams( "2016-6", 2016, 6, 2016, 6, 13.50 ), TestDecParams( "2016-7", 2016, 7, 2016, 7, 13.50 ), TestDecParams( "2016-8", 2016, 8, 2016, 8, 13.50 ), TestDecParams( "2016-9", 2016, 9, 2016, 9, 13.50 ), TestDecParams( "2016-10", 2016, 10, 2016, 10, 13.50 ), TestDecParams( "2016-11", 2016, 11, 2016, 11, 13.50 ), TestDecParams( "2016-12", 2016, 12, 2016, 12, 13.50 ), )), TestDecScenario("2017", listOf( TestDecParams( "2017-1", 2017, 1, 2017, 1, 13.50 ), TestDecParams( "2017-2", 2017, 2, 2017, 2, 13.50 ), TestDecParams( "2017-3", 2017, 3, 2017, 3, 13.50 ), TestDecParams( "2017-4", 2017, 4, 2017, 4, 13.50 ), TestDecParams( "2017-5", 2017, 5, 2017, 5, 13.50 ), TestDecParams( "2017-6", 2017, 6, 2017, 6, 13.50 ), TestDecParams( "2017-7", 2017, 7, 2017, 7, 13.50 ), TestDecParams( "2017-8", 2017, 8, 2017, 8, 13.50 ), TestDecParams( "2017-9", 2017, 9, 2017, 9, 13.50 ), TestDecParams( "2017-10", 2017, 10, 2017, 10, 13.50 ), TestDecParams( "2017-11", 2017, 11, 2017, 11, 13.50 ), TestDecParams( "2017-12", 2017, 12, 2017, 12, 13.50 ), )), TestDecScenario("2018", listOf( TestDecParams( "2018-1", 2018, 1, 2018, 1, 13.50 ), TestDecParams( "2018-2", 2018, 2, 2018, 2, 13.50 ), TestDecParams( "2018-3", 2018, 3, 2018, 3, 13.50 ), TestDecParams( "2018-4", 2018, 4, 2018, 4, 13.50 ), TestDecParams( "2018-5", 2018, 5, 2018, 5, 13.50 ), TestDecParams( "2018-6", 2018, 6, 2018, 6, 13.50 ), TestDecParams( "2018-7", 2018, 7, 2018, 7, 13.50 ), TestDecParams( "2018-8", 2018, 8, 2018, 8, 13.50 ), TestDecParams( "2018-9", 2018, 9, 2018, 9, 13.50 ), TestDecParams( "2018-10", 2018, 10, 2018, 10, 13.50 ), TestDecParams( "2018-11", 2018, 11, 2018, 11, 13.50 ), TestDecParams( "2018-12", 2018, 12, 2018, 12, 13.50 ), )), TestDecScenario("2019", listOf( TestDecParams( "2019-1", 2019, 1, 2019, 1, 13.50 ), TestDecParams( "2019-2", 2019, 2, 2019, 2, 13.50 ), TestDecParams( "2019-3", 2019, 3, 2019, 3, 13.50 ), TestDecParams( "2019-4", 2019, 4, 2019, 4, 13.50 ), TestDecParams( "2019-5", 2019, 5, 2019, 5, 13.50 ), TestDecParams( "2019-6", 2019, 6, 2019, 6, 13.50 ), TestDecParams( "2019-7", 2019, 7, 2019, 7, 13.50 ), TestDecParams( "2019-8", 2019, 8, 2019, 8, 13.50 ), TestDecParams( "2019-9", 2019, 9, 2019, 9, 13.50 ), TestDecParams( "2019-10", 2019, 10, 2019, 10, 13.50 ), TestDecParams( "2019-11", 2019, 11, 2019, 11, 13.50 ), TestDecParams( "2019-12", 2019, 12, 2019, 12, 13.50 ), )), TestDecScenario("2020", listOf( TestDecParams( "2020-1", 2020, 1, 2020, 1, 13.50 ), TestDecParams( "2020-2", 2020, 2, 2020, 2, 13.50 ), TestDecParams( "2020-3", 2020, 3, 2020, 3, 13.50 ), TestDecParams( "2020-4", 2020, 4, 2020, 4, 13.50 ), TestDecParams( "2020-5", 2020, 5, 2020, 5, 13.50 ), TestDecParams( "2020-6", 2020, 6, 2020, 6, 13.50 ), TestDecParams( "2020-7", 2020, 7, 2020, 7, 13.50 ), TestDecParams( "2020-8", 2020, 8, 2020, 8, 13.50 ), TestDecParams( "2020-9", 2020, 9, 2020, 9, 13.50 ), TestDecParams( "2020-10", 2020, 10, 2020, 10, 13.50 ), TestDecParams( "2020-11", 2020, 11, 2020, 11, 13.50 ), TestDecParams( "2020-12", 2020, 12, 2020, 12, 13.50 ), )), TestDecScenario("2021", listOf( TestDecParams( "2021-1", 2021, 1, 2021, 1, 13.50 ), TestDecParams( "2021-2", 2021, 2, 2021, 2, 13.50 ), TestDecParams( "2021-3", 2021, 3, 2021, 3, 13.50 ), TestDecParams( "2021-4", 2021, 4, 2021, 4, 13.50 ), TestDecParams( "2021-5", 2021, 5, 2021, 5, 13.50 ), TestDecParams( "2021-6", 2021, 6, 2021, 6, 13.50 ), TestDecParams( "2021-7", 2021, 7, 2021, 7, 13.50 ), TestDecParams( "2021-8", 2021, 8, 2021, 8, 13.50 ), TestDecParams( "2021-9", 2021, 9, 2021, 9, 13.50 ), TestDecParams( "2021-10", 2021, 10, 2021, 10, 13.50 ), TestDecParams( "2021-11", 2021, 11, 2021, 11, 13.50 ), TestDecParams( "2021-12", 2021, 12, 2021, 12, 13.50 ), )), TestDecScenario("2022", listOf( TestDecParams( "2022-1", 2022, 1, 2022, 1, 13.50 ), TestDecParams( "2022-2", 2022, 2, 2022, 2, 13.50 ), TestDecParams( "2022-3", 2022, 3, 2022, 3, 13.50 ), TestDecParams( "2022-4", 2022, 4, 2022, 4, 13.50 ), TestDecParams( "2022-5", 2022, 5, 2022, 5, 13.50 ), TestDecParams( "2022-6", 2022, 6, 2022, 6, 13.50 ), TestDecParams( "2022-7", 2022, 7, 2022, 7, 13.50 ), TestDecParams( "2022-8", 2022, 8, 2022, 8, 13.50 ), TestDecParams( "2022-9", 2022, 9, 2022, 9, 13.50 ), TestDecParams( "2022-10", 2022, 10, 2022, 10, 13.50 ), TestDecParams( "2022-11", 2022, 11, 2022, 11, 13.50 ), TestDecParams( "2022-12", 2022, 12, 2022, 12, 13.50 ), )), ) // 01_Health_05_FactorCompound logTestDecExamples("01_Health_05_FactorCompound.txt", testList) testList.forEach { tx -> describe("year ${tx.title}") { tx.tests.forEach { tt -> context("period ${tt.title}") { val period = Period.getWithYearMonth(tt.year, tt.month) val service = ServiceLegalios() val result: Result<IBundleProps, HistoryResultError> = service.getBundle(period) val bundle: IBundleProps? = result.get() val error: HistoryResultError? = result.getError() val props: IPropsHealth? = bundle?.healthProps tt.testBasicResult(this, result, bundle, props, error) it("GetProps should return value = ${tt.expected}") { val expDecimal = tt.expectedDec() assertEquals(expDecimal, props?.factorCompound) } } } } } })
0
Kotlin
0
0
3393f208546e8b369222dffb91e01bb9515045b8
12,472
legalioskotlin
The Unlicense
materialLib/src/androidTest/java/com/google/android/material/composethemeadapter/test/DefaultFontFamilyMdcThemeTest.kt
material-components
281,142,915
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("DEPRECATION") package com.google.android.material.composethemeadapter.test import android.view.ContextThemeWrapper import androidx.annotation.StyleRes import androidx.compose.material.MaterialTheme import androidx.compose.material.Typography import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.toFontFamily import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import com.google.android.material.composethemeadapter.MdcTheme import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @MediumTest @RunWith(JUnit4::class) class DefaultFontFamilyMdcThemeTest { @get:Rule val composeTestRule = createAndroidComposeRule<DefaultFontFamilyMdcActivity>() @Test @SdkSuppress(maxSdkVersion = 22) // On API 21-22, the family is loaded with only the 400 font fun rubik_family_api21() = composeTestRule.setContent { val rubik = Font(R.font.rubik, FontWeight.W400).toFontFamily() WithThemeOverlay(R.style.ThemeOverlay_MdcThemeTest_DefaultFontFamily_Rubik) { MdcTheme(setDefaultFontFamily = true) { MaterialTheme.typography.assertFontFamilies(expected = rubik) } } WithThemeOverlay(R.style.ThemeOverlay_MdcThemeTest_DefaultAndroidFontFamily_Rubik) { MdcTheme(setDefaultFontFamily = true) { MaterialTheme.typography.assertFontFamilies(expected = rubik) } } } @Test @SdkSuppress(minSdkVersion = 23) // XML font families with >1 fonts are only supported on API 23+ fun rubik_family_api23() = composeTestRule.setContent { val rubik = FontFamily( Font(R.font.rubik_300, FontWeight.W300), Font(R.font.rubik_400, FontWeight.W400), Font(R.font.rubik_500, FontWeight.W500), Font(R.font.rubik_700, FontWeight.W700), ) WithThemeOverlay(R.style.ThemeOverlay_MdcThemeTest_DefaultFontFamily_Rubik) { MdcTheme(setDefaultFontFamily = true) { MaterialTheme.typography.assertFontFamilies(expected = rubik) } } WithThemeOverlay(R.style.ThemeOverlay_MdcThemeTest_DefaultAndroidFontFamily_Rubik) { MdcTheme(setDefaultFontFamily = true) { MaterialTheme.typography.assertFontFamilies(expected = rubik) } } } @Test fun rubik_fixed400() = composeTestRule.setContent { val rubik400 = Font(R.font.rubik_400, FontWeight.W400).toFontFamily() WithThemeOverlay(R.style.ThemeOverlay_MdcThemeTest_DefaultFontFamily_Rubik400) { MdcTheme(setDefaultFontFamily = true) { MaterialTheme.typography.assertFontFamilies(expected = rubik400) } } WithThemeOverlay(R.style.ThemeOverlay_MdcThemeTest_DefaultAndroidFontFamily_Rubik400) { MdcTheme(setDefaultFontFamily = true) { MaterialTheme.typography.assertFontFamilies(expected = rubik400) } } } @Test fun rubik_fixed700_withTextAppearances() = composeTestRule.setContent { val rubik700 = Font(R.font.rubik_700, FontWeight.W700).toFontFamily() WithThemeOverlay( R.style.ThemeOverlay_MdcThemeTest_DefaultFontFamilies_Rubik700_WithTextAppearances ) { MdcTheme { MaterialTheme.typography.assertFontFamilies( expected = rubik700, notEquals = true ) } } } } private fun Typography.assertFontFamilies( expected: FontFamily, notEquals: Boolean = false ) { if (notEquals) assertNotEquals(expected, h1.fontFamily) else assertEquals(expected, h1.fontFamily) if (notEquals) assertNotEquals(expected, h2.fontFamily) else assertEquals(expected, h2.fontFamily) if (notEquals) assertNotEquals(expected, h3.fontFamily) else assertEquals(expected, h3.fontFamily) if (notEquals) assertNotEquals(expected, h4.fontFamily) else assertEquals(expected, h4.fontFamily) if (notEquals) assertNotEquals(expected, h5.fontFamily) else assertEquals(expected, h5.fontFamily) if (notEquals) assertNotEquals(expected, h6.fontFamily) else assertEquals(expected, h6.fontFamily) if (notEquals) assertNotEquals(expected, subtitle1.fontFamily) else assertEquals(expected, subtitle1.fontFamily) if (notEquals) assertNotEquals(expected, subtitle2.fontFamily) else assertEquals(expected, subtitle2.fontFamily) if (notEquals) assertNotEquals(expected, body1.fontFamily) else assertEquals(expected, body1.fontFamily) if (notEquals) assertNotEquals(expected, body2.fontFamily) else assertEquals(expected, body2.fontFamily) if (notEquals) assertNotEquals(expected, button.fontFamily) else assertEquals(expected, button.fontFamily) if (notEquals) assertNotEquals(expected, caption.fontFamily) else assertEquals(expected, caption.fontFamily) if (notEquals) assertNotEquals(expected, overline.fontFamily) else assertEquals(expected, overline.fontFamily) } /** * Function which applies an Android theme overlay to the current context. */ @Composable fun WithThemeOverlay( @StyleRes themeOverlayId: Int, content: @Composable () -> Unit, ) { val themedContext = ContextThemeWrapper(LocalContext.current, themeOverlayId) CompositionLocalProvider(LocalContext provides themedContext, content = content) }
8
null
42
411
b689b1e6b41b932f7d100385566194de46ce4ae4
6,473
material-components-android-compose-theme-adapter
Apache License 2.0
com.github.queercat/src/main/kotlin/Main.kt
queercat
766,336,490
false
{"Kotlin": 14888}
package org.example import java.io.DataInputStream import java.io.DataOutputStream import java.net.ServerSocket import java.util.* import kotlin.concurrent.thread class Environment() { val values = HashMap<String, Type>() var outer: Environment? = null constructor(parameters: Type.List, arguments: Type.List, outer: Environment?) : this() { if (parameters.value.count() != arguments.value.count()) throw IllegalArgumentException("Parameters") this.outer = outer parameters.value.zip(arguments.value).forEach { val (parameter, argument) = it if (parameter !is Type.Symbol) throw IllegalArgumentException("Expected all parameters to be symbol but instead found ${it.first::class.qualifiedName} ${it.first}") values[parameter.value] = argument } } fun find(symbol: String): Environment { return if (this.values.containsKey(symbol)) this else this.outer?.find(symbol) ?: throw ClassNotFoundException("Unable to find symbol $symbol in environment $this") } } open class Type { class Number(val value: Float) : Type() { override fun toString(): kotlin.String { return value.toString() } } class Symbol(val value: kotlin.String) : Type() { override fun toString(): kotlin.String { return value } } class Null : Type() { override fun toString(): kotlin.String { return "null" } } class List(val value: Vector<Type>) : Type() { override fun toString(): kotlin.String { val text = value.joinToString { it.toString() } return "($text)" } } class String(val value: kotlin.String) : Type() { override fun toString(): kotlin.String { return value } } class Function( val body: (Type.List) -> Type, ) : Type() { override fun toString(): kotlin.String { return "Function {$body}" } } class Boolean(val value: kotlin.Boolean) : Type() { override fun toString(): kotlin.String { return value.toString() } } class Atom(var value: Type) : Type() { override fun toString(): kotlin.String { return "@ -> ${value.toString()}" } } class Thread(var ast: Type.List, var environment: Environment) : Type() { operator fun invoke(): Type.Thread { val lambda: () -> Unit = { evaluate(ast, environment) } val thread = thread(block = lambda, isDaemon = true) return this } } class Server(val port: Int, var lambda: Type.Function, var environment: Environment) : Type() { operator fun invoke(): Type { while (true) { try { val server = ServerSocket(port) val client = server.accept() val output = DataOutputStream(client.getOutputStream()) //val input = DataInputStream(client.getInputStream()) val content = "hello" //input.close() val arguments = Type.List(Vector(listOf(Type.String(content)))) val result = lambda.body(arguments).assert<Type.List>() result.assertAllOfType<Type.String>() result.value.forEach { output.write(it.assert<Type.String>().value.toByteArray()) } output.flush() client.close() server.close() } catch (exception: Exception) { error(exception) } } return Type.Null() } } } class Peekable<T>(private val values: List<T>) { private var index = 0 fun peek(): T { return if (index > values.count() - 1) throw IndexOutOfBoundsException("Expected a value but instead found EOF.") else values[index] } fun next(): T { return if (index + 1 > values.count() - 1) throw IndexOutOfBoundsException("Expected a value but instead found EOF.") else values[++index] } } object Patterns { val numberPattern = Regex("\\d+") val unaryPattern = Regex("[()+\\-/*^@']") val symbolPattern = Regex("[a-zA-Z\\-\\d]+") } fun parseList(tokens: Peekable<String>): Type.List { val list = Vector<Type>() var token = tokens.next() while (token != ")") { list.addElement(parse(tokens)) token = tokens.next() } return Type.List(list) } fun parseAtom(tokens: Peekable<String>): Type { val token = tokens.peek() if (token[0] == '\"') { val text = token.slice(1 until token.length - 1) .replace("\\n", "\n") .replace("\\r", "\r") return Type.String(text) } if (Patterns.numberPattern.matches(token)) { return Type.Number(token.toFloat()) } else if (Patterns.unaryPattern.matches(token)) { return Type.Symbol(token) } else if (token == "true" || token == "false") { return Type.Boolean(token == "true") } return Type.Symbol(token) } fun apply(ast: Type, environment: Environment): Type { if (ast is Type.List) { return Type.List(Vector(ast.value.map { evaluate(it, environment) })) } if (ast is Type.Symbol) { return environment.find(ast.value).values[ast.value] ?: throw IllegalAccessException("Unable to find ${ast.value} in environment.") } return ast } fun evaluate(ast: Type, environment: Environment): Type { if (ast is Type.List) { if (ast.value.isEmpty()) return ast val first = ast.value.first() var arguments = Type.List(Vector(ast.value.slice(1..<ast.value.count()))) if (first !is Type.Symbol) throw IllegalArgumentException("Expected a symbol as the first argument but instead found {$first}") if (first.value == "'") { if (arguments.value.count() > 1) throw IllegalArgumentException("Too many parameters for quoting, expected 1 but instead found ${arguments.value.count()}") return arguments.value[0] } else if (first.value == "if") { if (arguments.value.count() != 3) throw IllegalArgumentException("Expected 3 arguments but instead found ${arguments.value.count()}") val bool = evaluate(arguments.value[0], environment) if (bool !is Type.Boolean) throw IllegalArgumentException("Expected boolean value but instead found ${bool::class.qualifiedName} $bool") return if (bool.value) evaluate(arguments.value[1], environment) else evaluate( arguments.value[2], environment ) } else if (first.value == "let") { if (arguments.value.count() != 2) throw IllegalArgumentException("Expected 2 arguments but instead found ${arguments.value.count()}") val symbol = arguments.value[0] if (symbol !is Type.Symbol) throw IllegalArgumentException("Expected symbol to assign to but instead found ${symbol::class.qualifiedName} $symbol") environment.values[symbol.value] = evaluate(arguments.value[1], environment) return environment.values[symbol.value] ?: throw ClassNotFoundException("Unable to bind value to symbol. $environment") } else if (first.value == "^") { return Type.Function(fun(lambdaArguments: Type.List): Type { val lambdaParameters = arguments.value[0] as Type.List val closure = Environment(lambdaParameters, lambdaArguments, environment) return evaluate(arguments.value[1], closure) }) } else if (first.value == "thread") { return Type.Thread(arguments.value[0].assert(), environment) } arguments = apply(arguments, environment).assert<Type.List>() val lambda = environment.find(first.value).values[first.value]!! if (lambda is Type.Function) { return lambda.body(arguments) } else if (lambda is Type.Thread) { return lambda() } else if (lambda is Type.Server) { return lambda() } return lambda } else if (ast is Type.Symbol) { return environment.find(ast.value).values[ast.value] ?: throw IllegalArgumentException("Unable to find symbol ${ast.value} in environment.") } return ast } fun parse(tokens: Peekable<String>): Type { val ast = when (val token = tokens.peek()) { "(" -> parseList(tokens) else -> parseAtom(tokens) } return ast } fun tokenize(source: String): List<String> { var start = 0 var end = 0 var char = source[start] val tokens = mutableListOf<String>() while (start < source.length) { char = source[start] if (Patterns.unaryPattern.matches(char.toString())) { end++ } else if (Patterns.numberPattern.matches(char.toString())) { while (end < source.length && Patterns.numberPattern.matches(source[end].toString())) { end++ } } else if (Patterns.symbolPattern.matches(char.toString())) { while (end < source.length && Patterns.symbolPattern.matches(source[end].toString())) { end++ } } else if (char == '"') { if (end == source.length - 1) { throw IllegalArgumentException("Expected a closing quote but instead found EOF.") } while (source[++end] != '"'){} end++ } else if (char == ' ' || char == '\n' || char == '\t' || char == '\r') { if (end == source.length - 1) { break } while (char == ' ' || char == '\n' || char == '\t' || char == '\r') { char = source[++end] } start = end continue } else { throw IllegalArgumentException("Unable to tokenize character ${source[start]}") } tokens += source.slice(start until end) start = end } return tokens } fun read(): String { val source: String = readlnOrNull() ?: throw Exception("Unable to read from standard-in.") return source } fun eval(source: String, environment: Environment): Type { val tokens = Peekable(tokenize(source)) val ast = parse(tokens) return evaluate(ast, environment) } inline fun <reified T : Type> Type.assert(): T { if (this !is T) throw IllegalArgumentException("Expected a ${T::class} type but found ${this::class.qualifiedName} $this instead.") return this } inline fun <reified T : Type>Type.List.assertAllOfType(): Type.List { this.value.forEach { it.assert<T>() } return this } fun createStandardEnvironment(): Environment { val environment = Environment() environment.values["+"] = Type.Function(fun(list: Type.List): Type { val first = list.value.first() if (first is Type.String) { list.assertAllOfType<Type.String>() var text = "" list.value.forEach { text += it.assert<Type.String>().value } return Type.String(text) } else if (first is Type.Number) { list.assertAllOfType<Type.Number>() var accumulator: Float = 0f list.value.forEach { accumulator += it.assert<Type.Number>().value } return Type.Number(accumulator) } return Type.Null() }) environment.values["atom"] = Type.Function(fun(list: Type.List): Type { return Type.Atom(list.value[0]) }) environment.values["@"] = Type.Function(fun(list: Type.List): Type { return list.value[0].assert<Type.Atom>().value }) environment.values["$"] = Type.Function(fun(list: Type.List): Type { val atom = list.value[0].assert<Type.Atom>() val lambda = list.value[1].assert<Type.Function>() val value = atom.value atom.value = lambda.body(Type.List(Vector(arrayOf(value).toList()))) return atom }) environment.values["sleep"] = Type.Function(fun(list: Type.List): Type { val duration = list.value[0].assert<Type.Number>().value Thread.sleep(duration.toLong()) return Type.Null() }) environment.values["list"] = Type.Function(fun(list: Type.List): Type { return list }) environment.values["do"] = Type.Function(fun(list: Type.List): Type { var result: Type = Type.Null() list.value.forEach { result = evaluate(it, environment) } return result }) environment.values["slurp"] = Type.Function(fun(list: Type.List): Type { val filename = list.value[0].assert<Type.String>().value return Type.String(java.io.File(filename).readText()) }) environment.values["eval"] = Type.Function(fun(list: Type.List): Type { val source = list.value[0].assert<Type.String>().value return eval(source, environment) }) environment.values["string"] = Type.Function(fun(list: Type.List): Type { val value = list.value[0] if (value is Type.String) { return value } else if (value is Type.Number) { return Type.String(value.value.toInt().toString()) } return value }) environment.values["length"] = Type.Function(fun(list: Type.List): Type { var result: Type = Type.Null() val value = list.value[0] if (value is Type.String) { result = Type.Number(value.value.length.toFloat()) } return result }) environment.values["server"] = Type.Function(fun(list: Type.List): Type { val port = list.value[0].assert<Type.Number>().value.toInt() val lambda = list.value[1].assert<Type.Function>() val server = Type.Server(port, lambda, environment) return server }) return environment } fun print(ast: Type) { println(ast) } fun evaluate(source: String, environment: Environment) { val ast = parseList(Peekable(tokenize(source))) evaluate(ast, environment) } fun main() { val environment = createStandardEnvironment() val readFile = "(let read-file (^ (name) (eval (+ (+ \"(do\" (slurp name)) \")\"))))" evaluate(readFile, environment) evaluate("(read-file \"core/core.silly\")", environment) while (true) { try { print(eval(read(), environment)) } catch (exception: Exception) { println(exception) } } }
0
Kotlin
0
0
2a55c8066d317cc27bb1bc0e360772b5107b95c1
14,888
silly
MIT License