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
feature-nft-impl/src/main/java/jp/co/soramitsu/nft/impl/domain/usecase/tokensbycontract/TokensMappingAdapter.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.nft.impl.domain.usecase.tokensbycontract import jp.co.soramitsu.nft.data.models.TokenInfo import jp.co.soramitsu.nft.data.pagination.PageBackStack import jp.co.soramitsu.nft.data.pagination.PagedResponse import jp.co.soramitsu.nft.domain.models.NFTCollection import jp.co.soramitsu.nft.impl.domain.models.nft.CollectionWithTokensImpl import jp.co.soramitsu.nft.impl.domain.models.nft.NFTImpl import jp.co.soramitsu.runtime.multiNetwork.chain.ChainsRepository import jp.co.soramitsu.runtime.multiNetwork.chain.model.Chain import jp.co.soramitsu.runtime.multiNetwork.chain.model.ChainId import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onCompletion import java.util.concurrent.atomic.AtomicReference import javax.inject.Inject import javax.inject.Singleton @Singleton class TokensMappingAdapter @Inject constructor( private val chainsRepository: ChainsRepository ) { private val chainRef: AtomicReference<Chain?> = AtomicReference(null) operator fun invoke(factory: () -> Flow<PagedResponse<TokenInfo>>): Flow<NFTCollection.Loaded> = factory().map { it.mapToNFTCollectionResultWithToken() } .onCompletion { chainRef.set(null) }.flowOn(Dispatchers.Default) private suspend fun PagedResponse<TokenInfo>.mapToNFTCollectionResultWithToken(): NFTCollection.Loaded { val chain = chainRef.get().let { savedChain -> if (savedChain == null || savedChain.id != tag) { chainsRepository.getChain(tag as ChainId).also { chainRef.set(it) } } else { savedChain } } val (chainId, chainName) = chain.run { id to name } return result.mapCatching { pageResult -> if (pageResult !is PageBackStack.PageResult.ValidPage) { return@mapCatching NFTCollection.Loaded.Result.Empty(chainId, chainName) } CollectionWithTokensImpl( response = pageResult, chainId = chainId, chainName = chainName, tokens = pageResult.items .filter { token -> token.id?.tokenId != null } .map { token -> NFTImpl(token, chainId, chainName) } ) }.getOrElse { throwable -> NFTCollection.Loaded.WithFailure( chainId = chainId, chainName = chainName, throwable = throwable ) } } }
15
null
30
89
812c6ed5465d19a0616865cbba3e946d046720a1
2,583
fearless-Android
Apache License 2.0
common/src/main/java/com/ds/ciceksepeti/common/viewmodel/CoreViewModel.kt
developersancho
371,180,136
false
null
package com.ds.ciceksepeti.common.viewmodel import android.os.Bundle import androidx.annotation.StringRes import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.asFlow import androidx.lifecycle.viewModelScope import com.ds.ciceksepeti.common.helper.SingleEvent import com.ds.ciceksepeti.common.repository.DataState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import java.lang.ref.WeakReference abstract class CoreViewModel : ViewModel(), InitState, LifecycleState { private val _isLoading = MutableLiveData<SingleEvent<Boolean>>() val isLoading get() = _isLoading.asFlow() private val _errorMessage = MutableLiveData<SingleEvent<String>>() val errorMessage get() = _errorMessage.asFlow() protected fun showLoading() { _isLoading.value = SingleEvent(true) } protected fun hideLoading() { _isLoading.value = SingleEvent(false) } protected fun showError(message: String) { _errorMessage.value = SingleEvent(message) } protected suspend fun <T> executeState( callFlow: Flow<DataState<T>>, completionHandler: (data: T) -> Unit ) = callFlow .onStart { showLoading() } .onCompletion { hideLoading() } .catch { onError(it) } .collect { state -> when (state) { is DataState.Success -> { completionHandler(state.response) } is DataState.Error -> { onError(state.error) } } } protected suspend fun <T> executeFlow( callFlow: Flow<T>, completionHandler: (data: T) -> Unit ) = callFlow .onStart { showLoading() } .onCompletion { hideLoading() } .catch { onError(it) } .collect { state -> completionHandler(state) } open suspend fun onError(throwable: Throwable) {} protected fun launchOn(block: suspend CoroutineScope.() -> Unit) { viewModelScope.launch { block() } } override var arguments: Bundle? = null override var fragmentManager: FragmentManager? = null override var activity: WeakReference<FragmentActivity>? = null override fun onViewReady(bundle: Bundle?) {} override fun onStart() {} override fun onResume() {} override fun onPause() {} override fun onStop() {} override fun onDestroyView() {} override fun onDestroy() {} protected fun getString(@StringRes resId: Int): String = activity?.get()?.getString(resId).orEmpty() fun getActivity(): FragmentActivity? = activity?.get() fun requireActivity(): FragmentActivity = requireNotNull(activity?.get()) fun requireFragmentManager(): FragmentManager = requireNotNull(fragmentManager) fun requireArgument(): Bundle = requireNotNull(arguments) }
0
Kotlin
0
0
1ad877d404b6c6777db0d23b50d8b832b2a89d52
3,028
CicekSepeti-Challenge
Apache License 2.0
logrecorder-modules/logrecorder-log4j/src/main/kotlin/io/github/logrecorder/log4j/Log4jLogRecorderContext.kt
logrecorder
78,454,007
false
{"Kotlin": 262733}
package io.github.logrecorder.log4j import io.github.logrecorder.common.LogRecorderContext import org.apache.logging.log4j.Logger /** * [LogRecorderContext] for Log4j. * * Allows for the [starting][start] and [stopping][stop] of the recording of multiple [Logger]. */ internal class Log4jLogRecorderContext(loggers: Collection<Logger>) : LogRecorderContext { override val record = Log4jLogRecord() private val recorders = loggers.map { Log4jLogRecorder(it, record) } override fun start() { recorders.forEach(Log4jLogRecorder::start) } override fun stop() { recorders.forEach(Log4jLogRecorder::stop) } }
0
Kotlin
4
16
1743dd23d193a2badb8902c4edc26f4db63cc70f
652
logrecorder
Apache License 2.0
app/src/main/java/com/example/bookloverfinalapp/app/ui/general_screens/screen_reader/router/FragmentReaderRouter.kt
yusuf0405
484,801,816
false
null
package com.example.bookloverfinalapp.app.ui.general_screens.screen_reader.router import com.example.bookloverfinalapp.app.models.BookThatRead import com.example.bookloverfinalapp.app.utils.navigation.NavCommand interface FragmentReaderRouter { fun navigateToQuestionnaireFragment( savedBook: BookThatRead, path: String, chapter: Int ): NavCommand fun navigateToBookInfoFragment(bookId:String): NavCommand }
1
Kotlin
1
3
067abb34f0348b0dda1f05470a32ecbed59cfb19
448
BookLoverFinalApp
Apache License 1.1
jdbc/src/main/kotlin/com/oneliang/ktx/frame/jdbc/ConnectionSource.kt
tongxiaoyi
379,480,354
false
null
package com.oneliang.ktx.frame.jdbc import com.oneliang.ktx.Constants import com.oneliang.ktx.util.logging.LoggerManager import com.oneliang.ktx.util.resource.ResourceSource import java.sql.Connection import java.sql.DriverManager /** * ConnectionSource bean describe the database detail,include driver,url,user,password * four important property * * @author Dandelion * @since 2008-08-22 */ open class ConnectionSource : ResourceSource<Connection>() { companion object { private val logger = LoggerManager.getLogger(ConnectionSource::class) const val CONNECTION_SOURCE_NAME = "connectionSourceName" const val DRIVER = "driver" const val URL = "url" const val USER = "user" const val PASSWORD = "<PASSWORD>" } /** * connection source name */ var connectionSourceName: String = Constants.String.BLANK /** * driver */ var driver: String = Constants.String.BLANK set(driver) { field = driver if (this.driver.isNotBlank()) { try { Thread.currentThread().contextClassLoader.loadClass(this.driver).newInstance() } catch (e: Exception) { logger.error(Constants.String.EXCEPTION, e) } } } /** * url */ var url: String = Constants.String.BLANK /** * user */ var user: String = Constants.String.BLANK /** * password */ var password: String = Constants.String.BLANK /** * Method: initial the connection operate,load the config file or use the * default file * This method initial the config file */ override val resource: Connection get() { return getConnection(this.url, this.user, this.password) } @Synchronized protected fun getConnection(url: String, user: String, password: String): Connection { var connection: Connection? = null try { connection = DriverManager.getConnection(url, user, password) } catch (e: Exception) { logger.error(Constants.String.EXCEPTION, e) } if (connection == null) { throw NullPointerException("connection can not be null") } return connection } }
1
null
2
1
1a4cbe107b7adc8941691911f75c3fc2aa383ca1
2,329
frame-kotlin
Apache License 2.0
Projects Manager/Backend/src/main/kotlin/pt/isel/daw/service/contract/ICommentService.kt
LuisGuerraa
242,099,578
false
null
package pt.isel.daw.service.contract import pt.isel.daw.model.Issue import pt.isel.daw.model.IssueComment interface ICommentService { fun createIssueComment(uid: Int, comment: IssueComment): Int fun getIssueComments(pname: String, issueId: Int): List<IssueComment> fun getIssueCommentDetails(pname: String, issueID: Int, id: Int): IssueComment fun updateIssueComment(uid: Int, oldComment: IssueComment): Boolean fun deleteIssueComment(uid: Int, pname: String, issueID: Int, commentID: Int): Boolean fun deleteIssueComments(uid: Int, issue: Issue): Boolean }
8
null
1
3
a73ada1f8a133d222577f9d7e004d3458ae4b536
589
BscInformaticsWork
Apache License 2.0
app/src/main/java/ir/dunijet/saman_managment/ui/activities/SignupActivity.kt
amir00462
509,503,374
false
null
package ir.dunijet.saman_managment.ui.activities import android.content.Context import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.view.WindowManager import android.widget.Toast import com.google.gson.JsonObject import ir.dunijet.saman_managment.R import ir.dunijet.saman_managment.me.LoginResponse import ir.dunijet.saman_managment.me.TokenInMemory import ir.dunijet.saman_managment.me.createApiService import ir.dunijet.saman_managment.model.repository.user.UserRepository import ir.dunijet.saman_managment.model.repository.user.UserRepositoryImpl import kotlinx.android.synthetic.main.activity_signup.* import kotlinx.android.synthetic.main.nav_header_main.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response class SignupActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_signup) window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) setupActionBar() btn_sign_up.setOnClickListener { registerUser() } } private fun setupActionBar() { setSupportActionBar(toolbar_sign_up_activity) val actionBar = supportActionBar if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true) actionBar.setHomeAsUpIndicator(R.drawable.ic_black_color_back_24dp) } toolbar_sign_up_activity.setNavigationOnClickListener { onBackPressed() } } private fun registerUser() { val name = et_name.text.toString().trim() val email = et_email.text.toString().trim() val password = et_password.text.toString().trim() if (validateForm(name, email, password)) { // sing up now val jsonObject = JsonObject().apply { addProperty("name", name) addProperty("username", email) addProperty("password", <PASSWORD>) } val apiService = createApiService() apiService.signUp(jsonObject).enqueue(object : Callback<LoginResponse> { override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) { val data = response.body()!! if (data.success) { val jsonObjectSignIn = JsonObject().apply { addProperty("username", email) addProperty("password", <PASSWORD>) } apiService.signIn(jsonObjectSignIn).enqueue( object :Callback<LoginResponse> { override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) { val newData = response.body()!! if(newData.success) { val sharedPref = getSharedPreferences("main", Context.MODE_PRIVATE) sharedPref.edit().putString("token", newData.token).apply() sharedPref.edit().putString("username", email).apply() sharedPref.edit().putString("name", name).apply() TokenInMemory.refreshToken(email , newData.token) val intent = Intent(this@SignupActivity, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP.or(Intent.FLAG_ACTIVITY_CLEAR_TASK) startActivity(intent) } else { Toast.makeText(this@SignupActivity, newData.message, Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call<LoginResponse>, t: Throwable) { Toast.makeText(this@SignupActivity, t.message, Toast.LENGTH_SHORT).show() } } ) } else { Toast.makeText(this@SignupActivity, data.message ?: "null", Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call<LoginResponse>, t: Throwable) { Toast.makeText(this@SignupActivity, t.message, Toast.LENGTH_SHORT).show() } }) } } private fun validateForm(name: String, email: String, password: String): Boolean { return when { TextUtils.isEmpty(name) -> { showErrorSnackBar("Please enter a name") false } TextUtils.isEmpty(email) -> { showErrorSnackBar("Please enter an email") false } TextUtils.isEmpty(password) -> { showErrorSnackBar("Please enter a password") false } else -> { true } } } }
0
Kotlin
0
0
d814c196736e30ab1117cc6d4fa72c94020592fe
5,253
Saman_Manager_App
Apache License 2.0
app/src/main/java/com/dkbrothers/apps/chatsnow/SplashActivity.kt
elssiany
251,348,100
false
{"Kotlin": 30514}
package com.dkbrothers.apps.chatsnow import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import com.dkbrothers.apps.chatsnow.view.ui.HomeActivity import com.dkbrothers.apps.chatsnow.view.ui.IntroActivity import loadPreference class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //setContentView(R.layout.activity_splash) delaySplashScreen() } fun delaySplashScreen() { val delaySplash: Long = 2500 Handler().postDelayed({ //Start Activity var intent = Intent(this, IntroActivity::class.java) if(loadPreference("showHome", false)) { intent = Intent(this, HomeActivity::class.java) } startActivity(intent) finish() }, delaySplash) } }
0
Kotlin
0
3
7613286c76d33c383526872c9103e7060cbb32ff
949
ChatNow
MIT License
SecondTempleTimer/src/commonMain/kotlin/sternbach/software/kosherkotlin/metadata/Occurrence.kt
kdroidFilter
849,781,239
false
{"Kotlin": 814129}
package sternbach.software.kosherkotlin.metadata import sternbach.software.kosherkotlin.Zman import kotlin.math.absoluteValue data class Occurrence(val subject: ZmanType, val calculationMethod: ZmanCalculationMethod) { infix fun after(zmanType: ZmanType): ZmanRelationship = ZmanRelationship( subject, +calculationMethod, zmanType ) infix fun after(zmanDefinition: ZmanDefinition): ZmanRelationship = ZmanRelationship( subject, +calculationMethod, relativeToZman = zmanDefinition ) infix fun before(zmanType: ZmanType): ZmanRelationship = ZmanRelationship( subject, -calculationMethod, zmanType ) infix fun before(zmanDefinition: ZmanDefinition): ZmanRelationship = ZmanRelationship( subject, -calculationMethod, relativeToZman = zmanDefinition ) /** * Syntactic sugar for [after] ([zman].[definition][Zman.definition]). * */ infix fun after(zman: Zman<*>): ZmanRelationship = after(zman.definition) /** * Syntactic sugar for [before] ([zman].[definition][Zman.definition]). * */ infix fun before(zman: Zman<*>): ZmanRelationship = before(zman.definition) /** * Returns a [ZmanCalculationMethod] with a [ZmanCalculationMethod.value] that is the negative of [this.value]. * If [this.value] is already negative, it will remain negative, unlike a regular unary minus operator. * */ private operator fun ZmanCalculationMethod.unaryMinus(): ZmanCalculationMethod = when (this) { is ZmanCalculationMethod.Degrees -> ZmanCalculationMethod.Degrees(-(degrees.absoluteValue)) is ZmanCalculationMethod.FixedDuration -> ZmanCalculationMethod.FixedDuration(-(duration.absoluteValue)) is ZmanCalculationMethod.ZmaniyosDuration -> ZmanCalculationMethod.ZmaniyosDuration(-(duration.absoluteValue)) is ZmanCalculationMethod.FixedDuration.AteretTorah -> ZmanCalculationMethod.FixedDuration.AteretTorah(-(minutes.absoluteValue)) is ZmanAuthority, is ZmanCalculationMethod.DayDefinition, is ZmanCalculationMethod.LaterOf, is ZmanCalculationMethod.Relationship, ZmanCalculationMethod.FixedLocalChatzos, ZmanCalculationMethod.Unspecified,-> this } private operator fun ZmanCalculationMethod.unaryPlus(): ZmanCalculationMethod = when (this) { is ZmanCalculationMethod.Degrees -> ZmanCalculationMethod.Degrees(degrees.absoluteValue) is ZmanCalculationMethod.FixedDuration -> ZmanCalculationMethod.FixedDuration(duration.absoluteValue) is ZmanCalculationMethod.ZmaniyosDuration -> ZmanCalculationMethod.ZmaniyosDuration(duration.absoluteValue) is ZmanCalculationMethod.FixedDuration.AteretTorah -> ZmanCalculationMethod.FixedDuration.AteretTorah(minutes.absoluteValue) is ZmanAuthority, is ZmanCalculationMethod.DayDefinition, is ZmanCalculationMethod.LaterOf, is ZmanCalculationMethod.Relationship, ZmanCalculationMethod.FixedLocalChatzos, ZmanCalculationMethod.Unspecified, -> this } }
0
Kotlin
0
0
577cd4818376400b4acc0f580ef19def3bf9e8d9
3,167
SecondTempleTimerLibrary
Apache License 2.0
plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigMissingRequiredDeclarationInspection.kt
ingokegel
284,920,751
false
null
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.codeinsight.inspections import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import org.editorconfig.language.codeinsight.quickfixes.EditorConfigAddRequiredDeclarationsQuickFix import org.editorconfig.language.codeinsight.quickfixes.EditorConfigRemoveOptionQuickFix import org.editorconfig.language.messages.EditorConfigBundle import org.editorconfig.language.psi.EditorConfigVisitor import org.editorconfig.language.psi.interfaces.EditorConfigDescribableElement import org.editorconfig.language.schema.descriptors.impl.EditorConfigDeclarationDescriptor import org.editorconfig.language.services.EditorConfigOptionDescriptorManager import org.editorconfig.language.util.EditorConfigIdentifierUtil class EditorConfigMissingRequiredDeclarationInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() { override fun visitPsiElement(element: PsiElement) { if (element !is EditorConfigDescribableElement) return val descriptor = element.getDescriptor(false) as? EditorConfigDeclarationDescriptor ?: return val declarations = EditorConfigIdentifierUtil.findDeclarations(element.section, descriptor.id, element.text) val manager = EditorConfigOptionDescriptorManager.getInstance(element.project) val errors = manager.getRequiredDeclarationDescriptors(descriptor.id).filter { requiredDescriptor -> declarations.none { describable -> describable.getDescriptor(false) === requiredDescriptor } } val message = when (val errorCount = errors.count()) { 0 -> return 1 -> EditorConfigBundle.get("inspection.declaration.missing.singular.message", element.text) else -> EditorConfigBundle.get("inspection.declaration.missing.plural.message", element.text, errorCount) } holder.registerProblem( element, message, EditorConfigRemoveOptionQuickFix(), EditorConfigAddRequiredDeclarationsQuickFix(errors, descriptor.id) ) } } }
284
null
5162
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
2,309
intellij-community
Apache License 2.0
app/src/main/java/id/yuana/todo/compose/ui/todo_list/TodoListScreen.kt
andhikayuana
577,216,760
false
null
package id.yuana.todo.compose.ui.todo_list import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ExitToApp import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import id.yuana.todo.compose.util.UiEvent import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun TodoListScreen( onNavigate: (UiEvent.Navigate) -> Unit, viewModel: TodoListViewModel = hiltViewModel() ) { val todos = viewModel.todos.collectAsState(initial = emptyList()) val snackbarHostState = remember { SnackbarHostState() } val logoutDialogState = remember { mutableStateOf(false) } val scope = rememberCoroutineScope() LaunchedEffect(key1 = true) { viewModel.uiEvent.collect { event -> when (event) { is UiEvent.Navigate -> onNavigate(event) is UiEvent.ShowSnackbar -> { scope.launch { val result = snackbarHostState.showSnackbar( message = event.message, actionLabel = event.action, duration = SnackbarDuration.Short ) if (result == SnackbarResult.ActionPerformed) { viewModel.onEvent(TodoListEvent.OnUndoDeleteClick) } } } UiEvent.ShowDialog -> { logoutDialogState.value = true } else -> Unit } } } Scaffold( topBar = { TopAppBar( title = { Text(text = "Todo Compose - List") }, actions = { IconButton(onClick = { viewModel.onEvent(TodoListEvent.ShowLogoutDialog) }) { Icon( imageVector = Icons.Default.ExitToApp, contentDescription = "Logout" ) } } ) }, snackbarHost = { SnackbarHost(snackbarHostState) }, floatingActionButton = { FloatingActionButton(onClick = { viewModel.onEvent(TodoListEvent.OnAddTodoClick) }) { Icon( imageVector = Icons.Default.Add, contentDescription = "Add" ) } }) { if (logoutDialogState.value) { AlertDialog( onDismissRequest = { logoutDialogState.value = false }, title = { Text(text = "Logout") }, text = { Text(text = "Are you sure want to logout from this app?") }, confirmButton = { TextButton( onClick = { logoutDialogState.value = false viewModel.onEvent(TodoListEvent.OnLogoutClick) } ) { Text("Yes") } }, dismissButton = { TextButton( onClick = { logoutDialogState.value = false } ) { Text("No") } } ) } LazyColumn( modifier = Modifier .padding(it) .fillMaxSize(), ) { if (todos.value.isEmpty()) { item { Text( text = "Todo is empty", modifier = Modifier.fillMaxSize(), textAlign = TextAlign.Center ) } } else { items(todos.value) { todo -> TodoItem( todo = todo, onEvent = viewModel::onEvent, modifier = Modifier .fillMaxWidth() .clickable { viewModel.onEvent(TodoListEvent.OnTodoClick(todo)) } .padding(16.dp) ) } } } } }
0
Kotlin
1
3
f3404f46bdc9e244620f95c7043fd84b4c623ea0
5,094
todo-compose
MIT License
vector/src/main/java/im/vector/app/features/home/xspace/conference/JitsiCallViewModel.kt
xlinx-indonesia
321,889,530
false
null
/* * Copyright (c) 2020 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.app.features.home.xspace.conference import com.airbnb.mvrx.MvRxViewModelFactory import com.airbnb.mvrx.ViewModelContext import com.squareup.inject.assisted.Assisted import com.squareup.inject.assisted.AssistedInject import im.vector.app.core.platform.VectorViewModel import im.vector.app.core.resources.StringProvider import org.jitsi.meet.sdk.JitsiMeetUserInfo import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.util.toMatrixItem import java.net.URL class JitsiCallViewModel @AssistedInject constructor( @Assisted initialState: JitsiCallViewState, @Assisted val args: XlinxSpaceActivity.Args, private val session: Session, private val stringProvider: StringProvider ) : VectorViewModel<JitsiCallViewState, JitsiCallViewActions, JitsiCallViewEvents>(initialState) { @AssistedInject.Factory interface Factory { fun create(initialState: JitsiCallViewState, args: XlinxSpaceActivity.Args): JitsiCallViewModel } init { val me = session.getUser(session.myUserId)?.toMatrixItem() val userInfo = JitsiMeetUserInfo().apply { displayName = args.nickName avatar = me?.avatarUrl?.let { session.contentUrlResolver().resolveFullSize(it) }?.let { URL(it) } } val roomName = args.roomId setState { copy( userInfo = userInfo, jitsiUrl = "https://x-linx.space", subject = roomName ) } } override fun handle(action: JitsiCallViewActions) { } companion object : MvRxViewModelFactory<JitsiCallViewModel, JitsiCallViewState> { const val ENABLE_VIDEO_OPTION = "ENABLE_VIDEO_OPTION" @JvmStatic override fun create(viewModelContext: ViewModelContext, state: JitsiCallViewState): JitsiCallViewModel? { val callActivity: XlinxSpaceActivity = viewModelContext.activity() val callArgs: XlinxSpaceActivity.Args = viewModelContext.args() return callActivity.viewModelFactory.create(state, callArgs) } override fun initialState(viewModelContext: ViewModelContext): JitsiCallViewState? { val args: XlinxSpaceActivity.Args = viewModelContext.args() return JitsiCallViewState( roomId = args.roomId, nickName = args.nickName, enableVideo = args.enableVideo ) } } }
0
Kotlin
0
0
339981999e1286420ecc016c8501dca07b42695b
3,107
matrix-xlinx
Apache License 2.0
core/kotlinx-coroutines-io/src/main/kotlin/kotlinx/coroutines/experimental/io/WriterJob.kt
snowe2010
117,292,230
true
{"Kotlin": 1646975, "CSS": 8706, "JavaScript": 3331, "Ruby": 1760, "HTML": 1675}
package kotlinx.coroutines.experimental.io import kotlinx.coroutines.experimental.CoroutineScope import kotlinx.coroutines.experimental.Job import kotlinx.coroutines.experimental.newCoroutineContext import kotlin.coroutines.experimental.CoroutineContext import kotlin.coroutines.experimental.startCoroutine /** * A coroutine job that is writing to a byte channel */ interface WriterJob : Job { /** * A reference to the channel that this coroutine is writing to */ val channel: ByteReadChannel } interface WriterScope : CoroutineScope { val channel: ByteWriteChannel } fun writer(coroutineContext: CoroutineContext, channel: ByteChannel, parent: Job? = null, block: suspend WriterScope.() -> Unit): WriterJob { val newContext = newCoroutineContext(coroutineContext, parent) val coroutine = WriterCoroutine(newContext, channel) coroutine.initParentJob(newContext[Job]) block.startCoroutine(coroutine, coroutine) return coroutine } fun writer(coroutineContext: CoroutineContext, autoFlush: Boolean = false, parent: Job? = null, block: suspend WriterScope.() -> Unit): WriterJob { val channel = ByteChannel(autoFlush) as ByteBufferChannel val job = writer(coroutineContext, channel, parent, block) channel.attachJob(job) return job } private class WriterCoroutine(ctx: CoroutineContext, channel: ByteChannel) : ByteChannelCoroutine(ctx, channel), WriterScope, WriterJob
0
Kotlin
0
0
ae416729fcf147ca49120b982881cd7a48032f0d
1,503
kotlinx.coroutines
Apache License 2.0
webauthn2-json-moshi/src/test/java/io/github/ryunen344/webauthn2/json/moshi/MoshiLargeBlobSupportTest.kt
RyuNen344
729,132,404
false
{"Kotlin": 340153, "TypeScript": 26425, "WebIDL": 5880}
package io.github.ryunen344.webauthn2.json.moshi import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import io.github.ryunen344.webauthn2.json.core.enum.LargeBlobSupport import io.github.ryunen344.webauthn2.json.core.enum.LargeBlobSupportTest import io.github.ryunen344.webauthn2.json.core.test.runJsonTest import io.github.ryunen344.webauthn2.json.core.test.truth.assertJson import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class MoshiLargeBlobSupportTest : LargeBlobSupportTest() { @Test override fun testSerialize_givenRequired_thenValueIsRequired() = runJsonTest("LargeBlobSupport-required.json") { val adapter = MoshiUtil.adapter(LargeBlobSupport::class) val serialized = adapter.toJson(LargeBlobSupport.Required) assertJson(serialized).isEquivalentTo(it) } @Test override fun testSerialize_givenPreferred_thenValueIsPreferred() = runJsonTest("LargeBlobSupport-preferred.json") { val adapter = MoshiUtil.adapter(LargeBlobSupport::class) val serialized = adapter.toJson(LargeBlobSupport.Preferred) assertJson(serialized).isEquivalentTo(it) } @Test override fun testDeserialize_givenRequiredJsonString_thenValueIsRequired() = runJsonTest("LargeBlobSupport-required.json") { val adapter = MoshiUtil.adapter(LargeBlobSupport::class) val support = adapter.fromJson(it) assertThat(support).isEqualTo(LargeBlobSupport.Required) } @Test override fun testDeserialize_givenPreferredJsonString_thenValueIsPreferred() = runJsonTest("LargeBlobSupport-preferred.json") { val adapter = MoshiUtil.adapter(LargeBlobSupport::class) val support = adapter.fromJson(it) assertThat(support).isEqualTo(LargeBlobSupport.Preferred) } }
2
Kotlin
0
2
560157c5f84df28012a0e897cc4bdd90a0bb4875
1,946
WebAuthnKt
Apache License 2.0
app/src/main/java/com/bagadesh/myallsampleapps/mainScreen/timeline/TimeLineUI.kt
bagadesh
754,458,708
false
{"Kotlin": 300128}
package com.bagadesh.myallsampleapps.mainScreen.timeline import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect 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 androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.delay /** * Created by bagadesh on 24/01/23. */ @Composable fun TimeLineUI() { var finished by remember { mutableStateOf(false) } LaunchedEffect(key1 = Unit) { splashTracker.mark("Initial") delay(100) splashTracker.mark("First") delay(100) splashTracker.mark("Second") delay(100) splashTracker.mark("Third") delay(100) splashTracker.mark("Finish") delay(100) splashTracker.mark("Initial") delay(100) splashTracker.mark("First") delay(100) splashTracker.mark("Second") delay(100) splashTracker.mark("Third") delay(100) splashTracker.mark("Finish") finished = true } if (finished) { val result = remember { splashTracker.getTimeLine() } Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.Start ) { Text( text = result.mainTag, modifier = Modifier .padding(10.dp) .align(Alignment.CenterHorizontally), fontSize = 24.sp, fontWeight = FontWeight.Black ) result.timelines.forEach { Row( modifier = Modifier .fillMaxWidth() .height(IntrinsicSize.Min) .padding(0.dp), verticalAlignment = Alignment.Top ) { CircleIndicator( modifier = Modifier.padding(start = 10.dp, top = 10.dp) ) Column( modifier = Modifier.padding(10.dp) ) { Text( text = it.tag, fontSize = 20.sp, modifier = Modifier.padding(start = 0.dp) ) Text( text = "difference ${it.loggedTimeBasedOnTime} ms", fontSize = 18.sp, color = Color(0xFF767B7B), ) Text( text = "${it.loggedTimeFromStart} ms", fontSize = 18.sp, color = Color(0xFF767B7B), ) } } } } } else { Row { CircularProgressIndicator() Text(text = "Loading") } } } @Composable fun CircleIndicator( modifier: Modifier = Modifier ) { val shape = RoundedCornerShape(50) Column( modifier = modifier then Modifier .fillMaxHeight(), horizontalAlignment = Alignment.CenterHorizontally ) { Box( modifier = Modifier .clip(shape) .size(20.dp) .background(color = Color(0xFF379FB5)) .border(1.dp, Color.White, shape) .drawWithContent { drawContent() drawCircle( color = Color.White, radius = size.minDimension / 4 ) } ) Box( modifier = Modifier .padding(top = 10.dp) .fillMaxHeight() .width(1.dp) .background(Color.White) .weight(1f) ) } }
0
Kotlin
0
0
c37ada4e6382877485f6693b7f784a9200873884
5,251
MySamplesAndroid
Apache License 2.0
packages/plugin-google-non-gms/src/main/java/com/openmobilehub/android/auth/plugin/google/nongms/domain/auth/AuthRepository.kt
openmobilehub
742,146,209
false
null
/* * Copyright 2023 Open Mobile Hub * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.omh.android.auth.nongms.domain.auth import com.omh.android.auth.nongms.domain.models.ApiResult import com.omh.android.auth.nongms.domain.models.OAuthTokens internal interface AuthRepository { /** * Requests OAuth tokens from the auth provider. * * @param clientId -> your client id from the console * @param authCode -> the auth code received after the user executed their login * @param redirectUri -> the same redirect URI from the login screen * @param codeVerifier -> code verifier of the PKCE protocol */ suspend fun requestTokens( clientId: String, authCode: String, redirectUri: String, codeVerifier: String ): ApiResult<OAuthTokens> /** * Builds the login URL to use in the custom tabs implementation. This will show the user the * login screen of the auth provider. * * @param scopes -> requested scopes from the application * @param clientId -> your client id from the console * @param codeChallenge -> code challenge of the PCKE protocol * @param redirectUri -> redirect URI for the application to catch the deeplink with params */ fun buildLoginUrl( scopes: String, clientId: String, codeChallenge: String, redirectUri: String ): String /** * Requests the access token. * * @return null if not available. */ fun getAccessToken(): String? /** * Refreshes the access token from the auth provider. * * @param clientId -> clientId from the auth console * * @return a [ApiResult] with the token inside. */ suspend fun refreshAccessToken(clientId: String): ApiResult<String> /** * Revokes the access token of the user from the auth provider. */ suspend fun revokeToken(): ApiResult<Unit> /** * Clears all local data of the user, including stored tokens. */ fun clearData() }
9
null
4
4
e3cecfffc694385ef12dd5d1d565ed4c2415daac
2,568
android-omh-auth
Apache License 2.0
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/stage/passive/BuffPassive.kt
qwewqa
390,928,568
false
null
package xyz.qwewqa.relive.simulator.core.stage.passive import xyz.qwewqa.relive.simulator.core.stage.ActionContext import xyz.qwewqa.relive.simulator.core.stage.TargetContext import xyz.qwewqa.relive.simulator.core.stage.actor.CountableBuff import xyz.qwewqa.relive.simulator.core.stage.autoskill.PassiveEffect import xyz.qwewqa.relive.simulator.core.stage.autoskill.PassiveEffectCategory import xyz.qwewqa.relive.simulator.core.stage.autoskill.EffectTag import xyz.qwewqa.relive.simulator.core.stage.buff.* import xyz.qwewqa.relive.simulator.core.stage.condition.Condition import xyz.qwewqa.relive.simulator.core.stage.stageeffect.StageEffect val SelfFortitudeBuffPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.Fortitude, EffectTag.Fortitude) { targetSelf() } val SelfEvasionBuffPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.Evasion, EffectTag.Evasion) { targetSelf() } val SelfReviveBuffPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.Revive, EffectTag.Revive) { targetSelf() } val SelfInvincibleRebirthBuffPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.InvincibleRebirth, EffectTag.Revive) { targetSelf() } val TeamEvasionBuffPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.Evasion, EffectTag.Evasion) { targetAllyAoe(it) } val TeamReviveBuffPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.Revive, EffectTag.Revive) { targetAllyAoe(it) } val TeamInvincibleRebirthBuffPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.InvincibleRebirth, EffectTag.Revive) { targetAllyAoe(it) } val TeamFortitudeBuffPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.Fortitude, EffectTag.Fortitude) { targetAllyAoe(it) } val SelfHopeBuffPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.Hope, EffectTag.Hope) { targetSelf() } val TeamBlessingHPRecoveryPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.BlessingHpRecovery, EffectTag.HpRecovery, "Team") { targetAllyAoe(it) } val TeamBlessingCountableDebuffReductionPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.BlessingCountableDebuffReduction, EffectTag.NegativeCountableReduction, "Team") { targetAllyAoe(it) } val SelfBlessingCountableDebuffReductionPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.BlessingCountableDebuffReduction, EffectTag.NegativeCountableReduction, "Self") { targetSelf() } val TeamBlessingContinuousDebuffRemovalPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.BlessingContinuousDebuffRemoval, EffectTag.NegativeEffectCleanse, "Team") { targetAllyAoe(it) } val SelfBlessingContinuousDebuffRemovalPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.BlessingContinuousDebuffRemoval, EffectTag.NegativeEffectCleanse, "Self") { targetSelf() } val TeamBlessingEffectiveDamagePassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.BlessingEffectiveDamage, EffectTag.EffectiveDamage, "Team") { targetAllyAoe(it) } val SelfBlessingEffectiveDamagePassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.BlessingEffectiveDamage, EffectTag.EffectiveDamage, "Self") { targetSelf() } val TeamHopeBuffPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.Hope, EffectTag.Hope, "Team") { targetAllyAoe(it) } val TeamBlessingHopePassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.BlessingHope, EffectTag.Hope, "Team") { targetAllyAoe(it) } val TeamBlessingAp2DownPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.BlessingAp2Down, EffectTag.AP2Down, "Team") { targetAllyAoe(it) } val SelfBlessingBlessingContinuousDebuffRemovalPassive: PassiveEffect = GenericCountableBuffPassive(CountableBuff.BlessingContinuousDebuffRemoval, EffectTag.NegativeEffectCleanse, "Self") { targetSelf() } val TeamActPowerUpBuffPassive: PassiveEffect = GenericBuffPassive(ActPowerUpBuff, EffectTag.Act,"Team") { targetAllyAoe(it) } val TeamDexterityUpBuffPassive: PassiveEffect = GenericBuffPassive(DexterityUpBuff, EffectTag.Dexterity, "Team") { targetAllyAoe(it) } val TeamCriticalUpBuffPassive: PassiveEffect = GenericBuffPassive(CriticalUpBuff, EffectTag.Critical, "Team") { targetAllyAoe(it) } val TeamEffectiveDamageDealtUpBuffPassive: PassiveEffect = GenericBuffPassive(EffectiveDamageDealtUpBuff, EffectTag.EffectiveDamage, "Team") { targetAllyAoe(it) } val SelfNormalDefenseUpBuffPassive: PassiveEffect = GenericBuffPassive(NormalDefenseUpBuff, EffectTag.Defense) { targetSelf() } val SelfSpecialDefenseUpBuffPassive: PassiveEffect = GenericBuffPassive(SpecialDefenseUpBuff, EffectTag.Defense) { targetSelf() } val TeamNormalDefenseUpBuffPassive: PassiveEffect = GenericBuffPassive(NormalDefenseUpBuff, EffectTag.Defense) { targetAllyAoe(it) } val TeamSpecialDefenseUpBuffPassive: PassiveEffect = GenericBuffPassive(SpecialDefenseUpBuff, EffectTag.SpecialDefense) { targetAllyAoe(it) } val SelfPerfectAimBuffPassive: PassiveEffect = GenericBuffPassive(PerfectAimBuff, EffectTag.PerfectAim) { targetSelf() } val TeamPerfectAimBuffPassive: PassiveEffect = GenericBuffPassive(PerfectAimBuff, EffectTag.PerfectAim) { targetAllyAoe(it) } val SelfDexterityUpBuffPassive: PassiveEffect = GenericBuffPassive(DexterityUpBuff, EffectTag.Dexterity) { targetSelf() } val SelfEffectiveDamageDealtUpBuffPassive: PassiveEffect = GenericBuffPassive(EffectiveDamageDealtUpBuff, EffectTag.EffectiveDamage) { targetSelf() } val SelfLockedEffectiveDamageDealtUpBuffPassive: PassiveEffect = GenericBuffPassive(LockedEffectiveDamageDealtUpBuff, EffectTag.EffectiveDamage) { targetSelf() } val SelfCriticalUpBuffPassive: PassiveEffect = GenericBuffPassive(CriticalUpBuff, EffectTag.Critical) { targetSelf() } val TeamAgilityUpBuffPassive: PassiveEffect = GenericBuffPassive(AgilityUpBuff, EffectTag.Agility,"Team") { targetAllyAoe(it) } val TeamAPDownBuffPassive: PassiveEffect = GenericBuffPassive(ApDownBuff, EffectTag.ApDown, "Team") { targetAllyAoe(it) } val TeamLockedAPDownBuffPassive: PassiveEffect = GenericBuffPassive(LockedApDownBuff, EffectTag.ApDown, "Team") { targetAllyAoe(it) } val TeamAP2DownBuffPassive: PassiveEffect = GenericBuffPassive(Ap2DownBuff, EffectTag.AP2Down, "Team") { targetAllyAoe(it) } val SelfAP2DownBuffPassive: PassiveEffect = GenericBuffPassive(Ap2DownBuff, EffectTag.AP2Down, "Self") { targetSelf() } val SelfClimaxDamageUpBuffPassive: PassiveEffect = GenericBuffPassive(ClimaxDamageUpBuff, EffectTag.ClimaxDamage) { targetSelf() } val SelfAbsorbBuffPassive: PassiveEffect = GenericBuffPassive(AbsorbBuff, EffectTag.Absorb) { targetSelf() } val TeamInvincibilityBuffPassive: PassiveEffect = GenericBuffPassive(InvincibilityBuff, EffectTag.Invincibility) { targetAllyAoe(it) } val TeamLockedInvincibilityBuffPassive: PassiveEffect = GenericBuffPassive(LockedInvincibilityBuff, EffectTag.Invincibility) { targetAllyAoe(it) } val SelfNormalBarrierBuffPassive: PassiveEffect = GenericBuffPassive(NormalBarrierBuff, EffectTag.NormalBarrier) { targetSelf() } val SelfSpecialBarrierBuffPassive: PassiveEffect = GenericBuffPassive(SpecialBarrierBuff, EffectTag.SpecialBarrier) { targetSelf() } val TeamHpRegenBuffPassive: PassiveEffect = GenericBuffPassive(HpRegenBuff, EffectTag.HpRegen, "Team") { targetAllyAoe(it) } val TeamNegativeEffectResistanceBuffPassive: PassiveEffect = GenericBuffPassive(NegativeEffectResistanceBuff, EffectTag.NegativeEffectResistance, "Team") { targetAllyAoe(it) } val TeamLockedNegativeEffectResistanceBuffPassive: PassiveEffect = GenericBuffPassive(LockedNegativeEffectResistanceBuff, EffectTag.NegativeEffectResistance, "Team") { targetAllyAoe(it) } val SelfNegativeEffectResistanceBuffPassive: PassiveEffect = GenericBuffPassive(NegativeEffectResistanceBuff, EffectTag.NegativeEffectResistance) { targetSelf() } val SelfLockedNegativeEffectResistanceBuffPassive: PassiveEffect = GenericBuffPassive(LockedNegativeEffectResistanceBuff, EffectTag.NegativeEffectResistance) { targetSelf() } val SelfNegativeCountableEffectResistanceBuffPassive: PassiveEffect = GenericBuffPassive(NegativeCountableEffectResistanceBuff, EffectTag.NegativeCountableResistance) { targetSelf() } val SelfLockedNegativeCountableEffectResistanceBuffPassive: PassiveEffect = GenericBuffPassive(LockedNegativeCountableResistanceBuff, EffectTag.NegativeCountableResistance) { targetSelf() } val SelfExitEvasionBuffPassive: PassiveEffect = GenericBuffPassive(ExitEvasionBuff, EffectTag.ExitEvasion) { targetSelf() } val TeamDamageDealtUpBuffPassive: PassiveEffect = GenericBuffPassive(DamageDealtUpBuff, EffectTag.Damage, "Team") { targetAllyAoe(it) } val TeamDamageTakenDownBuffPassive: PassiveEffect = GenericBuffPassive(DamageTakenDownBuff, EffectTag.Damage, "Team") { targetAllyAoe(it) } val TeamBrillianceGainUpBuffPassive: PassiveEffect = GenericBuffPassive(BrillianceGainUpBuff, EffectTag.BrillianceUp, "Team") { targetAllyAoe(it) } val TeamBrillianceRegenBuffPassive: PassiveEffect = GenericBuffPassive(BrillianceRegenBuff, EffectTag.BrillianceRegeneration, "Team") { targetAllyAoe(it) } val SelfBrillianceRegenBuffPassive: PassiveEffect = GenericBuffPassive(BrillianceRegenBuff, EffectTag.BrillianceRegeneration, "Self") { targetSelf() } val SelfLockedBrillianceRegenBuffPassive: PassiveEffect = GenericBuffPassive(LockedBrillianceRegenBuff, EffectTag.BrillianceRegeneration, "Self") { targetSelf() } val TeamNegativeCountableEffectResistanceBuffPassive: PassiveEffect = GenericBuffPassive(NegativeCountableEffectResistanceBuff, EffectTag.NegativeCountableResistance, "Team") { targetAllyAoe(it) } val TeamLockedNegativeCountableEffectResistanceBuffPassive: PassiveEffect = GenericBuffPassive(LockedNegativeCountableResistanceBuff, EffectTag.NegativeCountableResistance, "Team") { targetAllyAoe(it) } val TeamConfusionResistanceBuffPassive: PassiveEffect = ResistanceBuffPassive(ConfusionResistanceBuff, EffectTag.ConfusionResistance, "Team") { targetAllyAoe(it) } val TeamStopResistanceBuffPassive: PassiveEffect = ResistanceBuffPassive(StopResistanceBuff, EffectTag.StopResistance, "Team") { targetAllyAoe(it) } val SelfStopResistanceBuffPassive: PassiveEffect = ResistanceBuffPassive(StopResistanceBuff, EffectTag.StopResistance) { targetSelf() } val TeamStunResistanceBuffPassive: PassiveEffect = ResistanceBuffPassive(StunResistanceBuff, EffectTag.StunResistance, "Team") { targetAllyAoe(it) } val TeamBurnResistanceBuffPassive: PassiveEffect = ResistanceBuffPassive(BurnResistanceBuff, EffectTag.BurnResistance, "Team") { targetAllyAoe(it) } val TeamFreezeResistanceBuffPassive: PassiveEffect = ResistanceBuffPassive(FreezeResistanceBuff, EffectTag.FreezeResistance, "Team") { targetAllyAoe(it) } val TeamBlindnessResistanceBuffPassive: PassiveEffect = ResistanceBuffPassive(BlindnessResistanceBuff, EffectTag.BlindnessResistance, "Team") { targetAllyAoe(it) } val TeamSleepResistanceBuffPassive: PassiveEffect = ResistanceBuffPassive(SleepResistanceBuff, EffectTag.SleepResistance, "Team") { targetAllyAoe(it) } val EnemyBack1ConfusionBuffPassive: PassiveEffect = DebuffPassive(ConfusionBuff, EffectTag.Confusion, "Enemy Back 1") { targetBack(1) } val EnemyBack1DazeBuffPassive: PassiveEffect = CountableDebuffPassive(CountableBuff.Daze, EffectTag.Daze, "Enemy Back 1") { targetBack(1) } val EnemyFront3NightmareBuffPassive: PassiveEffect = DebuffPassive(NightmareBuff, EffectTag.Nightmare, "Enemy Front 3", 80) { targetFront(3) } val EnemyBack3StopBuffPassive: PassiveEffect = DebuffPassive(StopBuff, EffectTag.Stop, "Enemy Back 3", 80) { targetBack(3) } val EnemyActPowerDownBuffPassive: PassiveEffect = GenericBuffPassive(ActPowerDownBuff, EffectTag.Act, "Enemy AoE") { targetAoe(it) } val EnemyDexterityDownBuffPassive: PassiveEffect = GenericBuffPassive(DexterityDownBuff, EffectTag.Dexterity, "Enemy AoE") { targetAoe(it) } val EnemyNormalDefenseBuffPassive: PassiveEffect = GenericBuffPassive(NormalDefenseDownBuff, EffectTag.Defense, "Enemy AoE") { targetAoe(it) } val EnemySpecialDefenseBuffPassive: PassiveEffect = GenericBuffPassive(SpecialDefenseDownBuff, EffectTag.SpecialDefense, "Enemy AoE") { targetAoe(it) } val EnemyFront5APUpBuffPassive : PassiveEffect = GenericBuffPassive(ApUpBuff, EffectTag.ApUp, "Enemy Front 5") { targetFront(5) } val EnemyBack2APUpBuffPassive : PassiveEffect = GenericBuffPassive(ApUpBuff, EffectTag.ApUp, "Enemy Back 2") { targetBack(2) } val EnemyBack3APUpBuffPassive : PassiveEffect = GenericBuffPassive(ApUpBuff, EffectTag.ApUp, "Enemy Back 3") { targetBack(3) } val EnemyBack2LockedAPUpBuffPassive : PassiveEffect = GenericBuffPassive(LockedApUpBuff, EffectTag.ApUp, "Enemy Back 2") { targetBack(2) } val EnemyBack3LockedAPUpBuffPassive : PassiveEffect = GenericBuffPassive(LockedApUpBuff, EffectTag.ApUp, "Enemy Back 3") { targetBack(3) } val EnemyAPUpBuffPassive : PassiveEffect = GenericBuffPassive(ApUpBuff, EffectTag.ApUp, "Enemy AoE") { targetAoe(it) } val EnemyProvokeBuffPassive: PassiveEffect = GenericBuffPassive(ProvokeBuff, EffectTag.Provoke, "Enemy AoE") { targetAoe(it) } val EnemyAggroBuffPassive: PassiveEffect = GenericBuffPassive(AggroBuff, EffectTag.Aggro, "Enemy AoE") { targetAoe(it) } val EnemyLockedAggroBuffPassive: PassiveEffect = GenericBuffPassive(LockedAggroBuff, EffectTag.Aggro, "Enemy AoE") { targetAoe(it) } val EnemyDazeBuffPassive: PassiveEffect = CountableDebuffPassive(CountableBuff.Daze, EffectTag.Daze, "Enemy AoE") { targetAoe(it) } val EnemyPrideBuffPassive: PassiveEffect = CountableDebuffPassive(CountableBuff.Pride, EffectTag.Pride, "Enemy AoE") {targetAoe(it)} val EnemyFront5StunBuffPassive: PassiveEffect = DebuffPassive(StunBuff, EffectTag.Stun, "Enemy Front 5") { targetFront(5) } val EnemyStunBuffPassive: PassiveEffect = DebuffPassive(StunBuff, EffectTag.Stun, "Enemy AoE") { targetAoe(it) } val EnemyFront2FreezeBuffPassive: PassiveEffect = DebuffPassive(FreezeBuff, EffectTag.Freeze, "Enemy Front 2") { targetFront(2) } val EnemyFront5ConfusionBuffPassive: PassiveEffect = DebuffPassive(ConfusionBuff, EffectTag.Confusion, "Enemy Front 5") { targetFront(5) } val EnemyFront5ElectricShockBuffPassive: PassiveEffect = DebuffPassive(ElectricShockBuff, EffectTag.ElectricShock, "Enemy Front 5") { targetFront(5) } val EnemyElectricShockBuffPassive: PassiveEffect = DebuffPassive(ElectricShockBuff, EffectTag.ElectricShock, "Enemy AoE") { targetAoe(it) } val EnemyFront5LovesicknessBuffPassive: PassiveEffect = DebuffPassive(LovesicknessBuff, EffectTag.Lovesickness, "Enemy Front 5") { targetFront(5) } val EnemyLovesicknessBuffPassive: PassiveEffect = DebuffPassive(LovesicknessBuff, EffectTag.Lovesickness, "Enemy AoE") { targetAoe(it) } val EnemyBurnBuffPassive: PassiveEffect = DebuffPassive(BurnBuff, EffectTag.Burn, "Enemy AoE") { targetAoe(it) } val EnemyPoisonBuffPassive: PassiveEffect = DebuffPassive(PoisonBuff, EffectTag.Poison, "Enemy AoE") { targetAoe(it) } val EnemyBack2SleepBuffPassive: PassiveEffect = DebuffPassive(SleepBuff, EffectTag.Sleep, "Enemy Back 2") { targetBack(2) } private data class GenericBuffPassive( val buffEffect: TimedBuffEffect, val tag: EffectTag, val targetName: String = "Self", val target: ActionContext.(Condition) -> TargetContext, ) : PassiveEffect { override val name = "Auto Buff ${buffEffect.name} ($targetName)" override val category = PassiveEffectCategory.TurnStartPositiveB override val tags = listOf(tag) override fun activate(context: ActionContext, value: Int, time: Int, condition: Condition) = target(context, condition).act { applyBuff(buffEffect, value, time) } } private data class GenericCountableBuffPassive( val buff: CountableBuff, val tag: EffectTag, val targetName: String = "Self", val target: ActionContext.(Condition) -> TargetContext, ) : PassiveEffect { override val name = "Auto Countable Buff ${buff.name} ($targetName)" override val category = PassiveEffectCategory.TurnStartPositiveB override val tags = listOf(tag) override fun activate(context: ActionContext, value: Int, time: Int, condition: Condition) = target(context, condition).act { applyCountableBuff(buff, time, value) } } private data class ResistanceBuffPassive( val buffEffect: TimedBuffEffect, val tag: EffectTag, val targetName: String = "Team", val target: ActionContext.(Condition) -> TargetContext, ) : PassiveEffect { override val name = "Auto Resistance Buff ${buffEffect.name} ($targetName)" override val category = PassiveEffectCategory.TurnStartPositiveB override val tags = listOf(tag) override fun activate(context: ActionContext, value: Int, time: Int, condition: Condition) = target(context, condition).act { applyBuff(buffEffect, value, time) } } private data class DebuffPassive( val buffEffect: TimedBuffEffect, val tag: EffectTag, val targetName: String = "Enemy Team", val chance: Int = 100, val target: ActionContext.(Condition) -> TargetContext, ) : PassiveEffect { override val name = "Auto Debuff ${buffEffect.name} ($targetName)" override val category = PassiveEffectCategory.TurnStartNegative override val tags = listOf(tag) override fun activate(context: ActionContext, value: Int, time: Int, condition: Condition) = target(context, condition).act { applyBuff(buffEffect, value, time, chance) } } private data class CountableDebuffPassive( val buff: CountableBuff, val tag: EffectTag, val targetName: String = "Enemy Team", val target: ActionContext.(Condition) -> TargetContext, ) : PassiveEffect { override val name = "Auto Countable Debuff ${buff.name} ($targetName)" override val category = PassiveEffectCategory.TurnStartNegative override val tags = listOf(tag) override fun activate(context: ActionContext, value: Int, time: Int, condition: Condition) = target(context, condition).act { applyCountableBuff(buff, time, value) } } data class AllyStageEffectPassive( val effect: StageEffect ) : PassiveEffect { override val name = "Auto Ally Stage Effect [${effect.name}]" override val category = PassiveEffectCategory.TurnStartPositiveA //Unconfirmed category override fun activate(context: ActionContext, value: Int, time: Int, condition: Condition) = context.run { applyAllyStageEffect(effect, time, value) } } data class EnemyStageEffectPassive( val effect: StageEffect ) : PassiveEffect { override val name = "Auto Enemy Stage Effect [${effect.name}]" override val category = PassiveEffectCategory.TurnStartNegative //Unconfirmed category override fun activate(context: ActionContext, value: Int, time: Int, condition: Condition) = context.run { applyEnemyStageEffect(effect, time, value) } } data class DispelTimedBuffPassive( val buff: TimedBuffEffect, ) : PassiveEffect { override val name = "Auto Dispel Timed Buff [${buff.name}]" override val category = PassiveEffectCategory.TurnStartNegative //Unconfirmed category override fun activate(context: ActionContext, value: Int, time: Int, condition: Condition) = context.run { targetAoe(condition).act { dispelTimed(buff) } } } object DispelRevivePassive : PassiveEffect { override val name = "Auto Dispel Revive" override val category = PassiveEffectCategory.TurnStartPositiveB // Why? override fun activate(context: ActionContext, value: Int, time: Int, condition: Condition) = context.run { targetAoe(condition).act { dispelCountable(CountableBuff.Revive, time) } } } object DispelFortitudePassive : PassiveEffect { override val name = "Auto Dispel Fortitude" override val category = PassiveEffectCategory.TurnStartPositiveB // Why? override fun activate(context: ActionContext, value: Int, time: Int, condition: Condition) = context.run { targetAoe(condition).act { dispelCountable(CountableBuff.Fortitude, time) } } }
0
Kotlin
11
7
70e1cfaee4c2b5ab4deff33b0e4fd5001c016b74
20,059
relight
MIT License
app/src/main/java/io/github/wellingtoncosta/cursoandroidcongressodeti/resources/repository/ContatoRepositoryImpl.kt
ericcleao
201,647,675
true
{"Kotlin": 10478}
package io.github.wellingtoncosta.cursoandroidcongressodeti.resources.repository import io.github.wellingtoncosta.cursoandroidcongressodeti.domain.entity.Contato import io.github.wellingtoncosta.cursoandroidcongressodeti.domain.repository.ContatoRepository import io.github.wellingtoncosta.cursoandroidcongressodeti.resources.database.dao.ContatoFavoritoDao import io.github.wellingtoncosta.cursoandroidcongressodeti.resources.database.entity.toDomain import io.github.wellingtoncosta.cursoandroidcongressodeti.resources.database.entity.toEntity import io.github.wellingtoncosta.cursoandroidcongressodeti.resources.extension.runAsync import io.github.wellingtoncosta.cursoandroidcongressodeti.resources.network.ContatoApi import io.github.wellingtoncosta.cursoandroidcongressodeti.resources.network.entity.toDomain class ContatoRepositoryImpl( private val api: ContatoApi, private val dao: ContatoFavoritoDao ) : ContatoRepository { override fun listarTodos(): List<Contato> { return runAsync { api.listarTodos().map { it.toDomain() } } } override fun listarFavoritos(): List<Contato> { return runAsync { dao.listarTodos().map { it.toDomain() } } } override fun buscarPorId(contatoId: Int): Contato? { return runAsync { val response = api.buscarPorId(contatoId) if(response != null) { val favorito = dao.buscarPorContatoId(contatoId) response.toDomain().copy(favoritoId = favorito?.id) } else { null } } } override fun favoritar(contato: Contato): Contato { return runAsync { val favorito = dao.buscarPorContatoId(contato.id) if(favorito == null) { val favoritoId = dao.inserir(contato.toEntity()) contato.copy(favoritoId = favoritoId.toInt()) } else { dao.deletar(contato.toEntity()) contato.copy(favoritoId = null) } } } }
0
Kotlin
0
0
d0d7dab3a099feb300e1ec35e6c7a27671faef89
2,073
curso-android-congresso-ti
MIT License
app/src/main/java/com/concordium/wallet/data/model/AccountBalance.kt
Concordium
750,205,274
false
{"Kotlin": 1736626, "Java": 68714, "HTML": 52929, "CSS": 256}
package com.concordium.wallet.data.model import java.io.Serializable data class AccountBalance( val finalizedBalance: AccountBalanceInfo? ) : Serializable { fun accountExists(): Boolean = finalizedBalance != null }
13
Kotlin
0
1
734ec0fc9111970d12722f24db6fcbbda547fd05
233
cryptox-android
Apache License 2.0
kittybot/src/main/kotlin/org/bezsahara/kittybot/telegram/classes/media/Story.kt
bezsahara
846,146,531
false
{"Kotlin": 752625}
package org.bezsahara.kittybot.telegram.classes.media import kotlinx.serialization.Serializable import org.bezsahara.kittybot.telegram.classes.chats.Chat /** * This object represents a story. * * *[link](https://core.telegram.org/bots/api#story)*: https://core.telegram.org/bots/api#story * * @param chat Chat that posted the story * @param id Unique identifier for the story in the chat */ @Serializable data class Story( val chat: Chat, val id: Long )
0
Kotlin
1
5
a0b831c9f4ad00f681b2bfba5376e321766a8cfe
476
TelegramKitty
MIT License
src/main/kotlin/nl/hiddewieringa/money/CurrencyContextExtensions.kt
hiddewie
356,896,982
false
null
package nl.hiddewieringa.money import javax.money.CurrencyContext import javax.money.CurrencyContextBuilder /** * @see CurrencyContextBuilder.of */ fun currencyContext(provider: String, init: CurrencyContextBuilder.() -> Unit = {}): CurrencyContext = CurrencyContextBuilder .of(provider) .apply(init) .build() /** * @see CurrencyContextBuilder.of */ fun currencyContext(currencyContext: CurrencyContext, init: CurrencyContextBuilder.() -> Unit = {}): CurrencyContext = CurrencyContextBuilder .of(currencyContext) .apply(init) .build()
0
Kotlin
0
8
41781dd81c958572ffaedd84f92752eec62e6966
597
money-kotlin
Apache License 2.0
src/main/kotlin/no/njoh/pulseengine/modules/graphics/renderers/TextureBatchRenderer.kt
NiklasJohansen
239,208,354
false
null
package no.njoh.pulseengine.modules.graphics.renderers import no.njoh.pulseengine.data.assets.Texture import no.njoh.pulseengine.modules.graphics.* import org.lwjgl.opengl.GL11.* class TextureBatchRenderer( private val initialCapacity: Int, private val renderState: RenderState, private val graphicsState: GraphicsState ) : BatchRenderer { private var vertexCount = 0 private lateinit var program: ShaderProgram private lateinit var vao: VertexArrayObject private lateinit var vbo: FloatBufferObject private lateinit var ebo: IntBufferObject override fun init() { vao = VertexArrayObject.createAndBind() val layout = VertexAttributeLayout() .withAttribute("position",3, GL_FLOAT) .withAttribute("offset", 2, GL_FLOAT) .withAttribute("rotation", 1, GL_FLOAT) .withAttribute("texCoord", 2, GL_FLOAT) .withAttribute("texIndex",1, GL_FLOAT) .withAttribute("color",1, GL_FLOAT) if (!this::program.isInitialized) { val capacity = initialCapacity * layout.stride * 4L vbo = BufferObject.createAndBind(capacity) ebo = BufferObject.createAndBindElementBuffer(capacity / 6) program = ShaderProgram.create("/pulseengine/shaders/default/arrayTexture.vert", "/pulseengine/shaders/default/arrayTexture.frag").bind() } vbo.bind() ebo.bind() program.bind() program.defineVertexAttributeArray(layout) program.setUniform("textureArray", 0) vao.release() } fun drawTexture(texture: Texture, x: Float, y: Float, w: Float, h: Float, rot: Float, xOrigin: Float, yOrigin: Float) { val uMin = texture.uMin val vMin = texture.vMin val uMax = texture.uMax val vMax = texture.vMax val texIndex = texture.id.toFloat() + if (texture.format == GL_ALPHA) 0.5f else 0.0f val xOffset = w * xOrigin val yOffset = h * yOrigin val rgba = renderState.rgba val depth = renderState.depth vbo.put(x, y, depth, -xOffset, -yOffset, rot, uMin, vMin, texIndex, rgba) vbo.put(x, y, depth, -xOffset, h-yOffset, rot, uMin, vMax, texIndex, rgba) vbo.put(x, y, depth, w-xOffset, h-yOffset, rot, uMax, vMax, texIndex, rgba) vbo.put(x, y, depth, w-xOffset, -yOffset, rot, uMax, vMin, texIndex, rgba) ebo.put( vertexCount + 0, vertexCount + 1, vertexCount + 2, vertexCount + 2, vertexCount + 3, vertexCount + 0 ) vertexCount += 4 renderState.increaseDepth() } fun drawTexture(texture: Texture, x: Float, y: Float, w: Float, h: Float, rot: Float, xOrigin: Float, yOrigin: Float, uMin: Float, vMin: Float, uMax: Float, vMax: Float) { val uMax = texture.uMax * uMax val vMax = texture.vMax * vMax val uMin = texture.uMax * uMin val vMin = texture.vMax * vMin val index = texture.id.toFloat() val xOffset = w * xOrigin val yOffset = h * yOrigin val rgba = renderState.rgba val depth = renderState.depth vbo.put(x, y, depth, -xOffset, -yOffset, rot, uMin, vMin, index, rgba) vbo.put(x, y, depth, -xOffset, h-yOffset, rot, uMin, vMax, index, rgba) vbo.put(x, y, depth, w-xOffset, h-yOffset, rot, uMax, vMax, index, rgba) vbo.put(x, y, depth, w-xOffset, -yOffset, rot, uMax, vMin, index, rgba) ebo.put( vertexCount + 0, vertexCount + 1, vertexCount + 2, vertexCount + 2, vertexCount + 3, vertexCount + 0 ) vertexCount += 4 renderState.increaseDepth() } override fun render(camera: CameraEngineInterface) { if (vertexCount == 0) return vao.bind() vbo.bind() ebo.bind() program.bind() program.setUniform("projection", camera.projectionMatrix) program.setUniform("view", camera.viewMatrix) program.setUniform("model", camera.modelMatrix) graphicsState.textureArray.bind() vbo.flush() ebo.flush() ebo.draw(GL_TRIANGLES, 1) vertexCount = 0 vao.release() } override fun cleanup() { vbo.delete() vao.delete() ebo.delete() program.delete() } }
0
Kotlin
0
0
d2c0d09732fed1f2221ee17e5a28f0e50857b333
4,475
PulseEngine
MIT License
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findFunctionUsages/labeledReturns.0.kt
ingokegel
72,937,917
false
null
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtNamedFunction // OPTIONS: usages // PSI_ELEMENT_AS_TITLE: "fun <R> foo(??)" fun <R> <caret>foo(f: () -> R) = f() fun test() { foo { return@foo false } foo(fun(): Boolean { return@foo false }) }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
262
intellij-community
Apache License 2.0
mvp/src/main/java/com/xueqiu/shelf/mvp/IPresenter.kt
snowman-team
202,502,980
false
null
package com.xueqiu.shelf.mvp interface IPresenter<V : IViewer> { fun attachView(view: V) fun detachView(retainInstance: Boolean) }
0
Kotlin
0
0
c15df08149e7d62d598caca38abf4da63f9caf6e
139
Shelf
Apache License 2.0
macrobenchmark/src/main/java/com/csc2002s/assgnmnts/apps/alphabetapplication/macrobenchmark/AlphabetListBenchmarks.kt
BongaNjamela001
546,213,500
false
null
package com.csc2002s.assgnmnts.apps.alphabetapplication.macrobenchmark import androidx.benchmark.macro.CompilationMode import androidx.benchmark.macro.FrameTimingMetric import androidx.benchmark.macro.MacrobenchmarkScope import androidx.benchmark.macro.StartupMode import androidx.benchmark.macro.junit4.MacrobenchmarkRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.uiautomator.By import androidx.test.uiautomator.Until import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class AlphabetListBenchmarks { @get:Rule val benchmarkRule = MacrobenchmarkRule() @Test fun openAlphabetList() = openAlphabetList(CompilationMode.None()) @Test fun alphabetListCompilationPartial() = openAlphabetList(CompilationMode.Partial()) @Test fun alphabetListCompilationFull() = openAlphabetList(CompilationMode.Full()) private fun openAlphabetList(compilationMode: CompilationMode) = benchmarkRule.measureRepeated( packageName = PACKAGE_NAME, metrics = listOf(FrameTimingMetric()), compilationMode = compilationMode, iterations = 5, startupMode = StartupMode.COLD, setupBlock = { pressHome() // Start the default activity, but don't measure the frames yet startActivityAndWait() } ) { goToAlphabetListTab() } } fun MacrobenchmarkScope.goToAlphabetListTab() { // Find the tab with plants list val alphabetListTab = device.findObject(By.descContains("Alphabet list")) alphabetListTab.click() // Wait until plant list has children val recyclerHasChild = By.hasChild(By.res(packageName, "alphabet_list")) device.wait(Until.hasObject(recyclerHasChild), 5_000) // Wait until idle device.waitForIdle() }
0
Kotlin
0
0
29aa5c1862d5da19d646d56993b06b08036e74ad
1,907
Alphabet-Kotlin-App
Apache License 2.0
app/src/main/java/com/codingwithset/minie_commerce/utils/Utils.kt
ayetolusamuel
267,192,186
false
null
package com.codingwithset.minie_commerce.utils import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.net.Uri import android.os.Build import android.os.Message import android.util.Log import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.Toast import com.codingwithset.minie_commerce.R /* this function [callSeller] call the merchant */ fun View.callSeller() { val phone: String = context.getString(R.string.seller_number_developer) val intent = Intent(Intent.ACTION_DIAL, Uri.fromParts(context.getString(R.string.tel), phone, null)) context.startActivity(intent) } /* set the view visibility to be visible */ fun View.visible() { this.visibility = View.VISIBLE } /* set the view visibility to be gone */ fun View.gone() { this.visibility = View.GONE } /** * Check whether network is available * @return Whether device is connected to Network. */ fun Context.checkInternetAccess(): Boolean { try { with(getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //Device is running on Marshmallow or later Android OS. with(getNetworkCapabilities(activeNetwork)) { @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") return hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || hasTransport( NetworkCapabilities.TRANSPORT_CELLULAR ) } } else { @Suppress("DEPRECATION") activeNetworkInfo?.let { // connected to the internet @Suppress("DEPRECATION") return listOf( ConnectivityManager.TYPE_WIFI, ConnectivityManager.TYPE_MOBILE ).contains(it.type) } } } return false } catch (exc: NullPointerException) { return false } } fun Context.message(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } fun Context.chatSeller() { try { val browserIntent = Intent( Intent.ACTION_VIEW, Uri.parse(this.getString(R.string.seller_whatsap_link)) ) this.startActivity(browserIntent) } catch (exception: PackageManager.NameNotFoundException) { Log.e("Utils", exception.toString()) message("Whastsapp is not install on your phone") } } /* hide the keyboard */ fun Activity.hideKeyboard() { val inputMethodManager: InputMethodManager? = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager? inputMethodManager?.hideSoftInputFromWindow(currentFocus!!.windowToken, 0) }
0
Kotlin
2
3
a36b33cde873296681384a511c23c9b10ba4b02b
3,013
Mini-Shop
Apache License 2.0
application/src/main/kotlin/tech/alexib/yaba/server/plaid/entity/LinkMetadata.kt
ruffCode
381,245,396
false
null
/* * Copyright 2021 Alexi Bre * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.alexib.yaba.server.plaid.entity import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class LinkMetadata( val accounts: List<LinkAccount>, val institution: LinkInstitution, @SerialName("link_session_id") val linkSessionId: String, @SerialName("public_token") val publicToken: String ) @Serializable data class LinkInstitution( @SerialName("institution_id") val institutionId: String, val name: String ) @Serializable data class LinkAccount( val id: String, val mask: String, val name: String, val subtype: String, val type: String )
5
Kotlin
0
1
0f5ac0bf3e0cb9dedf8499b0763ea85eba4248ba
1,247
yaba-server
Apache License 2.0
httpserver/src/test/kotlin/TestData.kt
TBD54566975
696,627,382
false
null
import de.fxlae.typeid.TypeId import tbdex.sdk.protocol.models.Close import tbdex.sdk.protocol.models.CloseData import tbdex.sdk.protocol.models.MessageKind import tbdex.sdk.protocol.models.Offering import tbdex.sdk.protocol.models.Order import tbdex.sdk.protocol.models.PaymentInstruction import tbdex.sdk.protocol.models.Quote import tbdex.sdk.protocol.models.QuoteData import tbdex.sdk.protocol.models.QuoteDetails import tbdex.sdk.protocol.models.Rfq import tbdex.sdk.protocol.models.RfqData import tbdex.sdk.protocol.models.SelectedPaymentMethod import web5.sdk.crypto.InMemoryKeyManager import web5.sdk.dids.methods.dht.DidDht import java.time.OffsetDateTime object TestData { val aliceDid = DidDht.create(InMemoryKeyManager()) val pfiDid = DidDht.create(InMemoryKeyManager()) fun createRfq(offering: Offering? = null, claims: List<String>? = emptyList()): Rfq { return Rfq.create( to = pfiDid.uri, from = aliceDid.uri, rfqData = RfqData( offeringId = offering?.metadata?.id ?: TypeId.generate("offering").toString(), payinAmount = "1.00", payinMethod = SelectedPaymentMethod( kind = offering?.data?.payinMethods?.first()?.kind ?: "USD", paymentDetails = mapOf("foo" to "bar") ), payoutMethod = SelectedPaymentMethod( kind = offering?.data?.payoutMethods?.first()?.kind ?: "BTC", paymentDetails = mapOf("foo" to "bar") ), claims = claims ?: emptyList() ) ) } fun createOrder(exchangeId: String, protocol: String = "1.0") = Order.create( to = pfiDid.uri, from = aliceDid.uri, exchangeId = exchangeId, protocol = protocol ) fun createClose(exchangeId: String, protocol: String = "1.0") = Close.create( to = pfiDid.uri, from = aliceDid.uri, exchangeId = exchangeId, protocol = protocol, closeData = CloseData(reason = "test close reason") ) fun createQuote( exchangeId: String = TypeId.generate(MessageKind.rfq.name).toString(), expiresAt: OffsetDateTime = OffsetDateTime.now().plusDays(1) ) = Quote.create( to = aliceDid.uri, from = pfiDid.uri, exchangeId = exchangeId, quoteData = QuoteData( expiresAt = expiresAt, payin = QuoteDetails("AUD", "10.00", "0.1", PaymentInstruction( link = "https://block.xyz", instruction = "payin instruction" )), payout = QuoteDetails("BTC", "0.12", "0.02", PaymentInstruction( link = "https://block.xyz", instruction = "payout instruction" )) ) ) }
34
null
3
3
1be394dd757eee8c966c6d83c3bf0b112d3b93c5
2,569
tbdex-kt
Apache License 2.0
panel-kotlin/src/main/java/com/effective/android/panel/view/ContentContainer.kt
veloz17
357,704,542
true
{"Kotlin": 109823, "Java": 102377}
package com.effective.android.panel.view import android.annotation.TargetApi import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.EditText import android.widget.LinearLayout import androidx.annotation.IdRes import com.effective.android.panel.R import com.effective.android.panel.view.content.ContentContainerImpl import com.effective.android.panel.view.content.IContentContainer /** * -------------------- * | PanelSwitchLayout | * | ---------------- | * | | | | * | |ContentContainer| | * | | | | * | ---------------- | * | ---------------- | * | | PanelContainer | | * | ---------------- | * -------------------- * Created by yummyLau on 18-7-10 * Email: <EMAIL> * blog: yummylau.com * update by yummylau on 2020/05/07 请使用 [com.effective.android.panel.view.content.ContentLinearContainer] 后续该类将被遗弃 */ @Deprecated("use ContentLinearContainer instead of it") class ContentContainer : LinearLayout, IContentContainer { @IdRes var editTextId = 0 @IdRes var emptyViewId = 0 private var contentContainer: ContentContainerImpl? = null @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) { initView(attrs, defStyleAttr, 0) } @TargetApi(21) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { initView(attrs, defStyleAttr, defStyleRes) } private fun initView(attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ContentContainer, defStyleAttr, 0) if (typedArray != null) { editTextId = typedArray.getResourceId(R.styleable.ContentContainer_edit_view, -1) emptyViewId = typedArray.getResourceId(R.styleable.ContentContainer_empty_view, -1) typedArray.recycle() } orientation = VERTICAL } override fun onFinishInflate() { super.onFinishInflate() contentContainer = ContentContainerImpl(this, editTextId, emptyViewId) } override fun layoutGroup(l: Int, t: Int, r: Int, b: Int) { contentContainer!!.layoutGroup(l, t, r, b) } override fun findTriggerView(id: Int): View? { return contentContainer!!.findTriggerView(id) } override fun adjustHeight(targetHeight: Int) { contentContainer!!.adjustHeight(targetHeight) } override fun emptyViewVisible(visible: Boolean) { contentContainer!!.emptyViewVisible(visible) } override fun setEmptyViewClickListener(l: OnClickListener) { contentContainer!!.setEmptyViewClickListener(l) } override fun getEditText(): EditText { return contentContainer!!.getEditText() } override fun setEditTextClickListener(l: OnClickListener) { contentContainer!!.setEditTextClickListener(l) } override fun setEditTextFocusChangeListener(l: OnFocusChangeListener) { contentContainer!!.setEditTextFocusChangeListener(l) } override fun clearFocusByEditText() { contentContainer!!.clearFocusByEditText() } override fun requestFocusByEditText() { contentContainer!!.requestFocusByEditText() } override fun editTextHasFocus(): Boolean { return contentContainer!!.editTextHasFocus() } override fun preformClickForEditText() { contentContainer!!.preformClickForEditText() } }
0
null
0
0
ac4f611f12d6c44e70b1fc7e1bb4ecebe9a6ea60
3,608
emoji_keyboard
Apache License 2.0
app/src/main/java/com/example/android/pokedex/model/Converters.kt
quochuyhl99
704,825,857
false
{"Kotlin": 46836}
package com.example.android.pokedex.model import androidx.room.TypeConverter class TypesConverter { @TypeConverter fun fromTypes(types: List<String>): String { return types.joinToString(separator = ",") } @TypeConverter fun toTypes(typesString: String): List<String> { return typesString.split(",") } }
0
Kotlin
0
0
baf077a0338be6e5ca0501979e51a0cf15eccf27
345
Pokedex
Apache License 2.0
app/src/main/java/cc/oxie/morsebuzzer/BuzzNotificationListenerService.kt
mathieucaroff
468,682,670
false
null
package cc.oxie.morsebuzzer import android.content.Context import android.content.Intent import android.os.Build import android.os.IBinder import android.os.Vibrator import android.service.notification.NotificationListenerService import android.service.notification.StatusBarNotification import android.util.Log import androidx.annotation.RequiresApi class BuzzNotificationListenerService : NotificationListenerService() { private var vibrator: Vibrator? = null override fun onBind(intent: Intent?): IBinder? { return super.onBind(intent) } override fun onCreate() { super.onCreate() this.vibrator = (getSystemService(Context.VIBRATOR_SERVICE) as Vibrator) } @RequiresApi(Build.VERSION_CODES.O) override fun onNotificationPosted(sbn: StatusBarNotification) { if (false || sbn.packageName.endsWith("android.apps.maps") || sbn.packageName.endsWith("android.dialer") ) { // com.google.android.apps.maps // ignore this app because it creates too many notification signals // com.google.android.dialer // ignore this because it creates notifications during phone calls return } val notificationEntry = NotificationEntry(sbn) var isDuplicate = false val app: MorseBuzzerApplication = applicationContext as MorseBuzzerApplication val size = app.NOTIFICATION_LOG_SIZE for (k in 0 until size) { if(notificationEntry.isSimilarTo(app.notificationLog[k])) { // duplicate encountered isDuplicate = true if (notificationEntry.isEqualTo(app.notificationLog[k])) { return } } } app.notificationLog[app.notificationLogIndex] = notificationEntry app.notificationLogIndex = (1 + app.notificationLogIndex) % size if (isDuplicate) { return } notificationEntry.vibrate(this.vibrator!!) } }
0
Kotlin
0
0
c7ff48c6c58df8055310c43c9d6099dd78c1ea7d
2,050
morsebuzzer
MIT License
src/me/anno/ui/editor/SettingCategory.kt
AntonioNoack
456,513,348
false
null
package me.anno.ui.editor import me.anno.ecs.prefab.PrefabSaveable import me.anno.input.MouseButton import me.anno.language.translation.Dict import me.anno.maths.Maths.mixARGB import me.anno.ui.Keys.isClickKey import me.anno.ui.Panel import me.anno.ui.base.components.Padding import me.anno.ui.base.groups.PanelGroup import me.anno.ui.base.groups.PanelListY import me.anno.ui.base.scrolling.ScrollPanelY import me.anno.ui.base.text.TextPanel import me.anno.ui.input.InputVisibility import me.anno.ui.style.Style import kotlin.math.max open class SettingCategory( val title: String, val visibilityKey: String, withScrollbar: Boolean, val canCopyTitleText: Boolean, style: Style ) : PanelGroup(style) { constructor(title: String, style: Style) : this(title, title, false, false, style) constructor(title: String, description: String, dictPath: String, style: Style) : this(title, description, dictPath, false, style) constructor(title: String, description: String, dictPath: String, withScrollbar: Boolean, style: Style) : this(Dict[title, dictPath], title, withScrollbar, false, style) { tooltip = Dict[description, "$dictPath.desc"] } val titlePanel = object : TextPanel(title, style.getChild("group")) { override fun onMouseClicked(x: Float, y: Float, button: MouseButton, long: Boolean) { if (button.isLeft && !long) toggle() else super.onMouseClicked(x, y, button, long) } override fun onCopyRequested(x: Float, y: Float): Any? { return if (canCopyTitleText) text else uiParent?.onCopyRequested(x, y) } } val content = PanelListY(style) val child = if (withScrollbar) ScrollPanelY(content, Padding.Zero, style) else content val padding = Padding((titlePanel.font.size * .667f).toInt(), 0, 0, 0) init { titlePanel.parent = this titlePanel.textColor = mixARGB(titlePanel.textColor, titlePanel.textColor and 0xffffff, 0.5f) titlePanel.focusTextColor = -1 child.parent = this } fun show2() { InputVisibility.show(visibilityKey, null) } fun toggle() { InputVisibility.toggle(visibilityKey, this) } override fun onUpdate() { val visible = InputVisibility[visibilityKey] child.isVisible = visible content.isVisible = visible super.onUpdate() } override fun onKeyTyped(x: Float, y: Float, key: Int) { if (key.isClickKey()) toggle() } override fun acceptsChar(char: Int) = char.isClickKey() override fun isKeyInput() = true override val children: List<Panel> = listOf(titlePanel, child) override fun remove(child: Panel) { throw RuntimeException("Not supported!") } val isEmpty get(): Boolean { val children = content.children for (index in children.indices) { val child = children[index] if (child.isVisible) { return false } } return true } override fun calculateSize(w: Int, h: Int) { this.width = w this.height = h if (isEmpty) { minW = 0 minH = 0 } else { titlePanel.calculateSize(w, h) if (child.isVisible) { child.calculateSize(w - padding.width, h) minW = max(titlePanel.minW, content.minW + padding.width) minH = titlePanel.minH + content.minH + padding.height } else { minW = titlePanel.minW minH = titlePanel.minH } } } // todo we should try to reduce 2^x layout classes, maybe by caching results // todo maybe within a frame, already would be good enough // todo test with deeply cascaded layouts :) override fun setPosition(x: Int, y: Int) { super.setPosition(x, y) titlePanel.setPosition(x, y) child.setPosition(x + padding.left, y + titlePanel.minH + padding.top) } operator fun plusAssign(child: Panel) { content.add(child) } override fun addChild(child: PrefabSaveable) { content.addChild(child) } }
0
Kotlin
1
9
b2532f7d40527eb2c9e24e3659dd904aa725a1aa
4,280
RemsEngine
Apache License 2.0
Week4/countingLetters.kt
InfiniteExalt
528,918,884
false
{"Kotlin": 18434, "Roff": 397}
//<NAME> //Unit 4 Assignment2 //Letter Counter //09-29-2022 fun main() { println("Enter a String>> ") val text=readLine()!! println("Enter one character>> ") val symbol= readLine()!![0] var count = 0 for( a in text) if(a == symbol) count++ println("The Character $symbol appears $count times in \"$text\"") }
0
Kotlin
0
2
673cd3f2dae1c7e7c18815e6b81dfab8552924d4
399
KotlinFall22
MIT License
app/src/main/java/com/gateoftruth/sample/MainActivity.kt
GateOfTruth
204,602,230
false
null
package com.gateoftruth.sample import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btn_download.setOnClickListener { startActivity(Intent(this, DownloadActivity::class.java)) } btn_get.setOnClickListener { startActivity(Intent(this, GetActivity::class.java)) } btn_post_params.setOnClickListener { startActivity(Intent(this, PostParamsActivity::class.java)) } btn_post_json.setOnClickListener { startActivity(Intent(this, PostJsonActivity::class.java)) } btn_bitmap.setOnClickListener { startActivity(Intent(this, BitmapActivity::class.java)) } btn_upload.setOnClickListener { startActivity(Intent(this, UploadFileActivity::class.java)) } btn_post_form.setOnClickListener { startActivity(Intent(this, PostFormActivity::class.java)) } btn_glide_test.setOnClickListener { startActivity(Intent(this, GlideTestActivity::class.java)) } btn_brotli_test.setOnClickListener { startActivity(Intent(this, BrotliActivity::class.java)) } btn_multiple_download.setOnClickListener { startActivity(Intent(this, MultipleDownloadActivity::class.java)) } btn_synchronize_request.setOnClickListener { startActivity(Intent(this, SynchronizeRequestActivity::class.java)) } btn_method_request.setOnClickListener { startActivity(Intent(this, MethodActivity::class.java)) } } }
0
Kotlin
6
56
b74f8b61a7631949ad9945aae55b7c14a1382898
1,903
OkSimple
Apache License 2.0
app/src/main/java/com/ubergeek42/WeechatAndroid/upload/ShareObject.kt
ubergeek42
3,555,504
false
null
package com.ubergeek42.WeechatAndroid.upload import android.content.Context import android.content.Intent import android.graphics.* import android.graphics.drawable.Drawable import android.net.Uri import android.text.* import android.widget.EditText import androidx.annotation.MainThread import androidx.lifecycle.findViewTreeLifecycleOwner import androidx.lifecycle.lifecycleScope import com.bumptech.glide.Glide import com.bumptech.glide.load.MultiTransformation import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.transition.Transition import com.ubergeek42.WeechatAndroid.media.Config import com.ubergeek42.WeechatAndroid.media.WAGlideModule.isContextValidForGlide import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import java.io.FileNotFoundException import java.io.IOException import kotlin.coroutines.resume enum class InsertAt { CURRENT_POSITION, END } interface ShareObject { fun insert(editText: EditText, insertAt: InsertAt) } data class TextShareObject( val text: CharSequence ) : ShareObject { @MainThread override fun insert(editText: EditText, insertAt: InsertAt) { editText.insertAddingSpacesAsNeeded(insertAt, text) } } // non-breaking space. regular spaces and characters can lead to some problems with some keyboards... const val PLACEHOLDER_TEXT = "\u00a0" open class UrisShareObject( private val suris: List<Suri> ) : ShareObject { override fun insert(editText: EditText, insertAt: InsertAt) { editText.findViewTreeLifecycleOwner()?.lifecycleScope?.launch { insertAsync(editText, insertAt) } } suspend fun insertAsync(editText: EditText, insertAt: InsertAt) { val thumbnailSpannables = coroutineScope { suris.map { async { makeThumbnailSpannable(editText.context, it) } }.awaitAll() } thumbnailSpannables.forEach { thumbnailSpannable -> editText.insertAddingSpacesAsNeeded(insertAt, thumbnailSpannable) } } companion object { @JvmStatic @Throws(FileNotFoundException::class, IOException::class, SecurityException::class) fun fromUris(uris: List<Uri>): UrisShareObject { return UrisShareObject(uris.map { Suri.fromUri(it) }) } } } //////////////////////////////////////////////////////////////////////////////////////////////////// suspend fun makeThumbnailSpannable(context: Context, suri: Suri): Spannable { val bitmapOrNull = getBitmapOrNull(context, suri.uri) val span = if (bitmapOrNull != null) BitmapShareSpan(suri, bitmapOrNull) else NonBitmapShareSpan(suri) return SpannableString(PLACEHOLDER_TEXT).apply { setSpan(span, 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } } // this starts the upload in a worker thread and exits immediately. // target callbacks will be called on the main thread suspend fun getBitmapOrNull(context: Context, uri: Uri): Bitmap? = suspendCancellableCoroutine { continuation -> if (isContextValidForGlide(context)) { Glide.with(context) .asBitmap() .diskCacheStrategy(DiskCacheStrategy.RESOURCE) .transform(MultiTransformation( NotQuiteCenterCrop(), RoundedCorners(Config.THUMBNAIL_CORNER_RADIUS), )) .load(uri) .into(object : CustomTarget<Bitmap>(THUMBNAIL_MAX_WIDTH, THUMBNAIL_MAX_HEIGHT) { @MainThread override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap>?) { continuation.resume(bitmap) } // The request seems to be attempted once again on minimizing/restoring the app. // To avoid that, clear target soon, but not on current thread--the library doesn't allow it. // See https://github.com/bumptech/glide/issues/4125 @MainThread override fun onLoadFailed(errorDrawable: Drawable?) { continuation.resume(null) main { Glide.with(context).clear(this) } } override fun onLoadCleared(placeholder: Drawable?) { // this shouldn't happen } }) } } //////////////////////////////////////////////////////////////////////////////////////////////////// @MainThread fun EditText.insertAddingSpacesAsNeeded(insertAt: InsertAt, word: CharSequence) { val pos = if (insertAt == InsertAt.CURRENT_POSITION) selectionEnd else text.length insertAddingSpacesAsNeeded(pos, word) } @MainThread fun EditText.insertAddingSpacesAsNeeded(pos: Int, word: CharSequence) { val wordStartsWithSpace = word.firstOrNull() == ' ' val wordEndsWithSpace = word.lastOrNull() == ' ' val spaceBeforeInsertLocation = pos > 0 && text[pos - 1] == ' ' val nonSpaceBeforeInsertLocation = pos > 0 && text[pos - 1] != ' ' val spaceAfterInsertLocation = pos < text.length && text[pos] == ' ' val nonSpaceAfterInsertLocation = pos < text.length && text[pos] != ' ' val shouldPrependSpace = nonSpaceBeforeInsertLocation && !wordStartsWithSpace val shouldAppendSpace = nonSpaceAfterInsertLocation && !wordEndsWithSpace val shouldCollapseSpacesBefore = spaceBeforeInsertLocation && wordStartsWithSpace val shouldCollapseSpacesAfter = spaceAfterInsertLocation && wordEndsWithSpace val wordWithSurroundingSpaces = SpannableStringBuilder() if (shouldPrependSpace) wordWithSurroundingSpaces.append(' ') wordWithSurroundingSpaces.append(word) if (shouldAppendSpace) wordWithSurroundingSpaces.append(' ') val replaceFrom = if (shouldCollapseSpacesBefore) pos - 1 else pos val replaceTo = if (shouldCollapseSpacesAfter) pos + 1 else pos text.replace(replaceFrom, replaceTo, wordWithSurroundingSpaces) if (pos < replaceTo) setSelection(replaceFrom + wordWithSurroundingSpaces.length) } //////////////////////////////////////////////////////////////////////////////////////////////////// // this simply loads all images for an intent so that they are cached in glide fun preloadThumbnailsForIntent(intent: Intent) { val uris = when (intent.action) { Intent.ACTION_SEND -> { val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM) if (uri == null) null else listOf(uri) } Intent.ACTION_SEND_MULTIPLE -> { intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) } else -> null } uris?.forEach { uri -> GlobalScope.launch { getBitmapOrNull(applicationContext, uri) } } }
38
null
107
516
f3da88c7d7abfe5ea3e46d8ebb908e5a907c27eb
7,020
weechat-android
Apache License 2.0
UiLogicInterface/src/main/java/com/martysuzuki/uilogicinterface/DiffableItem.kt
marty-suzuki
398,268,245
false
null
package com.martysuzuki.uilogicinterface interface DiffableItem { val identifier: String }
0
Kotlin
0
9
0116d5b14b854549b8e083985573b59bbe5f565a
95
MyFirstAndroidPractice
MIT License
app/src/main/java/com/vivylabs/titan/ui/component/BottomAppBarComponent.kt
vivylabs
568,878,457
false
{"Kotlin": 26910}
package com.vivylabs.titan.ui.component import androidx.compose.material.BottomAppBar import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.navigation.NavController import androidx.navigation.compose.currentBackStackEntryAsState import com.vivylabs.titan.ui.data.bottomAppBarItemList @Composable fun BottomAppBarComponent(navController: NavController) { BottomAppBar { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route bottomAppBarItemList.forEachIndexed { index, item -> if (index != 2) { BottomNavigationItem( icon = { Icon(item.icon, "") }, selected = currentRoute == item.route, onClick = { navController.navigate(item.route) } ) } else { BottomNavigationItem( icon = { Icon(item.icon, "") }, selected = false, onClick = {}, ) } } } }
0
Kotlin
0
0
e5dc3e48c3fae378d83713494f66ddf101219302
1,259
titan
MIT License
src/main/kotlin/com/github/kechinvv/voicerside/listeners/PluginAppActivationListener.kt
kechinvv
780,407,887
false
{"Kotlin": 19863}
package com.github.kechinvv.voicerside.listeners import com.github.kechinvv.voicerside.services.PluginService import com.intellij.ide.AppLifecycleListener internal class PluginAppActivationListener : AppLifecycleListener { private val service = PluginService.getInstance() override fun appClosing() { service.endRecognition() } override fun appWillBeClosed(isRestart: Boolean) { service.endRecognition() } }
0
Kotlin
1
0
b949202bc8c23830142c4ef3173c8ec91f946e33
447
VoicerSide
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/apigateway/RequestAuthorizer.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 140726596}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.apigateway import io.cloudshiftdev.awscdk.Duration import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.services.iam.IRole import io.cloudshiftdev.awscdk.services.lambda.IFunction import kotlin.String import kotlin.Unit import kotlin.collections.List import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct import software.constructs.Construct as SoftwareConstructsConstruct /** * Request-based lambda authorizer that recognizes the caller's identity via request parameters, * such as headers, paths, query strings, stage variables, or context variables. * * Based on the request, authorization is performed by a lambda function. * * Example: * * ``` * Function authFn; * Resource books; * RequestAuthorizer auth = RequestAuthorizer.Builder.create(this, "booksAuthorizer") * .handler(authFn) * .identitySources(List.of(IdentitySource.header("Authorization"))) * .build(); * books.addMethod("GET", new HttpIntegration("http://amazon.com"), MethodOptions.builder() * .authorizer(auth) * .build()); * ``` */ public open class RequestAuthorizer internal constructor( internal override val cdkObject: software.amazon.awscdk.services.apigateway.RequestAuthorizer, ) : Authorizer(cdkObject), IAuthorizer { /** * The ARN of the authorizer to be used in permission policies, such as IAM and resource-based * grants. */ public open fun authorizerArn(): String = unwrap(this).getAuthorizerArn() /** * The id of the authorizer. */ public override fun authorizerId(): String = unwrap(this).getAuthorizerId() /** * A fluent builder for [io.cloudshiftdev.awscdk.services.apigateway.RequestAuthorizer]. */ @CdkDslMarker public interface Builder { /** * An optional IAM role for APIGateway to assume before calling the Lambda-based authorizer. * * The IAM role must be * assumable by 'apigateway.amazonaws.com'. * * Default: - A resource policy is added to the Lambda function allowing * apigateway.amazonaws.com to invoke the function. * * @param assumeRole An optional IAM role for APIGateway to assume before calling the * Lambda-based authorizer. */ public fun assumeRole(assumeRole: IRole) /** * An optional human friendly name for the authorizer. * * Note that, this is not the primary identifier of the authorizer. * * Default: - the unique construct ID * * @param authorizerName An optional human friendly name for the authorizer. */ public fun authorizerName(authorizerName: String) /** * The handler for the authorizer lambda function. * * The handler must follow a very specific protocol on the input it receives * and the output it needs to produce. API Gateway has documented the * handler's [input * specification](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-input.html) * and [output * specification](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html). * * @param handler The handler for the authorizer lambda function. */ public fun handler(handler: IFunction) /** * An array of request header mapping expressions for identities. * * Supported parameter types are * Header, Query String, Stage Variable, and Context. For instance, extracting an authorization * token from a header would use the identity source `IdentitySource.header('Authorization')`. * * Note: API Gateway uses the specified identity sources as the request authorizer caching key. * When caching is * enabled, API Gateway calls the authorizer's Lambda function only after successfully verifying * that all the * specified identity sources are present at runtime. If a specified identify source is missing, * null, or empty, * API Gateway returns a 401 Unauthorized response without calling the authorizer Lambda * function. * * [Documentation](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateAuthorizer.html#apigw-CreateAuthorizer-request-identitySource) * @param identitySources An array of request header mapping expressions for identities. */ public fun identitySources(identitySources: List<String>) /** * An array of request header mapping expressions for identities. * * Supported parameter types are * Header, Query String, Stage Variable, and Context. For instance, extracting an authorization * token from a header would use the identity source `IdentitySource.header('Authorization')`. * * Note: API Gateway uses the specified identity sources as the request authorizer caching key. * When caching is * enabled, API Gateway calls the authorizer's Lambda function only after successfully verifying * that all the * specified identity sources are present at runtime. If a specified identify source is missing, * null, or empty, * API Gateway returns a 401 Unauthorized response without calling the authorizer Lambda * function. * * [Documentation](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateAuthorizer.html#apigw-CreateAuthorizer-request-identitySource) * @param identitySources An array of request header mapping expressions for identities. */ public fun identitySources(vararg identitySources: String) /** * How long APIGateway should cache the results. * * Max 1 hour. * Disable caching by setting this to 0. * * Default: - Duration.minutes(5) * * @param resultsCacheTtl How long APIGateway should cache the results. */ public fun resultsCacheTtl(resultsCacheTtl: Duration) } private class BuilderImpl( scope: SoftwareConstructsConstruct, id: String, ) : Builder { private val cdkBuilder: software.amazon.awscdk.services.apigateway.RequestAuthorizer.Builder = software.amazon.awscdk.services.apigateway.RequestAuthorizer.Builder.create(scope, id) /** * An optional IAM role for APIGateway to assume before calling the Lambda-based authorizer. * * The IAM role must be * assumable by 'apigateway.amazonaws.com'. * * Default: - A resource policy is added to the Lambda function allowing * apigateway.amazonaws.com to invoke the function. * * @param assumeRole An optional IAM role for APIGateway to assume before calling the * Lambda-based authorizer. */ override fun assumeRole(assumeRole: IRole) { cdkBuilder.assumeRole(assumeRole.let(IRole::unwrap)) } /** * An optional human friendly name for the authorizer. * * Note that, this is not the primary identifier of the authorizer. * * Default: - the unique construct ID * * @param authorizerName An optional human friendly name for the authorizer. */ override fun authorizerName(authorizerName: String) { cdkBuilder.authorizerName(authorizerName) } /** * The handler for the authorizer lambda function. * * The handler must follow a very specific protocol on the input it receives * and the output it needs to produce. API Gateway has documented the * handler's [input * specification](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-input.html) * and [output * specification](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html). * * @param handler The handler for the authorizer lambda function. */ override fun handler(handler: IFunction) { cdkBuilder.handler(handler.let(IFunction::unwrap)) } /** * An array of request header mapping expressions for identities. * * Supported parameter types are * Header, Query String, Stage Variable, and Context. For instance, extracting an authorization * token from a header would use the identity source `IdentitySource.header('Authorization')`. * * Note: API Gateway uses the specified identity sources as the request authorizer caching key. * When caching is * enabled, API Gateway calls the authorizer's Lambda function only after successfully verifying * that all the * specified identity sources are present at runtime. If a specified identify source is missing, * null, or empty, * API Gateway returns a 401 Unauthorized response without calling the authorizer Lambda * function. * * [Documentation](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateAuthorizer.html#apigw-CreateAuthorizer-request-identitySource) * @param identitySources An array of request header mapping expressions for identities. */ override fun identitySources(identitySources: List<String>) { cdkBuilder.identitySources(identitySources) } /** * An array of request header mapping expressions for identities. * * Supported parameter types are * Header, Query String, Stage Variable, and Context. For instance, extracting an authorization * token from a header would use the identity source `IdentitySource.header('Authorization')`. * * Note: API Gateway uses the specified identity sources as the request authorizer caching key. * When caching is * enabled, API Gateway calls the authorizer's Lambda function only after successfully verifying * that all the * specified identity sources are present at runtime. If a specified identify source is missing, * null, or empty, * API Gateway returns a 401 Unauthorized response without calling the authorizer Lambda * function. * * [Documentation](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateAuthorizer.html#apigw-CreateAuthorizer-request-identitySource) * @param identitySources An array of request header mapping expressions for identities. */ override fun identitySources(vararg identitySources: String): Unit = identitySources(identitySources.toList()) /** * How long APIGateway should cache the results. * * Max 1 hour. * Disable caching by setting this to 0. * * Default: - Duration.minutes(5) * * @param resultsCacheTtl How long APIGateway should cache the results. */ override fun resultsCacheTtl(resultsCacheTtl: Duration) { cdkBuilder.resultsCacheTtl(resultsCacheTtl.let(Duration::unwrap)) } public fun build(): software.amazon.awscdk.services.apigateway.RequestAuthorizer = cdkBuilder.build() } public companion object { public operator fun invoke( scope: CloudshiftdevConstructsConstruct, id: String, block: Builder.() -> Unit = {}, ): RequestAuthorizer { val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id) return RequestAuthorizer(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.apigateway.RequestAuthorizer): RequestAuthorizer = RequestAuthorizer(cdkObject) internal fun unwrap(wrapped: RequestAuthorizer): software.amazon.awscdk.services.apigateway.RequestAuthorizer = wrapped.cdkObject } }
1
Kotlin
0
4
ddf2bfd2275b50bb86a667c4298dd92f59d7e342
11,604
kotlin-cdk-wrapper
Apache License 2.0
core/src/commonMain/kotlin/entity/interaction/response/EphemeralMessageInteractionResponse.kt
kordlib
202,856,399
false
{"Kotlin": 2728142, "Java": 87103}
package dev.kord.core.entity.interaction.response import dev.kord.common.entity.Snowflake import dev.kord.core.Kord import dev.kord.core.behavior.interaction.response.EphemeralMessageInteractionResponseBehavior import dev.kord.core.entity.Message import dev.kord.core.supplier.EntitySupplier import dev.kord.core.supplier.EntitySupplyStrategy /** * An [EphemeralMessageInteractionResponseBehavior] that holds the [message] this is a handle to. * * @param message The message. Any rest calls made through the message behavior, e.g. `message.delete()`, will throw * since ephemeral messages are not accessible through bot authorization. */ public class EphemeralMessageInteractionResponse( message: Message, override val applicationId: Snowflake, override val token: String, override val kord: Kord, override val supplier: EntitySupplier = kord.defaultSupplier, ) : MessageInteractionResponse(message), EphemeralMessageInteractionResponseBehavior { override fun withStrategy(strategy: EntitySupplyStrategy<*>): EphemeralMessageInteractionResponse = EphemeralMessageInteractionResponse(message, applicationId, token, kord, strategy.supply(kord)) }
52
Kotlin
82
922
e99c5c583229d20e69632aae39cee47da637abef
1,185
kord
MIT License
app/src/androidTest/java/danggai/app/parcelwhere/SettingActivityUiTest.kt
danggai
335,542,229
false
null
package danggai.app.parcelwhere import androidx.test.espresso.Espresso import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import danggai.app.parcelwhere.ui.main.MainActivity import danggai.app.parcelwhere.ui.setting.SettingActivity import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SettingActivityUiTest { @get:Rule val activityRule = ActivityScenarioRule(SettingActivity::class.java) @Test fun defaultUITest(){ Espresso.onView(ViewMatchers.withText(R.string.auto_register)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withText(R.string.notification_access)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withText(R.string.receive_noti)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withText(R.string.notification_catch_fail)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withText(R.string.auto_refresh)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withText(R.string.parcel_auto_refresh)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withText(R.string.parcel_refresh_receive_noti)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) Espresso.onView(ViewMatchers.withText(R.string.auto_refresh_period)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) } @Test fun test2(){ Espresso.onView(ViewMatchers.withText("실패해라!")) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) } }
1
Kotlin
0
1
b05daaab95c0293c4d3e386b85f7f6fe646f69ec
2,062
FindMyPackage
The Unlicense
app/src/main/java/de/christinecoenen/code/zapp/app/mediathek/ui/list/MediathekListFragmentViewModel.kt
mediathekview
68,289,398
false
null
package de.christinecoenen.code.zapp.app.mediathek.ui.list import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.cachedIn import de.christinecoenen.code.zapp.app.mediathek.api.IMediathekApiService import de.christinecoenen.code.zapp.app.mediathek.api.MediathekPagingSource import de.christinecoenen.code.zapp.app.mediathek.api.request.MediathekChannel import de.christinecoenen.code.zapp.app.mediathek.api.request.QueryRequest import de.christinecoenen.code.zapp.app.mediathek.api.result.QueryInfoResult import de.christinecoenen.code.zapp.app.mediathek.ui.list.models.ChannelFilter import de.christinecoenen.code.zapp.app.mediathek.ui.list.models.LengthFilter import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.flatMapLatest import kotlin.math.roundToInt @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) class MediathekListFragmentViewModel( private val mediathekApi: IMediathekApiService ) : ViewModel() { companion object { private const val ITEM_COUNT_PER_PAGE = 30 private const val DEBOUNCE_TIME_MILLIS = 300L } private val _searchQuery = MutableStateFlow<String?>(null) private val _lengthFilter = MutableStateFlow(LengthFilter()) val lengthFilter = _lengthFilter.asLiveData() private val _channelFilter = MutableStateFlow(ChannelFilter()) val channelFilter = _channelFilter.asLiveData() val isFilterApplied = combine(_lengthFilter, _channelFilter) { lengthFilter, channelFilter -> channelFilter.isApplied || lengthFilter.isApplied } .asLiveData() private val _queryInfoResult = MutableStateFlow<QueryInfoResult?>(null) val queryInfoResult = _queryInfoResult.asLiveData() val pageFlow = combine( _searchQuery, _lengthFilter, _channelFilter ) { searchQuery, lengthFilter, channelFilter -> createQueryRequest(searchQuery, lengthFilter, channelFilter) } .debounce(DEBOUNCE_TIME_MILLIS) .flatMapLatest { queryRequest -> Pager(PagingConfig(pageSize = ITEM_COUNT_PER_PAGE)) { MediathekPagingSource(mediathekApi, queryRequest, _queryInfoResult) }.flow }.cachedIn(viewModelScope) fun clearFilter() { _channelFilter.tryEmit(ChannelFilter()) _lengthFilter.tryEmit(LengthFilter()) } fun setLengthFilter(minLengthSeconds: Float?, maxLengthSeconds: Float?) { val min = minLengthSeconds?.roundToInt() ?: 0 val max = maxLengthSeconds?.roundToInt() _lengthFilter.tryEmit(LengthFilter(min, max)) } fun setChannelFilter(channel: MediathekChannel, isEnabled: Boolean) { val filter = _channelFilter.value.copy() val hasChanged = filter.setEnabled(channel, isEnabled) if (hasChanged) { _channelFilter.tryEmit(filter) } } fun setSearchQueryFilter(query: String?) { _searchQuery.tryEmit(query) } private fun createQueryRequest( searchQuery: String?, lengthFilter: LengthFilter, channelFilter: ChannelFilter ): QueryRequest { return QueryRequest().apply { size = ITEM_COUNT_PER_PAGE minDurationSeconds = lengthFilter.minDurationSeconds maxDurationSeconds = lengthFilter.maxDurationSeconds setQueryString(searchQuery) for (filterItem in channelFilter) { setChannel(filterItem.key, filterItem.value) } } } }
33
null
28
120
8c03a25615fb89fbb5f8085a5ca63459ea5c60f8
3,474
zapp
MIT License
sample/src/main/java/com/huma/roomforasset/AppDatabase.kt
humazed
97,947,209
false
null
package com.huma.roomforasset import android.arch.persistence.room.Database import android.arch.persistence.room.RoomDatabase @Database(entities = [Customers::class, Employees::class], version = 2) abstract class AppDatabase : RoomDatabase() { abstract fun chinookDao(): ChinookDao }
7
null
25
138
8ad7d83f5e93566337e08a2408bc23579ea0a75a
291
RoomAsset
Apache License 2.0
app/src/main/java/com/rgbstudios/alte/data/firebase/FirebaseService.kt
cooncudee
732,994,014
false
{"Kotlin": 327986}
package com.rgbstudios.alte.data.firebase import android.app.NotificationChannel import android.app.NotificationManager import android.app.NotificationManager.IMPORTANCE_HIGH import android.app.PendingIntent import android.app.PendingIntent.FLAG_ONE_SHOT import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.graphics.Color import android.os.Build import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import com.rgbstudios.alte.R import com.rgbstudios.alte.ui.activities.MainActivity import com.rgbstudios.alte.utils.SharedPreferencesManager import kotlin.random.Random private const val CHANNEL_ID ="alte_channel" class FirebaseService: FirebaseMessagingService() { companion object { var sharedPref: SharedPreferencesManager? = null var token: String? get() { return sharedPref?.getString("token", "") } set(value) { sharedPref?.putString("token", value ?: "") } } override fun onNewToken(newToken: String) { super.onNewToken(newToken) token = newToken } override fun onMessageReceived(message: RemoteMessage) { super.onMessageReceived(message) val intent =Intent(this, MainActivity::class.java) val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationId = Random.nextInt() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createNotificationChannel(notificationManager) } intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) val pendingIntent = PendingIntent.getActivity( this, 0, intent, FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE ) val notification = NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle(message.data["title"]) .setContentText(message.data["message"]) .setSmallIcon(R.drawable.logo) .setAutoCancel(true) .setContentIntent(pendingIntent) .build() notificationManager.notify(notificationId, notification) } @RequiresApi(Build.VERSION_CODES.O) private fun createNotificationChannel(notificationManager: NotificationManager) { val channelName = "alteChannel" val channel = NotificationChannel(CHANNEL_ID, channelName, IMPORTANCE_HIGH).apply { description = "Stay Connected" enableLights(true) lightColor = Color.YELLOW } notificationManager.createNotificationChannel(channel) } }
0
Kotlin
0
1
226e188bba7c7c29479d6d795d036ad5a979d4c8
2,820
Alte
MIT License
common/src/main/java/com/howettl/wearquicksettings/common/injection/module/SettingsModule.kt
howettl
159,567,086
false
null
package com.howettl.wearquicksettings.common.injection.module import android.content.Context import android.net.ConnectivityManager import android.net.wifi.WifiManager import com.google.android.gms.wearable.MessageClient import com.google.android.gms.wearable.Wearable import dagger.Module import dagger.Provides import javax.inject.Singleton @Module object SettingsModule { @Provides @Singleton @JvmStatic internal fun providesWearableMessageClient(context: Context): MessageClient { return Wearable.getMessageClient(context) } @Provides @Singleton @JvmStatic internal fun providesWifiManager(context: Context): WifiManager { return context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager } @Provides @Singleton @JvmStatic internal fun providesConnectivityManager(context: Context): ConnectivityManager { return context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager } }
0
Kotlin
0
0
a7ae9c53935179496ffa6e06be58a13ff8ab0fb3
1,028
Wear-Quick-Settings
MIT License
data-android/model/src/main/java/dev/shuanghua/weather/data/android/model/FavoriteCityWeather.kt
shuanghua
479,336,029
false
{"Kotlin": 303212}
package dev.shuanghua.weather.data.android.model data class FavoriteCityWeather( val cityName: String, val cityId: String, val provinceName: String = "", val isAutoLocation: String = "", val currentT: String, val bgImageNew: String, val iconUrl: String )
0
Kotlin
2
5
218cd475728687ed3c6bf63df793577ea7087bc7
263
jianmoweather
Apache License 2.0
app/src/main/java/br/com/alphaaquilae/halloffamebr/adapter/VariaveisEventos.kt
DanielIlaro
138,787,845
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 19, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 9, "Proguard": 1, "Kotlin": 29, "XML": 115, "Java": 3, "HTML": 96, "CSS": 2, "JavaScript": 1}
package br.com.alphaaquilae.halloffamebr.adapter import com.google.firebase.database.Exclude //Será Continuado depois, dia de parada 23/04/2018 /** * Created by danielilaro on 09/04/18. */ class VariaveisEventos{ /* lateinit var titulo:String lateinit var horario:String lateinit var data:String lateinit var esporte:String lateinit var aovivoEm:String*/ lateinit var url:String @Exclude fun toMap():Map<String, Any>{ val result = object:HashMap<String, Any>(){} result.put("url", url) /* result.put("titulo", titulo) result.put("esporte", esporte) result.put("aovivoEm", aovivoEm) result.put("data", data) result.put("horario", horario)*/ return result } }
1
null
1
1
01785a6fb869b891d74312458b90a2d4682d7f1b
762
HallofFameBR
MIT License
src/main/kotlin/kotlinmud/startup/token/RoomIdToken.kt
danielmunro
241,230,796
false
null
package kotlinmud.startup.token import kotlinmud.startup.model.builder.Builder import kotlinmud.startup.parser.TokenType import kotlinmud.startup.parser.Tokenizer class RoomIdToken : Token { override val token = TokenType.RoomId override val terminator = "\n" override fun parse(builder: Builder, tokenizer: Tokenizer) {} }
0
Kotlin
1
8
8fa34c2e986c109fc4c7cc917d785827300be99d
339
kotlinmud
MIT License
buildSrc/src/main/kotlin/Config.kt
Milszym
369,444,382
true
{"Kotlin": 11439}
object Config { val group = "pl.brightinventions.codified" val version = "1.0" val jvmTarget = "1.6" }
0
null
0
0
d3f15c741b1738ee3a41785bd182ad160f8b7270
114
codified
MIT License
backend/src/main/java/dev/sergiobelda/todometer/backend/database/table/TaskTable.kt
serbelga
301,817,067
false
null
/* * Copyright 2021 <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 dev.sergiobelda.todometer.backend.database.table import org.jetbrains.exposed.sql.ReferenceOption import org.jetbrains.exposed.sql.Table internal object TaskTable : Table() { val id = uuid("id").autoGenerate() val title = text("title") val description = text("description") val state = text("state") val taskListId = uuid("tasklist_id").references( TaskListTable.id, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.CASCADE ) val tag = text("tag") override val primaryKey = PrimaryKey(id, name = "PK_Task_ID") }
6
Kotlin
7
93
bd39269ff685f0ac1c487becfa106fb7ece2cf1a
1,184
ToDometer_Kotlin_Multiplatform
Apache License 2.0
navigation-koin/src/main/kotlin/com/miquido/android/navigation/NavEntryKoinViewModelInitializer.kt
miquido
620,179,851
false
null
package com.miquido.android.navigation import android.content.Context import androidx.startup.Initializer import com.miquido.android.navigation.viewmodel.NavEntryViewModelProvider @Suppress("UNUSED") internal class NavEntryKoinViewModelInitializer : Initializer<Unit> { override fun create(context: Context) { NavEntryViewModelProvider.factory = NavEntryKoinViewModelFactory() } override fun dependencies(): List<Class<out Initializer<*>>> = emptyList() }
0
Kotlin
0
0
02f019780994cb1a648861fc0656fe84b9d0cb88
479
android-navigation
Apache License 2.0
src/main/kotlin/no/njoh/pulseengine/modules/scene/entities/SceneEntity.kt
NiklasJohansen
239,208,354
false
null
package no.njoh.pulseengine.core.scene import com.fasterxml.jackson.annotation.JsonIgnore import no.njoh.pulseengine.core.PulseEngine import no.njoh.pulseengine.core.asset.types.Font import no.njoh.pulseengine.core.asset.types.Texture import no.njoh.pulseengine.core.graphics.Surface2D import no.njoh.pulseengine.core.shared.annotations.Property import kotlin.reflect.KClass abstract class SceneEntity { @Property("", -1) var id = -1L // Id gets assigned when entity is added to the scene @Property("Transform", 0) open var x: Float = 0f @Property("Transform", 1) open var y: Float = 0f @Property("Transform", 2) open var z: Float = -0.1f @Property("Transform", 3) open var width: Float = 0f @Property("Transform", 4) open var height: Float = 0f @Property("Transform", 5) var rotation: Float = 0f @JsonIgnore val typeName = this::class.simpleName ?: "" @JsonIgnore var flags = DISCOVERABLE open fun onCreate() { } open fun onStart(engine: PulseEngine) { } open fun onUpdate(engine: PulseEngine) { } open fun onFixedUpdate(engine: PulseEngine) { } open fun onRender(engine: PulseEngine, surface: Surface2D) { if (engine.scene.state == SceneState.STOPPED) { surface.setDrawColor(1f, 1f, 1f, 0.5f) surface.drawTexture(Texture.BLANK, x, y, width, height, rotation, 0.5f, 0.5f) surface.setDrawColor(1f, 1f, 1f, 1f) var text = typeName val width = Font.DEFAULT.getWidth(typeName) if (width > this.width) text = text.substring(0, ((text.length / (width / this.width)).toInt().coerceIn(0, text.length))) surface.drawText(text, x, y, xOrigin = 0.5f, yOrigin = 0.5f) } } fun set(flag: Int) { flags = flags or flag } fun setNot(flag: Int) { flags = flags and flag.inv() } fun isSet(flag: Int) = flags and flag == flag fun isAnySet(flag: Int) = flags and flag != 0 fun isNot(flag: Int) = flags and flag == 0 companion object { const val DEAD = 1 // Is the entity alive const val POSITION_UPDATED = 2 // Was position of entity updated const val ROTATION_UPDATED = 4 // Was rotation of entity updated const val SIZE_UPDATED = 8 // Was size of entity updated const val DISCOVERABLE = 16 // Can it be discovered by other entities val REGISTERED_TYPES = mutableSetOf<KClass<out SceneEntity>>() } }
0
Kotlin
0
0
d2c0d09732fed1f2221ee17e5a28f0e50857b333
2,528
PulseEngine
MIT License
auth/src/test/java/de/whitefrog/frogr/auth/test/model/Person.kt
joewhite86
118,778,368
false
null
package de.whitefrog.frogr.auth.test.model import com.fasterxml.jackson.annotation.JsonView import de.whitefrog.frogr.model.Entity import de.whitefrog.frogr.model.annotation.* import de.whitefrog.frogr.rest.Views import org.neo4j.graphdb.Direction import java.util.* class Person(var field: String? = null, @Indexed var number: Long? = null) : Entity() { enum class Age { Old, Mature, Child} @Uuid @Unique var uniqueField: String? = null @Indexed var fulltext: String? = null var age: Age? = null var dateField: Date? = null @JsonView(Views.Secure::class) var secureField: String? = null @NullRemove var nullRemoveField: String? = null @Lazy @RelatedTo(direction = Direction.OUTGOING, type = "Likes") var likes: ArrayList<Person> = ArrayList() @Lazy @RelatedTo(direction = Direction.INCOMING, type = "Likes") var likedBy: ArrayList<Person> = ArrayList() @Lazy @RelatedTo(direction = Direction.OUTGOING, type = "Likes") var likesRelationships: ArrayList<Likes> = ArrayList() @Lazy @RelatedTo(direction = Direction.INCOMING, type = "Likes") var likedByRelationships: ArrayList<Likes> = ArrayList() @RelationshipCount(direction = Direction.OUTGOING, type = "Likes") var likesCount: Long? = null @RelatedTo(direction = Direction.BOTH, type = "MarriedWith") var marriedWith: Person? = null @RelatedTo(direction = Direction.BOTH, type = "MarriedWith") var marriedWithRelationship: MarriedWith? = null @RelatedTo(direction = Direction.OUTGOING, type = "Wears") var wears: ArrayList<Clothing> = ArrayList() override fun equals(other: Any?): Boolean { if(other !is Person) return false val eq = super.equals(other) if(!eq && id < 0 && other.id < 0 && field != null) { return field == other.field } return eq } override fun toString(): String { val sField = if(field != null) " ($field)" else "" return "Person$sField" } }
1
Kotlin
1
2
396ac4243acb7b75f624431e61d691e3fb6c9103
1,923
frogr
MIT License
src/main/kotlin/com/liquidforte/roguelike/game/Game.kt
cwzero
315,412,403
false
null
package com.liquidforte.roguelike.game import com.liquidforte.roguelike.entities.attributes.types.Player import com.liquidforte.roguelike.extensions.GameEntity import com.liquidforte.roguelike.world.World data class Game(val world: World, val player: GameEntity<Player>)
0
Kotlin
0
0
ed94313fc89f659d3d1721bfb82be8c09484fc5b
272
Roguelike
MIT License
app/src/main/java/com/example/kotlincodingtest/programmers/Lv2/예상_대진표/Solution.kt
ichanguk
788,416,368
false
{"Kotlin": 318239}
package com.example.kotlincodingtest.programmers.Lv2.예상_대진표 class Solution { fun solution(n: Int, A: Int, B: Int): Int { var answer = 1 var a = (A + 1) / 2 var b = (B + 1) / 2 while (a != b) { a = (a + 1) / 2 b = (b + 1) / 2 answer++ } return answer } }
0
Kotlin
0
0
321cb09c31e8a0bdb310b156a938e64ecb0116bf
347
KotlinCodingTest
MIT License
sample/kotlinapp/src/main/java/com/marcinmoskala/kotlinapp/StudentDataActivity.kt
sawasawasawa
96,225,324
false
null
package com.marcinmoskala.kotlinapp import activitystarter.Arg import activitystarter.MakeActivityStarter import activitystarter.Optional import android.os.Bundle import kotlinx.android.synthetic.main.activity_data.* @MakeActivityStarter class StudentDataActivity : BaseActivity() { @Arg @Optional var name: String = defaultName @Arg @Optional var id: Int = defaultId @Arg var grade: Char = ' ' @Arg var passing: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_data) nameView.text = "Name: " + name idView.text = "Id: " + id gradeView.text = "Grade: " + grade isPassingView.text = "Passing status: " + passing } companion object { private val NO_ID = -1 val defaultName = "No name provided" val defaultId = NO_ID } }
0
Kotlin
0
1
b697a89bd28c8d7af812d376562bc0a15d105a04
916
test
Apache License 2.0
src/main/kotlin/csense/idea/base/bll/kotlin/LineMarkerBll.kt
csense-oss
226,373,994
false
{"Kotlin": 165209}
package csense.idea.base.bll.kotlin import com.intellij.psi.* import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.util.* import org.jetbrains.kotlin.lexer.* import org.jetbrains.kotlin.psi.* /** * Expected to be used in a linemarker provider function to extract the "expected" ktNameFunction */ fun PsiElement.getKtNamedFunctionFromLineMarkerIdentifierLeaf(): KtNamedFunction? { return getKtElementFromLineMarkerIdentifierLeaf() } fun PsiElement.getKtPropertyFromLineMarkerIdentifierLeaf(): KtProperty? { return getKtElementFromLineMarkerIdentifierLeaf() } inline fun <reified T: KtElement>PsiElement.getKtElementFromLineMarkerIdentifierLeaf(): T? { val isNotLeaf: Boolean = this !is LeafPsiElement if (isNotLeaf) { return null } if (elementType != KtTokens.IDENTIFIER) { return null } return parent as? T }
1
Kotlin
0
0
2888dfc8991ba5eb6d9df5facd4d1ad375d67e81
890
idea-kotlin-shared-base
MIT License
backend/mlreef-system-test/src/test/kotlin/com/mlreef/rest/SystemTestConfiguration.kt
boboamin
447,199,115
true
{"Kotlin": 1792703, "JavaScript": 1383596, "Python": 165260, "SCSS": 145217, "Shell": 122988, "Ruby": 100068, "TypeScript": 56139, "ANTLR": 27697, "CSS": 19114, "Dockerfile": 18068, "HTML": 8912, "PLpgSQL": 3248, "Batchfile": 310}
package com.mlreef.rest import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.EnableConfigurationProperties @EnableConfigurationProperties @ConfigurationProperties(prefix = "systemtest") class SystemTestConfiguration { lateinit var backendUrl: String // lateinit var gitlabUrl: String // lateinit var adminUsername: String // lateinit var adminPassword: String // lateinit var adminUserToken: String }
0
null
0
1
80c9af03f324c929b8f8889256c13c865afa95c1
491
mlreef
MIT License
Skyflow/src/main/kotlin/Skyflow/utils/EventName.kt
skyflowapi
396,648,989
false
{"Kotlin": 674976, "Shell": 585}
package Skyflow.utils enum class EventName { CHANGE, READY, FOCUS, BLUR }
13
Kotlin
2
7
0ffcbf43c2767d6324f29952e8ce94d354aa57d8
90
skyflow-android
MIT License
app/src/main/java/pawelsadanowicz/movieplayground/feature/splash/di/SplashActivityModule.kt
psadanowicz
136,707,118
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "YAML": 2, "Proguard": 1, "Kotlin": 31, "XML": 14, "Java": 1}
package pawelsadanowicz.movieplayground.feature.splash.di import dagger.Module import dagger.Provides import pawelsadanowicz.movieplayground.di.ActivityScope import pawelsadanowicz.movieplayground.feature.splash.SplashActivity import pawelsadanowicz.movieplayground.util.navigator.AndroidApplicationNavigator import pawelsadanowicz.movieplayground.util.navigator.ApplicationNavigator @Module object SplashActivityModule { @Provides @ActivityScope @JvmStatic fun provideApplicationNavigator(activity: SplashActivity): ApplicationNavigator = AndroidApplicationNavigator(activity) }
1
null
1
1
148b758f00f04786eb6033cfc54c6ca38ce67ca1
599
movie-playground
Apache License 2.0
app/src/main/java/com/jason/rickandmorty/ui/helper/SwipeDetector.kt
h11128
324,210,115
false
null
package com.jason.rickandmorty.ui.helper import android.util.Log import android.view.MotionEvent import android.view.View import android.view.View.OnTouchListener import kotlin.math.abs const val swipe_error = "SwipeDetector error" const val default_log = "please pass SwipeDetector.OnSwipeEvent Interface instance" class SwipeDetector(private val v: View) : OnTouchListener { private var minDistance1 = 100 private var downX = 0f private var downY = 0f private var upX = 0f private var upY = 0f private var swipeEventListener: OnSwipeEvent? = null fun setOnSwipeListener(listener: OnSwipeEvent?) { try { swipeEventListener = listener } catch (e: ClassCastException) { Log.e("ClassCastException", default_log, e) } } private fun onRightToLeftSwipe() { onSwipe(SwipeTypeEnum.RIGHT_TO_LEFT) } private fun onLeftToRightSwipe() { onSwipe(SwipeTypeEnum.LEFT_TO_RIGHT) } private fun onTopToBottomSwipe() { onSwipe(SwipeTypeEnum.TOP_TO_BOTTOM) } private fun onBottomToTopSwipe() { Log.d("abc", "OnBottomToTopSwipe") onSwipe(SwipeTypeEnum.BOTTOM_TO_TOP) } private fun onSwipe(swipeType: SwipeTypeEnum?) { if (swipeEventListener != null) { swipeEventListener!!.swipeEventDetected(v, swipeType) } else Log.e(swipe_error, default_log) } override fun onTouch(v: View, event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { downX = event.x downY = event.y return true } MotionEvent.ACTION_UP -> { v.performClick() upX = event.x upY = event.y Log.d("anc", "$downX $downY $upX $upY") val deltaX = downX - upX val deltaY = downY - upY //HORIZONTAL SCROLL if (abs(deltaX) > abs(deltaY)) { if (abs(deltaX) > minDistance1) { // left or right if (deltaX < 0) { onLeftToRightSwipe() return true } if (deltaX > 0) { onRightToLeftSwipe() return true } } else { //not long enough swipe... return false } } else { if (abs(deltaY) > minDistance1) { // top or down if (deltaY < 0) { onTopToBottomSwipe() return true } if (deltaY > 0) { onBottomToTopSwipe() return true } } else { //not long enough swipe... return false } } return true } } return false } interface OnSwipeEvent { fun swipeEventDetected(v: View?, swipeType: SwipeTypeEnum?) } enum class SwipeTypeEnum { RIGHT_TO_LEFT, LEFT_TO_RIGHT, TOP_TO_BOTTOM, BOTTOM_TO_TOP } init { v.setOnTouchListener(this) } }
0
Kotlin
0
0
e501e02e2914399ad8ea399853bd9f8df472645b
3,501
RickAndMorty
MIT License
red-screen-of-death-no-op/src/main/java/com/melegy/redscreenofdeath/RedScreenOfDeath.kt
mlegy
306,869,656
false
null
package com.melegy.redscreenofdeath import android.app.Application object RedScreenOfDeath { @JvmStatic fun init(application: Application) { // no-op } }
5
Kotlin
11
179
2767e786b20b08cf8d2790bc605d4321eca1415a
176
red-screen-of-death
Apache License 2.0
AnimationApplication/app/src/main/java/cn/hakim/animationapplication/db/dao/WeatherDao.kt
basion
94,980,082
true
{"Markdown": 4, "Text": 1, "Ignore List": 3, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 1, "JSON": 1, "Java": 2, "XML": 13, "Kotlin": 26}
package cn.hakim.animationapplication.db.dao import android.arch.lifecycle.LiveData import android.arch.persistence.room.Dao import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy import android.arch.persistence.room.Query import cn.hakim.animationapplication.db.entity.WeatherEntity import cn.hakim.animationapplication.model.Weather import io.reactivex.Flowable import io.reactivex.Observable /** * Created by Administrator on 2017/6/23. */ @Dao interface WeatherDao { // @Query("SELECT * FROM weathers") // LiveData<List<WeatherEntity>> getAll(); // @Query("select * from weathers where id = :id") // LiveData<WeatherEntity> loadWeather(int weatherId); @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(entities: List<WeatherEntity>) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(weather: WeatherEntity) //NOTICE : 使用kapt时有一个bug(可通过gradlew build --info 查看编译错误信息message view默认不显示)本来weatherId作为占位符被编译成了arg0,导致kapt编译出错。 @Query("SELECT * FROM weathers where id = :arg0") fun loadWeatherSync(arg0: Int): Flowable<WeatherEntity> @get:Query("SELECT * FROM weathers") val all: Flowable<List<WeatherEntity>> // @Query("select * from weathers where id = :weatherId") // Observable<WeatherEntity> loadWeather(int weatherId); }
0
Kotlin
0
0
d15e81f27ac25d902d427abe343bdd5cee6e256e
1,376
test-mobile
MIT License
AnimationApplication/app/src/main/java/cn/hakim/animationapplication/db/dao/WeatherDao.kt
basion
94,980,082
true
{"Markdown": 4, "Text": 1, "Ignore List": 3, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 1, "JSON": 1, "Java": 2, "XML": 13, "Kotlin": 26}
package cn.hakim.animationapplication.db.dao import android.arch.lifecycle.LiveData import android.arch.persistence.room.Dao import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy import android.arch.persistence.room.Query import cn.hakim.animationapplication.db.entity.WeatherEntity import cn.hakim.animationapplication.model.Weather import io.reactivex.Flowable import io.reactivex.Observable /** * Created by Administrator on 2017/6/23. */ @Dao interface WeatherDao { // @Query("SELECT * FROM weathers") // LiveData<List<WeatherEntity>> getAll(); // @Query("select * from weathers where id = :id") // LiveData<WeatherEntity> loadWeather(int weatherId); @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(entities: List<WeatherEntity>) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(weather: WeatherEntity) //NOTICE : 使用kapt时有一个bug(可通过gradlew build --info 查看编译错误信息message view默认不显示)本来weatherId作为占位符被编译成了arg0,导致kapt编译出错。 @Query("SELECT * FROM weathers where id = :arg0") fun loadWeatherSync(arg0: Int): Flowable<WeatherEntity> @get:Query("SELECT * FROM weathers") val all: Flowable<List<WeatherEntity>> // @Query("select * from weathers where id = :weatherId") // Observable<WeatherEntity> loadWeather(int weatherId); }
0
Kotlin
0
0
d15e81f27ac25d902d427abe343bdd5cee6e256e
1,376
test-mobile
MIT License
app/src/main/java/dev/shreyansh/pokemon/pokedex/db/pokemon_moves/PokemonMovesDatabase.kt
binaryshrey
667,418,478
false
null
package dev.shreyansh.pokemon.pokedex.db.pokemon_moves import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import dev.shreyansh.pokemon.pokedex.utils.MovesConvertor @Database(entities = [PokemonMovesEntity::class], exportSchema = false, version = 1) @TypeConverters(MovesConvertor::class) abstract class PokemonMovesDatabase : RoomDatabase() { abstract val pokemonMovesDao: PokemonMovesDao companion object { @Volatile private var INSTANCE: PokemonMovesDatabase? = null fun getInstance(context: Context): PokemonMovesDatabase { synchronized(this) { var instance = INSTANCE if (instance == null) { instance = Room.databaseBuilder( context.applicationContext, PokemonMovesDatabase::class.java, "pokemon_moves_db" ).build() INSTANCE = instance } return instance } } } }
0
Kotlin
1
0
c2b250a32748b0f5f5249695231507a0692def74
1,143
Pokedex
MIT License
advent2021/src/main/kotlin/year2021/day05/Board.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2021.day05 import kotlin.math.max val Collection<Line>.maxX get() = maxOf { max(it.from.x, it.to.x) } val Collection<Line>.maxY get() = maxOf { max(it.from.y, it.to.y) } class Board(private val lines: Collection<Line>) { private val map: Map<Point, Int> = buildMap { lines.forEach { line -> line.points.forEach { p -> val r = get(p) ?: 0 set(p, r + 1) } } } private val maxX get() = lines.maxX private val maxY get() = lines.maxY /** * used to generate the visual representation */ @Suppress("unused") fun printBoard() { (0..maxY).map { y -> (0..maxX).map { Point(it, y) } }.forEach { line -> println(line.map { p -> map[p] ?: '.' }.joinToString("\t")) } } fun count(test: (Pair<Point, Int>) -> Boolean): Int = map.entries.count { test(it.key to it.value) } }
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
946
advent-of-code
Apache License 2.0
src/test/kotlin/com/testing/miniproject/MiniprojectApplicationTests.kt
4liAkbar
426,528,120
false
null
package com.testing.miniproject import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class MiniprojectApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
ce67df43c07c7dc6fcdb1005d7adb9df85673e4b
216
miniproject
Apache License 2.0
kotlin/src/main/kotlin/com/github/json/NullableStringSerializer.kt
pnemonic78
149,122,819
false
{"Kotlin": 217840}
package com.github.json import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder typealias NullableString = String? @OptIn(ExperimentalSerializationApi::class) object NullableStringSerializer : KSerializer<NullableString> { override val descriptor = PrimitiveSerialDescriptor("java.lang.String", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): NullableString { if (decoder.decodeNotNullMark()) { return decoder.decodeString() } return decoder.decodeNull() } override fun serialize(encoder: Encoder, value: NullableString) { if (value == null) { encoder.encodeNull() return } encoder.encodeString(value) } }
0
Kotlin
0
1
8d16d60b527c08e8ce746dd4534e31fbad137138
989
android-lib
Apache License 2.0
libnavigation-core/src/test/java/com/mapbox/navigation/core/navigator/TilesDescriptorFactoryTest.kt
mapbox
87,455,763
false
null
package com.mapbox.navigation.core.navigator import com.mapbox.navigation.base.options.RoutingTilesOptions import com.mapbox.navigation.core.navigator.TilesetDescriptorFactory.NativeFactoryWrapper import com.mapbox.navigator.CacheHandle import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.Before import org.junit.Test class TilesDescriptorFactoryTest { private val routingTilesOptions: RoutingTilesOptions = mockk(relaxed = true) private val cache: CacheHandle = mockk(relaxed = true) private val nativeFactoryWrapper: NativeFactoryWrapper = mockk(relaxed = true) private val tilesetDescriptorFactory by lazy { TilesetDescriptorFactory(routingTilesOptions, cache, nativeFactoryWrapper) } @Before fun setUp() { every { routingTilesOptions.tilesDataset } returns OPTIONS_DATASET every { routingTilesOptions.tilesProfile } returns OPTIONS_PROFILE every { routingTilesOptions.tilesVersion } returns OPTIONS_VERSION } @Test fun checkBuildWithParams() { tilesetDescriptorFactory.build(DATASET, PROFILE, VERSION) verify { nativeFactoryWrapper.build("$DATASET/$PROFILE", VERSION) } } @Test fun checkBuildWithDefaultDataset() { tilesetDescriptorFactory.build(tilesProfile = PROFILE, tilesVersion = VERSION) verify { nativeFactoryWrapper.build("$OPTIONS_DATASET/$PROFILE", VERSION) } } @Test fun checkBuildWithDefaultProfile() { tilesetDescriptorFactory.build(tilesDataset = DATASET, tilesVersion = VERSION) verify { nativeFactoryWrapper.build("$DATASET/$OPTIONS_PROFILE", VERSION) } } @Test fun checkBuildWithDefaultVersion() { tilesetDescriptorFactory.build(tilesDataset = DATASET, tilesProfile = PROFILE) verify { nativeFactoryWrapper.build("$DATASET/$PROFILE", OPTIONS_VERSION) } } @Test fun checkBuildWithDefaults() { tilesetDescriptorFactory.build() verify { nativeFactoryWrapper.build("$OPTIONS_DATASET/$OPTIONS_PROFILE", OPTIONS_VERSION) } } private companion object { private const val DATASET = "dataset" private const val PROFILE = "profile" private const val VERSION = "version" private const val OPTIONS_DATASET = "options_dataset" private const val OPTIONS_PROFILE = "options_profile" private const val OPTIONS_VERSION = "options_version" } }
508
null
318
621
88163ae3d7e34948369d6945d5b78a72bdd68d7c
2,555
mapbox-navigation-android
Apache License 2.0
app/src/main/java/github/com/st235/facialprocessing/domain/MediaFilesProcessor.kt
st235
756,046,103
false
{"Kotlin": 207478}
package github.com.st235.facialprocessing.domain import androidx.annotation.WorkerThread import github.com.st235.facialprocessing.domain.faces.FaceProcessor import github.com.st235.facialprocessing.domain.model.GalleryEntry import github.com.st235.facialprocessing.domain.model.ProcessedGalleryEntry import github.com.st235.facialprocessing.utils.LocalUriLoader import github.com.st235.facialprocessing.utils.tflite.InterpreterFactory class MediaFilesProcessor( private val faceProcessor: FaceProcessor, private val localUriLoader: LocalUriLoader, ) { @WorkerThread companion object { fun create( localUriLoader: LocalUriLoader, interpreterFactory: InterpreterFactory, ): MediaFilesProcessor { return MediaFilesProcessor(FaceProcessor(interpreterFactory), localUriLoader) } } class ProcessingException : RuntimeException() @WorkerThread fun process(galleryEntry: GalleryEntry): Result<ProcessedGalleryEntry> { val bitmap = localUriLoader.load(galleryEntry.contentUri) if (bitmap == null) { return Result.failure(ProcessingException()) } val faceDescriptors = faceProcessor.detect(bitmap) return Result.success( ProcessedGalleryEntry( id = galleryEntry.id, contentUri = galleryEntry.contentUri, descriptors = faceDescriptors ) ) } }
0
Kotlin
0
0
e8c1dfbf037b360aa9f77be3d8834dcc8cba7f37
1,465
HSE.CVforMobileDevices.FacialProcessing
MIT License
jetbrains-core/src/software/aws/toolkits/jetbrains/services/apprunner/actions/ServiceUrlActions.kt
JetBrains
223,485,227
true
{"Gradle Kotlin DSL": 21, "Markdown": 16, "Java Properties": 2, "Shell": 1, "Text": 12, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 3, "YAML": 28, "XML": 96, "Kotlin": 1102, "JSON": 54, "Java": 9, "SVG": 64, "TOML": 1, "INI": 1, "CODEOWNERS": 1, "Maven POM": 4, "Dockerfile": 14, "JavaScript": 3, "Python": 5, "Go": 1, "Go Module": 1, "Microsoft Visual Studio Solution": 6, "C#": 79}
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.apprunner.actions import com.intellij.ide.browsers.BrowserLauncher import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.DumbAware import software.amazon.awssdk.services.apprunner.model.ServiceSummary import software.aws.toolkits.jetbrains.core.explorer.actions.SingleResourceNodeAction import software.aws.toolkits.jetbrains.services.apprunner.AppRunnerServiceNode import software.aws.toolkits.telemetry.ApprunnerTelemetry import java.awt.datatransfer.StringSelection class CopyServiceUrlAction : SingleResourceNodeAction<AppRunnerServiceNode>(), DumbAware { override fun actionPerformed(selected: AppRunnerServiceNode, e: AnActionEvent) { CopyPasteManager.getInstance().setContents(StringSelection(selected.service.urlWithProtocol())) ApprunnerTelemetry.copyServiceUrl(selected.nodeProject) } } class OpenServiceUrlAction : SingleResourceNodeAction<AppRunnerServiceNode>(), DumbAware { override fun actionPerformed(selected: AppRunnerServiceNode, e: AnActionEvent) { BrowserLauncher.instance.browse(selected.service.urlWithProtocol(), project = selected.nodeProject) ApprunnerTelemetry.openServiceUrl(selected.nodeProject) } } private fun ServiceSummary.urlWithProtocol() = "https://${serviceUrl()}"
6
Kotlin
4
9
ccee3307fe58ad48f93cd780d4378c336ee20548
1,504
aws-toolkit-jetbrains
Apache License 2.0
src/main/kotlin/Prologue.kt
sander
606,774,943
false
null
package nl.sanderdijkhuis.noise @JvmInline value class Prologue(val data: Data)
1
Kotlin
0
0
5b961e181eb30ae5807f160ed04c629d0ebc5916
81
noise-kotlin
MIT License
app/src/test/java/lt/vilnius/tvarkau/dagger/module/TestAnalyticsModule.kt
vilnius
45,076,585
false
null
package lt.vilnius.tvarkau.dagger.module import com.mixpanel.android.mpmetrics.MixpanelAPI import com.nhaarman.mockito_kotlin.mock import dagger.Module import dagger.Provides import lt.vilnius.tvarkau.TestTvarkauApplication import lt.vilnius.tvarkau.analytics.Analytics import javax.inject.Singleton /** * @author <NAME> */ @Module class TestAnalyticsModule { @Provides @Singleton internal fun providesMixpanel(application: TestTvarkauApplication): MixpanelAPI = mock() @Provides @Singleton fun providesAnalytics(application: TestTvarkauApplication): Analytics = mock() }
7
null
15
24
3d546e1e70b5b05514f47e7cb6c1c2e03a7da093
602
tvarkau-vilniu
MIT License
source-code/starter-project/SideEffectHandlers/app/src/main/java/com/example/sideeffecthandlers/notification/TaskNotificationService.kt
droidcon-academy
784,702,823
false
{"Kotlin": 64632}
package com.droidcon.tasktimer.notification import android.app.NotificationManager import android.content.Context import androidx.core.app.NotificationCompat import com.droidcon.tasktimer.R import kotlin.random.Random class TaskNotificationService(private val context: Context) { private val notificationManager=context.getSystemService(NotificationManager::class.java) fun showBasicNotification(taskName:String){ val notification= NotificationCompat.Builder(context,"task_notification") .setContentTitle(taskName) .setContentText("Task Completed") .setSmallIcon(R.drawable.ic_launcher_foreground) .setPriority(NotificationManager.IMPORTANCE_HIGH) .setAutoCancel(true) .build() notificationManager.notify( Random.nextInt(), notification ) } }
0
Kotlin
0
0
e245413eb9cfb94eaa42f72d0cb6e0690e1a24b5
879
android-cbc-side-effect-handlers-compose
Apache License 2.0
source-code/starter-project/SideEffectHandlers/app/src/main/java/com/example/sideeffecthandlers/notification/TaskNotificationService.kt
droidcon-academy
784,702,823
false
{"Kotlin": 64632}
package com.droidcon.tasktimer.notification import android.app.NotificationManager import android.content.Context import androidx.core.app.NotificationCompat import com.droidcon.tasktimer.R import kotlin.random.Random class TaskNotificationService(private val context: Context) { private val notificationManager=context.getSystemService(NotificationManager::class.java) fun showBasicNotification(taskName:String){ val notification= NotificationCompat.Builder(context,"task_notification") .setContentTitle(taskName) .setContentText("Task Completed") .setSmallIcon(R.drawable.ic_launcher_foreground) .setPriority(NotificationManager.IMPORTANCE_HIGH) .setAutoCancel(true) .build() notificationManager.notify( Random.nextInt(), notification ) } }
0
Kotlin
0
0
e245413eb9cfb94eaa42f72d0cb6e0690e1a24b5
879
android-cbc-side-effect-handlers-compose
Apache License 2.0
src/TreeNode.kt
ilinqh
390,190,883
false
{"Kotlin": 367003, "Java": 30918}
import java.util.* import kotlin.collections.ArrayList class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null } fun ArrayList<Int?>.toTreeNode(): TreeNode { val root = TreeNode(this[0] ?: 0) val queue = LinkedList<TreeNode?>() queue.add(root) var index = 1 while (index < this.size) { val parent = queue.peek() queue.poll() val leftVal = this[index] val leftNode = if (leftVal == null) { null } else { TreeNode(leftVal) } parent?.left = leftNode queue.add(leftNode) index += 1 if (index < this.size) { val rightVal = this[index] val rightNode = if (rightVal == null) { null } else { TreeNode(rightVal) } parent?.right = rightNode queue.add(rightNode) } index += 1 } return root }
0
Kotlin
0
0
7ad1e092e59af11a161188f7660c481a396a3d9d
974
AlgorithmsProject
Apache License 2.0
basics/common/src/main/java/top/sunhy/common/core/popup/BaseHorizontalAttachPopup.kt
RDSunhy
421,280,382
false
null
package top.sunhy.common.core.popup import android.view.View import androidx.annotation.LayoutRes import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.lifecycle.* import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.kingja.loadsir.core.LoadService import com.kingja.loadsir.core.LoadSir import com.lxj.xpopup.XPopup import com.lxj.xpopup.core.BasePopupView import com.lxj.xpopup.core.HorizontalAttachPopupView import top.sunhy.base.adapter.BaseMultiAdapter import top.sunhy.base.application.BaseApplication import top.sunhy.common.R import top.sunhy.common.core.vm.BaseViewModel import top.sunhy.common.loadsir.EmptyCallback import top.sunhy.common.loadsir.ErrorCallback import top.sunhy.common.loadsir.LoadingCallback abstract class BaseHorizontalAttachPopup<B : ViewDataBinding, VM : BaseViewModel>(activity: AppCompatActivity) : HorizontalAttachPopupView(activity), IBasePopup { protected lateinit var mBinding: B protected lateinit var mViewModel: VM protected var mActivity = activity /** * 预置 recyclerview 相关内容 */ protected var mBefore = "" protected var mDatas = mutableListOf<Any>() protected var mAdapter = BaseMultiAdapter(mDatas) /** * 状态布局 */ protected var mLoadService: LoadService<*>? = null @LayoutRes protected abstract fun getLayoutId(): Int protected abstract fun registViewBinder() protected abstract fun initView() protected abstract fun initData() protected abstract fun initListener() protected abstract fun initViewModel(): VM protected abstract fun initObserver() //加载中弹窗 protected var mPopupLoading: BasePopupView? = null override fun initPopupContent() { super.initPopupContent() popupInfo.isDestroyOnDismiss = true mBinding = DataBindingUtil.bind(popupImplView) ?: throw NullPointerException("XmxHorizontalAttachPopup mBinding is Null!") mViewModel = initViewModel() mViewModel.application = BaseApplication.instance() lifecycle.addObserver(mViewModel) initCommonView() initView() initListener() initData() initObserver() } protected fun setLoadsir(view: View?) { mLoadService = LoadSir.getDefault().register(view) { onRetry() } } override fun getImplLayoutId(): Int { return getLayoutId() } private fun initCommonView() { if (getRefreshLayout() != null) { getRefreshLayout()?.setOnRefreshListener(this) getRefreshLayout()?.setOnLoadMoreListener(this) } registViewBinder() getMainRecyclerview()?.overScrollMode = View.OVER_SCROLL_NEVER getMainRecyclerview()?.layoutManager = getLayoutManager() getMainRecyclerview()?.adapter = mAdapter } fun setBefore(time: Long){ if (time != null){ mBefore = time.toString() } } open fun getLayoutManager(): RecyclerView.LayoutManager { return LinearLayoutManager(mActivity) } override fun onDismiss() { super.onDismiss() } override fun onShow() { super.onShow() } /** * 初始化一个新的 viewmodel * 不和 activity 或 fragment 共用!!! */ protected fun <T : ViewModel> getViewModel(modelClass: Class<T>): T { return ViewModelProvider.AndroidViewModelFactory(BaseApplication.instance()) .create(modelClass) } override fun onDestroy() { super.onDestroy() } override fun onRetry() { showLoading() } override fun showLoading() { mLoadService?.showCallback(LoadingCallback::class.java) } override fun showContent() { mLoadService?.showSuccess() } override fun showEmpty() { mLoadService?.showCallback(EmptyCallback::class.java) } override fun showError() { mLoadService?.showCallback(ErrorCallback::class.java) } protected fun showLoadingDialog(){ showLoadingDialog(null) } protected fun showLoadingDialog(msg: String?) { var hintMsg = if (msg.isNullOrEmpty()){ "正在加载中..." }else{ msg } mPopupLoading = XPopup.Builder(mActivity) .isDestroyOnDismiss(true) .asLoading(hintMsg, R.layout.common_popup_loading) .show() } protected fun dismissLoadingDialog() { mPopupLoading?.dismiss() } }
0
Kotlin
0
0
ff8d615fceeb21169caba21df32e120e2ac783f6
4,589
android-component
Apache License 2.0
app/src/test/java/eu/caraus/dynamo/application/data/local/CoursesItemDatabaseTest.kt
alexandrucaraus
140,244,389
false
{"Kotlin": 69803, "Java": 19004}
package eu.caraus.dynamo.application.data.local class CoursesItemDatabaseTest { }
0
Kotlin
0
0
e0ab8096448088b23ee908abda7ec2d9791cd099
83
ShowCase-UdacityApiMvvm
MIT License
misc/function/src/commonMain/kotlin/com/bselzer/ktx/function/collection/Array.kt
Woody230
388,189,330
false
{"Kotlin": 3122860}
package com.bselzer.ktx.function.collection /** * @return whether the item exists and is one of the items in the collection */ fun <T> T.isOneOf(vararg items: T?): Boolean { this ?: return false return items.contains(this) } /** * Builds a new read-only List by populating a MutableList using the given builderAction and returning a read-only list with the same elements. * The list passed as a receiver to the builderAction is valid only inside that function. Using it outside of the function produces an unspecified behavior. * The returned list is serializable (JVM). * * The list is then converted into an array. */ inline fun <reified T> buildArray(builderAction: MutableList<T>.() -> Unit): Array<T> = buildList(builderAction).toTypedArray()
2
Kotlin
0
7
50901f7b1ff6211ad09b857e098386238496cbe8
765
KotlinExtensions
Apache License 2.0
app/src/main/kotlin/ru/cherryperry/amiami/screen/activity/SingleActivityModule.kt
wargry
139,280,084
true
{"Kotlin": 102696}
package ru.cherryperry.amiami.screen.activity import android.app.Activity import android.support.v7.app.AppCompatActivity import dagger.Binds import dagger.Module import dagger.android.ActivityKey import dagger.android.AndroidInjector import dagger.multibindings.IntoMap @Module(subcomponents = [SingleActivitySubcomponent::class]) abstract class SingleActivityModule { @Binds @IntoMap @ActivityKey(SingleActivity::class) abstract fun bindFactory(builder: SingleActivitySubcomponent.Builder): AndroidInjector.Factory<out Activity> @Binds abstract fun appCompatActivity(singleActivity: SingleActivity): AppCompatActivity }
0
Kotlin
0
0
ada84ecfc0a574380f49446048be4e550a7ed018
649
Amiami-android-app
Apache License 2.0
src/marais/graphql/ktor/execution/FlowSubscriptionExecutionStrategy.kt
Gui-Yom
336,641,560
false
null
package marais.graphql.ktor.execution import graphql.AssertException import graphql.ExecutionResult import graphql.ExecutionResultImpl import graphql.execution.DataFetcherExceptionHandler import graphql.execution.ExecutionContext import graphql.execution.ExecutionContextBuilder import graphql.execution.ExecutionStepInfo import graphql.execution.ExecutionStrategy import graphql.execution.ExecutionStrategyParameters import graphql.execution.FetchedValue import graphql.execution.SimpleDataFetcherExceptionHandler import graphql.execution.SubscriptionExecutionStrategy import graphql.execution.instrumentation.ExecutionStrategyInstrumentationContext import graphql.execution.instrumentation.SimpleInstrumentationContext.nonNullCtx import graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters import graphql.execution.instrumentation.parameters.InstrumentationExecutionStrategyParameters import graphql.execution.instrumentation.parameters.InstrumentationFieldParameters import graphql.execution.reactive.SubscriptionPublisher import graphql.schema.GraphQLObjectType import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.future.await import org.reactivestreams.Publisher import java.util.* import java.util.concurrent.CompletableFuture /** * [SubscriptionExecutionStrategy] only accepts [org.reactivestreams.Publisher] as fetcher return type. * This implementation allows using [Flow] and [org.reactivestreams.Publisher] as return type. * * Code from this class is copied from [SubscriptionExecutionStrategy] and converted to kotlin by IntelliJ, then cleaned by hand. * Changes are only in the function [execute]. [SubscriptionExecutionStrategy.createSourceEventStream] has been inlined in [execute]. */ class FlowSubscriptionExecutionStrategy(dataFetcherExceptionHandler: DataFetcherExceptionHandler) : ExecutionStrategy(dataFetcherExceptionHandler) { constructor() : this(SimpleDataFetcherExceptionHandler()) override fun execute( executionContext: ExecutionContext, parameters: ExecutionStrategyParameters ): CompletableFuture<ExecutionResult>? { val instrumentation = executionContext.instrumentation val instrumentationParameters = InstrumentationExecutionStrategyParameters(executionContext, parameters) val executionStrategyCtx = ExecutionStrategyInstrumentationContext.nonNullCtx( instrumentation.beginExecutionStrategy( instrumentationParameters, executionContext.instrumentationState ) ) val newParameters = firstFieldOfSubscriptionSelection(parameters) val fieldFetched = fetchField(executionContext, newParameters) val sourceFut = fieldFetched.thenApply(FetchedValue::getFetchedValue) // when the upstream source event stream completes, subscribe to it and wire in our adapter val overallResult = sourceFut.thenApply<ExecutionResult> { source -> if (source == null) { return@thenApply ExecutionResultImpl(null, executionContext.errors) } val transformed: Any = when (source) { is Flow<*> -> source.map { executeSubscriptionEvent(executionContext, parameters, it).await() } is Publisher<*> -> { SubscriptionPublisher(source as Publisher<Any?>?) { executeSubscriptionEvent( executionContext, parameters, it ) } } else -> throw AssertException( """ This subscription execution strategy support the following return types for your subscriptions fetchers : - org.reactivestreams.Publisher - kotlinx.coroutines.Flow """.trimIndent() ) } ExecutionResultImpl(transformed, executionContext.errors) } // dispatched the subscription query executionStrategyCtx.onDispatched(overallResult) overallResult.whenComplete { result: ExecutionResult, t: Throwable? -> executionStrategyCtx.onCompleted( result, t ) } return overallResult } private fun executeSubscriptionEvent( executionContext: ExecutionContext, parameters: ExecutionStrategyParameters, eventPayload: Any? ): CompletableFuture<ExecutionResult> { val instrumentation = executionContext.instrumentation val newExecutionContext = executionContext.transform { builder: ExecutionContextBuilder -> builder.root(eventPayload).resetErrors() } val newParameters = firstFieldOfSubscriptionSelection(parameters) val subscribedFieldStepInfo = createSubscribedFieldStepInfo(executionContext, newParameters) val i13nFieldParameters = InstrumentationFieldParameters(executionContext) { subscribedFieldStepInfo } val subscribedFieldCtx = nonNullCtx( instrumentation.beginSubscribedFieldEvent( i13nFieldParameters, executionContext.instrumentationState ) ) val fetchedValue = unboxPossibleDataFetcherResult(newExecutionContext, parameters, eventPayload) val fieldValueInfo = completeField(newExecutionContext, newParameters, fetchedValue) var overallResult = fieldValueInfo.fieldValue.thenApply { executionResult: ExecutionResult -> wrapWithRootFieldName( newParameters, executionResult ) } // dispatch instrumentation so they can know about each subscription event subscribedFieldCtx.onDispatched(overallResult) overallResult.whenComplete { result: ExecutionResult, t: Throwable? -> subscribedFieldCtx.onCompleted( result, t ) } // allow them to instrument each ER should they want to val i13nExecutionParameters = InstrumentationExecutionParameters( executionContext.executionInput, executionContext.graphQLSchema, executionContext.instrumentationState ) overallResult = overallResult.thenCompose { executionResult: ExecutionResult? -> instrumentation.instrumentExecutionResult( executionResult, i13nExecutionParameters, executionContext.instrumentationState ) } return overallResult } private fun wrapWithRootFieldName( parameters: ExecutionStrategyParameters, executionResult: ExecutionResult ): ExecutionResult { val rootFieldName = getRootFieldName(parameters) return ExecutionResultImpl( Collections.singletonMap(rootFieldName, executionResult.getData<Any>()), executionResult.errors ) } private fun getRootFieldName(parameters: ExecutionStrategyParameters): String { val rootField = parameters.field.singleField return rootField.resultKey } private fun firstFieldOfSubscriptionSelection(parameters: ExecutionStrategyParameters): ExecutionStrategyParameters { val fields = parameters.fields val firstField = fields.getSubField(fields.keys[0]) val fieldPath = parameters.path.segment(mkNameForPath(firstField.singleField)) return parameters.transform { builder: ExecutionStrategyParameters.Builder -> builder.field( firstField ).path(fieldPath) } } private fun createSubscribedFieldStepInfo( executionContext: ExecutionContext, parameters: ExecutionStrategyParameters ): ExecutionStepInfo { val field = parameters.field.singleField val parentType = parameters.executionStepInfo.unwrappedNonNullType as GraphQLObjectType val fieldDef = getFieldDef(executionContext.graphQLSchema, parentType, field) return createExecutionStepInfo(executionContext, parameters, fieldDef, parentType) } }
0
null
1
8
86283bd90832ddd70ad2d10bd01cf319d03fe8d0
8,273
ktor-graphql
Apache License 2.0
app/src/main/java/com/example/aiboroid/CognitionApiViewModel.kt
adoth
280,972,743
false
null
package com.example.aiboroid import androidx.lifecycle.ViewModel class CognitionApiViewModel : ViewModel() { // TODO: Implement the ViewModel }
3
Kotlin
0
0
da414929d2569691d49df795ef949717be63dd24
149
Aiboroid
Apache License 2.0
src/test/kotlin/no/nav/familie/dokument/storage/integrationTest/StorageControllerIntegrationTest.kt
navikt
222,470,666
false
{"Kotlin": 109855, "HTML": 31392, "Dockerfile": 153}
package no.nav.familie.dokument.storage.integrationTest import com.google.cloud.storage.Blob import com.google.cloud.storage.BlobId import com.google.cloud.storage.Storage import com.google.cloud.storage.StorageException import io.mockk.every import io.mockk.mockk import io.mockk.slot import no.nav.familie.http.client.MultipartBuilder import no.nav.familie.kontrakter.felles.Ressurs import no.nav.familie.kontrakter.felles.objectMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.web.client.exchange import org.springframework.core.io.ByteArrayResource import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.test.context.ActiveProfiles import org.springframework.util.MultiValueMap @ActiveProfiles("integration-test") class StorageControllerIntegrationTest : OppslagSpringRunnerTest() { @Autowired lateinit var storageMock: Storage @BeforeEach fun setup() { headers.setBearerAuth(søkerBearerToken()) headers.contentType = MediaType.MULTIPART_FORM_DATA } @Test internal fun `skal lagre fil med navnet på filen`() { initMock() val navn = "gyldig-0.8m.pdf" val vedlegg = leseVedlegg(navn) val response = restTemplate.exchange<Map<String, String>>( localhost("/api/mapper/familie-dokument-test"), HttpMethod.POST, HttpEntity(vedlegg, headers), ) val filnavn = response.body?.get("filnavn") assertThat(filnavn).isEqualTo(navn) } @Test fun `Skal returnere 400 for vedlegg som overstiger størrelsesgrensen`() { val vedlegg = leseVedlegg("ugyldig-2.6m.pdf") val response = restTemplate.exchange<Map<String, Any>>( localhost("/api/mapper/familie-dokument-test"), HttpMethod.POST, HttpEntity(vedlegg, headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.BAD_REQUEST) } @Test fun `Skal returnere 500 for vedlegg med ustøttet type`() { initMock() val vedlegg = leseVedlegg("ugyldig.txt") val response = restTemplate.exchange<Map<String, Any>>( localhost("/api/mapper/familie-dokument-test"), HttpMethod.POST, HttpEntity(vedlegg, headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.BAD_REQUEST) } @Test fun `Skal returnere 500 hvis Google Storage feil`() { val vedlegg = leseVedlegg("gyldig-0.8m.pdf") every { storageMock.create(any(), any<ByteArray>()) } throws StorageException( HttpStatus.UNAUTHORIZED.value(), "Unauthorized", ) val response = restTemplate.exchange<Map<String, Any>>( localhost("/api/mapper/familie-dokument-test"), HttpMethod.POST, HttpEntity(vedlegg, headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) } private fun leseVedlegg(navn: String): MultiValueMap<String, Any> { val content = StorageControllerIntegrationTest::class.java.getResource("/vedlegg/$navn")!!.readBytes() return MultipartBuilder() .withByteArray("file", navn, content) .build() } private fun initMock() { val slot = slot<ByteArray>() val blob = mockk<Blob>() every { storageMock.create(any(), capture(slot)) } answers { every { blob.getContent() } returns slot.captured blob } every { storageMock.get(any<BlobId>()) } returns blob } class RessursData { lateinit var data: ByteArray lateinit var status: Ressurs.Status } @Test fun `Skal lese vedlegg ut som er lagret`() { initMock() val vedlegg = leseVedlegg("gyldig-0.8m.pdf") val response = restTemplate.exchange<Map<String, String>>( localhost("/api/mapper/familie-dokument-test"), HttpMethod.POST, HttpEntity(vedlegg, headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.CREATED) val dokumentId = response.body?.get("dokumentId") headers.contentType = MediaType.APPLICATION_JSON val responseGet = restTemplate.exchange<String>( localhost("/api/mapper/familie-dokument-test/$dokumentId"), HttpMethod.GET, HttpEntity<String>(headers), ) assertThat(responseGet.statusCode).isEqualTo(HttpStatus.OK) val ressursData = objectMapper.readValue(responseGet.body?.toString(), RessursData::class.java) assertThat(ressursData.status).isEqualTo(Ressurs.Status.SUKSESS) assertThat(ressursData.data.size).isEqualTo((vedlegg.get("file")?.first() as ByteArrayResource).byteArray.size) } @Test fun `Skal kunne hente lagret vedlegg som bytearray uten å pakke inn det i ressurs`() { initMock() val vedlegg = leseVedlegg("gyldig-0.8m.pdf") val response = restTemplate.exchange<Map<String, String>>( localhost("/api/mapper/familie-dokument-test"), HttpMethod.POST, HttpEntity(vedlegg, headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.CREATED) val dokumentId = response.body?.get("dokumentId") headers.contentType = MediaType.APPLICATION_OCTET_STREAM val responseGet = restTemplate.exchange<String>( localhost("/api/mapper/familie-dokument-test/$dokumentId/pdf"), HttpMethod.GET, HttpEntity<String>(headers), ) assertThat(responseGet.statusCode).isEqualTo(HttpStatus.OK) assertThat(responseGet.body?.toString()?.length).isEqualTo((vedlegg.get("file")?.first() as ByteArrayResource).byteArray.size) } @Test fun `Skal returnere 404 for å hente ukjent dokument`() { every { storageMock.get(any<BlobId>()) } returns null headers.contentType = MediaType.APPLICATION_JSON val responseGet = restTemplate.exchange<String>( localhost("/api/mapper/familie-dokument-test/ukjent-id"), HttpMethod.GET, HttpEntity<String>(headers), ) assertThat(responseGet.statusCode).isEqualTo(HttpStatus.NOT_FOUND) } @Test internal fun `skal returnere 400 dersom tom liste sendes inn`() { val emptyMap = HttpHeaders() val response = restTemplate.exchange<Map<String, Any>>( localhost("/api/mapper/familie-dokument-test"), HttpMethod.POST, HttpEntity(emptyMap, headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.BAD_REQUEST) } }
0
Kotlin
0
0
d1955fc07994be0b5a949560f98813ae9870e8a5
7,011
familie-dokument
MIT License
src/main/kotlin/lirand/api/dsl/menu/exposed/fixed/chest/StaticChestMenu.kt
dyam0
453,766,342
false
null
package lirand.api.dsl.menu.exposed.fixed.chest import lirand.api.dsl.menu.exposed.fixed.StaticMenu import lirand.api.dsl.menu.exposed.fixed.StaticSlot import org.bukkit.inventory.Inventory interface StaticChestMenu : StaticMenu<StaticSlot<Inventory>, Inventory> { val lines: Int fun setInventory(inventory: Inventory) }
0
Kotlin
1
12
96cc59d4fbf0db90863499db798907a915e90237
327
LirandAPI
MIT License
feature/details/src/main/kotlin/com/yerastov/assignment/pokedex/feature/details/ui/PokemonDetailsScreen.kt
alterpie
592,035,814
false
null
package com.assignment.catawiki.details.ui import androidx.compose.animation.Crossfade import androidx.compose.animation.animateColor import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicText import androidx.compose.foundation.verticalScroll import androidx.compose.material.MaterialTheme import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.unit.dp import coil.compose.rememberAsyncImagePainter import com.assignment.catawiki.design.button.TextButton import com.assignment.catawiki.design.gradient.BottomGradient import com.assignment.catawiki.design.gradient.TopGradient import com.assignment.catawiki.details.mvi.PokemonDetailsContract.State import com.assignment.catawiki.pokemon.species.domain.model.PokemonSpecies import java.util.Locale import com.assignment.catawiki.design.R as DesignR @Composable internal fun PokemonDetailsScreen( state: State, onRetryLoadDetailsClick: () -> Unit, onRetryLoadEvolutionClick: () -> Unit, onBackClick: () -> Unit, ) { Box( modifier = Modifier .fillMaxSize() .background(color = MaterialTheme.colors.background) ) { Image( modifier = Modifier .align(Alignment.TopEnd) .statusBarsPadding() .padding(end = 16.dp) .size(150.dp) .alpha(0.5f), painter = rememberAsyncImagePainter(model = state.imageUrl), contentDescription = null, ) Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) .systemBarsPadding() .padding(horizontal = 16.dp) ) { TopAppBar(onBackClick = onBackClick) Spacer(modifier = Modifier.height(8.dp)) BasicText( text = state.name.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }, style = MaterialTheme.typography.h1.copy(color = MaterialTheme.colors.onBackground), ) Spacer(modifier = Modifier.height(16.dp)) if (state.error is State.Error.LoadingDetailsFailed) { ErrorSection( text = stringResource(DesignR.string.error_loading_details), onRetryClick = onRetryLoadDetailsClick ) } else { Crossfade(targetState = state.loadingDetails) { loading -> if (loading) { LoadingDetailsPlaceholder() } else { DetailsSection(description = state.description) } } } Spacer(modifier = Modifier.height(24.dp)) if (state.error == null) { Crossfade(targetState = state.loadingEvolution) { loading -> if (loading) { LoadingEvolutionPlaceholder() } else { EvolutionSection( evolution = state.evolution, captureRateDifference = state.captureRateDifference ) } } } else if (state.error is State.Error.LoadingEvolutionFailed) { ErrorSection( text = stringResource(DesignR.string.error_loading_evolution), onRetryClick = onRetryLoadEvolutionClick ) } Spacer(modifier = Modifier.height(16.dp)) } TopGradient() BottomGradient() } } @Composable private fun TopAppBar(onBackClick: () -> Unit) { Row( modifier = Modifier .fillMaxWidth() .height(48.dp), verticalAlignment = Alignment.CenterVertically ) { Image( painter = painterResource(DesignR.drawable.ic_arrow_back), contentDescription = null, colorFilter = ColorFilter.tint(color = MaterialTheme.colors.onBackground), modifier = Modifier.clickable( MutableInteractionSource(), rememberRipple(bounded = false), onClick = onBackClick ) ) } } @Composable private fun DetailsSection(description: String) { Column { BasicText( text = description, style = MaterialTheme.typography.subtitle1.copy(color = MaterialTheme.colors.onBackground) ) } } @Composable private fun EvolutionSection( evolution: PokemonSpecies.Evolution?, captureRateDifference: Int? ) { Column { when (evolution) { PokemonSpecies.Evolution.Final -> { BasicText( text = stringResource(DesignR.string.final_evolution_link), style = MaterialTheme.typography.h1.copy(color = MaterialTheme.colors.onBackground) ) } is PokemonSpecies.Evolution.EvolvesTo -> { if (captureRateDifference != null) { val captureRateColor = if (captureRateDifference < 0) { MaterialTheme.colors.error } else { MaterialTheme.colors.secondary } val captureRateLabel = buildAnnotatedString { val captureRateValue = kotlin.math.abs(captureRateDifference) val text = stringResource( DesignR.string.template_capture_rate_difference, captureRateValue ) append(text) val startIndex = text.indexOf(captureRateValue.toString()) val endIndex = startIndex + captureRateValue.toString().length addStyle( SpanStyle(color = captureRateColor), startIndex, endIndex ) } BasicText( text = captureRateLabel, style = MaterialTheme.typography.subtitle1.copy(color = MaterialTheme.colors.onBackground) ) } Spacer(modifier = Modifier.height(8.dp)) BasicText( text = stringResource(DesignR.string.evolves_to), style = MaterialTheme.typography.subtitle1.copy(color = MaterialTheme.colors.onBackground) ) Spacer(modifier = Modifier.height(16.dp)) Row( modifier = Modifier .fillMaxWidth() .height(160.dp) .clip(RoundedCornerShape(16.dp)) .border( width = 2.dp, color = MaterialTheme.colors.onBackground, shape = RoundedCornerShape(16.dp) ) .background(color = MaterialTheme.colors.surface), verticalAlignment = Alignment.CenterVertically, ) { Image( modifier = Modifier.size(150.dp), painter = rememberAsyncImagePainter(model = evolution.imageUrl), contentDescription = null, ) Spacer(modifier = Modifier.width(8.dp)) BasicText( modifier = Modifier .padding(bottom = 16.dp, end = 16.dp), text = evolution.name.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }, style = MaterialTheme.typography.h1.copy(color = MaterialTheme.colors.onSurface) ) } } null -> Unit } } } @Composable private fun LoadingDetailsPlaceholder() { val transition = rememberInfiniteTransition() val color by transition.animateColor( initialValue = MaterialTheme.colors.surface, targetValue = MaterialTheme.colors.surface.copy(alpha = 0.5f), animationSpec = infiniteRepeatable( animation = tween(1000, easing = LinearEasing), repeatMode = RepeatMode.Reverse, ) ) Column { Box( modifier = Modifier .clip(RoundedCornerShape(8.dp)) .background(color = color) .size(width = 150.dp, height = 28.dp) ) Spacer(modifier = Modifier.height(8.dp)) Box( modifier = Modifier .clip(RoundedCornerShape(8.dp)) .background(color = color) .size(width = 100.dp, height = 28.dp) ) Spacer(modifier = Modifier.height(8.dp)) Box( modifier = Modifier .clip(RoundedCornerShape(8.dp)) .background(color = color) .size(width = 180.dp, height = 28.dp) ) Spacer(modifier = Modifier.height(8.dp)) Box( modifier = Modifier .clip(RoundedCornerShape(8.dp)) .background(color = color) .size(width = 110.dp, height = 28.dp) ) } } @Composable private fun LoadingEvolutionPlaceholder() { val bgColorTransition = rememberInfiniteTransition() val bgColor by bgColorTransition.animateColor( initialValue = MaterialTheme.colors.surface, targetValue = MaterialTheme.colors.surface.copy(alpha = 0.5f), animationSpec = infiniteRepeatable( animation = tween(1000, easing = LinearEasing), repeatMode = RepeatMode.Reverse, ) ) val contentColorTransition = rememberInfiniteTransition() val contentColor by contentColorTransition.animateColor( initialValue = MaterialTheme.colors.onSurface, targetValue = MaterialTheme.colors.onSurface.copy(alpha = 0.5f), animationSpec = infiniteRepeatable( animation = tween(1000, easing = LinearEasing), repeatMode = RepeatMode.Reverse, ) ) Column(modifier = Modifier.padding(vertical = 16.dp)) { Box( modifier = Modifier .clip(RoundedCornerShape(8.dp)) .background(color = bgColor) .size(width = 110.dp, height = 28.dp) ) Spacer(modifier = Modifier.height(8.dp)) Box( modifier = Modifier .clip(RoundedCornerShape(8.dp)) .background(color = bgColor) .size(width = 80.dp, height = 28.dp) ) Spacer(modifier = Modifier.height(8.dp)) Box( modifier = Modifier .clip(RoundedCornerShape(8.dp)) .background(color = bgColor) .fillMaxWidth() .height(160.dp) ) { Box( modifier = Modifier .padding(start = 16.dp, top = 16.dp) .clip(RoundedCornerShape(8.dp)) .background(color = contentColor) .size(width = 110.dp, height = 28.dp) ) } } } @Composable private fun ErrorSection(text: String, onRetryClick: () -> Unit) { Column { BasicText( text = text, style = MaterialTheme.typography.subtitle1.copy(color = MaterialTheme.colors.onBackground) ) Spacer(modifier = Modifier.height(8.dp)) TextButton(text = stringResource(DesignR.string.retry), onClick = onRetryClick) } }
0
Kotlin
0
0
f6bb6b082eb8311c12b860b65a33cac54f19c8e9
13,593
Pokedex
Apache License 2.0
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/kapt2/android-databinding/library/src/androidTest/java/org/maw/library/ExampleInstrumentedTest.kt
JetBrains
3,432,266
false
null
package org.maw.library import android.support.test.annotation.UiThreadTest import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import android.view.ViewGroup import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * @see [Testing documentation](http://d.android.com/tools/testing) */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @get:Rule var activityTestRule = ActivityTestRule<BlankActivity>(BlankActivity::class.java) @UiThreadTest @Test fun createAndAddView() { val container = activityTestRule.activity.findViewById<ViewGroup>(android.R.id.content) val testView = TestView(activityTestRule.activity) container.addView(testView) } }
157
null
5209
42,102
65f712ab2d54e34c5b02ffa3ca8c659740277133
850
kotlin
Apache License 2.0
app/src/main/java/org/traccar/client/utils/PreferenceKey.kt
ilhamhadisyah
391,513,478
false
null
package org.traccar.client.utils object PreferenceKey { const val MAIN_PREFERENCE = "ceria" const val IS_LOGIN = "is_login" const val TOKEN = "token" const val PARENT_SESSION = "parent_session" const val CHILD_SESSION = "child_session" const val USERNAME = "username" const val PASSWORD = "<PASSWORD>" //timer service const val SECONDS = "seconds" const val RUNNING = "running" const val WAS_RUNNING = "was_running" }
0
Kotlin
0
0
429efeaf55dd468c9b9434ce7a6dec789027d5a9
464
ceria-nugraha-indotama-fms
Apache License 2.0
kool-editor/src/commonMain/kotlin/de/fabmax/kool/editor/overlays/TransformGizmoOverlay.kt
fabmax
81,503,047
false
null
package de.fabmax.kool.editor.ui import de.fabmax.kool.KoolContext import de.fabmax.kool.editor.KoolEditor import de.fabmax.kool.editor.model.SceneNodeModel import de.fabmax.kool.math.Mat4d import de.fabmax.kool.math.Vec3f import de.fabmax.kool.scene.Node import de.fabmax.kool.util.Gizmo import kotlin.math.sqrt class NodeTransformGizmo(private val editor: KoolEditor) : Node("Node transform gizmo") { private var transformNodeModel: SceneNodeModel? = null private var hasTransformAuthority = false private val gizmo = Gizmo() private val gizmoListener = object : Gizmo.GizmoListener { private val startTransform = Mat4d() override fun onDragAxis(axis: Vec3f, distance: Float, targetTransform: Mat4d, ctx: KoolContext) { targetTransform.translate(axis.x * distance, axis.y * distance, axis.z * distance) } override fun onDragPlane(planeNormal: Vec3f, dragPosition: Vec3f, targetTransform: Mat4d, ctx: KoolContext) { targetTransform.translate(dragPosition) } override fun onDragRotate(rotationAxis: Vec3f, angle: Float, targetTransform: Mat4d, ctx: KoolContext) { targetTransform.rotate(angle, rotationAxis) } override fun onDragStart(ctx: KoolContext) { transformNodeModel?.let { val transformNode = it.node startTransform.set(transformNode.transform.matrix) hasTransformAuthority = true } } override fun onDragFinished(ctx: KoolContext) { hasTransformAuthority = false transformNodeModel?.let { val transformNode = it.node ObjectPropertyEditor.applyTransformAction(it, startTransform, transformNode.transform.matrix) } } } init { addNode(gizmo) hideGizmo() gizmo.gizmoListener = gizmoListener gizmo.onUpdate { transformNodeModel?.node?.let { if (hasTransformAuthority) { val gizmoTransform = Mat4d() val tmp = Mat4d() gizmo.getGizmoTransform(gizmoTransform) it.parent?.transform?.matrixInverse?.let { toLocal -> toLocal.mul(gizmoTransform, tmp) gizmoTransform.set(tmp) } it.transform.set(gizmoTransform) it.updateModelMat(true) } else { gizmo.transform.set(it.modelMat) gizmo.transform.matrix.resetScale() gizmo.setFixedScale(sqrt(it.globalRadius) + 0.5f) } } } } private fun hideGizmo() { gizmo.isVisible = false editor.editorInputContext.pointerListeners -= gizmo } private fun showGizmo() { gizmo.isVisible = true if (gizmo !in KoolEditor.instance.editorInputContext.pointerListeners) { editor.editorInputContext.pointerListeners += gizmo } } fun setTransformObject(nodeModel: SceneNodeModel?) { transformNodeModel = nodeModel gizmo.isVisible = nodeModel != null nodeModel?.node?.let { gizmo.setFixedScale(sqrt(it.globalRadius) + 0.5f) } if (nodeModel != null) { showGizmo() } else { hideGizmo() } } }
9
null
13
191
a72584d9cdf14d7f8bafc40eefc7e694eb121bb8
3,440
kool
Apache License 2.0
idea/testData/refactoring/move/kotlin/moveFile/moveMultipleFIles/after/target/foo.kt
JakeWharton
99,388,807
false
null
package target interface NamedFaceN class NamedClassN : NamedFaceN
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
68
kotlin
Apache License 2.0
app/src/main/java/com/tamimi/movies/ui/HostActivity.kt
tamtom
228,876,159
false
null
package com.tamimi.movies.ui import android.os.Bundle import com.tamimi.movies.R import com.tamimi.movies.ui.base.BaseDaggerActivity class HostActivity : BaseDaggerActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
0
Kotlin
0
0
e366f6e72816c0edf4c10a8d5c2293e85aa1fd34
334
MoviesCatalog
Apache License 2.0
typescript-kotlin/src/jsMain/kotlin/typescript/PseudoLiteralSyntaxKind.kt
karakum-team
393,199,102
false
{"Kotlin": 6915863}
// Automatically generated - do not modify! package typescript sealed external interface PseudoLiteralSyntaxKind : SyntaxKind, Union.PseudoLiteralSyntaxKind_ /* SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail */
0
Kotlin
7
31
d1315f1524758eb6883a4f7e0a0da46816152ed8
248
types-kotlin
Apache License 2.0
src/main/kotlin/model/RunEmulatorParams.kt
Pulimet
678,269,308
false
{"Kotlin": 295687}
package model data class RunEmulatorParams( val proxy: String = "", val ram: Int = 0, val partition: Int = 0, val latency: String = "none", val speed: String = "full", val quickBoot: String = "enabled", val touchMode: String = "touch", val bootAnimEnabled: Boolean = true, val audioEnabled: Boolean = true, )
12
Kotlin
2
25
62a201e9b3cd9cfd4eca32b77da2d27e8b1483b1
345
ADBugger
MIT License
completion/src/org/jetbrains/kotlin/idea/completion/handlers/SmartCompletionTailOffsetProviderFE10Impl.kt
JetBrains
278,369,660
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.handlers import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.Lookup import com.intellij.codeInsight.lookup.LookupElement import org.jetbrains.kotlin.idea.completion.KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY import org.jetbrains.kotlin.idea.completion.smart.SmartCompletion import org.jetbrains.kotlin.idea.completion.tryGetOffset class SmartCompletionTailOffsetProviderFE10Impl: SmartCompletionTailOffsetProvider() { override fun getTailOffset(context: InsertionContext, item: LookupElement): Int { val completionChar = context.completionChar var tailOffset = context.tailOffset if (completionChar == Lookup.REPLACE_SELECT_CHAR && item.getUserData(KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY) != null) { context.offsetMap.tryGetOffset(SmartCompletion.OLD_ARGUMENTS_REPLACEMENT_OFFSET) ?.let { tailOffset = it } } return tailOffset } }
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
1,196
intellij-kotlin
Apache License 2.0
backend/testing/src/main/kotlin/io/tolgee/testing/AbstractTransactionalTest.kt
tolgee
303,766,501
false
null
package io.tolgee.testing import io.tolgee.repository.LanguageRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.transaction.TestTransaction import org.springframework.transaction.annotation.Transactional import javax.persistence.EntityManager @Transactional abstract class AbstractTransactionalTest { @Autowired protected lateinit var entityManager: EntityManager @Autowired protected lateinit var languageRepository: LanguageRepository protected fun commitTransaction() { TestTransaction.flagForCommit() entityManager.flush() TestTransaction.end() TestTransaction.start() entityManager.clear() } }
28
Kotlin
4
134
cb12f5f4ecf162276df52b8cf782f287fca1bc75
698
server
Apache License 2.0
app/src/main/java/fr/legris/pokedex/ui/model/Type.kt
legrisnico
346,312,999
false
{"Kotlin": 55798}
package fr.legris.pokedex.ui.model import androidx.compose.ui.graphics.Color import fr.legris.pokedex.ui.theme.* enum class Type( val typeName: String, val typeColor: Color ) { NORMAL("normal", normalTypeColor), FIRE("fire", fireTypeColor), WATER("water", waterTypeColor), GRASS("grass", grassTypeColor), ELECTRIC("electric", electricTypeColor), ICE("ice", iceTypeColor), FIGHTING("fighting", fightingTypeColor), POISON("poison", poisonTypeColor), GROUND("ground", groundTypeColor), FLYING("flying", flyingTypeColor), PSYCHIC("psychic", psychicTypeColor), BUG("bug", bugTypeColor), ROCK("rock", rockTypeColor), GHOST("ghost", ghostTypeColor), DRAGON("dragon", dragonTypeColor), DARK("dark", darkTypeColor), STEEL("steel", steelTypeColor), FAIRY("fairy", fairyTypeColor), UNKNOWN("unknown", fairyTypeColor), }
2
Kotlin
0
1
fb07531519c80d0884b2f30c987ad0c06ff7e2f7
894
pokedex
Apache License 2.0
ktorm-ksp-compiler/src/main/kotlin/org/ktorm/ksp/compiler/generator/ComponentFunctionGenerator.kt
kotlin-orm
159,785,192
false
{"Kotlin": 1287281, "Java": 1980}
/* * Copyright 2018-2024 the original author or authors. * * 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.ktorm.ksp.compiler.generator import com.google.devtools.ksp.isAbstract import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ksp.KotlinPoetKspPreview import com.squareup.kotlinpoet.ksp.toClassName import com.squareup.kotlinpoet.ksp.toTypeName import org.ktorm.ksp.compiler.util._type import org.ktorm.ksp.spi.TableMetadata @OptIn(KotlinPoetKspPreview::class) internal object ComponentFunctionGenerator { fun generate(table: TableMetadata): Sequence<FunSpec> { return table.entityClass.getAllProperties() .filter { it.isAbstract() } .filterNot { it.simpleName.asString() in setOf("entityClass", "properties") } .mapIndexed { i, prop -> FunSpec.builder("component${i + 1}") .addKdoc("Return the value of [%L.%L]. ", table.entityClass.simpleName.asString(), prop.simpleName.asString()) .addModifiers(KModifier.OPERATOR) .receiver(table.entityClass.toClassName()) .returns(prop._type.toTypeName()) .addCode("return·this.%N", prop.simpleName.asString()) .build() } } }
84
Kotlin
143
2,023
f59e40695218ae370401d1c27a9134f2b944364a
1,882
ktorm
Apache License 2.0
src/test/kotlin/com/vauthenticator/server/support/SmsUtils.kt
VAuthenticator
191,632,792
false
{"Kotlin": 594019, "TypeScript": 47216, "HCL": 13254, "Python": 11052, "HTML": 6658, "Shell": 1961, "JavaScript": 1917, "Dockerfile": 1302}
package com.vauthenticator.server.support import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.springframework.web.client.RestClient.builder import software.amazon.awssdk.auth.credentials.AwsBasicCredentials import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider import software.amazon.awssdk.regions.Region import software.amazon.awssdk.services.sns.SnsClient import java.net.URI private val objectMapper = jacksonObjectMapper() private val restClient = builder().build() object SmsUtils { val snsClient: SnsClient = SnsClient.builder() .credentialsProvider( StaticCredentialsProvider.create( AwsBasicCredentials.create("ACCESS_KEY_ID", "SECRET_ACCESS_KEY") ) ).region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:4566")) .build() fun getMessageFor(phoneNumber: String, messageId: Int = 0): String { val body = restClient.get() .uri("http://localhost:4566/_aws/sns/sms-messages") .retrieve() .body(String::class.java) return objectMapper .readTree(body) .at("/sms_messages/$phoneNumber/$messageId/Message").asText() } fun resetSmsProvider() { restClient.delete() .uri("http://localhost:4566/_aws/sns/sms-messages") .retrieve() } }
41
Kotlin
1
18
6c7f6cd4820318921a3a08844d063e55f92fca97
1,399
vauthenticator
Apache License 2.0
core/src/commonMain/kotlin/work/socialhub/kslack/api/methods/request/files/FilesUploadRequest.kt
uakihir0
794,979,552
false
{"Kotlin": 868677, "Ruby": 2164, "Shell": 2095, "Makefile": 316}
package work.socialhub.kslack.api.methods.request.files import work.socialhub.kslack.api.methods.FormRequest import work.socialhub.kslack.api.methods.SlackApiRequest class FilesUploadRequest( /** Authentication token. Requires scope: `files:write:user` */ override var token: String?, /** File contents via `multipart/form-data`. If omitting this parameter, you must submit `content`. */ var file: ByteArray?, /** File contents via a POST variable. If omitting this parameter, you must provide a `file`. */ var content: String?, /** A [file type](/types/file#file_types) identifier. */ var filetype: String?, /** Filename of file. */ var filename: String?, /** Title of file. */ var title: String?, /** Initial comment to add to file. */ var initialComment: String?, /** Comma-separated list of channel names or IDs where the file will be shared. */ var channels: Array<String>?, /** Provide another message's ts value to upload this file as a reply. Never use a reply's ts value; use its parent instead. */ var threadTs: String?, ) : SlackApiRequest, FormRequest { override fun toMap(): Map<String, Any> { return mutableMapOf<String, Any>().also { it.addParam("content", content) it.addParam("filetype", filetype) it.addParam("filename", filename) it.addParam("title", title) it.addParam("initial_comment", initialComment) if (channels != null) { it.addParam("channels", channels!!.joinToString(",")) } } /* TODO if (File() != null) { form.addFile("file", File) } if (Filestream() != null) { form.addFile("file", Filestream(), Filename) } it.addParam("filetype", Filetype) it.addParam("filename", Filename) it.addParam("title", Title) it.addParam("initial_comment", InitialComment) if (Channels() != null) { it.addParam("channels", Channels().stream().collect(java.util.stream.Collectors.joining(","))) } it.addParam("thread_ts", ThreadTs) */ } }
5
Kotlin
0
0
3975e9de4fae5ef2ddc5b013c2a346536852f7b3
2,203
kslack
MIT License
android/src/main/kotlin/com/ekycsolutions/ekyc_id_flutter/FaceScanner/FaceScannerViewFactory.kt
EKYCSolutions
507,305,515
false
{"Dart": 59127, "Swift": 40658, "Kotlin": 33972, "Ruby": 2309, "Objective-C": 732, "Shell": 460}
package com.ekycsolutions.ekyc_id_flutter.FaceScanner import android.content.Context import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.StandardMessageCodec import io.flutter.plugin.platform.PlatformView import io.flutter.plugin.platform.PlatformViewFactory class FaceScannerViewFactory( private var binding: FlutterPlugin.FlutterPluginBinding, private var context: Context ): PlatformViewFactory(StandardMessageCodec.INSTANCE) { override fun create(_s: Context?, viewId: Int, args: Any?): PlatformView { return FlutterFaceScanner(binding, context, viewId) } }
0
Dart
4
18
17571db6ccffbed61a1c00e768c19d42c3b74405
626
ekyc-id-flutter
Academic Free License v1.2
app/src/main/java/com/yoy/foodiemap/MapFragment.kt
yy197133
173,682,545
false
null
package com.yoy.foodiemap import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.navigation.fragment.findNavController import com.amap.api.location.AMapLocation import com.amap.api.location.AMapLocationClient import com.amap.api.location.AMapLocationClientOption import com.amap.api.location.AMapLocationListener import com.amap.api.maps.AMap import com.amap.api.maps.CameraUpdateFactory import com.amap.api.maps.MapView import com.amap.api.maps.Projection import com.amap.api.maps.model.* import com.yoy.foodiemap.adapters.InfoWindowAdapter import com.yoy.foodiemap.utils.Injector import com.yoy.foodiemap.viewmodels.PlacesViewModel import kotlinx.android.synthetic.main.fragment_map.view.* class MapFragment : Fragment(), AMapLocationListener { private var rootView: View? = null private lateinit var viewModel: PlacesViewModel private lateinit var mMapView: MapView private lateinit var mLocationBtn: ImageButton private lateinit var aMap: AMap private var mLocationClient: AMapLocationClient? = null private var useMoveToLocationWithMapMode = true private lateinit var currLatLng: LatLng //自定义定位小蓝点的Marker // private var locationMarker: Marker? = null //坐标和经纬度转换工具 private var projection: Projection? = null // private val myCancelCallback = MyCancelCallback() private val mInfoWindowAdapter by lazy { InfoWindowAdapter(requireContext()) } //当前选中的已收藏的marker private var placeMarker: Marker? = null //点击地图poi,添加的marker private var poiMarker: Marker? = null private var isMarkerClicked = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { Log.i("123","onCreateView:$activity") if (rootView == null){ rootView = inflater.inflate(R.layout.fragment_map,container,false) mMapView = rootView!!.mapView mLocationBtn = rootView!!.map_view_location mMapView.onCreate(savedInstanceState) viewModel = ViewModelProviders .of(this, Injector.providePlaceViewModelFactory(requireContext())) .get(PlacesViewModel::class.java) init() initListeners() } return rootView } override fun onDestroyView() { super.onDestroyView() } private fun init() { if (!this::aMap.isInitialized) { aMap = mMapView.map locate() } addMarkers() } private fun initListeners(){ aMap.setOnMyLocationChangeListener { currLatLng = LatLng(it.latitude, it.longitude) } aMap.setOnMarkerClickListener{ //如果点击的是本身定位marker if (it.position.latitude == aMap.myLocation.latitude && it.position.longitude == aMap.myLocation.longitude) return@setOnMarkerClickListener true if (poiMarker == it){ val poi = poiMarker?.`object` as Poi val args = bundleOf( AddPlaceFragment.NAME to poi.name, AddPlaceFragment.ADDRESS to "", AddPlaceFragment.LAT to poi.coordinate.latitude, AddPlaceFragment.LNG to poi.coordinate.longitude) findNavController().navigate(R.id.action_fragment_map_to_addPlaceFragment,args) it.remove() return@setOnMarkerClickListener true } val places = viewModel.places.value places?.forEach { place -> if (it.position == place.getLatLng()){ // toast(place.name) mInfoWindowAdapter.place = place placeMarker = it isMarkerClicked = true } } false } aMap.setOnMapClickListener { if (isMarkerClicked) isMarkerClicked = false else { placeMarker?.hideInfoWindow() placeMarker = null } poiMarker?.remove() } aMap.setOnPOIClickListener { placeMarker?.hideInfoWindow() placeMarker = null poiMarker?.remove() poiMarker = null val markerOptions = MarkerOptions() markerOptions.position(it.coordinate) val view = layoutInflater.inflate(R.layout.marker_add_place,null) markerOptions.icon(BitmapDescriptorFactory.fromView(view)) poiMarker = aMap.addMarker(markerOptions) poiMarker?.`object` = it } aMap.setOnMapLongClickListener { } mLocationBtn.setOnClickListener { aMap.moveCamera(CameraUpdateFactory.changeLatLng(currLatLng)) } } private fun setUpMap() { val myLocationStyle = MyLocationStyle() myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER) myLocationStyle.interval(2000) myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.ic_navigation)) myLocationStyle.radiusFillColor(resources.getColor(R.color.location_circle)) myLocationStyle.strokeColor(resources.getColor(R.color.location_circle)) aMap.myLocationStyle = myLocationStyle // aMap.setLocationSource(this) // aMap.uiSettings.isMyLocationButtonEnabled = true aMap.uiSettings.isZoomControlsEnabled = false aMap.uiSettings.isRotateGesturesEnabled = false aMap.isMyLocationEnabled = true aMap.setInfoWindowAdapter(mInfoWindowAdapter) } private fun locate() { if (mLocationClient == null) { val locationClientOption = AMapLocationClientOption() mLocationClient = AMapLocationClient(context) //设置定位监听 mLocationClient?.setLocationListener(this) locationClientOption.isOnceLocation = true locationClientOption.isLocationCacheEnable = false //设置为高精度定位模式 locationClientOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy //是指定位间隔 // locationClientOption.interval = 2000 //设置定位参数 mLocationClient?.setLocationOption(locationClientOption) // 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗, // 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求 // 在定位结束后,在合适的生命周期调用onDestroy()方法 // 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除 mLocationClient?.startLocation() } } private fun addMarkers() { viewModel.places.observe(this, Observer { it?.forEach { place -> aMap.addMarker( MarkerOptions() .position(LatLng(place.lat, place.lng)) .icon(BitmapDescriptorFactory.fromResource(R.mipmap.location_marker)) .snippet(place.name) .anchor(0.5f, 0.5f) ) } }) } private fun deactivate() { mLocationClient?.let { it.stopLocation() it.onDestroy() } mLocationClient = null } /** * 定位成功后回调函数 */ override fun onLocationChanged(amapLocation: AMapLocation?) { if (amapLocation != null && amapLocation.errorCode == 0) { currLatLng = LatLng(amapLocation.latitude, amapLocation.longitude) //展示自定义定位小蓝点 // if (locationMarker == null){ //首次定位 // locationMarker = aMap.addMarker( // MarkerOptions() // .position(latLng) // .icon(BitmapDescriptorFactory.fromResource(R.mipmap.location_marker)) // .anchor(0.5f,0.5f)) //首次定位,选择移动到地图中心点并修改级别到15级 aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currLatLng, 16f)) if (useMoveToLocationWithMapMode) { useMoveToLocationWithMapMode = false setUpMap() } // } // else { // if (useMoveToLocationWithMapMode) // moveLocationAndMap(latLng) // else // changeLocation(latLng) // } } } override fun onResume() { super.onResume() mMapView.onResume() useMoveToLocationWithMapMode = true } override fun onPause() { super.onPause() mMapView.onPause() deactivate() useMoveToLocationWithMapMode = false } override fun onDestroy() { super.onDestroy() mMapView.onDestroy() mLocationClient?.onDestroy() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) mMapView.onSaveInstanceState(outState) } }
0
Kotlin
0
0
aa9316aeb108f8e1d521e5e44cc768c3888ddea2
9,318
FoodieMap
Apache License 2.0