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
apps-projects/Native-Android-Kotlin/04-mobileapp-android-commerce/src/main/java/br/com/cybertimeup/appcommerce/CartActivity.kt
jonypeixoto
315,496,664
false
{"PHP": 1686780, "HTML": 793867, "JavaScript": 524420, "CSS": 449282, "Kotlin": 77277, "SCSS": 33028, "Hack": 29882, "Java": 1169, "EJS": 714}
package br.com.cybertimeup.appcommerce import android.os.Bundle import android.widget.TextView import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.lifecycle.Observer import br.com.cybertimeup.appcommerce.viewmodel.CartViewModel class CartActivity : AppCompatActivity(), CartFragment.Callback { lateinit var toolbar: Toolbar lateinit var textTitle: TextView lateinit var cartTotal: TextView private val cartViewModel by viewModels<CartViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_cart) toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowTitleEnabled(false) textTitle = findViewById(R.id.toolbar_title) textTitle.text = getString(R.string.cart_title) cartTotal = findViewById(R.id.tv_total) cartViewModel.cartPrice.observe(this, Observer { cartTotal.text = "R$ ${it}" }) val fragment = ProductFragment() supportFragmentManager.beginTransaction() .replace(R.id.fragment_cart, fragment) .commit() } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } override fun updateCart() { cartViewModel.cartPrice.value = CartViewModel.order.price } }
0
PHP
1
1
dd8a34f51151fe4cf51d3d387737bedd325ab645
1,552
full-stack-web2-projects
MIT License
kpermissions/src/test/kotlin/com/fondesa/kpermissions/request/runtime/FragmentRuntimePermissionHandlerProviderTest.kt
naseemakhtar994
117,924,700
true
{"Kotlin": 123298, "Groovy": 16841}
/* * Copyright (c) 2018 Fondesa * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fondesa.kpermissions.request.runtime import android.app.Activity import android.app.Fragment import android.os.Build import com.fondesa.test.createActivity import junit.framework.Assert.* import org.hamcrest.CoreMatchers.instanceOf import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config /** * Tests for [FragmentRuntimePermissionHandlerProvider]. */ @RunWith(RobolectricTestRunner::class) @Config(minSdk = Build.VERSION_CODES.M) class FragmentRuntimePermissionHandlerProviderTest { private val activity = createActivity<Activity>() private val provider = FragmentRuntimePermissionHandlerProvider(activity.fragmentManager) @Test fun handlerProvided() { // Provide the handler. val handler = provider.provideHandler() assertNotNull(handler) assertThat(handler, instanceOf(RuntimePermissionHandler::class.java)) // The handler must be a Fragment. assertThat(handler, instanceOf(Fragment::class.java)) val fragment = handler as Fragment // The Fragment must be attached and not visible. assertTrue(fragment.isAdded) assertFalse(fragment.isVisible) } @Test fun sameFragmentProvidedMultipleTimes() { // Provide the handler. val fragment = provider.provideHandler() val secondFragment = provider.provideHandler() // They must point to the same Fragment. assertEquals(fragment, secondFragment) } }
0
Kotlin
0
0
3b41da8908849be1b135956e94802042a7503e84
2,188
KPermissions
Apache License 2.0
checkboxlibrary/src/main/java/com/github/praveen2gemini/CheckBoxGroup.kt
praveen2gemini
142,638,553
false
null
package com.github.praveen2gemini import android.content.Context import android.content.res.ColorStateList import android.content.res.TypedArray import android.graphics.Color import android.os.Build import android.support.annotation.ColorInt import android.support.annotation.IdRes import android.support.annotation.StyleRes import android.support.v4.content.ContextCompat import android.support.v4.widget.CompoundButtonCompat import android.util.AttributeSet import android.util.Log import android.util.TypedValue import android.view.View import android.view.ViewGroup import android.view.autofill.AutofillManager import android.widget.CheckBox import android.widget.CompoundButton import android.widget.LinearLayout import com.praveen2gemini.design.R import java.util.* /** * @author Praveen on 26/07/18. */ class CheckBoxGroup : LinearLayout { private val mCheckedIds = ArrayList<Int>() // tracks children checkbox buttons checked state private lateinit var mChildOnCheckedChangeListener: CompoundButton.OnCheckedChangeListener private lateinit var mPassThroughListener: PassThroughHierarchyChangeListener private var mOnCheckedChangeListener: CheckBoxGroup.OnCheckedChangeListener? = null private var isCheckGroupHeaderEnabled: Boolean = false private var checkGroupHeaderTitle: String? = null @ColorInt private var checkGroupHeaderTitleColor: Int? = null @ColorInt private var checkGroupHeaderBackgroundColor: Int? = null private var innerMarginValue: Int? = null private var checkGroupHeaderMaxLines: Int = Int.MAX_VALUE private var checkGroupBoxTextSize: Float? = null @StyleRes private var checkGroupBoxTextAppearance: Int? = null /** * * Returns the identifier of the selected checkbox button in this group. * Upon empty selection, the returned value is -1. * * @return the unique id of the selected checkbox button in this group * @attr ref android.R.styleable#checkboxGroup_checkedButton * @see .check * @see .clearCheck */ val checkedCheckboxButtonIds: ArrayList<Int> @IdRes get() = ArrayList(HashSet(mCheckedIds)) constructor(context: Context) : super(context) { if (!isInEditMode) { init(null) } } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { if (!isInEditMode) { init(attrs) } } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { if (!isInEditMode) { // checkboxGroup is important by default, unless app developer overrode attribute. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (importantForAutofill == View.IMPORTANT_FOR_AUTOFILL_AUTO) { importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_YES } } init(attrs) } } private fun init(attrs: AttributeSet?) { val a = context.theme.obtainStyledAttributes( attrs, R.styleable.CheckBoxGroup, 0, 0) try { isCheckGroupHeaderEnabled = a.getBoolean(R.styleable.CheckBoxGroup_isCheckGroupHeaderEnabled, false) checkGroupHeaderTitle = a.getString(R.styleable.CheckBoxGroup_checkGroupHeaderTitle) checkGroupHeaderTitleColor = a.getColor(R.styleable.CheckBoxGroup_checkGroupHeaderTextColor, Color.BLACK) checkGroupHeaderBackgroundColor = a.getColor(R.styleable.CheckBoxGroup_checkGroupHeaderBackgroundColor, Color.TRANSPARENT) innerMarginValue = a.getDimensionPixelOffset(R.styleable.CheckBoxGroup_checkGroupChildInnerMargin, 10) checkGroupBoxTextSize = a.getDimension(R.styleable.CheckBoxGroup_checkGroupHeaderTextSize, -1f) checkGroupHeaderMaxLines = a.getInteger(R.styleable.CheckBoxGroup_checkGroupHeaderMaxLines, Int.MAX_VALUE) checkGroupBoxTextAppearance = a.getResourceId( R.styleable.CheckBoxGroup_checkGroupHeaderTextAppearance, -1) } finally { a.recycle(); } mChildOnCheckedChangeListener = CheckedStateTracker() mPassThroughListener = PassThroughHierarchyChangeListener() super.setOnHierarchyChangeListener(mPassThroughListener) } @ColorInt private fun findAccentColor(): Int { var a: TypedArray? = null try { val typedValue = TypedValue() a = context.obtainStyledAttributes(typedValue.data, intArrayOf(R.attr.colorAccent)) return a.getColor(0, Color.BLACK) // Default BLACK } finally { a?.recycle() } } /** * * Sets the selection to the checkbox button whose identifier is passed in * parameter. Using -1 as the selection identifier clears the selection; * such an operation is equivalent to invoking * * @param id the unique id of the checkbox button to select in this group */ fun check(@IdRes id: Int) { val isChecked = mCheckedIds.contains(id) if (id != -1) { setCheckedStateForView(id, isChecked) } setCheckedId(id, isChecked) } private fun setCheckedId(@IdRes id: Int, isChecked: Boolean) { if (id == DEFAULT_HEADER_ID) { for (i in 1..childCount) { [email protected](i)?.let { val headerCheckBox = it as CheckBox headerCheckBox.isChecked = isChecked } } } else { if (mCheckedIds.contains(id) && !isChecked) { mCheckedIds.remove(id) } else { mCheckedIds.add(id) } } val headerCheckBox = [email protected](0) as CheckBox when { checkedCheckboxButtonIds.size == 0 -> { headerCheckBox.isActivated = false headerCheckBox.isChecked = false } checkedCheckboxButtonIds.size == childCount - 1 -> { headerCheckBox.isActivated = false headerCheckBox.isChecked = true } checkedCheckboxButtonIds.size in 1..(childCount - 2) -> { headerCheckBox.isActivated = true CompoundButtonCompat.setButtonTintList(headerCheckBox, ColorStateList.valueOf(findAccentColor())) } } mOnCheckedChangeListener?.onCheckedChanged(this, id, isChecked) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { val afm = context.getSystemService(AutofillManager::class.java) afm?.notifyValueChanged(this) } } private fun setCheckedStateForView(@IdRes viewId: Int, checked: Boolean) { val checkedView = findViewById<View>(viewId) if (checkedView != null && checkedView is CheckBox) { checkedView.isChecked = checked } } override fun generateLayoutParams(attrs: AttributeSet): LayoutParams { return CheckBoxGroup.LayoutParams(context, attrs) } override fun setOnHierarchyChangeListener(listener: ViewGroup.OnHierarchyChangeListener) { mPassThroughListener.mOnHierarchyChangeListener = listener } override fun onFinishInflate() { super.onFinishInflate() for (mCheckedId in mCheckedIds) { // checks the appropriate checkbox button as requested in the XML file if (mCheckedId <= 0) continue setCheckedStateForView(mCheckedId, true) setCheckedId(mCheckedId, true) } } override fun addView(child: View, index: Int, params: ViewGroup.LayoutParams) { addCheckBoxHeader(0, params) val marginAddedParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) if (child is CheckBox) { Log.e("***********", "checkboz added " + child.text) Log.e("***********", "checkboz this.childCount " + this.childCount) innerMarginValue?.let { marginAddedParams.leftMargin = getInnerChildMargin(it) if (params is LinearLayout.LayoutParams) { marginAddedParams.rightMargin = params.rightMargin marginAddedParams.topMargin = params.topMargin marginAddedParams.bottomMargin = params.bottomMargin } } CompoundButtonCompat.setButtonTintList(child, ColorStateList.valueOf(findAccentColor())) if (child.isChecked) { setCheckedId(child.id, true) } } super.addView(child, index, marginAddedParams) } private fun getInnerChildMargin(dpValue: Int): Int { val d = context.resources.displayMetrics.density return (dpValue * d).toInt() // margin in pixels } private fun addCheckBoxHeader(index: Int, params: ViewGroup.LayoutParams?) { params?.let { if (childCount == 0 && isCheckGroupHeaderEnabled) { val headerBox = CheckBox(context) headerBox.id = DEFAULT_HEADER_ID headerBox.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) checkGroupHeaderTitleColor?.let { headerBox.setTextColor(it) } checkGroupHeaderBackgroundColor?.let { headerBox.setBackgroundColor(it) } headerBox.text = checkGroupHeaderTitle headerBox.maxLines = checkGroupHeaderMaxLines checkGroupBoxTextAppearance?.let { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { headerBox.setTextAppearance(it) } else { headerBox.setTextAppearance(context, it) } } checkGroupBoxTextSize?.let { if (it != -1f) { headerBox.textSize = it } } headerBox.buttonDrawable = ContextCompat.getDrawable(context, R.drawable.checkbox_selector) CompoundButtonCompat.setButtonTintList(headerBox, ColorStateList.valueOf(findAccentColor())) super.addView(headerBox, index, it) } } } /** * * Clears the selection. When the selection is cleared, no checkbox button * in this group is selected * null. */ fun clearCheck() { check(-1) } /** * * Register a callback to be invoked when the checked checkbox button * changes in this group. * * @param listener the callback to call on checked state change */ fun setOnCheckedChangeListener(listener: OnCheckedChangeListener) { mOnCheckedChangeListener = listener } /** * * Interface definition for a callback to be invoked when the checked * checkbox button changed in this group. */ interface OnCheckedChangeListener { /** * * Called when the checked checkbox button has changed. When the * selection is cleared, checkedId is -1. * * @param group the group in which the checked checkbox button has changed * @param checkedId the unique identifier of the newly checked checkbox button */ fun onCheckedChanged(group: CheckBoxGroup, @IdRes checkedId: Int, isChecked: Boolean) } /** * * This set of layout parameters defaults the width and the height of * the children to [.WRAP_CONTENT] when they are not specified in the * XML file. Otherwise, this class ussed the value read from the XML file. * * * for a list of all child view attributes that this class supports. */ class LayoutParams : LinearLayout.LayoutParams { constructor(c: Context, attrs: AttributeSet) : super(c, attrs) constructor(w: Int, h: Int) : super(w, h) constructor(w: Int, h: Int, initWeight: Float) : super(w, h, initWeight) constructor(p: ViewGroup.LayoutParams) : super(p) constructor(source: ViewGroup.MarginLayoutParams) : super(source) /** * * Fixes the child's width to * [android.view.ViewGroup.LayoutParams.WRAP_CONTENT] and the child's * height to [android.view.ViewGroup.LayoutParams.WRAP_CONTENT] * when not specified in the XML file. * * @param a the styled attributes set * @param widthAttr the width attribute to fetch * @param heightAttr the height attribute to fetch */ override fun setBaseAttributes(a: TypedArray, widthAttr: Int, heightAttr: Int) { width = if (a.hasValue(widthAttr)) { a.getLayoutDimension(widthAttr, "layout_width") } else { ViewGroup.LayoutParams.WRAP_CONTENT } height = if (a.hasValue(heightAttr)) { a.getLayoutDimension(heightAttr, "layout_height") } else { ViewGroup.LayoutParams.WRAP_CONTENT } } } private inner class CheckedStateTracker : CompoundButton.OnCheckedChangeListener { override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) { val id = buttonView.id setCheckedId(id, isChecked) } } /** * * A pass-through listener acts upon the events and dispatches them * to another listener. This allows the table layout to set its own internal * hierarchy change listener without preventing the user to setup his. */ private inner class PassThroughHierarchyChangeListener : ViewGroup.OnHierarchyChangeListener { internal var mOnHierarchyChangeListener: ViewGroup.OnHierarchyChangeListener? = null override fun onChildViewAdded(parent: View, child: View) { if (parent === this@CheckBoxGroup && child is CheckBox) { var id = child.getId() // generates an id if it's missing if (id == View.NO_ID) { id = View.generateViewId() child.setId(id) } child.setOnCheckedChangeListener( mChildOnCheckedChangeListener) } mOnHierarchyChangeListener?.onChildViewAdded(parent, child) } override fun onChildViewRemoved(parent: View, child: View) { if (parent === this@CheckBoxGroup && child is CheckBox) { child.setOnCheckedChangeListener(null) } mOnHierarchyChangeListener?.onChildViewRemoved(parent, child) } } companion object { val DEFAULT_HEADER_ID: Int = 1234 } }
0
Kotlin
3
4
99e402d7c18b01466d4515b0299ad314f5762251
15,022
Android-CheckBoxGroup
Apache License 2.0
MomentumAndroid/src/main/java/com/mwaibanda/momentum/android/presentation/event/EventViewModel.kt
MwaiBanda
509,266,324
false
{"Kotlin": 463439, "Swift": 256451, "Ruby": 2520}
package com.mwaibanda.momentum.android.presentation.event import android.util.Log import androidx.lifecycle.ViewModel import com.mwaibanda.momentum.domain.controller.EventController import com.mwaibanda.momentum.domain.models.GroupedEvent import com.mwaibanda.momentum.utils.Result class EventViewModel( private val eventController: EventController ): ViewModel() { fun getEvents(onCompletion: (List<GroupedEvent>) -> Unit) { eventController.getAllEvents { when (it) { is Result.Failure -> { Log.e("MealViewModel[getAllMeals]", it.message ?: "" ) } is Result.Success -> { onCompletion(it.data ?: emptyList()) } } } } }
0
Kotlin
4
31
ec6b7b552a8c07bf71a65b8c84218ed109e4b938
776
Momentum
MIT License
app/src/main/java/com/rskopyl/shake/ui/screen/discover/DiscoverViewModel.kt
rskopyl
626,140,252
false
null
package com.rskopyl.shake.ui.screen.discover import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.rskopyl.shake.data.model.CocktailFilter import com.rskopyl.shake.data.model.CocktailOverview import com.rskopyl.shake.repository.CocktailOverviewRepository import com.rskopyl.shake.util.Resource import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class DiscoverViewModel @Inject constructor( private val cocktailOverviewRepository: CocktailOverviewRepository ) : ViewModel() { private val _cocktailName = MutableStateFlow("") private val _cocktailFilters = MutableStateFlow( listOf( CocktailFilter(CocktailFilter.Purpose.CATEGORY), CocktailFilter(CocktailFilter.Purpose.INGREDIENT), CocktailFilter(CocktailFilter.Purpose.ALCOHOL), CocktailFilter(CocktailFilter.Purpose.GLASS) ) ) private val _cocktailOverviews = MutableStateFlow<Resource<List<CocktailOverview>>>(Resource.Loading()) val cocktailName: StateFlow<String> get() = _cocktailName.asStateFlow() val cocktailFilters: StateFlow<List<CocktailFilter>> get() = _cocktailFilters.asStateFlow() val cocktailOverviews: StateFlow<Resource<List<CocktailOverview>>> get() = _cocktailOverviews.asStateFlow() init { search() } fun changeCocktailName(name: String) { _cocktailName.value = name if (name.isEmpty()) search() } fun applyCocktailFilter(filter: CocktailFilter) { _cocktailFilters.update { filters -> filters .map { if (it.purpose == filter.purpose) filter else it.copy(pattern = null) } .sortedByDescending { it.pattern != null } } search() } fun clearCocktailFilter(filter: CocktailFilter) { _cocktailFilters.update { filters -> filters .map { if (it == filter) it.copy(pattern = null) else it } .sortedByDescending { it.pattern != null } } search() } fun search() { viewModelScope.launch(Dispatchers.IO) { cocktailOverviewRepository .getByNameAndFilter( name = _cocktailName.value, filter = _cocktailFilters.value .singleOrNull { it.pattern != null } ) .collectLatest { overviews -> _cocktailOverviews.value = overviews } } } }
0
Kotlin
0
0
e825ddcef13202477104dcecd13b9a26fc680e4a
2,794
Shake
MIT License
foryouandme/src/main/java/com/foryouandme/data/datasource/analytics/AnalyticsFirebaseDataSource.kt
4youandme
308,387,557
false
null
package com.foryouandme.data.datasource.analytics import com.foryouandme.domain.usecase.analytics.AnalyticsEvent import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.logEvent import javax.inject.Inject class AnalyticsFirebaseDataSource @Inject constructor( private val firebaseAnalytics: FirebaseAnalytics, private val firebaseDataMapper: FirebaseDataMapper ) { fun sendEvent(event: AnalyticsEvent) { when (event) { is AnalyticsEvent.ScreenViewed -> firebaseAnalytics .logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) { param(FirebaseAnalytics.Param.SCREEN_NAME, event.eventName) } else -> firebaseAnalytics.logEvent(event.eventName, firebaseDataMapper.map(event)) } } fun setUserId(id: String) { firebaseAnalytics.setUserId(id) } }
0
Kotlin
0
0
5a57ba15c408638a3cfea8084f609293a1defdc6
948
4YouandmeAndroid
MIT License
packages/mongodb-access-adapter/datagrip-access-adapter/src/main/kotlin/com/mongodb/jbplugin/accessadapter/datagrip/adapter/DataGripMongoDbDriver.kt
mongodb-js
797,134,624
false
{"Kotlin": 51646, "Shell": 1686, "Java": 765}
/** * Represents a MongoDB driver interface that uses a DataGrip * connection to query MongoDB. */ package com.mongodb.jbplugin.accessadapter.datagrip.adapter import com.google.gson.Gson import com.intellij.database.dataSource.DatabaseConnection import com.intellij.database.dataSource.DatabaseConnectionManager import com.intellij.database.dataSource.LocalDataSource import com.intellij.database.dataSource.connection.ConnectionRequestor import com.intellij.database.run.ConsoleRunConfiguration import com.intellij.openapi.project.Project import com.mongodb.jbplugin.accessadapter.MongoDbDriver import com.mongodb.jbplugin.accessadapter.Namespace import org.bson.Document import kotlin.reflect.KClass import kotlin.time.Duration import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout /** * The driver itself. Shouldn't be used directly, but through the * DataGripBasedReadModelProvider. * * @see com.mongodb.jbplugin.accessadapter.datagrip.DataGripBasedReadModelProvider * * @param project * @param dataSource */ internal class DataGripMongoDbDriver( private val project: Project, private val dataSource: LocalDataSource ) : MongoDbDriver { private val gson = Gson() override suspend fun <T : Any> runCommand( command: Document, result: KClass<T>, timeout: Duration ): T = withContext( Dispatchers.IO ) { runQuery( """db.runCommand(${command.toJson()})""", result, timeout )[0] } override suspend fun <T : Any> findOne( namespace: Namespace, query: Document, options: Document, result: KClass<T>, timeout: Duration ): T? = withContext(Dispatchers.IO) { runQuery( """db.getSiblingDB("${namespace.database}") .getCollection("${namespace.collection}") .findOne(${query.toJson()}, ${options.toJson()}) """.trimMargin(), result, timeout ).getOrNull(0) } override suspend fun <T : Any> findAll( namespace: Namespace, query: Document, result: KClass<T>, limit: Int, timeout: Duration ) = withContext(Dispatchers.IO) { runQuery( """db.getSiblingDB("${namespace.database}") .getCollection("${namespace.collection}") .find(${query.toJson()}).limit($limit) """.trimMargin(), result, timeout ) } suspend fun <T : Any> runQuery( queryString: String, resultClass: KClass<T>, timeout: Duration ): List<T> = withContext(Dispatchers.IO) { val connection = getConnection() val remoteConnection = connection.remoteConnection val statement = remoteConnection.prepareStatement(queryString.trimIndent()) withTimeout(timeout) { val listOfResults = mutableListOf<T>() val resultSet = statement.executeQuery() if (resultClass.java.isPrimitive || resultClass == String::class.java) { while (resultSet.next()) { listOfResults.add(resultSet.getObject(1) as T) } } else { while (resultSet.next()) { val hashMap = resultSet.getObject(1) as Map<String, Any> val result = gson.fromJson(gson.toJson(hashMap), resultClass.java) listOfResults.add(result) } } listOfResults } } private suspend fun getConnection(): DatabaseConnection { val connections = DatabaseConnectionManager.getInstance().activeConnections return connections.firstOrNull { it.connectionPoint.dataSource == dataSource } ?: DatabaseConnectionManager.establishConnection( dataSource, ConsoleRunConfiguration.newConfiguration(project).apply { setOptionsFromDataSource(dataSource) }, ConnectionRequestor.Anonymous(), project, true // if password is not available )!! } }
0
Kotlin
0
3
d5318666de5721c966a8e896079d95e3d3854617
4,316
intellij
Apache License 2.0
src/main/kotlin/no/nav/syfo/environment/DbEnv.kt
navikt
650,618,614
false
null
package no.nav.syfo.application.environment data class DbEnv( var dbHost: String, var dbPort: String, var dbName: String, val dbUsername: String = "", val dbPassword: String = "", )
9
Kotlin
0
0
a598fc4a58ce17a0d3d2b4486155f41f0e870fae
223
lps-oppfolgingsplan-mottak
MIT License
lib_cameraxqrcode/src/main/java/com/yh/cxqr/camerax/QRCodeAnalyzer.kt
CListery
442,337,819
false
null
package com.yh.cxqr.camerax import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import com.yh.cxqr.QRCodeParser import com.yh.cxqr.model.Barcode import kotlin.time.ExperimentalTime internal class QRCodeAnalyzer(private val resultHandler: (barcode: Barcode?, nextBlock: () -> Unit) -> Unit) : ImageAnalysis.Analyzer { private val parser by lazy { QRCodeParser() } @ExperimentalTime @androidx.camera.core.ExperimentalGetImage override fun analyze(imageProxy: ImageProxy) { parser.decodeImageProxyWithTimed(imageProxy, success = { resultHandler.invoke(it, imageProxy::close) }, fail = { imageProxy.close() }) } }
0
Kotlin
0
0
e3d8f689beb639d0d714e094cc246d9fa1de29c0
714
CameraX-QRcode
MIT License
core/ui/common/src/main/kotlin/com/flixclusive/core/ui/common/navigation/StartHomeScreenAction.kt
flixclusiveorg
659,237,375
false
{"Kotlin": 1904772, "Java": 18011}
package com.flixclusive.core.ui.common.navigation interface StartHomeScreenAction : GoBackAction { fun openHomeScreen() }
26
Kotlin
29
362
f488f6d1b2de3ec0737a8437ce1c981bc2f55c31
126
Flixclusive
MIT License
src/test/kotlin/me/carltonwhitehead/tornadofx/junit5/SimpleTestView.kt
carltonwhitehead
191,853,704
false
null
package me.carltonwhitehead.tornadofx.junit5 import javafx.scene.text.Text import tornadofx.* import tornadofx.View class SimpleTestView : View() { init { title = SimpleTestView::class.simpleName!! } override val root = vbox { text(titleProperty) { id = "title-text" } } val titleText: Text get() = root.lookup("#title-text") as Text }
0
Kotlin
0
3
8407ebd6ac96b973df0cd0d89eb5bd1ed026ebae
404
tornadofx-junit5
Apache License 2.0
app/src/main/java/com/anggitprayogo/movon/di/component/AppComponent.kt
anggit97
294,907,791
false
null
package com.anggitprayogo.movon.di.component import android.content.Context import com.anggitprayogo.movon.di.module.AppModule import com.anggitprayogo.movon.di.module.ViewModelModule import com.anggitprayogo.movon.feature.detail.MovieDetailActivity import com.anggitprayogo.movon.feature.favourite.FavouriteActivity import com.anggitprayogo.movon.feature.favouritedetail.FavouriteDetailActivity import com.anggitprayogo.movon.feature.main.MainActivity import dagger.BindsInstance import dagger.Component import javax.inject.Singleton /** * Created by <NAME> on 12,September,2020 * GitHub : https://github.com/anggit97 */ @Singleton @Component( modules = [ AppModule::class, ViewModelModule::class ] ) interface AppComponent { @Component.Factory interface Factory { fun create(@BindsInstance context: Context): AppComponent } fun inject(activity: MainActivity) fun inject(activity: MovieDetailActivity) fun inject(activity: FavouriteActivity) fun inject(activity: FavouriteDetailActivity) }
0
Kotlin
0
0
d0b11392329dc2215e37907c9521d95f4039885f
1,061
MovOn
MIT License
bootstrap-icons-compose/src/main/java/com/wiryadev/bootstrapiconscompose/bootstrapicons/normal/LayoutSidebarInset.kt
wiryadev
380,639,096
false
null
package com.wiryadev.bootstrapiconscompose.bootstrapicons.normal import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.wiryadev.bootstrapiconscompose.bootstrapicons.NormalGroup public val NormalGroup.LayoutSidebarInset: ImageVector get() { if (_layoutSidebarInset != null) { return _layoutSidebarInset!! } _layoutSidebarInset = Builder(name = "LayoutSidebarInset", defaultWidth = 16.0.dp, defaultHeight = 16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.0f, 2.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f) verticalLineToRelative(10.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f) horizontalLineTo(2.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f) verticalLineTo(3.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f) horizontalLineToRelative(12.0f) close() moveTo(2.0f, 1.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, false, -2.0f, 2.0f) verticalLineToRelative(10.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.0f, 2.0f) horizontalLineToRelative(12.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.0f, -2.0f) verticalLineTo(3.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, false, -2.0f, -2.0f) horizontalLineTo(2.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 4.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f) horizontalLineToRelative(2.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f) verticalLineToRelative(8.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f) horizontalLineTo(4.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f) verticalLineTo(4.0f) close() } } .build() return _layoutSidebarInset!! } private var _layoutSidebarInset: ImageVector? = null
0
Kotlin
0
2
1c199d953dc96b261aab16ac230dc7f01fb14a53
3,297
bootstrap-icons-compose
MIT License
reduks/src/main/kotlin/com/beyondeye/reduks/modules/MultiStoreSubscription.kt
Judrummer
69,236,028
true
{"Kotlin": 228257, "Java": 74455}
package com.beyondeye.reduks.modules import com.beyondeye.reduks.IStoreSubscription class MultiStoreSubscription(vararg subscriptions_: IStoreSubscription) : IStoreSubscription { val subscriptions=subscriptions_ override fun unsubscribe() { subscriptions.forEach { it.unsubscribe() } } }
0
Kotlin
0
0
ad522775e9ce2f88bfaa0b695dd677449eef6a76
309
Reduks
Apache License 2.0
src/main/kotlin/leetcode/Problem2176.kt
fredyw
28,460,187
false
null
package leetcode /** * https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array/ */ class Problem2176 { fun countPairs(nums: IntArray, k: Int): Int { val map = mutableMapOf<Int, MutableList<Int>>() for (i in nums.indices) { val list = map[nums[i]] ?: mutableListOf() list += i map[nums[i]] = list } var answer = 0 for (indexes in map.values) { for (i in 0 until indexes.size) { for (j in i + 1 until indexes.size) { if ((indexes[i] * indexes[j]) % k == 0) { answer++ } } } } return answer } }
1
null
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
726
leetcode
MIT License
plugin-bazel-event-service/src/main/kotlin/bazel/bazel/events/BuildMetrics.kt
JetBrains
143,697,750
false
null
package bazel.bazel.events data class BuildMetrics( override val id: Id, override val children: List<Id>, val actionsCreated: Long, val usedHeapSizePostBuild: Long) : BazelContent
6
null
7
14
6ff893ae8c3e6a8260568698d28df16b915593a6
214
teamcity-bazel-plugin
Apache License 2.0
app/src/main/java/com/klim/koinsample/data/repository/post/PostDTO.kt
makstron
349,967,030
false
null
package com.klim.koinsample.data.repository.post class PostDTO( var id: Int, var userId: Int, var title: String, var body: String, )
0
Kotlin
0
0
86493f318e76f0f9a3d177f66fcb57937aafe934
149
KoinSample
Apache License 2.0
router/react/core/src/main/kotlin/captain/HooksParams.kt
aSoft-Ltd
635,681,621
false
null
@file:JsExport @file:Suppress("UNUSED_PARAMETER", "NON_EXPORTABLE_TYPE", "NOTHING_TO_INLINE") package captain import js.core.Record import js.core.jso import kase.Optional import kase.optionalOf import kollections.Map import kollections.mapOf import kollections.component1 import kollections.component2 import kollections.component3 import kollections.component4 import kollections.component5 import kollections.component6 import kollections.entries import kollections.iterator import kollections.toList import kollections.values external interface Params : Record<String, String> { var all: Map<String, String> } inline fun useOptionalParam(key: String): Optional<String> = optionalOf(useRouteInfo()).flatMap { it.match.param(key) } inline fun useParam(key: String): String = useOptionalParam(key).getOrThrow() fun useParams(): Params { val ri = useRouteInfo() val params = ri?.match?.params ?: mapOf() val pb = jso<Params>() pb.all = params for ((key, value) in params.entries) pb[key] = value return pb } fun <T : Params> useParamsOf(): T = useParams().unsafeCast<T>() inline operator fun Params.component1(): String = all.values.toList().component1() inline operator fun Params.component2(): String = all.values.toList().component2() inline operator fun Params.component3(): String = all.values.toList().component3() inline operator fun Params.component4(): String = all.values.toList().component4() inline operator fun Params.component5(): String = all.values.toList().component5() inline operator fun Params.component6(): String = all.values.toList().component6()
1
null
1
9
15ba4dcd9841d493c96ab2d5058afa9cbbca4e29
1,605
captain
MIT License
app/src/main/java/com/tsu/firstlab/database/Meaning.kt
astyd256
609,680,319
false
null
package com.tsu.firstlab.database import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Meaning( @PrimaryKey(autoGenerate = true) val id: Int, val definition: String, val example: String, val word: String )
0
Kotlin
0
0
ef4281bcec96d5fa7bff489c889e3789d5e92dcd
249
English-Vocabulary-Android-App
MIT License
app/src/main/java/com/breezefsmparas/features/report/model/MISResponse.kt
DebashisINT
646,827,078
false
{"Kotlin": 15132793, "Java": 1023856}
package com.breezefsmparas.features.report.model import com.breezefsmparas.base.BaseResponse import com.breezefsmparas.features.nearbyshops.model.ShopData /** * Created by Pratishruti on 27-12-2017. */ class MISResponse:BaseResponse() { var shop_list:List<ShopData>? = null var shop_list_count:MISShopListCount?=null }
0
Kotlin
0
0
b3a654585537264aaec676ba124110e998983033
330
ParasPanMasala
Apache License 2.0
lib/src/commonTest/kotlin/io.telereso.kmp.core/SettingsTest.kt
telereso
590,271,736
false
{"Kotlin": 525497, "Swift": 66730, "JavaScript": 5405, "Java": 5190, "HTML": 2358, "CSS": 2092, "Shell": 1365, "Ruby": 188, "Makefile": 36}
/* * MIT License * * Copyright (c) 2023 Telereso * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.telereso.kmp.core import kotlinx.coroutines.test.runTest import io.kotest.matchers.booleans.shouldBeFalse import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.collections.shouldContain import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.datetime.Instant import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.time.DurationUnit import kotlin.time.toDuration import app.cash.turbine.test import kotlinx.coroutines.ExperimentalCoroutinesApi @OptIn(ExperimentalCoroutinesApi::class) class SettingsTest { var testDispatcher = UnconfinedTestDispatcher() private lateinit var settings: Settings @BeforeTest fun before() { settings = SettingsImpl(com.russhwolf.settings.MapSettings()) } @Test fun shouldClearAllSettings() { settings.putString("STRINGKEY", "CLEARME") settings.putInt("INTKEY", 8) settings.clear() settings.get<String>("STRINGKEY").shouldBeNull() settings.get<Int>("STRINGKEY").shouldBeNull() } @Test fun shouldReturnCorrectSizeSettings() { settings.putString("STRINGKEY", "CLEARME") settings.putInt("INTKEY", 8) settings.size.shouldBe(2) } @Test fun shouldReturnCorrectKeysSettings() { settings.putString("STRINGKEY", "CLEARME") settings.putInt("INTKEY", 8) settings.keys.also { it.shouldContain("INTKEY") it.shouldContain("STRINGKEY") } } @Test fun shouldRemoveCorrectValue() { settings.putString("STRINGKEY", "CLEARME") settings.putInt("INTKEY", 8) settings.remove("STRINGKEY") settings.get<String>("STRINGKEY").shouldBeNull() } @Test fun shouldPutEnGetString() { settings.putString("STRINGKEY", "SOMESTRING") settings.getString("STRINGKEY","DEFAULT").shouldBe("SOMESTRING") settings.getStringOrNull("4543354FF").shouldBeNull() // should get default value settings.getString("STRINGDEF","DEFAULT").shouldBe("DEFAULT") } @Test fun shouldPutEnGetInt() { settings.putInt("INTKEY", 666) settings.getInt("INTKEY",0).shouldBe(666) settings.getIntOrNull("FFJJGf").shouldBeNull() // should get default value settings.getInt("INTDEF",0).shouldBe(0) } @Test fun shouldPutEnGetLong() { settings.putLong("LONGKEY", 99L) settings.getLong("LONGKEY",0L).shouldBe(99L) settings.getLongOrNull("UT5554").shouldBeNull() // should get default value settings.getLong("INTDEF",0L).shouldBe(0L) } @Test fun shouldPutEnGetFloat() { settings.putFloat("FLOATKEY", 60F) settings.getFloat("FLOATKEY",0F).shouldBe(60F) settings.getFloatOrNull("TOEOEOE").shouldBeNull() // should get default value settings.getFloat("INTDEF",0F).shouldBe(0F) } @Test fun shouldPutEnGetDouble() { settings.putDouble("DOUBLEKEY", 100000.99) settings.getDouble("DOUBLEKEY",0.0).shouldBe(100000.99) settings.getDoubleOrNull("DFFDS").shouldBeNull() // should get default value settings.getDouble("INTDEF",100.0).shouldBe(100.0) } @Test fun shouldPutEnGetBoolean() { settings.putBoolean("BOOLEANKEY", false) settings.getBoolean("BOOLEANKEY",false).shouldBeFalse() settings.putBoolean("BOOLEANKEY", true) settings.getBoolean("BOOLEANKEY",false).shouldBeTrue() settings.getBooleanOrNull("FNFNFNF").shouldBeNull() // should get default value settings.getBoolean("INTDEF",true).shouldBeTrue() } @Test fun hasKeyShouldReturn() { settings.hasKey("LONGKEY").shouldBeFalse() settings.putBoolean("BAKABOOL", true) settings.hasKey("BAKABOOL").shouldBeTrue() } @Test fun shouldListenGivenInt() { settings.putBoolean("BAKABOOL", true) settings.hasKey("BAKABOOL").shouldBeTrue() } @Test fun expirableString() { val now = 1671086104L Utils.unitTestInstance = Instant.fromEpochSeconds(now) // Expired settings.putExpirableString("TEST","test",now - 1) settings.getStringOrNull("TEST").shouldNotBeNull() settings.getExpirableString("TEST").shouldBeNull() // make sure it's cleaned too settings.getStringOrNull("TEST").shouldBeNull() // Expired with default settings.putExpirableString("TEST","test",now - 1) settings.getStringOrNull("TEST").shouldNotBeNull() settings.getExpirableString("TEST","test2").shouldBe("test2") // make sure it's cleaned too settings.getStringOrNull("TEST").shouldBeNull() // valid settings.putExpirableString("TEST","test",now + 1000) settings.getStringOrNull("TEST").shouldNotBeNull() settings.getExpirableString("TEST").shouldBe("test") settings.getStringOrNull("TEST").shouldNotBeNull() // valid with default settings.putExpirableString("TEST","test",now + 1000) settings.getStringOrNull("TEST").shouldNotBeNull() settings.getExpirableString("TEST","test2").shouldBe("test") settings.getStringOrNull("TEST").shouldNotBeNull() } @Test fun testClearExpiredKeys() = runTest(testDispatcher) { val now = 1671086104L Utils.unitTestInstance = Instant.fromEpochSeconds(now) settings = SettingsImpl(com.russhwolf.settings.MapSettings(), 1.toDuration(DurationUnit.SECONDS)) val onRemoveExpiredKeysFlow = MutableSharedFlow<Int?>(replay = 0) val afterRemoveExpired = async { onRemoveExpiredKeysFlow.first() } settings.listener = object :Settings.Listener{ override fun deactivate() { } override fun onRemoveExpiredKeys() { launch { onRemoveExpiredKeysFlow.emit(settings.size) } } } settings.putExpirableString("TEST", "test", now - 1) settings.size.shouldBe(1) delay(100) afterRemoveExpired.await().shouldBe(0) settings.cancelRemovingExpiredKeys() } @Test fun testNotClearExpiredKeys() = runTest(testDispatcher) { val now = 1671086104L Utils.unitTestInstance = Instant.fromEpochSeconds(now) val onRemoveExpiredKeysFlow = MutableSharedFlow<Int?>(replay = 0) val afterRemoveExpired = async { withTimeoutOrNull(2000){ onRemoveExpiredKeysFlow.first() } } settings.listener = object :Settings.Listener{ override fun deactivate() { } override fun onRemoveExpiredKeys() { launch { onRemoveExpiredKeysFlow.emit(settings.size) } } } settings.putExpirableString("TEST", "test", now - 1) settings.size.shouldBe(1) afterRemoveExpired.await().shouldBe(null) settings.cancelRemovingExpiredKeys() } @Test fun shouldPutEnGetStringFlow() = runTest { settings.putString("STRING_KEY_FLOW", "SOMESTRINGFLOW") settings.getStringFlow("STRING_KEY_FLOW","DEFAULT").test { awaitItem().shouldBe("SOMESTRINGFLOW") } // should return null value given key not found settings.getStringFlow("12345").test { awaitItem().shouldBeNull() } // should get default value settings.getStringFlow("888","DEFAULT").test { awaitItem().shouldBe("DEFAULT") } } @Test fun shouldPutEnGetLongFlow() = runTest { settings.putLong("LONGKEY_FLOW", 66L) settings.getLongFlow("LONGKEY_FLOW",0L).test { awaitItem().shouldBe(66L) } // should return null value given key not found settings.getLongFlow("UT5554").test { awaitItem().shouldBeNull() } // should get default value settings.getLongFlow("INTDEF",2L).test { awaitItem().shouldBe(2L) } } @Test fun shouldPutEnGetFloatFlow() = runTest { settings.putFloat("FLOATKEY_FLOW", 60F) settings.getFloatFlow("FLOATKEY_FLOW",0F).test { awaitItem().shouldBe(60F) } // should return null value given key not found settings.getFloatFlow("TOEOEOE").test { awaitItem().shouldBeNull() } // should get default value settings.getFloatFlow("INTDEF",0F).test { awaitItem().shouldBe(0F) } } @Test fun shouldPutEnGetDoubleFlow() = runTest { settings.putDouble("DOUBLEKEY_FLOW", 100000.99) settings.getDoubleFlow("DOUBLEKEY_FLOW",0.0).test { awaitItem().shouldBe(100000.99) } // should return null value given key not found settings.getDoubleFlow("DFFDS").test { awaitItem().shouldBeNull() } // should get default value settings.getDoubleFlow("INTDEF",100.0).test { awaitItem().shouldBe(100.0) } } @Test fun shouldPutEnGetBooleanFlow() = runTest { settings.putBoolean("BOOLEANKEY_FLOW", false) settings.getBooleanFlow("BOOLEANKEY_FLOW",false).test { awaitItem().shouldBeFalse() } // should return null value given key not found settings.getBooleanFlow("FNFNFNF").test { awaitItem().shouldBeNull() } // should get default value settings.getBooleanFlow("INTDEF",true).test { awaitItem().shouldBeTrue() } } @Test fun shouldPutEnGetIntFlow() = runTest { settings.putInt("INTKEY_FLOW", 666) settings.getIntFlow("INTKEY_FLOW",0).test { awaitItem().shouldBe(666) } // should return null value given key not found settings.getIntFlow("FFJJGf").test { awaitItem().shouldBeNull() } // should get default value settings.getIntFlow("INTDEF",0).test { awaitItem().shouldBe(0) } } }
2
Kotlin
0
4
f125bb94b3a345e1be33ce94666cc6f3a3f5524a
11,564
kmp-core
MIT License
kautomator/src/main/kotlin/com/kaspersky/components/kautomator/intercept/exception/UnfoundedUiObjectException.kt
KasperskyLab
208,070,025
false
{"Kotlin": 736940, "Shell": 1880, "Makefile": 387}
package com.kaspersky.components.kautomator.intercept.exception import com.kaspersky.components.kautomator.component.common.builders.UiViewSelector /** * The exception is thrown in case if UiObject2 is not found on the screen */ class UnfoundedUiObjectException(selector: UiViewSelector) : RuntimeException("The UiObject2 was not found on the screen. " + "The selector=${selector.bySelector}, index=${selector.index}")
55
Kotlin
150
1,784
9c94128c744d640dcd646b86de711d2a1b9c3aa1
435
Kaspresso
Apache License 2.0
app/src/main/java/me/ykrank/s1next/view/event/EditAppPostEvent.kt
ykrank
52,680,091
false
{"Kotlin": 850930, "Java": 727444, "HTML": 20430}
package me.ykrank.s1next.view.event import me.ykrank.s1next.data.api.app.model.AppPost import me.ykrank.s1next.data.api.app.model.AppThread data class EditAppPostEvent(val post: AppPost, val thread: AppThread)
1
Kotlin
37
317
0c0b0fdb992db9b046265ee6e9b50ac676a1c104
212
S1-Next
Apache License 2.0
decorator/src/main/kotlin/io/kommons/designpatterns/decorator/Troll.kt
debop
235,066,649
false
null
package io.kommons.designpatterns.decorator /** * Troll */ interface Troll { fun attach() fun getAttackPower(): Int fun fleeBattle() }
0
Kotlin
11
53
c00bcc0542985bbcfc4652d0045f31e5c1304a70
152
kotlin-design-patterns
Apache License 2.0
gateway/src/test/kotlin/com/mdelbel/poc/paging/pagekeyed/gateway/moviedb/di/TestCoroutineContextProvider.kt
matiasdelbel
201,551,242
false
null
package com.mdelbel.poc.paging.pagekeyed.gateway.moviedb.di import com.mdelbel.poc.paging.pagekeyed.gateway.di.CoroutineContextProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlin.coroutines.CoroutineContext class TestCoroutineContextProvider : CoroutineContextProvider() { @ExperimentalCoroutinesApi override val Main: CoroutineContext = Dispatchers.Unconfined @ExperimentalCoroutinesApi override val IO: CoroutineContext = Dispatchers.Unconfined }
0
Kotlin
0
0
03951d68787220daee3446c3a22e78b3c9204358
529
android-poc-paging-page-keyed
Apache License 2.0
analyzer/src/main/kotlin/YamlFilePackageCurationProvider.kt
enterstudio
151,004,023
true
{"Kotlin": 489933, "Shell": 1064}
/* * Copyright (C) 2017-2018 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package com.here.ort.analyzer import com.here.ort.model.Identifier import com.here.ort.model.PackageCuration import com.here.ort.model.yamlMapper import java.io.File /** * A [PackageCurationProvider] that loads [PackageCuration]s from a single YAML file. */ class YamlFilePackageCurationProvider( curationFile: File ) : PackageCurationProvider { internal val packageCurations: List<PackageCuration> by lazy { val valueType = yamlMapper.typeFactory.constructCollectionType(List::class.java, PackageCuration::class.java) yamlMapper.readValue(curationFile, valueType) as List<PackageCuration> } override fun getCurationsFor(identifier: Identifier) = packageCurations.filter { it.id.matches(identifier) } }
0
Kotlin
1
0
a9a1dad964e8a1b1a3637a386f05d34131fac9ef
1,426
oss-review-toolkit
Apache License 2.0
feature-governance-impl/src/main/java/io/novafoundation/nova/feature_governance_impl/domain/referendum/details/call/treasury/TreasurySpendAdapter.kt
novasamatech
415,834,480
false
null
package io.novafoundation.nova.feature_governance_impl.domain.referendum.details.call.treasury import io.novafoundation.nova.common.data.network.runtime.binding.bindAccountIdentifier import io.novafoundation.nova.common.data.network.runtime.binding.bindNonce import io.novafoundation.nova.common.utils.Modules import io.novafoundation.nova.common.utils.instanceOf import io.novafoundation.nova.feature_governance_api.domain.referendum.details.ReferendumCall import io.novafoundation.nova.feature_governance_impl.domain.referendum.details.call.ReferendumCallAdapter import io.novafoundation.nova.feature_governance_impl.domain.referendum.details.call.ReferendumCallParseContext import jp.co.soramitsu.fearless_utils.runtime.definitions.types.generics.GenericCall class TreasurySpendAdapter : ReferendumCallAdapter { override suspend fun fromCall( call: GenericCall.Instance, context: ReferendumCallParseContext ): ReferendumCall? { // TODO: spend call is using MultiLocation now instead of MultiAddress so binding throws an exception if (!call.instanceOf(Modules.TREASURY, "spend_local", "spend")) return null val amount = bindNonce(call.arguments["amount"]) val beneficiary = bindAccountIdentifier(call.arguments["beneficiary"]) return ReferendumCall.TreasuryRequest(amount, beneficiary) } }
14
null
6
9
404bd5141bf0e1bc4d09cae42d6ea9fa50d78975
1,365
nova-wallet-android
Apache License 2.0
app/src/main/java/hu/kristof/nagy/hikebookclient/view/mymap/MyMapListAdapter.kt
Kristof1999
464,363,767
false
{"Kotlin": 405541}
/* * Copyright 2019, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ // based on: // https://github.com/google-developer-training/android-kotlin-fundamentals-apps/tree/master/RecyclerViewFundamentals // https://github.com/android/sunflower // https://github.com/google-developer-training/android-kotlin-fundamentals-apps/tree/master/RecyclerViewClickHandler package hu.kristof.nagy.hikebookclient.view.mymap import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import hu.kristof.nagy.hikebookclient.databinding.MyMapListItemBinding class MyMapListAdapter(private val clickListener: MyMapClickListener) : ListAdapter<String, MyMapListAdapter.ViewHolder>(MyMapListDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder.from(parent, clickListener) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val routeName = getItem(position) holder.bind(routeName) } class ViewHolder private constructor( private val binding : MyMapListItemBinding, private val clickListener: MyMapClickListener ) : RecyclerView.ViewHolder(binding.root) { fun bind(routeName: String) { binding.routeName = routeName binding.clickListener = clickListener binding.executePendingBindings() } companion object { fun from(parent: ViewGroup, clickListener: MyMapClickListener): ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val binding = MyMapListItemBinding.inflate(layoutInflater, parent, false) return ViewHolder(binding, clickListener) } } } } class MyMapListDiffCallback : DiffUtil.ItemCallback<String>() { override fun areItemsTheSame(oldItem: String, newItem: String): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: String, newItem: String): Boolean { return oldItem == newItem } } class MyMapClickListener( private val editListener: (routeName: String) -> Unit, private val deleteListener: (routeName: String) -> Unit, private val printListener: (routeName: String) -> Unit, private val detailNavListener: (routeName: String) -> Unit, private val hikePlanListener: (routeName: String) -> Unit, private val groupHikeCreateListener: (routeName: String) -> Unit ) { fun onEdit(routeName: String) = editListener(routeName) fun onDelete(routeName: String) = deleteListener(routeName) fun onPrint(routeName: String) = printListener(routeName) fun onDetailNav(routeName: String) = detailNavListener(routeName) fun onHikePlan(routeName: String) = hikePlanListener(routeName) fun onGroupHikeCreate(routeName: String) = groupHikeCreateListener(routeName) }
0
Kotlin
0
0
013501c897446b02c4b08d3d6922c2e0d6a9d902
4,157
HikeBookClient
Apache License 2.0
erc20/listener/src/test/kotlin/com/rarible/protocol/erc20/listener/integration/IntegrationTest.kt
NFTDroppr
418,665,809
true
{"Kotlin": 2329156, "Scala": 37343, "Shell": 6001, "HTML": 547}
package com.rarible.protocol.erc20.listener.integration import org.springframework.boot.test.autoconfigure.json.AutoConfigureJson import org.springframework.boot.test.context.SpringBootTest import org.springframework.context.annotation.Import import org.springframework.test.context.ActiveProfiles import org.testcontainers.junit.jupiter.Testcontainers @Retention @AutoConfigureJson @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK, properties = [ "application.environment = e2e", "listener.blockchain = ethereum", "rarible.blockchain.monitoring = ethereum", "spring.cloud.service-registry.auto-registration.enabled = false", "spring.cloud.discovery.enabled = false", "rarible.common.jms-brokerUrls = localhost:\${random.int(5000,5100)}", "rarible.common.jms-eventTopic = protocol", "spring.cloud.consul.config.enabled = false", "logging.logstash.tcp-socket.enabled = false" ] ) @ActiveProfiles("integration") @Import(TestPropertiesConfiguration::class) @Testcontainers annotation class IntegrationTest
0
Kotlin
0
1
b1efdaceab8be95429befe80ce1092fab3004d18
1,108
ethereum-indexer
MIT License
app/src/main/java/by/godevelopment/kingcalculator/presentation/playerpresentation/playeraddform/AddFormUserEvent.kt
aleh-god
458,515,512
false
{"Kotlin": 256219, "Java": 6183}
package by.godevelopment.kingcalculator.presentation.playerpresentation.playeraddform sealed interface AddFormUserEvent { data class RealNameChanged(val realName: String) : AddFormUserEvent data class PlayerNameChanged(val playerName: String) : AddFormUserEvent object PressSaveButton : AddFormUserEvent }
2
Kotlin
0
2
295cfb7970e2a488612f3b2ec65984eb5046a460
319
calculator-king
MIT License
voyager-hilt/src/main/java/cafe/adriel/voyager/hilt/ScreenModelFactoryKey.kt
adrielcafe
387,613,592
false
null
package cafe.adriel.voyager.hilt import dagger.MapKey import kotlin.reflect.KClass /** * A Dagger multibinding key used to identify a [ScreenModelFactory] */ @MustBeDocumented @Target( AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER ) @Retention(AnnotationRetention.RUNTIME) @MapKey public annotation class ScreenModelFactoryKey(val value: KClass<out ScreenModelFactory>)
31
Kotlin
39
945
d7932b28cf8c2545fcd52c3883467a648f9d2888
434
voyager
MIT License
src/en/koharu/src/eu/kanade/tachiyomi/extension/en/koharu/KoharuDto.kt
komikku-app
720,497,299
false
{"Kotlin": 6775539, "JavaScript": 2160}
package eu.kanade.tachiyomi.extension.en.koharu import kotlinx.serialization.Serializable @Serializable class Tag( var name: String, var namespace: Int = 0, ) @Serializable class Books( val entries: List<Entry> = emptyList(), val total: Int = 0, val limit: Int = 0, val page: Int, ) @Serializable class Entry( val id: Int, val public_key: String, val title: String, val thumbnail: Thumbnail, ) @Serializable class MangaEntry( val id: Int, val title: String, val public_key: String, val created_at: Long = 0L, val updated_at: Long?, val thumbnails: Thumbnails, val tags: List<Tag> = emptyList(), val data: Data, ) @Serializable class Thumbnails( val base: String, val main: Thumbnail, val entries: List<Thumbnail>, ) @Serializable class Thumbnail( val path: String, ) @Serializable class Data( val `0`: DataKey, val `780`: DataKey? = null, val `980`: DataKey? = null, val `1280`: DataKey? = null, val `1600`: DataKey? = null, ) @Serializable class DataKey( val id: Int? = null, val size: Double = 0.0, val public_key: String? = null, ) { fun readableSize() = when { size >= 300 * 1000 * 1000 -> "${"%.2f".format(size / (1000.0 * 1000.0 * 1000.0))} GB" size >= 100 * 1000 -> "${"%.2f".format(size / (1000.0 * 1000.0))} MB" size >= 1000 -> "${"%.2f".format(size / (1000.0))} kB" else -> "$size B" } } @Serializable class ImagesInfo( val base: String, val entries: List<ImagePath>, ) @Serializable class ImagePath( val path: String, )
22
Kotlin
8
97
7fc1d11ee314376fe0daa87755a7590a03bc11c0
1,614
komikku-extensions
Apache License 2.0
src/main/kotlin/com/github/mictaege/arete_gradle/JUnitExt.kt
mictaege
366,137,094
false
null
package com.github.mictaege.arete_gradle import org.junit.platform.engine.support.descriptor.ClassSource import org.junit.platform.engine.support.descriptor.MethodSource import org.junit.platform.launcher.TestIdentifier import java.lang.reflect.Method fun TestIdentifier.testClass(): Class<*>? { return when (val source = this.source.orElse(null)) { is ClassSource -> source.javaClass is MethodSource -> source.javaClass else -> null } } fun TestIdentifier.testMethod(): Method? { return when (val source = this.source.orElse(null)) { is MethodSource -> source.javaMethod else -> null } } fun TestIdentifier.isAnnotated(annotation: Class<out Annotation>): Boolean { return when (val source = this.source.orElse(null)) { is ClassSource -> source.javaClass.isAnnotationPresent(annotation) is MethodSource -> source.javaMethod.isAnnotationPresent(annotation) else -> false } }
0
Kotlin
0
0
413cd3f3e9c671e424e185d6fb6e3f51641b6c6d
966
arete-gradle
Apache License 2.0
src/main/kotlin/ru/stersh/bookcrawler/module/at/api/GalleryImage.kt
siper
720,533,744
false
{"Kotlin": 100005, "Dockerfile": 361}
package ru.stersh.bookcrawler.module.at.api import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class GalleryImage( @SerialName("caption") val caption: String?, @SerialName("height") val height: Int, @SerialName("id") val id: String, @SerialName("url") val url: String, @SerialName("width") val width: Int )
12
Kotlin
0
0
b20d197b68d1b501dc53f33cc62dff91af02f4ba
399
BookCrawler
MIT License
arrow-optics/src/test/kotlin/arrow/optics/data/ListInstancesTest.kt
alvarlaigna
118,357,376
true
{"Kotlin": 1355960, "CSS": 115796, "HTML": 9297, "JavaScript": 7275, "Java": 4423, "Shell": 3057}
package arrow.optics import io.kotlintest.KTestJUnitRunner import io.kotlintest.properties.Gen import arrow.typeclasses.Eq import arrow.test.laws.IsoLaws import arrow.core.OptionMonoidInstanceImplicits import arrow.data.ListKWMonoidInstanceImplicits import arrow.data.NonEmptyListSemigroupInstanceImplicits import arrow.data.k import arrow.test.laws.OptionalLaws import arrow.test.UnitSpec import arrow.test.generators.genFunctionAToB import arrow.test.generators.genNonEmptyList import arrow.test.generators.genOption import arrow.optics.instances.listHead import arrow.optics.instances.listTail import arrow.optics.instances.listToListKW import arrow.optics.instances.listToOptionNel import org.junit.runner.RunWith @RunWith(KTestJUnitRunner::class) class ListInstancesTest : UnitSpec() { init { testLaws( OptionalLaws.laws( optional = listHead(), aGen = Gen.list(Gen.int()), bGen = Gen.int(), funcGen = genFunctionAToB(Gen.int()), EQA = Eq.any(), EQB = Eq.any(), EQOptionB = Eq.any()), OptionalLaws.laws( optional = listTail(), aGen = Gen.list(Gen.int()), bGen = Gen.list(Gen.int()), funcGen = genFunctionAToB(Gen.list(Gen.int())), EQA = Eq.any(), EQB = Eq.any(), EQOptionB = Eq.any()), IsoLaws.laws( iso = listToOptionNel(), aGen = Gen.list(Gen.int()), bGen = genOption(genNonEmptyList(Gen.int())), funcGen = genFunctionAToB(genOption(genNonEmptyList(Gen.int()))), EQA = Eq.any(), EQB = Eq.any(), bMonoid = OptionMonoidInstanceImplicits.instance(NonEmptyListSemigroupInstanceImplicits.instance<Int>())), IsoLaws.laws( iso = listToListKW(), aGen = Gen.list(Gen.int()), bGen = Gen.create { Gen.list(Gen.int()).generate().k() }, funcGen = genFunctionAToB(Gen.create { Gen.list(Gen.int()).generate().k() }), EQA = Eq.any(), EQB = Eq.any(), bMonoid = ListKWMonoidInstanceImplicits.instance()) ) } }
0
Kotlin
0
0
d81270f65dc98d1b1e6d3217850a5a12768f4ce6
2,327
arrow
Apache License 2.0
src/main/kotlin/io/github/rhdunn/exposed/dao/EntityClass.kt
rhdunn
738,613,487
false
{"Kotlin": 17732, "CSS": 551}
// Copyright (C) 2024 <NAME>. SPDX-License-Identifier: Apache-2.0 package io.github.rhdunn.exposed.dao import org.jetbrains.exposed.dao.Entity import org.jetbrains.exposed.dao.EntityClass import org.jetbrains.exposed.exceptions.ExposedSQLException import org.jetbrains.exposed.sql.Op fun <ID : Comparable<ID>, T : Entity<ID>> EntityClass<ID, T>.findOrNew(op: Op<Boolean>, init: T.() -> Unit): T { return find(op).firstOrNull() ?: try { new(init) } catch (e: ExposedSQLException) { // The entity has been added between inserts, or this is a different error. find(op).firstOrNull() ?: throw e } }
0
Kotlin
0
0
ab507833bf5debac3d15ef4bc77ce74a17801db7
633
ktor-template
Apache License 2.0
core-frame/src/main/java/com/panyz/core_frame/http/interceptor/HttpInterceptor.kt
panyz
333,628,190
false
null
package com.panyz.core_frame.http.interceptor import com.panyz.core_frame.constant.HttpStatusCode import com.panyz.core_frame.http.exception.ConnectionException import com.panyz.core_frame.http.exception.ForbidenUrlException import com.panyz.core_frame.http.exception.HttpRequestException import okhttp3.Interceptor import okhttp3.Response class HttpInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val originalResponse: Response try { originalResponse = chain.proceed(request) } catch (e: Exception) { throw ConnectionException(HttpStatusCode.ERR_HTTP_CONNECTION) } if (originalResponse.code != HttpStatusCode.RESPONSE_SUCCESS) { if (originalResponse.code == HttpStatusCode.ERR_FORBIDDEN) { throw ForbidenUrlException(HttpStatusCode.ERR_FORBIDDEN) } throw HttpRequestException(HttpStatusCode.ERR_HTTP_REQUEST) } return originalResponse } }
0
Kotlin
0
0
5f382b9e6b64d7533af88cce928b1eb4cac44a21
1,064
GankIO
Apache License 2.0
platform/workspaceModel/ide/src/com/intellij/workspaceModel/ide/impl/jps/serialization/DelayedProjectSynchronizer.kt
eric730212
293,685,206
true
null
// Copyright 2000-2020 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 com.intellij.workspaceModel.ide.impl.jps.serialization import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.impl.WorkspaceModelImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeProjectLifecycleListener import kotlin.system.measureTimeMillis class DelayedProjectSynchronizer : StartupActivity { override fun runActivity(project: Project) { if (LegacyBridgeProjectLifecycleListener.enabled(project) && (WorkspaceModel.getInstance(project) as WorkspaceModelImpl).loadedFromCache) { val loadingTime = measureTimeMillis { JpsProjectModelSynchronizer.getInstance(project)?.loadRealProject(project) } log.info("Workspace model loaded from cache. Syncing real project state into workspace model in $loadingTime ms. ${Thread.currentThread()}") } } companion object { private val log = logger<DelayedProjectSynchronizer>() } }
0
null
0
0
16648e5689e213f02d4ed56b435fa508501b023b
1,228
intellij-community
Apache License 2.0
app/src/main/java/com/amachikhin/testapplication/data/model/WeatherModel.kt
shustreek
259,710,149
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 54, "XML": 26, "Java": 1}
package com.amachikhin.testapplication.data.model import com.google.gson.annotations.SerializedName data class WeatherModel( @SerializedName("id") val id: Int, @SerializedName("main") val main: String, @SerializedName("description") val description: String, @SerializedName("icon") val icon: String )
1
null
1
1
cd17c880561a88d0c77dd625ad699560a2e140ce
318
progress
Apache License 2.0
common/src/main/kotlin/org/valkyrienskies/mod/api/SeatedControllingPlayer.kt
AlphaMode
561,128,018
false
null
package org.valkyrienskies.mod.api import net.minecraft.core.Direction class SeatedControllingPlayer(val seatInDirection: Direction) { var forwardImpulse: Float = 0.0f var leftImpulse: Float = 0.0f var upImpulse: Float = 0.0f }
1
null
1
2
545394e1bcb200cecfd2a0d451610941e6d3d9d4
242
Valkyrien-Skies-2
Apache License 2.0
Lesson02-GitHub-Repo-Search/T02.03-Exercise-DisplayUrl/app/src/main/java/com/example/android/datafrominternet/utilities/NetworkUtils.kt
Stropek
103,762,850
false
null
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.datafrominternet.utilities import android.net.Uri import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.MalformedURLException import java.net.URI import java.net.URL import java.util.Scanner /** * These utilities will be used to communicate with the network. */ object NetworkUtils { internal val GITHUB_BASE_URL = "https://api.github.com/search/repositories" internal val PARAM_QUERY = "q" /* * The sort field. One of stars, forks, or updated. * Default: results are sorted by best match if no field is specified. */ internal val PARAM_SORT = "sort" internal val sortBy = "stars" /** * Builds the URL used to query Github. * * @param githubSearchQuery The keyword that will be queried for. * @return The URL to use to query the weather server. */ fun buildUrl(githubSearchQuery: String): URL? { var uri : Uri = Uri.parse(githubSearchQuery).buildUpon().build() var url : URL? = null try { url = URL(uri.toString()) } catch (e: MalformedURLException) { e.printStackTrace() } return url } /** * This method returns the entire result from the HTTP response. * * @param url The URL to fetch the HTTP response from. * @return The contents of the HTTP response. * @throws IOException Related to network and stream reading */ @Throws(IOException::class) fun getResponseFromHttpUrl(url: URL): String? { val urlConnection = url.openConnection() as HttpURLConnection try { val `in` = urlConnection.inputStream val scanner = Scanner(`in`) scanner.useDelimiter("\\A") val hasInput = scanner.hasNext() return if (hasInput) { scanner.next() } else { null } } finally { urlConnection.disconnect() } } }
1
null
1
1
feb1e04f77f7e08306e163887ed67fbbbbc270f4
2,646
ud851-Exercises
Apache License 2.0
http4k-testing/hamkrest/src/main/kotlin/org/http4k/filter/hamkrestExt.kt
http4k
86,003,479
false
{"Kotlin": 2855594, "Java": 41165, "HTML": 14220, "Shell": 3200, "Handlebars": 1455, "Pug": 944, "JavaScript": 777, "Dockerfile": 256, "CSS": 248}
package org.http4k.filter import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.assertion.assertThat import org.http4k.core.Filter import org.http4k.core.Request import org.http4k.core.Response /** * Perform an assertThat on the incoming Request as a Filter operation */ fun RequestFilters.Assert(matcher: Matcher<Request>) = Filter { next -> { next(it.also { assertThat(it, matcher) }) } } /** * Perform an assertThat on the outgoing Response as a Filter operation */ fun ResponseFilters.Assert(matcher: Matcher<Response>) = Filter { next -> { next(it).also { assertThat(it, matcher) } } }
34
Kotlin
249
2,615
7ad276aa9c48552a115a59178839477f34d486b1
642
http4k
Apache License 2.0
app/src/main/java/info/touchimage/demo/MirroringExampleActivity.kt
FDuhen
223,975,992
true
{"Gradle": 4, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 2, "Markdown": 1, "Java Properties": 1, "XML": 15, "Kotlin": 12, "Proguard": 1, "Java": 1}
package info.touchimage.demo import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_mirroring_example.* class MirroringExampleActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_mirroring_example) // // Each image has an OnTouchImageViewListener which uses its own TouchImageView // to set the other TIV with the same zoom variables. // topImage.setOnTouchImageViewListener { bottomImage.setZoom(topImage) } bottomImage.setOnTouchImageViewListener { topImage.setZoom(bottomImage) } } }
0
Java
0
1
46d098bdb5bdfbdf1d5d4597e76df9d6e45b84b8
729
TouchImageView
MIT License
TestAndroid/TestUnitarios/app/src/main/java/ec/com/paul/testunitarios/calculadora/Calculadora.kt
PaulMarcelo
255,495,694
false
null
package ec.com.paul.testunitarios.calculadora import java.lang.ArithmeticException /** * Created by <NAME> on 20/8/2019. * <NAME> */ class Calculadora { /* //METODO////////////////////////////////////////ESPECIFICACIOM////////////////////////////////////////////////////////////////////////////// int sumar( |Este método devuelve un int resultado de la suma de numero 1 y numero2 int numero1, | int numero2) | ------------------------------------------------------------------------------------------------------------------------ int restar( |Este método devuelve un int resultado de la resta de numero 1 y numero2 int numero1, | int numero2) | ------------------------------------------------------------------------------------------------------------------------ */ var resultado = 0 fun sumar(numero1: Int, numero2: Int): Int { resultado = numero1 + numero2 return resultado } fun restar(numero1: Int, numero2: Int): Int { resultado = numero1 - numero2 return resultado } fun dividir(numero1: Int, numero2: Int): Int { resultado = numero1 / numero2 return resultado } fun dividirPorCero(numero1: Int, numero2: Int): Int { if (numero2 == 0) { throw ArithmeticException("No se puede dividir por cero") } resultado = numero1 / numero2 return resultado } fun operacionLargaDuracion() { try { Thread.sleep(599) } catch (e: Exception) { //Does nothing } } }
0
Kotlin
0
0
5c363e7e5837eaec8c43c1edf6eafa69ab84725d
1,691
Android
Apache License 2.0
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/expressions/IrCall.kt
JakeWharton
99,388,807
true
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.ir.expressions import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.ir.symbols.IrClassSymbol import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol interface IrCall : IrFunctionAccessExpression { val superQualifier: ClassDescriptor? val superQualifierSymbol: IrClassSymbol? } interface IrCallWithShallowCopy : IrCall { fun shallowCopy(newOrigin: IrStatementOrigin?, newCallee: IrFunctionSymbol, newSuperQualifier: IrClassSymbol?): IrCall @Deprecated("Creates unbound symbols") fun shallowCopy(newOrigin: IrStatementOrigin?, newCallee: FunctionDescriptor, newSuperQualifier: ClassDescriptor?): IrCall }
0
Kotlin
4
83
4383335168338df9bbbe2a63cb213a68d0858104
1,349
kotlin
Apache License 2.0
src/main/kotlin/de/flapdoodle/io/resolve/commands/Intention.kt
flapdoodle-oss
231,620,257
false
{"Shell": 10, "Batchfile": 1, "Maven POM": 1, "Text": 2, "Ignore List": 1, "Markdown": 1, "INI": 1, "Java": 3, "XML": 1, "Kotlin": 269}
package de.flapdoodle.io.resolve.commands enum class Intention { UpdateDestination, UpdateSource }
1
null
1
1
2c39e73edb0d1eefd277c1e31d2ed7042cf62029
107
photosync
Apache License 2.0
compiler/testData/diagnostics/tests/functionLiterals/return/LocalReturnExplicitLabelParens.kt
staltz
38,581,975
true
{"Java": 15450397, "Kotlin": 8578737, "JavaScript": 176060, "HTML": 22810, "Lex": 17327, "Protocol Buffer": 13024, "ANTLR": 9689, "CSS": 9431, "Shell": 3931, "IDL": 3257, "Groovy": 3010, "Batchfile": 2831}
// !CHECK_TYPE fun test() { val x = run(f@{return@f 1}) checkSubtype<Int>(x) } fun test1() { val x = run(l@{return@l 1}) checkSubtype<Int>(x) } fun run<T>(f: () -> T): T { return f() }
0
Java
0
1
80074c71fa925a1c7173e3fffeea4cdc5872460f
204
kotlin
Apache License 2.0
kotlin/src/test/kotlin/io/github/konfigur8/ConfigurationTemplateTest.kt
daviddenton
30,429,565
false
null
package io.github.konfigur8 import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.junit.Test import kotlin.test.fail class ConfigurationTemplateTest { private val FOO = Property.string("FOO") @Test fun requiringPropsIsImmutable() { try { val originalConfig = ConfigurationTemplate().requiring(FOO) val updatedConfig = ConfigurationTemplate().withProp(FOO, "foo") assertThat(updatedConfig.reify().valueOf(FOO), equalTo("foo")) originalConfig.reify() fail("expected exception") } catch(e: Misconfiguration) { assertThat(e.message!!, equalTo("No value supplied for key 'FOO'")) } } @Test fun overridingPropsIsImmutable() { val originalConfig = ConfigurationTemplate().withProp(FOO, "foo") val updatedConfig = originalConfig.withProp(FOO, "bar") assertThat(originalConfig.reify().valueOf(FOO), equalTo("foo")) assertThat(updatedConfig.reify().valueOf(FOO), equalTo("bar")) } }
6
Scala
4
9
a556149fe8676dc07fff5bbf8647b9e7c2e8bf17
1,081
configur8
Apache License 2.0
src/main/kotlin/com/github/thepwagner/actionupdate/gradle/service/UpdateService.kt
thepwagner
341,193,418
false
{"Java": 3265, "Kotlin": 2757, "Dockerfile": 181}
package com.github.thepwagner.actionupdate.gradle.service import com.github.thepwagner.actionupdate.v1.rpc.RpcUpdateService import com.github.thepwagner.actionupdate.v1.rpc.Update.* import com.github.thepwagner.actionupdate.v1.rpc.Update.Dependency class UpdateService : RpcUpdateService { var dep: Dependency? = null override fun handleListDependencies(req: ListDependenciesRequest?): ListDependenciesResponse { val foo = Dependency.newBuilder() .setPath("foo") .setVersion("2.0.0") val bar = Dependency.newBuilder() .setPath("bar") .setVersion("2.0.0") return ListDependenciesResponse.newBuilder() .addDependencies(foo) .addDependencies(bar) .build() } }
1
null
1
1
663db818ce9c313fc174ff7c2c48bd2a7fce24af
779
action-update-twirp-gradle
MIT License
plugin-location/src/test/java/com/mapbox/maps/plugin/location/LocationComponentPositionManagerTest.kt
mohammadrezabk
355,219,500
true
{"Kotlin": 1837346, "Java": 163377, "C++": 10129, "Python": 9280, "JavaScript": 4344, "Shell": 1830, "Makefile": 1756, "CMake": 1201, "HTML": 1194}
package com.mapbox.maps.plugin.location import com.mapbox.maps.LayerPosition import com.mapbox.maps.StyleManagerInterface import com.mapbox.maps.plugin.delegates.MapStyleStateDelegate import io.mockk.mockk import io.mockk.verify import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class LocationComponentPositionManagerTest { private var style: StyleManagerInterface = mockk(relaxed = true) private var styleState: MapStyleStateDelegate = mockk(relaxed = true) private var layerWrapper: LocationLayerWrapper = mockk(relaxed = true) @Test fun update_noChange_null() { val positionManager = LocationComponentPositionManager(style, styleState, null, null) val requiresUpdate = positionManager.update(null, null) assertFalse(requiresUpdate) } @Test fun update_noChange_above() { val positionManager = LocationComponentPositionManager(style, styleState, "above", null) val requiresUpdate = positionManager.update("above", null) assertFalse(requiresUpdate) } @Test fun update_noChange_below() { val positionManager = LocationComponentPositionManager(style, styleState, null, "below") val requiresUpdate = positionManager.update(null, "below") assertFalse(requiresUpdate) } @Test fun update_fromNull_above() { val positionManager = LocationComponentPositionManager(style, styleState, null, null) val requiresUpdate = positionManager.update("above", null) assertTrue(requiresUpdate) } @Test fun update_fromNull_below() { val positionManager = LocationComponentPositionManager(style, styleState, null, null) val requiresUpdate = positionManager.update(null, "below") assertTrue(requiresUpdate) } @Test fun update_toNull_above() { val positionManager = LocationComponentPositionManager(style, styleState, "above", null) val requiresUpdate = positionManager.update(null, null) assertTrue(requiresUpdate) } @Test fun update_toNull_below() { val positionManager = LocationComponentPositionManager(style, styleState, null, "below") val requiresUpdate = positionManager.update(null, null) assertTrue(requiresUpdate) } @Test fun update_fromValue_above() { val positionManager = LocationComponentPositionManager(style, styleState, "above1", null) val requiresUpdate = positionManager.update("above2", null) assertTrue(requiresUpdate) } @Test fun update_fromValue_below() { val positionManager = LocationComponentPositionManager(style, styleState, null, "below1") val requiresUpdate = positionManager.update(null, "below2") assertTrue(requiresUpdate) } @Test fun addLayer_noModifier() { val positionManager = LocationComponentPositionManager(style, styleState, null, null) positionManager.addLayerToMap(layerWrapper) verify { layerWrapper.bindTo(style, styleState, null) } } @Test fun addLayer_above() { val positionManager = LocationComponentPositionManager(style, styleState, "above", null) positionManager.addLayerToMap(layerWrapper) verify { layerWrapper.bindTo(style, styleState, LayerPosition("above", null, null)) } } @Test fun addLayer_below() { val positionManager = LocationComponentPositionManager(style, styleState, null, "below") positionManager.addLayerToMap(layerWrapper) verify { layerWrapper.bindTo(style, styleState, LayerPosition(null, "below", null)) } } @Test fun addLayer_afterUpdate_above() { val positionManager = LocationComponentPositionManager(style, styleState, null, null) positionManager.update("above", null) positionManager.addLayerToMap(layerWrapper) verify { layerWrapper.bindTo(style, styleState, LayerPosition("above", null, null)) } } @Test fun addLayer_afterUpdate_below() { val positionManager = LocationComponentPositionManager(style, styleState, null, null) positionManager.update(null, "below") positionManager.addLayerToMap(layerWrapper) verify { layerWrapper.bindTo(style, styleState, LayerPosition(null, "below", null)) } } }
0
null
0
0
979c80f9f8eb46c830868702268b73c06761d698
4,081
mapbox-maps-android
Apache License 2.0
app/src/main/java/com/wang/roomdemo/WSubscriber.kt
kingwang666
136,951,973
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 4, "Kotlin": 17, "XML": 9, "Java": 1}
package com.wang.roomdemo import android.util.Log import io.reactivex.rxjava3.subscribers.DisposableSubscriber /** * Author: wangxiaojie6 * Date: 2018/4/4 */ abstract class WSubscriber<T> : DisposableSubscriber<T>() { override fun onComplete() { // dispose() } override fun onNext(t: T) { try { success(t) } catch (e: NullPointerException) { Log.e("Error", e.message, e) } } override fun onError(t: Throwable) { Log.e("Error", t.message, t) try { error(t.message) } catch (e: NullPointerException) { Log.e("Error", e.message, e) } } abstract fun success(t: T) abstract fun error(error: String?) }
0
Kotlin
0
0
99af5bf4acdfacd3d4aef07906fe600fbd428867
749
RoomDemo
Apache License 2.0
module/cluster/management/kubernetes/configuration/src/main/kotlin/pl/beone/promena/cluster/management/kubernetes/configuration/framework/ClusterBootstrapContext.kt
BeOne-PL
235,044,896
false
null
package pl.beone.promena.cluster.management.kubernetes.configuration.framework import akka.actor.ExtendedActorSystem import akka.management.cluster.bootstrap.ClusterBootstrap import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class ClusterBootstrapContext { @Bean fun clusterBootstrap( actorSystem: ExtendedActorSystem ) = ClusterBootstrap(actorSystem).apply { start() } }
2
null
1
9
adbc25d2cd3acf1990f7188938fee25d834aa0db
499
promena
Apache License 2.0
compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/SinceKotlinAnnotationValueChecker.kt
gigliovale
89,726,097
false
{"Java": 23302590, "Kotlin": 21941511, "JavaScript": 137521, "Protocol Buffer": 56992, "HTML": 49980, "Lex": 18051, "Groovy": 14093, "ANTLR": 9797, "IDL": 7706, "Shell": 5152, "CSS": 4679, "Batchfile": 3721}
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.resolve.checkers import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.diagnostics.DiagnosticSink import org.jetbrains.kotlin.diagnostics.Errors.ILLEGAL_SINCE_KOTLIN_VALUE import org.jetbrains.kotlin.diagnostics.Errors.NEWER_VERSION_IN_SINCE_KOTLIN import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.getSinceKotlinAnnotation import org.jetbrains.kotlin.resolve.source.getPsi object SinceKotlinAnnotationValueChecker : DeclarationChecker { private val regex: Regex = "(0|[1-9][0-9]*)".let { number -> Regex("$number\\.$number(\\.$number)?") } override fun check( declaration: KtDeclaration, descriptor: DeclarationDescriptor, diagnosticHolder: DiagnosticSink, bindingContext: BindingContext, languageVersionSettings: LanguageVersionSettings ) { val annotation = descriptor.getSinceKotlinAnnotation() ?: return val version = annotation.allValueArguments.values.singleOrNull()?.value as? String ?: return if (!version.matches(regex)) { diagnosticHolder.report(ILLEGAL_SINCE_KOTLIN_VALUE.on(annotation.source.getPsi() ?: declaration)) return } val apiVersion = ApiVersion.parse(version) val specified = languageVersionSettings.apiVersion if (apiVersion != null && apiVersion > specified) { diagnosticHolder.report(NEWER_VERSION_IN_SINCE_KOTLIN.on(annotation.source.getPsi() ?: declaration, specified.versionString)) } } }
0
Java
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
2,352
kotlin
Apache License 2.0
project/jimmer-sql-kotlin/src/test/kotlin/org/babyfish/jimmer/sql/kt/model/classic/book/Book.kt
babyfish-ct
488,154,823
false
null
package org.babyfish.jimmer.sql.kt.model.classic.book import org.babyfish.jimmer.sql.* import org.babyfish.jimmer.sql.kt.model.classic.store.BookStore import org.babyfish.jimmer.sql.kt.model.classic.author.Author import java.math.BigDecimal import javax.validation.constraints.Positive import javax.validation.constraints.PositiveOrZero @Entity interface Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long @Key val name: String @Key val edition: @PositiveOrZero Int val price: @Positive BigDecimal @ManyToOne val store: BookStore? @ManyToMany val authors: List<Author> @IdView val storeId: Long? @IdView("authors") val authorIds: List<Long> }
4
null
57
497
41f9c3fe6b3a4eececb7ffcac15096295e75e68e
741
jimmer
Apache License 2.0
katalog-server/src/test/kotlin/com/bol/katalog/security/support/TestTokenService.kt
fossabot
171,489,498
false
{"Git Config": 1, "Batchfile": 1, "Shell": 3, "Maven POM": 13, "XML": 6, "Markdown": 6, "Text": 1, "Ignore List": 7, "SVG": 3, "YAML": 12, "INI": 1, "Java": 13, "Kotlin": 165, "SQL": 3, "JSON with Comments": 4, "JSON": 9, "EditorConfig": 1, "Browserslist": 1, "HTML": 28, "CSS": 8, "HCL": 1, "AsciiDoc": 4}
package com.bol.katalog.security.support import com.bol.katalog.security.tokens.auth.TokenService import com.bol.katalog.users.UserId import org.springframework.security.core.Authentication import java.time.Instant class TestTokenService : TokenService { override suspend fun authenticate(token: String): Authentication? { throw NotImplementedError() } override suspend fun issueToken( issuer: UserId, subjectId: UserId, namespace: String, createdOn: Instant ): String { return "jwt-$issuer-$subjectId-$namespace" } }
1
null
2
1
1b432560afae25a4058be7e311b44108d94c85c2
588
katalog
Apache License 2.0
annotations-runtime/src/main/kotlin/com/github/dynamicextensionsalfresco/metrics/SpringTimer.kt
vdewillem
96,100,822
true
{"Java": 514363, "Kotlin": 73038, "Groovy": 12904, "JavaScript": 3167, "CSS": 1733}
package com.github.dynamicextensionsalfresco.metrics import org.alfresco.repo.transaction.AlfrescoTransactionSupport import org.alfresco.repo.transaction.TransactionListener import org.slf4j.LoggerFactory import org.springframework.transaction.support.TransactionSynchronizationManager import org.springframework.util.StopWatch /** * [Timer] based on Spring's [StopWatch] * collects data during a transaction and logs to log4j after commit at TRACE level */ public class SpringTimer : Timer { val logger = LoggerFactory.getLogger(javaClass) val identifier = javaClass.`package`.name override val enabled: Boolean get() = logger.isTraceEnabled private val stopWatch: StopWatch get() { var stopWatch = TransactionSynchronizationManager.getResource(identifier) as? StopWatch if (stopWatch == null) { stopWatch = StopWatch(identifier) TransactionSynchronizationManager.bindResource(identifier, stopWatch) registerTxListener() } return stopWatch } private fun registerTxListener() { AlfrescoTransactionSupport.bindListener(object : TransactionListener { override fun flush() {} override fun beforeCompletion() {} override fun beforeCommit(readOnly: Boolean) {} override fun afterRollback() {} override fun afterCommit() { logger.trace(stopWatch.prettyPrint()) } }) } override fun start(label: String) { if (enabled) { with(stopWatch) { if (isRunning) { stop() } start(label) } } } override fun stop() { if (enabled) { with(stopWatch) { if (isRunning) { stop() } } } } }
0
Java
0
0
afc834ddc25d4335b9efd84db8a701775db77631
1,945
dynamic-extensions-for-alfresco
Apache License 2.0
src/test/java/com/silverhetch/clotho/geo/GeoUriTest.kt
fossabot
268,971,219
false
{"Gradle": 2, "YAML": 3, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Kotlin": 139, "Java": 20, "SQL": 1, "XML": 14}
package com.silverhetch.clotho.geo import org.junit.Assert.* import org.junit.Test /** * Test for com.silverhetch.clotho.geo.GeoUri */ class GeoUriTest { /** * Build result with latitude and longitude only */ @Test fun coordinatorOnly() { assertEquals( "geo:20.0,121.0", GeoUri( 121.0, 20.0 ).value().toASCIIString() ) } /** * Have parameters latitude, longitude and crs. */ @Test fun additionalCrs() { assertEquals( "geo:20.0,121.0;crs=EPSG:32718", GeoUri( 121.0, 20.0, "EPSG:32718" ).value().toASCIIString() ) } /** * Parameter latitude, longitude and uncertainly */ @Test fun additionalUncertainly() { assertEquals( "geo:20.0,121.0;u=10", GeoUri( 121.0, 20.0, u = 10 ).value().toASCIIString() ) } /** * All parameter provided. */ @Test fun allParameter() { assertEquals( "geo:20.0,121.0;crs=WGS-84;u=10", GeoUri( 121.0, 20.0, "WGS-84", 10 ).value().toASCIIString() ) } }
1
null
1
1
aeffa8e69ed87376e7ce1b792d5fe18b188a7e25
1,384
Clotho
MIT License
plugins/kotlin/base/code-insight/src/org/jetbrains/kotlin/idea/base/codeInsight/KotlinMainFunctionDetector.kt
JetBrains
2,489,216
false
{"Text": 9788, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 633, "Markdown": 750, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7904, "SVG": 4537, "Kotlin": 60205, "Java": 84268, "HTML": 3803, "Java Properties": 217, "Gradle": 462, "Maven POM": 95, "JavaScript": 232, "CSS": 79, "JSON": 1436, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 735, "Groovy": 3102, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 73, "GraphQL": 127, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17095, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.codeInsight import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.util.CachedValueProvider.Result import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.psi.util.descendantsOfType import com.intellij.util.concurrency.annotations.RequiresReadLock import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.idea.base.codeInsight.KotlinMainFunctionDetector.Configuration import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf @ApiStatus.Internal interface KotlinMainFunctionDetector { class Configuration( val checkJvmStaticAnnotation: Boolean = true, val checkParameterType: Boolean = true, val checkResultType: Boolean = true, val allowParameterless: Boolean = true, val checkStrictlyOneMain: Boolean = false ) { companion object { val DEFAULT = Configuration() } class Builder( var checkJvmStaticAnnotation: Boolean, var checkParameterType: Boolean, var checkResultType: Boolean, var allowParameterless: Boolean, ) { fun build(): Configuration = Configuration( checkJvmStaticAnnotation, checkParameterType, checkResultType, allowParameterless ) } inline fun with(action: Builder.() -> Unit): Configuration { val configuration = this return Builder( checkJvmStaticAnnotation = configuration.checkJvmStaticAnnotation, checkParameterType = configuration.checkParameterType, checkResultType = configuration.checkResultType, allowParameterless = configuration.allowParameterless, ).apply { action() }.build() } } /** * Checks if a given function satisfies 'main()' function contracts. * * Service implementations perform resolution. * See 'PsiOnlyKotlinMainFunctionDetector' for PSI-only heuristic-based checker. */ @RequiresReadLock fun isMain(function: KtNamedFunction, configuration: Configuration = Configuration.DEFAULT): Boolean companion object { const val MAIN_FUNCTION_NAME: String = "main" fun getInstance(): KotlinMainFunctionDetector = service() @ApiStatus.Internal fun getInstanceDumbAware(project: Project): KotlinMainFunctionDetector { return if (DumbService.isDumb(project)) PsiOnlyKotlinMainFunctionDetector else getInstance() } } } @RequiresReadLock fun KotlinMainFunctionDetector.hasMain(file: KtFile, configuration: Configuration = Configuration.DEFAULT): Boolean { return findMain(file, configuration) != null } @RequiresReadLock fun KotlinMainFunctionDetector.findMain(file: KtFile, configuration: Configuration = Configuration.DEFAULT): KtNamedFunction? { return findMainInContainer(file, configuration) } @RequiresReadLock fun KotlinMainFunctionDetector.hasMain(declaration: KtClassOrObject, configuration: Configuration = Configuration.DEFAULT): Boolean { return findMain(declaration, configuration) != null } @RequiresReadLock fun KotlinMainFunctionDetector.findMain( declaration: KtClassOrObject, configuration: Configuration = Configuration.DEFAULT ): KtNamedFunction? { if (declaration is KtObjectDeclaration) { if (declaration.isObjectLiteral()) { return null } return findMainInContainer(declaration, configuration) } return declaration.companionObjects.firstNotNullOfOrNull { findMain(it, configuration) } } private fun KotlinMainFunctionDetector.findMainInContainer(owner: KtDeclarationContainer, configuration: Configuration): KtNamedFunction? { val mains = owner .declarations .asSequence() .filterIsInstance<KtNamedFunction>() .filter { isMain(it, configuration) } return if (configuration.checkStrictlyOneMain) mains.singleOrNull() else mains.firstOrNull() } @RequiresReadLock fun KotlinMainFunctionDetector.findMainOwner(element: PsiElement): KtDeclarationContainer? { return findMainOwnerDumbAware(element) } private fun KotlinMainFunctionDetector.findMainOwnerDumbAware(element: PsiElement): KtDeclarationContainer? { val project = element.project val dumbService = DumbService.getInstance(project) if (!dumbService.isDumb || this !is PsiOnlyKotlinMainFunctionDetector) return findMainFunctionContainer(element) return CachedValuesManager.getManager(project).getCachedValue(element) { val mainOwner = findMainFunctionContainer(element, Configuration(checkStrictlyOneMain = true)) Result.create(mainOwner, PsiModificationTracker.getInstance(project), dumbService.modificationTracker) } } private fun KotlinMainFunctionDetector.findMainFunctionContainer( element: PsiElement, configuration: Configuration = Configuration.DEFAULT ): KtDeclarationContainer? { val containingFile = element.containingFile as? KtFile ?: return null if (!RootKindFilter.projectSources.matches(containingFile)) { return null } for (parent in element.parentsWithSelf) { if (parent is KtClassOrObject && hasMain(parent, configuration)) { return parent } } if (hasMain(containingFile, configuration)) { return containingFile } for (descendant in element.descendantsOfType<KtClassOrObject>()) { if (hasMain(descendant, configuration)) { return descendant } } return null }
1
null
1
1
0d546ea6a419c7cb168bc3633937a826d4a91b7c
6,119
intellij-community
Apache License 2.0
app/src/main/java/com/selimasik/imdbapp/ui/splash/SplashActivity.kt
asikselim
377,492,768
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Ignore List": 1, "Kotlin": 24, "XML": 15, "Java": 1}
package com.selimasik.imdbapp.ui.splash import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.CountDownTimer import androidx.annotation.RequiresApi import com.selimasik.imdbapp.utils.AlertDialogUtil import com.selimasik.imdbapp.utils.NetworkUtil import com.selimasik.imdbapp.R import com.selimasik.imdbapp.ui.login.LoginActivity class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) init() } private fun init() { val timer = object: CountDownTimer(3000, 1000) { override fun onTick(millisUntilFinished: Long) { } @RequiresApi(Build.VERSION_CODES.M) override fun onFinish() { if(NetworkUtil.isOnline(applicationContext)){ startActivity(Intent(this@SplashActivity, LoginActivity::class.java)) finish() } else{ AlertDialogUtil.alertDialogShow(this@SplashActivity, resources.getString(R.string.uyari), resources.getString(R.string.internet_yok_mesaj), resources.getString(R.string.ayaralara_git), resources.getString(R.string.kapat), resources.getString(R.string.splash_activity) ) } } } timer.start() } }
1
null
1
1
3b09959d7ee2cbaaaa9f1ed10ce5069fba41df0e
1,603
IMDBCloneApp
Apache License 2.0
schedule/src/main/kotlin/com/example/demo/KotlinCounter.kt
hantsy
442,958,179
false
{"Java": 777124, "Kotlin": 13935, "FreeMarker": 11635, "HTML": 3844, "CSS": 483, "JavaScript": 11}
package com.example.demo import kotlinx.coroutines.reactor.awaitSingle import org.slf4j.LoggerFactory import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import reactor.core.publisher.Mono import java.util.concurrent.atomic.AtomicInteger @Component class KotlinCounter { companion object { val log = LoggerFactory.getLogger(KotlinCounter::class.java) } private val count = AtomicInteger(0) @Scheduled(fixedDelay = 5) suspend fun scheduled(): Void { return Mono.defer { Mono.just(count.incrementAndGet()) } .doOnNext { item: Int? -> log.debug("current count:{}", item) } .then() .awaitSingle() } suspend fun getInvocationCount(): Int { return count.get() } }
1
Java
17
77
3c3607e899422d3ead6c96ca87c6a38e976fa2b9
809
spring6-sandbox
Apache License 2.0
app/src/sharedTest/java/com/kenilt/mock/MockServerRule.kt
kenilt
247,617,328
false
{"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 2, "Proguard": 2, "XML": 50, "Java": 12, "JSON": 1, "Kotlin": 223}
package com.kenilt.mock import okhttp3.mockwebserver.MockWebServer import org.junit.After import org.junit.Before import org.junit.rules.ExternalResource class MockServerRule @JvmOverloads constructor( private val port: Int = 8080 ) : ExternalResource() { lateinit var mockWebServer: MockWebServer lateinit var mockDispatcher: MockDispatcher @Before override fun before() { mockWebServer = MockWebServer() mockWebServer.start(port) mockDispatcher = MockDispatcher() mockWebServer.dispatcher = mockDispatcher } @After override fun after() { mockWebServer.shutdown() } fun setDispatcher(mockDispatcher: MockDispatcher) { this.mockDispatcher = mockDispatcher mockWebServer.dispatcher = mockDispatcher } }
0
Kotlin
0
0
9d5f445839d9741f4df5aa8cdfc46dfedada6b9b
812
Android-Skeleton-Project
MIT License
idea/testData/intentions/replaceSubstringWithSubstringBefore/nonZeroFirstArgument.kt
JakeWharton
99,388,807
false
null
// IS_APPLICABLE: false // WITH_RUNTIME fun foo(s: String) { s.substring<caret>(1, s.indexOf('x')) }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
105
kotlin
Apache License 2.0
app/src/main/kotlin/com/juniperphoton/myersplash/widget/RingProgressView.kt
JuniperPhoton
67,424,471
false
null
package com.juniperphoton.myersplash.widget import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.view.View import com.juniperphoton.myersplash.R import com.juniperphoton.myersplash.extension.use class RingProgressView(context: Context, attrs: AttributeSet) : View(context, attrs) { companion object { private const val STROKE_WIDTH = 5 private const val INIT_PROGRESS_VALUE = 10 private const val INTERVAL_PROGRESS_VALUE = 5 } private val paint: Paint = Paint() var progress = INIT_PROGRESS_VALUE set(value) { var finalValue = value if (finalValue < INTERVAL_PROGRESS_VALUE) { finalValue = INTERVAL_PROGRESS_VALUE } field = finalValue invalidate() } var color = Color.WHITE set(value) { field = value invalidate() } private val rect: RectF = RectF() init { paint.color = color paint.strokeWidth = STROKE_WIDTH.toFloat() paint.isAntiAlias = true paint.style = Paint.Style.STROKE paint.strokeCap = Paint.Cap.ROUND context.obtainStyledAttributes(attrs, R.styleable.CustomProgressView).use { progress = getInt(R.styleable.CustomProgressView_custom_progress, 0) } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val center = (width / 2f).toInt() val radius = (center - STROKE_WIDTH / 2f).toInt() paint.color = color rect.set((center - radius).toFloat(), (center - radius).toFloat(), (center + radius).toFloat(), (center + radius).toFloat()) val angle = (360 * progress / 100f).toInt() canvas.drawArc(rect, -90f, angle.toFloat(), false, paint) } }
27
Kotlin
23
93
d2e6da91c20b638445c60b089e9aa789c646d22b
1,950
MyerSplash.Android
MIT License
example/src/test/kotlin/specs/soap/Soap.kt
Adven27
97,571,739
false
{"Gradle": 16, "INI": 2, "Shell": 2, "Text": 8, "Ignore List": 1, "Batchfile": 1, "Markdown": 8, "XML": 58, "YAML": 3, "Kotlin": 119, "Java": 13, "HTML": 44, "JavaScript": 21, "CSS": 20, "SVG": 3, "JSON": 17, "SQL": 1}
package specs.soap import specs.Specs class Soap : Specs()
1
JavaScript
4
17
afe287665d835f9f212c00143822e0a0069c7d69
61
Exam
MIT License
app/src/main/java/com/google/android/stardroid/layers/IssLayer.kt
sky-map-team
37,151,000
false
{"Gradle": 5, "Markdown": 14, "Shell": 6, "YAML": 4, "Java Properties": 1, "Ignore List": 1, "Batchfile": 1, "INI": 2, "Java": 123, "Kotlin": 92, "JSON": 2, "XML": 150, "HTML": 7, "Protocol Buffer": 1, "Text": 8, "Python": 1}
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.itepinnovation.android.stardroid.layers import android.content.res.Resources import android.graphics.Color import android.util.Log import com.itepinnovation.android.stardroid.base.TimeConstants import com.itepinnovation.android.stardroid.control.AstronomerModel import com.itepinnovation.android.stardroid.renderer.RendererObjectManager.UpdateType import com.google.common.io.Closeables import com.itepinnovation.android.stardroid.R import com.itepinnovation.android.stardroid.ephemeris.OrbitalElements import com.itepinnovation.android.stardroid.math.Vector3 import com.itepinnovation.android.stardroid.renderables.* import com.itepinnovation.android.stardroid.util.MiscUtil import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.net.URL import java.util.* import java.util.concurrent.Executors import java.util.concurrent.TimeUnit /** * @author Brent Bryan */ class IssLayer(resources: Resources, model: AstronomerModel) : AbstractRenderablesLayer(resources, true) { private val scheduler = Executors.newScheduledThreadPool(1) private val issRenderable: IssRenderable = IssRenderable(model, resources) override fun initializeAstroSources(sources: ArrayList<AstronomicalRenderable>) { sources.add(issRenderable) scheduler.scheduleAtFixedRate( OrbitalElementsGrabber(issRenderable), 0, 60, TimeUnit.SECONDS ) } override val layerDepthOrder = 70 override val layerNameId = R.string.show_satellite_layer_pref /** Thread Runnable which parses the orbital elements out of the Url. */ internal class OrbitalElementsGrabber(private val renderable: IssRenderable) : Runnable { private var lastSuccessfulUpdateMs = -1L /** * Parses the OrbitalElements from the given BufferedReader. Factored out * of [.getOrbitalElements] to simplify testing. */ @Throws(IOException::class) fun parseOrbitalElements(`in`: BufferedReader): OrbitalElements? { var s: String while (`in`.readLine().also { s = it } != null && !s.contains("M50 Keplerian")) { } // Skip the dashed line `in`.readLine() val params = FloatArray(9) var i = 0 while (i < params.size && `in`.readLine().also { s = it } != null) { s = s.substring(46).trim { it <= ' ' } val tokens = s.split("\\s+").toTypedArray() params[i] = tokens[2].toFloat() i++ } if (i == params.size) { // we read all the data. // TODO(serafini): Add magic here to create orbital elements or whatever. val sb = StringBuilder() for (param in params) { sb.append(" ").append(param) } //Blog.d(this, "Params: " + sb); } return null } /** * Reads the given URL and returns the OrbitalElements associated with the object * described therein. */ fun getOrbitalElements(urlString: String?): OrbitalElements? { var `in`: BufferedReader? = null try { val connection = URL(urlString).openConnection() `in` = BufferedReader(InputStreamReader(connection.getInputStream())) return parseOrbitalElements(`in`) } catch (e: IOException) { Log.e(TAG, "Error reading Orbital Elements") } finally { Closeables.closeQuietly(`in`) } return null } override fun run() { val currentTimeMs = System.currentTimeMillis() if (currentTimeMs - lastSuccessfulUpdateMs > UPDATE_FREQ_MS) { //Blog.d(this, "Fetching ISS data..."); val elements = getOrbitalElements(URL_STRING) if (elements == null) { Log.d(TAG, "Error downloading ISS orbital data") } else { lastSuccessfulUpdateMs = currentTimeMs renderable.setOrbitalElements(elements) } } } companion object { private const val UPDATE_FREQ_MS = TimeConstants.MILLISECONDS_PER_HOUR private val TAG = MiscUtil.getTag(OrbitalElementsGrabber::class.java) private const val URL_STRING = "http://spaceflight.nasa.gov/realdata/" + "sightings/SSapplications/Post/JavaSSOP/orbit/ISS/SVPOST.html" } } /** AstronomicalRenderable corresponding to the International Space Station. */ internal class IssRenderable(private val model: AstronomerModel, resources: Resources?) : AbstractAstronomicalRenderable() { private val coords = Vector3(1f, 0f, 0f) private val pointPrimitives = ArrayList<PointPrimitive>() private val textPrimitives = ArrayList<TextPrimitive>() private val name: String private var orbitalElements: OrbitalElements? = null private var orbitalElementsChanged = false private var lastUpdateTimeMs = 0L @Synchronized fun setOrbitalElements(elements: OrbitalElements?) { orbitalElements = elements orbitalElementsChanged = true } private fun updateCoords(time: Date) { lastUpdateTimeMs = time.time orbitalElementsChanged = false if (orbitalElements == null) { return } // TODO(serafini): Update coords of Iss from OrbitalElements. // issCoords.assign(...); } override fun initialize(): Renderable { updateCoords(model.time) return this } @Synchronized override fun update(): EnumSet<UpdateType> { val updateTypes = EnumSet.noneOf(UpdateType::class.java) val modelTime = model.time if (orbitalElementsChanged || Math.abs(modelTime.time - lastUpdateTimeMs) > UPDATE_FREQ_MS ) { updateCoords(modelTime) if (orbitalElements != null) { updateTypes.add(UpdateType.UpdatePositions) } } return updateTypes } companion object { private const val UPDATE_FREQ_MS = 1L * TimeConstants.MILLISECONDS_PER_SECOND private const val ISS_COLOR = Color.YELLOW } init { name = resources!!.getString(R.string.space_station) pointPrimitives.add( PointPrimitive( coords, ISS_COLOR, 5 ) ) textPrimitives.add( TextPrimitive( coords, name, ISS_COLOR ) ) } } }
143
Java
231
858
b7115f5a180573c5368c6e31b4d836ba82827395
7,607
stardroid
Apache License 2.0
app/src/main/java/com/androiddev/social/ui/SplashActivity.kt
digitalbuddha
599,627,508
false
{"Kotlin": 545804, "Nix": 3254, "Java": 978}
@file:OptIn(ExperimentalTextApi::class) package com.androiddev.social.ui import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.View import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.text.ExperimentalTextApi import androidx.constraintlayout.motion.widget.MotionLayout import com.androiddev.social.timeline.ui.MainActivity import social.androiddev.firefly.R @ExperimentalMaterial3Api @ExperimentalComposeUiApi class SplashActivity : Activity() { @OptIn(ExperimentalTextApi::class, ExperimentalMaterialApi::class, ExperimentalAnimationApi::class ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) findViewById<MotionLayout>(R.id.motionLayout).setTransitionListener(object : MotionLayout.TransitionListener { override fun onTransitionCompleted(p0: MotionLayout?, p1: Int) { startActivity(Intent(this@SplashActivity, MainActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)) } override fun onTransitionChange(p0: MotionLayout?, p1: Int, p2: Int, p3: Float) {} override fun onTransitionStarted(p0: MotionLayout?, p1: Int, p2: Int) {} override fun onTransitionTrigger(p0: MotionLayout?, p1: Int, p2: Boolean, p3: Float) {} }) } override fun onResume() { super.onResume() findViewById<MotionLayout>(R.id.motionLayout).startLayoutAnimation() } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) if (hasFocus) { // hideSystemUIAndNavigation(this) } } private fun hideSystemUIAndNavigation(activity: Activity) { val decorView: View = activity.window.decorView decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN) } }
4
Kotlin
5
31
dbfb0d20aa074260384b3c9c8cc083cb32ca50c2
2,678
Firefly
Apache License 2.0
build-logic/convention/src/main/java/ru/ilyasekunov/convention/ru/ilyasekunov/officeapp/KotlinAndroid.kt
IlyaSekunov
744,587,168
false
{"Kotlin": 691090}
package ru.ilyasekunov.convention.ru.ilyasekunov.officeapp import com.android.build.api.dsl.CommonExtension import org.gradle.api.JavaVersion import org.gradle.api.Project import org.gradle.api.plugins.JavaPluginExtension import org.gradle.kotlin.dsl.assign import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.provideDelegate import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.dsl.KotlinAndroidProjectExtension import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension import org.jetbrains.kotlin.gradle.dsl.KotlinTopLevelExtension /** * Configure base Kotlin with Android options */ internal fun Project.configureKotlinAndroid( commonExtension: CommonExtension<*, *, *, *, *, *>, ) { commonExtension.apply { compileSdk = 34 defaultConfig { minSdk = 26 } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } } configureKotlin<KotlinAndroidProjectExtension>() } /** * Configure base Kotlin options for JVM (non-Android) */ internal fun Project.configureKotlinJvm() { extensions.configure<JavaPluginExtension> { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } configureKotlin<KotlinJvmProjectExtension>() } /** * Configure base Kotlin options */ private inline fun <reified T : KotlinTopLevelExtension> Project.configureKotlin() = configure<T> { val warningsAsErrors: String? by project when (this) { is KotlinAndroidProjectExtension -> compilerOptions is KotlinJvmProjectExtension -> compilerOptions else -> TODO("Unsupported project extension $this ${T::class}") }.apply { jvmTarget = JvmTarget.JVM_17 allWarningsAsErrors = warningsAsErrors.toBoolean() freeCompilerArgs.add( // Enable experimental coroutines APIs, including Flow "-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi", ) } }
0
Kotlin
0
3
2fbc3342e0d36bb0e093b55cbdaf3402c8f1a05c
2,078
office-app
Apache License 2.0
data/src/main/java/com/rowland/adventcalendly/data/adventday/AdventDayRepository.kt
RowlandOti
236,055,285
false
null
package com.rowland.adventcalendly.data.adventday import com.rowland.adventcalendly.data.mapper.AdventDayDataMapper import com.rowland.adventcalendly.domain.contract.IAdventDayRepository import com.rowland.adventcalendly.domain.model.AdventDay import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Single import javax.inject.Inject /** * Created by Rowland on 1/26/2020. */ class AdventDayRepository @Inject constructor(private val dataStoreFactory: AdventDayDataStoreFactory) : IAdventDayRepository { override fun getAll(): Flowable<List<AdventDay>> { return dataStoreFactory.retrieveCacheDataStore().isCached() .flatMapPublisher { dataStoreFactory.retrieveDataStore(it).getAll() } .flatMap { Flowable.just(it.map { AdventDayDataMapper.mapFromData(it) }) } } override fun insert(model: AdventDay): Single<Long> { return dataStoreFactory.retrieveDataStore(true).insert(AdventDayDataMapper.mapToData(model)) } override fun bulkInsert(modelList: List<AdventDay>): Single<List<Long>> { return dataStoreFactory.retrieveDataStore(true).bulkInsert(AdventDayDataMapper.mapToDataList(modelList)) } override fun deleteAll(): Completable { return dataStoreFactory.retrieveDataStore(true).deleteAll() } override fun update(model: AdventDay): Single<Int> { return dataStoreFactory.retrieveDataStore(true).update(AdventDayDataMapper.mapToData(model)) } }
0
Kotlin
0
0
ebc109636cea730f3e1041bf30617548da50fc05
1,486
AdventCalendly
The Unlicense
crypto_btc_like/src/test/java/io/noone/adnroidcore/btclike/WifTest.kt
noonewallet
596,143,484
false
{"Kotlin": 169235}
package io.noone.adnroidcore.btclike import io.noone.androidcore.btclike.PrivateKey import io.noone.androidcore.btclike.addresses.BitcoinCashAddress import io.noone.androidcore.btclike.addresses.LegacyAddress import io.noone.androidcore.btclike.networks.BchParams import io.noone.androidcore.btclike.networks.BitcoinParams import io.noone.androidcore.btclike.networks.DogeParams import io.noone.androidcore.btclike.networks.LitecoinParams import org.junit.Assert import org.junit.Test class WifTest { // for mnemonic: bunker ring viable sphere trap flush cost motor mixture transfer copy motor resist prize speed private val btcWifKeys = listOf( "<KEY>" to "1Ff7U7nbofhZzENXdHG6YJT7ngLUnPeSu6", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", ) private val ltcWifKeys = listOf( "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", ) private val dogeWifKeys = listOf( "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", ) private val bchWifKeys = listOf( "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", "<KEY>" to "<KEY>", ) @Test fun testWifDecoder() { for ((key, _) in btcWifKeys) { Assert.assertThrows(IllegalArgumentException::class.java) { PrivateKey.fromWif(key, DogeParams) } Assert.assertThrows(IllegalArgumentException::class.java) { PrivateKey.fromWif(key, LitecoinParams) } } for ((key, expectedAddress) in btcWifKeys) { val privateKey = PrivateKey.fromWif(key, BitcoinParams) val address = LegacyAddress.fromKey(BitcoinParams, privateKey.key) Assert.assertEquals(expectedAddress, address.toString()) } for ((key, expectedAddress) in ltcWifKeys) { val privateKey = PrivateKey.fromWif(key, LitecoinParams) val address = LegacyAddress.fromKey(LitecoinParams, privateKey.key) Assert.assertEquals(expectedAddress, address.toString()) } for ((key, expectedAddress) in bchWifKeys) { val privateKey = PrivateKey.fromWif(key, BchParams) val address = BitcoinCashAddress.fromKey(BchParams, privateKey.key) Assert.assertEquals(expectedAddress, address.bech32) } for ((key, expectedAddress) in dogeWifKeys) { val privateKey = PrivateKey.fromWif(key, DogeParams) val address = LegacyAddress.fromKey(DogeParams, privateKey.key) Assert.assertEquals(expectedAddress, address.toString()) } } }
0
Kotlin
0
0
345703ca2b30ba9e270e531210f941c81c71fe33
2,869
noone-android-core-btclike
MIT License
libraries/tools/kotlin-gradle-statistics/src/main/kotlin/org/jetbrains/kotlin/statistics/metrics/MetricContainers.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2020 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.statistics.metrics import java.io.Serializable import java.util.* interface IMetricContainer<T> : Serializable { fun addValue(t: T, weight: Long? = null) fun toStringRepresentation(): String fun getValue(): T? } interface IMetricContainerFactory<T> { fun newMetricContainer(): IMetricContainer<T> fun fromStringRepresentation(state: String): IMetricContainer<T>? } open class OverrideMetricContainer<T>() : IMetricContainer<T> { internal var myValue: T? = null override fun addValue(t: T, weight: Long?) { myValue = t } internal constructor(v: T?) : this() { myValue = v } override fun toStringRepresentation(): String { return myValue?.toString() ?: "null" } override fun getValue() = myValue } class OverrideVersionMetricContainer() : OverrideMetricContainer<String>() { constructor(v: String) : this() { myValue = v } override fun addValue(t: String, weight: Long?) { if (myValue == null || myValue == "0.0.0") { myValue = t } } } class SumMetricContainer() : OverrideMetricContainer<Long>() { constructor(v: Long) : this() { myValue = v } override fun addValue(t: Long, weight: Long?) { myValue = (myValue ?: 0) + t } } class AverageMetricContainer() : IMetricContainer<Long> { private var totalWeight = 0L private var totalSum: Long? = null constructor(v: Long) : this() { totalSum = v totalWeight = 1 } override fun addValue(t: Long, weight: Long?) { val w = weight ?: 1 totalSum = (totalSum ?: 0) + t * w totalWeight += w } override fun toStringRepresentation(): String { return getValue()?.toString() ?: "null" } override fun getValue(): Long? { return totalSum?.div(if (totalWeight > 0) totalWeight else 1) } } class OrMetricContainer() : OverrideMetricContainer<Boolean>() { constructor(v: Boolean) : this() { myValue = v } override fun addValue(t: Boolean, weight: Long?) { myValue = (myValue ?: false) || t } } class ConcatMetricContainer() : IMetricContainer<String> { private val myValues = TreeSet<String>() companion object { const val SEPARATOR = ";" } constructor(values: Collection<String>) : this() { myValues.addAll(values) } override fun addValue(t: String, weight: Long?) { myValues.add(t.replace(SEPARATOR, ",")) } override fun toStringRepresentation(): String { return myValues.sorted().joinToString(SEPARATOR) } override fun getValue() = toStringRepresentation() }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
2,918
kotlin
Apache License 2.0
app/src/main/java/com/studiocinqo/diardeonandroid/engine3d/Polygon/PolygonTexture.kt
Diarde
375,262,759
false
null
package com.studiocinqo.diardeonandroid.engine3d.Polygon import android.opengl.GLES20 import com.studiocinqo.diardeonandroid.engine3d.GLShaders import com.studiocinqo.diardeonandroid.engine3d.Texture import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.FloatBuffer class PolygonTexture internal constructor(private val texture: Texture, vertices: FloatArray, indices: ShortArray, private val uvs: FloatArray, normals: FloatArray): Polygon( vertices, indices, normals){ private val uvBuffer = getUVBuffer(uvs) override fun Render(m: FloatArray?) { //get handle to vertex shader's vPosition member val mPositionHandle: Int = GLES20.glGetAttribLocation( GLShaders.sp_Image, "vPosition" ) // Enable generic vertex attribute array GLES20.glEnableVertexAttribArray(mPositionHandle) // Prepare the triangle coordinate data GLES20.glVertexAttribPointer( mPositionHandle, 3, GLES20.GL_FLOAT, false, 0, vertexBuffer ) val mNormalLoc: Int = GLES20.glGetAttribLocation( GLShaders.sp_Image, "vNormal" ) // Enable generic normals attribute array GLES20.glEnableVertexAttribArray(mNormalLoc) // Prepare the texturecoordinates GLES20.glVertexAttribPointer( mNormalLoc, 3, GLES20.GL_FLOAT, false, 0, normalsBuffer ) // Get handle to texture coordinates location val mTexCoordLoc: Int = GLES20.glGetAttribLocation( GLShaders.sp_Image, "a_texCoord" ) // Enable generic vertex attribute array GLES20.glEnableVertexAttribArray(mTexCoordLoc) // Prepare the texturecoordinates GLES20.glVertexAttribPointer( mTexCoordLoc, 2, GLES20.GL_FLOAT, false, 0, uvBuffer ) // Get handle to shape's transformation matrix val mtrxhandle: Int = GLES20.glGetUniformLocation( GLShaders.sp_Image, "uMVPMatrix" ) // Apply the projection and view transformation GLES20.glUniformMatrix4fv(mtrxhandle, 1, false, m, 0) // Get handle to textures locations val mSamplerLoc: Int = GLES20.glGetUniformLocation( GLShaders.sp_Image, "s_texture" ) // Set the sampler texture unit to 0, where we have saved the texture. GLES20.glUniform1i(mSamplerLoc, texture.lot) val mOffset: Int = GLES20.glGetUniformLocation( GLShaders.sp_Image, "f_offset" ) GLES20.glUniform1f(mOffset, 0f) // Draw the triangle GLES20.glDrawElements( GLES20.GL_TRIANGLES, indices.size, GLES20.GL_UNSIGNED_SHORT, drawListBuffer ) // Disable vertex array GLES20.glDisableVertexAttribArray(mPositionHandle) GLES20.glDisableVertexAttribArray(mTexCoordLoc) GLES20.glDisableVertexAttribArray(mNormalLoc) } private fun getUVBuffer(uvs: FloatArray): FloatBuffer { val uvBuffer: FloatBuffer val bb = ByteBuffer.allocateDirect(uvs.size * 4) bb.order(ByteOrder.nativeOrder()) uvBuffer = bb.asFloatBuffer() uvBuffer.put(uvs) uvBuffer.position(0) return uvBuffer } }
0
Kotlin
0
0
bb1e1b792e2162763a09778de2181cc412e42f6c
3,588
DIARDEOnAndroid
MIT License
app/src/main/java/com/github/mahendranv/podroom/list/IPopupHandler.kt
mahendranv
607,981,900
false
null
package com.github.mahendranv.podroom.list interface IPopupHandler { fun getActions(): List<String> fun onActionClicked(position: Int, item: Any) }
8
Kotlin
0
1
ec995f449d3deeb8e48a5ff4a3b72119c32901cc
158
pod-room
MIT License
src/main/kotlin/com/hoho/upbitapihelper/dto/quotation/TickOrderSide.kt
hoho4190
518,368,050
false
{"Kotlin": 113377, "Java": 2565}
package com.hoho.upbitapihelper.dto.quotation /** * 주문 종류 */ enum class TickOrderSide { /** * 매수 */ BID, /** * 매도 */ ASK }
0
Kotlin
0
3
9f38818e8c82e7c64a4e11119187ce2b21cdb021
163
upbit-api-helper
Apache License 2.0
assertk-common/src/main/kotlin/assertk/assertions/array.kt
maverick1601
170,570,765
true
{"Kotlin": 193395, "Java": 134}
package assertk.assertions import assertk.Assert import assertk.PlatformName import assertk.all import assertk.assertions.support.expected import assertk.assertions.support.fail import assertk.assertions.support.show /** * Returns an assert on the Arrays's size. */ fun Assert<Array<*>>.size() = prop("size") { it.size } /** * Asserts the array contents are equal to the expected one, using [contentDeepEquals]. * @see isNotEqualTo */ fun <T> Assert<Array<T>>.isEqualTo(expected: Array<T>) = given { actual -> if (actual.contentDeepEquals(expected)) return fail(expected, actual) } /** * Asserts the array contents are not equal to the expected one, using [contentDeepEquals]. * @see isEqualTo */ fun <T> Assert<Array<T>>.isNotEqualTo(expected: Array<T>) = given { actual -> if (!(actual.contentDeepEquals(expected))) return val showExpected = show(expected) val showActual = show(actual) // if they display the same, only show one. if (showExpected == showActual) { expected("to not be equal to:$showActual") } else { expected(":$showExpected not to be equal to:$showActual") } } /** * Asserts the array is empty. * @see [isNotEmpty] * @see [isNullOrEmpty] */ @PlatformName("arrayIsEmpty") fun Assert<Array<*>>.isEmpty() = given { actual -> if (actual.isEmpty()) return expected("to be empty but was:${show(actual)}") } /** * Asserts the array is not empty. * @see [isEmpty] */ @PlatformName("arrayIsNotEmpty") fun Assert<Array<*>>.isNotEmpty() = given { actual -> if (actual.isNotEmpty()) return expected("to not be empty") } /** * Asserts the array is null or empty. * @see [isEmpty] */ @PlatformName("arrayIsNullOrEmpty") fun Assert<Array<*>?>.isNullOrEmpty() = given { actual -> if (actual == null || actual.isEmpty()) return expected("to be null or empty but was:${show(actual)}") } /** * Asserts the array has the expected size. */ @PlatformName("arrayHasSize") fun Assert<Array<*>>.hasSize(size: Int) { size().isEqualTo(size) } /** * Asserts the array has the same size as the expected array. */ @PlatformName("arrayHasSameSizeAs") fun <T> Assert<Array<T>>.hasSameSizeAs(other: Array<*>) = given { actual -> val actualSize = actual.size val otherSize = other.size if (actualSize == otherSize) return expected("to have same size as:${show(other)} ($otherSize) but was size:($actualSize)") } /** * Asserts the array contains the expected element, using `in`. * @see [doesNotContain] */ @PlatformName("arrayContains") fun <T> Assert<Array<T>>.contains(element: Any?) = given { actual -> if (element in actual) return expected("to contain:${show(element)} but was:${show(actual)}") } /** * Asserts the array does not contain the expected element, using `!in`. * @see [contains] */ @PlatformName("arrayDoesNotContain") fun <T> Assert<Array<T>>.doesNotContain(element: Any?) = given { actual -> if (element !in actual) return expected("to not contain:${show(element)} but was:${show(actual)}") } /** * Asserts the collection does not contain any of the expected elements. * @see [containsAll] */ fun <T> Assert<Array<T>>.containsNone(vararg elements: Any?) = given { actual -> if (elements.none { it in actual }) { return } val notExpected = elements.filter { it in actual } expected("to contain none of:${show(elements)} some elements were not expected:${show(notExpected)}") } /** * Asserts the array contains all the expected elements, in any order. The array may also contain * additional elements. * @see [containsExactly] */ @PlatformName("arrayContainsAll") fun <T> Assert<Array<T>>.containsAll(vararg elements: Any?) = given { actual -> if (elements.all { actual.contains(it) }) return val notFound = elements.filterNot { it in actual } expected("to contain all:${show(elements)} but was:${show(actual)}. Missing elements:${show(notFound)}") } /** * Returns an assert that assertion on the value at the given index in the array. * * ``` * assertThat(arrayOf(0, 1, 2)).index(1) { it.isPositive() } * ``` */ @Deprecated(message = "Use index(index) instead.", replaceWith = ReplaceWith("index(index).let(f)")) fun <T> Assert<Array<T>>.index(index: Int, f: (Assert<T>) -> Unit) { index(index).let(f) } /** * Returns an assert that assertion on the value at the given index in the array. * * ``` * assertThat(arrayOf(0, 1, 2)).index(1).isPositive() * ``` */ fun <T> Assert<Array<T>>.index(index: Int): Assert<T> = transform("${name ?: ""}${show(index, "[]")}") { actual -> if (index in 0 until actual.size) { actual[index] } else { expected("index to be in range:[0-${actual.size}) but was:${show(index)}") } } /** * Asserts the array contains exactly the expected elements. They must be in the same order and * there must not be any extra elements. * @see [containsAll] */ @PlatformName("arrayContainsExactly") fun <T> Assert<Array<T>>.containsExactly(vararg elements: Any?) = given { actual -> if (actual.contentEquals(elements)) return expected(listDifferExpected(elements.asList(), actual.asList())) } /** * Asserts on each item in the array. The given lambda will be run for each item. * * ``` * assertThat(arrayOf("one", "two")).each { * it.hasLength(3) * } * ``` */ @PlatformName("arrayEach") fun <T> Assert<Array<T>>.each(f: (Assert<T>) -> Unit) = given { actual -> all { actual.forEachIndexed { index, item -> f(assertThat(item, name = "${name ?: ""}${show(index, "[]")}")) } } }
0
Kotlin
0
0
fc7c4b062c157f20d9a0777be4d2cb41c7be58ec
5,626
assertk
MIT License
app/src/main/java/com/github/pakka_papad/collection/CollectionTopBar.kt
pakka-papad
539,192,838
false
null
package com.github.pakka_papad.collection import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.ArrowBack import androidx.compose.material.icons.outlined.MoreVert import androidx.compose.material.ripple.rememberRipple import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import com.github.pakka_papad.components.TopBarWithBackArrow import com.github.pakka_papad.components.more_options.OptionsDropDown import com.github.pakka_papad.data.UserPreferences import com.github.pakka_papad.ui.theme.ThemePreference @Composable fun CollectionTopBar( topBarTitle: String, topBarBackgroundImageUri: String, onBackArrowPressed: () -> Unit, themePreference: ThemePreference, actions: List<CollectionActions> = listOf(), ) { val configuration = LocalConfiguration.current if (topBarBackgroundImageUri.isEmpty() || configuration.screenHeightDp < 360) { TopBarWithBackArrow( onBackArrowPressed = onBackArrowPressed, title = topBarTitle, actions = { CollectionTopBarActions(actions) } ) } else { val systemInDarkTheme = isSystemInDarkTheme() val darkScrim by remember(themePreference) { derivedStateOf { when (themePreference.theme) { UserPreferences.Theme.DARK_MODE -> true UserPreferences.Theme.LIGHT_MODE, UserPreferences.Theme.UNRECOGNIZED -> false UserPreferences.Theme.USE_SYSTEM_MODE -> systemInDarkTheme } } } Box( modifier = Modifier .fillMaxWidth() .height(if (configuration.screenHeightDp >= 720) 240.dp else 120.dp) ) { AsyncImage( model = topBarBackgroundImageUri, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize() ) Spacer( modifier = Modifier .fillMaxSize() .background( Brush.verticalGradient( listOf( Color.Transparent, Color.Transparent, Color.Black, ) ), ) .align(Alignment.BottomCenter) ) val paddingValues = WindowInsets.systemBars.only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal) .asPaddingValues() Spacer( modifier = Modifier .fillMaxWidth() .height(paddingValues.calculateTopPadding()) .background( (if (darkScrim) Color.Black else Color.White).copy(alpha = 0.4f) ) .align(Alignment.TopCenter) ) SmallTopAppBar( modifier = Modifier .background(Color.Transparent) .padding( start = paddingValues.calculateStartPadding(LayoutDirection.Ltr), end = paddingValues.calculateEndPadding(LayoutDirection.Ltr), ) .align(Alignment.BottomCenter), navigationIcon = { Icon( imageVector = Icons.Outlined.ArrowBack, contentDescription = null, modifier = Modifier .padding(16.dp) .size(30.dp) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberRipple( bounded = false, radius = 25.dp, color = Color.White, ), onClick = onBackArrowPressed ), tint = Color.White ) }, title = { Text( modifier = Modifier .padding(16.dp) .align(Alignment.BottomStart), text = topBarTitle, color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis, fontSize = 20.sp ) }, actions = { CollectionTopBarActions(actions) }, colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = Color.Transparent ) ) } } } @Composable private fun CollectionTopBarActions( actions: List<CollectionActions> ) { var dropDownMenuExpanded by remember { mutableStateOf(false) } Icon( imageVector = Icons.Outlined.MoreVert, contentDescription = null, modifier = Modifier .padding(16.dp) .size(30.dp) .rotate(90f) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberRipple( bounded = false, radius = 25.dp, color = Color.White, ), onClick = { dropDownMenuExpanded = true } ), tint = Color.White, ) OptionsDropDown( options = actions, expanded = dropDownMenuExpanded, onDismissRequest = { dropDownMenuExpanded = false }, offset = DpOffset(x = 0.dp, y = (-46).dp) ) }
5
Kotlin
8
97
332de5a4418cdcc5fdf837c846e30e76df4103c3
6,858
Zen
MIT License
app/src/main/java/com/sky/account/manager/data/disk/impl/AccountManagerImpl.kt
sky-wei
103,029,152
false
null
/* * Copyright (c) 2017 The sky 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 com.sky.account.manager.data.disk.impl import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import com.j256.ormlite.dao.Dao import com.sky.account.manager.data.DataException import com.sky.account.manager.data.disk.AccountManager import com.sky.account.manager.data.disk.DBManager import com.sky.account.manager.data.disk.converter.AccountConverter import com.sky.account.manager.data.disk.converter.AdminConverter import com.sky.account.manager.data.disk.entity.AccountEntity import com.sky.account.manager.data.disk.entity.AdminEntity import com.sky.account.manager.model.AccountModel import com.sky.account.manager.model.AdminModel import com.sky.account.manager.util.DialogUtil import com.sky.account.manager.util.Log import com.sky.account.manager.util.MD5Util import com.sky.account.manager.util.SecretUtil import io.reactivex.Observable import javafx.application.Platform import javafx.scene.control.Alert import java.io.File import java.util.* /** * Created by sky on 17-9-4. */ class AccountManagerImpl(dbManager: DBManager) : AccountManager { private val adminDao: Dao<AdminEntity, Int> = dbManager.getAdminDao() private val accountDao: Dao<AccountEntity, Int> = dbManager.getAccountDao() private var mAdmin: AdminModel = AdminModel() override fun createAdmin(model: AdminModel): Boolean { val admins = adminDao.queryForEq("name", model.name) if (admins.isNotEmpty()) return false val tempModel = model.copy() tempModel.password = <PASSWORD>(model.password) // 添加到数据库 if (adminDao.create( AdminConverter.converterModel(tempModel)) > 0) { val admins = adminDao.queryForEq("name", model.name) val adminModel = AdminConverter.converterEntity(admins[0]) // 设置未加密的密码 adminModel.password = <PASSWORD> mAdmin = adminModel return true } return false } override fun loginAdmin(model: AdminModel): Boolean { val admins = adminDao.queryForEq("name", model.name) if (admins.isEmpty()) return false val value = MD5Util.md5sum(model.password) if (admins[0].password == value) { val adminModel = AdminConverter.converterEntity(admins[0]) // 设置未加密的密码 adminModel.password = <PASSWORD> // 保存 mAdmin = adminModel return true } return false } override fun getAdmin(): AdminModel { return mAdmin } override fun changeAdminPassword(model: AdminModel): Observable<Boolean> { return Observable.create { try { // 解密的账号 val dAccounts = ArrayList<AccountModel>() // 查询所有账号 search(0, "").forEach { // 解密账号 dAccounts.add(decryptionAccount(it)) } // 更新管理员的密码 updateAdmin(model) dAccounts.forEach { // 更新账号 updateAccount(it) } it.onNext(true) it.onComplete() } catch (tr: Throwable) { it.onError(DataException("修改管理员密码异常!", tr)) } } } private fun updateAdmin(model: AdminModel): Boolean { val tempModel = model.copy() tempModel.password = <PASSWORD>(model.password) if (adminDao.update( AdminConverter.converterModel(tempModel)) > 0) { // 保存 mAdmin = model return true } return false } override fun search(type: Int, key: String): List<AccountModel> { if (key.isNullOrBlank()) { return AccountConverter.converterEntity( accountDao.queryForEq("adminId", mAdmin.id)) } return AccountConverter.converterEntity( accountDao.queryBuilder().where().eq("adminId", mAdmin.id).and().like("desc", "%$key%").query()) } override fun createAccount(model: AccountModel): Boolean { val encrypt = encryptAccount(model) return accountDao.create(AccountConverter.converterModel(encrypt)) > 0 } override fun deleteAccount(model: AccountModel): Boolean { return accountDao.deleteById(model.id) > 0 } override fun updateAccount(model: AccountModel): Boolean { val encrypt = encryptAccount(model) return accountDao.update(AccountConverter.converterModel(encrypt)) > 0 } override fun encryptAccount(model: AccountModel): AccountModel { val encrypt = model.copy() encrypt.password = SecretUtil.encrypt( mAdmin.password, model.password) return encrypt } override fun decryptionAccount(model: AccountModel): AccountModel { val decrypt = model.copy() decrypt.password = SecretUtil.decrypt( mAdmin.password, model.password) return decrypt } override fun importAccount(file: File): Observable<Boolean> { return Observable.create { try { // 获取账号信息 val accounts = Gson() .fromJson<List<AccountModel>>(file.readText()) accounts.forEach { // 创建账号 createAccount( it.copy(id = 0, adminId = mAdmin.id, createTime = System.currentTimeMillis())) } it.onNext(true) it.onComplete() } catch (tr: Throwable) { it.onError(DataException("导入账号异常", tr)) } } } override fun exportAccount(file: File): Observable<Boolean> { return Observable.create { try { // 解密的账号 val dAccounts = ArrayList<AccountModel>() // 查询所有账号 search(0, "").forEach { // 解密账号 dAccounts.add(decryptionAccount(it)) } val gson = GsonBuilder() .setPrettyPrinting() .create() // 保存到文件 file.writeText(gson.toJson(dAccounts)) it.onNext(true) it.onComplete() } catch (tr: Throwable) { it.onError(DataException("导出账号异常", tr)) } } } inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type) }
0
Kotlin
3
8
24be07c4f5521fddc4bac3f4933cb8c53468323e
7,279
java-polarbear
Apache License 2.0
src/main/kotlin/com/github/quanticheart/intellijplugincleantree/wizard/cleanArch/domain/repository/CleanArchRepository.kt
quanticheart
519,671,971
false
{"Kotlin": 115237, "Java": 237}
package com.github.quanticheart.intellijplugincleantree.wizard.cleanArch.domain.repository fun cleanArchRepository( featurePackage: String, featureName: String, repositoryName: String, domainModelPackage: String, domainModelRequestName: String, domainModelResponseName: String, ) = """ package $featurePackage import $domainModelPackage.$domainModelResponseName import $domainModelPackage.$domainModelRequestName interface $repositoryName { suspend fun get$featureName(mainStatus: $domainModelRequestName): Result<$domainModelResponseName> } """
0
Kotlin
0
0
92dfc1c111b991296c4575daa23522f4bc381339
577
intellij-plugin-cleantree
Apache License 2.0
common/src/main/kotlin/de/sambalmueslie/openevent/common/crud/BusinessObject.kt
Black-Forrest-Development
542,810,521
false
null
package de.sambalmueslie.openevent.common.crud interface BusinessObject<T> { val id: T }
1
Kotlin
0
1
317fbad90ec99908cc527b4082af0ba89525fe42
94
open-event
Apache License 2.0
Common/src/main/java/ram/talia/moreiotas/common/lib/MoreIotasIotaTypes.kt
Talia-12
565,479,446
false
null
package ram.talia.moreiotas.common.lib import at.petrak.hexcasting.api.spell.iota.Iota import at.petrak.hexcasting.api.spell.iota.IotaType import at.petrak.hexcasting.common.lib.hex.HexIotaTypes import net.minecraft.core.Registry import net.minecraft.resources.ResourceLocation import org.jetbrains.annotations.ApiStatus import ram.talia.moreiotas.api.MoreIotasAPI.modLoc import ram.talia.moreiotas.api.spell.iota.MatrixIota import ram.talia.moreiotas.api.spell.iota.StringIota import java.util.function.BiConsumer object MoreIotasIotaTypes { @JvmStatic @ApiStatus.Internal fun registerTypes() { val r = BiConsumer { type: IotaType<*>, id: ResourceLocation -> Registry.register(HexIotaTypes.REGISTRY, id, type) } for ((key, value) in TYPES) { r.accept(value, key) } } private val TYPES: MutableMap<ResourceLocation, IotaType<*>> = LinkedHashMap() @JvmField val STRING_TYPE: IotaType<StringIota> = type("string", StringIota.TYPE) @JvmField val MATRIX_TYPE: IotaType<MatrixIota> = type("matrix", MatrixIota.TYPE) private fun <U : Iota, T : IotaType<U>> type(name: String, type: T): T { val old = TYPES.put(modLoc(name), type) require(old == null) { "Typo? Duplicate id $name" } return type } }
5
Kotlin
4
1
3dd3c0ccc1933cbd5dcb4b60aabfd2a6e911b940
1,300
MoreIotas
MIT License
src/main/kotlin/com/kneelawk/notsosimplepipes/client/screen/ScreenPipeFluidSource.kt
Kneelawk
443,305,417
false
null
package com.kneelawk.notsosimplepipes.client.screen import com.kneelawk.notsosimplepipes.handler.HandlerPipeFluidSource import net.minecraft.entity.player.PlayerInventory import net.minecraft.text.Text import spinnery.client.screen.BaseHandledScreen import spinnery.widget.WAbstractWidget import spinnery.widget.WPanel import spinnery.widget.WSlot import spinnery.widget.api.Position import spinnery.widget.api.Size class ScreenPipeFluidSource(handler: HandlerPipeFluidSource, playerInv: PlayerInventory, name: Text) : BaseHandledScreen<HandlerPipeFluidSource>(handler, playerInv, name) { init { val mainPanel = `interface`.createChild( ::WPanel, Position.of(0f, 0f, 0f), Size.of(16f + 9f * 18f, 16f + 14f + 5f * 18f + 8f) ) mainPanel.setLabel<WPanel>(name) mainPanel.setOnAlign(WAbstractWidget::center) mainPanel.center() `interface`.add(mainPanel) `interface`.createChild( ::WSlot, Position.of(mainPanel, 8f + 4f * 18f, 8f + 14f), Size.of(18f, 18f) ).setSlotNumber<WSlot>(0).setInventoryNumber<WSlot>(HandlerPipeFluidSource.PIPE_INVENTORY) WSlot.addPlayerInventory(Position.of(mainPanel, 8f, 8f + 14f + 18f + 4f), Size.of(18f, 18f), `interface`) } }
0
Kotlin
0
0
cb7120c4282871ce17a730d489e05550ec0e85da
1,339
NotSoSimplePipes
MIT License
src/userCLI/src/test/kotlin/org/vaccineimpact/api/security/tests/AddUserToGroupOptionsTests.kt
vimc
85,062,678
false
null
package org.vaccineimpact.api.security.tests import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.Test import org.vaccineimpact.api.security.ActionException import org.vaccineimpact.api.security.AddUserToGroupOptions import org.vaccineimpact.api.security.Groups import org.vaccineimpact.api.test_helpers.MontaguTests class AddUserToGroupOptionsTests : MontaguTests() { @Test fun `can parse one group`() { val options = AddUserToGroupOptions.parseArgs(listOf("username", "group")) assertThat(options).isEqualTo(AddUserToGroupOptions( "username", Groups.GroupList(listOf("group")) )) } @Test fun `can parse multiple groups`() { val options = AddUserToGroupOptions.parseArgs(listOf("username", "a", "b", "c")) assertThat(options).isEqualTo(AddUserToGroupOptions( "username", Groups.GroupList(listOf("a", "b", "c")) )) } @Test fun `can parse ALL group option`() { val options = AddUserToGroupOptions.parseArgs(listOf("username", "ALL")) assertThat(options).isEqualTo(AddUserToGroupOptions( "username", Groups.AllGroups() )) } @Test fun `cannot combine ALL group option with group list`() { assertThatThrownBy { AddUserToGroupOptions.parseArgs(listOf("username", "ALL", "group")) } .isInstanceOf(ActionException::class.java) } @Test fun `throws exception if not enough arguments are supplied`() { assertThatThrownBy { AddUserToGroupOptions.parseArgs(emptyList()) } assertThatThrownBy { AddUserToGroupOptions.parseArgs(listOf("username")) } } }
1
null
1
2
0b3acb5f22b71300d6c260c5ecb252b0bddbe6ea
1,804
montagu-api
MIT License
ideamc-core/src/org/imcl/core/network/NetworkState.kt
ResetPower
451,759,768
false
{"Kotlin": 156599, "Java": 19713}
package org.imcl.core.network import java.io.IOException import java.io.InputStream import java.net.MalformedURLException import java.net.URL object NetworkState { @JvmStatic fun isConnectedToInternet(): Boolean { try { val url = URL("http://baidu.com") try { val `in`: InputStream = url.openStream() `in`.close() return true } catch (e: IOException) { return false } } catch (e: MalformedURLException) { return false } } }
0
Kotlin
0
1
7b1017b549986a8fd49e47d3ea98b8e42fec81a7
586
ideamc
Apache License 2.0
app/src/main/java/com/ibashkimi/tris/model/Board.kt
indritbashkimi
229,824,844
false
null
package com.ibashkimi.tris.model import android.os.Parcelable import kotlinx.android.parcel.IgnoredOnParcel import kotlinx.android.parcel.Parcelize import java.util.* @Parcelize class Board(val array: IntArray = IntArray(9)) : Parcelable { val availableMoves: List<Int> get() = array.filterEmpty() @IgnoredOnParcel var movesCount: Int private set val isGameOver: Boolean get() = winningMoves != null || movesCount == 9 @IgnoredOnParcel val state: State get() { return if (!isGameOver) State.Going else { if (winningSeed == null) State.Ended.Draw else State.Ended.WithWinner(winningSeed!!, winningMoves!!) } } sealed class State { object Going : State() sealed class Ended : State() { object Draw : Ended() data class WithWinner(val seed: Int, val moves: List<Int>) : Ended() } } @IgnoredOnParcel var winningSeed: Int? = null @IgnoredOnParcel var winningMoves: List<Int>? = null init { movesCount = array.filterNotEmpty().size checkWinner() } fun occupy(position: Int, seed: Int) { when { isGameOver -> { throw Exception("Game is over. Cannot occupy cell. Reset board first.") } array[position] != EMPTY -> { throw Exception("Position $position is not free. board[$position] = ${array[position]}") } seed == EMPTY -> { throw Exception("Invalid playerSeed ${seed}. It's reserved for empty cells.") } else -> { array[position] = seed movesCount++ checkWinner() if (winningMoves != null) { winningSeed = seed } else if (movesCount == 9) { winningSeed = null } } } } fun reset() { for (i in array.indices) array[i] = EMPTY winningSeed = null winningMoves = null movesCount = 0 } private fun checkWinner() { var moves: ArrayList<Int>? = null for (line in lines) { if (array[line[0]] != EMPTY && array[line[0]] == array[line[1]] && array[line[1]] == array[line[2]]) { if (moves == null) moves = ArrayList(6) moves.add(line[0]) moves.add(line[1]) moves.add(line[2]) winningSeed = array[line[0]] } } winningMoves = moves } private fun IntArray.filterEmpty(): List<Int> = indices.filter { this[it] == EMPTY } private fun IntArray.filterNotEmpty(): List<Int> = indices.filter { this[it] != EMPTY } companion object { @Transient val lines = arrayOf( intArrayOf(0, 1, 2), intArrayOf(3, 4, 5), intArrayOf(6, 7, 8), intArrayOf(0, 3, 6), intArrayOf(1, 4, 7), intArrayOf(2, 5, 8), intArrayOf(0, 4, 8), intArrayOf(2, 4, 6) ) const val EMPTY = 0 const val PLAYER_1 = 1 const val PLAYER_2 = 2 } }
0
null
1
3
b4fa88ef31a8816344d8de8f6a982f64977b7ebf
3,341
ttt-xo
Apache License 2.0
app/src/main/java/tmidev/localaccount/util/LaIcons.kt
tminet
574,995,467
false
null
package tmidev.localaccount.util import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Android import androidx.compose.material.icons.rounded.Clear import androidx.compose.material.icons.rounded.DarkMode import androidx.compose.material.icons.rounded.Email import androidx.compose.material.icons.rounded.LightMode import androidx.compose.material.icons.rounded.Logout import androidx.compose.material.icons.rounded.NavigateBefore import androidx.compose.material.icons.rounded.Password import androidx.compose.material.icons.rounded.Person import androidx.compose.material.icons.rounded.Settings import androidx.compose.material.icons.rounded.Visibility import androidx.compose.material.icons.rounded.VisibilityOff /** * Local Account icons. */ object LaIcons { val NavigateBefore = Icons.Rounded.NavigateBefore val Settings = Icons.Rounded.Settings val Clear = Icons.Rounded.Clear val Visibility = Icons.Rounded.Visibility val VisibilityOff = Icons.Rounded.VisibilityOff val Person = Icons.Rounded.Person val Email = Icons.Rounded.Email val Password = Icons.Rounded.Password val Logout = Icons.Rounded.Logout val Android = Icons.Rounded.Android val DarkMode = Icons.Rounded.DarkMode val LightMode = Icons.Rounded.LightMode }
0
Kotlin
1
3
db2f3c56b01b74b8cf5eefec449f732cc289cf45
1,315
LocalAccount
MIT License
app/src/main/kotlin/taiwan/no1/app/mvp/presenters/fragment/TvEpisodePresenter.kt
bearfong
88,131,690
true
{"Kotlin": 306879, "Java": 197491}
package taiwan.no1.app.mvp.presenters.fragment import taiwan.no1.app.mvp.contracts.fragment.TvEpisodeContract /** * * @author Jieyi * @since 3/6/17 */ class TvEpisodePresenter: BasePresenter<TvEpisodeContract.View>(), TvEpisodeContract.Presenter { //region View implementation override fun init(view: TvEpisodeContract.View) { super.init(view) } //endregion }
0
Kotlin
0
0
95ed2604d30585a29f602d516e3889dcd7dda042
393
mvp-magazine
Apache License 2.0
foundation/analytics/main/ru/pixnews/foundation/analytics/NoOpAnalytics.kt
illarionov
305,333,284
false
null
/* * Copyright 2023 <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 ru.pixnews.foundation.analytics public class NoOpAnalytics : Analytics { public override fun setCurrentScreenName(screenName: String, screenClass: String): Unit = Unit public override fun setEnableAnalytics(enable: Boolean): Unit = Unit public override fun setUserId(userId: String?): Unit = Unit public override fun setUserProperty(name: String, value: String): Unit = Unit public override fun logEvent(name: String, params: Map<String, *>?): Unit = Unit }
0
Kotlin
0
2
8912bf1116dd9fe94d110162ff9a302e93af1509
1,081
Pixnews
Apache License 2.0
src/main/kotlin/com/example/militaryservicecompanychecker/company/controller/CompanyController.kt
Ji-InPark
538,543,045
false
{"Kotlin": 26302, "Dockerfile": 143}
package com.example.militaryservicecompanychecker.company.controller import com.example.militaryservicecompanychecker.common.util.Util.safeValueOf import com.example.militaryservicecompanychecker.company.controller.dto.CompanyAutoCompleteRequest import com.example.militaryservicecompanychecker.company.controller.dto.CompanyAutoCompleteResponse import com.example.militaryservicecompanychecker.company.controller.dto.CompanyRequest import com.example.militaryservicecompanychecker.company.controller.dto.CompanyResponse import com.example.militaryservicecompanychecker.company.enums.GovernmentLocation import com.example.militaryservicecompanychecker.company.enums.Sector import com.example.militaryservicecompanychecker.company.enums.ServiceType import com.example.militaryservicecompanychecker.company.service.CompanyService import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.web.bind.annotation.* @RestController @CrossOrigin(origins = ["https://k-agent.services/", "http://localhost:3000/"]) class CompanyController( private val companyService: CompanyService, private val passwordEncoder: BCryptPasswordEncoder ) { @PostMapping("/search/autocomplete") fun searchCompanyByRegex(@RequestBody request: CompanyAutoCompleteRequest): CompanyAutoCompleteResponse { return CompanyAutoCompleteResponse( companyService.searchCompanyByRegex(request.regex).map { it.companyName } ) } @PostMapping("/search") fun searchCompany(@RequestBody request: CompanyRequest): CompanyResponse { return CompanyResponse( companyService.searchCompany( request.companyName.toString(), safeValueOf<GovernmentLocation>(request.governmentLocation.toString()), safeValueOf<Sector>(request.sector.toString()) ) ) } @GetMapping("/government-locations") fun getGovernmentLocations(): Array<GovernmentLocation> { return companyService.getGovernmentLocations() } @GetMapping("/sectors") fun getSectors(): Array<Sector> { return companyService.getSectors() } @GetMapping("/serviceTypes") fun getServiceTypes(): Array<ServiceType> { return companyService.getServiceTypes() } @GetMapping("/wanted-insight/{id}") fun getWantedInsightKey(@PathVariable("id") id: Long): String? { return companyService.getOrRequestWantedInsightKey(id) } @PostMapping("/company") fun updateCompany( @RequestPart("password") password: String ): Any { if (!passwordEncoder.matches( password, System.getenv("ADMIN_PASSWORD") ) ) return "비밀번호가 틀렸습니다." return CompanyResponse( companyService.updateCompanyInfoByBYIS() ) } }
0
Kotlin
0
1
5e911546e8264a8452889826932a5fae7c066f8f
2,860
k-agent.service-api
MIT License
benchmark/benchmark-common/src/androidTest/java/androidx/benchmark/ShellBehaviorTest.kt
androidx
256,589,781
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.benchmark import android.os.Build import android.os.Process import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue import org.junit.Test import org.junit.runner.RunWith /** * This class collects tests of strange shell behavior, for the purpose of documenting * and validating how general the problems are. */ @MediumTest @SdkSuppress(minSdkVersion = 21) @RunWith(AndroidJUnit4::class) class ShellBehaviorTest { /** * Test validates consistent behavior of pgrep, for usage in discovering processes without * needing to check stderr */ @Test fun pgrepLF() { // Should only be one process - this one! val pgrepOutput = Shell.executeScriptCaptureStdoutStderr("pgrep -l -f ${Packages.TEST}") if (Build.VERSION.SDK_INT >= 23) { // API 23 has trailing whitespace after the package name for some reason :shrug: val regex = "^\\d+ ${Packages.TEST.replace(".", "\\.")}\\s*$".toRegex() assertTrue( // For some reason, `stdout.contains(regex)` doesn't work :shrug: pgrepOutput.stdout.lines().any { it.matches(regex) }, "expected $regex to be contained in output:\n${pgrepOutput.stdout}" ) } else { // command doesn't exist assertEquals("", pgrepOutput.stdout) assertTrue(pgrepOutput.stderr.isNotBlank()) } } @Test fun pidof() { // Should only be one process - this one! val output = Shell.executeScriptCaptureStdoutStderr("pidof ${Packages.TEST}") val pidofString = output.stdout.trim() when { Build.VERSION.SDK_INT < 23 -> { // command doesn't exist assertTrue( output.stdout.isBlank() && output.stderr.isNotBlank(), "saw output $output" ) } Build.VERSION.SDK_INT == 23 -> { // on API 23 specifically, pidof prints... all processes, ignoring the arg... assertTrue(pidofString.contains(" ")) } else -> { assertNotNull(pidofString.toLongOrNull(), "Error, can't parse $pidofString") } } } @Test fun psDashA() { val output = Shell.executeScriptCaptureStdout("ps -A").trim() when { Build.VERSION.SDK_INT <= 23 -> { // doesn't correctly handle -A, sometimes sees nothing, sometimes only this process val processes = output.lines() assertTrue(processes.size <= 2) assertTrue(processes.first().matches(psLabelRowRegex)) if (processes.size > 1) { assertTrue(processes.last().endsWith(Packages.TEST)) } } Build.VERSION.SDK_INT in 24..25 -> { // still doesn't support, but useful error at least assertEquals("bad pid '-A'", output) } else -> { // ps -A should work - expect several processes including this one val processes = output.lines() assertTrue(processes.size > 5) assertTrue(processes.first().matches(psLabelRowRegex)) assertTrue(processes.any { it.endsWith(Packages.TEST) }) } } } /** * Test validates consistent behavior of ps, for usage in checking process is alive without * needing to check stderr */ @Test fun ps() { val output = Shell.executeScriptCaptureStdout("ps ${Process.myPid()}").trim() // ps should work - expect several processes including this one val lines = output.lines() assertEquals(2, lines.size) assertTrue(lines.first().matches(psLabelRowRegex)) assertTrue(lines.last().endsWith(Packages.TEST)) } companion object { /** * Regex for matching ps output label row * * Note that `ps` output changes over time, e.g.: * * * API 23 - `USER\s+PID\s+PPID\s+VSIZE\s+RSS\s+WCHAN\s+PC\s+NAME` * * API 33 - `USER\s+PID\s+PPID\s+VSZ\s+RSS\s+WCHAN\s+ADDR\s+S\s+NAME\s` */ val psLabelRowRegex = Regex("USER\\s+PID.+NAME\\s*") } }
28
null
937
5,108
89ec14e39cf771106a8719337062572717cbad31
5,109
androidx
Apache License 2.0
kotlin-mui-icons/src/main/generated/mui/icons/material/HighQualitySharp.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/HighQualitySharp") @file:JsNonModule package mui.icons.material @JsName("default") external val HighQualitySharp: SvgIconComponent
12
Kotlin
145
983
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
214
kotlin-wrappers
Apache License 2.0
features/src/main/kotlin/com/leonards/tmdb/features/favorite/presentation/fragment/BaseFavoriteFragment.kt
Leonards03
370,141,672
false
null
package com.leonards.tmdb.features.favorite.presentation.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.LinearLayoutManager import com.leonards.tmdb.app.extension.intentToDetailsActivity import com.leonards.tmdb.app.utils.AppPreferences import com.leonards.tmdb.core.domain.model.DomainModel import com.leonards.tmdb.core.extension.invisible import com.leonards.tmdb.core.extension.visible import com.leonards.tmdb.core.presentation.adapter.FavoriteAdapter import com.leonards.tmdb.features.databinding.FragmentFavoriteBinding import com.leonards.tmdb.features.favorite.presentation.factory.ViewModelFactory import com.leonards.tmdb.features.favorite.ui.FavoriteViewModel import javax.inject.Inject abstract class BaseFavoriteFragment<T : DomainModel> : Fragment() { private var binding: FragmentFavoriteBinding? = null private lateinit var adapter: FavoriteAdapter<T> @Inject lateinit var factory: ViewModelFactory @Inject lateinit var appPreferences: AppPreferences protected val viewModel: FavoriteViewModel by activityViewModels { factory } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { binding = FragmentFavoriteBinding.inflate(layoutInflater, container, false) return binding?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupRecyclerView() loadData() } private fun setupRecyclerView() = binding?.apply { adapter = FavoriteAdapter(appPreferences.getImageSize(), ::intentToDetailsActivity) rvFavorite.setHasFixedSize(true) rvFavorite.layoutManager = LinearLayoutManager(context) rvFavorite.adapter = adapter } protected abstract fun loadData() protected fun render(list: List<T>) { adapter.submitData(list) binding?.apply { if (list.isEmpty()) { stateEmpty.root.visible() } else { stateEmpty.root.invisible() } } } override fun onDestroyView() { binding = null super.onDestroyView() } }
0
Kotlin
0
0
b7663c774cbf81d411d1faf32796cee6bee03399
2,422
TheMovieDB-Dummy
Apache License 2.0
step-builder/src/main/kotlin/io/kommons/designpatterns/stepbuilder/App.kt
debop
235,066,649
false
null
package io.kommons.designpatterns.stepbuilder class App fun main() { val warrier = CharacterStepBuilder.newBuilder() .name("Amberjill") .fighterClass("Paladin") .withWeapon("Sword") .noAbilities() .build() println(warrier) val mage = CharacterStepBuilder.newBuilder() .name("Riobard") .wizardClass("Sorcerer") .withSpell("Fireball") .withAbility("Fire Aura") .withAbility("Teleport") .noMoreAbilities() .build() println(mage) val thief = CharacterStepBuilder.newBuilder() .name("Desmond") .fighterClass("Rogue") .noWeapon() .build() println(thief) }
0
Kotlin
11
53
c00bcc0542985bbcfc4652d0045f31e5c1304a70
709
kotlin-design-patterns
Apache License 2.0
app/src/main/java/com/example/project2wishlis/UserData.kt
BRuff5
727,838,162
false
{"Kotlin": 4321}
package com.example.project2wishlis class UserData(var name: String, var url: String, var price: String)
0
Kotlin
0
0
b123a8ded2214670b2a00be80ab37c014ca4b169
105
Project2-wishlist
Apache License 2.0
actions/javatests/com/squareup/tools/sqldelight/cli/ArgsTest.kt
cgruber
360,700,058
false
null
package com.squareup.tools.sqldelight.cli import com.xenomachina.argparser.ShowHelpException import com.xenomachina.argparser.SystemExitException import org.junit.Assert.assertThrows import org.junit.Test class ArgsTest { @Test fun help() { val args = arrayOf("--help") assertThrows(ShowHelpException::class.java) { realMain(args) } } @Test fun badDialect() { val args = arrayOf("--database_dialect=FOOSQL") val e = assertThrows(SystemExitException::class.java) { realMain(args) } assert(e.message!!.contains("Invalid dialect \"FOOSQL\". Should be one of: SQLITE_3_18")) } }
1
null
1
1
5de2119368ae35532275a291a82d832adb3cb012
630
sqldelight_bazel_rules
Apache License 2.0
opendc-simulator/opendc-simulator-resources/src/main/kotlin/org/opendc/simulator/resources/SimResourceDistributorMaxMin.kt
Koen1999
419,678,775
true
{"Kotlin": 1112148, "Jupyter Notebook": 275743, "JavaScript": 264579, "Shell": 133323, "Python": 101126, "Sass": 7151, "HTML": 3690, "Dockerfile": 1742}
/* * Copyright (c) 2021 AtLarge Research * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.opendc.simulator.resources import kotlin.math.max import kotlin.math.min /** * A [SimResourceDistributor] that distributes the capacity of a resource over consumers using max-min fair sharing. */ public class SimResourceDistributorMaxMin( override val input: SimResourceProvider, private val scheduler: SimResourceScheduler, private val listener: Listener? = null ) : SimResourceDistributor { override val outputs: Set<SimResourceProvider> get() = _outputs private val _outputs = mutableSetOf<OutputProvider>() /** * The active output contexts. */ private val outputContexts: MutableList<OutputContext> = mutableListOf() /** * The total speed requested by the output resources. */ private var totalRequestedSpeed = 0.0 /** * The total amount of work requested by the output resources. */ private var totalRequestedWork = 0.0 /** * The total allocated speed for the output resources. */ private var totalAllocatedSpeed = 0.0 /** * The total allocated work requested for the output resources. */ private var totalAllocatedWork = 0.0 /** * The amount of work that could not be performed due to over-committing resources. */ private var totalOvercommittedWork = 0.0 /** * The amount of work that was lost due to interference. */ private var totalInterferedWork = 0.0 /** * A flag to indicate that the switch is closed. */ private var isClosed: Boolean = false /** * An internal [SimResourceConsumer] implementation for switch inputs. */ private val consumer = object : SimResourceConsumer { /** * The resource context of the consumer. */ private lateinit var ctx: SimResourceContext val remainingWork: Double get() = ctx.remainingWork override fun onNext(ctx: SimResourceContext): SimResourceCommand { return doNext(ctx.capacity) } override fun onEvent(ctx: SimResourceContext, event: SimResourceEvent) { when (event) { SimResourceEvent.Start -> { this.ctx = ctx } SimResourceEvent.Exit -> { val iterator = _outputs.iterator() while (iterator.hasNext()) { val output = iterator.next() // Remove the output from the outputs to prevent ConcurrentModificationException when removing it // during the call to output.close() iterator.remove() output.close() } } else -> {} } } } /** * The total amount of remaining work. */ private val totalRemainingWork: Double get() = consumer.remainingWork override fun addOutput(capacity: Double): SimResourceProvider { check(!isClosed) { "Distributor has been closed" } val provider = OutputProvider(capacity) _outputs.add(provider) return provider } override fun close() { if (!isClosed) { isClosed = true input.cancel() } } init { input.startConsumer(consumer) } /** * Indicate that the workloads should be re-scheduled. */ private fun schedule() { input.interrupt() } /** * Schedule the work over the physical CPUs. */ private fun doSchedule(capacity: Double): SimResourceCommand { // If there is no work yet, mark all inputs as idle. if (outputContexts.isEmpty()) { return SimResourceCommand.Idle() } val maxUsage = capacity var duration: Double = Double.MAX_VALUE var deadline: Long = Long.MAX_VALUE var availableSpeed = maxUsage var totalRequestedSpeed = 0.0 var totalRequestedWork = 0.0 // Flush the work of the outputs var outputIterator = outputContexts.listIterator() while (outputIterator.hasNext()) { val output = outputIterator.next() output.flush(isIntermediate = true) if (output.activeCommand == SimResourceCommand.Exit) { // Apparently the output consumer has exited, so remove it from the scheduling queue. outputIterator.remove() } } // Sort the outputs based on their requested usage // Profiling shows that it is faster to sort every slice instead of maintaining some kind of sorted set outputContexts.sort() // Divide the available input capacity fairly across the outputs using max-min fair sharing outputIterator = outputContexts.listIterator() var remaining = outputContexts.size while (outputIterator.hasNext()) { val output = outputIterator.next() val availableShare = availableSpeed / remaining-- when (val command = output.activeCommand) { is SimResourceCommand.Idle -> { // Take into account the minimum deadline of this slice before we possible continue deadline = min(deadline, command.deadline) output.actualSpeed = 0.0 } is SimResourceCommand.Consume -> { val grantedSpeed = min(output.allowedSpeed, availableShare) // Take into account the minimum deadline of this slice before we possible continue deadline = min(deadline, command.deadline) // Ignore idle computation if (grantedSpeed <= 0.0 || command.work <= 0.0) { output.actualSpeed = 0.0 continue } totalRequestedSpeed += command.limit totalRequestedWork += command.work output.actualSpeed = grantedSpeed availableSpeed -= grantedSpeed // The duration that we want to run is that of the shortest request from an output duration = min(duration, command.work / grantedSpeed) } SimResourceCommand.Exit -> assert(false) { "Did not expect output to be stopped" } } } assert(deadline >= scheduler.clock.millis()) { "Deadline already passed" } this.totalRequestedSpeed = totalRequestedSpeed this.totalRequestedWork = totalRequestedWork this.totalAllocatedSpeed = maxUsage - availableSpeed this.totalAllocatedWork = min(totalRequestedWork, totalAllocatedSpeed * duration) return if (totalAllocatedWork > 0.0 && totalAllocatedSpeed > 0.0) SimResourceCommand.Consume(totalAllocatedWork, totalAllocatedSpeed, deadline) else SimResourceCommand.Idle(deadline) } /** * Obtain the next command to perform. */ private fun doNext(capacity: Double): SimResourceCommand { val totalRequestedWork = totalRequestedWork.toLong() val totalRemainingWork = totalRemainingWork.toLong() val totalAllocatedWork = totalAllocatedWork.toLong() val totalRequestedSpeed = totalRequestedSpeed val totalAllocatedSpeed = totalAllocatedSpeed // Force all inputs to re-schedule their work. val command = doSchedule(capacity) // Report metrics listener?.onSliceFinish( this, totalRequestedWork, totalAllocatedWork - totalRemainingWork, totalOvercommittedWork.toLong(), totalInterferedWork.toLong(), totalAllocatedSpeed, totalRequestedSpeed ) totalInterferedWork = 0.0 totalOvercommittedWork = 0.0 return command } /** * Event listener for hypervisor events. */ public interface Listener { /** * This method is invoked when a slice is finished. */ public fun onSliceFinish( switch: SimResourceDistributor, requestedWork: Long, grantedWork: Long, overcommittedWork: Long, interferedWork: Long, cpuUsage: Double, cpuDemand: Double ) } /** * An internal [SimResourceProvider] implementation for switch outputs. */ private inner class OutputProvider(val capacity: Double) : SimResourceProvider { /** * The [OutputContext] that is currently running. */ private var ctx: OutputContext? = null override var state: SimResourceState = SimResourceState.Pending internal set override fun startConsumer(consumer: SimResourceConsumer) { check(state == SimResourceState.Pending) { "Resource cannot be consumed" } val ctx = OutputContext(this, consumer) this.ctx = ctx this.state = SimResourceState.Active outputContexts += ctx ctx.start() schedule() } override fun close() { cancel() if (state != SimResourceState.Stopped) { state = SimResourceState.Stopped _outputs.remove(this) } } override fun interrupt() { ctx?.interrupt() } override fun cancel() { val ctx = ctx if (ctx != null) { this.ctx = null ctx.stop() } if (state != SimResourceState.Stopped) { state = SimResourceState.Pending } } } /** * A [SimAbstractResourceContext] for the output resources. */ private inner class OutputContext( private val provider: OutputProvider, consumer: SimResourceConsumer ) : SimAbstractResourceContext(provider.capacity, scheduler, consumer), Comparable<OutputContext> { /** * The current command that is processed by the vCPU. */ var activeCommand: SimResourceCommand = SimResourceCommand.Idle() /** * The processing speed that is allowed by the model constraints. */ var allowedSpeed: Double = 0.0 /** * The actual processing speed. */ var actualSpeed: Double = 0.0 private fun reportOvercommit() { val remainingWork = remainingWork totalOvercommittedWork += remainingWork } override fun onIdle(deadline: Long) { reportOvercommit() allowedSpeed = 0.0 activeCommand = SimResourceCommand.Idle(deadline) } override fun onConsume(work: Double, limit: Double, deadline: Long) { reportOvercommit() allowedSpeed = speed activeCommand = SimResourceCommand.Consume(work, limit, deadline) } override fun onFinish() { reportOvercommit() activeCommand = SimResourceCommand.Exit provider.cancel() } override fun getRemainingWork(work: Double, speed: Double, duration: Long): Double { // Apply performance interference model val performanceScore = 1.0 // Compute the remaining amount of work return if (work > 0.0) { // Compute the fraction of compute time allocated to the VM val fraction = actualSpeed / totalAllocatedSpeed // Compute the work that was actually granted to the VM. val processingAvailable = max(0.0, totalAllocatedWork - totalRemainingWork) * fraction val processed = processingAvailable * performanceScore val interferedWork = processingAvailable - processed totalInterferedWork += interferedWork max(0.0, work - processed) } else { 0.0 } } private var isProcessing: Boolean = false override fun interrupt() { // Prevent users from interrupting the CPU while it is constructing its next command, this will only lead // to infinite recursion. if (isProcessing) { return } try { isProcessing = false super.interrupt() // Force the scheduler to re-schedule schedule() } finally { isProcessing = true } } override fun compareTo(other: OutputContext): Int = allowedSpeed.compareTo(other.allowedSpeed) } }
0
Kotlin
0
0
f9b43518d2d50f33077734537a477539fca9f5b7
13,928
opendc
MIT License
src/main/kotlin/org/teamvoided/dusk_autumn/init/worldgen/DuskFeatures.kt
TeamVoided
737,359,498
false
{"Kotlin": 562878, "Java": 6328}
package org.teamvoided.dusk_autumn.init.worldgen import net.minecraft.registry.Registries import net.minecraft.registry.Registry import net.minecraft.world.gen.feature.Feature import net.minecraft.world.gen.feature.FeatureConfig import org.teamvoided.dusk_autumn.DuskAutumns import org.teamvoided.dusk_autumn.world.gen.configured_feature.FarmlandFeature import org.teamvoided.dusk_autumn.world.gen.configured_feature.config.FarmlandConfig object DuskFeatures { val FARMLAND = register("farmland_feature", FarmlandFeature(FarmlandConfig.CODEC)) fun init() = Unit private fun <C : FeatureConfig, F : Feature<C>> register(name: String, feature: F): F = Registry.register(Registries.FEATURE, DuskAutumns.id(name), feature) }
0
Kotlin
0
0
ffc85325250110d8426a4bcacbb5a3ca00f5debd
744
DusksAndDungeons
MIT License
groups/group_member_click_listener.kt
nitish098123
481,869,940
false
null
package com.example.database_part_3.groups // for horizontal recycleView of group members interface group_member_click_listener{ fun click_listener(position : Int){ // listen the position of clicked item of horizontal recycleView } }
1
Kotlin
0
1
61ef3ffb99db93ece011f701a55804cb8fedf211
248
Sofessist-a-messaging-specialist
Apache License 2.0
transport/src/main/kotlin/br/com/guiabolso/hyperloop/transport/aws/SQSTransport.kt
GuiaBolso
139,899,515
false
{"Kotlin": 86515}
package br.com.guiabolso.hyperloop.transport.aws import br.com.guiabolso.hyperloop.exceptions.SendMessageException import br.com.guiabolso.hyperloop.md5 import br.com.guiabolso.hyperloop.transport.Transport import com.amazonaws.regions.Regions import com.amazonaws.services.sqs.AmazonSQSClientBuilder import com.amazonaws.services.sqs.model.SendMessageRequest class SQSTransport( private val queueURL: String, region: Regions ) : Transport { private val sqs = AmazonSQSClientBuilder .standard() .withRegion(region) .build() override fun sendMessage(message: String) { val sendMessageRequest = SendMessageRequest() .withQueueUrl(queueURL) .withMessageBody(message) val messageResult = sqs.sendMessage(sendMessageRequest) if (messageResult.mD5OfMessageBody != message.md5()) { throw SendMessageException("Transport could not deliver message correctly! MD5 from event differs from MD5 of transport.") } } }
0
Kotlin
5
0
87f016bf178e3b70152a9cd013249c20d76930c6
1,021
hyperloop
Apache License 2.0
shared/src/commonMain/kotlin/com/vickikbt/shared/data/cache/realm/models/PlanEntity.kt
VictorKabata
451,854,817
false
{"Kotlin": 211021, "Swift": 19405, "Ruby": 2077}
package com.vickikbt.shared.data.cache.realm.models import io.realm.kotlin.types.RealmObject open class PlanEntity : RealmObject { var collaborators: Int? = null var name: String? = null var privateRepos: Int? = null var space: Int? = null }
1
Kotlin
4
39
c076838dd5daab9025041025fbeb5e151fd68e10
260
Gistagram
MIT License
app/src/main/java/com/bruce32/psnprofileviewer/database/ProfileDatabase.kt
jbruce2112
509,893,709
false
{"Kotlin": 139600}
package com.bruce32.psnprofileviewer.database import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.bruce32.psnprofileviewer.model.CurrentUser import com.bruce32.psnprofileviewer.model.Game import com.bruce32.psnprofileviewer.model.Profile import com.bruce32.psnprofileviewer.model.Trophy @Database( entities = [Profile::class, Game::class, Trophy::class, CurrentUser::class], version = 1, exportSchema = false ) @TypeConverters(ProfileTypeConverters::class) abstract class ProfileDatabase : RoomDatabase() { abstract fun profileDao(): ProfileDao }
0
Kotlin
0
1
d9b26d225b4b49127027d826f8dcf2988981bb09
624
psnprofile-viewer
MIT License
src/main/kotlin/org/serenityos/jakt/stubs/JaktFileStub.kt
mattco98
494,614,613
false
null
package org.serenityos.jakt.stubs import com.intellij.psi.stubs.PsiFileStubImpl import com.intellij.psi.tree.IStubFileElementType import org.serenityos.jakt.JaktFile import org.serenityos.jakt.JaktLanguage class JaktFileStub(file: JaktFile?): PsiFileStubImpl<JaktFile>(file) { object Type : IStubFileElementType<JaktFileStub>(JaktLanguage) { // Should be incremented when lexer, parser, or stub tree changes override fun getStubVersion() = 7 } }
3
Kotlin
3
14
c57f43c1ba5a9aef0def7017a454ac16417b1053
472
jakt-intellij-plugin
MIT License