path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/pose/composingclocks/feature/add/AddCitySecondaryScreen.kt
lotdrops
343,812,742
false
null
package com.pose.composingclocks.feature.add import androidx.compose.foundation.Image import androidx.compose.foundation.background 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.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.ImagePainter import coil.compose.rememberImagePainter import com.pose.composingclocks.R import com.pose.composingclocks.common.widgets.ScreenTitleWithBack import com.pose.composingclocks.common.widgets.SectionTitle import com.pose.composingclocks.core.scopednav.navigation.NoParams import com.pose.composingclocks.core.scopednav.navigation.ScreenDestination import com.pose.composingclocks.feature.add.widgets.NoPhotoView object AddCitySecondaryScreen : ScreenDestination<NoParams>(pathRoot = "addCitySecondaryScreen") @Composable fun AddCitySecondaryScreen(viewModel: AddCitySecondaryViewModel) { val description = viewModel.description.collectAsState() val url = viewModel.photoUrl.collectAsState() AddCityOptionalContent( description = description.value, onDescriptionChange = { viewModel.description.value = it }, url = url.value, onUrlChange = { viewModel.photoUrl.value = it }, onSave = { viewModel.onSaveClicked() }, onBack = { viewModel.onBack() }, ) } @Composable private fun AddCityOptionalContent( description: String, onDescriptionChange: (String) -> Unit, url: String, onUrlChange: (String) -> Unit, onSave: () -> Unit, onBack: () -> Unit, ) { Column( Modifier .fillMaxSize() .background(colorResource(R.color.very_light_blue)) .padding(vertical = 16.dp) ) { ScreenTitleWithBack( text = stringResource(R.string.add_screen_optional_data_title), onBack = onBack, ) Column( Modifier .fillMaxSize() .padding(horizontal = 16.dp) ) { TextField( value = description, onValueChange = onDescriptionChange, modifier = Modifier .fillMaxWidth() .weight(1f) .padding(vertical = 8.dp), label = { Text(text = stringResource(id = R.string.add_screen_description_hint)) }, ) SectionTitle( text = stringResource(R.string.add_screen_image_title), modifier = Modifier.padding(top = 16.dp, bottom = 8.dp), ) TextField( value = url, onValueChange = { onUrlChange(it) }, singleLine = true, modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp), label = { Text(text = stringResource(id = R.string.add_screen_image_url)) }, ) PhotoSelectedView( url, Modifier .weight(2f) .padding(vertical = 8.dp) ) Button( onClick = onSave, modifier = Modifier .padding(top = 24.dp, bottom = 8.dp) .align(Alignment.CenterHorizontally) ) { Text( text = stringResource(id = R.string.add_screen_save_button), modifier = Modifier.padding(vertical = 8.dp, horizontal = 32.dp), ) } } } } @Composable fun PhotoSelectedView(url: String, modifier: Modifier) { if (url.trim().isEmpty()) { NoPhotoView(modifier.padding(vertical = 8.dp)) } else { val painter = rememberImagePainter(url) Box { Image(painter = painter, contentDescription = null,) when (painter.state) { is ImagePainter.State.Loading -> { NoPhotoView(modifier, true) } is ImagePainter.State.Error -> { NoPhotoView(modifier, loading = false, isError = true) } } } } } @Preview @Composable fun AddCityOptionalContentPreview() { var description = "" var url = "" AddCityOptionalContent( description = description, onDescriptionChange = { description = it }, url = url, onUrlChange = { url = it }, {}, {}, ) }
0
null
2
86
fe79ad04d962401362d5693306349afbd1a93b42
5,005
Composing-Clocks
MIT License
src/main/java/org/bubenheimer/android/threading/MainThreadRunner.kt
bubenheimer
76,136,695
false
{"Kotlin": 21733}
/* * Copyright (c) 2015-2019 Uli Bubenheimer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.bubenheimer.android.threading import android.annotation.SuppressLint import android.os.Handler import android.os.Looper import android.os.Message private val MAIN_HANDLER = Handler(Looper.getMainLooper()) public fun isMainThread(): Boolean = Thread.currentThread() === MAIN_HANDLER.looper.thread public fun post(async: Boolean = true, runnable: () -> Unit) { if (Thread.currentThread() === MAIN_HANDLER.looper.thread) { runnable() } else { forcePost(async, runnable) } } @Suppress("unused") public fun postDelayed(delayMs: Long, async: Boolean = true, runnable: () -> Unit) { if (delayMs <= 0L && Thread.currentThread() === MAIN_HANDLER.looper.thread) { runnable() } else { forcePostDelayed(delayMs, async, runnable) } } public fun forcePost(async: Boolean = true, runnable: () -> Unit) { obtainMessage(async, runnable).sendToTarget() } public fun forcePostDelayed(delayMs: Long, async: Boolean = true, runnable: () -> Unit) { val msg = obtainMessage(async, runnable) msg.target.sendMessageDelayed(msg, delayMs) } @Suppress("unused") public fun postAtFrontOfQueue(async: Boolean = true, runnable: () -> Unit) { if (Thread.currentThread() === MAIN_HANDLER.looper.thread) { runnable() } else { forcePostAtFrontOfQueue(async, runnable) } } public fun forcePostAtFrontOfQueue(async: Boolean = true, runnable: () -> Unit) { val msg = obtainMessage(async, runnable) val result = msg.target.sendMessageAtFrontOfQueue(msg) check(result) } @SuppressLint("NewApi") private fun obtainMessage(async: Boolean, runnable: () -> Unit): Message { val msg = Message.obtain(MAIN_HANDLER, runnable) if (async) msg.isAsynchronous = true return msg }
0
Kotlin
0
0
8859ce8fb1e65afae1ab8819d1a6b4644375aa8d
2,384
androidutil
Apache License 2.0
module_home/src/main/java/com/czl/module_home/adapter/PopularCoursesAdapter.kt
pigletzzzzzz
516,985,475
false
{"Kotlin": 723880, "Java": 176802}
package com.czl.module_home.adapter import androidx.recyclerview.widget.DiffUtil import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder import com.czl.lib_base.config.AppConstants import com.czl.lib_base.data.bean.HomeDetailBean import com.czl.lib_base.extension.loadRoundImage import com.czl.lib_base.util.DensityUtils import com.czl.module_home.R import com.czl.module_home.databinding.AdapterCoursesItemBinding import com.czl.module_home.fragment.HomeFragment class PopularCoursesAdapter(val homeFragment: HomeFragment) : BaseQuickAdapter<HomeDetailBean.JpCourse, BaseDataBindingHolder<AdapterCoursesItemBinding>>( R.layout.adapter_courses_item ) { override fun convert( holder: BaseDataBindingHolder<AdapterCoursesItemBinding>, item: HomeDetailBean.JpCourse ) { holder.dataBinding?.apply { data = item adapter = this@PopularCoursesAdapter if (item.cover.isNotEmpty()) { imgKc.loadRoundImage(AppConstants.Url.IMG_UPLOAD_URL + item.cover, 16) } val layoutParams = clAllView.layoutParams layoutParams.width = ((DensityUtils.getWidthInPx(context) - DensityUtils.dip2px(context,41f))/2).toInt() clAllView.layoutParams = layoutParams } } val diffConfig = object : DiffUtil.ItemCallback<HomeDetailBean.JpCourse>() { override fun areItemsTheSame( oldItem: HomeDetailBean.JpCourse, newItem: HomeDetailBean.JpCourse ): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame( oldItem: HomeDetailBean.JpCourse, newItem: HomeDetailBean.JpCourse ): Boolean { return oldItem.title == newItem.title } } }
0
Kotlin
0
0
a3276c0149c7d2d3284a6a4d83fa5cb3874664e9
1,892
XPZX-New_Kotlin
Apache License 2.0
app/src/main/java/com/lianyi/paimonsnotebook/common/components/dialog/InputDialog.kt
QooLianyi
435,314,581
false
{"Kotlin": 1822660}
package com.lianyi.paimonsnotebook.common.components.dialog import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import com.lianyi.paimonsnotebook.common.components.widget.InputTextFiled @Composable fun InputDialog( title: String = "输入框", placeholder: String = "请输入内容", initialValue: String = "", onConfirm: (value: String) -> Unit, onCancel: () -> Unit, textMaxLength:Int = Int.MAX_VALUE ) { //输入值 var value by remember { mutableStateOf(initialValue) } LazyColumnDialog( title = title, onDismissRequest = onCancel, buttons = arrayOf("取消", "确定"), onClickButton = { if (it == 0) { onCancel.invoke() } else { onConfirm.invoke(value) } }, content = { item { InputTextFiled( value = value, onValueChange = { if(it.length < textMaxLength){ value = it } }, placeholder = placeholder, contentAlignment = Alignment.CenterStart ) } } ) }
1
Kotlin
2
35
accd1e82ed4ca6e209fbed1199069fd99655407f
1,390
PaimonsNotebook
MIT License
app/src/main/java/com/telen/easylineup/settings/SettingsViewModel.kt
kaygenzo
177,859,247
false
null
package com.telen.easylineup.settings import android.net.Uri import androidx.lifecycle.ViewModel import com.telen.easylineup.domain.application.ApplicationInteractor import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.subjects.PublishSubject import io.reactivex.rxjava3.subjects.Subject import org.koin.core.component.KoinComponent import org.koin.core.component.inject import timber.log.Timber import java.util.concurrent.TimeUnit sealed class Event object DeleteAllDataEventSuccess: Event() object DeleteAllDataEventFailure: Event() data class ExportDataEventSuccess(val pathDirectory: String): Event() object ExportDataEventFailure: Event() class SettingsViewModel: ViewModel(), KoinComponent { private val domain: ApplicationInteractor by inject() private val _event = PublishSubject.create<Event>() private val disposables = CompositeDisposable() fun clear() { disposables.clear() } fun deleteAllData() { val disposable = domain.data().deleteAllData() .andThen(Completable.timer(1000, TimeUnit.MILLISECONDS)) .subscribe({ _event.onNext(DeleteAllDataEventSuccess) }, { Timber.e(it) _event.onNext(DeleteAllDataEventFailure) }) disposables.add(disposable) } /** * @return The directory name where the file is exported */ fun exportData(dirUri: Uri) { val disposable = domain.data().exportData(dirUri) .subscribe({ _event.onNext(ExportDataEventSuccess(it)) }, { Timber.e(it) _event.onNext(ExportDataEventFailure) }) disposables.add(disposable) } fun observeEvent(): Subject<Event> { return _event } }
0
Kotlin
0
0
67bc24d99346cb1812857bafe4e4979d3a1ca1f5
1,929
EasyLineUp
Apache License 2.0
core/network/src/main/java/com/sonder/myweatherapp/network/di/LocalDataSourceModule.kt
rafa-hoffmann
595,871,372
false
null
package com.sonder.myweatherapp.network.di import com.sonder.myweatherapp.network.MwaLocalDataSource import com.sonder.myweatherapp.network.local.MwaLocalDataSourceImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface LocalDataSourceModule { @Binds fun MwaLocalDataSourceImpl.binds(): MwaLocalDataSource }
0
Kotlin
0
0
522c525dc1d68580bdb3a7439f0ec28acf46b0cb
442
myweatherapp
Apache License 2.0
mvilite-core/src/main/java/ru/ar2code/mvilite_core/MviLiteSavedStateHandleInitialFactory.kt
ar2code
431,801,504
false
null
package ru.ar2code.mvilite_core import androidx.lifecycle.SavedStateHandle /** * Factory that has access to ViewModel's [SavedStateHandle]. * You can restore view model and create appropriate initial state. */ abstract class MviLiteSavedStateHandleInitialFactory<S>(private val savedStateHandle: SavedStateHandle) : MviLiteInitialStateFactory<S> { /** * Get initial state from [savedStateHandle] */ abstract fun getInitialState(savedStateHandle: SavedStateHandle): S /** * Load initial state from [savedStateHandle] with coroutine */ open suspend fun loadState(savedStateHandle: SavedStateHandle): S? { return null } final override suspend fun loadState(): S? { return loadState(savedStateHandle) } final override fun getInitialState(): S { return getInitialState(savedStateHandle) } }
0
Kotlin
0
0
34adcb564b4776e3997d7aff44e3fa15765ae56b
878
mvilite-android
MIT License
app/src/main/java/dev/mcd/untitledcaloriesapp/di/AppModule.kt
jlmcdonnell
339,825,242
false
null
package dev.mcd.untitledcaloriesapp.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dev.mcd.untitledcaloriesapp.data.env.Environment import dev.mcd.untitledcaloriesapp.data.env.Production @Module @InstallIn(SingletonComponent::class) class AppModule { @Provides fun environment(): Environment = Production() }
0
Kotlin
0
1
e28015812e23c7d1d7ca38207fdeae7179231bdc
405
calories-app
The Unlicense
projects/tier-to-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/integrations/delius/nsi/entity/Nsi.kt
ministryofjustice
500,855,647
false
null
package uk.gov.justice.digital.hmpps.integrations.delius.nsi.entity import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.Id import jakarta.persistence.JoinColumn import jakarta.persistence.ManyToOne import jakarta.persistence.Table import org.hibernate.annotations.Immutable import org.hibernate.annotations.Where import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query import uk.gov.justice.digital.hmpps.integrations.delius.nsi.EnforcementActivityCode import uk.gov.justice.digital.hmpps.integrations.delius.referencedata.ReferenceData import java.time.LocalDate @Entity @Immutable @Table(name = "nsi") @Where(clause = "soft_deleted = 0") class Nsi( @Id @Column(name = "nsi_id") val id: Long, @Column(name = "offender_id") val personId: Long, @ManyToOne @JoinColumn(name = "event_id") val event: NsiEvent?, val referralDate: LocalDate, @ManyToOne @JoinColumn(name = "nsi_outcome_id") val outcome: ReferenceData?, @Column(columnDefinition = "number") val softDeleted: Boolean ) @Immutable @Entity @Table(name = "event") @Where(clause = "soft_deleted = 0") class NsiEvent( @Id @Column(name = "event_id") val id: Long, @Column(columnDefinition = "number") val softDeleted: Boolean ) interface NsiRepository : JpaRepository<Nsi, Long> { @Query( """ select count(nsi) from Nsi nsi join nsi.event e where nsi.personId = :personId and nsi.referralDate >= :referralDate and nsi.outcome.code in :outcomes """ ) fun countByPersonIdAndOutcomeIn(personId: Long, referralDate: LocalDate, outcomes: List<String>): Int } fun NsiRepository.previousEnforcementActivity(personId: Long): Boolean = countByPersonIdAndOutcomeIn(personId, LocalDate.now().minusDays(365), EnforcementActivityCode.stringValues) > 0
4
Kotlin
0
2
404fca1520f49953b96a792d266ee3d3d12ee73a
1,958
hmpps-probation-integration-services
MIT License
app/src/main/java/com/plcoding/cryptocurrencyappyt/presentation/use_case/get_coins_list/GetCoinsListUseCases.kt
carlospadilha007
648,836,975
false
null
package com.plcoding.cryptocurrencyappyt.presentation.use_case.get_coins_list import com.plcoding.cryptocurrencyappyt.common.Resource import com.plcoding.cryptocurrencyappyt.data.remote.dto.toCoin import com.plcoding.cryptocurrencyappyt.data.repository.CoinRepositoryImpl import com.plcoding.cryptocurrencyappyt.domain.model.Coin import com.plcoding.cryptocurrencyappyt.domain.repository.CoinRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import retrofit2.HttpException import java.io.IOException import javax.inject.Inject class GetCoinsListUseCases @Inject constructor( private val repository: CoinRepository ) { // Invoke permite chamer a classe como se fosse uma função // Flow serve para emitir multiplos valores ao longo do tempo // Resource é util para retorna o erro ou sucesso da requisição // Caso hajá dados como retorno, ele retorna uma lista de coins operator fun invoke(): Flow<Resource<List<Coin>>> = flow { try { emit(Resource.Loading<List<Coin>>()) // vai ser usado na barra de progresso val coins = repository.getCoins().map { it.toCoin() } emit(Resource.Success<List<Coin>>(coins)) } catch(e: HttpException) { emit(Resource.Error<List<Coin>>(e.localizedMessage ?: "Um erro inesperado aconteceu")) } catch(e: IOException) { emit(Resource.Error<List<Coin>>("Não foi possivel conectar-se ao servidor. Verifique a sua conexão de internet!!")) } } }
0
Kotlin
0
0
0b203a560d1a97315296331d716b5dce14a671ea
1,522
CryptoMoedas-MVVM-JetPack
Apache License 2.0
app/src/main/java/com/felipe/androidportfolio/fragment/PortfolioListFragment.kt
felipemvitor
223,221,762
false
null
package com.felipe.androidportfolio.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.felipe.androidportfolio.R import com.felipe.androidportfolio.adapter.PortfolioListAdapter import com.felipe.androidportfolio.listener.OnListItemClickListener import kotlinx.android.synthetic.main.fragment_portfolio_list.* /** * A simple [Fragment] subclass. */ class PortfolioListFragment : Fragment(), OnListItemClickListener { private lateinit var mAdapter: PortfolioListAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_portfolio_list, container, false) } override fun onResume() { super.onResume() mAdapter = PortfolioListAdapter(context!!, this) elvPortfolio.setAdapter(mAdapter) elvPortfolio.setGroupIndicator(null) } override fun onItemClick(action: Int) { findNavController().navigate(action) } }
0
Kotlin
0
0
f42ad738f8758b9dad816d4bec0607600fc45db2
1,238
android-portfolio
MIT License
jetbrains-ultimate/src-202+/software/aws/toolkits/jetbrains/datagrip/DatagripCompatabilityUtils.kt
kolaamoo
310,663,671
true
{"Kotlin": 2987126, "C#": 94789, "Java": 18989}
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.datagrip import com.intellij.database.Dbms import com.intellij.database.dataSource.DatabaseConnectionInterceptor.ProtoConnection import com.intellij.database.dataSource.LocalDataSource import software.aws.toolkits.resources.message // FIX_WHEN_MIN_IS_202 merge this one and the 202+ version together into secretsManagerAuth, 201 is missing Aurora MySQL fun secretsManagerIsApplicable(dataSource: LocalDataSource): Boolean { val dbms = dataSource.dbms return dbms == Dbms.MYSQL || dbms == Dbms.POSTGRES || dbms == Dbms.REDSHIFT || dbms == Dbms.MYSQL_AURORA } // FIX_WHEN_MIN_IS_202 merge this one and the 202+ version together into iamAuth, 201 is missing Aurora MySQL fun iamIsApplicable(dataSource: LocalDataSource): Boolean = dataSource.dbms == Dbms.MYSQL || dataSource.dbms == Dbms.POSTGRES || dataSource.dbms == Dbms.MYSQL_AURORA // FIX_WHEN_MIN_IS_202 merge this one and the 202+ version together into IamAuth, 201 is missing Aurora MySQL fun validateIamConfiguration(connection: ProtoConnection) { // MariaDB/Mysql aurora will never work if SSL is turned off, so validate and give // a good message if it is not enabled if ( connection.connectionPoint.dataSource.dbms == Dbms.MYSQL_AURORA && connection.connectionPoint.dataSource.sslCfg == null ) { throw IllegalArgumentException(message("rds.validation.aurora_mysql_ssl_required")) } }
0
null
0
0
06b8a7b47f30718043bbd9adc3885fe279b1169f
1,558
aws-toolkit-jetbrains
Apache License 2.0
app/src/main/java/com/pg/cloudcleaner/helper/Syncer.kt
prateekgupta22195
556,909,764
false
{"Kotlin": 100649, "Java": 60}
package com.pg.cloudcleaner.helper import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import android.os.Environment import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.work.CoroutineWorker import androidx.work.ForegroundInfo import androidx.work.WorkerParameters import com.pg.cloudcleaner.R import com.pg.cloudcleaner.app.App import com.pg.cloudcleaner.data.repository.LocalFilesRepoImpl import com.pg.cloudcleaner.domain.interactors.FileUseCases import kotlinx.coroutines.* import timber.log.Timber class ReadFileWorker(context: Context, workerParameters: WorkerParameters) : CoroutineWorker(context, workerParameters), WorkerNotification { companion object { private const val NOTIFICATION_CHANNEL_ID = "11" private const val NOTIFICATION_CHANNEL_NAME = "Work Service" } override suspend fun doWork(): Result { val startTime = System.currentTimeMillis() val fileUseCases = FileUseCases(LocalFilesRepoImpl(App.instance.db.localFilesDao())) fileUseCases.syncAllFilesToDb(Environment.getExternalStorageDirectory().absolutePath) Timber.d("Time for filling DB ${System.currentTimeMillis() - startTime}") return Result.success() } override suspend fun getForegroundInfo(): ForegroundInfo { return ForegroundInfo( System.currentTimeMillis().toInt(), setForegroundNotification() ) } @RequiresApi(Build.VERSION_CODES.O) override fun createChannel() { val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val channel = NotificationChannel( NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH ) notificationManager.createNotificationChannel(channel) } override fun getNotification(): Notification { return NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL_ID) .setSmallIcon(R.mipmap.ic_launcher).setOngoing(true).setAutoCancel(true) .setProgress(100, 0, true).setPriority(NotificationCompat.PRIORITY_MIN) .setContentTitle(applicationContext.getString(R.string.app_name)).setLocalOnly(true) .setVisibility(NotificationCompat.VISIBILITY_SECRET).setContentText("Scanning Files") .build() } override fun setForegroundNotification(): Notification { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createChannel() } return getNotification() } }
1
Kotlin
0
2
e7b24119ae94d6518b7a3b3f7d04b444773427dc
2,729
free-memory-android
MIT License
compose/material3/material3-adaptive/src/androidInstrumentedTest/kotlin/androidx/compose/material3/adaptive/ListDetailPaneScaffoldNavigatorTest.kt
androidx
256,589,781
false
{"Kotlin": 95878258, "Java": 67276414, "C++": 9121933, "AIDL": 629410, "Python": 308602, "Shell": 191832, "TypeScript": 40586, "HTML": 26377, "Svelte": 20307, "ANTLR": 19860, "C": 16935, "CMake": 14401, "Groovy": 13532, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3.adaptive import androidx.compose.foundation.layout.PaddingValues import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.google.common.truth.Truth.assertThat import kotlin.properties.Delegates import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalMaterial3AdaptiveApi::class) @SmallTest @RunWith(AndroidJUnit4::class) class ListDetailPaneScaffoldNavigatorTest { @get:Rule val composeRule = createComposeRule() @Test fun singlePaneLayout_navigateTo_makeDestinationPaneExpanded() { lateinit var scaffoldNavigator: ThreePaneScaffoldNavigator var canNavigateBack by Delegates.notNull<Boolean>() composeRule.setContent { scaffoldNavigator = rememberListDetailPaneScaffoldNavigator( scaffoldDirective = MockSinglePaneScaffoldDirective ) canNavigateBack = scaffoldNavigator.canNavigateBack() } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.Detail] ).isEqualTo(PaneAdaptedValue.Hidden) scaffoldNavigator.navigateTo(ListDetailPaneScaffoldRole.Detail) } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.Detail] ).isEqualTo(PaneAdaptedValue.Expanded) assertThat(canNavigateBack).isTrue() } } @Test fun dualPaneLayout_navigateTo_keepDestinationPaneExpanded() { lateinit var scaffoldNavigator: ThreePaneScaffoldNavigator var canNavigateBack by Delegates.notNull<Boolean>() composeRule.setContent { scaffoldNavigator = rememberListDetailPaneScaffoldNavigator( scaffoldDirective = MockDualPaneScaffoldDirective ) canNavigateBack = scaffoldNavigator.canNavigateBack() } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.Detail] ).isEqualTo(PaneAdaptedValue.Expanded) scaffoldNavigator.navigateTo(ListDetailPaneScaffoldRole.Detail) } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.Detail] ).isEqualTo(PaneAdaptedValue.Expanded) assertThat(canNavigateBack).isFalse() } } @Test fun dualPaneLayout_navigateToExtra_hideListWhenNotHistoryAware() { lateinit var scaffoldNavigator: ThreePaneScaffoldNavigator var canNavigateBack by Delegates.notNull<Boolean>() composeRule.setContent { scaffoldNavigator = rememberListDetailPaneScaffoldNavigator( scaffoldDirective = MockDualPaneScaffoldDirective, isDestinationHistoryAware = false ) canNavigateBack = scaffoldNavigator.canNavigateBack() } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.List] ).isEqualTo(PaneAdaptedValue.Expanded) scaffoldNavigator.navigateTo(ListDetailPaneScaffoldRole.Extra) } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.List] ).isEqualTo(PaneAdaptedValue.Hidden) assertThat(canNavigateBack).isTrue() } } @Test fun dualPaneLayout_navigateToExtra_keepListExpandedWhenHistoryAware() { lateinit var scaffoldNavigator: ThreePaneScaffoldNavigator var canNavigateBack by Delegates.notNull<Boolean>() composeRule.setContent { scaffoldNavigator = rememberListDetailPaneScaffoldNavigator( scaffoldDirective = MockDualPaneScaffoldDirective, isDestinationHistoryAware = true ) canNavigateBack = scaffoldNavigator.canNavigateBack() } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.List] ).isEqualTo(PaneAdaptedValue.Expanded) scaffoldNavigator.navigateTo(ListDetailPaneScaffoldRole.Extra) } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.List] ).isEqualTo(PaneAdaptedValue.Expanded) assertThat(canNavigateBack).isTrue() } } @Test fun singlePaneLayout_navigateBack_makeDestinationPaneHidden() { lateinit var scaffoldNavigator: ThreePaneScaffoldNavigator var canNavigateBack by Delegates.notNull<Boolean>() composeRule.setContent { scaffoldNavigator = rememberListDetailPaneScaffoldNavigator( scaffoldDirective = MockSinglePaneScaffoldDirective ) canNavigateBack = scaffoldNavigator.canNavigateBack() } composeRule.runOnIdle { scaffoldNavigator.navigateTo(ListDetailPaneScaffoldRole.Detail) } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.Detail] ).isEqualTo(PaneAdaptedValue.Expanded) assertThat(canNavigateBack).isTrue() scaffoldNavigator.navigateBack() } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.Detail] ).isEqualTo(PaneAdaptedValue.Hidden) assertThat(canNavigateBack).isFalse() } } @Test fun dualPaneLayout_enforceScaffoldValueChange_cannotNavigateBack() { lateinit var scaffoldNavigator: ThreePaneScaffoldNavigator composeRule.setContent { scaffoldNavigator = rememberListDetailPaneScaffoldNavigator( scaffoldDirective = MockDualPaneScaffoldDirective, initialDestinationHistory = listOf( ListDetailPaneScaffoldRole.List, ListDetailPaneScaffoldRole.Detail, ) ) } composeRule.runOnIdle { assertThat(scaffoldNavigator.canNavigateBack()).isFalse() } } @Test fun dualPaneLayout_notEnforceScaffoldValueChange_canNavigateBack() { lateinit var scaffoldNavigator: ThreePaneScaffoldNavigator composeRule.setContent { scaffoldNavigator = rememberListDetailPaneScaffoldNavigator( scaffoldDirective = MockDualPaneScaffoldDirective, initialDestinationHistory = listOf( ListDetailPaneScaffoldRole.List, ListDetailPaneScaffoldRole.Detail, ) ) } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.Detail] ).isEqualTo(PaneAdaptedValue.Expanded) assertThat(scaffoldNavigator.canNavigateBack(false)).isTrue() scaffoldNavigator.navigateBack(false) } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.Detail] ).isEqualTo(PaneAdaptedValue.Expanded) } } @Test fun dualPaneLayout_enforceScaffoldChangeWhenHistoryAware_notSkipBackstackEntry() { lateinit var scaffoldNavigator: ThreePaneScaffoldNavigator composeRule.setContent { scaffoldNavigator = rememberListDetailPaneScaffoldNavigator( scaffoldDirective = MockDualPaneScaffoldDirective, initialDestinationHistory = listOf( ListDetailPaneScaffoldRole.Extra, ListDetailPaneScaffoldRole.List, ), isDestinationHistoryAware = true ) } composeRule.runOnIdle { scaffoldNavigator.scaffoldState.scaffoldValue.assert( PaneAdaptedValue.Hidden, PaneAdaptedValue.Expanded, PaneAdaptedValue.Expanded ) scaffoldNavigator.navigateTo(ListDetailPaneScaffoldRole.Detail) } composeRule.runOnIdle { scaffoldNavigator.scaffoldState.scaffoldValue.assert( PaneAdaptedValue.Expanded, PaneAdaptedValue.Expanded, PaneAdaptedValue.Hidden ) scaffoldNavigator.navigateBack() } composeRule.runOnIdle { scaffoldNavigator.scaffoldState.scaffoldValue.assert( PaneAdaptedValue.Hidden, PaneAdaptedValue.Expanded, PaneAdaptedValue.Expanded ) } } @Test fun dualPaneLayout_enforceScaffoldChangeWhenNotHistoryAware_skipBackstackEntry() { lateinit var scaffoldNavigator: ThreePaneScaffoldNavigator composeRule.setContent { scaffoldNavigator = rememberListDetailPaneScaffoldNavigator( scaffoldDirective = MockDualPaneScaffoldDirective, initialDestinationHistory = listOf( ListDetailPaneScaffoldRole.Extra, ListDetailPaneScaffoldRole.List, ), isDestinationHistoryAware = false ) } composeRule.runOnIdle { scaffoldNavigator.scaffoldState.scaffoldValue.assert( PaneAdaptedValue.Expanded, PaneAdaptedValue.Expanded, PaneAdaptedValue.Hidden ) scaffoldNavigator.navigateTo(ListDetailPaneScaffoldRole.Detail) } composeRule.runOnIdle { scaffoldNavigator.scaffoldState.scaffoldValue.assert( PaneAdaptedValue.Expanded, PaneAdaptedValue.Expanded, PaneAdaptedValue.Hidden ) scaffoldNavigator.navigateBack() } composeRule.runOnIdle { scaffoldNavigator.scaffoldState.scaffoldValue.assert( PaneAdaptedValue.Expanded, PaneAdaptedValue.Hidden, PaneAdaptedValue.Expanded ) } } @Test fun singlePaneToDualPaneLayout_enforceScaffoldValueChange_cannotNavigateBack() { lateinit var scaffoldNavigator: ThreePaneScaffoldNavigator val mockCurrentScaffoldDirective = mutableStateOf(MockSinglePaneScaffoldDirective) composeRule.setContent { scaffoldNavigator = rememberListDetailPaneScaffoldNavigator( scaffoldDirective = mockCurrentScaffoldDirective.value, initialDestinationHistory = listOf( ListDetailPaneScaffoldRole.List, ListDetailPaneScaffoldRole.Detail, ) ) } composeRule.runOnIdle { assertThat( scaffoldNavigator.scaffoldState.scaffoldValue[ListDetailPaneScaffoldRole.Detail] ).isEqualTo(PaneAdaptedValue.Expanded) // Switches to dual pane mockCurrentScaffoldDirective.value = MockDualPaneScaffoldDirective } composeRule.runOnIdle { assertThat(scaffoldNavigator.canNavigateBack()).isFalse() } } } @OptIn(ExperimentalMaterial3AdaptiveApi::class) private val MockSinglePaneScaffoldDirective = PaneScaffoldDirective( contentPadding = PaddingValues(0.dp), maxHorizontalPartitions = 1, horizontalPartitionSpacerSize = 0.dp, maxVerticalPartitions = 1, verticalPartitionSpacerSize = 0.dp, excludedBounds = emptyList() ) @OptIn(ExperimentalMaterial3AdaptiveApi::class) private val MockDualPaneScaffoldDirective = PaneScaffoldDirective( contentPadding = PaddingValues(16.dp), maxHorizontalPartitions = 2, horizontalPartitionSpacerSize = 16.dp, maxVerticalPartitions = 1, verticalPartitionSpacerSize = 0.dp, excludedBounds = emptyList() ) @OptIn(ExperimentalMaterial3AdaptiveApi::class) private fun ThreePaneScaffoldValue.assert( expectedDetailPaneAdaptedValue: PaneAdaptedValue, expectedListPaneAdaptedValue: PaneAdaptedValue, expectedExtraPaneAdaptedValue: PaneAdaptedValue ) { assertThat(this[ListDetailPaneScaffoldRole.Detail]).isEqualTo(expectedDetailPaneAdaptedValue) assertThat(this[ListDetailPaneScaffoldRole.List]).isEqualTo(expectedListPaneAdaptedValue) assertThat(this[ListDetailPaneScaffoldRole.Extra]).isEqualTo(expectedExtraPaneAdaptedValue) }
27
Kotlin
901
4,898
e7c7c42655aba3f04cb7672f2eb02744bd24ce7f
13,660
androidx
Apache License 2.0
decompose/src/commonMain/kotlin/com/arkivanov/decompose/router/panels/ChildPanelsMode.kt
arkivanov
437,015,897
false
{"Kotlin": 700677}
package com.arkivanov.decompose.router.panels import com.arkivanov.decompose.ExperimentalDecomposeApi /** * Determines how lifecycles of the child components within the Child Panels navigation model are changing. * * @see com.arkivanov.essenty.lifecycle.Lifecycle.State */ @ExperimentalDecomposeApi enum class ChildPanelsMode { /** * There is only one `RESUMED` panel at a time. * If the Extra panel exists, then it is `RESUMED` and all other panels are `CREATED`. * Otherwise, if the Details panel exists, then it is `RESUMED` and the Main panel is `CREATED`. * Otherwise, the Main panel is `RESUMED`. */ SINGLE, /** * There are at most two panels `RESUMED` at a time. The Main panel is always `RESUMED`. * If the Extra panel exists, then it is `RESUMED` and the Details panel (if exists) is `CREATED`. * Otherwise, if the Details panel exists, then it is `RESUMED`. */ DUAL, /** * Any existing panel is always `RESUMED`. */ TRIPLE, } val ChildPanelsMode.isSingle: Boolean get() = this == ChildPanelsMode.SINGLE val ChildPanelsMode.isDual: Boolean get() = this == ChildPanelsMode.DUAL val ChildPanelsMode.isTriple: Boolean get() = this == ChildPanelsMode.TRIPLE
2
Kotlin
84
2,207
8af551e8895951a5082a5d2750335713d673f80b
1,254
Decompose
Apache License 2.0
kts/src/main/kotlin/detaching/jobsCommand.sh.kts
jakubriegel
201,905,455
false
null
#!/usr/bin/env kshell package detaching val echo = "echo hello".process() shell { detach(echo.copy(), echo.copy(), echo.copy()) detach { echo.copy() pipe "cat".process() } // call the command jobs() // [1] [[SystemProcess 1] PID echo] // [2] [[SystemProcess 2] PID echo] // [3] [[SystemProcess 3] PID echo] // [4] [Pipeline ID] // pipe the command pipeline { jobs pipe "grep Pipeline".process() } // [4] [Pipeline ID] }
0
Kotlin
1
1
569a0e2f32bc0d0fe6121ebf75801d714dc83d1a
469
kotlin-shell-examples
Apache License 2.0
panna-shared/src/main/kotlin/com/mgtriffid/games/panna/shared/game/components/SolidTerrainComponent.kt
mgtriffid
524,701,185
false
{"Kotlin": 478306, "Java": 9323}
package com.mgtriffid.games.panna.shared.game.components import com.mgtriffid.games.cotta.core.entities.Component @com.mgtriffid.games.cotta.core.annotations.Component interface SolidTerrainComponent : Component<SolidTerrainComponent>
2
Kotlin
0
6
ee0bd897c67451b31f68a3a31a6ee8de756b2b52
237
cotta
MIT License
src/main/kotlin/internals/instructions/bitwise/and.kt
ChippyPlus
850,474,357
false
{"Kotlin": 113521, "Python": 2374, "F#": 446, "Java": 228, "Shell": 148}
package internals.instructions.bitwise import data.registers.RegisterType import data.registers.RegisterType.R3 import errors import registers /** * Performs a bitwise AND operation on the values in two registers and stores the result in the `R3` register. * * @param operand1 The [RegisterType] holding the first operand. * @param operand2 The [RegisterType] holding the second operand. * @throws GeneralBitwiseException If an error occurs during the bitwise AND operation. */ fun Bitwise.and(operand1: RegisterType, operand2: RegisterType): Unit = try { registers.write( R3, value = registers.read(operand1) and registers.read(operand2) ) } catch (_: Exception) { errors.run { [email protected](message = "add") } }
0
Kotlin
0
1
8f564320fbe226a0a1f8f6aca56b67c411f5cd68
750
MVM
MIT License
feature-wallet-impl/src/main/java/jp/co/soramitsu/wallet/impl/data/network/subquery/OperationsHistoryApi.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.wallet.impl.data.network.subquery import jp.co.soramitsu.common.data.network.subquery.GiantsquidResponse import jp.co.soramitsu.common.data.network.subquery.SubQueryResponse import jp.co.soramitsu.common.data.network.subquery.SubsquidResponse import jp.co.soramitsu.wallet.impl.data.network.model.request.GiantsquidHistoryRequest import jp.co.soramitsu.wallet.impl.data.network.model.request.SubqueryHistoryRequest import jp.co.soramitsu.wallet.impl.data.network.model.request.SubsquidHistoryRequest import jp.co.soramitsu.wallet.impl.data.network.model.response.GiantsquidHistoryResponse import jp.co.soramitsu.wallet.impl.data.network.model.response.SubqueryHistoryElementResponse import jp.co.soramitsu.wallet.impl.data.network.model.response.SubsquidHistoryResponse import retrofit2.http.Body import retrofit2.http.POST import retrofit2.http.Url interface OperationsHistoryApi { @POST suspend fun getOperationsHistory( @Url url: String, @Body body: SubqueryHistoryRequest ): SubQueryResponse<SubqueryHistoryElementResponse> @POST suspend fun getSubsquidOperationsHistory( @Url url: String, @Body body: SubsquidHistoryRequest ): SubsquidResponse<SubsquidHistoryResponse> @POST suspend fun getGiantsquidOperationsHistory( @Url url: String, @Body body: GiantsquidHistoryRequest ): GiantsquidResponse<GiantsquidHistoryResponse> }
9
Kotlin
22
72
cddd39bac421b4be47cbd5f3ad02bd36c704f915
1,443
fearless-Android
Apache License 2.0
app/src/main/java/com/example/api_fetcher/di/NetworkModule.kt
abdbashar
733,064,716
false
{"Kotlin": 23589}
package com.example.api_fetcher.di import android.content.Context import android.net.ConnectivityManager import com.example.api_fetcher.data.connectivity.ConnectivityCheckerImpl import com.example.api_fetcher.data.remote.service.StoreApiService import com.example.api_fetcher.data.connectivity.ConnectivityChecker import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { private const val BASE_URL = "https://fakestoreapi.com" @Singleton @Provides fun provideStoreApiService( retrofit: Retrofit, ): StoreApiService { return retrofit.create(StoreApiService::class.java) } @Singleton @Provides fun provideOkHttpClient(): OkHttpClient { val builder = OkHttpClient() .newBuilder() .callTimeout(1, TimeUnit.MINUTES) .connectTimeout(1, TimeUnit.MINUTES) return builder.build() } @Singleton @Provides fun provideGsonConverterFactory(): GsonConverterFactory { return GsonConverterFactory.create() } @Singleton @Provides fun provideRetrofit( okHttpClient: OkHttpClient, gsonConverterFactory: GsonConverterFactory ): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(gsonConverterFactory) .build() } @Singleton @Provides fun provideConnectivityChecker(@ApplicationContext context: Context): ConnectivityChecker { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return ConnectivityCheckerImpl(connectivityManager) } }
0
Kotlin
0
0
dfefe2a64d00293ab7f02d58c401da959108db07
2,053
api_fetcher
MIT License
example/android/app/src/main/kotlin/io/ecosed/kit/MainApp.kt
libecosed
741,032,508
false
{"Kotlin": 43335, "Dart": 17780, "CMake": 1830, "AIDL": 669, "C++": 161}
package io.ecosed.kit import io.flutter.app.FlutterApplication class MainApp : FlutterApplication()
0
Kotlin
0
1
7461479aadd7c13ade82b17929689f30bd443d09
101
ecosed_kit
Apache License 2.0
http-shared/src/commonTest/kotlin/Config.kt
CLOVIS-AI
693,330,798
false
{"Kotlin": 21691, "Dockerfile": 979}
package opensavvy.notes.http import io.ktor.client.* import io.ktor.serialization.kotlinx.json.* import io.ktor.server.application.* import io.ktor.client.plugins.contentnegotiation.ContentNegotiation.Plugin as ClientContentNegotiation import io.ktor.server.plugins.contentnegotiation.ContentNegotiation as ServerContentNegotiation fun Application.configureTest() { install(ServerContentNegotiation) { json() } } fun HttpClientConfig<*>.configureTest() { install(ClientContentNegotiation) { json() } }
0
Kotlin
0
0
a00c93ce765dd0ddf6b92a6a82759a5883ff86b6
513
Notes-Kotlin-Fullstack
Apache License 2.0
backend/src/main/kotlin/com/project/smonkey/global/exception/error/InvalidMethodArgumentException.kt
hackersground-kr
656,532,644
false
null
package com.project.smonkey.global.exception.error import com.project.smonkey.global.exception.GlobalException object InvalidMethodArgumentException : GlobalException(GlobalExceptionErrorCode.INVALID_METHOD_ARGUMENT) { val EXCEPTION = InvalidMethodArgumentException }
0
Kotlin
3
3
6782fb89e747b4b3f7cd8170d480597bb1b99c30
274
smonkey
MIT License
app/src/main/kotlin/com/sergeylappo/booxrapiddraw/OverlayShowingService.kt
sergeylappo
868,643,131
false
{"Kotlin": 15856}
package com.sergeylappo.booxrapiddraw import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE import android.graphics.Color import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.Rect import android.graphics.RectF import android.view.Gravity import android.view.MotionEvent import android.view.SurfaceView import android.view.View import android.view.View.OnLayoutChangeListener import android.view.WindowManager import android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE import android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE import android.view.WindowManager.LayoutParams.MATCH_PARENT import android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY import android.widget.Toast import androidx.core.app.NotificationCompat import androidx.core.app.ServiceCompat import com.onyx.android.sdk.api.device.epd.EpdController import com.onyx.android.sdk.data.note.TouchPoint import com.onyx.android.sdk.pen.RawInputCallback import com.onyx.android.sdk.pen.TouchHelper import com.onyx.android.sdk.pen.data.TouchPointList import com.sergeylappo.booxrapiddraw.PreferenceKey.IS_RUNNING private const val CHANNEL_ID = "rapid_draw_channel_overlay_01" private const val STROKE_WIDTH = 3.0f // TODO need to detect pen-up event to increase responsiveness, so that can start raw drawing while reading that pen is near // Or would require schedule or timer to clean-up after retrieving a pen-down event class OverlayShowingService : Service() { private val paint = Paint() private lateinit var touchHelper: TouchHelper private lateinit var wm: WindowManager private lateinit var overlayPaintingView: SurfaceView @Volatile private var enabledLiveWriting: Boolean = false override fun onBind(intent: Intent) = null override fun onCreate() { super.onCreate() createForegroundNotification() wm = getSystemService(WINDOW_SERVICE) as WindowManager createOverlayPaintingView() initPaint() initSurfaceView() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent?.action == "STOP") { Toast.makeText(this, "Terminating Rapid Draw Service...", Toast.LENGTH_SHORT).show() stopSelf() return START_NOT_STICKY // Prevents service from being recreated } // Set the flag to indicate that the service is now running val prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE) prefs.edit().putBoolean(IS_RUNNING.key, true).apply() Toast.makeText(this, "Starting Rapid Draw Service", Toast.LENGTH_SHORT).show() return START_STICKY // Service will be recreated if killed } private fun createForegroundNotification() { val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel( NotificationChannel( CHANNEL_ID, "Boox Rapid draw overlay service", NotificationManager.IMPORTANCE_HIGH ) ) // add notification intent to finish the service val pendingIntent = PendingIntent.getService( this, 0, Intent(this, OverlayShowingService::class.java).apply { action = "STOP" }, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) val notification = NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle(getString(R.string.overlay_service_notification_content_title)) .setContentText(getString(R.string.overlay_service_notification_content)) .setSmallIcon(R.drawable.rapid_draw) .addAction(NotificationCompat.Action.Builder(null, "Stop", pendingIntent).build()) .build() //noinspection InlinedApi (Seems to work, IDK why, maybe older Android versions might not support this) ServiceCompat.startForeground(this, 1, notification, FOREGROUND_SERVICE_TYPE_SPECIAL_USE) } private fun createOverlayPaintingView() { overlayPaintingView = SurfaceView(this) overlayPaintingView.setZOrderOnTop(true) overlayPaintingView.holder.setFormat(PixelFormat.TRANSPARENT) overlayPaintingView.alpha = 1.0f val topLeftParams = WindowManager.LayoutParams( MATCH_PARENT, MATCH_PARENT, TYPE_APPLICATION_OVERLAY, FLAG_NOT_FOCUSABLE or FLAG_NOT_TOUCHABLE, PixelFormat.TRANSPARENT ) topLeftParams.alpha = 0.2f topLeftParams.gravity = Gravity.START or Gravity.TOP // TODO this is duplicated // TODO actual bottom place is calculated incorrectly due to the status bar... val displayMetrics = resources.displayMetrics val bounds = Rect(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels) topLeftParams.x = bounds.left topLeftParams.y = bounds.top wm.addView(overlayPaintingView, topLeftParams) } private fun initPaint() { paint.isAntiAlias = true paint.style = Paint.Style.STROKE paint.color = Color.BLACK paint.strokeWidth = STROKE_WIDTH } // TODO fix suppress @SuppressLint("ClickableViewAccessibility") private fun initSurfaceView() { touchHelper = TouchHelper.create(overlayPaintingView, 2, callback) overlayPaintingView.addOnLayoutChangeListener(object : OnLayoutChangeListener { override fun onLayoutChange( v: View, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int ) { val bounds = Rect(0, 0, right, bottom) overlayPaintingView.getLocalVisibleRect(bounds) touchHelper.setStrokeColor(Color.BLACK) touchHelper.setStrokeStyle(TouchHelper.STROKE_STYLE_PENCIL) touchHelper.openRawDrawing() touchHelper.setStrokeWidth(STROKE_WIDTH).setLimitRect(bounds, listOf()) touchHelper.setRawInputReaderEnable(!touchHelper.isRawDrawingInputEnabled) overlayPaintingView.addOnLayoutChangeListener(this) } }) overlayPaintingView.setOnTouchListener { _: View?, _: MotionEvent? -> true } } override fun onDestroy() { super.onDestroy() wm.removeViewImmediate(overlayPaintingView) touchHelper.closeRawDrawing() // Reset the flag when the service is destroyed val prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE) prefs.edit().putBoolean(IS_RUNNING.key, false).apply() } private val callback: RawInputCallback = object : RawInputCallback() { override fun onBeginRawDrawing(b: Boolean, touchPoint: TouchPoint?) { if (!enabledLiveWriting) { touchHelper.isRawDrawingRenderEnabled = true enabledLiveWriting = true disableFingerTouch(applicationContext) } } override fun onEndRawDrawing(b: Boolean, touchPoint: TouchPoint?) { enableFingerTouch(applicationContext) } override fun onRawDrawingTouchPointMoveReceived(touchPoint: TouchPoint?) {} override fun onRawDrawingTouchPointListReceived(touchPointList: TouchPointList) {} override fun onBeginRawErasing(b: Boolean, touchPoint: TouchPoint?) {} override fun onEndRawErasing(b: Boolean, touchPoint: TouchPoint?) {} override fun onRawErasingTouchPointMoveReceived(touchPoint: TouchPoint?) {} override fun onRawErasingTouchPointListReceived(touchPointList: TouchPointList?) {} override fun onPenUpRefresh(refreshRect: RectF?) { if (enabledLiveWriting) { touchHelper.isRawDrawingRenderEnabled = false enabledLiveWriting = false } super.onPenUpRefresh(refreshRect) } } } private fun disableFingerTouch(context: Context) { val width = context.resources.displayMetrics.widthPixels val height = context.resources.displayMetrics.heightPixels val rect = Rect(0, 0, width, height) val arrayRect = arrayOf(rect) EpdController.setAppCTPDisableRegion(context, arrayRect) } private fun enableFingerTouch(context: Context) { EpdController.appResetCTPDisableRegion(context) }
9
Kotlin
2
51
720ce81a10ef0ebd7802a16609c174597c86c9d3
8,846
boox-rapid-draw
MIT License
app/shared/state-machine/ui/public/src/commonMain/kotlin/build/wallet/statemachine/dev/AppStateDeleterOptionsUiStateMachine.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.statemachine.dev import build.wallet.statemachine.core.StateMachine import build.wallet.ui.model.list.ListGroupModel /** * State machine for showing debug options to delete app state: keys, account, backup, onboarding * states, etc. */ interface AppStateDeleterOptionsUiStateMachine : StateMachine<AppStateDeleterOptionsUiProps, ListGroupModel?> /** * @property [onDeleteAppKeyRequest] called when "Delete App Key" is pressed. * @property [onDeleteAppKeyBackupRequest] called when "Delete App Key" is pressed. * @property [onDeleteAppKeyAndBackupRequest] called when "Delete App Key and Backup" is pressed. */ data class AppStateDeleterOptionsUiProps( val onDeleteAppKeyRequest: () -> Unit, val onDeleteAppKeyBackupRequest: () -> Unit, val onDeleteAppKeyAndBackupRequest: () -> Unit, )
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
823
bitkey
MIT License
components/virtual-node/virtual-node-write-service/src/main/kotlin/net/corda/virtualnode/write/db/VirtualNodeWriteService.kt
corda
346,070,752
false
null
package net.corda.virtualnode.write.db import net.corda.lifecycle.Lifecycle /** * A service responsible for handling virtual node write requests, from both RPC and asynchronous message patterns. */ interface VirtualNodeWriteService : Lifecycle
14
null
27
69
0766222eb6284c01ba321633e12b70f1a93ca04e
247
corda-runtime-os
Apache License 2.0
lib/src/commonMain/kotlin/xyz/mcxross/bcs/model/Option.kt
mcxross
664,203,464
false
null
package xyz.mcxross.bcs.model class Option { }
0
Kotlin
0
0
eaa228526cc6df846afbae14b96504cdcee1918f
48
kotlinx-serialization-bcs
Apache License 2.0
app/src/main/java/ci/projccb/mobile/repositories/databases/daos/TypeMachineDao.kt
SICADEVD
686,088,142
false
{"Kotlin": 1262281, "Java": 20027}
package ci.projccb.mobile.repositories.databases.daos import androidx.room.* import ci.projccb.mobile.models.* /** * Created by didierboka.developer on 18/12/2021 * mail for work: (<EMAIL>) */ @Dao interface TypeMachineDao { @Transaction @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(typeMachine: TypeMachineModel) @Transaction @Query("SELECT * FROM type_machine WHERE agentId = :agentID") fun getAll(agentID: String?): MutableList<TypeMachineModel> @Transaction @Query("DELETE FROM type_machine") fun deleteAll() } /* cours_eaux eaux_usees garde_machines lieu_formations nationalites niveaux ordures_menageres sources_eaux sources_energies type_localites type_machines type_pieces varietes_cacao */
0
Kotlin
0
2
136bdf2aff6a25593bc2778e52df55ed56b37978
816
ccbm
Apache License 2.0
app/src/main/java/ci/projccb/mobile/repositories/databases/daos/TypeMachineDao.kt
SICADEVD
686,088,142
false
{"Kotlin": 1262281, "Java": 20027}
package ci.projccb.mobile.repositories.databases.daos import androidx.room.* import ci.projccb.mobile.models.* /** * Created by didierboka.developer on 18/12/2021 * mail for work: (<EMAIL>) */ @Dao interface TypeMachineDao { @Transaction @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(typeMachine: TypeMachineModel) @Transaction @Query("SELECT * FROM type_machine WHERE agentId = :agentID") fun getAll(agentID: String?): MutableList<TypeMachineModel> @Transaction @Query("DELETE FROM type_machine") fun deleteAll() } /* cours_eaux eaux_usees garde_machines lieu_formations nationalites niveaux ordures_menageres sources_eaux sources_energies type_localites type_machines type_pieces varietes_cacao */
0
Kotlin
0
2
136bdf2aff6a25593bc2778e52df55ed56b37978
816
ccbm
Apache License 2.0
parkingmanagement-api/src/main/kotlin/parkandrest/parkingmanagement/api/tariff/DifferentParkingOnTariffsException.kt
pokemzok
166,366,410
false
null
package parkandrest.parkingmanagement.api.tariff import parkandrest.exception.api.exceptionparent.BusinessException import parkandrest.parkingmanagement.api.businessexception.BusinessExceptionCode class DifferentParkingOnTariffsException(exceptionObjects: Array<Any>, exceptionMessage: String) : BusinessException(CODE, exceptionObjects, exceptionMessage) { companion object { private val CODE = BusinessExceptionCode.DIFFERENT_PARKING_ON_TARIFFS.name } }
0
Kotlin
0
1
f079ade5c5407ac1d41dfb3432f8ba1b10c1b274
474
parkandrest-kotlin
MIT License
domain/src/main/kotlin/com/hernandazevedo/moviedb/exceptions/NetworkTimeoutException.kt
hernandazevedo
156,968,020
false
null
package com.hernandazevedo.moviedb.domain.exceptions class NetworkTimeoutException(override var message: String?) : Exception()
1
Kotlin
5
5
42ebf06c7a113c35cb009bab1ca8cb0719dddea1
128
moviedb
MIT License
buildSrc/src/main/kotlin/Dependencies.kt
Pidsamhai
371,868,606
false
null
object Dependencies { const val AGT = "com.android.tools.build:gradle:${Versions.AGT}" const val KotlinGradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.Kotlin}" const val KotlinSerialization = "org.jetbrains.kotlin:kotlin-serialization:${Versions.Kotlin}" const val Hilt = "com.google.dagger:hilt-android-gradle-plugin:${Versions.Hilt}" const val ObjectBox = "io.objectbox:objectbox-gradle-plugin:${Versions.ObjectBox}" }
1
Kotlin
1
3
c44ffe1d8f341f5e77cf845199f7371e475333ff
461
movie_db
Apache License 2.0
src/main/kotlin/no/nav/helse/flex/repository/SvarDAO.kt
navikt
475,306,289
false
{"Kotlin": 1689296, "Dockerfile": 267}
package no.nav.helse.flex.repository import no.nav.helse.flex.domain.Sporsmal import no.nav.helse.flex.domain.Svar import no.nav.helse.flex.domain.Sykepengesoknad import org.springframework.jdbc.core.namedparam.MapSqlParameterSource import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.stereotype.Repository import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional @Repository class SvarDAO(private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate) { fun finnSvar(sporsmalIder: Set<String>): HashMap<String, MutableList<Svar>> { val svarMap = HashMap<String, MutableList<Svar>>() sporsmalIder.chunked(1000).forEach { namedParameterJdbcTemplate.query( """ SELECT * FROM svar WHERE sporsmal_id IN (:sporsmalIder) """.trimIndent(), MapSqlParameterSource() .addValue("sporsmalIder", it), ) { resultSet -> val sporsmalId = resultSet.getString("sporsmal_id") svarMap.computeIfAbsent(sporsmalId) { ArrayList() } svarMap[sporsmalId]!!.add( Svar( id = resultSet.getString("id"), verdi = resultSet.getString("verdi"), ), ) } } return svarMap } fun lagreSvar( sporsmalId: String, svar: Svar?, ) { fun isEmpty(str: String?): Boolean { return str == null || "" == str } if (svar == null || isEmpty(svar.verdi)) { return } namedParameterJdbcTemplate.update( """ INSERT INTO svar (sporsmal_id, verdi) VALUES (:sporsmalId, :verdi) """.trimIndent(), MapSqlParameterSource() .addValue("sporsmalId", sporsmalId) .addValue("verdi", svar.verdi), ) } fun slettSvar(sykepengesoknadUUID: String) { namedParameterJdbcTemplate.update( """ DELETE FROM svar WHERE svar.id IN ( SELECT svar.id FROM svar INNER JOIN sporsmal ON svar.sporsmal_id = sporsmal.id INNER JOIN sykepengesoknad ON sporsmal.sykepengesoknad_id = sykepengesoknad.id WHERE sykepengesoknad_uuid = :soknadUUID ) """.trimIndent(), MapSqlParameterSource() .addValue("soknadUUID", sykepengesoknadUUID), ) } fun slettSvar(sporsmalIder: List<String>) { if (sporsmalIder.isEmpty()) { return } sporsmalIder.chunked(1000).forEach { namedParameterJdbcTemplate.update( "DELETE FROM svar WHERE sporsmal_id IN (:sporsmalIder)", MapSqlParameterSource() .addValue("sporsmalIder", it), ) } } fun slettSvar( sporsmalId: String, svarId: String, ) { namedParameterJdbcTemplate.update( "DELETE FROM svar WHERE sporsmal_id = :sporsmalId AND id = :svarId", MapSqlParameterSource() .addValue("sporsmalId", sporsmalId) .addValue("svarId", svarId), ) } fun overskrivSvar(sykepengesoknad: Sykepengesoknad) { val alleSporsmalOgUndersporsmal = sykepengesoknad.alleSporsmalOgUndersporsmal() slettSvar(alleSporsmalOgUndersporsmal.mapNotNull { it.id }) alleSporsmalOgUndersporsmal .forEach { sporsmal -> sporsmal.svar .forEach { svar -> lagreSvar(sporsmal.id!!, svar) } } } fun overskrivSvar(sporsmal: List<Sporsmal>) { slettSvar(sporsmal.mapNotNull { it.id }) sporsmal.forEach { it.svar.forEach { svar -> lagreSvar(it.id!!, svar) } } } }
8
Kotlin
0
4
4c07a767676b309ebf7db20c76674b152f3ec2ee
4,069
sykepengesoknad-backend
MIT License
app/src/main/java/ziox/ramiro/saes/features/saes/features/schedule/view_models/ScheduleViewModel.kt
RamiroEstradaG
270,838,409
false
{"Kotlin": 522260, "HTML": 56894}
package ziox.ramiro.saes.features.saes.features.schedule.view_models import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import ziox.ramiro.saes.features.saes.features.schedule.data.models.ClassSchedule import ziox.ramiro.saes.features.saes.features.schedule.data.models.CustomClassSchedule import ziox.ramiro.saes.features.saes.features.schedule.data.repositories.CustomScheduleRoomRepository import ziox.ramiro.saes.features.saes.features.schedule.data.repositories.ScheduleRepository import ziox.ramiro.saes.utils.dismissAfterTimeout import ziox.ramiro.saes.utils.runOnDefaultThread class ScheduleViewModel( private val scheduleRepository: ScheduleRepository, private val customScheduleRoomRepository: CustomScheduleRoomRepository ) : ViewModel() { val scheduleList = mutableStateListOf<ClassSchedule>() val isLoading = mutableStateOf(false) val error = MutableStateFlow<String?>(null) init { fetchMySchedule() error.dismissAfterTimeout() } private fun fetchMySchedule() = viewModelScope.launch { scheduleList.clear() isLoading.value = true kotlin.runCatching { scheduleRepository.getMySchedule() }.onSuccess { scheduleList.addAll(it) }.onFailure { error.value = "Error al cargar el horario" } isLoading.value = false } fun editClass(classSchedule: CustomClassSchedule) = viewModelScope.launch { val index = scheduleList.indexOfFirst { it.id == classSchedule.id } if(index in scheduleList.indices){ runOnDefaultThread { customScheduleRoomRepository.removeClass(classSchedule.id) customScheduleRoomRepository.addClass(classSchedule) } scheduleList[index] = classSchedule.toClassSchedule() } } }
9
Kotlin
0
20
213ffe59f3f55830ed378132fdda65f4d4199c38
2,073
SAES-para-Alumnos
MIT License
vgscollect/src/main/java/com/verygoodsecurity/vgscollect/core/OnVgsViewStateChangeListener.kt
verygoodsecurity
273,198,410
false
{"Kotlin": 1118374, "Python": 210}
package com.verygoodsecurity.vgscollect.core import com.verygoodsecurity.vgscollect.core.model.state.VGSFieldState /** @suppress */ interface OnVgsViewStateChangeListener { fun emit(viewId:Int, state: VGSFieldState) }
5
Kotlin
8
8
237826181dc852687874fca87c9dddd4a9a686f2
223
vgs-collect-android
MIT License
library/src/main/java/com/github/sumimakito/rhythmview/effect/Ray.kt
SumiMakito
148,911,910
false
null
package com.github.sumimakito.rhythmview.effect import android.graphics.Canvas import android.graphics.Paint import android.graphics.PointF import com.github.sumimakito.rhythmview.RhythmView import com.github.sumimakito.rhythmview.util.MathUtils import com.github.sumimakito.rhythmview.wave.WavePoint import kotlin.math.floor import kotlin.math.max import kotlin.math.min /** * A preset visual effect. * * Resolution of the data source should not be less than `resolution * 3` here. * * When using with `PlaybackSource`, parameter `resolution` should not be larger than 256, or the * capture size may exceeded the maximum capture size of the system. */ class Ray @JvmOverloads constructor(rhythmView: RhythmView, private val resolution: Int = 256, private val waveSpeed: Float = 0.04f) : BaseEffect<Int>(rhythmView) { var colorHF: Int = 0xffef9a9a.toInt() var colorMF: Int = 0xff90caf9.toInt() var colorLF: Int = 0xffa5d6a7.toInt() var alphaHF: Float = 0.65f var alphaMF: Float = 0.65f var alphaLF: Float = 0.65f private var frameId = 0 private var wavePoints = ArrayList<WavePoint>() private var outerPoints = ArrayList<PointF>() private var innerPoints = ArrayList<PointF>() private var paintRay = Paint() private var delta: Float init { if (resolution < 4) throw RuntimeException("Division should be an integer larger than 4.") delta = 360f / resolution for (i in 0 until resolution * 3) { wavePoints.add(WavePoint(0f, waveSpeed, 0f, 1f)) } paintRay.isAntiAlias = true paintRay.style = Paint.Style.STROKE paintRay.strokeWidth = 3f computePoints() } private fun refillWave(wave: Array<Int>) { for (i in 0 until min(wavePoints.size, wave.size)) { wavePoints[i].changeTo(wave[i] / 256f) } } override fun onFrameRendered() { if (frameId % 2 == 0) { if (dataSource != null && dataSource!!.data != null) refillWave(dataSource!!.data!!) } for (wavePoint in wavePoints) { wavePoint.nextTick() } computePoints() frameId++ if (frameId > 2) { frameId = 0 } } override fun render(canvas: Canvas) { paintRay.color = colorHF paintRay.alpha = floor(255f * alphaHF).toInt() var ptIndex = 0 for (i in 0 until resolution) { val start = innerPoints[ptIndex] val stop = outerPoints[ptIndex] canvas.drawLine(start.x, start.y, stop.x, stop.y, paintRay) ptIndex++ } paintRay.color = colorLF paintRay.alpha = floor(255f * alphaLF).toInt() for (i in 0 until resolution) { val start = innerPoints[ptIndex] val stop = outerPoints[ptIndex] canvas.drawLine(start.x, start.y, stop.x, stop.y, paintRay) ptIndex++ } paintRay.color = colorMF paintRay.alpha = floor(255f * alphaMF).toInt() for (i in 0 until resolution) { val start = innerPoints[ptIndex] val stop = outerPoints[ptIndex] canvas.drawLine(start.x, start.y, stop.x, stop.y, paintRay) ptIndex++ } } private fun computePoints() { outerPoints.clear() for (i in 0 until wavePoints.size) { val deg = (i % 360) * delta innerPoints.add(MathUtils.getPointOnCircle(centerX, centerY, minDrawingRadius, deg)) outerPoints.add(MathUtils.getPointOnCircle(centerX, centerY, minDrawingRadius + getWaveHeight(i), deg)) } } private fun getWaveHeight(index: Int): Float { if (index < wavePoints.size) { return min(1f, max(0f, wavePoints[index].displayValue)) * maxDrawingWidth } return 0f } }
0
Kotlin
3
27
661584b7119aa1b33e1eb0294ea72fd5f68ba3de
3,871
RhythmView
Apache License 2.0
app/src/main/java/com/purplepotato/kajianku/home/SuggestedKajianRecyclerAdapter.kt
mfathur
332,154,291
false
null
package com.purplepotato.kajianku.home import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.findNavController import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import coil.load import coil.transform.RoundedCornersTransformation import com.purplepotato.kajianku.R import com.purplepotato.kajianku.core.domain.Kajian import com.purplepotato.kajianku.core.util.DiffUtilItemCallback import com.purplepotato.kajianku.core.util.Helpers import com.purplepotato.kajianku.databinding.ItemKajianBinding class SuggestedKajianRecyclerAdapter : ListAdapter<Kajian, SuggestedKajianRecyclerAdapter.SuggestedKajianViewHolder>( DiffUtilItemCallback.KAJIAN_DIFF_CALLBACK ) { inner class SuggestedKajianViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val binding = ItemKajianBinding.bind(itemView) fun bind(item: Kajian) { with(binding) { itemImgPoster.load(item.imageUrl) { crossfade(true) placeholder(R.drawable.image_placeholder) error(R.drawable.image_placeholder) transformations(RoundedCornersTransformation(8f)) } itemTxtTitle.text = item.title itemTxtSpeaker.text = item.speaker itemTxtPlace.text = item.location itemTxtDateTime.text = "${Helpers.convertTimeStampToDateTimeFormat(item.startedAt)} WIB" root.setOnClickListener { val action = HomeFragmentDirections.actionHomeFragmentToDetailFragment() action.kajian = item root.findNavController().navigate(action) } } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SuggestedKajianViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_kajian, parent, false) return SuggestedKajianViewHolder(view) } override fun onBindViewHolder(holder: SuggestedKajianViewHolder, position: Int) { holder.bind(getItem(position)) } }
0
Kotlin
2
0
7b56424b1d65ff42b1668ac337a39c31e607150e
2,262
kajianku
Apache License 2.0
reservation-domain/src/main/kotlin/my/gayeon/reservation/configuration/DomainConfig.kt
gayeonkim91
745,275,807
false
{"Kotlin": 3140}
package my.gayeon.reservation.configuration import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Import @Import(value = [ JpaConfig::class ]) @Configuration @ComponentScan(basePackages = [ "my.gayeon.reservation.domain" ]) class DomainConfig { }
0
Kotlin
0
0
6c01343d249d9496c16e4b0a2aa19800fb23933e
360
ticket-reservation
MIT License
src/main/kotlin/creational_patterns/prototype/CopyThroughSerialisation.kt
ThijsBoehme
291,005,516
false
{"Kotlin": 88248, "Java": 31062}
package creational_patterns.prototype import org.apache.commons.lang3.SerializationUtils import java.io.Serializable class Foo(var stuff: Int, var whatever: String): Serializable { override fun toString(): String { return "Foo(stuff=$stuff, whatever='$whatever')" } } fun main() { val foo = Foo(42, "life") val foo2 = SerializationUtils.roundtrip(foo) foo2.whatever = "xyz" println(foo) println(foo2) }
0
Kotlin
0
0
9bdb5be77dcd527493b39ad562291a4023e36a98
444
portfolio-design-patterns-udemy
MIT License
library/src/main/java/io/github/chenfei0928/content/res/ResUriUtil.kt
chenfei0928
130,954,695
false
null
package io.github.chenfei0928.content.res import android.content.ContentResolver import android.content.res.Resources import androidx.annotation.AnyRes class ResUriUtil { companion object { @JvmStatic fun getResUri(context: Resources, @AnyRes id: Int) = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getResourcePackageName(id) + "/" + context.getResourceTypeName(id) + "/" + context.getResourceEntryName(id) @JvmStatic fun getResUri2(context: Resources, @AnyRes id: Int) = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getResourcePackageName(id) + "/" + id } }
0
null
0
2
622dbf879e5d57ed8d3865442a137daf77400950
732
Util
MIT License
image/src/main/kotlin/net/insprill/mapdisplays/image/codec/cache/CachedImageCodec.kt
Insprill
525,202,305
false
null
package net.insprill.mapdisplays.image.codec.cache import com.google.common.primitives.Ints import net.insprill.mapdisplays.core.MapCoord import net.insprill.mapdisplays.core.codec.cache.CachedCodec import net.insprill.mapdisplays.core.exception.DecodeException import net.insprill.mapdisplays.image.Image import net.insprill.mapdisplays.image.Pixel import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.InputStream import java.io.OutputStream object CachedImageCodec : CachedCodec<Image> { private const val CODEC_VERSION = 0 override fun encode(obj: Image): ByteArrayOutputStream { val output = ByteArrayOutputStream() output.write(CODEC_VERSION) output.write(obj.multiPos.x) output.write(obj.multiPos.y) output.writeLarge(obj.pixels.size) for (pixel in obj.pixels) { output.write(pixel.color.toInt()) output.writeLarge(pixel.mapCoords.size) for (coord in pixel.mapCoords) { output.write(coord.x) output.write(coord.y) } } return output } override fun decode(input: ByteArrayInputStream): Image { val codec = input.read() if (codec != CODEC_VERSION) throw DecodeException("Unknown codec version $codec") val multiPos = MapCoord(input.read(), input.read()) val pixels = ArrayList<Pixel>() val pixelCount = input.readLarge() repeat(pixelCount) { val pixelColor = input.read() val pixel = Pixel(pixelColor.toByte()) val coordCount = input.readLarge() repeat(coordCount) { val x = input.read() val y = input.read() pixel.addCoord(MapCoord(x, y)) } pixels.add(pixel) } return Image(pixels, multiPos) } private fun OutputStream.writeLarge(i: Int) { if (i > Byte.MAX_VALUE || i < Byte.MIN_VALUE) { this.write(1) this.write(Ints.toByteArray(i)) } else { this.write(0) this.write(i) } } private fun InputStream.readLarge(): Int { return if (this.read() == 1) { Ints.fromByteArray(this.readNBytes(4)) } else { this.read() } } }
0
Kotlin
0
0
ccb719808d2d5d3e3b1f4601c924f59c56276c8c
2,358
map-displays
Apache License 2.0
app/src/main/java/de/fhe/ai/flipsen/view/ui/generator/GeneratorFragment.kt
fh-erfurt
575,489,613
false
{"Kotlin": 61843}
package de.fhe.ai.flipsen.view.ui.generator import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import de.fhe.ai.flipsen.databinding.FragmentGeneratorBinding class GeneratorFragment : Fragment() { private lateinit var generatorViewModel: GeneratorViewModel private var _binding: FragmentGeneratorBinding? = null private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { generatorViewModel = ViewModelProvider(this)[GeneratorViewModel::class.java] _binding = FragmentGeneratorBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textGenerator generatorViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
1
ce9cdceca5deac561f9364a9416036062f4870e8
1,127
ws2022_pme_flipsen
MIT License
tangem-demo/src/main/java/com/tangem/tangemtest/_arch/structure/abstraction/Item.kt
byennen
259,809,719
true
{"Kotlin": 449827}
package com.tangem.tangemtest._arch.structure.abstraction import com.tangem.tangemtest._arch.structure.Id /** * Created by <NAME> on 22/03/2020. */ interface UpdateBy<B>{ fun update(value: B) } interface Item: UpdateBy<Item> { val id: Id var parent: Item? var viewModel: ItemViewModel fun added(parent: Item) { this.parent = parent } fun removed(parent: Item) { this.parent = null } fun <D> getData(): D? = viewModel.data as? D fun setData(value: Any?) { viewModel.data = value } fun restoreDefaultData() { setData(viewModel.defaultData) } } open class BaseItem( override val id: Id, override var viewModel: ItemViewModel ) : Item { override var parent: Item? = null override fun update(value: Item) { viewModel.update(value.viewModel) } }
0
null
0
1
92e1f653522aefde668fdc100230d62492487182
873
tangem-sdk-android
MIT License
src/main/kotlin/io/nais/Metrics.kt
nais
319,762,249
false
{"Kotlin": 43774, "HTML": 5684, "CSS": 4355, "JavaScript": 3947, "Dockerfile": 144}
package io.nais import io.micrometer.prometheus.PrometheusConfig import io.micrometer.prometheus.PrometheusMeterRegistry import io.prometheus.client.Counter object Metrics { val meterRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT) private val downloadsCounter = Counter.build() .name("apps") .labelNames("team", "platform", "format") .help("Nr of generated responses") .register(meterRegistry.prometheusRegistry) private val userAgentCounter = Counter.build() .name("useragent") .labelNames("name") .help("Nr of unique user agents") .register(meterRegistry.prometheusRegistry) fun scrape(): String = meterRegistry.scrape() fun countNewDownload(team: String, platform: PLATFORM, format: String) = downloadsCounter.labels(team, platform.toString(), format).inc() fun countUserAgent(name: String) = userAgentCounter.labels(name).inc() }
0
Kotlin
2
4
4da4e19fc05fa55779a91885b43eb9954f60e968
934
start.nais.io
MIT License
app/src/main/java/com/erkaslan/servio/ui/add/AddFragment.kt
emreerkaslan
418,259,277
false
{"Kotlin": 133595, "Python": 70589, "Dockerfile": 941, "Shell": 45}
package com.erkaslan.servio.ui.add import android.content.Context import android.content.SharedPreferences import android.icu.text.SimpleDateFormat import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.erkaslan.servio.AllUtil import com.erkaslan.servio.MainActivity import com.erkaslan.servio.databinding.FragmentAddBinding import com.erkaslan.servio.model.GenericResult import com.google.gson.JsonObject import java.util.* class AddFragment : Fragment() { private var _binding: FragmentAddBinding? = null private val binding get() = _binding!! private lateinit var addViewModel: AddViewModel private var sharedPreferences: SharedPreferences? = context?.getSharedPreferences("app", Context.MODE_PRIVATE) private var util = AllUtil() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) addViewModel = ViewModelProvider(this).get(AddViewModel::class.java) initViews() initObservers() } fun initViews(){ binding.isService = true binding.btnServiceHeader.setOnClickListener{ binding.isService = true } binding.btnEventHeader.setOnClickListener{ binding.isService = false } binding.btnServiceCreate.setOnClickListener{ createService() } binding.btnEventCreate.setOnClickListener{ createEvent() } } fun initObservers(){ addViewModel.serviceCreatedMutableLiveData.observe(viewLifecycleOwner, { when(it) { is GenericResult.Success -> { Toast.makeText(context, "Service Created", Toast.LENGTH_SHORT).show() } is GenericResult.Failure -> { Toast.makeText(context, "Something was wrong, try again", Toast.LENGTH_SHORT).show() } else -> {} } }) addViewModel.eventCreatedMutableLiveData.observe(viewLifecycleOwner, { when(it) { is GenericResult.Success -> { Toast.makeText(context, "Event Created", Toast.LENGTH_SHORT).show() } is GenericResult.Failure -> { Toast.makeText(context, "Something was wrong, try again", Toast.LENGTH_SHORT).show() } else -> {} } }) } private fun createService(){ val calendar = Calendar.getInstance() var format = SimpleDateFormat(("yyyy-MM-dd'T'HH:mm:ss'Z'"), Locale.getDefault()) calendar.set(binding.dpServiceCreation.year, binding.dpServiceCreation.month, binding.dpServiceCreation.dayOfMonth, binding.tpServiceCreation.currentHour, binding.tpServiceCreation.currentMinute) if(calendar.time < Calendar.getInstance().time){ Toast.makeText(context, "Picking a later date than now may be wise", Toast.LENGTH_LONG).show() return } if(binding.etServiceCreationCredits.text.toString().toIntOrNull() == null){ Toast.makeText(context, "Enter a numeric value less than 15 for credits", Toast.LENGTH_LONG).show() return } else if (Integer.parseInt(binding.etServiceCreationCredits.text.toString()) > 15 || Integer.parseInt(binding.etServiceCreationCredits.text.toString()) <1) { Toast.makeText(context, "Enter a numeric value less than 15 for credits", Toast.LENGTH_LONG).show() return } val json = JsonObject() json.addProperty("title", binding.etServiceCreationTitle.text.toString()) json.addProperty("description", binding.etServiceCreationDescription.text.toString()) json.addProperty("credits", Integer.parseInt(binding.etServiceCreationCredits.text.toString())) json.addProperty("date", format.format(calendar.time).toString()) //"2022-01-14T05:03:00Z" json.addProperty("geolocation", binding.etServiceCreationGeolocation.text.toString()) json.addProperty("giver", (activity as MainActivity)?.currentUser?.pk) val tags = binding.etServiceCreationTags.text.toString().split(" ", ",", "#") //json.addProperty("tags", binding.etServiceCreationTags.text.toString()) if(binding.cbServiceCreationRecurring.isChecked){ json.addProperty("recurring", true) }else{ json.addProperty("recurring", false) } //val result = util.validateServiceCreation(json) addViewModel.createService((activity as MainActivity).token?.token ?: "", json) } private fun createEvent(){ if(((activity as MainActivity).currentUser?.service?.filter { (it.date ?: Calendar.getInstance().time) > Calendar.getInstance().time } ?: listOf()).size >=10) { Toast.makeText(context, "You can provide maximum of 10 services at a time", Toast.LENGTH_LONG).show() } val calendar = Calendar.getInstance() var format = SimpleDateFormat(("yyyy-MM-dd'T'HH:mm:ss'Z'"), Locale.getDefault()) calendar.set(binding.dpEventCreation.year, binding.dpEventCreation.month, binding.dpEventCreation.dayOfMonth, binding.tpEventCreation.currentHour, binding.tpEventCreation.currentMinute) if(calendar.time < Calendar.getInstance().time){ Toast.makeText(context, "Picking a later date than now may be wise", Toast.LENGTH_LONG).show() return } val json = JsonObject() json.addProperty("title", binding.etEventCreationTitle.text.toString()) json.addProperty("description", binding.etEventCreationDescription.text.toString()) json.addProperty("date", format.format(calendar.time).toString()) //"2022-01-14T05:03:00Z" json.addProperty("geolocation", binding.etEventCreationGeolocation.text.toString()) json.addProperty("address", binding.etEventCreationAddress.text.toString()) json.addProperty("organizer", (activity as MainActivity)?.currentUser?.pk) if(binding.cbEventCreationQuota.isChecked){ json.addProperty("hasQuota", true) json.addProperty("quota", binding.etEventCreationQuota.text.toString()) }else{ json.addProperty("hasQuota", false) } Log.d("CALL",json.toString()) addViewModel.createEvent((activity as MainActivity).token?.token ?: "", json) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentAddBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
77f21bae55ff0c0ef5367b59b6aa28ff9ba09a0f
6,932
Servio
MIT License
src/main/java/dev/blachut/svelte/lang/utils.kt
tomblachut
184,821,501
false
{"JavaScript": 467590, "Kotlin": 426521, "Java": 81911, "Lex": 16310, "Svelte": 14923, "HTML": 2052, "TypeScript": 709}
package dev.blachut.svelte.lang import com.intellij.codeInspection.InspectionProfileEntry import com.intellij.codeInspection.LocalInspectionTool import com.intellij.lang.PsiBuilder import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiElement import com.intellij.psi.TokenType import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.util.indexing.FileBasedIndexImpl import com.intellij.webSymbols.context.WebSymbolsContext import com.intellij.webSymbols.context.WebSymbolsContext.Companion.KIND_FRAMEWORK import com.intellij.xml.util.HtmlUtil import dev.blachut.svelte.lang.psi.SvelteHtmlFile import dev.blachut.svelte.lang.psi.SvelteHtmlTag fun isSvelteContext(context: PsiElement): Boolean { return context.containingFile is SvelteHtmlFile } fun isSvelteContext(file: VirtualFile): Boolean { return file.fileType == SvelteHtmlFileType.INSTANCE } fun isSvelteProjectContext(context: PsiElement): Boolean { return WebSymbolsContext.get(KIND_FRAMEWORK, context) == "svelte" } fun isSvelteProjectContext(project: Project, context: VirtualFile): Boolean { return WebSymbolsContext.get(KIND_FRAMEWORK, context, project) == "svelte" } fun isSvelteComponentTag(tagName: CharSequence): Boolean { // TODO Support namespaced components WEB-61636 return tagName.isNotEmpty() && tagName[0].isUpperCase() } fun isSvelteNamespacedComponentTag(tagName: CharSequence): Boolean { return tagName.contains('.') } fun isTSLangValue(value: String?): Boolean { return value == "ts" || value == "typescript" } fun PsiBuilder.isTokenAfterWhiteSpace(): Boolean { // tokenType is called because it skips whitespaces, unlike bare advanceLexer() this.tokenType val lastRawToken = this.rawLookup(-1) return lastRawToken === TokenType.WHITE_SPACE } fun SvelteHtmlTag.isScriptOrStyleTag(): Boolean { return this.name == HtmlUtil.SCRIPT_TAG_NAME || this.name == HtmlUtil.STYLE_TAG_NAME } internal inline fun <reified T : LocalInspectionTool> String.equalsName(): Boolean { return this == InspectionProfileEntry.getShortName(T::class.java.simpleName) } fun hasSvelteFiles(project: Project): Boolean = CachedValuesManager.getManager(project).getCachedValue(project) { CachedValueProvider.Result.create( FileBasedIndexImpl.disableUpToDateCheckIn<Boolean, Exception> { FileTypeIndex.containsFileOfType(SvelteHtmlFileType.INSTANCE, GlobalSearchScope.projectScope(project)) }, VirtualFileManager.VFS_STRUCTURE_MODIFICATIONS, DumbService.getInstance(project) ) }
0
JavaScript
38
469
8c6c1ecb2141324268e0dc7d044cb01b7ba03722
2,824
svelte-intellij
MIT License
src/main/kotlin/no/trulsjor/keywordfrequencycounter/tikahandler/TextNormalizer.kt
trulsjor
320,417,562
false
null
package no.trulsjor.keywordfrequencycounter.tikahandler class TextNormalizer { private val doc = mutableListOf<String>() private val specialCharacters = "[\\P{IsAlphabetic}&&\\P{Digit}&&[^\\s+]]".toRegex() internal fun append(text: String) = doc.add(text.toLowerCase().replace(specialCharacters, " ")) internal fun normalize() = doc.joinToString(" ") .replace("\\s+".toRegex(), " ") .trim() }
0
Kotlin
0
0
6f41a6d8b58b5bd6dfa471870dac5aa0c7048485
445
keyword-frequency-counter
MIT License
src/commonTest/kotlin/ru/capjack/tool/depin/TestBind.kt
CaptainJack
144,030,622
false
null
package ru.capjack.tool.depin import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith @Suppress("FunctionName") class TestBind { @Test fun typed() { val obj = StubEmpty() val injector = Injector { bind(obj) } assertEquals(obj, injector.get()) } @Test fun named() { val obj = StubEmpty() val name = stubNameEmpty val injector = Injector { bindInstance(name, obj) } assertEquals(obj, injector.get(name)) } @Test fun fail_on_strong_typed() { val builder = Injection() builder.configure { bind(StubEmpty()) bind(StubEmpty()) } assertFailsWith<InjectException> { builder.build(true) } } @Test fun fail_on_strong_named() { val name = stubNameEmpty val builder = Injection() builder.configure { bindInstance(name, StubEmpty()) bindInstance(name, StubEmpty()) } assertFailsWith<InjectException> { builder.build(true) } } @Test fun success_on_not_strong_typed() { val builder = Injection() builder.configure { bind(StubEmpty()) bind(StubEmpty()) } builder.build(false) } @Test fun success_on_not_strong_named() { val builder = Injection() val name = stubNameEmpty builder.configure { bindInstance(name, StubEmpty()) bindInstance(name, StubEmpty()) } builder.build(false) } }
0
Kotlin
0
0
83076dd9b664031b5449b585f0332179eaffc35c
1,355
tool-depin
MIT License
decoder/src/main/kotlin/app/redwarp/gif/decoder/descriptors/ImageDescriptor.kt
redwarp
323,195,114
false
null
/* Copyright 2020 Benoit Vermont * * 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 app.redwarp.gif.decoder.descriptors class ImageDescriptor( val position: Point, val dimension: Dimension, val isInterlaced: Boolean, val localColorTable: IntArray?, val imageData: ImageData, val graphicControlExtension: GraphicControlExtension? )
1
null
7
43
284e8d83aebaccf72807f2f0b1d1fd52b840d06e
875
gifdecoder
Apache License 2.0
opendc-experiments/opendc-experiments-capelin/src/main/kotlin/org/opendc/experiments/capelin/monitor/ParquetExperimentMonitor.kt
Koen1999
419,678,775
true
{"Kotlin": 1112148, "Jupyter Notebook": 275743, "JavaScript": 264579, "Shell": 133323, "Python": 101126, "Sass": 7151, "HTML": 3690, "Dockerfile": 1742}
/* * Copyright (c) 2021 AtLarge Research * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.opendc.experiments.capelin.monitor import mu.KotlinLogging import org.opendc.compute.api.Server import org.opendc.compute.api.ServerState import org.opendc.compute.service.driver.Host import org.opendc.compute.service.driver.HostState import org.opendc.experiments.capelin.telemetry.HostEvent import org.opendc.experiments.capelin.telemetry.ProvisionerEvent import org.opendc.experiments.capelin.telemetry.parquet.ParquetHostEventWriter import org.opendc.experiments.capelin.telemetry.parquet.ParquetProvisionerEventWriter import java.io.File /** * The logger instance to use. */ private val logger = KotlinLogging.logger {} /** * An [ExperimentMonitor] that logs the events to a Parquet file. */ public class ParquetExperimentMonitor(base: File, partition: String, bufferSize: Int) : ExperimentMonitor { private val hostWriter = ParquetHostEventWriter( File(base, "host-metrics/$partition/data.parquet"), bufferSize ) private val provisionerWriter = ParquetProvisionerEventWriter( File(base, "provisioner-metrics/$partition/data.parquet"), bufferSize ) override fun reportVmStateChange(time: Long, server: Server, newState: ServerState) {} override fun reportHostStateChange(time: Long, host: Host, newState: HostState) { logger.debug { "Host ${host.uid} changed state $newState [$time]" } } override fun reportHostSlice( time: Long, requestedBurst: Long, grantedBurst: Long, overcommissionedBurst: Long, interferedBurst: Long, cpuUsage: Double, cpuDemand: Double, powerDraw: Double, numberOfDeployedImages: Int, host: Host ) { hostWriter.write( HostEvent( time, 5 * 60 * 1000L, host, numberOfDeployedImages, requestedBurst, grantedBurst, overcommissionedBurst, interferedBurst, cpuUsage, cpuDemand, powerDraw, host.model.cpuCount ) ) } override fun reportProvisionerMetrics( time: Long, totalHostCount: Int, availableHostCount: Int, totalVmCount: Int, activeVmCount: Int, inactiveVmCount: Int, waitingVmCount: Int, failedVmCount: Int ) { provisionerWriter.write( ProvisionerEvent( time, totalHostCount, availableHostCount, totalVmCount, activeVmCount, inactiveVmCount, waitingVmCount, failedVmCount ) ) } override fun close() { hostWriter.close() provisionerWriter.close() } }
0
Kotlin
0
0
f9b43518d2d50f33077734537a477539fca9f5b7
3,985
opendc
MIT License
Android/app/src/main/java/com/example/android/presentation/ui/repo/RepoActivity.kt
notmyfault02
199,797,357
false
null
package com.example.android.presentation.ui.repo import android.os.Bundle import android.view.Menu import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.android.R import com.example.android.presentation.model.RepoSearchResponse import com.example.android.presentation.ui.adapter.RepoAdapter import kotlinx.android.synthetic.main.activity_repo.* import org.koin.android.ext.android.inject class RepoActivity : AppCompatActivity(), UserDataList { private val presenter: RepoPresenter<UserDataList> by inject() val repoAdapter by lazy { RepoAdapter(this, ArrayList()) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_repo) presenter.userData = this rv_repo.apply { layoutManager = LinearLayoutManager(this@RepoActivity, RecyclerView.VERTICAL, false) rv_repo.setHasFixedSize(true) rv_repo.adapter = repoAdapter } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_activity_search, menu) val searchView = menu?.findItem(R.id.menu_activity_search_query)?.actionView as androidx.appcompat.widget.SearchView searchView?.setOnQueryTextListener(object: androidx.appcompat.widget.SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { query?.let { searchGithubUser(query)} return false } override fun onQueryTextChange(newText: String?): Boolean { return false } }) return super.onCreateOptionsMenu(menu) } override fun onDataLoaded(storeResponse: RepoSearchResponse) { repoAdapter.apply { items.clear() items.addAll(storeResponse.items) notifyDataSetChanged() } } override fun onDataFailed() { repoAdapter.apply { items.clear() notifyDataSetChanged() } } override fun searchGithubUser(searchWord: String) { if (searchWord.isNullOrBlank()) { repoAdapter.apply { items.clear() notifyDataSetChanged() } } else { presenter.getGithubUser(searchWord) } } }
0
Kotlin
0
0
e346e276b9c7bfd5381298cc5af7a3ee0fce447d
2,469
GithubApi-Android
MIT License
korge-foundation/src/korlibs/math/geom/_MathGeom.binpack.kt
korlibs
80,095,683
false
{"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41}
@file:Suppress("PackageDirectoryMismatch") package korlibs.math.geom.binpack import korlibs.datastructure.* import korlibs.datastructure.iterators.* import korlibs.math.geom.* import kotlin.collections.set class BinPacker(val size: Size, val algo: Algo = MaxRects(size)) { val width: Double get() = size.width val height: Double get() = size.height interface Algo { fun add(size: Size): Rectangle? } class Result<T>(val maxWidth: Double, val maxHeight: Double, val items: List<Pair<T, Rectangle?>>) { private val rectanglesNotNull = items.mapNotNull { it.second } val width: Double = rectanglesNotNull.maxOfOrNull { it.right } ?: 0.0 val height: Double = rectanglesNotNull.maxOfOrNull { it.bottom } ?: 0.0 val rects: List<Rectangle?> get() = items.map { it.second } val rectsStr: String get() = rects.toString() } val allocated = FastArrayList<Rectangle>() fun <T> Algo.addBatch(items: Iterable<T>, getSize: (T) -> Size): List<Pair<T, Rectangle?>> { val its = items.toList() val out = hashMapOf<T, Rectangle?>() val sorted = its.map { it to getSize(it) }.sortedByDescending { it.second.area } for ((i, size) in sorted) out[i] = this.add(size) return its.map { it to out[it] } } fun add(width: Double, height: Double): Rectangle = addOrNull(width, height) ?: throw ImageDoNotFitException(width, height, this) fun add(width: Int, height: Int): Rectangle = add(width.toDouble(), height.toDouble()) fun add(width: Float, height: Float): Rectangle = add(width.toDouble(), height.toDouble()) fun addOrNull(width: Double, height: Double): Rectangle? { val rect = algo.add(Size(width, height)) ?: return null allocated += rect return rect } fun addOrNull(width: Int, height: Int): Rectangle? = addOrNull(width.toDouble(), height.toDouble()) fun addOrNull(width: Float, height: Float): Rectangle? = addOrNull(width.toDouble(), height.toDouble()) fun <T> addBatch(items: Iterable<T>, getSize: (T) -> Size): Result<T> { return Result(width, height, algo.addBatch(items, getSize)) } fun addBatch(items: Iterable<Size>): List<Rectangle?> = algo.addBatch(items) { it }.map { it.second } companion object { operator fun invoke(width: Double, height: Double, algo: Algo = MaxRects(width, height)) = BinPacker(Size(width, height), algo) operator fun invoke(width: Int, height: Int, algo: Algo = MaxRects(width.toDouble(), height.toDouble())) = BinPacker(width.toDouble(), height.toDouble(), algo) operator fun invoke(width: Float, height: Float, algo: Algo = MaxRects(width.toDouble(), height.toDouble())) = BinPacker(width.toDouble(), height.toDouble(), algo) fun <T> pack(width: Double, height: Double, items: Iterable<T>, getSize: (T) -> Size): Result<T> = BinPacker(width, height).addBatch(items, getSize) fun <T> pack(width: Int, height: Int, items: Iterable<T>, getSize: (T) -> Size): Result<T> = pack(width.toDouble(), height.toDouble(), items, getSize) fun <T> pack(width: Float, height: Float, items: Iterable<T>, getSize: (T) -> Size): Result<T> = pack(width.toDouble(), height.toDouble(), items, getSize) fun <T> packSeveral( maxSize: Size, items: Iterable<T>, getSize: (T) -> Size ): List<Result<T>> { val (maxWidth, maxHeight) = maxSize var currentBinPacker = BinPacker(maxWidth, maxHeight) var currentPairs = FastArrayList<Pair<T, Rectangle>>() val sortedItems = items.sortedByDescending { getSize(it).area } sortedItems.fastForEach { val size = getSize(it) if (size.width > maxWidth || size.height > maxHeight) { throw ImageDoNotFitException(size.width, size.height, currentBinPacker) } } val out = FastArrayList<Result<T>>() fun emit() { if (currentPairs.isEmpty()) return out += Result(maxWidth, maxHeight, currentPairs.toList()) currentPairs = FastArrayList() currentBinPacker = BinPacker(maxWidth, maxHeight) } //for (item in items) { // var done = false // while (!done) { // try { // val size = getSize(item) // val rect = currentBinPacker.add(size.width, size.height) // currentPairs.add(item to rect) // done = true // } catch (e: IllegalStateException) { // emit() // } // } //} for (item in items) { var done = false while (!done) { val size = getSize(item) val rect = currentBinPacker.addOrNull(size.width, size.height) if (rect != null) { currentPairs.add(item to rect) done = true } else { emit() } } } emit() return out } fun <T : Sizeable> packSeveral(maxSize: Size, items: Iterable<T>): List<Result<T>> = packSeveral(maxSize, items) { it.size } } class ImageDoNotFitException(val width: Double, val height: Double, val packer: BinPacker) : Throwable( "Size '${width}x${height}' doesn't fit in '${packer.width}x${packer.height}'" ) } class MaxRects(maxSize: Size) : BinPacker.Algo { constructor(width: Float, height: Float) : this(Size(width, height)) constructor(width: Double, height: Double) : this(Size(width, height)) var freeRectangles = fastArrayListOf(Rectangle(Point.ZERO, maxSize)) override fun add(size: Size): Rectangle? = quickInsert(size) fun quickInsert(size: Size): Rectangle? { val (width, height) = size if (width <= 0.0 && height <= 0.0) return Rectangle(0, 0, 0, 0) val newNode = quickFindPositionForNewNodeBestAreaFit(width, height) if (newNode.height == 0.0) return null var numRectanglesToProcess = freeRectangles.size var i = 0 while (i < numRectanglesToProcess) { if (splitFreeNode(freeRectangles[i], newNode)) { freeRectangles.removeAt(i) --numRectanglesToProcess --i } i++ } pruneFreeList() return newNode } private fun quickFindPositionForNewNodeBestAreaFit(width: Double, height: Double): Rectangle { var score = Double.MAX_VALUE var areaFit: Double var bestNode = Rectangle() for (r in freeRectangles) { // Try to place the rectangle in upright (non-flipped) orientation. if (r.width >= width && r.height >= height) { areaFit = (r.width * r.height - width * height).toDouble() if (areaFit < score) { bestNode = Rectangle(r.x, r.y, width, height) score = areaFit } } } return bestNode } private fun splitFreeNode(freeNode: Rectangle, usedNode: Rectangle): Boolean { var newNode: Rectangle // Test with SAT if the rectangles even intersect. if (usedNode.left >= freeNode.right || usedNode.right <= freeNode.x || usedNode.top >= freeNode.bottom || usedNode.bottom <= freeNode.top) { return false } if (usedNode.x < freeNode.right && usedNode.right > freeNode.x) { // New node at the top side of the used node. if (usedNode.y > freeNode.y && usedNode.y < freeNode.bottom) { newNode = freeNode.copy(height = usedNode.y - freeNode.y) freeRectangles.add(newNode) } // New node at the bottom side of the used node. if (usedNode.bottom < freeNode.bottom) { newNode = freeNode.copy( y = usedNode.bottom, height = freeNode.bottom - usedNode.bottom ) freeRectangles.add(newNode) } } if (usedNode.y < freeNode.bottom && usedNode.bottom > freeNode.y) { // New node on the left side of the used node. if (usedNode.x > freeNode.x && usedNode.x < freeNode.right) { newNode = freeNode.copy(width = usedNode.x - freeNode.x) freeRectangles.add(newNode) } // New node on the right side of the used node. if (usedNode.right < freeNode.right) { newNode = freeNode.copy( x = usedNode.right, width = freeNode.right - usedNode.right ) freeRectangles.add(newNode) } } return true } private fun pruneFreeList() { // Go through each pair and remove any rectangle that is redundant. var len = freeRectangles.size var i = 0 while (i < len) { var j = i + 1 val tmpRect = freeRectangles[i] while (j < len) { val tmpRect2 = freeRectangles[j] if (Rectangle.isContainedIn(tmpRect, tmpRect2)) { freeRectangles.removeAt(i) --i --len break } if (Rectangle.isContainedIn(tmpRect2, tmpRect)) { freeRectangles.removeAt(j) --len --j } j++ } i++ } } }
444
WebAssembly
121
2,207
dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a
9,796
korge
Apache License 2.0
src/main/kotlin/aoc2018/day12/Pots.kt
arnab
75,525,311
false
null
package aoc2018.day12 data class Pots(val initialState: String, val rules: Map<CharSequence, CharSequence>) { fun sumAfterNGenerations(numGenerations: Long): Long { val seen = mutableMapOf<String, Pair<Long, Long>>() var offset = 0L var state = initialState var i = 0L while (i < numGenerations) { seen[state] = i to offset state = "....$state....".windowed(5) { rules.getOrElse(it) { "." } } .joinToString(separator = "") .dropLastWhile { it != '#' } .apply { offset += indexOf('#') - 2 } .dropWhile { it != '#' } i++ val (previousI, previousOffset) = seen[state] ?: continue offset += (numGenerations - i) / (i - previousI) * (offset - previousOffset) i = numGenerations - (numGenerations - i) % (i - previousI) } return state.withIndex().fold(0L) { acc, (i, c) -> if (c == '#') acc + offset + i else acc } } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
1,032
adventofcode
MIT License
src/main/kotlin/com/sergeysav/voxel/common/block/impl/Log.kt
SergeySave
260,611,748
false
null
package com.sergeysav.voxel.common.block.impl import com.sergeysav.voxel.common.block.state.AxialBlockState import com.sergeysav.voxel.common.block.state.BlockState import com.sergeysav.voxel.common.data.Direction /** * @author sergeys * * @constructor Creates a new Log */ object Log : BaseBlock<AxialBlockState>("log") { val states = AxialBlockState.states override fun getStateFromSimpleValue(value: Byte): AxialBlockState = AxialBlockState.states[value.toInt() and 0xFF] override fun getSimpleValueForState(state: AxialBlockState): Byte = state.axis.ordinal.toByte() }
0
Kotlin
0
0
446f91f11661f1b87e1fb7b2f533f9e24b45704e
593
Voxel
MIT License
webserver/src/main/kotlin/net/corda/tools/error/codes/server/web/Options.kt
isabella232
474,550,367
true
{"Kotlin": 114301, "Dockerfile": 491}
package net.corda.tools.error.codes.server.web import com.uchuhimo.konf.Config import com.uchuhimo.konf.ConfigSpec import net.corda.tools.error.codes.server.commons.domain.Port import javax.inject.Inject import javax.inject.Named @Named internal class Options @Inject constructor(applyConfigStandards: (Config) -> Config) : WebServer.Options { private companion object { private const val CONFIGURATION_SECTION_PATH = "configuration.web.server" private object Spec : ConfigSpec(CONFIGURATION_SECTION_PATH) { val port by required<Int>() } } private val config = applyConfigStandards.invoke(Config { addSpec(Spec) }) override val port: Port = Port(config[Spec.port]) }
0
null
0
0
7bc7fcc3d7e3a51a531b2988b7d3ca691272e12b
726
error-codes-web-app
Apache License 2.0
src/main/kotlin/no/nav/amt/deltaker/bff/deltaker/model/Deltakelsesinnhold.kt
navikt
701,285,451
false
{"Kotlin": 454916, "PLpgSQL": 635, "Dockerfile": 194}
package no.nav.amt.deltaker.bff.deltaker.model data class Deltakelsesinnhold( val ledetekst: String?, val innhold: List<Innhold>, ) data class Innhold( val tekst: String, val innholdskode: String, val valgt: Boolean, val beskrivelse: String?, )
1
Kotlin
0
0
a6d96147a5e89dddd8e4cf42d0f840d93acdf19e
271
amt-deltaker-bff
MIT License
feature_albums/src/main/java/com/wassim/showcase/featurealbums/view/item/view/AlbumViewModel.kt
WassimBenltaief
275,135,668
false
null
package com.wassim.showcase.featurealbums.view.item.view import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.wassim.showcase.R import com.wassim.showcase.core.data.remote.Album import com.wassim.showcase.featurealbums.view.item.SingleAlbumUiState import com.wassim.showcase.featurealbums.view.item.usecase.GetAlbumInfoUseCase import com.wassim.showcase.featurealbums.view.item.usecase.SaveAlbumUseCase import com.wassim.showcase.featurealbums.view.toUiModel import com.wassim.showcase.utils.Result import javax.inject.Inject import kotlinx.coroutines.launch class AlbumViewModel @Inject constructor( private val getAlbumInfo: GetAlbumInfoUseCase, private val saveAlbum: SaveAlbumUseCase ) : ViewModel() { private val _album = MutableLiveData<Album?>(null) private val _state = MutableLiveData<SingleAlbumUiState>( SingleAlbumUiState.Loading ) val uiState: LiveData<SingleAlbumUiState> get() = _state fun findAlbum( albumId: String, album: String, artist: String ) = viewModelScope.launch { when (val result = getAlbumInfo(albumId, album, artist)) { is Result.Success -> { _album.value = result.data _state.value = SingleAlbumUiState.Content(album = result.data.toUiModel()) } is Result.Error -> { _state.value = SingleAlbumUiState.SnackBar( resId = R.string.generic_single_album_error ) } } } fun markAsFavorite() = viewModelScope.launch { _album.value?.let { when (saveAlbum(it)) { is Result.Success -> _state.value = SingleAlbumUiState.SnackBar( resId = R.string.marked_as_favorite ) is Result.Error -> _state.value = SingleAlbumUiState.SnackBar( resId = R.string.unable_to_mark_album_as_favorite ) } } } }
0
Kotlin
0
0
91a8a266bdc8578e56d7514a70270bd1ad02836a
2,104
albums
Apache License 2.0
src/test/kotlin/io/github/grassmc/mcdev/gradle/McdevPlatformPluginTests.kt
GrassMC
603,643,726
false
null
/* * Copyright 2023 GrassMC * * 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.github.grassmc.mcdev.gradle import io.github.grassmc.mcdev.gradle.ProxyVendor.* import io.github.grassmc.mcdev.gradle.ServerVendor.* import io.github.grassmc.mcdev.gradle.extensions.CommonRepositories import io.github.grassmc.mcdev.gradle.extensions.MinecraftRepositories import io.github.grassmc.mcdev.gradle.version.MinecraftVersion import org.junit.jupiter.api.BeforeEach import kotlin.test.Test class McdevSpigotPluginTest { private lateinit var tester: PlatformPluginTester @BeforeEach fun setUp() { tester = PlatformPluginTester(SpigotMC) } @Test fun `plugin register extensions`() = tester.testRegister() @Test fun `plugin project extension with default values`() = tester.testExtension(MinecraftVersion.LATEST) @Test fun `plugin with default repositories`() = tester.testRepositories(CommonRepositories.SONATYPE.name, MinecraftRepositories.SPIGOT_MC.name) @Test fun `plugin with default dependencies`() = tester.testDependencies(MinecraftVersion.LATEST) } class McdevPaperPluginTest { private lateinit var tester: PlatformPluginTester @BeforeEach fun setUp() { tester = PlatformPluginTester(PaperMC) } @Test fun `plugin register extensions`() = tester.testRegister() @Test fun `plugin project extension with default values`() = tester.testExtension(MinecraftVersion.LATEST) @Test fun `plugin with default repositories`() = tester.testRepositories(MinecraftRepositories.PAPER_MC.name) @Test fun `plugin with default dependencies`() = tester.testDependencies(MinecraftVersion.LATEST) } class McdevPurpurPluginTest { private lateinit var tester: PlatformPluginTester @BeforeEach fun setUp() { tester = PlatformPluginTester(PurpurMC) } @Test fun `plugin register extensions`() = tester.testRegister() @Test fun `plugin project extension with default values`() = tester.testExtension(MinecraftVersion.LATEST) @Test fun `plugin with default repositories`() = tester.testRepositories(MinecraftRepositories.PURPUR_MC.name) @Test fun `plugin with default dependencies`() = tester.testDependencies(MinecraftVersion.LATEST) } class McdevVelocityPluginTest { private lateinit var tester: PlatformPluginTester @BeforeEach fun setUp() { tester = PlatformPluginTester(Velocity) } @Test fun `plugin register extensions`() = tester.testRegister() @Test fun `plugin project extension with default values`() = tester.testExtension(McdevVelocityPlugin.VELOCITY_API_LATEST_VERSION) @Test fun `plugin with default repositories`() = tester.testRepositories(MinecraftRepositories.PAPER_MC.name) @Test fun `plugin with default dependencies`() = tester.testDependencies(McdevVelocityPlugin.VELOCITY_API_LATEST_VERSION) } class McdevBungeeCordPluginTest { private lateinit var tester: PlatformPluginTester @BeforeEach fun setUp() { tester = PlatformPluginTester(BungeeCord) } @Test fun `plugin register extensions`() = tester.testRegister() @Test fun `plugin project extension with default values`() = tester.testExtension(McdevBungeeCordPlugin.BUNGEECORD_API_LATEST_VERSION) @Test fun `plugin with default repositories`() = tester.testRepositories(CommonRepositories.SONATYPE.name) @Test fun `plugin with default dependencies`() = tester.testDependencies(McdevBungeeCordPlugin.BUNGEECORD_API_LATEST_VERSION) } class McdevWaterfallPluginTest { private lateinit var tester: PlatformPluginTester @BeforeEach fun setUp() { tester = PlatformPluginTester(Waterfall) } @Test fun `plugin register extensions`() = tester.testRegister() @Test fun `plugin project extension with default values`() = tester.testExtension(McdevBungeeCordPlugin.BUNGEECORD_API_LATEST_VERSION) @Test fun `plugin with default repositories`() = tester.testRepositories(MinecraftRepositories.PAPER_MC.name) @Test fun `plugin with default dependencies`() = tester.testDependencies(McdevBungeeCordPlugin.BUNGEECORD_API_LATEST_VERSION) }
4
Kotlin
0
0
236acac52c9008ec011ae692e198e42c7fd3de09
4,806
mcdev-gradle-plugin
Apache License 2.0
droidbox/src/main/java/com/github/giacomoparisi/droidbox/recycler/ViewHolderFactory.kt
giacomoParisi
106,693,190
false
null
package com.github.giacomoparisi.droidbox.recycler import androidx.databinding.ViewDataBinding /** * Created by <NAME> on 10/04/17. * https://github.com/giacomoParisi */ /** * * Factory class used to create a DroidViewHolder for a specifc item * Every DroidItem need this */ interface ViewHolderFactory<in B : ViewDataBinding, D: DroidItem> { /** * * Create a DroidViewHolder instance for the specific item ViewDataBinding * * @param binding The ViewDataBinding object of the DroidItem */ fun newInstance(binding: B): DroidViewHolder<D> }
0
Kotlin
0
0
58b6b6a5a47dd3e01fccf64f51ab41919797e307
583
DroidBox
Apache License 2.0
app/src/main/java/com/microsoft/device/samples/dualscreenexperience/presentation/store/list/StoreListFragment.kt
microsoft
333,507,793
false
{"Kotlin": 626561, "HTML": 33449}
/* * * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. * */ package com.microsoft.device.samples.dualscreenexperience.presentation.store.list import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import com.microsoft.device.samples.dualscreenexperience.R import com.microsoft.device.samples.dualscreenexperience.databinding.FragmentStoreListBinding import com.microsoft.device.samples.dualscreenexperience.presentation.store.StoreViewModel import com.microsoft.device.samples.dualscreenexperience.presentation.util.appCompatActivity import com.microsoft.device.samples.dualscreenexperience.presentation.util.changeToolbarTitle import com.microsoft.device.samples.dualscreenexperience.presentation.util.setupToolbar class StoreListFragment : Fragment() { private val viewModel: StoreViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentStoreListBinding.inflate(inflater, container, false) binding.lifecycleOwner = this binding.viewModel = viewModel val recyclerView = binding.storeList val storeAdapter = StoreAdapter(requireContext(), viewModel) recyclerView.adapter = storeAdapter viewModel.visibleStoresList.observe(viewLifecycleOwner) { binding.isListEmpty = it.isNullOrEmpty() storeAdapter.refreshData() } setupObservers() return binding.root } private fun setupObservers() { viewModel.selectedStore.observe(viewLifecycleOwner) { if (it == null && viewModel.selectedCity.value != null) { setupToolbar() } } } override fun onResume() { super.onResume() setupToolbar() } private fun setupToolbar() { appCompatActivity?.setupToolbar(isBackButtonEnabled = true, viewLifecycleOwner) { viewModel.navigateUp() } appCompatActivity?.changeToolbarTitle(getString(R.string.toolbar_stores_title)) } }
1
Kotlin
6
29
76577bf9cb72fc5cadd0170652936cd7fc30e3f5
2,293
surface-duo-dual-screen-experience-example
MIT License
app/src/main/java/fr/lenny/dronemonitorv2/ui/screens/app_nav/NavBarViewModel.kt
Embedded-MUTEX-1
750,752,672
false
{"Kotlin": 81898}
package fr.lenny.dronemonitorv2.ui.screens.app_nav import android.app.usage.UsageEvents import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.LineDataSet import com.google.gson.JsonSyntaxException import dagger.hilt.android.lifecycle.HiltViewModel import fr.lenny.dronemonitorv2.DRONE_UDP_PORT import fr.lenny.dronemonitorv2.data.repository.drone.DroneRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import java.net.SocketTimeoutException import javax.inject.Inject @HiltViewModel class NavBarViewModel @Inject constructor( private val droneRepository: DroneRepository ): ViewModel() { val _ipAddrText = MutableStateFlow("192.168.1.113") val ipAddrText = _ipAddrText.asStateFlow() val _buttonState = MutableStateFlow(false) val buttonState = _buttonState.asStateFlow() var isRunning = false var isReceiving = false val _event = MutableStateFlow(EventType.NONE) val event = _event.asStateFlow() init { viewModelScope.launch(Dispatchers.IO) { while (true) { if(isRunning) { try { isReceiving = true droneRepository.processData() isReceiving = false } catch (e: JsonSyntaxException) { _event.emit(EventType.JSON_ERR) _buttonState.value = false isRunning = false isReceiving = false droneRepository.closeSocket() } catch (e: SocketTimeoutException) { _event.emit(EventType.TIMEOUT_ERR) _buttonState.value = false isRunning = false isReceiving = false droneRepository.closeSocket() } } delay(100) } } } fun updateTextField(text: String) { _ipAddrText.value = text } fun setDroneIpaddr() { viewModelScope.launch(Dispatchers.IO) { if(!_buttonState.value) { droneRepository.setDroneIpAndPort(ipAddrText.value) _buttonState.value = true isRunning = true } else { while(isReceiving); isRunning = false droneRepository.closeSocket() _buttonState.value = false } } } }
0
Kotlin
0
0
96d04ede88392bff4e643e041f0068167c298a5d
2,923
DroneMonitoringApp
MIT License
bukkit/rpk-permissions-bukkit/src/main/kotlin/com/rpkit/permissions/bukkit/database/table/RPKCharacterGroupTable.kt
RP-Kit
54,840,905
false
null
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.rpkit.permissions.bukkit.database.table import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.characters.bukkit.character.RPKCharacterId import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.core.service.Services import com.rpkit.permissions.bukkit.RPKPermissionsBukkit import com.rpkit.permissions.bukkit.database.create import com.rpkit.permissions.bukkit.database.jooq.Tables.RPKIT_CHARACTER_GROUP import com.rpkit.permissions.bukkit.group.RPKCharacterGroup import com.rpkit.permissions.bukkit.group.RPKGroup import com.rpkit.permissions.bukkit.group.RPKGroupName import com.rpkit.permissions.bukkit.group.RPKGroupService import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.runAsync import java.util.logging.Level import java.util.logging.Level.SEVERE class RPKCharacterGroupTable(private val database: Database, private val plugin: RPKPermissionsBukkit) : Table { data class CharacterGroupCacheKey( val characterId: Int, val groupName: String ) val cache = if (plugin.config.getBoolean("caching.rpkit_character_group.character_id.enabled")) { database.cacheManager.createCache( "rpk-permissions-bukkit.rpkit_character_group.character_id", CharacterGroupCacheKey::class.java, RPKCharacterGroup::class.java, plugin.config.getLong("caching.rpkit_character_group.character_id.size") ) } else { null } fun insert(entity: RPKCharacterGroup): CompletableFuture<Void> { val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null) val groupName = entity.group.name return runAsync { database.create .insertInto( RPKIT_CHARACTER_GROUP, RPKIT_CHARACTER_GROUP.CHARACTER_ID, RPKIT_CHARACTER_GROUP.GROUP_NAME, RPKIT_CHARACTER_GROUP.PRIORITY ) .values( characterId.value, groupName.value, entity.priority ) .execute() cache?.set(CharacterGroupCacheKey(characterId.value, groupName.value), entity) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to insert character group", exception) throw exception } } fun update(entity: RPKCharacterGroup): CompletableFuture<Void> { val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null) val groupName = entity.group.name return runAsync { database.create .update(RPKIT_CHARACTER_GROUP) .set(RPKIT_CHARACTER_GROUP.PRIORITY, entity.priority) .where(RPKIT_CHARACTER_GROUP.CHARACTER_ID.eq(characterId.value)) .and(RPKIT_CHARACTER_GROUP.GROUP_NAME.eq(entity.group.name.value)) .execute() cache?.set(CharacterGroupCacheKey(characterId.value, groupName.value), entity) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to update character group", exception) throw exception } } operator fun get(character: RPKCharacter, group: RPKGroup): CompletableFuture<RPKCharacterGroup?> { val characterId = character.id ?: return CompletableFuture.completedFuture(null) val groupName = group.name val cacheKey = CharacterGroupCacheKey(characterId.value, groupName.value) if (cache?.containsKey(cacheKey) == true) { return CompletableFuture.completedFuture(cache[cacheKey]) } return CompletableFuture.supplyAsync { val result = database.create .select(RPKIT_CHARACTER_GROUP.PRIORITY) .from(RPKIT_CHARACTER_GROUP) .where(RPKIT_CHARACTER_GROUP.CHARACTER_ID.eq(characterId.value)) .and(RPKIT_CHARACTER_GROUP.GROUP_NAME.eq(groupName.value)) .fetchOne() ?: return@supplyAsync null val characterGroup = RPKCharacterGroup( character, group, result[RPKIT_CHARACTER_GROUP.PRIORITY] ) cache?.set(cacheKey, characterGroup) return@supplyAsync characterGroup }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get character group", exception) throw exception } } fun get(character: RPKCharacter): CompletableFuture<List<RPKCharacterGroup>> { val characterId = character.id ?: return CompletableFuture.completedFuture(emptyList()) return CompletableFuture.supplyAsync { return@supplyAsync database.create .select( RPKIT_CHARACTER_GROUP.GROUP_NAME, RPKIT_CHARACTER_GROUP.PRIORITY ) .from(RPKIT_CHARACTER_GROUP) .where(RPKIT_CHARACTER_GROUP.CHARACTER_ID.eq(characterId.value)) .orderBy(RPKIT_CHARACTER_GROUP.PRIORITY.desc()) .fetch() .mapNotNull { result -> val group = result[RPKIT_CHARACTER_GROUP.GROUP_NAME] .let { Services[RPKGroupService::class.java]?.getGroup(RPKGroupName(it)) } ?: return@mapNotNull null RPKCharacterGroup( character, group, result[RPKIT_CHARACTER_GROUP.PRIORITY] ) } }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get character groups", exception) throw exception } } fun delete(entity: RPKCharacterGroup): CompletableFuture<Void> { val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null) val groupName = entity.group.name return runAsync { database.create .deleteFrom(RPKIT_CHARACTER_GROUP) .where(RPKIT_CHARACTER_GROUP.CHARACTER_ID.eq(characterId.value)) .and(RPKIT_CHARACTER_GROUP.GROUP_NAME.eq(groupName.value)) .execute() cache?.set(CharacterGroupCacheKey(characterId.value, groupName.value), entity) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to delete character group", exception) throw exception } } fun delete(characterId: RPKCharacterId): CompletableFuture<Void> = runAsync { database.create .deleteFrom(RPKIT_CHARACTER_GROUP) .where(RPKIT_CHARACTER_GROUP.CHARACTER_ID.eq(characterId.value)) .execute() cache?.removeMatching { it.character.id?.value == characterId.value } }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to delete character groups for character id", exception) throw exception } }
69
null
9
22
aee4060598dc25cd8e4f3976ed5e70eb1bf874a2
7,731
RPKit
Apache License 2.0
src/main/kotlin/com/mylosoftworks/kpython/environment/pythonobjects/PyList.kt
Mylo-Softworks
832,296,602
false
{"Kotlin": 81729}
package com.mylosoftworks.kpython.environment.pythonobjects import com.mylosoftworks.kpython.proxy.DontUsePython import com.mylosoftworks.kpython.proxy.GCBehavior import com.mylosoftworks.kpython.proxy.KPythonProxy import com.mylosoftworks.kpython.proxy.PythonProxyObject import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong interface PyList : KPythonProxy { fun append(item: Any?) fun clear() fun copy(): PyList fun count(value: Any?): Int fun extend(other: PyList) fun insert(index: Int, value: Any?) fun pop(index: Int): Any? fun remove(value: Any?) fun reverse() fun sort(reverse: Boolean = false, key: ((Any?) -> Int)? = null) fun index(key: Int): PythonProxyObject @DontUsePython fun size(): Long @DontUsePython operator fun get(key: Long): PythonProxyObject @DontUsePython operator fun set(key: Long, value: Any?) @DontUsePython operator fun iterator(): Iterator<PythonProxyObject> companion object { fun size(self: PythonProxyObject): Long { return self.env.quickAccess.listGetSize(self) // return self.let { // it.env.engine.PyList_Size(it.obj) // } } fun get(self: PythonProxyObject, key: Long): PythonProxyObject { return self.env.quickAccess.listGetItem(self, key) // return self.let { // it.env.engine.PyList_GetItem(self.obj, key.toLong())?.let { it2 -> // it.env.createProxyObject(it2, GCBehavior.IGNORE) // Borrowed // } // } } fun set(self: PythonProxyObject, key: Long, value: Any?) { self.env.quickAccess.listSetItem(self, key, value) // self.env.engine.PyList_SetItem(self.obj, key.toLong(), value.obj) } fun iterator(self: PythonProxyObject): Iterator<PythonProxyObject?> { return PythonListIterator(self.asInterface<PyList>()) } } } class PythonListIterator(val list: PyList) : Iterator<PythonProxyObject?> { val idx = AtomicLong(0) val size = list.size() override fun hasNext(): Boolean { return idx.get() < size } override fun next(): PythonProxyObject { return list[idx.getAndIncrement()] } }
0
Kotlin
0
0
a71e0d9ba7671754772ac83ae5878becf69aa540
2,327
KPython
MIT License
presentation-map/src/main/java/com/jacekpietras/zoo/map/extensions/MapViewLogicExtensions.kt
JacekPietras
334,416,736
false
null
package com.jacekpietras.zoo.map.extensions import com.jacekpietras.mapview.model.ComposablePaint import com.jacekpietras.mapview.ui.MapViewLogic import com.jacekpietras.zoo.map.model.MapVolatileViewState import com.jacekpietras.zoo.map.model.MapWorldViewState internal fun MapViewLogic<ComposablePaint>.applyToMap(viewState: MapWorldViewState) { worldData = MapViewLogic.WorldData( bounds = viewState.worldBounds, objectList = viewState.mapData, ) } internal fun MapViewLogic<ComposablePaint>.applyToMap(viewState: MapVolatileViewState) { userData = MapViewLogic.UserData( userPosition = viewState.userPosition, compass = viewState.compass, objectList = viewState.mapData, ) }
0
Kotlin
1
1
80ad5284561109264eac85e6593bfe5be77c3893
737
ZOO
MIT License
app/src/main/kotlin/org/hertsig/commander/interaction/GlobalKeyboardListener.kt
jorn86
481,216,861
false
{"Kotlin": 41958}
package org.hertsig.commander.interaction import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.input.key.* import org.hertsig.commander.ui.FolderPanel @OptIn(ExperimentalComposeUiApi::class) class GlobalKeyboardListener( private val ui: FolderPanel, private val focusManager: FocusManager, private val focusDirectionForTab: FocusDirection, ) : (KeyEvent) -> Boolean { override fun invoke(event: KeyEvent): Boolean { if (event.type == KeyEventType.KeyDown) { when (event.key) { Key.Backspace -> ui.back() Key.Delete -> ui.onDelete() Key.DirectionUp -> focusManager.moveFocus(FocusDirection.Up) Key.DirectionDown -> focusManager.moveFocus(FocusDirection.Down) Key.DirectionLeft -> focusManager.moveFocus(FocusDirection.Left) Key.DirectionRight -> focusManager.moveFocus(FocusDirection.Right) } } return false } }
0
Kotlin
0
0
7bd4922a9cdb9054982984336c225efef174637b
1,097
commander
MIT License
core/src/main/kotlin/com/github/dod/doddy/db/Db.kt
Devs-On-Discord
145,478,771
false
null
package com.github.dod.doddy.db import org.litote.kmongo.async.KMongo object Db { val client = KMongo.createClient() val instance = client.getDatabase("mongo") }
0
Kotlin
6
10
428bf7468b69f7ab24fc1b24103ff48bff1c184a
171
DoDdy
MIT License
app/src/main/java/com/yuchen/howyo/home/notification/NotificationType.kt
ione0213
418,168,888
false
null
package com.yuchen.howyo.home.notification import com.yuchen.howyo.R import com.yuchen.howyo.util.Util.getString enum class NotificationType(val type: String) { LIKE(getString(R.string.notification_like_type)), FOLLOW(getString(R.string.notification_follow_type)) }
0
Kotlin
0
0
481104d1a79bd7c9e761ce6c5c7d28aa94b6aaa6
276
HowYo
MIT License
decoder/src/commonMain/kotlin/io/github/charlietap/chasm/decoder/decoder/type/number/NumberTypeDecoder.kt
CharlieTap
743,980,037
false
null
package io.github.charlietap.chasm.decoder.decoder.type.number import com.github.michaelbull.result.Err import com.github.michaelbull.result.Result import com.github.michaelbull.result.binding import io.github.charlietap.chasm.ast.type.NumberType import io.github.charlietap.chasm.decoder.context.DecoderContext import io.github.charlietap.chasm.decoder.error.TypeDecodeError import io.github.charlietap.chasm.decoder.error.WasmDecodeError internal fun NumberTypeDecoder( context: DecoderContext, ): Result<NumberType, WasmDecodeError> = binding { when (val encoded = context.reader.ubyte().bind()) { NUMBER_TYPE_I32 -> NumberType.I32 NUMBER_TYPE_I64 -> NumberType.I64 NUMBER_TYPE_F32 -> NumberType.F32 NUMBER_TYPE_F64 -> NumberType.F64 else -> Err(TypeDecodeError.InvalidNumberType(encoded)).bind<NumberType>() } } internal const val NUMBER_TYPE_I32: UByte = 0x7Fu internal const val NUMBER_TYPE_I64: UByte = 0x7Eu internal const val NUMBER_TYPE_F32: UByte = 0x7Du internal const val NUMBER_TYPE_F64: UByte = 0x7Cu
5
null
3
67
dd6fa51262510ecc5ee5b03866b3fa5d1384433b
1,071
chasm
Apache License 2.0
app/src/androidTest/java/com/nicolasguillen/kointlin/utils/LocaleUtil.kt
nicolasguillen
113,652,016
false
{"Kotlin": 96449, "Ruby": 5242}
package com.nicolasguillen.kointlin.utils import android.content.res.Configuration import android.os.Build import android.util.Log import androidx.test.InstrumentationRegistry import java.util.* object LocaleUtil { private val TAG = LocaleUtil::class.java.simpleName val testLocale: Locale? get() = localeFromInstrumentation("testLocale") val endingLocale: Locale? get() = localeFromInstrumentation("endingLocale") fun changeDeviceLocaleTo(locale: Locale?) { if (locale == null) { Log.w(TAG, "Skipping setting device locale to null") } else { try { var amnClass = Class.forName("android.app.ActivityManagerNative") val methodGetDefault = amnClass.getMethod("getDefault") methodGetDefault.isAccessible = true val activityManagerNative = methodGetDefault.invoke(amnClass) if (Build.VERSION.SDK_INT >= 26) { amnClass = Class.forName(activityManagerNative.javaClass.name) } val methodGetConfiguration = amnClass.getMethod("getConfiguration") methodGetConfiguration.isAccessible = true val config = methodGetConfiguration.invoke(activityManagerNative) as Configuration config.javaClass.getField("userSetLocale").setBoolean(config, true) config.locale = locale if (Build.VERSION.SDK_INT >= 17) { config.setLayoutDirection(locale) } val updateConfigurationMethod = amnClass.getMethod("updateConfiguration", Configuration::class.java) updateConfigurationMethod.isAccessible = true updateConfigurationMethod.invoke(activityManagerNative, config) Log.d(TAG, "Locale changed to $locale") } catch (var7: Exception) { Log.e(TAG, "Failed to change device locale to $locale", var7) throw RuntimeException(var7) } } } fun localePartsFrom(localeString: String?): Array<String>? { if (localeString == null) { return null } else { val localeParts = localeString.split("_".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() return if (localeParts.size >= 1 && localeParts.size <= 3) localeParts else null } } fun localeFromParts(localeParts: Array<String>?): Locale? { return if (localeParts != null && localeParts.size != 0) { if (localeParts.size == 1) { Locale(localeParts[0]) } else { if (localeParts.size == 2) Locale(localeParts[0], localeParts[1]) else Locale(localeParts[0], localeParts[1], localeParts[2]) } } else { null } } private fun localeFromInstrumentation(key: String): Locale? { val localeString = InstrumentationRegistry.getArguments().getString(key) return localeFromParts(localePartsFrom(localeString)) } }
2
Kotlin
0
2
569c5817777ad75d052221a51ea56f8916590e56
3,080
kointlin
Apache License 2.0
kotlin/extensions/src/main/kotlin/org/sollecitom/chassis/kotlin/extensions/duration/DurationExtensions.kt
sollecitom
669,483,842
false
null
package org.sollecitom.chassis.kotlin.extensions.duration import kotlin.time.Duration import kotlin.time.Duration.Companion.days val Int.weeks: Duration get() = (this * 7).days
0
null
0
2
a9ffd2d2fd649fc1c967098da9add4aac73a74b0
178
chassis
MIT License
app/src/main/java/sarmisdead/a7minutesworkout/FinishActivity.kt
Sarmisdead
519,865,069
false
{"Kotlin": 31682}
package sarmisdead.a7minutesworkout import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.launch import sarmisdead.a7minutesworkout.databinding.ActivityFinishBinding import java.text.SimpleDateFormat import java.util.* class FinishActivity : AppCompatActivity() { private var binding : ActivityFinishBinding? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityFinishBinding.inflate(layoutInflater) setContentView(binding?.root) setSupportActionBar(binding?.toolbarFinishActivity) if(supportActionBar != null){ supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = "7 MINUTES YOGA" } //End of if binding?.toolbarFinishActivity?.setNavigationOnClickListener { onBackPressed() } //End of SetNavigationOnClickListener binding?.btnFinish?.setOnClickListener{ finish() } //End of setOnClickListener val dao = (application as YogaApp).db.historyDao() addDateToDatabase(dao) } //End of onCreate private fun addDateToDatabase(historyDao: HistoryDao){ val myCalendar = Calendar.getInstance() val dateTime = myCalendar.time Log.e("Date: ", "" +dateTime) val sdf = SimpleDateFormat("dd MMM yyyy HH:mm:ss", Locale.getDefault()) val date = sdf.format(dateTime) Log.e("Formatted Date : ", "" + date) lifecycleScope.launch { historyDao.insert(HistoryEntity(date)) Log.e( "Date : ", "Added...") } //End of LifecycleScope } //End of addDateToDatabase } //End of FinishActivity
0
Kotlin
0
0
7cd8fd597fed8db2cc4b827bdaccb2fc09e43fb2
1,830
7MinutesYogaApp
MIT License
server/src/main/kotlin/dev/kdrag0n/quicklock/server/Data.kt
kdrag0n
512,900,415
false
{"Kotlin": 127083, "JavaScript": 94229, "Rust": 88205, "TypeScript": 53751, "Java": 43766, "Shell": 4854, "HTML": 1777, "CSS": 930}
package dev.kdrag0n.quicklock.server import kotlinx.serialization.Serializable import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream @Serializable object EmptyObject fun java.io.Serializable.serializeToByteArray(): ByteArray { val bos = ByteArrayOutputStream() ObjectOutputStream(bos).use { it.writeObject(this) it.flush() return bos.toByteArray() } } fun ByteArray.decodeSerializable(): Any? { val bis = ByteArrayInputStream(this) return ObjectInputStream(bis).use { it.readObject() } }
0
Kotlin
0
2
86297ee58e0a757a4542bca9efb1a4b8961d3f0c
634
quicklock
MIT License
app/src/main/java/com/kondroid/sampleproject/dto/websocket/WebSocketActionDto.kt
kondroid00
104,654,160
false
null
package com.kondroid.sampleproject.dto.websocket /** * Created by kondo on 2017/10/19. */ data class WebSocketActionDto(val clients: List<WebSocketActionDto.Client>) { data class Client(val clientNo: Int, val name: String?, val action: Boolean, val self: Boolean) }
0
Kotlin
0
0
3892ddf080a44472f0e4997f79020729e33b7658
339
SampleProject_Android
MIT License
room/src/main/java/com/kodyuzz/room/di/module/ActivityModule.kt
mustafaatush
274,828,691
false
null
package com.kodyuzz.room.di.module import android.app.Activity import android.content.Context import com.kodyuzz.room.di.qualifier.ActivityContext import dagger.Module import dagger.Provides @Module class ActivityModule(var activity: Activity) { @ActivityContext @Provides fun getActivityContext(): Context = activity }
0
Kotlin
0
0
a946972fe26c3ed8bb2abc69be6a72af976320c1
340
kodyuzz
Apache License 2.0
sphereon-kmp-crypto/src/commonMain/kotlin/com/sphereon/crypto/jose/Jwk.kt
Sphereon-Opensource
832,677,457
false
{"Kotlin": 532209, "JavaScript": 3855}
package com.sphereon.crypto.jose import com.sphereon.crypto.cose.CoseKeyCbor import com.sphereon.crypto.cose.CoseKeyJson import com.sphereon.crypto.cose.ICoseKeyCbor import com.sphereon.crypto.cose.ICoseKeyJson import com.sphereon.crypto.IKey import com.sphereon.crypto.toCoseCurve import com.sphereon.crypto.toCoseKeyOperations import com.sphereon.crypto.toCoseKeyType import com.sphereon.crypto.toCoseSignatureAlgorithm import com.sphereon.crypto.toJoseCurve import com.sphereon.crypto.toJoseKeyOperations import com.sphereon.crypto.toJoseKeyType import com.sphereon.crypto.toJoseSignatureAlgorithm import com.sphereon.json.cryptoJsonSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlin.js.JsExport /** * JWK [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517#section-4). * * ordered alphabetically [RFC7638 s3](https://www.rfc-editor.org/rfc/rfc7638.html#section-3) */ expect interface IJwkJson : IKey { override val alg: String? override val crv: String? override val d: String? val e: String? val k: String? override val key_ops: Array<String>? override val kid: String? override val kty: String val n: String? val use: String? override val x: String? val x5c: Array<String>? val x5t: String? val x5u: String? @SerialName("x5t#S256") val x5t_S256: String? override val y: String? } /** * JWK [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517#section-4). * * ordered alphabetically [RFC7638 s3](https://www.rfc-editor.org/rfc/rfc7638.html#section-3) */ expect interface IJwk : IKey { override val alg: JwaAlgorithm? override val crv: JwaCurve? override val d: String? val e: String? val k: String? override val key_ops: Array<JoseKeyOperations>? override val kid: String? override val kty: JwaKeyType val n: String? val use: String? override val x: String? val x5c: Array<String>? val x5t: String? val x5u: String? @SerialName("x5t#S256") val x5t_S256: String? override val y: String? } @JsExport @Serializable data class Jwk( override val alg: JwaAlgorithm? = null, override val crv: JwaCurve? = null, override val d: String? = null, override val e: String? = null, override val k: String? = null, override val key_ops: Array<JoseKeyOperations>? = null, override val kid: String? = null, override val kty: JwaKeyType, override val n: String? = null, override val use: String? = null, override val x: String? = null, override val x5c: Array<String>? = null, override val x5t: String? = null, override val x5u: String? = null, @SerialName("x5t#S256") override val x5t_S256: String? = null, override val y: String? = null, ) : IJwk { override val additional: JsonObject? get() = TODO("Not yet implemented") class Builder { var alg: JwaAlgorithm? = null var crv: JwaCurve? = null var d: String? = null var e: String? = null var k: String? = null var key_ops: Array<JoseKeyOperations>? = null var kid: String? = null var kty: JwaKeyType? = null var n: String? = null var use: String? = null var x: String? = null var x5c: Array<String>? = null var x5t: String? = null var x5u: String? = null var x5t_S256: String? = null var y: String? = null fun withAlg(alg: JwaAlgorithm? = null) = apply { this.alg = alg } fun withCrv(crv: JwaCurve?) = apply { this.crv = crv } fun withD(d: String?) = apply { this.d = d } fun withE(e: String?) = apply { this.e = e } fun withK(k: String?) = apply { this.k = k } fun withKeyOps(key_ops: Array<JoseKeyOperations>?) = apply { this.key_ops = key_ops } fun withKid(kid: String?) = apply { this.kid = kid } fun withKty(kty: JwaKeyType?) = apply { this.kty = kty } fun withN(n: String?) = apply { this.n = n } fun withUse(use: String?) = apply { this.use = use } fun withX(x: String?) = apply { this.x = x } fun withX5c(x5c: Array<String>?) = apply { this.x5c = x5c } fun withX5t(x5t: String?) = apply { this.x5t = x5t } fun withX5u(x5u: String?) = apply { this.x5u = x5u } fun withX5t_S256(x5t_S256: String?) = apply { this.x5t_S256 = x5t_S256 } fun withY(y: String?) = apply { this.y = y } fun build(): Jwk = Jwk( alg = alg, crv = crv, d = d, e = e, k = k, key_ops = key_ops, kid = kid, kty = kty ?: throw IllegalArgumentException("kty value missing"), n = n, use = use, x = x, x5c = x5c, x5t = x5t, x5u = x5u, x5t_S256 = x5t_S256, y = y ) } // Name is like other extensions functions to not class with JS fun jwkToCoseKeyJson(): CoseKeyJson = CoseKeyJson.Builder() .withKty([email protected]() ?: throw IllegalArgumentException("kty value missing")) .withAlg(alg?.toCoseSignatureAlgorithm()) .withCrv(crv?.toCoseCurve()) .withD(d) // .withE(e) // .withK(k) .withKeyOps(key_ops?.map { it.toCoseKeyOperations() }?.toTypedArray()) .withKid(kid) // .withN(n) // .withUse(use) .withX(x) // .withX5t(x5t) // todo .withY(y) .build() // Name is like other extensions functions to not class with JS fun jwkToCoseKeyCbor(): CoseKeyCbor = this.jwkToCoseKeyJson().toCbor() fun toJsonObject() = cryptoJsonSerializer.encodeToJsonElement(serializer(), this).jsonObject object Static { fun fromJson(jwk: IJwkJson): Jwk = with(jwk) { return Jwk( alg = JwaAlgorithm.Static.fromValue(alg), crv = JwaCurve.Static.fromValue(crv), d = d, e = e, k = k, key_ops = key_ops?.map { JoseKeyOperations.Static.fromValue(it) }?.toTypedArray(), kid = kid, kty = JwaKeyType.Static.fromValue(kty), n = n, use = use, x = x, x5c = x5c?.map { it }?.toTypedArray(), x5t = x5t, x5u = x5u, x5t_S256 = x5t_S256, y = y, ) } fun fromJsonObject(jwk: JsonObject): Jwk = with(jwk) { return@fromJsonObject Jwk( alg = get("alg")?.jsonPrimitive?.content?.let { JwaAlgorithm.Static.fromValue(it) }, crv = get("crv")?.jsonPrimitive?.content?.let { JwaCurve.Static.fromValue(it) }, d = get("d")?.jsonPrimitive?.content, e = get("e")?.jsonPrimitive?.content, k = get("k")?.jsonPrimitive?.content, key_ops = get("key_ops")?.jsonArray?.map { JoseKeyOperations.Static.fromValue(it.jsonPrimitive.content) }?.toTypedArray(), kid = get("kid")?.jsonPrimitive?.content, kty = get("kty")?.jsonPrimitive?.content?.let { JwaKeyType.Static.fromValue(it) } ?: throw IllegalArgumentException("kty is missing"), n = get("n")?.jsonPrimitive?.content, use = get("use")?.jsonPrimitive?.content, x = get("x")?.jsonPrimitive?.content, x5c = get("x5c")?.jsonArray?.map { it.jsonPrimitive.content }?.toTypedArray(), x5t = get("x5t")?.jsonPrimitive?.content, x5u = get("x5u")?.jsonPrimitive?.content, x5t_S256 = get("x5t#S256")?.jsonPrimitive?.content, y = get("y")?.jsonPrimitive?.content, ) } fun fromDTO(jwk: IJwk): Jwk = with(jwk) { return@fromDTO Jwk( alg = alg, crv = crv, d = d, e = e, k = k, key_ops = key_ops, kid = kid, kty = kty, n = n, use = use, x = x, x5c = x5c, x5t = x5t, x5u = x5u, x5t_S256 = x5t_S256, y = y ) } fun fromCoseKeyJson(coseKey: ICoseKeyJson): Jwk { with(coseKey) { val kty = kty.toJoseKeyType() return Builder() .withKty(kty) .withAlg(alg?.toJoseSignatureAlgorithm()) .withCrv(crv?.toJoseCurve()) .withD(d) // .withE(e) // .withK(k) .withKeyOps(key_ops?.map { it.toJoseKeyOperations() }?.toTypedArray()) .withKid(kid) // .withN(n) // .withUse(use) .withX(x) .withX5c(x5chain) // .withX5t(x5t) // todo .withY(y) .build() } } fun fromCoseKey(coseKey: ICoseKeyCbor) = fromCoseKeyJson(CoseKeyCbor.Static.fromDTO(coseKey).toJson()) } } @JsExport fun CoseKeyCbor.cborToJwk() = Jwk.Static.fromCoseKey(this) @JsExport fun CoseKeyJson.jsonToJwk() = Jwk.Static.fromCoseKeyJson(this)
0
Kotlin
0
2
15a6f133cd830a213eccc96726d4167a6fd81891
9,834
mdoc-cbor-crypto-multiplatform
Apache License 2.0
presentation/src/commonMain/kotlin/kosh/presentation/transaction/rememberSign.kt
niallkh
855,100,709
false
{"Kotlin": 1845307, "Swift": 768}
package kosh.presentation.transaction import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import kosh.domain.failure.LedgerFailure import kosh.domain.failure.TrezorFailure import kosh.domain.repositories.LedgerListener import kosh.domain.repositories.TrezorListener import kosh.presentation.ledger.rememberLedger import kosh.presentation.ledger.rememberSignLedger import kosh.presentation.models.SignRequest import kosh.presentation.models.SignedRequest import kosh.presentation.trezor.rememberSignTrezor import kosh.presentation.trezor.rememberTrezor @Composable fun rememberSign( trezorListener: TrezorListener, ledgerListener: LedgerListener, ): SignState { val ledger = rememberLedger() val trezor = rememberTrezor() val signTrezor = rememberSignTrezor(trezorListener) val signLedger = rememberSignLedger(ledgerListener) return SignState( signedRequest = signTrezor.signedRequest ?: signLedger.signedRequest, loading = signTrezor.loading || signLedger.loading, ledgerFailure = signLedger.failure, trezorFailure = signTrezor.failure, sign = { request -> when { trezor.trezor != null -> signTrezor.sign(trezor.trezor, request) ledger.ledger != null -> signLedger.sign(ledger.ledger, request) else -> signTrezor.sign(trezor.trezor, request) } }, retry = { when { trezor.trezor != null -> signTrezor.retry(trezor.trezor) ledger.ledger != null -> signLedger.retry(ledger.ledger) else -> signTrezor.retry(trezor.trezor) } } ) } @Immutable data class SignState( val signedRequest: SignedRequest?, val loading: Boolean, val ledgerFailure: LedgerFailure?, val trezorFailure: TrezorFailure?, val sign: (SignRequest) -> Unit, val retry: () -> Unit, )
0
Kotlin
0
3
2be90c7ce7775a76d44fac4cae3a6777d6e9c7f7
1,949
kosh
MIT License
src/main/kotlin/pro/dionea/service/actions/VoteCallBackAction.kt
peterarsentev
782,528,938
false
{"Kotlin": 79560, "HTML": 32995, "Shell": 412}
package pro.dionea.service.actions import org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageReplyMarkup import org.telegram.telegrambots.meta.api.objects.Message import org.telegram.telegrambots.meta.api.objects.Update import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton import pro.dionea.domain.Spam import pro.dionea.domain.Vote import pro.dionea.service.* import java.sql.Timestamp class VoteCallBackAction( val voteService: VoteService, val contactService: ContactService, val spamService: SpamService, val chatService: ChatService, val remoteChat: RemoteChat ) : UpdateAction { override fun check(update: Update): Boolean = update.hasCallbackQuery() override fun execute(update: Update) { val spamMessage = update.callbackQuery.message.replyToMessage ?: return val chtId = spamMessage.chat.id val replyMessage = update.callbackQuery.message val voteByContact = if (update.callbackQuery.data.startsWith("yes")) Vote.YES else Vote.NO val voted = voteService.findByChatIdAndMessageIdAndUserId( chtId, spamMessage.messageId.toLong(), userId = update.callbackQuery.from.id) if (voted != null && voted.vote == voteByContact) { return } voteService.save(Vote().apply { chatId = chtId messageId = spamMessage.messageId.toLong() userId = update.callbackQuery.from.id vote = voteByContact }) val votes = voteService.findByMessageId(spamMessage.messageId.toLong()) val votesYes = votes.count { it.vote == Vote.YES } val votesNo = votes.size - votesYes val updateVote = EditMessageReplyMarkup().apply { chatId = chtId.toString() messageId = replyMessage.messageId } val markupInline = InlineKeyboardMarkup() val rowsInline: MutableList<List<InlineKeyboardButton>> = ArrayList() val rowInline: MutableList<InlineKeyboardButton> = ArrayList() val callBotMessageId = update.callbackQuery.data.split(" ")[1].toInt() rowInline.add(InlineKeyboardButton().apply { text = "Да: $votesYes" callbackData = "yes $callBotMessageId" }) rowInline.add(InlineKeyboardButton().apply { text = "Нет: $votesNo" callbackData = "no $callBotMessageId" }) rowsInline.add(rowInline) markupInline.keyboard = rowsInline updateVote.replyMarkup = markupInline remoteChat.execute(updateVote) if (votesYes >= Receiver.VOTE_SIZE_YES) { deleteByVoteMessage(spamMessage, replyMessage, callBotMessageId) } if (votesNo >= Receiver.VOTE_SIZE_NO) { remoteChat.execute(DeleteMessage(chtId.toString(), replyMessage.messageId)) remoteChat.execute(DeleteMessage(chtId.toString(), callBotMessageId)) } } private fun deleteByVoteMessage(spamMessage: Message, replyMessage: Message, callBotMessageId: Int) { val chtId = spamMessage.chatId.toString() val spammer = contactService.findIfNotCreate(spamMessage.from) contactService.increaseCountOfMessages(spammer, true) val spam = Spam().apply { text = if (spamMessage.isMessageWithImage()) "Содержит фото" else spamMessage.text time = Timestamp(System.currentTimeMillis()) contact = spammer chat = chatService.findOrCreate(spamMessage) } spamService.add(spam) remoteChat.execute(DeleteMessage( chtId, replyMessage.messageId )) remoteChat.execute(DeleteMessage( chtId, spamMessage.messageId )) remoteChat.execute(DeleteMessage( chtId, callBotMessageId )) } private fun Message.isMessageWithImage(): Boolean { return photo != null && photo.isNotEmpty() } }
6
Kotlin
1
2
d9662c08ec490d2c833d8f4ff4f37367121fd8b1
4,214
dionea_bot
MIT License
src/main/kotlin/komat/space/Vect.kt
Pascal-Institute
730,722,004
false
{"Kotlin": 60973}
package komat.space import komat.Element import komat.Utility.Companion.eq import komat.type.ElementType import komat.type.Padding import kotlin.math.* //1-Dimensional open class Vect() { var elementType = ElementType.ANY var column: Int = 0 var elements = Array(0) { Element(0.0) } companion object { operator fun Double.times(vect: Vect): Vect { return Element(this) * vect } operator fun Element.times(vect: Vect): Vect { for (i: Int in 0..<vect.column) { vect[i] = this.toDouble() * (vect[i].toDouble()) } return vect } } constructor(values: Array<Element>) : this() { elements = values this.column = elements.size } constructor(vararg values: Number) : this() { this.elementType = ElementType.DOUBLE this.elements = values.map { Element(it) }.toTypedArray() this.column = elements.size } constructor(vararg values: Double) : this() { this.elementType = ElementType.DOUBLE this.elements = values.map { Element(it) }.toTypedArray() this.column = this.elements.size } constructor(values: ByteArray) : this() { this.elementType = ElementType.BYTE this.elements = values.map { Element(it) }.toTypedArray() this.column = this.elements.size } constructor(values: BooleanArray) : this() { this.elementType = ElementType.BYTE this.elements = values.map { Element(it) }.toTypedArray() this.column = this.elements.size } operator fun get(c: Int): Element { if (c >= size()) { throw IndexOutOfBoundsException("Index out of bounds: [$c]") } return elements[c] } operator fun set(c: Int, value: Element) { if (c >= size()) { throw IndexOutOfBoundsException("Index out of bounds: [$c]") } elements[c] = value } operator fun set(c: Int, value: Number) { if (c >= size()) { throw IndexOutOfBoundsException("Index out of bounds: [$c]") } elements[c] = Element(value) } operator fun set(c: Int, value: Double) { if (c >= size()) { throw IndexOutOfBoundsException("Index out of bounds: [$c]") } elements[c] = Element(value) } operator fun set(c: Int, value: Byte) { if (c >= size()) { throw IndexOutOfBoundsException("Index out of bounds: [$c]") } elements[c] = Element(value) } operator fun set(c: Int, value: Boolean) { if (c >= size()) { throw IndexOutOfBoundsException("Index out of bounds: [$c]") } elements[c] = Element(value) } fun toDoubleArray() : DoubleArray { return elements.map { it.toDouble() }.toDoubleArray() } fun toByteArray() : ByteArray { return elements.map { it.toByte() }.toByteArray() } fun toBooleanArray() : BooleanArray { return elements.map { it.toBoolean() }.toBooleanArray() } operator fun plus(vect: Vect): Vect { for (i: Int in elements.indices) { this[i] += vect[i] } return this } operator fun minus(vect: Vect): Vect { for (i: Int in elements.indices) { this[i] -= vect[i] } return this } open fun isOrthogonal(vect: Vect): Boolean { return dot(vect) eq 0.0 } open fun size() : Int { return column } open fun copy(): Vect { val copiedVect = Vect(column) copiedVect.elements = elements.copyOf() return copiedVect } open fun print() { print("[") for (i: Int in elements.indices - 1) { print("${this[i].getValue()}, ") } print(elements.last().getValue()) println("]") } open fun pad(padding: Padding, size: Int): Vect { return pad(padding, size, 0.0) } open fun pad(padding: Padding, size: Int, bias: Any): Vect { var newBias = Element(0.0) when(elementType){ ElementType.DOUBLE ->{ newBias = Element(bias as Double) } ElementType.BYTE->{ newBias = Element(bias as Byte) } else->{} } when (padding) { Padding.ZERO -> {} Padding.MEAN -> newBias = mean() Padding.MIN -> newBias = min() Padding.MAX -> newBias = max() Padding.BIAS -> {} } val vect = Vect(Array(size) { newBias }) return concat(vect) } fun flip(): Vect { elements.reverse() return this } fun concat(vect: Vect): Vect { return Vect(elements + vect.elements) } fun convolve(vect: Vect, stride: Int): Vect { if (elements.size < vect.elements.size + stride) { throw IllegalArgumentException("Size Invalid") } val size: Int = (elements.size - vect.elements.size) / stride + 1 var convolutionVect = Vect(Array(size) { Element(0.0) }) when(elementType){ ElementType.DOUBLE ->{} ElementType.BYTE->{ convolutionVect = Vect(Array(size) { Element((0).toByte())})} else->{} } for (i in convolutionVect.elements.indices) { for (j in vect.elements.indices) { convolutionVect[i] += vect[j] * this[i * stride + j] } } return convolutionVect } fun convolve(vect: Vect, stride: Int, padding: Padding, padSize: Int): Vect { val newVect = pad(padding, padSize) return convolve(newVect, stride) } fun sum(): Element { var sum = Element(0.0) when(elementType){ ElementType.DOUBLE ->{} ElementType.BYTE->{ sum = Element(0)} else->{} } for (value in elements) { sum += value } return sum } //TODO Need to fix for Byte fun mean(): Element { return sum() / Element(elements.size.toDouble()) } fun max(): Element { var max = elements.first() when(elementType){ ElementType.DOUBLE ->{ elements.forEach { if ((it.toDouble()) > max.toDouble()) { max = it } } } ElementType.BYTE->{ elements.forEach { if (it.toByte() > max.toByte()) { max = it } } } else->{} } return max } fun min(): Element { var min = elements.first() when(elementType){ ElementType.DOUBLE ->{ elements.forEach { if ((it.toDouble()) < min.toDouble()) { min = it } } } ElementType.BYTE->{ elements.forEach { if (it.toByte() < min.toByte()) { min = it } } } else->{} } return min } //TODO Need to fix for Byte fun roundUp(decimalPlaces: Int): Vect { val factor = Element(10.0.pow(decimalPlaces)) for (i: Int in elements.indices) { this[i] = Element(round(this[i].toDouble() * factor.toDouble())) / factor } return this } fun dot(vect: Vect): Element { var scalar = Element(0.0) when(elementType){ ElementType.DOUBLE ->{} ElementType.BYTE->{ scalar = Element((0).toByte())} else->{} } elements.forEachIndexed { index, it -> scalar += it * vect[index] } return scalar } //TODO Need to fix for Byte fun l1norm(): Element { var sum = Element(0.0) elements.forEach { sum += Element(abs(it.toDouble())) } return sum } //TODO Need to fix for Byte fun l2norm(): Element { var sum = Element(0.0) elements.forEach { sum += (it * it) } return Element(sqrt(sum.toDouble())) } //TODO Need to fix for Byte fun l3norm(): Element { var sum = Element(0.0) elements.forEach { sum += (it * it * it) } return Element(cbrt(sum.toDouble())) } fun hat(): Vect { val l2norm = l2norm() for (i: Int in elements.indices) { this[i] = this[i] / l2norm } return this } //projection from this to u fun project(u: Vect): Vect { return (u.dot(this) / u.dot(u)) * u } //gramSchmidt for b fun gramSchmidt(b: Vect): Vect { val vect = this - project(b) return vect } }
0
Kotlin
0
1
0a9fced8f4f523f99a916cc67e1da043a553bd23
8,963
komat
MIT License
src/main/java/cn/origin/cube/utils/animations/Easing2D.kt
FadeRainbow
645,271,146
false
{"Java": 278796, "Kotlin": 149382, "GLSL": 89922}
package cn.origin.cube.utils.animations import net.minecraft.util.math.Vec2f class Easing2D (pos : Vec2f,size : Float) { private var lastPos : Vec2f private var newPos : Vec2f private val offset: Vec2f get() = Vec2f( (newPos.x - lastPos.x), (newPos.y - lastPos.y) ) private val animationX: AnimationFlag private val animationY: AnimationFlag private val animationSize : Easing1D private var startTime : Long init { lastPos = pos newPos = pos animationX = AnimationFlag(Easing.IN_OUT_EXPO,600f).also { it.forceUpdate(pos.x,pos.x) } animationY = AnimationFlag(Easing.IN_OUT_EXPO,600f).also { it.forceUpdate(pos.y,pos.y) } animationSize = Easing1D(size) startTime = System.currentTimeMillis() } fun reset(){ animationX.forceUpdate(0f,0f) animationY.forceUpdate(0f,0f) animationSize.reset() } fun updatePos(pos : Vec2f){ lastPos = newPos newPos = pos } fun updateSize(size : Float){ animationSize.updatePos(size) } fun getUpdate() = Vec2f( animationX.getAndUpdate(offset.x + lastPos.x), animationY.getAndUpdate(offset.y + lastPos.y) ) fun getUpdateSize() = animationSize.getUpdate() }
1
null
1
1
1d275bc0d2b3374b6541878a98bd5094e44c27a4
1,350
Kettle-Hack
MIT License
app/src/main/java/com/yoavst/quickapps/calendar/EventRetiever.kt
yoavst
22,375,409
false
null
package com.yoavst.quickapps.calendar import android.content.Context import android.text.format.Time import java.util.ArrayList /** * Created by yoavst. */ public object EventRetiever { public fun getEvents(context: Context, days: Int): List<Event> { var temp = ArrayList<Event>(days * 2) // Let's hope user has less then 2 events per days for performance. val time = Time(Time.getCurrentTimezone()); Event.loadEvents(context, temp, Time.getJulianDay(System.currentTimeMillis(), time.gmtoff), 30) val now = System.currentTimeMillis() return temp filter { now < it.endMillis } sortBy(comparator { l, r -> val start = (l.startMillis - r.startMillis).toInt() if (start != 0) start else { val end = (l.endMillis - r.endMillis).toInt() if (end != 0) end else l.title.toString().compareTo(r.title.toString(), ignoreCase = true) } }) } }
2
Kotlin
23
34
8b7fe52844a0bcc29c6288044322fe04e890c028
986
quickapps
Creative Commons Attribution 3.0 Unported
testutils/src/jsMain/kotlin/testutils/runSuspendTest.kt
cybernetics
364,759,458
true
{"Kotlin": 825333}
package testutils import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.promise actual fun runSuspendTest(block: suspend () -> Unit): dynamic = GlobalScope.promise { block() }
0
null
0
0
7fc4a9b3e37d2056582229e807fc92c8fe5bab5e
192
matrix-kt
Apache License 2.0
src/main/kotlin/com/github/frozencure/helix/subscriptions/SubscriptionsResponse.kt
frozencure
253,615,832
false
null
package com.github.frozencure.helix.subscriptions import com.github.frozencure.helix.http.model.array.HelixArrayDTO import com.github.frozencure.helix.http.model.array.ScrollableResponse import com.github.frozencure.helix.subscriptions.model.Subscription import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.statement.* import kotlinx.coroutines.runBlocking class SubscriptionsResponse(httpResponse: HttpResponse, httpClient: HttpClient) : ScrollableResponse<Subscription>(httpResponse, httpClient) { override val helixArrayDTO: HelixArrayDTO<Subscription> = runBlocking { httpResponse.receive<HelixArrayDTO<Subscription>>() } override suspend fun nextPage(): SubscriptionsResponse? = nextPageHttpResponse()?.let { SubscriptionsResponse( it, httpClient ) } }
3
Kotlin
3
17
285d49ad2ddf19f8ba2d0973ca17a40168fac914
863
twitch-client
MIT License
outdated/api/src/main/kotlin/de/hypercdn/ticat/api/endpoints/data/board/BoardHistory.kt
HyperCDN
543,352,274
false
null
package de.hypercdn.ticat.api.endpoints.data.board import de.hypercdn.ticat.api.entities.helper.* import de.hypercdn.ticat.api.entities.helper.entities.sql.* import de.hypercdn.ticat.api.entities.helper.repositories.findByIdElseThrow404 import de.hypercdn.ticat.api.entities.helper.repositories.getLoggedInElse403 import de.hypercdn.ticat.api.entities.json.out.BoardJson import de.hypercdn.ticat.api.entities.json.out.HistoryJson import de.hypercdn.ticat.api.entities.json.out.PagedJson import de.hypercdn.ticat.api.entities.json.out.UserJson import de.hypercdn.ticat.api.entities.sql.entities.Audit import de.hypercdn.ticat.api.entities.sql.entities.Member import de.hypercdn.ticat.api.entities.sql.repo.BoardRepository import de.hypercdn.ticat.api.entities.sql.repo.MemberRepository import de.hypercdn.ticat.api.entities.sql.repo.UserRepository import de.hypercdn.ticat.api.services.AuditService import de.hypercdn.ticat.api.services.HistoryService import jakarta.validation.constraints.Min import org.hibernate.validator.constraints.Range import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.domain.PageRequest import org.springframework.data.domain.Sort import org.springframework.data.repository.findByIdOrNull import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.springframework.web.server.ResponseStatusException @RestController class BoardHistory @Autowired constructor( val userRepository: UserRepository, val boardRepository: BoardRepository, val memberRepository: MemberRepository, val historyService: HistoryService, val auditService: AuditService ) { @GetMapping("/board/{boardId}/history") fun getBoardHistory( @PathVariable("boardId") boardId: String, @RequestParam("page", required = false, defaultValue = "0") @Min(0) page: Int, @RequestParam("chunkSize", required = false, defaultValue = "10") @Range(min = 1, max = 10) chunkSize: Int ): ResponseEntity<PagedJson<HistoryJson<BoardJson>>> { val selfUser = userRepository.getLoggedInElse403() val board = boardRepository.findByIdElseThrow404(boardId) val selfMember = memberRepository.findByIdOrNull(Member.Key(selfUser.uuid, board.id)) if (!board.isVisibleTo(selfUser, selfMember)) throw ResponseStatusException(HttpStatus.FORBIDDEN) val pageRequest = PageRequest.of(page, chunkSize, Sort.by(Sort.Direction.DESC, "version")) val changeHistory = historyService.getHistoryEntriesFor(board, pageRequest) val pagedJson = PagedJson<HistoryJson<BoardJson>>(pageRequest).apply { entities = changeHistory.map { HistoryJson.of(it) }.toList() } return ResponseEntity(pagedJson, HttpStatus.OK) } @PatchMapping("/board/{boardId}/history") fun revertHistory( @PathVariable("boardId") boardId: String, @RequestParam("version", required = true) @Min(0) version: Int, ): ResponseEntity<BoardJson> { val selfUser = userRepository.getLoggedInElse403() val board = boardRepository.findByIdElseThrow404(boardId) val selfMember = memberRepository.findByIdOrNull(Member.Key(selfUser.uuid, board.id)) if (!board.isManageableBy(selfUser, selfMember)) throw ResponseStatusException(HttpStatus.FORBIDDEN) if (board.isModificationLocked()) throw ResponseStatusException(HttpStatus.LOCKED) val changeHistory = historyService.getHistoryEntriesFor(board, PageRequest.of(0, Int.MAX_VALUE, Sort.by(Sort.Direction.DESC, "version")), IntRange(Int.MAX_VALUE, version)) val updateContext = board.applyHistoryToReverse(changeHistory) val updatedBoardSaved = boardRepository.save(updateContext.entity) val audit = auditService.writeFor(updatedBoardSaved, selfUser, Audit.Action.BOARD_HISTORY_RESTORE) historyService.writeHistoryEntryForDiffBetween(updateContext, audit) val boardJson = BoardJson(updatedBoardSaved) .includeId() .includeTitle() .includeDescription() .includeOwner { user -> UserJson(user) .includeId() .includeName() } .includeSettings() return ResponseEntity(boardJson, HttpStatus.OK) } }
0
Kotlin
0
0
6cbcec1a7e1627246e6fb7a300351d9fd65f4301
4,413
TiCat
Apache License 2.0
outdated/api/src/main/kotlin/de/hypercdn/ticat/api/endpoints/data/board/BoardHistory.kt
HyperCDN
543,352,274
false
null
package de.hypercdn.ticat.api.endpoints.data.board import de.hypercdn.ticat.api.entities.helper.* import de.hypercdn.ticat.api.entities.helper.entities.sql.* import de.hypercdn.ticat.api.entities.helper.repositories.findByIdElseThrow404 import de.hypercdn.ticat.api.entities.helper.repositories.getLoggedInElse403 import de.hypercdn.ticat.api.entities.json.out.BoardJson import de.hypercdn.ticat.api.entities.json.out.HistoryJson import de.hypercdn.ticat.api.entities.json.out.PagedJson import de.hypercdn.ticat.api.entities.json.out.UserJson import de.hypercdn.ticat.api.entities.sql.entities.Audit import de.hypercdn.ticat.api.entities.sql.entities.Member import de.hypercdn.ticat.api.entities.sql.repo.BoardRepository import de.hypercdn.ticat.api.entities.sql.repo.MemberRepository import de.hypercdn.ticat.api.entities.sql.repo.UserRepository import de.hypercdn.ticat.api.services.AuditService import de.hypercdn.ticat.api.services.HistoryService import jakarta.validation.constraints.Min import org.hibernate.validator.constraints.Range import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.domain.PageRequest import org.springframework.data.domain.Sort import org.springframework.data.repository.findByIdOrNull import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.springframework.web.server.ResponseStatusException @RestController class BoardHistory @Autowired constructor( val userRepository: UserRepository, val boardRepository: BoardRepository, val memberRepository: MemberRepository, val historyService: HistoryService, val auditService: AuditService ) { @GetMapping("/board/{boardId}/history") fun getBoardHistory( @PathVariable("boardId") boardId: String, @RequestParam("page", required = false, defaultValue = "0") @Min(0) page: Int, @RequestParam("chunkSize", required = false, defaultValue = "10") @Range(min = 1, max = 10) chunkSize: Int ): ResponseEntity<PagedJson<HistoryJson<BoardJson>>> { val selfUser = userRepository.getLoggedInElse403() val board = boardRepository.findByIdElseThrow404(boardId) val selfMember = memberRepository.findByIdOrNull(Member.Key(selfUser.uuid, board.id)) if (!board.isVisibleTo(selfUser, selfMember)) throw ResponseStatusException(HttpStatus.FORBIDDEN) val pageRequest = PageRequest.of(page, chunkSize, Sort.by(Sort.Direction.DESC, "version")) val changeHistory = historyService.getHistoryEntriesFor(board, pageRequest) val pagedJson = PagedJson<HistoryJson<BoardJson>>(pageRequest).apply { entities = changeHistory.map { HistoryJson.of(it) }.toList() } return ResponseEntity(pagedJson, HttpStatus.OK) } @PatchMapping("/board/{boardId}/history") fun revertHistory( @PathVariable("boardId") boardId: String, @RequestParam("version", required = true) @Min(0) version: Int, ): ResponseEntity<BoardJson> { val selfUser = userRepository.getLoggedInElse403() val board = boardRepository.findByIdElseThrow404(boardId) val selfMember = memberRepository.findByIdOrNull(Member.Key(selfUser.uuid, board.id)) if (!board.isManageableBy(selfUser, selfMember)) throw ResponseStatusException(HttpStatus.FORBIDDEN) if (board.isModificationLocked()) throw ResponseStatusException(HttpStatus.LOCKED) val changeHistory = historyService.getHistoryEntriesFor(board, PageRequest.of(0, Int.MAX_VALUE, Sort.by(Sort.Direction.DESC, "version")), IntRange(Int.MAX_VALUE, version)) val updateContext = board.applyHistoryToReverse(changeHistory) val updatedBoardSaved = boardRepository.save(updateContext.entity) val audit = auditService.writeFor(updatedBoardSaved, selfUser, Audit.Action.BOARD_HISTORY_RESTORE) historyService.writeHistoryEntryForDiffBetween(updateContext, audit) val boardJson = BoardJson(updatedBoardSaved) .includeId() .includeTitle() .includeDescription() .includeOwner { user -> UserJson(user) .includeId() .includeName() } .includeSettings() return ResponseEntity(boardJson, HttpStatus.OK) } }
0
Kotlin
0
0
6cbcec1a7e1627246e6fb7a300351d9fd65f4301
4,413
TiCat
Apache License 2.0
Chapter07/src/main/kotlin/com/packt/chapter2/char.kt
PacktPublishing
78,835,440
false
null
package com.packt.chapter2 val chars = arrayOf('\t', '\b', '\n', '\r', '\'', '\"', '\\', '\$')
5
null
41
76
4502b55d4086795df3f76ef65517679ad6c8cd55
97
Programming-Kotlin
MIT License
core/src/main/java/org/softeg/slartus/forpdaplus/core/entities/QmsContact.kt
slartus
21,554,455
false
null
package org.softeg.slartus.forpdaplus.core.entities interface QmsContact { val id: String? val nick: String? val avatarUrl: String? val newMessagesCount: Int? } class QmsContacts(list: List<QmsContact>) : List<QmsContact> by list
6
Java
15
56
6f01ebaa862d58e1cce01bd7e70910d49fd2de80
247
4pdaClient-plus
Apache License 2.0
src/main/kotlin/com/zqf/pomodoroschedule/PomodoroTimerStarterWidget.kt
fdslk
521,456,413
false
{"Kotlin": 29301, "Java": 849}
package com.zqf.pomodoroschedule import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.PlatformDataKeys.CONTEXT_COMPONENT import com.intellij.openapi.actionSystem.impl.AsyncDataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupFactory.ActionSelectionAid.SPEEDSEARCH import com.intellij.openapi.wm.CustomStatusBarWidget import com.intellij.openapi.wm.StatusBar import com.intellij.openapi.wm.StatusBarWidget import com.intellij.openapi.wm.StatusBarWidgetFactory import com.intellij.openapi.wm.impl.status.TextPanel import com.intellij.ui.awt.RelativePoint import com.zqf.pomodoroschedule.model.BasicSettings import com.zqf.pomodoroschedule.model.PomodoroModel import com.zqf.pomodoroschedule.model.PomodoroState import com.zqf.pomodoroschedule.model.PomodoroState.Mode import com.zqf.pomodoroschedule.model.time.Duration import com.zqf.pomodoroschedule.model.time.Time import java.awt.Graphics import java.awt.Insets import java.awt.Point import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.Icon import javax.swing.ImageIcon import javax.swing.JComponent class PomodoroTimerStarterWidget: StatusBarWidgetFactory { override fun getId() = "Pomodoro.schedule" override fun getDisplayName() = "Pomodoro.schedule" override fun isAvailable(project: Project) = true override fun createWidget(project: Project) = PomodoroWidget() override fun disposeWidget(widget: StatusBarWidget) = widget.dispose() override fun canBeEnabledOn(statusBar: StatusBar) = true } class PomodoroWidget : CustomStatusBarWidget, StatusBarWidget.Multiframe { private lateinit var statusBar: StatusBar private val model = service<PomodoroService>().model private val panelWithIcon = TextPanelWithIcon() init { val basicSettings = service<BasicSettings>() updateWidgetPanel(model, panelWithIcon, basicSettings.isShowTimeInToolbarWidget) model.addListener(this, object : PomodoroModel.Listener { override fun onStateChange(state: PomodoroState, wasManuallyStopped: Boolean) { ApplicationManager.getApplication().invokeLater { updateWidgetPanel(model, panelWithIcon, basicSettings.isShowTimeInToolbarWidget) } } }) panelWithIcon.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent?) { if (e == null) return if (e.isAltDown) { val popup = JBPopupFactory.getInstance().createActionGroupPopup( null, DefaultActionGroup(listOf(StartOrStopPomodoro(), ResetPomodorosCounter())), MapDataContext(mapOf(CONTEXT_COMPONENT.name to e.component)), SPEEDSEARCH, true ) val dimension = popup.content.preferredSize val point = Point(0, -dimension.height) popup.show(RelativePoint(e.component, point)) } else if (e.button == MouseEvent.BUTTON1) { model.onUserSwitchToNextState(Time.now()) } } override fun mouseEntered(e: MouseEvent?) { statusBar.info = UIBundle.message("statuspanel.tooltip", nextActionName(model), model.state.pomodorosAmount) } override fun mouseExited(e: MouseEvent?) { statusBar.info = "" } }) } private class MapDataContext(private val map: Map<String, Any?> = HashMap()) : AsyncDataContext { override fun getData(dataId: String) = map[dataId] } override fun dispose() { model.removeListener(this) } override fun ID() = "Pomodoro.schedule" override fun install(statusBar: StatusBar) { this.statusBar = statusBar } override fun copy() = PomodoroWidget() override fun getComponent(): JComponent = panelWithIcon private fun Long.formatted(): String { val formattedMinutes = String.format("%02d", this) val formattedSeconds = String.format("%02d", 0) return "$formattedMinutes:$formattedSeconds" } private fun nextActionName(model: PomodoroModel) = when (model.state.currentMode) { Mode.Run -> UIBundle.message("statuspanel.stop") Mode.Break -> UIBundle.message("statuspanel.stop_break") Mode.Stop -> UIBundle.message("statuspanel.start") } private fun updateWidgetPanel(model: PomodoroModel, panelWithIcon: TextPanelWithIcon, showTimeInToolbarWidget: Boolean) { panelWithIcon.text = if (showTimeInToolbarWidget) model.leftPomodorosTimeSpan.formatted() else "" panelWithIcon.toolTipText = UIBundle.message("statuspanel.widget_tooltip", nextActionName(model)) panelWithIcon.icon = when (model.state.currentMode) { Mode.Run -> pomodoroIcon Mode.Break -> pomodoroBreakIcon Mode.Stop -> pomodoroStoppedIcon } panelWithIcon.repaint() } private fun Duration.formatted(): String { val formattedMinutes = String.format("%02d", minutes) val formattedSeconds = String.format("%02d", (this - Duration(minutes)).seconds) return "$formattedMinutes:$formattedSeconds" } companion object { private val pomodoroIcon = loadIcon("/pomodoro.png") private val pomodoroStoppedIcon = loadIcon("/pomodoro.png") private val pomodoroBreakIcon = loadIcon("/pomodoro.png") private fun loadIcon(filePath: String) = ImageIcon(PomodoroWidget::class.java.getResource(filePath)) } } internal class TextPanelWithIcon: TextPanel() { private val gap = 2 var icon: Icon? = null override fun paintComponent(g: Graphics) { super.paintComponent(g) if (text == null) return icon?.paintIcon( this, g, insets.left - gap - iconWidth(), bounds.height / 2 - iconWidth() / 2 ) } override fun getInsets(): Insets { val insets = super.getInsets() insets.left += iconWidth() + gap * 2 return insets } private fun iconWidth() = icon?.iconWidth ?: 0 }
0
Kotlin
0
0
37d300ae4375435399018b80dd14006d8ab4be0a
6,454
pomodoro-schedule
MIT License
stripe/src/test/java/com/stripe/android/view/i18n/TranslatorManagerTest.kt
christurnertv
214,309,112
true
{"Kotlin": 1393069, "Java": 357270, "Ruby": 6208}
package com.stripe.android.view.i18n import com.stripe.android.StripeErrorFixtures import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals class TranslatorManagerTest { @BeforeTest fun setup() { TranslatorManager.setErrorMessageTranslator(null) } @Test fun testDefaultErrorMessageTranslator() { assertEquals("error!", TranslatorManager.getErrorMessageTranslator() .translate(0, "error!", STRIPE_ERROR)) } @Test fun testCustomErrorMessageTranslator() { TranslatorManager.setErrorMessageTranslator { _, _, _ -> "custom message" } assertEquals("custom message", TranslatorManager.getErrorMessageTranslator() .translate(0, "original message", STRIPE_ERROR)) } companion object { private val STRIPE_ERROR = StripeErrorFixtures.INVALID_REQUEST_ERROR } }
0
null
0
0
6f635ffe86469c81318f2ac9234658b98ad0ddd9
908
stripe-android
MIT License
app/src/main/java/com/example/eamobiles/screens/Anime/AnimeViewModel.kt
AnguloDev10
414,837,957
false
null
package com.example.eamobiles.screens.Anime import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.eamobiles.data.model.Anime import com.example.eamobiles.repository.AnimeRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class AnimeViewModel @Inject constructor(private val animeRepository: AnimeRepository): ViewModel() { private var _animes = MutableLiveData<List<Anime>>() val animes get() = _animes fun fetchAnimes() { viewModelScope.launch { _animes.postValue(animeRepository.fetchAnime()) } } fun insert(anime: Anime) { viewModelScope.launch { animeRepository.insert(anime) } } fun delete(anime: Anime) { viewModelScope.launch { animeRepository.delete(anime) } } }
0
Kotlin
0
0
b01ee45e8061a16002ba29c5eb89bba6ffdcbb45
965
ComposeMVVM
Apache License 2.0
utgang-pdl/src/main/kotlin/no/nav/paw/arbeidssoekerregisteret/utgang/pdl/metrics/Metrics.kt
navikt
771,406,758
false
{"Kotlin": 102366, "Dockerfile": 143}
package no.nav.paw.arbeidssoekerregisteret.utgang.pdl.metrics import io.micrometer.core.instrument.Tags import io.micrometer.core.instrument.Tag import io.micrometer.prometheus.PrometheusMeterRegistry const val METRICS_UTGANG_PDL = "paw.arbeidssoekerregisteret.utgang.pdl" const val ANTALL_AVSLUTTET_HENDELSER = "antall_avsluttet_hendelser" const val AVSLUTTET_HENDELSE_AARSAK = "avsluttet_hendelse_aarsak" const val PDL_HENT_PERSON_STATUS = "pdl_hent_person_status" fun PrometheusMeterRegistry.tellPdlAvsluttetHendelser(aarsak: String) = counter( METRICS_UTGANG_PDL, Tags.of(Tag.of(ANTALL_AVSLUTTET_HENDELSER, "avsluttet hendelse"), Tag.of(AVSLUTTET_HENDELSE_AARSAK, aarsak)) ).increment() fun PrometheusMeterRegistry.tellStatusFraPdlHentPersonBolk(status: String) = counter( METRICS_UTGANG_PDL, Tags.of(Tag.of(PDL_HENT_PERSON_STATUS, status)) ).increment()
0
Kotlin
0
0
21787f5b460ed10b7f75ba09ed9f2c65fac92e56
883
paw-arbeidssoekerregisteret-utgang
MIT License
app/src/main/java/com/phantom/banguminote/base/Utils.kt
PhantomLGZ
741,144,233
false
{"Kotlin": 247864}
package com.phantom.banguminote.base import android.content.Context import android.util.TypedValue import java.time.LocalDate import java.time.LocalDateTime import java.time.format.DateTimeFormatter fun Float.spToPx(context: Context?): Float = context?.let { TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, this, it.resources.displayMetrics ) } ?: 0f fun Float.dpToPx(context: Context?): Float = context?.let { TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, this, it.resources.displayMetrics ) } ?: 0f fun String.checkHttps(): String = this.replace("http:", "https:") val dateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") val date1Formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX") val dateTimeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") fun String.toLocalDate(): LocalDate = LocalDate.parse(this, dateFormatter) fun LocalDate.toFormattedString(): String = dateFormatter.format(this) fun String.reformatDate(): String = LocalDateTime.parse(this, date1Formatter).format(dateTimeFormatter) /** * copy from hutool */ fun String.unicodeToString(): String { if (this.isBlank()) { return this } val len = this.length val sb = StringBuilder(len) var i: Int var pos = 0 while (this.indexOf("\\u", pos, true).also { i = it } != -1) { sb.append(this, pos, i) //写入Unicode符之前的部分 pos = i if (i + 5 < len) { var c: Char try { c = this.substring(i + 2, i + 6).toInt(16).toChar() sb.append(c) pos = i + 6 //跳过整个Unicode符 } catch (e: NumberFormatException) { //非法Unicode符,跳过 sb.append(this, pos, i + 2) //写入"\\u" pos = i + 2 } } else { //非Unicode符,结束 break } } if (pos < len) { sb.append(this, pos, len) } return sb.toString() }
0
Kotlin
0
3
f47b57c45c57eded74c80980a9d9853f61724c8d
2,137
BangumiNote
MIT License
system/src/main/kotlin/com/commonsense/android/kotlin/system/base/helpers/KeyboardHandlerHelper.kt
Tvede-dk
82,486,921
false
null
package com.commonsense.android.kotlin.system.base.helpers import android.app.* import com.commonsense.android.kotlin.base.* import com.commonsense.android.kotlin.base.extensions.collections.* import com.commonsense.android.kotlin.system.extensions.* /** * Created by kasper on 15/12/2017. * Handles dismissing keyboard when switching screens . * */ class KeyboardHandlerHelper { /** * if false, nothing happens at lifecycle events */ var isEnabled: Boolean = true var hideOnPause: Boolean = true fun onDestroy(activity: Activity) = ifIsEnabled { activity.hideSoftKeyboard() } fun onPause(activity: Activity) = ifIsEnabled { if (hideOnPause) { activity.hideSoftKeyboard() } } private inline fun ifIsEnabled(crossinline action: EmptyFunction) { isEnabled.ifTrue(action) } override fun toString(): String = toPrettyString() fun toPrettyString(): String { return "Keyboard handler state: " + "\n\t\tis enabled: $isEnabled" + "\n\t\tHide on pause: $hideOnPause" } }
9
Kotlin
0
8
eae2deb915804d4c431c3fc9d93c33f011a98e5c
1,118
CommonsenseAndroidKotlin
MIT License
app/src/main/java/com/qxy/tiktlin/ui/vm/MainViewModel.kt
lukelmouse-github
517,612,289
false
null
package com.qxy.tiktlin.ui.vm import com.qxy.tiktlin.widget.BaseViewModel class MainViewModel : BaseViewModel() { }
0
Kotlin
0
1
5ba2bdc7eb41371b578d52e8289b8d08f77ce10d
118
Tiktlin
Apache License 2.0
app/src/main/java/github/com/st235/easycurrency/domain/Currency.kt
st235
167,151,844
false
null
package github.com.st235.easycurrency.domain /** * Internal currency model, contains * id (ISO 4217 code), title (in local language) * current value, convert rate * and info about base value */ class Currency(val id: String, val title: String, var isBase: Boolean = false) { companion object { fun copy(currency: Currency, newRate: Double, newValue: Double): Currency { val newOne = Currency(currency) newOne.value = newValue newOne.rate = newRate return newOne } fun copyWithNewValue(currency: Currency, newValue: Double): Currency { val newOne = Currency(currency) newOne.value = newValue return newOne } } var value: Double = 1.0 var rate: Double = 1.0 constructor(currency: Currency): this(currency.id, currency.title, currency.isBase) { rate = currency.rate } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Currency if (id != other.id) return false if (isBase != other.isBase) return false return true } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + isBase.hashCode() return result } override fun toString(): String { return "Currency(id='$id', title='$title', isBase=$isBase, value=$value, rate=$rate)" } }
0
Kotlin
1
5
95098ccdda15c6325135c944242df1a080b68661
1,531
EasyCurrency
MIT License
uikit/src/main/java/com/sendbird/uikit/internal/model/templates/MessageTemplateStatus.kt
sendbird
350,188,329
false
null
package com.sendbird.uikit.internal.model.templates internal enum class MessageTemplateStatus { NOT_APPLICABLE, CACHED, LOADING, FAILED_TO_PARSE, FAILED_TO_FETCH }
1
null
43
39
c2f6aa7f37fb1428a96f3d93cf05e736e3659351
185
sendbird-uikit-android
MIT License
sykepenger-model/src/test/kotlin/no/nav/helse/spleis/e2e/IngentingÅSimulereE2ETest.kt
navikt
193,907,367
false
null
package no.nav.helse.spleis.e2e import no.nav.helse.hendelser.Periode import no.nav.helse.hendelser.Sykmeldingsperiode import no.nav.helse.hendelser.Søknad.Søknadsperiode.Ferie import no.nav.helse.hendelser.Søknad.Søknadsperiode.Sykdom import no.nav.helse.januar import no.nav.helse.person.TilstandType.AVSLUTTET import no.nav.helse.person.TilstandType.AVVENTER_BLOKKERENDE_PERIODE import no.nav.helse.person.TilstandType.AVVENTER_GODKJENNING import no.nav.helse.person.TilstandType.AVVENTER_HISTORIKK import no.nav.helse.person.TilstandType.AVVENTER_INNTEKTSMELDING_ELLER_HISTORIKK import no.nav.helse.person.TilstandType.AVVENTER_SIMULERING import no.nav.helse.person.TilstandType.AVVENTER_VILKÅRSPRØVING import no.nav.helse.person.TilstandType.START import no.nav.helse.utbetalingslinjer.Utbetaling import no.nav.helse.økonomi.Prosentdel.Companion.prosent import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class IngentingÅSimulereE2ETest : AbstractEndToEndTest() { @Test fun `forlenger et vedtak med bare helg`() { nyttVedtak(1.januar, 19.januar) håndterSykmelding(Sykmeldingsperiode(20.januar, 21.januar, 100.prosent)) håndterSøknad(Sykdom(20.januar, 21.januar, 100.prosent)) håndterYtelser(2.vedtaksperiode) håndterUtbetalingsgodkjenning(2.vedtaksperiode) assertTilstander(2.vedtaksperiode, START, AVVENTER_BLOKKERENDE_PERIODE, AVVENTER_HISTORIKK, AVVENTER_GODKJENNING, AVSLUTTET) assertEquals(Utbetaling.GodkjentUtenUtbetaling, inspektør.utbetalingtilstand(1)) } @Test fun `førstegangsbehandling på eksisterende utbetaling med bare helg`() { nyttVedtak(1.januar, 18.januar) håndterSykmelding(Sykmeldingsperiode(20.januar, 21.januar, 100.prosent)) håndterSøknad(Sykdom(20.januar, 21.januar, 100.prosent)) håndterInntektsmelding(listOf(Periode(1.januar, 16.januar)), førsteFraværsdag = 20.januar) håndterYtelser(2.vedtaksperiode) håndterVilkårsgrunnlag(2.vedtaksperiode) håndterYtelser(2.vedtaksperiode) håndterUtbetalingsgodkjenning(2.vedtaksperiode) assertTilstander( 2.vedtaksperiode, START, AVVENTER_INNTEKTSMELDING_ELLER_HISTORIKK, AVVENTER_BLOKKERENDE_PERIODE, AVVENTER_HISTORIKK, AVVENTER_VILKÅRSPRØVING, AVVENTER_HISTORIKK, AVVENTER_GODKJENNING, AVSLUTTET ) assertEquals(Utbetaling.GodkjentUtenUtbetaling, inspektør.utbetalingtilstand(1)) } @Test fun `forlenger et vedtak med bare helg og litt ferie`() { nyttVedtak(1.januar, 19.januar) håndterSykmelding(Sykmeldingsperiode(20.januar, 23.januar, 100.prosent)) håndterSøknad(Sykdom(20.januar, 23.januar, 100.prosent), Ferie(22.januar, 23.januar)) håndterYtelser(2.vedtaksperiode) håndterUtbetalingsgodkjenning(2.vedtaksperiode) assertTilstander( 2.vedtaksperiode, START, AVVENTER_BLOKKERENDE_PERIODE, AVVENTER_HISTORIKK, AVVENTER_GODKJENNING, AVSLUTTET ) assertEquals(Utbetaling.GodkjentUtenUtbetaling, inspektør.utbetalingtilstand(1)) } @Test fun `tomt simuleringsresultat`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 21.januar, 100.prosent)) håndterSøknad(Sykdom(1.januar, 21.januar, 100.prosent)) håndterInntektsmelding(listOf(Periode(1.januar, 16.januar))) håndterYtelser(1.vedtaksperiode) håndterVilkårsgrunnlag(1.vedtaksperiode) håndterYtelser(1.vedtaksperiode) håndterSimulering(1.vedtaksperiode, simuleringsresultat = null) assertTilstander( 1.vedtaksperiode, START, AVVENTER_INNTEKTSMELDING_ELLER_HISTORIKK, AVVENTER_BLOKKERENDE_PERIODE, AVVENTER_HISTORIKK, AVVENTER_VILKÅRSPRØVING, AVVENTER_HISTORIKK, AVVENTER_SIMULERING, AVVENTER_GODKJENNING ) } }
1
Kotlin
5
5
a1d4ace847a123e6bf09754ea0640116caf6ceb7
4,097
helse-spleis
MIT License
uisdk/src/main/java/tech/dojo/pay/uisdk/presentation/components/InputFieldModifierWithFocusChangedAndScrollingLogic.kt
dojo-engineering
478,120,913
false
{"Kotlin": 1013793}
package tech.dojo.pay.uisdk.presentation.components import androidx.compose.foundation.ScrollState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInParent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.math.roundToInt @Composable internal fun Modifier.autoScrollableInputFieldOnFocusChangeAndValidator( coroutineScope: CoroutineScope, scrollState: ScrollState, initialHasBeenFocused: Boolean, parentPosition: Float, onValidate: () -> Unit, ): Modifier { var hasBeenFocused by remember { mutableStateOf(initialHasBeenFocused) } val scrollOffsets by remember { mutableStateOf(mutableListOf<Float>()) } var inputFieldLabelHeightInPx by remember { mutableStateOf(0) } return this.onFocusChanged { focusState -> if (focusState.isFocused) { coroutineScope.launch { delay(300) val totalOffset = scrollOffsets.maxOrNull() ?: 0F if (totalOffset != 0F) { scrollState.animateScrollTo((parentPosition + totalOffset - inputFieldLabelHeightInPx).roundToInt()) } else { scrollState.animateScrollTo((totalOffset).roundToInt()) } } hasBeenFocused = true } else { if (hasBeenFocused) { onValidate() scrollOffsets.clear() } } }.onGloballyPositioned { layoutCoordinates -> inputFieldLabelHeightInPx = layoutCoordinates.size.height val totalHeight = layoutCoordinates.positionInParent().y scrollOffsets.add(totalHeight) } }
1
Kotlin
2
3
bd6ae5ad2c46cf15e126979dcacbf383c96a9128
2,029
android-dojo-pay-sdk
MIT License
uisdk/src/main/java/tech/dojo/pay/uisdk/presentation/components/InputFieldModifierWithFocusChangedAndScrollingLogic.kt
dojo-engineering
478,120,913
false
{"Kotlin": 1013793}
package tech.dojo.pay.uisdk.presentation.components import androidx.compose.foundation.ScrollState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInParent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.math.roundToInt @Composable internal fun Modifier.autoScrollableInputFieldOnFocusChangeAndValidator( coroutineScope: CoroutineScope, scrollState: ScrollState, initialHasBeenFocused: Boolean, parentPosition: Float, onValidate: () -> Unit, ): Modifier { var hasBeenFocused by remember { mutableStateOf(initialHasBeenFocused) } val scrollOffsets by remember { mutableStateOf(mutableListOf<Float>()) } var inputFieldLabelHeightInPx by remember { mutableStateOf(0) } return this.onFocusChanged { focusState -> if (focusState.isFocused) { coroutineScope.launch { delay(300) val totalOffset = scrollOffsets.maxOrNull() ?: 0F if (totalOffset != 0F) { scrollState.animateScrollTo((parentPosition + totalOffset - inputFieldLabelHeightInPx).roundToInt()) } else { scrollState.animateScrollTo((totalOffset).roundToInt()) } } hasBeenFocused = true } else { if (hasBeenFocused) { onValidate() scrollOffsets.clear() } } }.onGloballyPositioned { layoutCoordinates -> inputFieldLabelHeightInPx = layoutCoordinates.size.height val totalHeight = layoutCoordinates.positionInParent().y scrollOffsets.add(totalHeight) } }
1
Kotlin
2
3
bd6ae5ad2c46cf15e126979dcacbf383c96a9128
2,029
android-dojo-pay-sdk
MIT License
android-app/app/src/main/java/arun/com/chromer/home/epoxycontroller/model/TabModel.kt
Efreak
435,082,649
false
null
package arun.com.chromer.home.epoxycontroller.model import arun.com.chromer.R import arun.com.chromer.data.website.model.Website import arun.com.chromer.tabs.TabsManager import arun.com.chromer.util.glide.GlideApp import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyAttribute.Option.DoNotHash import com.airbnb.epoxy.EpoxyModelClass import dev.arunkumar.android.epoxy.model.KotlinEpoxyModelWithHolder import dev.arunkumar.android.epoxy.model.KotlinHolder import kotlinx.android.synthetic.main.widget_tab_model_preview.* @EpoxyModelClass(layout = R.layout.widget_tab_model_preview) abstract class TabModel : KotlinEpoxyModelWithHolder<TabModel.ViewHolder>() { @EpoxyAttribute lateinit var tab: TabsManager.Tab @EpoxyAttribute(DoNotHash) lateinit var tabsManager: TabsManager override fun bind(holder: ViewHolder) { super.bind(holder) GlideApp.with(holder.containerView.context) .load(tab.website ?: Website(tab.url)) .circleCrop() .into(holder.icon) holder.containerView.setOnClickListener { tabsManager.reOrderTabByUrl( holder.containerView.context, Website(tab.url), listOf(tab.getTargetActivityName()) ) } } class ViewHolder : KotlinHolder() }
0
null
0
1
8ae744e51849a961059517fa50f6c5fd5e580fd9
1,250
lynket-browser
Condor Public License v1.1
src/main/kotlin/org/rust/lang/core/psi/ext/RsExternCrateItem.kt
Keats
87,803,437
true
{"Kotlin": 1257227, "Rust": 74475, "Lex": 19046, "HTML": 9205, "Java": 586, "Shell": 377, "RenderScript": 15}
package org.rust.lang.core.psi.ext import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.stubs.IStubElementType import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.RsExternCrateItem import org.rust.lang.core.psi.RustPsiImplUtil import org.rust.lang.core.resolve.ref.RsExternCrateReferenceImpl import org.rust.lang.core.resolve.ref.RsReference import org.rust.lang.core.stubs.RsExternCrateItemStub abstract class RsExternCrateItemImplMixin : RsStubbedNamedElementImpl<RsExternCrateItemStub>, RsExternCrateItem { constructor(node: ASTNode) : super(node) constructor(stub: RsExternCrateItemStub, elementType: IStubElementType<*, *>) : super(stub, elementType) override fun getReference(): RsReference = RsExternCrateReferenceImpl(this) override val referenceNameElement: PsiElement get() = identifier override val referenceName: String get() = name!! override val isPublic: Boolean get() = RustPsiImplUtil.isPublic(this, stub) override fun getIcon(flags: Int) = RsIcons.CRATE }
0
Kotlin
0
1
0d1082cac60f0d02b807194f1453761fc1a53a1e
1,106
intellij-rust
MIT License