path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/realtyna/realtyfeedsdksample/MainActivity.kt | realtyna | 592,809,856 | false | null | package com.realtyna.realtyfeedsdksample
import android.os.Bundle
import android.util.Log
import android.widget.RadioGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatRadioButton
import androidx.appcompat.widget.AppCompatTextView
import com.realtyna.realtyfeedsdk.RealtyFeedSDK
import com.realtyna.realtyfeedsdk.API
import org.json.JSONObject
import java.util.Date
class MainActivity : AppCompatActivity() {
lateinit var radioGroup: RadioGroup
lateinit var rbtnListings: AppCompatRadioButton
lateinit var rbtnProperty: AppCompatRadioButton
lateinit var btnCheckData: AppCompatButton
lateinit var edAPIKey: AppCompatEditText
lateinit var edRapidAPIKey: AppCompatEditText
lateinit var tvResult: AppCompatTextView
lateinit var prefHelper: PreferenceHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
prefHelper = PreferenceHelper(this)
radioGroup = findViewById(R.id.radioGroup)
rbtnListings = findViewById(R.id.listings)
rbtnProperty = findViewById(R.id.property)
btnCheckData = findViewById(R.id.btnCheckData)
edAPIKey = findViewById(R.id.edAPIKey)
edRapidAPIKey = findViewById(R.id.edRapidAPIKey)
tvResult = findViewById(R.id.tvResult)
radioGroup.setOnCheckedChangeListener { group, checkedId ->
when (checkedId) {
R.id.listings -> {
rbtnProperty.isChecked = false
}
R.id.property -> {
rbtnListings.isChecked = false
}
}
}
edAPIKey.setText(prefHelper.getString("X-API-KEY", ""))
edRapidAPIKey.setText(prefHelper.getString("RAPID-API-KEY", ""))
btnCheckData.setOnClickListener {
btnCheckData.isEnabled = false
val startDate = Date()
RealtyFeedSDK.initial(edAPIKey.text.toString(), edRapidAPIKey.text.toString())
prefHelper.putString(edAPIKey.text.toString(), "X-API-KEY")
prefHelper.putString(edRapidAPIKey.text.toString(), "RAPID-API-KEY")
if (rbtnListings.isChecked){
API.instance.getListings { result, error ->
logResult(result, startDate, tvResult)
}
} else if (rbtnProperty.isChecked){
API.instance.getProperty("P_5dba1fb94aa4055b9f29691f") { result, error ->
logResult(result, startDate, tvResult)
}
}
}
}
private fun logResult(
result: JSONObject?,
startDate: Date,
tvResult: AppCompatTextView
) {
btnCheckData.isEnabled = true
Log.d("MainActivity", result.toString())
val diff = Date().time - startDate.time
val milliSeconds = diff % 1000
val seconds = diff / 1000
tvResult.text = "Done in $seconds:$milliSeconds seconds\n\n ${result.toString()}"
}
} | 0 | Kotlin | 0 | 0 | cabbe496a88a10fc0451969f394200c6ad4ea8b6 | 3,177 | RealtyFeedSDK-Android | MIT License |
app/src/main/java/com/example/wildfire_fixed_imports/view/map_display/WildFireMapFragment.kt | Lambda-School-Labs | 227,452,570 | false | null | package com.example.wildfire_fixed_imports.view.map_display
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.example.wildfire_fixed_imports.ApplicationLevelProvider
import com.example.wildfire_fixed_imports.R
import com.example.wildfire_fixed_imports.util.*
import com.example.wildfire_fixed_imports.view.EntranceActivity
import com.example.wildfire_fixed_imports.view.MainActivity
import com.example.wildfire_fixed_imports.viewmodel.view_model_classes.MapViewModel
import com.mapbox.mapboxsdk.maps.MapView
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.style.layers.Layer
import com.mapbox.mapboxsdk.style.layers.Property.NONE
import com.mapbox.mapboxsdk.style.layers.Property.VISIBLE
import com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility
import com.mapbox.mapboxsdk.style.layers.TransitionOptions
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber
class WildFireMapFragment : Fragment() {
// get the correct instance of application level provider
private val applicationLevelProvider: ApplicationLevelProvider = ApplicationLevelProvider.getApplicaationLevelProviderInstance()
val TAG: String
get() = "\nclass: $className -- file name: $fileName -- method: ${StackTraceInfo.invokingMethodName} \n"
override fun onAttach(context: Context) {
super.onAttach(context)
applicationLevelProvider.bottomSheet?.visibility = View.VISIBLE
applicationLevelProvider.aqiGaugeExpanded?.visibility = View.VISIBLE
if (applicationLevelProvider.dataRepository.fireGeoJson.value.isNullOrEmpty()) {
startActivity(Intent(this.context, EntranceActivity::class.java))
}
}
private lateinit var mapViewModel: MapViewModel
private lateinit var mapboxMap:MapboxMap
var mapView: MapView? = null
override fun onViewCreated(v: View, savedInstanceState: Bundle?) {
super.onViewCreated(v, savedInstanceState)
// Initialize Home View Model
mapViewModel = ViewModelProviders.of(this, applicationLevelProvider.mapViewModelFactory).get(
MapViewModel::class.java)
applicationLevelProvider.appMapViewModel =mapViewModel
mapView = v.findViewById(R.id.mapview_main)
mapView?.onCreate(savedInstanceState)
mapView?.getMapAsync { myMapboxMap ->
//set the applicationLevelProvider properties to reflect the loaded map
Timber.i("map loaded async ${System.currentTimeMillis()}")
applicationLevelProvider.mapboxMap = myMapboxMap
mapboxMap = myMapboxMap
applicationLevelProvider.mapboxView = mapView as MapView
finishLoading()
Timber.i("First finish loading")
applicationLevelProvider.currentActivity.locationInit()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_home, container, false)
return root
}
fun finishLoading() {
val style = Style.SATELLITE
mapboxMap.setStyle(style) { it ->
it.transition = TransitionOptions(0, 0, false)
it.resetIconsForNewStyle()
applicationLevelProvider.currentActivity.enableLocationComponent(it)
applicationLevelProvider.mapboxStyle = it
mapViewModel.onMapLoaded()
Timber.w("$TAG config")
applicationLevelProvider.dataRepository.aqiGeoJson.observe(this, Observer { string ->
if (string.isNotBlank()) {
mapViewModel.triggerMapRedraw()
}
})
applicationLevelProvider.dataRepository.aqiGeoJson.observe(this, Observer { string ->
if (string.isNotBlank()) {
mapViewModel.triggerMapRedraw()
}
})
applicationLevelProvider.dataRepository.aqiNearestNeighborGeoJson.observe(this, Observer { string ->
if (string.isNotBlank()) {
mapViewModel.doExperimental()
}
}
)
// start the fire service/immediately to start retrieving fires
}
applicationLevelProvider.switchFireBSIcon.setOnClickListener {
fireToggleButtonOnClick()
}
applicationLevelProvider.switchAqiCloudBSIcon.setOnClickListener {
aqiToggleButtonOnClick()
}
applicationLevelProvider.fireImageView.setOnClickListener {
fireToggleButtonOnClick()
}
applicationLevelProvider.cloudImageView.setOnClickListener {
aqiToggleButtonOnClick()
}
applicationLevelProvider.btmsheetToggleIndex?.setOnClickListener {
aqiToggleBaseText()
aqiToggleCompositeText()
}
applicationLevelProvider.btmSheetToggleRadius?.setOnClickListener {
aqiToggleBaseHML()
aqiToggleCompositeHML()
}
applicationLevelProvider.btmSheetTvIndex?.text="Air Quality index"
applicationLevelProvider.btmSheetTvRadius?.text="Air Quality Radius"
}
fun aqiToggleBaseText() {
mapboxMap.getStyle { style ->
val layer2: Layer? = style.getLayer(AQI_BASE_TEXT_LAYER)
if (layer2 != null) {
if (VISIBLE == layer2.visibility.getValue()) {
layer2.setProperties(visibility(NONE))
applicationLevelProvider.aqiBaseTextLayerVisibility = NONE
} else {
layer2.setProperties(visibility(VISIBLE))
applicationLevelProvider.aqiBaseTextLayerVisibility = VISIBLE
}
}
}
}
fun aqiToggleCompositeText() {
mapboxMap.getStyle { style ->
val layer: Layer? = style.getLayer(AQI_CLUSTERED_COUNT_LAYER)
if (layer != null) {
if (VISIBLE == layer.visibility.getValue()) {
layer.setProperties(visibility(NONE))
applicationLevelProvider.aqiClusterTextLayerVisibility = NONE
} else {
layer.setProperties(visibility(VISIBLE))
applicationLevelProvider.aqiClusterTextLayerVisibility = VISIBLE
}
}
}
}
fun aqiToggleBaseHML() {
mapboxMap.getStyle { style ->
val layer1: Layer? = style.getLayer(AQI_HEATLITE_BASE_LAYER)
if (layer1 != null) {
if (VISIBLE == layer1.visibility.getValue()) {
layer1.setProperties(visibility(NONE))
applicationLevelProvider.aqiBaseHMLLayerVisibility = NONE
} else {
layer1.setProperties(visibility(VISIBLE))
applicationLevelProvider.aqiBaseHMLLayerVisibility = VISIBLE
}
}
}
}
fun aqiToggleCompositeHML() {
mapboxMap.getStyle { style ->
for (i in 0..2) {
val layer: Layer? = style.getLayer("cluster-hml-$i")
if (layer != null) {
if (VISIBLE == layer.visibility.getValue()) {
layer.setProperties(visibility(NONE))
applicationLevelProvider.aqiClusterHMLLayerVisibility = NONE
} else {
layer.setProperties(visibility(VISIBLE))
applicationLevelProvider.aqiClusterHMLLayerVisibility = VISIBLE
}
}
}
}
}
fun fireToggleButtonOnClick() {
opacitySwitch(applicationLevelProvider.fireImageView)
mapboxMap.getStyle { style ->
val layer: Layer? = style.getLayer(FIRE_SYMBOL_LAYER)
if (layer != null) {
if (VISIBLE == layer.visibility.getValue()) {
layer.setProperties(visibility(NONE))
applicationLevelProvider.fireLayerVisibility = NONE
applicationLevelProvider.switchFireBSIcon.setChecked(false)
} else {
layer.setProperties(visibility(VISIBLE))
applicationLevelProvider.fireLayerVisibility = VISIBLE
applicationLevelProvider.switchFireBSIcon.setChecked(true)
}
}
}
mapViewModel.toggleFireRetrieval()
Timber.i("$TAG toggle fire")
}
private fun toggleAQIDetailSwitchs(switchOn: Boolean) {
if(switchOn) {
applicationLevelProvider.btmSheetToggleRadius?.setChecked(true)
applicationLevelProvider.btmsheetToggleIndex?.setChecked(true)
}
else {
applicationLevelProvider.btmSheetToggleRadius?.setChecked(false)
applicationLevelProvider.btmsheetToggleIndex?.setChecked(false)
}
}
fun aqiToggleButtonOnClick() {
opacitySwitch(applicationLevelProvider.cloudImageView)
mapViewModel.toggleAQIRetrieval()
mapboxMap.getStyle { style ->
val layer2: Layer? = style.getLayer(AQI_BASE_TEXT_LAYER)
if (layer2 != null) {
if (VISIBLE == layer2.visibility.getValue()) {
layer2.setProperties(visibility(NONE))
applicationLevelProvider.aqiBaseTextLayerVisibility = NONE
applicationLevelProvider.switchAqiCloudBSIcon.setChecked(false)
toggleAQIDetailSwitchs(false)
} else {
layer2.setProperties(visibility(VISIBLE))
applicationLevelProvider.aqiBaseTextLayerVisibility = VISIBLE
applicationLevelProvider.switchAqiCloudBSIcon.setChecked(true)
toggleAQIDetailSwitchs(true)
}
}
val layer: Layer? = style.getLayer(AQI_CLUSTERED_COUNT_LAYER)
if (layer != null) {
if (VISIBLE == layer.visibility.getValue()) {
layer.setProperties(visibility(NONE))
applicationLevelProvider.aqiLayerVisibility =NONE
applicationLevelProvider.aqiClusterTextLayerVisibility = NONE
} else {
layer.setProperties(visibility(VISIBLE))
applicationLevelProvider.aqiLayerVisibility =VISIBLE
applicationLevelProvider.aqiClusterTextLayerVisibility = VISIBLE
}
}
val layer1: Layer? = style.getLayer(AQI_HEATLITE_BASE_LAYER)
if (layer1 != null) {
if (VISIBLE == layer1.visibility.getValue()) {
layer1.setProperties(visibility(NONE))
applicationLevelProvider.aqiBaseHMLLayerVisibility = NONE
} else {
layer1.setProperties(visibility(VISIBLE))
applicationLevelProvider.aqiBaseHMLLayerVisibility = VISIBLE
}
}
for (i in 0..2) {
val layer: Layer? = style.getLayer("cluster-hml-$i")
if (layer != null) {
if (VISIBLE == layer.visibility.getValue()) {
layer.setProperties(visibility(NONE))
applicationLevelProvider.aqiClusterHMLLayerVisibility = NONE
} else {
layer.setProperties(visibility(VISIBLE))
applicationLevelProvider.aqiClusterHMLLayerVisibility = VISIBLE
}
}
}
}
Timber.i("$TAG toggle aqi")
}
fun opacitySwitch(view: ImageView){
if (view.alpha == 1F){
view.alpha = 0.5F
}else{
view.alpha = 1F
}
}
//mapbox boilerplate for surviving config changes
override fun onStart(): Unit {
super.onStart()
mapView?.onStart()
}
override fun onResume() {
super.onResume()
mapView?.onResume()
}
override fun onPause() {
super.onPause()
mapView?.onPause()
}
override fun onStop() {
super.onStop()
mapView?.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView?.onSaveInstanceState(outState)
}
override fun onDestroyView() {
super.onDestroyView()
mapView?.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView?.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView?.onDestroy()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
}
override fun onDetach() {
super.onDetach()
}
} | 0 | Kotlin | 2 | 0 | 315b0bc7cd79c35e8d8b2347e7196ac3e8955dbc | 13,367 | forest-fire-watch-android | MIT License |
src/main/kotlin/com/muhron/kotlinq/skipWhile.kt | RyotaMurohoshi | 53,187,022 | false | null | package com.muhron.kotlinq
fun <TSource> Sequence<TSource>.skipWhile(predicate: (TSource) -> Boolean): Sequence<TSource> =
dropWhile(predicate)
fun <TSource> Iterable<TSource>.skipWhile(predicate: (TSource) -> Boolean): Sequence<TSource> =
asSequence().skipWhile(predicate)
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.skipWhile(predicate: (Map.Entry<TSourceK, TSourceV>) -> Boolean): Sequence<Map.Entry<TSourceK, TSourceV>> =
asSequence().skipWhile(predicate)
fun <TSource> Array<TSource>.skipWhile(predicate: (TSource) -> Boolean): Sequence<TSource> =
asSequence().skipWhile(predicate)
| 1 | Kotlin | 0 | 5 | 1bb201d7032cdcc302f342bc771ab356f1d96db2 | 628 | KotLinq | MIT License |
utilk_android/src/main/java/com/mozhimen/kotlin/utilk/kotlin/UtilKStrHtml.kt | mozhimen | 798,079,717 | false | {"Kotlin": 1378809, "Java": 3920} | package com.mozhimen.kotlin.utilk.kotlin
import android.text.Spanned
import androidx.annotation.RequiresApi
import com.mozhimen.kotlin.elemk.android.os.cons.CVersCode
import com.mozhimen.kotlin.elemk.android.text.cons.CHtml
import com.mozhimen.kotlin.utilk.android.os.UtilKBuildVersion
import com.mozhimen.kotlin.utilk.android.text.UtilKHtml
/**
* @ClassName UtilKStrHtml
* @Description TODO
* @Author Mozhimen & Kolin Zhao
* @Date 2024/2/20
* @Version 1.0
*/
@RequiresApi(CVersCode.V_24_7_N)
fun String.strHtml2chars(flags: Int): Spanned =
UtilKStrHtml.strHtml2chars(this, flags)
fun String.strHtml2chars(): Spanned =
UtilKStrHtml.strHtml2chars(this)
/////////////////////////////////////////////////////////////////////////////
object UtilKStrHtml {
//CHtml.FROM_HTML_MODE_COMPACT
@JvmStatic
@RequiresApi(CVersCode.V_24_7_N)
fun strHtml2chars(strHtml: String, flags: Int): Spanned =
UtilKHtml.fromHtml(strHtml, flags)
@JvmStatic
fun strHtml2chars(strHtml: String): Spanned =
if (UtilKBuildVersion.isAfterV_24_7_N())
strHtml2chars(strHtml, CHtml.FROM_HTML_MODE_COMPACT)
else
UtilKHtml.fromHtml(strHtml)
} | 0 | Kotlin | 0 | 0 | d0958b68d3f5a830284cd375980e93ec4069d0d5 | 1,197 | KUtilKit | MIT License |
app/src/main/kotlin/openeyes/drawalive/seven/openeyes/filter/BitmapFilter.kt | stallpool | 116,222,959 | false | null | package openeyes.drawalive.seven.openeyes.filter
import android.graphics.Bitmap
interface BitmapFilter {
fun act(bmp: Bitmap): Bitmap
}
| 0 | Kotlin | 0 | 2 | fcde530b7041fe327dcd9b4d2a6d5a280c1f5581 | 142 | OpenEyes | MIT License |
shared/src/commonMain/kotlin/com/thomaskioko/tvmaniac/di/Koin.kt | c0de-wizard | 361,393,353 | false | null | package com.thomaskioko.tvmaniac.di
import com.thomaskioko.tvmaniac.core.db.di.dbPlatformModule
import com.thomaskioko.tvmaniac.discover.api.cache.CategoryCache
import com.thomaskioko.tvmaniac.discover.api.cache.ShowCategoryCache
import com.thomaskioko.tvmaniac.discover.implementation.cache.CategoryCacheImpl
import com.thomaskioko.tvmaniac.discover.implementation.cache.ShowCategoryCacheImpl
import com.thomaskioko.tvmaniac.discover.implementation.cache.TvShowCacheImpl
import com.thomaskioko.tvmaniac.discover.implementation.di.discoverDomainModule
import com.thomaskioko.tvmaniac.episodes.implementation.di.episodeDomainModule
import com.thomaskioko.tvmaniac.genre.implementation.di.genreModule
import com.thomaskioko.tvmaniac.lastairepisodes.implementation.di.lastAirEpisodeDomainModule
import com.thomaskioko.tvmaniac.remote.di.remotePlatformModule
import com.thomaskioko.tvmaniac.remote.di.serviceModule
import com.thomaskioko.tvmaniac.seasonepisodes.implementation.seasonEpisodesDomainModule
import com.thomaskioko.tvmaniac.seasons.implementation.di.seasonsDomainModule
import com.thomaskioko.tvmaniac.shared.core.di.corePlatformModule
import com.thomaskioko.tvmaniac.showcommon.api.TvShowCache
import com.thomaskioko.tvmaniac.similar.implementation.di.similarDomainModule
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import org.koin.core.context.startKoin
import org.koin.core.module.Module
import org.koin.dsl.KoinAppDeclaration
import org.koin.dsl.module
fun initKoin(appDeclaration: KoinAppDeclaration = {}) = startKoin {
appDeclaration()
modules(
serviceModule,
cacheModule,
dispatcherModule,
discoverDomainModule,
seasonsDomainModule,
episodeDomainModule,
genreModule,
lastAirEpisodeDomainModule,
similarDomainModule,
seasonEpisodesDomainModule,
corePlatformModule(),
dbPlatformModule(),
remotePlatformModule()
)
}
val cacheModule: Module = module {
single<com.thomaskioko.tvmaniac.showcommon.api.TvShowCache> { TvShowCacheImpl(get()) }
single<ShowCategoryCache> { ShowCategoryCacheImpl(get()) }
single<CategoryCache> { CategoryCacheImpl(get()) }
}
val dispatcherModule = module {
factory { Dispatchers.Default }
factory { MainScope() }
}
| 1 | Kotlin | 4 | 23 | f209c7d1cf9e172e8be7573cab50e59b4218c92d | 2,322 | tv-maniac | Apache License 2.0 |
odl-core/src/main/kotlin/sk/jt/jnetbios/odl/core/api/OdlCoreServices.kt | jaro0149 | 410,344,130 | false | {"Maven POM": 6, "Text": 2, "Ignore List": 1, "Markdown": 1, "Java": 7, "Kotlin": 10} | package sk.jt.jnetbios.odl.core.api
import org.opendaylight.mdsal.binding.api.DataBroker
import org.opendaylight.mdsal.binding.api.RpcProviderService
import org.opendaylight.mdsal.binding.dom.codec.spi.BindingDOMCodecServices
import org.opendaylight.mdsal.dom.api.DOMDataBroker
import org.opendaylight.mdsal.dom.api.DOMRpcProviderService
import org.opendaylight.mdsal.dom.api.DOMRpcService
import org.opendaylight.mdsal.dom.api.DOMSchemaService
/**
* Grouped ODL core services.
*/
interface OdlCoreServices {
/**
* Schema service that is holding all compiled system YANG files.
*
* @return [DOMSchemaService]
*/
fun schemaService(): DOMSchemaService
/**
* Codec used for conversion of paths and data between binding-aware (YANG elements are modelled
* by generated classes) and binding-independent representations (YANG elements are represented by generic classes).
*
* @return [BindingDOMCodecServices]
*/
fun bindingDomCodec(): BindingDOMCodecServices
/**
* Data broker for accessing of **CONFIGURATION** and **OPERATIONAL** data-stores using transactions.
*
* @return [DOMDataBroker]
*/
fun dataBroker(): DOMDataBroker
/**
* Binding-aware representation of [dataBroker].
*
* @return [DataBroker]
*/
fun bindingDataBroker(): DataBroker
/**
* Service used for invocation of RPC implementations.
*
* @return [DOMRpcService]
*/
fun rpcService(): DOMRpcService
/**
* RPC register.
*
* @return [DOMRpcProviderService]
*/
fun rpcProvider(): DOMRpcProviderService
/**
* Binding-aware representation of [rpcProvider].
*
* @return [RpcProviderService]
*/
fun bindingRpcProvider(): RpcProviderService
} | 0 | Kotlin | 0 | 0 | d0b4c16506dd1d972da8522fe529de46114c01f4 | 1,806 | jnetbios | MIT License |
src/node/net/typealiases.kt | Shengaero | 145,035,315 | false | null | /*
* Copyright 2018 <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 node.net
import node.dns.LookupOptions
typealias LookupCallback = (err: Throwable?, address: String, family: Int) -> Unit
typealias LookupFunction = (hostname: String,
options: LookupOptions,
callback: LookupCallback) -> Unit | 0 | Kotlin | 2 | 1 | 8baaf485a691bfc31b00498e2ca1636682644b1d | 881 | node-kt | Apache License 2.0 |
solar/src/main/java/com/chiksmedina/solar/outline/notes/ClipboardRemove.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.outline.notes
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.outline.NotesGroup
val NotesGroup.ClipboardRemove: ImageVector
get() {
if (_clipboardRemove != null) {
return _clipboardRemove!!
}
_clipboardRemove = Builder(
name = "ClipboardRemove", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(7.2628f, 3.2587f)
curveTo(7.3832f, 2.1295f, 8.3389f, 1.25f, 9.5f, 1.25f)
horizontalLineTo(14.5f)
curveTo(15.6611f, 1.25f, 16.6168f, 2.1295f, 16.7372f, 3.2587f)
curveTo(17.5004f, 3.2743f, 18.1602f, 3.3137f, 18.7236f, 3.4172f)
curveTo(19.4816f, 3.5564f, 20.1267f, 3.8217f, 20.6517f, 4.3466f)
curveTo(21.2536f, 4.9485f, 21.5125f, 5.7064f, 21.6335f, 6.6065f)
curveTo(21.75f, 7.4735f, 21.75f, 8.5758f, 21.75f, 9.9434f)
verticalLineTo(16.0531f)
curveTo(21.75f, 17.4207f, 21.75f, 18.523f, 21.6335f, 19.39f)
curveTo(21.5125f, 20.2901f, 21.2536f, 21.048f, 20.6517f, 21.6499f)
curveTo(20.0497f, 22.2518f, 19.2919f, 22.5107f, 18.3918f, 22.6317f)
curveTo(17.5248f, 22.7483f, 16.4225f, 22.7483f, 15.0549f, 22.7483f)
horizontalLineTo(8.9451f)
curveTo(7.5775f, 22.7483f, 6.4752f, 22.7483f, 5.6083f, 22.6317f)
curveTo(4.7081f, 22.5107f, 3.9503f, 22.2518f, 3.3484f, 21.6499f)
curveTo(2.7464f, 21.048f, 2.4875f, 20.2901f, 2.3665f, 19.39f)
curveTo(2.25f, 18.523f, 2.25f, 17.4207f, 2.25f, 16.0531f)
verticalLineTo(9.9434f)
curveTo(2.25f, 8.5758f, 2.25f, 7.4735f, 2.3665f, 6.6065f)
curveTo(2.4875f, 5.7064f, 2.7464f, 4.9485f, 3.3484f, 4.3466f)
curveTo(3.8733f, 3.8217f, 4.5184f, 3.5564f, 5.2764f, 3.4172f)
curveTo(5.8398f, 3.3137f, 6.4996f, 3.2743f, 7.2628f, 3.2587f)
close()
moveTo(7.2648f, 4.7591f)
curveTo(6.5467f, 4.7745f, 5.9933f, 4.8106f, 5.5473f, 4.8925f)
curveTo(4.9805f, 4.9966f, 4.6525f, 5.1638f, 4.409f, 5.4073f)
curveTo(4.1322f, 5.684f, 3.9518f, 6.0726f, 3.8531f, 6.8064f)
curveTo(3.7516f, 7.5617f, 3.75f, 8.5628f, 3.75f, 9.9983f)
verticalLineTo(15.9983f)
curveTo(3.75f, 17.4337f, 3.7516f, 18.4348f, 3.8531f, 19.1901f)
curveTo(3.9518f, 19.9239f, 4.1322f, 20.3125f, 4.409f, 20.5893f)
curveTo(4.6858f, 20.866f, 5.0743f, 21.0465f, 5.8081f, 21.1451f)
curveTo(6.5635f, 21.2467f, 7.5646f, 21.2483f, 9.0f, 21.2483f)
horizontalLineTo(15.0f)
curveTo(16.4354f, 21.2483f, 17.4365f, 21.2467f, 18.1919f, 21.1451f)
curveTo(18.9257f, 21.0465f, 19.3142f, 20.866f, 19.591f, 20.5893f)
curveTo(19.8678f, 20.3125f, 20.0482f, 19.9239f, 20.1469f, 19.1901f)
curveTo(20.2484f, 18.4348f, 20.25f, 17.4337f, 20.25f, 15.9983f)
verticalLineTo(9.9983f)
curveTo(20.25f, 8.5628f, 20.2484f, 7.5617f, 20.1469f, 6.8064f)
curveTo(20.0482f, 6.0726f, 19.8678f, 5.684f, 19.591f, 5.4073f)
curveTo(19.3475f, 5.1638f, 19.0195f, 4.9966f, 18.4527f, 4.8925f)
curveTo(18.0067f, 4.8106f, 17.4533f, 4.7745f, 16.7352f, 4.7591f)
curveTo(16.6067f, 5.8797f, 15.655f, 6.75f, 14.5f, 6.75f)
horizontalLineTo(9.5f)
curveTo(8.345f, 6.75f, 7.3933f, 5.8797f, 7.2648f, 4.7591f)
close()
moveTo(9.5f, 2.75f)
curveTo(9.0858f, 2.75f, 8.75f, 3.0858f, 8.75f, 3.5f)
verticalLineTo(4.5f)
curveTo(8.75f, 4.9142f, 9.0858f, 5.25f, 9.5f, 5.25f)
horizontalLineTo(14.5f)
curveTo(14.9142f, 5.25f, 15.25f, 4.9142f, 15.25f, 4.5f)
verticalLineTo(3.5f)
curveTo(15.25f, 3.0858f, 14.9142f, 2.75f, 14.5f, 2.75f)
horizontalLineTo(9.5f)
close()
moveTo(8.9697f, 11.5303f)
curveTo(8.6768f, 11.2375f, 8.6768f, 10.7626f, 8.9697f, 10.4697f)
curveTo(9.2626f, 10.1768f, 9.7374f, 10.1768f, 10.0303f, 10.4697f)
lineTo(12.0f, 12.4394f)
lineTo(13.9697f, 10.4697f)
curveTo(14.2626f, 10.1768f, 14.7374f, 10.1768f, 15.0303f, 10.4697f)
curveTo(15.3232f, 10.7626f, 15.3232f, 11.2375f, 15.0303f, 11.5304f)
lineTo(13.0607f, 13.5f)
lineTo(15.0303f, 15.4697f)
curveTo(15.3232f, 15.7626f, 15.3232f, 16.2374f, 15.0303f, 16.5303f)
curveTo(14.7374f, 16.8232f, 14.2625f, 16.8232f, 13.9697f, 16.5303f)
lineTo(12.0f, 14.5607f)
lineTo(10.0304f, 16.5303f)
curveTo(9.7375f, 16.8232f, 9.2626f, 16.8232f, 8.9697f, 16.5304f)
curveTo(8.6768f, 16.2375f, 8.6768f, 15.7626f, 8.9697f, 15.4697f)
lineTo(10.9394f, 13.5f)
lineTo(8.9697f, 11.5303f)
close()
}
}
.build()
return _clipboardRemove!!
}
private var _clipboardRemove: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 6,151 | SolarIconSetAndroid | MIT License |
app/src/main/java/com/example/shoppinglist/model/ShoppingListItem.kt | simone-di-paolo | 794,616,361 | false | {"Kotlin": 16114} | package com.example.shoppinglist.model
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.shoppinglist.R
import com.example.shoppinglist.bean.ShoppingItem
@Composable
fun ShoppingListItem(
shoppingItem: ShoppingItem,
onEditClick: () -> Unit,
onDeleteClick: () -> Unit
) {
var name = shoppingItem.name
if (name.length > 10) {
name = name.substring(0, 7) + "..."
}
Row (
modifier = Modifier
.fillMaxWidth()
.clickable {
onEditClick()
}
.padding(8.dp)
.border(
border = BorderStroke(
1.dp,
color = Color(0xFF018786)
),
shape = RoundedCornerShape(20)
),
){
Text(
text = name,
modifier = Modifier
.width(135.dp)
.padding(16.dp),
)
Text(
text = stringResource(id = R.string.quantity_label) + ": " + shoppingItem.quantity,
modifier = Modifier.padding(16.dp)
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End
) {
IconButton (onClick = onEditClick) {
Icon(
modifier = Modifier
.padding(8.dp)
.width(20.dp),
imageVector = Icons.Default.Delete, contentDescription = "Delete button")
}
}
}
}
@Preview
@Composable
fun ShoppingListItemPreview() {
ShoppingListItem(
shoppingItem = ShoppingItem(1, "Banana", 1),
onEditClick = {},
onDeleteClick = {}
)
} | 0 | Kotlin | 0 | 0 | ae869453f5d9339d5793fca328ae596c95038cfe | 2,611 | shopping-list | MIT License |
src/test/kotlin/com/github/jyc228/keth/client/eth/TransactionJsonTest.kt | jyc228 | 833,953,853 | false | {"Kotlin": 217816, "Solidity": 5515} | package com.github.jyc228.keth.client.eth
import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.core.spec.style.StringSpec
import kotlinx.serialization.json.Json
class TransactionJsonTest : StringSpec({
"decode legacy transaction" {
val tx = decodeJsonResource<RpcTransaction>("/transaction/tx_legacy.json")
println(tx)
}
"decode dynamic fee transaction" {
val tx = decodeJsonResource<RpcTransaction>("/transaction/tx_dynamic_fee.json")
println(tx)
}
"decode blob transaction" {
val tx = decodeJsonResource<RpcTransaction>("/transaction/tx_blob.json")
println(tx)
}
"decode unknown transaction" {
shouldThrowAny { decodeJsonResource<RpcTransaction>("/transaction/tx_unknown.json", Json) }
val tx = decodeJsonResource<RpcTransaction>("/transaction/tx_unknown.json", Json { ignoreUnknownKeys = true })
println(tx)
}
})
| 0 | Kotlin | 0 | 2 | 4fd6f900b4e80b5f731090f33c1ddc10c6ede9ca | 943 | keth-client | Apache License 2.0 |
feature/monster-content-manager/android/src/main/java/br/alexandregpereira/hunter/monster/content/preview/MonsterContentPreviewFeature.kt | alexandregpereira | 347,857,709 | false | {"Kotlin": 1323782, "Swift": 74314, "Shell": 139} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package br.alexandregpereira.hunter.monster.content.preview
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import br.alexandregpereira.hunter.monster.content.preview.ui.MonsterContentPreviewScreen
import org.koin.androidx.compose.koinViewModel
@Composable
internal fun MonsterContentPreviewFeature(
contentPadding: PaddingValues = PaddingValues(),
) {
val viewModel: MonsterContentPreviewViewModel = koinViewModel()
MonsterContentPreviewScreen(
state = viewModel.state.collectAsState().value,
actionHandler = viewModel,
contentPadding = contentPadding,
onClose = viewModel::onClose,
onTableContentOpenButtonClick = viewModel::onTableContentOpenButtonClick,
onTableContentClose = viewModel::onTableContentClose,
onTableContentClick = viewModel::onTableContentClick,
onFirstVisibleItemChange = viewModel::onFirstVisibleItemChange,
)
}
| 7 | Kotlin | 4 | 80 | ca1695daf3f23e7cbb634b66e62b4fee36440ef8 | 1,602 | Monster-Compendium | Apache License 2.0 |
example/src/main/kotlin/autodagger/example/fifth/SixthActivityAnnotation.kt | psh | 201,416,543 | true | {"Kotlin": 63685, "Shell": 175} | package autodagger.example.fifth
import autodagger.AutoComponent
import autodagger.example.KotlinExampleApplication
import autodagger.example.first.HasDependenciesOne
import autodagger.example.first.HasDependenciesTwo
import dagger.Module
@AutoComponent(
dependencies = [KotlinExampleApplication::class],
superinterfaces = [HasDependenciesOne::class, HasDependenciesTwo::class],
modules = [SixthModule::class]
)
annotation class SixthActivityIncludesViaAnnotation
@Module
class SixthModule | 0 | Kotlin | 0 | 1 | 32e35fdb308727e2d4f4e7b108f6cd2e4c40b781 | 504 | auto-dagger2 | MIT License |
src/main/kotlin/org/pkl/lsp/analyzers/ModifierAnalyzer.kt | apple | 831,117,024 | false | {"Kotlin": 585408, "Pkl": 4143} | /**
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.lsp.analyzers
import org.pkl.lsp.ErrorMessages
import org.pkl.lsp.Project
import org.pkl.lsp.ast.*
import org.pkl.lsp.ast.TokenType.*
class ModifierAnalyzer(project: Project) : Analyzer(project) {
companion object {
private val MODULE_MODIFIERS = setOf(ABSTRACT, OPEN)
private val AMENDING_MODULE_MODIFIERS = emptySet<TokenType>()
private val CLASS_MODIFIERS = setOf(ABSTRACT, OPEN, EXTERNAL, LOCAL)
private val TYPE_ALIAS_MODIFIERS = setOf(EXTERNAL, LOCAL)
private val CLASS_METHOD_MODIFIERS = setOf(ABSTRACT, EXTERNAL, LOCAL, CONST)
private val CLASS_PROPERTY_MODIFIERS = setOf(ABSTRACT, EXTERNAL, HIDDEN, LOCAL, FIXED, CONST)
private val OBJECT_METHOD_MODIFIERS = setOf(LOCAL)
private val OBJECT_PROPERTY_MODIFIERS = setOf(LOCAL)
}
override fun doAnalyze(node: PklNode, diagnosticsHolder: MutableList<PklDiagnostic>): Boolean {
// removing module and module declaration because this will be checked in PklModuleHeader
if (
node !is ModifierListOwner ||
node.modifiers == null ||
node is PklModule ||
node is PklModuleHeader
) {
return true
}
var localModifier: PklNode? = null
var abstractModifier: PklNode? = null
var openModifier: PklNode? = null
var hiddenModifier: PklNode? = null
var fixedModifier: PklNode? = null
for (modifier in node.modifiers!!) {
when (modifier.type) {
LOCAL -> localModifier = modifier
ABSTRACT -> abstractModifier = modifier
OPEN -> openModifier = modifier
HIDDEN -> hiddenModifier = modifier
FIXED -> fixedModifier = modifier
else -> {}
}
}
if (localModifier == null) {
when (node) {
is PklClassProperty -> {
if (
node.parent is PklModule &&
(node.parent as PklModule).isAmend &&
(hiddenModifier != null || node.typeAnnotation != null)
) {
if (node.identifier != null) {
diagnosticsHolder.add(
error(node.identifier!!, ErrorMessages.create("missingModifierLocal"))
)
return true
}
}
}
}
}
if (abstractModifier != null && openModifier != null) {
diagnosticsHolder.add(
error(abstractModifier, ErrorMessages.create("modifierAbstractConflictsWithOpen"))
)
diagnosticsHolder.add(
error(openModifier, ErrorMessages.create("modifierOpenConflictsWithAbstract"))
)
}
val (description, applicableModifiers) =
when (node) {
is PklModuleHeader ->
if (node.isAmend) "amending modules" to AMENDING_MODULE_MODIFIERS
else "modules" to MODULE_MODIFIERS
is PklClass -> "classes" to CLASS_MODIFIERS
is PklTypeAlias -> "typealiases" to TYPE_ALIAS_MODIFIERS
is PklClassMethod -> "class methods" to CLASS_METHOD_MODIFIERS
is PklClassProperty -> "class properties" to CLASS_PROPERTY_MODIFIERS
else -> return true
}
for (modifier in node.modifiers!!) {
if (modifier.type !in applicableModifiers) {
diagnosticsHolder.add(
error(
modifier,
ErrorMessages.create("modifierIsNotApplicable", modifier.text, description),
)
)
}
}
return true
}
}
| 2 | Kotlin | 6 | 24 | d4cff17a023ec8aa24bda8b60ff8c7fa561842fd | 4,004 | pkl-lsp | Apache License 2.0 |
buildSrc/src/main/kotlin/us/ihmc/cd/RemoteExtension.kt | ihmcrobotics | 177,029,933 | false | null | package us.ihmc.cd
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.common.IOUtils
import net.schmizz.sshj.connection.channel.direct.Session
import net.schmizz.sshj.sftp.SFTPClient
import net.schmizz.sshj.transport.verification.PromiscuousVerifier
import org.gradle.api.Action
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
open class RemoteExtension
{
fun session(address: String, username: String, password: String, action: Action<RemoteConnection>)
{
session(address, {sshClient -> sshClient.authPassword(username, password)} , action)
}
fun session(address: String, username: String, action: Action<RemoteConnection>)
{
session(address, {sshClient -> authWithSSHKey(username, sshClient)} , action)
}
/**
* Replicate OpenSSH functionality where users can name private keys whatever they want.
*/
private fun authWithSSHKey(username: String, sshClient: SSHClient)
{
val userSSHConfigFolder = Paths.get(System.getProperty("user.home")).resolve(".ssh")
val list = Files.list(userSSHConfigFolder)
val privateKeyFiles = arrayListOf<String>()
for (path in list)
{
if (Files.isRegularFile(path)
&& path.fileName.toString() != "config"
&& path.fileName.toString() != "known_hosts"
&& !path.fileName.toString().endsWith(".pub"))
{
val absoluteNormalizedString = path.toAbsolutePath().normalize().toString()
privateKeyFiles.add(absoluteNormalizedString)
}
}
LogTools.info("Passing keys to authPublicKey: {}", privateKeyFiles)
sshClient.authPublickey(username, *privateKeyFiles.toTypedArray())
}
class RemoteConnection(val ssh: SSHClient, val sftp: SFTPClient)
{
fun exec(command: String, timeout: Double = 5.0)
{
var session: Session? = null
try
{
session = ssh.startSession()
LogTools.quiet("Executing on ${ssh.remoteHostname}: \"$command\"")
val sshjCommand = session.exec(command)
LogTools.quiet(IOUtils.readFully(sshjCommand.inputStream).toString())
sshjCommand.join((timeout * 1e9).toLong(), TimeUnit.NANOSECONDS)
LogTools.quiet("** exit status: " + sshjCommand.exitStatus)
}
finally
{
try
{
if (session != null)
{
session.close();
}
}
catch (e: IOException)
{
// do nothing
}
}
}
fun put(source: String, dest: String)
{
LogTools.quiet("Putting $source to ${ssh.remoteHostname}:$dest")
sftp.put(source, dest)
}
fun get(source: String, dest: String)
{
LogTools.quiet("Getting ${ssh.remoteHostname}:$source to $dest")
sftp.get(source, dest)
}
}
fun session(address: String, authenticate: (SSHClient) -> Unit, action: Action<RemoteConnection>)
{
val sshClient = SSHClient()
sshClient.loadKnownHosts()
sshClient.addHostKeyVerifier(PromiscuousVerifier()) // TODO: Try removing this again
sshClient.connect(address)
try
{
authenticate(sshClient)
val sftpClient: SFTPClient = sshClient.newSFTPClient()
try
{
action.execute(RemoteConnection(sshClient, sftpClient))
}
finally
{
sftpClient.close()
}
}
finally
{
sshClient.disconnect()
}
}
} | 3 | Kotlin | 0 | 0 | 7bdbf5c12b6eb4ded35b0761d9386e09597e2702 | 3,675 | ihmc-cd | Apache License 2.0 |
XTool/src/main/java/com/danny/xtool/executor/ThreadExecutor.kt | dannycx | 643,140,932 | false | {"Gradle": 12, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 10, "Batchfile": 1, "Markdown": 58, "INI": 8, "Proguard": 9, "Kotlin": 149, "XML": 117, "Java": 130, "JSON": 2} | /*
* Copyright (c) 2023-2023 x
*/
package com.danny.xtool.executor
import android.util.Log
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicInteger
/**
* 线程池
*
* @author x
* @since 2023-05-22
*/
class ThreadExecutor: Executor {
private val mThreadPool = ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS,
ArrayBlockingQueue(4), object : ThreadFactory{
val mThreadNumber = AtomicInteger(1)
override fun newThread(r: Runnable?) = Thread(r, "wb-thread-${mThreadNumber.getAndIncrement()}")
}) { r, executor -> Log.e("", "$r rejected, completedTaskCount: ${executor.completedTaskCount}") }
companion object{
fun getInstance(): ThreadExecutor {
return ThreadExecutor()
}
}
override fun execute(command: Runnable?) {
command?:return
mThreadPool.execute(command)
}
}
| 0 | Java | 0 | 0 | bfb22a1abf9270e1d837113cc998cca0f9aac650 | 893 | XLib | Apache License 2.0 |
reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/widget/CompoundButtonEvent.kt | Judrummer | 51,418,404 | true | {"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 7, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Proguard": 6, "XML": 27, "Kotlin": 104, "Java": 1} | package com.github.kittinunf.reactiveandroid.widget
import android.widget.CompoundButton
import com.github.kittinunf.reactiveandroid.subscription.AndroidMainThreadSubscription
import rx.Observable
//================================================================================
// Event
//================================================================================
data class CompoundButtonCheckedChangeListener(val compoundButton: CompoundButton, val isChecked: Boolean)
fun CompoundButton.rx_checkedChange(): Observable<CompoundButtonCheckedChangeListener> {
return Observable.create { subscriber ->
setOnCheckedChangeListener { compoundButton, isChecked ->
subscriber.onNext(CompoundButtonCheckedChangeListener(compoundButton, isChecked))
}
subscriber.add(AndroidMainThreadSubscription {
setOnCheckedChangeListener(null)
})
}
}
| 0 | Kotlin | 0 | 0 | c9a90e31736f3c3a992e48d8a76c9e40c76f767f | 918 | ReactiveAndroid | MIT License |
src/main/kotlin/usecases/UseCase.kt | ktlib-org | 718,419,916 | false | {"Kotlin": 81117, "PLpgSQL": 4310} | package usecases
import entities.organization.OrganizationUser
import entities.organization.OrganizationUsers
import entities.organization.UserRole
import entities.user.User
import entities.user.UserLogin
import entities.user.UserLogins
import org.ktlib.entities.NotFoundException
import org.ktlib.entities.UnauthorizedException
import org.ktlib.typeArguments
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.full.createInstance
enum class Role {
Owner, Admin, User, UserNoOrg, Employee, Anyone;
val userRole: UserRole? by lazy { UserRole.entries.find { it.name == name } }
}
fun createContext(token: String? = null, orgId: UUID? = null) =
UseCaseContext(UserLogins.findByToken(token), orgId, Unit)
fun <T> createContext(token: String? = null, orgId: UUID? = null, input: T) =
UseCaseContext(UserLogins.findByToken(token), orgId, input)
class UseCaseContext<T>(
val userLogin: UserLogin? = null,
val orgId: UUID? = null,
val input: T? = null
)
typealias DataMap = Map<String, Any?>
abstract class UseCase<D : Any, T>(role: Role, vararg roles: Role) {
companion object {
fun <U : UseCase<D, T>, D : Any?, T : Any?> create(type: KClass<U>, context: UseCaseContext<D>): U {
return type.createInstance().apply { this.context = context }
}
}
val useCaseRoles: List<Role>
private lateinit var context: UseCaseContext<D>
val input: D get() = context.input!!
val currentUserLoginOrNull: UserLogin? get() = context.userLogin
val currentUserLogin: UserLogin get() = currentUserLoginOrNull!!
val currentUserIdOrNull: UUID? get() = currentUserLoginOrNull?.userId
val currentUserId: UUID get() = currentUserIdOrNull!!
val currentUser: User get() = currentUserLogin.user
val orgIdOrNull: UUID? get() = context.orgId
val orgId: UUID get() = orgIdOrNull!!
open val aliases: List<String> = emptyList()
val currentOrganizationUser: OrganizationUser? by lazy {
OrganizationUsers.findByUserIdAndOrganizationId(currentUserId, orgId)
}
val userRole: UserRole get() = currentOrganizationUser!!.role
@Suppress("UNCHECKED_CAST")
val inputType: KClass<D> get() = typeArguments(UseCase::class)[0] as KClass<D>
init {
this.useCaseRoles = listOf(role, *roles)
}
private val notInitializedMessage =
"UseCase context needs to be initialized before executing. Use UseCase.create() to create a UseCase instance."
fun execute() = when {
!::context.isInitialized -> throw IllegalStateException(notInitializedMessage)
!roleAuthorize() -> throw UnauthorizedException()
else -> doExecute()
}
protected abstract fun doExecute(): T
private fun roleAuthorize() = when {
useCaseRoles.contains(Role.Employee) -> if (currentUserLoginOrNull != null && currentUser.employee) true else throw NotFoundException()
useCaseRoles.contains(Role.Anyone) -> true
useCaseRoles.contains(Role.UserNoOrg) && currentUserLoginOrNull != null -> true
currentUserLoginOrNull != null && context.orgId != null -> userHasRole() && authorize()
else -> false
}
open fun authorize() = true
private fun userHasRole() =
currentOrganizationUser?.hasPermission(useCaseRoles.mapNotNull { it.userRole }) == true
protected fun <D : Any, T> executeUseCase(type: KClass<out UseCase<D, T>>, input: D): T {
return create(type, UseCaseContext(context.userLogin, context.orgId, input)).execute()
}
} | 0 | Kotlin | 0 | 0 | fa6b2ea8cb94fee06b66309bea918523dfb26a37 | 3,538 | example-api | The Unlicense |
src/main/java/dev/nafusoft/magictransportchest/listener/InventoryOpenEventListener.kt | nafu-at | 790,790,517 | false | {"Kotlin": 71580} | /*
* Copyright 2024 Nafu Satsuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.nafusoft.magictransportchest.listener
import dev.nafusoft.magictransportchest.entities.MagicInventoryHolder
import org.bukkit.ChatColor
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.inventory.InventoryOpenEvent
import redis.clients.jedis.Jedis
class InventoryOpenEventListener(private val jedis: Jedis) : Listener {
@EventHandler
fun onInventoryOpen(event: InventoryOpenEvent) {
val inventory = event.inventory
val holder = inventory.holder
if (holder is MagicInventoryHolder) {
if (jedis.exists("open:${holder.storageId}")) {
event.player.sendMessage("${ChatColor.RED}${ChatColor.BOLD}This chest is already opened by another player. Please wait a moment.")
event.isCancelled = true
}
jedis.set("open:${holder.storageId}", System.currentTimeMillis().toString())
}
}
}
| 0 | Kotlin | 0 | 0 | a65e5f2d7f9d4bcc672b3067b63e150fe9b2686d | 1,541 | MagicTransportChest | Apache License 2.0 |
src/main/java/dev/nafusoft/magictransportchest/listener/InventoryOpenEventListener.kt | nafu-at | 790,790,517 | false | {"Kotlin": 71580} | /*
* Copyright 2024 Nafu Satsuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.nafusoft.magictransportchest.listener
import dev.nafusoft.magictransportchest.entities.MagicInventoryHolder
import org.bukkit.ChatColor
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.inventory.InventoryOpenEvent
import redis.clients.jedis.Jedis
class InventoryOpenEventListener(private val jedis: Jedis) : Listener {
@EventHandler
fun onInventoryOpen(event: InventoryOpenEvent) {
val inventory = event.inventory
val holder = inventory.holder
if (holder is MagicInventoryHolder) {
if (jedis.exists("open:${holder.storageId}")) {
event.player.sendMessage("${ChatColor.RED}${ChatColor.BOLD}This chest is already opened by another player. Please wait a moment.")
event.isCancelled = true
}
jedis.set("open:${holder.storageId}", System.currentTimeMillis().toString())
}
}
}
| 0 | Kotlin | 0 | 0 | a65e5f2d7f9d4bcc672b3067b63e150fe9b2686d | 1,541 | MagicTransportChest | Apache License 2.0 |
code/core/src/main/java/com/adobe/marketing/mobile/services/ui/floatingbutton/FloatingButtonEventListener.kt | adobe | 458,293,389 | false | {"Kotlin": 1649922, "Java": 1480893, "Makefile": 7304, "Shell": 3493} | /*
Copyright 2023 Adobe. All rights reserved.
This file is licensed to you 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
package com.adobe.marketing.mobile.services.ui.floatingbutton
import com.adobe.marketing.mobile.services.ui.FloatingButton
import com.adobe.marketing.mobile.services.ui.Presentable
import com.adobe.marketing.mobile.services.ui.PresentationEventListener
/**
* Interface for listening to events on a floating button presentation.
*/
interface FloatingButtonEventListener : PresentationEventListener<FloatingButton> {
/**
* Called when a tap is detected on the floating button.
* @param presentable the floating button presentable on which the tap was detected
*/
fun onTapDetected(presentable: Presentable<FloatingButton>)
/**
* Called when a pan is detected on the floating button.
* @param presentable the floating button presentable on which the pan was detected
*/
fun onPanDetected(presentable: Presentable<FloatingButton>)
}
| 14 | Kotlin | 24 | 9 | 882669b9a1b6c0315d44b937d0a73b114f36ca28 | 1,489 | aepsdk-core-android | Apache License 2.0 |
app/src/main/java/com/flarnrules/pixelartpad/CanvasView.kt | flarnrules | 737,172,119 | false | {"Kotlin": 2073} | package com.flarnrules.pixelartpad
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Color
import android.view.MotionEvent
import android.view.View
class CanvasView(context: Context) : View(context) {
private val paint = Paint()
private var bitmap: Bitmap = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)
private var canvas = Canvas(bitmap)
private val blockSize = 40f // Size of each block in the grid
init {
paint.style = Paint.Style.FILL
bitmap.eraseColor(Color.WHITE) // Set default color
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// Draw the 16x16 grid
for (i in 0 until 16) {
for (j in 0 until 16) {
paint.color = bitmap.getPixel(i, j)
canvas.drawRect(
i * blockSize,
j * blockSize,
(i + 1) * blockSize,
(j + 1) * blockSize,
paint
)
}
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val x = (event.x / blockSize).toInt()
val y = (event.y / blockSize).toInt()
if (event.action == MotionEvent.ACTION_DOWN || event.action == MotionEvent.ACTION_MOVE) {
if (x < 16 && y < 16) {
// Set the pixel to a fixed color for now, e.g., black
bitmap.setPixel(x, y, Color.BLACK)
invalidate()
}
}
return true
}
}
| 0 | Kotlin | 0 | 0 | 26288dd358c37a68176aa4bff724dfd528c95284 | 1,624 | pixel-art-pad | MIT License |
library/src/main/kotlin/com/devbrackets/android/exomedia/nmp/config/PlayerConfigBuilder.kt | brianwernick | 32,229,221 | false | null | /*
* Copyright (C) 2021 ExoMedia Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.devbrackets.android.exomedia.nmp.config
import android.content.Context
import android.os.Handler
import android.os.Looper
import com.devbrackets.android.exomedia.AudioPlayer
import com.devbrackets.android.exomedia.core.renderer.PlayerRendererFactory
import com.devbrackets.android.exomedia.core.source.MediaSourceProvider
import com.devbrackets.android.exomedia.core.source.data.DataSourceFactoryProvider
import com.devbrackets.android.exomedia.core.source.data.DefaultDataSourceFactoryProvider
import com.devbrackets.android.exomedia.nmp.manager.UserAgentProvider
import com.devbrackets.android.exomedia.nmp.manager.WakeManager
import com.devbrackets.android.exomedia.nmp.manager.track.TrackManager
import com.devbrackets.android.exomedia.util.FallbackManager
import com.google.android.exoplayer2.DefaultLoadControl
import com.google.android.exoplayer2.LoadControl
import com.google.android.exoplayer2.RenderersFactory
import com.google.android.exoplayer2.analytics.AnalyticsCollector
import com.google.android.exoplayer2.source.DefaultMediaSourceFactory
import com.google.android.exoplayer2.source.MediaSourceFactory
import com.google.android.exoplayer2.upstream.BandwidthMeter
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter
import com.google.android.exoplayer2.util.Clock
class PlayerConfigBuilder(private val context: Context) {
private var analyticsCollector: AnalyticsCollector? = null
private var bandwidthMeter: BandwidthMeter? = null
private var handler: Handler? = null
private var rendererFactory: RenderersFactory? = null
private var trackManager: TrackManager? = null
private var wakeManager: WakeManager? = null
private var loadControl: LoadControl? = null
private var userAgentProvider: UserAgentProvider? = null
private var mediaSourceProvider: MediaSourceProvider? = null
private var mediaSourceFactory: MediaSourceFactory? = null
private var dataSourceFactoryProvider: DataSourceFactoryProvider? = null
private var fallbackManager: FallbackManager? = null
fun setAnalyticsCollector(analyticsCollector: AnalyticsCollector): PlayerConfigBuilder {
this.analyticsCollector = analyticsCollector
return this
}
fun setBandwidthMeter(bandwidthMeter: BandwidthMeter): PlayerConfigBuilder {
this.bandwidthMeter = bandwidthMeter
return this
}
fun setHandler(handler: Handler): PlayerConfigBuilder {
this.handler = handler
return this
}
fun setRendererFactory(factory: RenderersFactory): PlayerConfigBuilder {
this.rendererFactory = factory
return this
}
fun setTrackManager(trackManager: TrackManager): PlayerConfigBuilder {
this.trackManager = trackManager
return this
}
fun setWakeManager(wakeManager: WakeManager): PlayerConfigBuilder {
this.wakeManager = wakeManager
return this
}
/**
* Specifies the [LoadControl] to use when building the [com.google.android.exoplayer2.ExoPlayer] instance
* used in the [com.devbrackets.android.exomedia.ui.widget.VideoView] and [AudioPlayer]. This allows the
* buffering amounts to be modified to better suit your needs which can be easily specified by using an instance of
* [com.google.android.exoplayer2.DefaultLoadControl]. When the `loadControl` is `null`
* the default instance of the [com.google.android.exoplayer2.DefaultLoadControl] will be used. This will only
* take effect for any instances created *after* this was set.
*
* @param loadControl The [LoadControl] to use for any new [com.google.android.exoplayer2.ExoPlayer] instances
*/
fun setLoadControl(loadControl: LoadControl): PlayerConfigBuilder {
this.loadControl = loadControl
return this
}
fun setUserAgentProvider(provider: UserAgentProvider): PlayerConfigBuilder {
this.userAgentProvider = provider
return this
}
fun setMediaSourceProvider(provider: MediaSourceProvider): PlayerConfigBuilder {
this.mediaSourceProvider = provider
return this
}
fun setMediaSourceFactory(factory: MediaSourceFactory): PlayerConfigBuilder {
this.mediaSourceFactory = factory
return this
}
/**
* Specifies the provider to use when building [com.google.android.exoplayer2.upstream.DataSource.Factory]
* instances for use with the [com.devbrackets.android.exomedia.core.source.builder.MediaSourceBuilder]s. This will
* only be used for builders that haven't customized the [com.devbrackets.android.exomedia.core.source.builder.MediaSourceBuilder.buildDataSourceFactory]
* method.
*
* @param provider The provider to use for the [com.devbrackets.android.exomedia.core.source.builder.MediaSourceBuilder]s
*/
fun setDataSourceFactoryProvider(provider: DataSourceFactoryProvider): PlayerConfigBuilder {
this.dataSourceFactoryProvider = provider
return this
}
fun setFallbackManager(manager: FallbackManager): PlayerConfigBuilder {
this.fallbackManager = manager
return this
}
fun build(): PlayerConfig {
val actualHandler = handler ?: Handler(Looper.getMainLooper())
val actualAnalyticsCollector = analyticsCollector ?: AnalyticsCollector(Clock.DEFAULT)
val rendererFactory = rendererFactory ?: PlayerRendererFactory(context)
return PlayerConfig(
context = context,
fallbackManager = fallbackManager ?: FallbackManager(),
analyticsCollector = actualAnalyticsCollector,
bandwidthMeter = bandwidthMeter ?: DefaultBandwidthMeter.Builder(context).build(),
handler = actualHandler,
rendererFactory = rendererFactory,
trackManager = trackManager ?: TrackManager(context),
wakeManager = wakeManager ?: WakeManager(context),
loadControl = loadControl ?: DefaultLoadControl(),
userAgentProvider = userAgentProvider ?: UserAgentProvider(),
mediaSourceProvider = mediaSourceProvider ?: MediaSourceProvider(),
mediaSourceFactory = mediaSourceFactory ?: DefaultMediaSourceFactory(context),
dataSourceFactoryProvider = dataSourceFactoryProvider ?: DefaultDataSourceFactoryProvider()
)
}
} | 26 | null | 370 | 1,956 | 201b76bc23a53e27b5ac66a943f478aa63266a73 | 6,677 | ExoMedia | Apache License 2.0 |
app/src/main/java/com/active/orbit/baseapp/design/activities/questionnaire/HealthResponseActivity.kt | oakgroup | 629,001,920 | false | {"Kotlin": 503256} | package com.active.orbit.baseapp.design.activities.questionnaire
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import com.active.orbit.baseapp.R
import com.active.orbit.baseapp.core.database.models.DBHealth
import com.active.orbit.baseapp.core.database.tables.TableHealth
import com.active.orbit.baseapp.core.enums.HealthType
import com.active.orbit.baseapp.core.routing.enums.Extra
import com.active.orbit.baseapp.core.utils.Constants
import com.active.orbit.baseapp.core.utils.Logger
import com.active.orbit.baseapp.core.utils.ThreadHandler.backgroundThread
import com.active.orbit.baseapp.core.utils.ThreadHandler.mainThread
import com.active.orbit.baseapp.core.utils.TimeUtils
import com.active.orbit.baseapp.databinding.ActivityHealthResponseDetailsBinding
import com.active.orbit.baseapp.design.activities.engine.BaseActivity
import com.active.orbit.baseapp.design.utils.UiUtils
class HealthResponseActivity : BaseActivity(), View.OnClickListener {
private lateinit var binding: ActivityHealthResponseDetailsBinding
var response: Int = Constants.INVALID
var healthType: HealthType = HealthType.UNDEFINED
var healthResponse: DBHealth? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHealthResponseDetailsBinding.inflate(layoutInflater)
setContentView(binding.root)
showBackButton()
backgroundThread {
val modelId = activityBundle.getString(Extra.IDENTIFIER.key, Constants.EMPTY)
if (modelId != Constants.EMPTY) {
healthResponse = TableHealth.getById(this, modelId)
if (healthResponse?.isValid() != true) {
mainThread {
Logger.e("Model is not valid on on ${javaClass.name}")
UiUtils.showShortToast(this, R.string.health_show_error)
finish()
}
} else {
mainThread {
prepare()
}
}
}
}
}
private fun prepare() {
healthType = HealthType.MOBILITY
binding.timestamp.text = TimeUtils.format(TimeUtils.getCurrent(healthResponse?.healthID!!), Constants.DATE_FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
binding.mobilityTitle.text = getString(HealthType.MOBILITY.title)
binding.selfcareTitle.text = getString(HealthType.SELF_CARE.title)
binding.usualActivitiesTitle.text = getString(HealthType.USUAL_ACTIVITIES.title)
binding.painTitle.text = getString(HealthType.PAIN.title)
binding.anxietyTitle.text = getString(HealthType.ANXIETY.title)
binding.mobilityResponse.text = healthType.getResponse(healthResponse?.healthMobility!!, this)
binding.selfcareResponse.text = healthType.getResponse(healthResponse?.healthSelfCare!!, this)
binding.usualActivitiesResponse.text = healthType.getResponse(healthResponse?.healthActivities!!, this)
binding.painResponse.text = healthType.getResponse(healthResponse?.healthPain!!, this)
binding.anxietyResponse.text = healthType.getResponse(healthResponse?.healthAnxiety!!, this)
binding.mobilityResponse.isChecked = true
binding.selfcareResponse.isChecked = true
binding.usualActivitiesResponse.isChecked = true
binding.painResponse.isChecked = true
binding.anxietyResponse.isChecked = true
binding.healthScoreProgress.setBackgroundLineColorOne(ContextCompat.getColor(this, R.color.colorSecondaryLight))
binding.healthScoreProgress.setBackgroundLineColorTwo(ContextCompat.getColor(this, R.color.colorSecondaryLight))
binding.healthScoreProgress.setProgressLineColorOne(ContextCompat.getColor(this, R.color.colorPrimary))
binding.healthScoreProgress.setProgressLineColorTwo(ContextCompat.getColor(this, R.color.colorSecondary))
binding.healthScoreProgress.setLineWidth(20f)
binding.healthScoreProgress.hideProgressIcon()
binding.healthScoreProgress.setMaxProgress(Constants.HEALTH_MAX_PROGRESS.toFloat())
binding.healthScoreProgress.setProgress(healthResponse?.healthScore!!.toFloat())
binding.healthScore.text = getString(R.string.health_score_label, healthResponse?.healthScore.toString())
binding.mobilityResponse.setOnClickListener(this)
binding.selfcareResponse.setOnClickListener(this)
binding.usualActivitiesResponse.setOnClickListener(this)
binding.painResponse.setOnClickListener(this)
binding.anxietyResponse.setOnClickListener(this)
}
override fun onClick(v: View?) {
when(v) {
binding.mobilityResponse -> {
binding.mobilityResponse.isChecked = true
UiUtils.showShortToast(this,"Your answer cannot change")
}
binding.selfcareResponse -> {
binding.selfcareResponse.isChecked = true
UiUtils.showShortToast(this,"Your answer cannot change")
}
binding.usualActivitiesResponse -> {
binding.usualActivitiesResponse.isChecked = true
UiUtils.showShortToast(this,"Your answer cannot change")
}
binding.painResponse -> {
binding.painResponse.isChecked = true
UiUtils.showShortToast(this,"Your answer cannot change")
}
binding.anxietyResponse -> {
binding.anxietyResponse.isChecked = true
UiUtils.showShortToast(this,"Your answer cannot change")
}
}
}
}
| 0 | Kotlin | 0 | 0 | e34f107c1c1cf4408f070c145a62bb1ef739cb2c | 5,722 | android-bhf-doctors | MIT License |
app/src/main/java/com/taitascioredev/android/tvseriesdemo/feature/tvshowdetails/ShowDetailsAction.kt | phanghos | 119,651,014 | false | null | package com.taitascioredev.android.tvseriesdemo.feature.tvshowdetails
import com.taitascioredev.android.tvseriesdemo.presentation.base.Action
/**
* Created by rrtatasciore on 25/01/18.
*/
class ShowDetailsAction(val showId: Int) : Action | 0 | Kotlin | 0 | 1 | f2992ac104f0733d0707027e1c025d1f3ed6bf85 | 241 | tv-series-demo | MIT License |
shared/src/main/kotlin/com/github/denisidoro/korn/Main.kt | denisidoro | 130,622,460 | false | null | package com.github.denisidoro.korn
import com.github.denisidoro.korn.header.header
import com.github.denisidoro.korn.rating.*
import react.React
import react.Style
import react.native.AppRegistry
import react.registerComponent
import react.view
val kotlinStore = createStore(Rating("Kotlin", 55))
val javascriptStore = createStore(Rating("JavaScript", 50))
fun main(args: Array<String>) {
AppRegistry.registerComponent<HelloWorld>("Korn")
}
class HelloWorld : React.Component<Any, Any>() {
override fun render() =
view {
header()
rating(kotlinStore)
rating(javascriptStore)
}
}
| 0 | Kotlin | 2 | 20 | 5459000d2742596ac612785bb7a81f7fd2ba2b37 | 662 | korn | Apache License 2.0 |
app/src/main/java/com/e444er/cleanmovie/core/domain/use_case/firebase/movie/AddMovieToWatchListInFirebaseUseCase.kt | e444er | 597,756,971 | false | null | package com.e444er.cleanmovie.core.domain.use_case.firebase.movie
import com.e444er.cleanmovie.R
import com.e444er.cleanmovie.core.domain.models.MovieWatchListItem
import com.e444er.cleanmovie.core.domain.repository.FirebaseCoreMovieRepository
import com.e444er.cleanmovie.core.domain.repository.FirebaseCoreRepository
import com.e444er.cleanmovie.core.presentation.util.UiText
import com.e444er.cleanmovie.core.util.Constants
import javax.inject.Inject
class AddMovieToWatchListInFirebaseUseCase @Inject constructor(
private val firebaseCoreRepository: FirebaseCoreRepository,
private val firebaseCoreMovieRepository: FirebaseCoreMovieRepository
) {
operator fun invoke(
moviesInWatchList: List<MovieWatchListItem>,
onSuccess: () -> Unit,
onFailure: (uiText: UiText) -> Unit
) {
val currentUser = firebaseCoreRepository.getCurrentUser()
val userUid = currentUser?.uid
?: return onFailure(UiText.StringResource(R.string.must_login_able_to_add_in_list))
val data = mapOf(
Constants.FIREBASE_MOVIES_FIELD_NAME to moviesInWatchList
)
firebaseCoreMovieRepository.addMovieToWatchList(
userUid = userUid,
data = data,
onSuccess = onSuccess,
onFailure = onFailure
)
}
} | 0 | Kotlin | 0 | 0 | 1c939de424b4eb254fd4258f4e56e4399bdfb3cd | 1,331 | KinoGoClean | Apache License 2.0 |
app/src/main/java/com/apps/adrcotfas/goodtime/bl/TimerService.kt | adrcotfas | 61,319,303 | false | null | /*
* Copyright 2016-2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package com.apps.adrcotfas.goodtime.bl
import com.apps.adrcotfas.goodtime.database.AppDatabase.Companion.getDatabase
import dagger.hilt.android.AndroidEntryPoint
import androidx.lifecycle.LifecycleService
import javax.inject.Inject
import com.apps.adrcotfas.goodtime.settings.PreferenceHelper
import org.greenrobot.eventbus.EventBus
import kotlin.jvm.Synchronized
import android.content.Intent
import org.greenrobot.eventbus.Subscribe
import com.apps.adrcotfas.goodtime.util.Constants.OneMinuteLeft
import com.apps.adrcotfas.goodtime.util.Constants.FinishWorkEvent
import com.apps.adrcotfas.goodtime.util.Constants.FinishBreakEvent
import com.apps.adrcotfas.goodtime.util.Constants.FinishLongBreakEvent
import com.apps.adrcotfas.goodtime.util.Constants.UpdateTimerProgressEvent
import com.apps.adrcotfas.goodtime.util.Constants.ClearNotificationEvent
import com.apps.adrcotfas.goodtime.util.Constants.StartSessionEvent
import android.os.PowerManager
import android.media.AudioManager
import androidx.annotation.RequiresApi
import android.os.Build
import android.app.NotificationManager
import android.net.wifi.WifiManager
import com.apps.adrcotfas.goodtime.main.TimerActivity
import android.annotation.TargetApi
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.apps.adrcotfas.goodtime.database.Session
import com.apps.adrcotfas.goodtime.util.Constants
import com.apps.adrcotfas.goodtime.util.toFormattedTime
import com.apps.adrcotfas.goodtime.util.toLocalTime
import kotlinx.coroutines.*
import java.lang.Exception
import java.lang.Runnable
import java.util.concurrent.TimeUnit
/**
* Class representing the foreground service which triggers the countdown timer and handles events.
*/
@AndroidEntryPoint
class TimerService : LifecycleService() {
@Inject
lateinit var notificationHelper: NotificationHelper
@Inject
lateinit var ringtoneAndVibrationPlayer: RingtoneAndVibrationPlayer
@Inject
lateinit var preferenceHelper: PreferenceHelper
@Inject
lateinit var currentSessionManager: CurrentSessionManager
private var previousRingerMode = 0
private var previousWifiMode = false
override fun onCreate() {
super.onCreate()
Log.d(TAG, "onCreate " + this.hashCode())
notificationHelper = NotificationHelper(applicationContext)
EventBus.getDefault().register(this)
}
override fun onDestroy() {
Log.d(TAG, "onDestroy " + this.hashCode())
EventBus.getDefault().unregister(this)
super.onDestroy()
}
@Synchronized
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this)
}
var result = START_STICKY
if (intent == null) {
return result
}
Log.d(TAG, "onStartCommand " + this.hashCode() + " " + intent.action)
when (intent.action) {
Constants.ACTION.STOP -> onStopEvent()
Constants.ACTION.TOGGLE -> {
onToggleEvent()
result = START_NOT_STICKY
}
Constants.ACTION.START -> {
val sessionType =
SessionType.valueOf(intent.getStringExtra(Constants.SESSION_TYPE)!!)
onStartEvent(sessionType)
}
Constants.ACTION.ADD_SECONDS -> onAdd60Seconds()
Constants.ACTION.SKIP -> onSkipEvent()
else -> {
}
}
return result
}
/**
* Called when an event is posted to the EventBus
* @param o holds the type of the Event
*/
@Subscribe
fun onEvent(o: Any) {
when (o) {
is OneMinuteLeft -> {
onOneMinuteLeft()
}
is FinishWorkEvent -> {
Log.d(TAG, "onEvent " + o.javaClass.simpleName)
onFinishEvent(SessionType.WORK)
}
is FinishBreakEvent -> {
Log.d(TAG, "onEvent " + o.javaClass.simpleName)
onFinishEvent(SessionType.BREAK)
}
is FinishLongBreakEvent -> {
onFinishEvent(SessionType.LONG_BREAK)
}
is UpdateTimerProgressEvent -> {
updateNotificationProgress()
}
is ClearNotificationEvent -> {
Log.d(TAG, "onEvent " + o.javaClass.simpleName)
notificationHelper.clearNotification()
ringtoneAndVibrationPlayer.stop()
}
}
}
private fun onStartEvent(sessionType: SessionType) {
var sessionTypeTmp = sessionType
EventBus.getDefault().post(StartSessionEvent())
if (sessionTypeTmp !== SessionType.WORK && preferenceHelper.isLongBreakEnabled()
&& preferenceHelper.itsTimeForLongBreak()
) {
sessionTypeTmp = SessionType.LONG_BREAK
}
Log.d(TAG, "onStartEvent: $sessionTypeTmp")
currentSessionManager.startTimer(sessionTypeTmp)
if (sessionTypeTmp === SessionType.WORK) {
if (preferenceHelper.isWiFiDisabled()) {
toggleWifi(false)
}
if (preferenceHelper.isSoundAndVibrationDisabled()) {
toggleSound(false)
}
if (preferenceHelper.isDndModeActive()) {
toggleDndMode(false)
}
}
if (!preferenceHelper.isAutoStartWork() && !preferenceHelper.isAutoStartBreak()) {
ringtoneAndVibrationPlayer.stop()
}
notificationHelper.clearNotification()
startForeground(
NotificationHelper.GOODTIME_NOTIFICATION_ID, notificationHelper.getInProgressBuilder(
currentSessionManager.currentSession
).build()
)
}
private fun onToggleEvent() {
currentSessionManager.toggleTimer()
startForeground(
NotificationHelper.GOODTIME_NOTIFICATION_ID, notificationHelper.getInProgressBuilder(
currentSessionManager.currentSession
).build()
)
}
private fun onStopEvent() {
Log.d(TAG, "onStopEvent")
if (preferenceHelper.isWiFiDisabled()) {
toggleWifi(true)
}
if (preferenceHelper.isSoundAndVibrationDisabled()) {
toggleSound(true)
}
if (preferenceHelper.isDndModeActive()) {
toggleDndMode(true)
}
val sessionType = currentSessionManager.currentSession.sessionType.value
Log.d(TAG, "onStopEvent, sessionType: $sessionType")
if (sessionType === SessionType.LONG_BREAK) {
preferenceHelper.resetCurrentStreak()
}
stopForeground()
stopSelf()
finalizeSession(sessionType, currentSessionManager.elapsedMinutesAtStop)
}
private fun onOneMinuteLeft() {
acquireScreenLock()
bringActivityToFront()
ringtoneAndVibrationPlayer.play(SessionType.WORK, false)
}
private fun onFinishEvent(sessionType: SessionType) {
Log.d(
TAG,
[email protected]().toString() + " onFinishEvent " + sessionType.toString()
)
acquireScreenLock()
bringActivityToFront()
if (sessionType === SessionType.WORK) {
if (preferenceHelper.isWiFiDisabled()) {
toggleWifi(true)
}
if (preferenceHelper.isSoundAndVibrationDisabled()) {
toggleSound(true)
}
if (preferenceHelper.isDndModeActive()) {
toggleDndMode(true)
}
}
ringtoneAndVibrationPlayer.play(sessionType, preferenceHelper.isRingtoneInsistent())
stopForeground()
updateLongBreakStreak(sessionType)
// store what was done to the database
finalizeSession(sessionType, currentSessionManager.elapsedMinutesAtFinished)
if (preferenceHelper.isAutoStartBreak() && sessionType === SessionType.WORK) {
onStartEvent(SessionType.BREAK)
} else if (preferenceHelper.isAutoStartWork() && sessionType !== SessionType.WORK) {
onStartEvent(SessionType.WORK)
} else {
notificationHelper.notifyFinished(sessionType)
}
}
private fun onAdd60Seconds() {
Log.d(TAG, [email protected]().toString() + " onAdd60Seconds ")
preferenceHelper.increment60SecondsCounter()
if (currentSessionManager.currentSession.timerState.value == TimerState.INACTIVE) {
startForeground(
NotificationHelper.GOODTIME_NOTIFICATION_ID,
notificationHelper.getInProgressBuilder(
currentSessionManager.currentSession
).build()
)
}
currentSessionManager.add60Seconds()
}
private fun onSkipEvent() {
val sessionType = currentSessionManager.currentSession.sessionType.value
Log.d(
TAG,
[email protected]().toString() + " onSkipEvent " + sessionType.toString()
)
if (sessionType === SessionType.WORK) {
if (preferenceHelper.isWiFiDisabled()) {
toggleWifi(true)
}
if (preferenceHelper.isSoundAndVibrationDisabled()) {
toggleSound(true)
}
if (preferenceHelper.isDndModeActive()) {
toggleDndMode(true)
}
}
currentSessionManager.stopTimer()
stopForeground()
updateLongBreakStreak(sessionType)
finalizeSession(sessionType, currentSessionManager.elapsedMinutesAtStop)
onStartEvent(if (sessionType === SessionType.WORK) SessionType.BREAK else SessionType.WORK)
}
private fun updateLongBreakStreak(sessionType: SessionType?) {
if (preferenceHelper.isLongBreakEnabled()) {
if (sessionType === SessionType.LONG_BREAK) {
preferenceHelper.resetCurrentStreak()
} else if (sessionType === SessionType.WORK) {
preferenceHelper.incrementCurrentStreak()
}
Log.d(
TAG,
"preferenceHelper.getCurrentStreak: " + preferenceHelper.getCurrentStreak()
)
Log.d(
TAG,
"preferenceHelper.lastWorkFinishedAt: " + preferenceHelper.lastWorkFinishedAt()
)
}
}
private fun acquireScreenLock() {
val powerManager = getSystemService(POWER_SERVICE) as PowerManager
val wakeLock = powerManager.newWakeLock(
PowerManager.FULL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP,
AlarmReceiver::class.java.name
)
wakeLock.acquire(5000)
}
private fun updateNotificationProgress() {
notificationHelper.updateNotificationProgress(
currentSessionManager.currentSession
)
}
private fun toggleSound(restore: Boolean) {
if (isNotificationPolicyAccessGranted) {
toggleSoundInternal(restore)
} else {
// should not happen
Log.w(TAG, "Trying to toggle sound but permission was not granted.")
}
}
private fun toggleSoundInternal(restore: Boolean) {
val t = Thread {
val aManager = getSystemService(AUDIO_SERVICE) as AudioManager
if (restore) {
if (previousRingerMode == AudioManager.RINGER_MODE_SILENT) {
return@Thread
}
aManager.ringerMode = previousRingerMode
} else {
previousRingerMode = aManager.ringerMode
aManager.ringerMode = AudioManager.RINGER_MODE_SILENT
}
}
t.start()
}
private fun toggleDndMode(restore: Boolean) {
if (isNotificationPolicyAccessGranted) {
togglePriorityMode(restore)
} else {
// should not happen
Log.w(TAG, "Trying to toggle DnD mode but permission was not granted.")
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
private fun togglePriorityMode(restore: Boolean) {
val t = Thread {
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
if (restore) {
manager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL)
} else {
manager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY)
}
}
t.start()
}
private fun toggleWifi(restore: Boolean) {
val r = Runnable {
val wifiManager = this.getSystemService(WIFI_SERVICE) as WifiManager
if (restore) {
wifiManager.isWifiEnabled = previousWifiMode
} else {
previousWifiMode = wifiManager.isWifiEnabled
wifiManager.isWifiEnabled = false
}
}
val t = Thread(r)
t.start()
}
private fun finalizeSession(sessionType: SessionType?, minutes: Int) {
currentSessionManager.stopTimer()
preferenceHelper.resetAdd60SecondsCounter()
currentSessionManager.currentSession.setDuration(
TimeUnit.MINUTES.toMillis(preferenceHelper.getSessionDuration(SessionType.WORK))
)
if (sessionType !== SessionType.WORK) {
return
}
val labelVal = currentSessionManager.currentSession.label.value
val labelValProper =
if (labelVal == null || labelVal == "" || labelVal == "unlabeled") null else labelVal
val endTime = System.currentTimeMillis()
Log.d(TAG, "finalizeSession / elapsed minutes: $minutes")
if (minutes > 0) {
Log.d(
TAG,
"finalizeSession, saving session finished at" + endTime.toLocalTime()
.toFormattedTime()
)
val session = Session(0, endTime, minutes, labelValProper)
lifecycleScope.launch {
try {
getDatabase(applicationContext).sessionModel().addSession(session)
} catch (e: Exception) {
// the label was deleted in the meantime so set it to null and save the unlabeled session
withContext(Dispatchers.Main) {
currentSessionManager.currentSession.setLabel("")
}
val newSession = session.apply { label = null }
getDatabase(applicationContext).sessionModel().addSession(newSession)
}
}
}
}
private fun stopForeground() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
stopForeground(STOP_FOREGROUND_REMOVE)
else
stopForeground(true)
}
private fun bringActivityToFront() {
val activityIntent = Intent(this, TimerActivity::class.java)
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
activityIntent.putExtra("42", 42)
application.startActivity(activityIntent)
}
@get:TargetApi(Build.VERSION_CODES.M)
private val isNotificationPolicyAccessGranted: Boolean
get() {
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
return notificationManager.isNotificationPolicyAccessGranted
}
companion object {
private val TAG = TimerService::class.java.simpleName
}
} | 76 | null | 96 | 957 | 95845d126d914e68b46b8abab83e378978c2127c | 16,250 | Goodtime | Apache License 2.0 |
backend/src/org/kotlinacademy/backend/usecases/LogUseCase.kt | MarcinMoskala | 111,068,526 | false | null | package org.kotlinacademy.backend.usecases
import org.kotlinacademy.backend.repositories.db.LogDatabaseRepository
object LogUseCase {
suspend fun add(deviceType: String, userId: String, action: String, extra: String) {
val logDatabaseRepository = LogDatabaseRepository.get()
logDatabaseRepository.add(deviceType, userId, action, extra)
}
} | 9 | CSS | 58 | 446 | e7ad620f5a2fb2e3a0330928ed560adf1925d797 | 367 | KtAcademyPortal | Apache License 2.0 |
app/src/main/java/com/babylone/playbook/ui/splash/SplashViewState.kt | itslonua | 182,047,511 | false | {"Kotlin": 73294} | package com.babylone.playbook.ui.splash
import com.babylone.playbook.core.Resource
data class SplashViewState(val resource: Resource<Boolean>) {
companion object {
fun init(): SplashViewState {
return SplashViewState(Resource.loading(null))
}
}
} | 0 | Kotlin | 0 | 0 | ec7d289f5e41056f4776804ae008b642f8bb70ae | 286 | babylon-samples-mvi | MIT License |
shared/feature/geminio-sdk/src/test/kotlin/ru/hh/plugins/geminio/sdk/recipe/parsers/GeminioPredefinedFeatureSectionParserSpec.kt | hhru | 159,637,875 | false | null | package ru.hh.plugins.geminio.sdk.recipe.parsers
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.shouldBe
import org.yaml.snakeyaml.Yaml
import ru.hh.plugins.geminio.sdk.recipe.models.predefined.PredefinedFeature
import ru.hh.plugins.geminio.sdk.recipe.models.predefined.PredefinedFeatureParameter
import ru.hh.plugins.geminio.sdk.recipe.models.predefined.PredefinedFeaturesSection
import ru.hh.plugins.geminio.sdk.recipe.parsers.predefined.toPredefinedFeaturesSection
internal class GeminioPredefinedFeatureSectionParserSpec : FreeSpec({
"Should support predefined feature section without params" {
val predefineSection = """
predefinedFeatures:
- enableModuleCreationParams
""".trimIndent()
val parsed: Map<String, Any> = Yaml().load(predefineSection)
val expected = PredefinedFeaturesSection(
mapOf(
PredefinedFeature.ENABLE_MODULE_CREATION_PARAMS to
PredefinedFeatureParameter.ModuleCreationParameter()
)
)
parsed.toPredefinedFeaturesSection() shouldBe expected
}
"Should support predefined feature section with defaultPackageNamePrefix" {
val testPackageNamePrefix = "ru.hh.test"
val predefineSection = """
predefinedFeatures:
- enableModuleCreationParams:
defaultPackageNamePrefix: $testPackageNamePrefix
""".trimIndent()
val parsed: Map<String, Any> = Yaml().load(predefineSection)
val expected = PredefinedFeaturesSection(
mapOf(
PredefinedFeature.ENABLE_MODULE_CREATION_PARAMS to
PredefinedFeatureParameter.ModuleCreationParameter(testPackageNamePrefix)
)
)
parsed.toPredefinedFeaturesSection() shouldBe expected
}
"Should ignore if defaultPackageNamePrefix not exist" {
val predefineSection = """
predefinedFeatures:
- enableModuleCreationParams:
someDifferentParam: other
""".trimIndent()
val parsed: Map<String, Any> = Yaml().load(predefineSection)
val expected = PredefinedFeaturesSection(
mapOf(
PredefinedFeature.ENABLE_MODULE_CREATION_PARAMS to
PredefinedFeatureParameter.ModuleCreationParameter()
)
)
parsed.toPredefinedFeaturesSection() shouldBe expected
}
})
| 17 | Kotlin | 11 | 97 | 2d6c02fc814eff3934c17de77ef7ade91d3116f5 | 2,485 | android-multimodule-plugin | MIT License |
vxutil-vertigram/src/main/kotlin/ski/gagar/vxutil/vertigram/types/BotCommandScopeDefault.kt | gagarski | 314,041,476 | false | null | package ski.gagar.vxutil.vertigram.types
object BotCommandScopeDefault : BotCommandScope {
override val type: BotCommandScopeType = BotCommandScopeType.DEFAULT
}
| 0 | Kotlin | 0 | 0 | 9cb9209e905df3602fc87147c317ca75fdc12ad0 | 167 | vxutil | Apache License 2.0 |
flutter/packages/freelance/android/app/src/main/kotlin/com/example/freelance/MainActivity.kt | growerp | 524,615,937 | false | {"Groovy": 2587022, "Dart": 1983848, "Java": 1246390, "JavaScript": 742688, "FreeMarker": 724651, "HTML": 187442, "CSS": 73735, "Swift": 43724, "CMake": 36132, "Dockerfile": 25825, "C++": 22180, "Ruby": 17039, "Shell": 11753, "C": 2764, "Kotlin": 1735, "Procfile": 548, "Objective-C": 532} | package org.growerp.freelance
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 1 | Groovy | 29 | 61 | 1683837d237deef7832c3204730cdb185e2bec79 | 126 | growerp | Creative Commons Zero v1.0 Universal |
sample/src/main/java/com/afollestad/materialcabsample/ViewHolders.kt | afollestad | 35,056,138 | false | null | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.materialcabsample
import android.view.View
import android.widget.TextView
import com.afollestad.recyclical.ViewHolder
class MainViewHolder(itemView: View) : ViewHolder(itemView) {
val icon: View = itemView.findViewById(R.id.icon)
val title: TextView = itemView.findViewById(R.id.title)
}
| 5 | Kotlin | 102 | 995 | c053373ae56af32ff097d902a0f6911a56d71559 | 942 | material-cab | Apache License 2.0 |
backend/src/main/kotlin/dev/kviklet/kviklet/db/Event.kt | kviklet | 687,049,294 | false | {"Kotlin": 261537, "TypeScript": 163731, "HTML": 2400, "Dockerfile": 1972, "JavaScript": 1930, "CSS": 593, "Shell": 25} | package dev.kviklet.kviklet.db
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.annotation.JsonTypeName
import dev.kviklet.kviklet.db.util.BaseEntity
import dev.kviklet.kviklet.db.util.EventPayloadConverter
import dev.kviklet.kviklet.service.dto.Event
import dev.kviklet.kviklet.service.dto.EventType
import dev.kviklet.kviklet.service.dto.ExecuteEvent
import dev.kviklet.kviklet.service.dto.ExecutionRequestDetails
import dev.kviklet.kviklet.service.dto.ReviewAction
import jakarta.persistence.Column
import jakarta.persistence.Convert
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import org.apache.commons.lang3.builder.ToStringBuilder
import org.apache.commons.lang3.builder.ToStringStyle.SHORT_PREFIX_STYLE
import org.hibernate.annotations.ColumnTransformer
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Service
import java.time.LocalDateTime
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "foobar", visible = false)
sealed class Payload(
val type: EventType,
)
@JsonTypeName("COMMENT")
data class CommentPayload(
val comment: String,
) : Payload(EventType.COMMENT)
@JsonTypeName("REVIEW")
data class ReviewPayload(
val comment: String,
val action: ReviewAction,
) : Payload(EventType.REVIEW)
@JsonTypeName("EDIT")
data class EditPayload(
val previousQuery: String,
) : Payload(EventType.EDIT)
@JsonTypeName("EXECUTE")
data class ExecutePayload(
val query: String,
) : Payload(EventType.EXECUTE)
@Entity(name = "event")
class EventEntity(
@ManyToOne
@JoinColumn(name = "execution_request_id")
val executionRequest: ExecutionRequestEntity,
@ManyToOne
@JoinColumn(name = "author_id")
val author: UserEntity,
@Enumerated(EnumType.STRING)
private val type: EventType,
@Convert(converter = EventPayloadConverter::class)
@Column(columnDefinition = "json")
@ColumnTransformer(write = "?::json")
private val payload: Payload,
private val createdAt: LocalDateTime = LocalDateTime.now(),
) : BaseEntity() {
override fun toString(): String {
return ToStringBuilder(this, SHORT_PREFIX_STYLE)
.append("id", id)
.toString()
}
fun toDto(request: ExecutionRequestDetails? = null): Event {
if (request == null) {
val executionDetails = executionRequest.toDetailDto()
return executionDetails.events.find { it.eventId == id }!!
}
return Event.create(
id = id,
createdAt = createdAt,
payload = payload,
author = author.toDto(),
request = request,
)
}
}
interface EventRepository : JpaRepository<EventEntity, String> {
fun findByType(type: EventType): List<EventEntity>
}
@Service
class EventAdapter(
private val eventRepository: EventRepository,
) {
fun getExecutions(): List<ExecuteEvent> {
val events = eventRepository.findByType(EventType.EXECUTE)
return events.map { it.toDto() }.filterIsInstance<ExecuteEvent>()
}
}
| 4 | Kotlin | 3 | 99 | 79a2668fbf66f6a6984b09d5520b1b60667e73ee | 3,363 | kviklet | MIT License |
app/src/main/java/com/jerimkaura/contacts/SplashScreen.kt | jerimkaura | 520,493,196 | false | null | package com.jerimkaura.contacts
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.WindowManager
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import com.jerimkaura.contacts.databinding.ActivitySplashScreenBinding
@SuppressLint("CustomSplashScreen")
class SplashScreen : AppCompatActivity() {
private lateinit var binding: ActivitySplashScreenBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySplashScreenBinding.inflate(layoutInflater)
setContentView(binding.root)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
binding.animationView.setAnimation(R.raw.splash)
binding.animationView.animate().startDelay = 3000
binding.animationView.playAnimation()
Handler().postDelayed({
startActivity(Intent(this@SplashScreen, MainActivity::class.java))
finish()
}, 3000)
}
} | 0 | Kotlin | 0 | 0 | 1e590768743984a979a59f29e0775cbae4f1a028 | 1,372 | Contacts | The Unlicense |
sketch-compose-core/src/commonTest/kotlin/com/github/panpf/sketch/compose/core/common/test/state/IconAnimatablePainterStateImageCommonTest.kt | panpf | 14,798,941 | false | null | package com.github.panpf.sketch.compose.core.common.test.state
import androidx.compose.runtime.Composable
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import com.github.panpf.sketch.painter.asEquality
import com.github.panpf.sketch.state.rememberIconAnimatablePainterStateImage
import com.github.panpf.sketch.test.utils.SizeColorPainter
class IconAnimatablePainterStateImageCommonTest {
// TODO test
@Composable
fun CreateFunctionTest() {
val painterIcon =
Color.Cyan.let { SizeColorPainter(it, Size(100f, 100f)).asEquality(it) }
val painterBackground =
Color.Gray.let { SizeColorPainter(it, Size(100f, 100f)).asEquality(it) }
val colorBackground = Color.DarkGray
val iconSize = Size(200f, 200f)
val iconTint = Color.Magenta
// painter icon
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
background = painterBackground,
iconSize = iconSize,
iconTint = iconTint
)
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
background = colorBackground,
iconSize = iconSize,
iconTint = iconTint
)
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
background = painterBackground,
iconSize = iconSize,
)
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
background = colorBackground,
iconSize = iconSize,
)
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
background = painterBackground,
iconTint = iconTint
)
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
background = colorBackground,
iconTint = iconTint
)
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
iconSize = iconSize,
iconTint = iconTint
)
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
background = painterBackground,
)
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
background = colorBackground,
)
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
iconSize = iconSize,
)
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
iconTint = iconTint
)
rememberIconAnimatablePainterStateImage(
icon = painterIcon,
)
}
} | 8 | null | 309 | 2,057 | 89784530da0de6085a5b08f810415147cb3165cf | 2,706 | sketch | Apache License 2.0 |
rekotlin/src/test/kotlin/org/rekotlin/StoreSubscriptionTests.kt | rakutentech | 180,487,130 | true | {"Kotlin": 149039, "Shell": 1423} | /**
* 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.rekotlin
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test
class StoreSubscriptionTests {
@Test
fun `should notify subscriber of state changes after subscribing`() {
val store = store(::intReducer, IntState())
val subscriber = FakeSubscriber<IntState>()
store.subscribe(subscriber)
val baseline = subscriber.callCount
store.dispatch(IntAction(333))
assert(subscriber.callCount == baseline + 1)
assert(subscriber.lastState?.number == 333)
store.dispatch(IntAction(1337))
assert(subscriber.callCount == baseline + 2)
assert(subscriber.lastState?.number == 1337)
}
@Test
fun `should prevent duplicate subscriber silently`() {
val store = store(::intReducer, IntState())
val subscriber = FakeSubscriber<IntState>()
store.subscribe(subscriber)
store.subscribe(subscriber)
val callCount = subscriber.callCount
store.dispatch(IntAction(333))
assert(subscriber.callCount == callCount + 1)
}
@Test
fun `should prevent duplicate subscriber silently with substate selectors`() {
val store = store(::intReducer, IntState())
val subscriber = FakeSubscriber<Int?>()
store.subscribe(subscriber) { select { number } }
store.subscribe(subscriber) { select { number } }
val callCount = subscriber.callCount
store.dispatch(IntAction(333))
assert(subscriber.callCount == callCount + 1)
}
/**
* it replaces the subscription of an existing subscriber with the new one.
*/
@Test
fun `should prevent duplicate subscriber silently even when subscribing with and without state selector`() {
val store = store(::intReducer, IntState())
val subscriber = FakeSubscriber<IntState>()
store.subscribe(subscriber)
store.subscribe(subscriber) { skip { old, new -> old.number == new.number } }
val callCount = subscriber.callCount
store.dispatch(IntAction(1))
assert(subscriber.callCount == callCount + 1) // still only subscribed once
}
@Test
fun `should skip repeats automatically`() {
val store = store(::intReducer, IntState())
val subscriber = FakeSubscriber<IntState>()
store.subscribe(subscriber)
val action = IntAction(777)
store.dispatch(action)
val callCount = subscriber.callCount
// dispatching actions should be idempotent
store.dispatch(action)
store.dispatch(action)
store.dispatch(action)
// no state change, therefore no more calls
assert(subscriber.callCount == callCount)
}
@Test
fun `should pass initial state to subscriber upon subscribing`() {
val initalState = IntState(1723)
val store = store(::intReducer, initalState)
val subscriber = FakeSubscriber<IntState>()
store.subscribe(subscriber)
assert(subscriber.lastState == initalState)
}
@Test
fun `should pass initial state to subscriber upon subscribing, even if store was initialized with null state`() {
val initalState = null
val store = store(::intReducer, initalState)
val subscriber = FakeSubscriber<IntState>()
store.subscribe(subscriber)
assert(subscriber.callCount == 1)
}
@Test
fun `should allow to dispatch from a subscriber callback`() {
val store = ParentStore(::intReducer, IntState())
val subscriber = subscriber<IntState> { state ->
// Test if we've already dispatched this action to
// avoid endless recursion
if (state.number != 5) {
store.dispatch(IntAction(5))
}
}
store.subscribe(subscriber)
store.dispatch(IntAction(2))
assert(store.state.number == 5)
}
@Test
fun `should not notify subscriber after unsubscribe`() {
val store = store(::intReducer, IntState(0))
val subscriber = FakeSubscriber<IntState>()
store.subscribe(subscriber)
store.dispatch(IntAction(1))
store.dispatch(IntAction(2))
store.unsubscribe(subscriber)
store.dispatch(IntAction(3))
store.dispatch(IntAction(4))
assert(subscriber.history.map { it.number } == listOf(0, 1, 2))
}
@Test
fun `should allow to re-subscribe after unsubscribe`() {
val store = store(::intReducer, IntState(0))
val subscriber = FakeSubscriber<IntState>()
store.subscribe(subscriber)
store.dispatch(IntAction(1))
store.dispatch(IntAction(2))
store.unsubscribe(subscriber)
store.dispatch(IntAction(3))
store.dispatch(IntAction(4))
store.dispatch(IntAction(5))
store.subscribe(subscriber)
store.dispatch(IntAction(6))
assert(subscriber.history.map { it.number } == listOf(0, 1, 2, 5, 6))
}
@Test
fun `should allow to subscribe new subscriber during new state callback to subscriber`() {
val store = store(::stringReducer, StringState("initial"))
val subOne = FakeSubscriber<StringState>()
val subTwo = FakeSubscriber<StringState> { store.subscribe(subOne) }
store.subscribe(subTwo)
assert(subOne.callCount == 1)
assert(subTwo.callCount == 1)
// implicitly test this doesn't crash
}
class SelfUnSubscriber<T>(private val store: SubscribeStore<T>) : Subscriber<T> {
val callCount get() = _callCount
var _callCount = 0
override fun newState(state: T) {
_callCount += 1
store.unsubscribe(this)
}
}
@Test
fun `should allow to unsubscribe during new state callback`() {
val store = store(::stringReducer, StringState("initial"))
val subscriber = SelfUnSubscriber(store)
store.subscribe(subscriber)
store.dispatch(StringAction(""))
store.dispatch(StringAction(""))
store.dispatch(StringAction(""))
assert(subscriber.callCount == 1)
}
class SelfSubscriber<T>(private val store: SubscribeStore<T>) : Subscriber<T> {
override fun newState(state: T) {
store.subscribe(this)
}
}
@Test
fun `should not allow to re-subscribe oneself in new state callback to subscriber`() {
val store = store(::stringReducer, StringState("initial"))
val subscribre = SelfSubscriber(store)
try {
store.subscribe(subscribre)
fail<Any>("expected stack overflow")
} catch (e: StackOverflowError) {
assertNotNull(e)
}
}
}
| 0 | Kotlin | 3 | 6 | db4ccbce4845d0d10fa2499ed0b4477f67d74bdf | 7,878 | ReKotlin | MIT License |
usage-tracking/disabled/src/main/java/com/spotify/heroic/usagetracking/disabled/DisabledUsageTrackingModule.kt | spotify | 36,483,902 | false | null | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.spotify.heroic.usagetracking.disabled
import com.spotify.heroic.dagger.PrimaryComponent
import com.spotify.heroic.usagetracking.UsageTracking
import com.spotify.heroic.usagetracking.UsageTrackingComponent
import com.spotify.heroic.usagetracking.UsageTrackingModule
import dagger.Module
import dagger.Provides
@Module
class DisabledUsageTrackingModule: UsageTrackingModule {
override fun module(primary: PrimaryComponent): UsageTrackingComponent {
return DaggerDisabledUsageTrackingComponent
.builder()
.primaryComponent(primary)
.disabledUsageTrackingModule(this)
.build()
}
@DisabledScope
@Provides
fun usageTracking(usageTracking: DisabledUsageTracking): UsageTracking {
return usageTracking
}
class Builder: UsageTrackingModule.Builder {
var version: String = ""
var commit: String = ""
override fun version(version: String, commit: String): Builder {
return this
}
override fun build() = DisabledUsageTrackingModule()
}
}
| 70 | null | 110 | 845 | 9a021a7a4acf643012cd0b2bfe8f59e7b6cfda89 | 1,938 | heroic | Apache License 2.0 |
src/main/kotlin/dev/aohara/posts/Kotshi.kt | oharaandrew314 | 752,391,842 | false | {"Kotlin": 4375} | package dev.aohara.posts
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import org.http4k.format.*
import se.ansman.kotshi.KotshiJsonAdapterFactory
@KotshiJsonAdapterFactory
private object PostsJsonAdapterFactory : JsonAdapter.Factory by KotshiPostsJsonAdapterFactory
val kotshi = Moshi.Builder()
.add(PostsJsonAdapterFactory)
.add(ListAdapter)
.add(MapAdapter)
.asConfigurable()
.withStandardMappings()
.done()
.let { ConfigurableMoshi(it) } | 0 | Kotlin | 0 | 6 | 7d71368e98947f4fd052609d4d4ec48aedfe6217 | 496 | have-your-serverless-kotlin-functions | Apache License 2.0 |
incidents-and-rides-visualizer/src/main/kotlin/main/Main.kt | simra-project | 360,834,204 | false | {"Kotlin": 72103, "HTML": 21180, "Java": 15472, "Shell": 4211} | package main
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.opencsv.CSVParserBuilder
import com.opencsv.CSVReaderBuilder
import com.xenomachina.argparser.ArgParser
import com.xenomachina.argparser.mainBody
import org.apache.logging.log4j.LogManager
import org.geojson.*
import java.io.*
import java.nio.file.Paths
import java.text.SimpleDateFormat
import java.util.*
/**
* Generates an html file containing a leaflet map with the rides and incidents of the specified region
*/
private val logger = LogManager.getLogger()
private val bikeTypes = arrayOf("-","City-/Trekking Bike","Road Racing Bike","E-Bike","Liegerad","Lastenrad","Tandembike","Mountainbik","Sonstiges")
private val phoneLocations = arrayOf("Hosentasche","Lenker","Jackentasche","Hand","Fahrradkorb","Rucksack/Tasche","Sonstiges")
private val incidentTypes = arrayOf("Nichts","Zu dichtes Überholen","Ein- oder ausparkendes Fahrzeug","Beinahe-Abbiegeunfall","Entgegenkommender Verkehrsteilnehmer","Zu dichtes Auffahren","Beinahe-Dooring","Hindernis ausweichen (z.B. Hund)","Sonstiges")
private val participants = arrayOf("Bus","Fahrrad","Fußgänger","Lieferwagen","LKW","Motorrad","PKW","Taxi","Sonstiges","E-Scooter")
fun main(args: Array<String>) {
val startTime = System.currentTimeMillis()
val cla = mainBody { ArgParser(args).parseInto(::Conf) }
val incidentsInfo: MutableList<String> = mutableListOf()
val ridesInfo: MutableMap<String, MutableList<String>> = mutableMapOf()
logger.info("creating " + cla.outputDir.absolutePath + File.separator + cla.region + "-incidents.json and " + cla.outputDir.absolutePath + File.separator + cla.region + "-incidents.html")
var bboxList: ArrayList<Double>? = null
if (cla.bbox != "0.0,0.0,0.0,0.0") {
bboxList = ArrayList()
cla.bbox.split(",").forEach { it ->
bboxList.add(it.toDouble())
}
}
File(cla.simraRoot.toURI()).walk().maxDepth(1).forEach { it ->
if(cla.region.toString().lowercase() == it.name.lowercase() || (cla.region.toString() == "all" && !it.name.endsWith(".zip") && !it.name.contains("_")) && !it.name.equals("Regions")) {
File(it.toURI()).walk().forEach { path ->
if(path.isFile && path.toString().contains("Rides") && path.name.startsWith("VM2_")) {
val thisIncidentsInfo: MutableList<String> = getIncidents(path.absolutePath)
val thisRidesInfo: MutableList<String> = getGPSPoints(path.absolutePath, bboxList)
incidentsInfo.addAll(thisIncidentsInfo)
if (thisRidesInfo.size > 0) {
ridesInfo[path.name] = thisRidesInfo
}
}
}
}
}
printGeoJson(incidentsInfo, ridesInfo, cla.outputDir, cla.region.toString())
val endTime = System.currentTimeMillis()
logger.info("Done. Number of Rides: ${ridesInfo.size}. Number of Incidents: ${incidentsInfo.size}. Execution took ${((endTime - startTime)/1000)} seconds.")
}
/**
* Pretty prints a geoJson file where the incidents are written as points.
*/
fun printGeoJson(incidents: MutableList<String>, rides: MutableMap<String, MutableList<String>>, outputDir: File, region: String) {
val featureCollection = FeatureCollection()
var incidentsAsCsv = "lat,lon,ts,bike,childCheckBox,trailerCheckBox,pLoc,incident,i1,i2,i3,i4,i5,i6,i7,i8,i9,scary,desc,i10,region\n"
incidents.forEach { incidentLine ->
val elements: List<String>
if (incidentLine.contains(",\"") && incidentLine.contains("\",")) {
val parser = CSVParserBuilder().withSeparator(',').withQuoteChar('\"').build()
val csvReader = CSVReaderBuilder(StringReader(incidentLine)).withSkipLines(0).withCSVParser(parser).build()
elements = csvReader.readNext().toList()
incidentsAsCsv += incidentLine + "\n"
} else {
elements = incidentLine.split(",")
val cleanedIncidentLine = incidentLine.replace(";komma;",",").replace(";linebreak;","\\n")
incidentsAsCsv += (cleanedIncidentLine + "\n")
}
val point = Point((elements[1]).toDouble(),(elements[0]).toDouble())
val propertiesMap = mutableMapOf<String,String>()
val sdf = SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
val timestamp = if (elements[2].isNotEmpty()) sdf.format((Date((elements[2]).toLong()))) else 0
val bikeType = if (elements[3].isNotEmpty()) bikeTypes[elements[3].toInt()] else "-"
val childCheckBox = if (elements[4] == "1") "Ja" else "Nein"
val trailerCheckBox = if (elements[5] == "1") "Ja" else "Nein"
val pLoc = if (elements[6].isNotEmpty()) phoneLocations[elements[6].toInt()] else phoneLocations[0]
val incident = if (elements[7].isNotEmpty()) incidentTypes[elements[7].toInt()] else incidentTypes[0]
var prefix = ""
var participantsText = "";
elements.subList(8,17).forEachIndexed() { index, participant ->
if (participant.isNotEmpty() && participant.toInt() == 1) {
participantsText += prefix
participantsText += participants[index]
prefix = ", "
}
}
val scary = if (elements[17] == "1") "Ja" else "Nein"
val desc = elements[18].replace(";komma;",",").replace(";linebreak;","\\n")
participantsText += if (elements[19] == "1") (prefix + participants[9]) else ""
val thisRegion = if (elements.size > 20) {
elements[20]
} else {
elements[19]
}
val rideName = if (elements.size > 21) {
elements[21]
} else {
elements[20]
}
propertiesMap["date"] = timestamp.toString()
propertiesMap["bikeType"] = bikeType
propertiesMap["child"] = childCheckBox
propertiesMap["trailer"] = trailerCheckBox
propertiesMap["pLoc"] = pLoc
propertiesMap["incident"] = incident
propertiesMap["participant"] = participantsText
propertiesMap["scary"] = scary
propertiesMap["descr"] = desc
propertiesMap["region"] = thisRegion
propertiesMap["ride"] = rideName
featureCollection.add(Feature().apply {
geometry = point
properties = propertiesMap as Map<String, Any>?
})
}
rides.forEach { rideLine ->
val lineString = LineString()
rideLine.value.forEach { entry ->
lineString.add(LngLatAlt(entry.split(",")[1].toDouble(),entry.split(",")[0].toDouble()))
}
val propertiesMap = mutableMapOf<String,String>()
propertiesMap["ride"] = rideLine.key
featureCollection.add(Feature().apply {
geometry = lineString
properties = propertiesMap as Map<String, Any>?
})
}
val pathToOutputHtml = outputDir.absolutePath + File.separator + region + ".html"
val htmlContent = StringBuilder()
val html = object {}.javaClass.getResource("/Template.html")?.readText()?.split("\r\n")
html?.forEach { line ->
if (line != "const ridesUrl = null;") {
htmlContent.appendLine(line)
} else {
htmlContent.append("const ridesUrl = ")
htmlContent.append(ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(featureCollection))
htmlContent.appendLine(";")
}
}
Paths.get(pathToOutputHtml).toFile().writeText(htmlContent.toString())
val redMarker = object {}.javaClass.getResource("/redmarker.png")
File(redMarker!!.toURI()).copyTo(File("${outputDir.absolutePath}${File.separator}redmarker.png"),true)
val blueMarker = object {}.javaClass.getResource("/bluemarker.png")
File(blueMarker!!.toURI()).copyTo(File("${outputDir.absolutePath}${File.separator}bluemarker.png"),true)
}
/**
* Traverses a given ride and returns a List of incidents without incident key
* @param path - The absolute path to the ride file
* @return incidents without keys of given ride
*/
fun getIncidents(path: String): MutableList<String> {
val region = path.split("Regions${File.separator}")[1].split("${File.separator}Rides")[0]
val result: MutableList<String> = mutableListOf() // contains the result
val inputStream: InputStream = File(path).inputStream() // read the file
var incidentPart = false // set to true after the incident header "key,lat,lon,..." is passed
// iterate through the ride file
inputStream.bufferedReader().useLines { lines -> lines.forEach { line ->
if (line.isEmpty()) {
return result
}
// if incident part is reached...
if (incidentPart) {
// split the array by comma
var lineArray = line.split(",")
// omit the first element (key)
lineArray = lineArray.subList(1, lineArray.size)
var thisIncident = ""
var prefix = ""
// add the elements to result
lineArray.forEach { element ->
thisIncident += (prefix)
thisIncident += (element)
prefix = ","
}
if(!thisIncident.startsWith(",,,") && lineArray[7].isNotEmpty() && lineArray[7].toInt() != -5 && lineArray[7].toInt() != 0) {
thisIncident = correctTimeStamp(thisIncident, path)
result.add("$thisIncident,$region,${File(path).name}")
} // set incidentPart to true, if header "key,lat,lon,..." is reached
} else if(line.startsWith("key,lat,lon")) {
incidentPart = true
}
} }
return result
}
/**
* Traverses a given ride and returns a List of GPS and timestamps (lat,lon,ts) or null, if given bbox is not null and
* ride does not go through bbox
* @param path - The absolute path to the ride file
* @param bbox - (optional) if given, checks if the ride goes through the bbox.
* @return gps and timestamp of given ride
*/
fun getGPSPoints(path: String, bbox: ArrayList<Double>?): MutableList<String> {
var result: MutableList<String> = mutableListOf() // contains the result
val inputStream: InputStream = File(path).inputStream() // read the file
var ridePart = false // set to true after the ride header "lat,lon,X,Y,Z" is passed
var goesThroughBBox = false // set to true if ride goes through the bbox if given any
// iterate through the ride file
inputStream.bufferedReader().useLines { lines -> lines.forEach {
// if ride part is reached...
if (ridePart) {
// split the array by comma
val lineArray = it.split(",")
// and if the line is a gps line, add lat, lon and ts to result
if(lineArray[0].isNotEmpty()) {
val lat = lineArray[0]
val lon = lineArray[1]
result.add(("$lat,$lon"))
if (bbox != null) {
if (inBoundingBox(bbox[0],bbox[1],bbox[2],bbox[3],lat.toDouble(),lon.toDouble())) {
goesThroughBBox = true
}
}
}
}
// set ridePart to true, if header "lat,lon,X,Y,Z" is reached
if(it.startsWith("lat,lon,X,Y,Z")) {
ridePart = true
}
} }
if (bbox != null && !goesThroughBBox) {
result = mutableListOf()
}
return result
}
fun inBoundingBox(blLat: Double, blLon: Double, trLat: Double, trLon:Double, pLat:Double, pLon:Double): Boolean {
// in case longitude 180 is inside the box
return pLat in blLat..trLat && pLon in blLon..trLon
}
/**
* Retrieves the correct timestamp of old manually added incidents, which had 1337 as timestamp
*/
fun correctTimeStamp(thisIncident: String, path: String): String {
val parser = CSVParserBuilder().withSeparator(',').withIgnoreQuotations(true).build()
// val csvReader = CSVReaderBuilder(StringReader(thisIncident.replace("“","\""))).withSkipLines(0).withCSVParser(parser).build()
val csvReader = CSVReaderBuilder(StringReader(thisIncident)).withSkipLines(0).withCSVParser(parser).build()
val elements: MutableList<String> = csvReader.readNext().toList().toMutableList()
if (elements[2] != "1337") {
return thisIncident
} else {
val lat = elements[0] // latitude to look for in the ride part
val lon = elements[1] // longitude to look for in the ride part
val inputStream: InputStream = File(path).inputStream() // read the file
var ridePart = false // set to true after the ride header "lat,lon,X,..." is passed
inputStream.bufferedReader().useLines { lines ->
lines.forEach { line ->
if (line.isNotEmpty()) {
if (ridePart && !line.startsWith(",,")) {
val thisLine = line.split(",")
val thisLat = thisLine[0]
val thisLon = thisLine[1]
if (thisLat == lat && thisLon == lon) {
elements[2] = thisLine[5]
}
} else if (line.startsWith("lat,lon,X")) {
ridePart = true
}
}
}
}
return elements.joinToString(separator = ",")
}
}
| 0 | Kotlin | 0 | 0 | 01601085a6ecab2afac549814e9afaddd221180e | 13,418 | scripts | MIT License |
app/src/main/java/ir/rainyday/listexample/modules/messaging/MessagingActivity.kt | noundla | 147,912,823 | true | {"Kotlin": 123089, "Java": 1141} | package ir.rainyday.listexample.modules.messaging
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import ir.rainyday.listexample.R
import kotlinx.android.synthetic.main.content_messaging.*
import kotlinx.android.synthetic.main.layout_regular_appbar.*
class MessagingActivity : AppCompatActivity() {
val adapter = MessagingAdapter(this)
private val recyclerView: RecyclerView by lazy {
val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
linearLayoutManager.reverseLayout = true
reyclerview_message_list?.layoutManager = linearLayoutManager
reyclerview_message_list.setHasFixedSize(true)
reyclerview_message_list
}
private val viewModel: MessagingViewModel by lazy {
ViewModelProviders.of(this).get(MessagingViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_messaging)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true);
supportActionBar?.setDisplayShowHomeEnabled(true);
recyclerView.adapter=adapter
viewModel.items.observe(this, Observer { messages ->
adapter.items = messages
})
button_chatbox_send.setOnClickListener {
sendMessage()
}
edittext_chatbox.addTextChangedListener(object :TextWatcher{
override fun afterTextChanged(text: Editable?) {
button_chatbox_send.isEnabled = !(text.isNullOrEmpty())
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
})
edittext_chatbox.setOnEditorActionListener(object :TextView.OnEditorActionListener{
override fun onEditorAction(p0: TextView?, i: Int, p2: KeyEvent?): Boolean {
if (i == EditorInfo.IME_ACTION_SEND) {
sendMessage()
return true;
}
return false;
}
})
}
private fun sendMessage() {
val text = edittext_chatbox.text
if (text.isNullOrEmpty())
return
viewModel.sendMessage(text!!.toString())
recyclerView.scrollToPosition(0)
edittext_chatbox.text = null
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}
| 0 | Kotlin | 0 | 0 | 83cc7a38b12a5e5f7c0b5ac62e23a08453071f79 | 2,952 | AndroidEasyList | MIT License |
src/main/kotlin/no/java/mooseheadreborn/util/EmailTextGenerator.kt | javaBin | 835,594,711 | false | {"Kotlin": 63792, "TypeScript": 42500, "HTML": 3273, "Shell": 1428, "Procfile": 180, "CSS": 21} | package no.java.mooseheadreborn.util
import no.java.mooseheadreborn.*
enum class EmailTemplate(val templatePath:String,val subject:String) {
REGISTER_CONFIRMATION("templates/registrationConfirmation.html","Workshop confirmation"),
REGISTER_CONFIRMATION_WAITING("templates/waitingConfirmation.html","Workshop confirmation"),
PARTICIPANT_CONFIRMATION("templates/confirmEmail.html","Confirm email"),
CANCEL_CONFIRMATION("templates/cancelConfirmation.html","Workshop registration cancelled"),
}
enum class EmailVariable {
CANCEL_LINK,
CONFIRM_EMAIL_LINK,
WORKSHOP_NAME,
WORKSHOP_TIME_TEXT,
PARTICIPANT_REGISTER_LINK,
}
object EmailTextGenerator {
fun loadText(template: EmailTemplate,variableMap:Map<EmailVariable,String>): String {
val inputStream = this::class.java.classLoader.getResourceAsStream(template.templatePath)
val content = StringBuilder(inputStream?.bufferedReader().use { it?.readText() }?:"")
variableMap.forEach { (variable, value) ->
val search = "#${variable.name}#"
while (true) {
val pos = content.indexOf(search)
if (pos == -1) break
content.replace(pos,pos+search.length,value)
}
}
return content.toString()
}
fun emailConfirnmAddress(registerKey:String):String = "${Config.getConfigValue(ConfigVariable.SERVER_ADDRESS)}/activate/$registerKey"
fun cancelLinkAddress(registrationId:String):String = "${Config.getConfigValue(ConfigVariable.SERVER_ADDRESS)}/registration/$registrationId"
fun participantSummmaryAddress(participantId:String):String = "${Config.getConfigValue(ConfigVariable.SERVER_ADDRESS)}/participant/$participantId"
} | 0 | Kotlin | 0 | 0 | fd29e169a351d30933bbcb9cf9db32e2c952d0c2 | 1,737 | mooseheadreborn | Apache License 2.0 |
ocpp-2-0-api-adapter/src/main/kotlin/com/izivia/ocpp/adapter20/mapper/NotifyChargingLimitMapper.kt | IZIVIA | 501,708,979 | false | {"Kotlin": 1934096} | package com.izivia.ocpp.adapter20.mapper
import com.izivia.ocpp.core20.model.common.enumeration.ChargingLimitSourceEnumType
import com.izivia.ocpp.core20.model.notifycharginglimit.ChargingLimitType
import com.izivia.ocpp.core20.model.notifycharginglimit.NotifyChargingLimitReq
import com.izivia.ocpp.core20.model.notifycharginglimit.NotifyChargingLimitResp
import org.mapstruct.Mapper
import org.mapstruct.Mapping
import org.mapstruct.Named
import org.mapstruct.ReportingPolicy
import com.izivia.ocpp.api.model.common.enumeration.ChargingLimitSourceEnumType as ChargingLimitSourceEnumTypeGen
import com.izivia.ocpp.api.model.notifycharginglimit.ChargingLimitType as ChargingLimitTypeGen
import com.izivia.ocpp.api.model.notifycharginglimit.NotifyChargingLimitReq as NotifyChargingLimitReqGen
import com.izivia.ocpp.api.model.notifycharginglimit.NotifyChargingLimitResp as NotifyChargingLimitRespGen
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
abstract class NotifyChargingLimitMapper {
@Named("convertChargingLimitSource")
fun convertChargingLimitSource(chargingLimitSource: ChargingLimitSourceEnumTypeGen): ChargingLimitSourceEnumType =
ChargingLimitSourceEnumType.valueOf(chargingLimitSource.value)
@Named("convertChargingLimit")
fun convertChargingLimit(chargingLimit: ChargingLimitTypeGen): ChargingLimitType =
ChargingLimitType(convertChargingLimitSource(chargingLimit.chargingLimitSource), chargingLimit.isGridCritical)
@Mapping(target = "chargingLimit", source = "chargingLimit", qualifiedByName = ["convertChargingLimit"])
abstract fun genToCoreReq(notifyChargingLimitReq: NotifyChargingLimitReqGen?): NotifyChargingLimitReq
abstract fun coreToGenResp(notifyChargingLimitResp: NotifyChargingLimitResp?): NotifyChargingLimitRespGen
} | 6 | Kotlin | 10 | 32 | bd8e7334ae05ea75d02d96a508269acbe076bcd8 | 1,802 | ocpp-toolkit | MIT License |
ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/AppApi.kt | Fraunhofer-AISEC | 102,444,259 | false | null | /*-
* ========================LICENSE_START=================================
* ids-webconsole
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api
import de.fhg.aisec.ids.api.cm.ApplicationContainer
import de.fhg.aisec.ids.api.cm.ContainerManager
import de.fhg.aisec.ids.api.cm.NoContainerExistsException
import de.fhg.aisec.ids.api.settings.Settings
import de.fhg.aisec.ids.webconsole.ApiController
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.java.Java
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.http.ContentType
import io.ktor.serialization.jackson.jackson
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import io.swagger.annotations.ApiResponse
import io.swagger.annotations.ApiResponses
import io.swagger.annotations.Authorization
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.server.ResponseStatusException
import java.time.ZonedDateTime
import javax.ws.rs.core.MediaType
/**
* REST API interface for managing "apps" in the connector.
*
*
* In this implementation, apps are either docker or trustX containers.
*
*
* The API will be available at http://localhost:8181/cxf/api/v1/apps/<method>.
*
* @author Julian Schuette ([email protected])
</method> */
@ApiController
@RequestMapping("/app")
@Api(value = "Applications", authorizations = [Authorization(value = "oauth2")])
class AppApi {
@Autowired
private lateinit var cml: ContainerManager
@Autowired
private lateinit var settings: Settings
@GetMapping("list", produces = [MediaType.APPLICATION_JSON])
@ApiOperation(
value = "List all applications installed in the connector",
notes = "Returns an empty list if no apps are installed",
response = ApplicationContainer::class,
responseContainer = "List"
)
@ApiResponses(ApiResponse(code = 200, message = "List of apps"))
fun list(): List<ApplicationContainer> {
return cml.list(false).sortedWith { app1, app2 ->
try {
val date1 = ZonedDateTime.parse(app1.created)
val date2 = ZonedDateTime.parse(app2.created)
date1.compareTo(date2)
} catch (t: Exception) {
LOG.warn(
"Unexpected app creation date/time. Cannot sort pair [{}, {}]. {}",
app1.created,
app2.created,
t.message
)
0
}
}
}
@GetMapping("start/{containerId}", produces = [MediaType.APPLICATION_JSON])
@ApiOperation(
value = "Start an application",
notes = "Starting an application may take some time. " +
"This method will start the app asynchronously and return immediately. " +
"This method starts the latest version of the app.",
response = Boolean::class
)
@ApiResponses(
ApiResponse(
code = 200,
message = "true if the app has been requested to be started. " +
"false if no container management layer is available"
)
)
fun start(
@ApiParam(value = "ID of the app to start")
@PathVariable("containerId")
containerId: String
): Boolean {
return start(containerId, null)
}
@GetMapping("start/{containerId}/{key}", produces = [MediaType.APPLICATION_JSON])
@ApiOperation(
value = "Start an application",
notes = "Starting an application may take some time. This method will start the app asynchronously and return immediately. This methods starts a specific version of the app.",
response = Boolean::class
)
@ApiResponses(
ApiResponse(
code = 200,
message = "true if the app has been requested to be started. " +
"false if no container management layer is available"
)
)
fun start(
@ApiParam(value = "ID of the app to start")
@PathVariable("containerId")
containerId: String,
@ApiParam(value = "Key for user token (required for trustX containers)")
@PathVariable("key")
key: String?
): Boolean {
return try {
cml.startContainer(containerId, key)
true
} catch (e: NoContainerExistsException) {
LOG.error("Error starting container", e)
false
}
}
@GetMapping("stop/{containerId}", produces = [MediaType.APPLICATION_JSON])
@ApiOperation(
value = "Stop an app",
notes = "Stops an application. The application will remain installed and can be re-started later. All temporary data will be lost, however.",
response = Boolean::class
)
@ApiResponses(
ApiResponse(
code = 200,
message = "true if the app has been requested to be stopped. " +
"false if no container management layer is available"
)
)
fun stop(
@ApiParam(value = "ID of the app to stop")
@PathVariable("containerId")
containerId: String
): Boolean {
return try {
cml.stopContainer(containerId)
true
} catch (e: NoContainerExistsException) {
LOG.error(e.message, e)
false
}
}
@PostMapping("install", consumes = [MediaType.APPLICATION_JSON])
@ApiOperation(value = "Install an app", notes = "Requests to install an app.", response = Boolean::class)
@ApiResponses(
ApiResponse(
code = 200,
message = "If the app has been requested to be installed. " +
"The actual installation takes place asynchronously in the background " +
"and will terminate after a timeout of 20 minutes",
response = Boolean::class
),
ApiResponse(
code = 500,
message = "_No cmld_: If no container management layer is available",
response = String::class
),
ApiResponse(code = 500, message = "_Null image_: If imageID not given", response = String::class)
)
fun install(
@ApiParam(
value = "String with imageID",
collectionFormat = "Map"
)
@RequestBody
app: ApplicationContainer
) {
LOG.debug("Request to load {}", app.image)
val image = app.image
if (image == null) {
LOG.warn("Null image")
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Null image")
}
LOG.debug("Pulling app {}", image)
CoroutineScope(Dispatchers.IO).launch {
cml.pullImage(app)
}
}
@GetMapping("wipe")
@ApiOperation(value = "Wipes an app and all its data")
@ApiResponses(
ApiResponse(code = 200, message = "If the app is being wiped"),
ApiResponse(code = 500, message = "_No cmld_ if no container management layer is available")
)
fun wipe(
@ApiParam(value = "ID of the app to wipe")
@RequestParam
containerId: String
) {
CoroutineScope(Dispatchers.IO).launch {
try {
cml.wipe(containerId)
} catch (e: Throwable) {
LOG.error(e.message, e)
}
}
}
@GetMapping("cml_version", produces = [MediaType.APPLICATION_JSON])
@ApiOperation(
value = "Returns the version of the currently active container management layer",
response = MutableMap::class
)
fun getCml(): Map<String, String> {
return try {
val result: MutableMap<String, String> = HashMap()
result["cml_version"] = cml.version
result
} catch (sue: Exception) {
emptyMap()
}
}
@PostMapping(
"search",
consumes = [MediaType.TEXT_PLAIN],
produces = [MediaType.APPLICATION_JSON]
)
suspend fun search(@RequestBody term: String?): List<ApplicationContainer> {
return httpClient.get(settings.connectorConfig.appstoreUrl).body<List<ApplicationContainer>>().let { res ->
if (term?.isNotBlank() == true) {
res.filter { app: ApplicationContainer ->
app.name?.contains(term, true) ?: false ||
app.description?.contains(term, true) ?: false ||
app.image?.contains(term, true) ?: false ||
app.id?.contains(term, true) ?: false ||
app.categories.any { it.contains(term, true) }
}
} else {
res
}
}
}
companion object {
private val LOG = LoggerFactory.getLogger(AppApi::class.java)
private val httpClient = HttpClient(Java) {
install(ContentNegotiation) {
jackson(ContentType.Any)
}
}
}
}
| 7 | null | 39 | 44 | 7c3028edac913ea03b2e735e1896990f92e7bcb7 | 10,304 | trusted-connector | Apache License 2.0 |
ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/AppApi.kt | Fraunhofer-AISEC | 102,444,259 | false | null | /*-
* ========================LICENSE_START=================================
* ids-webconsole
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api
import de.fhg.aisec.ids.api.cm.ApplicationContainer
import de.fhg.aisec.ids.api.cm.ContainerManager
import de.fhg.aisec.ids.api.cm.NoContainerExistsException
import de.fhg.aisec.ids.api.settings.Settings
import de.fhg.aisec.ids.webconsole.ApiController
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.java.Java
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.http.ContentType
import io.ktor.serialization.jackson.jackson
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import io.swagger.annotations.ApiResponse
import io.swagger.annotations.ApiResponses
import io.swagger.annotations.Authorization
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.server.ResponseStatusException
import java.time.ZonedDateTime
import javax.ws.rs.core.MediaType
/**
* REST API interface for managing "apps" in the connector.
*
*
* In this implementation, apps are either docker or trustX containers.
*
*
* The API will be available at http://localhost:8181/cxf/api/v1/apps/<method>.
*
* @author <NAME> (<EMAIL>)
</method> */
@ApiController
@RequestMapping("/app")
@Api(value = "Applications", authorizations = [Authorization(value = "oauth2")])
class AppApi {
@Autowired
private lateinit var cml: ContainerManager
@Autowired
private lateinit var settings: Settings
@GetMapping("list", produces = [MediaType.APPLICATION_JSON])
@ApiOperation(
value = "List all applications installed in the connector",
notes = "Returns an empty list if no apps are installed",
response = ApplicationContainer::class,
responseContainer = "List"
)
@ApiResponses(ApiResponse(code = 200, message = "List of apps"))
fun list(): List<ApplicationContainer> {
return cml.list(false).sortedWith { app1, app2 ->
try {
val date1 = ZonedDateTime.parse(app1.created)
val date2 = ZonedDateTime.parse(app2.created)
date1.compareTo(date2)
} catch (t: Exception) {
LOG.warn(
"Unexpected app creation date/time. Cannot sort pair [{}, {}]. {}",
app1.created,
app2.created,
t.message
)
0
}
}
}
@GetMapping("start/{containerId}", produces = [MediaType.APPLICATION_JSON])
@ApiOperation(
value = "Start an application",
notes = "Starting an application may take some time. " +
"This method will start the app asynchronously and return immediately. " +
"This method starts the latest version of the app.",
response = Boolean::class
)
@ApiResponses(
ApiResponse(
code = 200,
message = "true if the app has been requested to be started. " +
"false if no container management layer is available"
)
)
fun start(
@ApiParam(value = "ID of the app to start")
@PathVariable("containerId")
containerId: String
): Boolean {
return start(containerId, null)
}
@GetMapping("start/{containerId}/{key}", produces = [MediaType.APPLICATION_JSON])
@ApiOperation(
value = "Start an application",
notes = "Starting an application may take some time. This method will start the app asynchronously and return immediately. This methods starts a specific version of the app.",
response = Boolean::class
)
@ApiResponses(
ApiResponse(
code = 200,
message = "true if the app has been requested to be started. " +
"false if no container management layer is available"
)
)
fun start(
@ApiParam(value = "ID of the app to start")
@PathVariable("containerId")
containerId: String,
@ApiParam(value = "Key for user token (required for trustX containers)")
@PathVariable("key")
key: String?
): Boolean {
return try {
cml.startContainer(containerId, key)
true
} catch (e: NoContainerExistsException) {
LOG.error("Error starting container", e)
false
}
}
@GetMapping("stop/{containerId}", produces = [MediaType.APPLICATION_JSON])
@ApiOperation(
value = "Stop an app",
notes = "Stops an application. The application will remain installed and can be re-started later. All temporary data will be lost, however.",
response = Boolean::class
)
@ApiResponses(
ApiResponse(
code = 200,
message = "true if the app has been requested to be stopped. " +
"false if no container management layer is available"
)
)
fun stop(
@ApiParam(value = "ID of the app to stop")
@PathVariable("containerId")
containerId: String
): Boolean {
return try {
cml.stopContainer(containerId)
true
} catch (e: NoContainerExistsException) {
LOG.error(e.message, e)
false
}
}
@PostMapping("install", consumes = [MediaType.APPLICATION_JSON])
@ApiOperation(value = "Install an app", notes = "Requests to install an app.", response = Boolean::class)
@ApiResponses(
ApiResponse(
code = 200,
message = "If the app has been requested to be installed. " +
"The actual installation takes place asynchronously in the background " +
"and will terminate after a timeout of 20 minutes",
response = Boolean::class
),
ApiResponse(
code = 500,
message = "_No cmld_: If no container management layer is available",
response = String::class
),
ApiResponse(code = 500, message = "_Null image_: If imageID not given", response = String::class)
)
fun install(
@ApiParam(
value = "String with imageID",
collectionFormat = "Map"
)
@RequestBody
app: ApplicationContainer
) {
LOG.debug("Request to load {}", app.image)
val image = app.image
if (image == null) {
LOG.warn("Null image")
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Null image")
}
LOG.debug("Pulling app {}", image)
CoroutineScope(Dispatchers.IO).launch {
cml.pullImage(app)
}
}
@GetMapping("wipe")
@ApiOperation(value = "Wipes an app and all its data")
@ApiResponses(
ApiResponse(code = 200, message = "If the app is being wiped"),
ApiResponse(code = 500, message = "_No cmld_ if no container management layer is available")
)
fun wipe(
@ApiParam(value = "ID of the app to wipe")
@RequestParam
containerId: String
) {
CoroutineScope(Dispatchers.IO).launch {
try {
cml.wipe(containerId)
} catch (e: Throwable) {
LOG.error(e.message, e)
}
}
}
@GetMapping("cml_version", produces = [MediaType.APPLICATION_JSON])
@ApiOperation(
value = "Returns the version of the currently active container management layer",
response = MutableMap::class
)
fun getCml(): Map<String, String> {
return try {
val result: MutableMap<String, String> = HashMap()
result["cml_version"] = cml.version
result
} catch (sue: Exception) {
emptyMap()
}
}
@PostMapping(
"search",
consumes = [MediaType.TEXT_PLAIN],
produces = [MediaType.APPLICATION_JSON]
)
suspend fun search(@RequestBody term: String?): List<ApplicationContainer> {
return httpClient.get(settings.connectorConfig.appstoreUrl).body<List<ApplicationContainer>>().let { res ->
if (term?.isNotBlank() == true) {
res.filter { app: ApplicationContainer ->
app.name?.contains(term, true) ?: false ||
app.description?.contains(term, true) ?: false ||
app.image?.contains(term, true) ?: false ||
app.id?.contains(term, true) ?: false ||
app.categories.any { it.contains(term, true) }
}
} else {
res
}
}
}
companion object {
private val LOG = LoggerFactory.getLogger(AppApi::class.java)
private val httpClient = HttpClient(Java) {
install(ContentNegotiation) {
jackson(ContentType.Any)
}
}
}
}
| 7 | null | 39 | 44 | 7c3028edac913ea03b2e735e1896990f92e7bcb7 | 10,267 | trusted-connector | Apache License 2.0 |
tensorflow/src/main/kotlin/org/jetbrains/kotlinx/dl/api/core/layer/core/Input.kt | Kotlin | 249,948,572 | false | {"Kotlin": 1599075, "Jupyter Notebook": 50439} | /*
* Copyright 2020-2022 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file.
*/
package org.jetbrains.kotlinx.dl.api.core.layer.core
import org.jetbrains.kotlinx.dl.api.core.layer.Layer
import org.jetbrains.kotlinx.dl.api.core.util.DATA_PLACEHOLDER
import org.jetbrains.kotlinx.dl.api.core.util.getDType
import org.tensorflow.Operand
import org.tensorflow.Shape
import org.tensorflow.op.Ops
import org.tensorflow.op.core.Placeholder
/**
* This layer is responsible for the input shape of the built model.
*
* First and required layer in [org.jetbrains.kotlinx.dl.api.core.Sequential.of] method.
*
* @property [name] Custom layer name.
* @constructor Creates [Input] layer from [packedDims] representing [input] data shape.
*/
public class Input(vararg dims: Long, name: String = "") : Layer(name) {
/** Placeholder for input data. */
public lateinit var input: Placeholder<Float>
/** Input data dimensions. Rank = 3 or 4 for most popular supported cases. */
public var packedDims: LongArray = dims
override fun build(
tf: Ops,
input: Operand<Float>,
isTraining: Operand<Boolean>,
numberOfLosses: Operand<Float>?
): Operand<Float> = build(tf)
/**
* Extend this function to define placeholder in layer.
*
* NOTE: Called instead of [Layer.build].
*
* @param [tf] TensorFlow graph API for building operations.
*/
public fun build(tf: Ops): Placeholder<Float> {
input = tf.withName(DATA_PLACEHOLDER).placeholder(
getDType(),
Placeholder.shape(Shape.make(-1L, *packedDims))
)
return input
}
override val hasActivation: Boolean get() = false
override fun toString(): String {
return "Input(name = $name, shape=${packedDims.contentToString()})"
}
}
| 81 | Kotlin | 102 | 1,418 | 0f36d1b481fc755a7108a34aaf7d8cc226bcc4eb | 1,965 | kotlindl | Apache License 2.0 |
day03/src/main/kotlin/Main.kt | Jaah | 585,902,672 | false | null | import java.io.File
fun main(args: Array<String>) {
if (args.isEmpty()) {
println("Input file not provided")
return
}
val fileName = args.first()
val file = File(fileName)
if (!file.exists()) {
println("File $fileName does not exist.")
return
}
solvePart1(file)
solvePart2(file)
}
fun solvePart2(input: File) {
val group = mutableListOf<Set<Char>>()
var count = 0
var total = 0
input.forEachLine {
val set = it.toSet()
group.add(set)
count++
if (count == 3) {
val intersect = group[0].intersect(group[1]).intersect(group[2])
val badge = intersect.first()
total += getPriority(badge)
group.clear()
count = 0
}
}
println("Part 2 total is $total")
}
fun solvePart1(input: File) {
var total = 0
input.forEachLine {
val compartments = it.chunked(it.length / 2)
val intersect = compartments.first().toSet().intersect(compartments.last().toSet())
total += getPriority(intersect.first())
}
println("Part 1 total is $total")
}
fun getPriority(item: Char): Int {
return when (item) {
'a' -> 1
'b' -> 2
'c' -> 3
'd' -> 4
'e' -> 5
'f' -> 6
'g' -> 7
'h' -> 8
'i' -> 9
'j' -> 10
'k' -> 11
'l' -> 12
'm' -> 13
'n' -> 14
'o' -> 15
'p' -> 16
'q' -> 17
'r' -> 18
's' -> 19
't' -> 20
'u' -> 21
'v' -> 22
'w' -> 23
'x' -> 24
'y' -> 25
'z' -> 26
'A' -> 26 + 1
'B' -> 26 + 2
'C' -> 26 + 3
'D' -> 26 + 4
'E' -> 26 + 5
'F' -> 26 + 6
'G' -> 26 + 7
'H' -> 26 + 8
'I' -> 26 + 9
'J' -> 26 + 10
'K' -> 26 + 11
'L' -> 26 + 12
'M' -> 26 + 13
'N' -> 26 + 14
'O' -> 26 + 15
'P' -> 26 + 16
'Q' -> 26 + 17
'R' -> 26 + 18
'S' -> 26 + 19
'T' -> 26 + 20
'U' -> 26 + 21
'V' -> 26 + 22
'W' -> 26 + 23
'X' -> 26 + 24
'Y' -> 26 + 25
'Z' -> 26 + 26
else -> 0
}
} | 0 | Kotlin | 0 | 0 | 134b748f17c77ee3780a94c5ba1a14ca8667b8da | 2,297 | advent-of-code-2022 | MIT License |
app/src/main/java/com/sherepenko/android/launchiteasy/livedata/LocationLiveData.kt | asherepenko | 241,422,907 | false | null | package com.sherepenko.android.launchiteasy.livedata
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import android.location.LocationManager
import androidx.lifecycle.LiveData
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.sherepenko.android.launchiteasy.BuildConfig
import com.sherepenko.android.launchiteasy.data.LocationItem
import com.sherepenko.android.launchiteasy.utils.isPermissionGranted
import java.util.concurrent.TimeUnit
import timber.log.Timber
@SuppressLint("MissingPermission")
class LocationLiveData(
private val context: Context
) : LiveData<LocationItem>() {
companion object {
private const val TAG = "Location"
private val FALLBACK_LOCATION = LocationItem(50.4501, 30.5234)
}
private val locationProviderClient =
LocationServices.getFusedLocationProviderClient(context)
private val locationManager =
context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult?.locations?.forEach {
Timber.tag(TAG).i("Current location updated: $it")
postValue(LocationItem(it.latitude, it.longitude))
}
}
}
private val locationRequest = LocationRequest.create().apply {
interval = TimeUnit.HOURS.toMillis(1)
priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
}
init {
if (context.isPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION)) {
locationProviderClient.lastLocation.addOnSuccessListener { location: Location? ->
if (location != null) {
Timber.tag(TAG).i("Last known location: $location")
postValue(LocationItem(location.latitude, location.longitude))
} else if (BuildConfig.DEBUG) {
postValue(FALLBACK_LOCATION)
}
}
locationProviderClient.lastLocation.addOnFailureListener {
Timber.tag(TAG).e(it, "Unable to get last known location")
}
}
}
override fun onActive() {
super.onActive()
if (context.isPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION)) {
locationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null)
}
}
override fun onInactive() {
super.onInactive()
locationProviderClient.removeLocationUpdates(locationCallback)
}
}
| 0 | null | 3 | 7 | 0ee2ac7b64001074b9bc3cafa9613af3322f9b6e | 2,844 | launchiteasy | MIT License |
mobileapp/src/commonMain/kotlin/io/github/landrynorris/multifactor/compose/CopyButton.kt | LandryNorris | 499,945,866 | false | {"Kotlin": 149473, "Swift": 9853, "Ruby": 1777, "Shell": 1049} | package io.github.landrynorris.multifactor.compose
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
@Composable
internal fun CopyButton(isEnabled: Boolean = true, onClick: () -> Unit) {
TextButton(onClick) { Text(modifier = Modifier.semantics { contentDescription = "Copy" },
text = "copy",
color = if(isEnabled) MaterialTheme.colors.onBackground else Color.DarkGray ) }
}
| 3 | Kotlin | 0 | 4 | 9549b6a1b153ec4b0e29bb9fed8f8793896dbfe1 | 699 | MultiFactor | Apache License 2.0 |
material_phone_widget/src/main/java/com/thushcapone/material_phone_widget/PhoneWatcher.kt | thushcapone | 232,567,416 | false | null | package com.thushcapone.material_phone_widget
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import com.thushcapone.material_edit_text.MaterialEditText
import com.thushcapone.material_phone_widget.extensions.*
import java.lang.ref.WeakReference
/**
* Created by thushcapone on 12/12/18.
*/
class PhoneWatcher(editText: MaterialEditText, private var mCountryCode: String) : TextWatcher {
private var mEditText: WeakReference<MaterialEditText>? = null
private var mCallback: PhoneWidget.OnValidPhoneListener? = null
private var phoneFormatted: String? = null
private var mNumberLength: Int = -1
init {
mEditText = WeakReference(editText)
phoneFormatted = ""
editText.edit?.removeTextChangedListener(sLastInstance)
editText.edit?.addTextChangedListener(this)
mNumberLength = mCountryCode.getPhoneNumberLength()
editText.edit?.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(mNumberLength))
sLastInstance = this
}
fun setCountryCode(countryCode: String){
mCountryCode = countryCode
mNumberLength = mCountryCode.getPhoneNumberLength()
mEditText?.get()?.edit?.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(mNumberLength))
}
fun setCallback(callback: PhoneWidget.OnValidPhoneListener) {
this.mCallback = callback
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
@Synchronized
override fun afterTextChanged(s: Editable) {
when {
s.toString().isValidPhoneNumber(mCountryCode) && phoneFormatted notEquals s.toString() -> {
phoneFormatted = s.toString().getNationalNumberFormatted(mCountryCode)
phoneFormatted?.let { mEditText?.get()?.edit?.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(it.length)) }
mCallback?.value(s.toString().getNormalizedNumber(mCountryCode))
}
phoneFormatted equals s.toString() -> phoneFormatted = ""
s.toString().trim { it <= ' ' }.length == mNumberLength && s.toString().isInValidPhoneNumber(mCountryCode) ->
mEditText?.get()?.layout?.error = mEditText?.get()?.context?.getString(R.string.error_phone_not_valid)
}
}
companion object {
private var sLastInstance: PhoneWatcher? = null
}
}
| 1 | null | 1 | 1 | 0fb1f8953e04a006eb124da2c67dc6dfdf510f19 | 2,508 | material_phone_widget | Apache License 2.0 |
community-family-component/src/main/java/com/kotlin/android/community/family/component/ui/clazz/adapter/FamilyItemBinder.kt | R-Gang-H | 538,443,254 | false | null | package com.kotlin.android.community.family.component.ui.clazz.adapter
import android.content.DialogInterface
import android.graphics.drawable.GradientDrawable
import android.view.View
import com.kotlin.android.community.family.component.R
import com.kotlin.android.community.family.component.databinding.ItemCommunityFamilyBinding
import com.kotlin.android.community.family.component.ui.clazz.bean.FamilyItem
import com.kotlin.android.community.family.component.ui.details.FamilyDetailActivity
import com.kotlin.android.app.data.constant.CommConstant
import com.kotlin.android.app.data.entity.common.CommonResult
import com.kotlin.android.ktx.ext.core.gone
import com.kotlin.android.ktx.ext.core.setCompoundDrawablesAndPadding
import com.kotlin.android.ktx.ext.core.setTextColorRes
import com.kotlin.android.ktx.ext.core.visible
import com.kotlin.android.ktx.ext.setTextWithFormat
import com.kotlin.android.mtime.ktx.ext.ShapeExt
import com.kotlin.android.mtime.ktx.ext.showToast
import com.kotlin.android.mtime.ktx.formatCount
import com.kotlin.android.widget.adapter.multitype.adapter.binder.MultiTypeBinder
import com.kotlin.android.widget.dialog.BaseDialog
/**
* @author ZhouSuQiang
* @email <EMAIL>
* @date 2020/7/27
*/
class FamilyItemBinder(val item: FamilyItem, private val goneLinePosition: Int = 0) : MultiTypeBinder<ItemCommunityFamilyBinding>() {
override fun layoutId(): Int {
return R.layout.item_community_family
}
override fun areContentsTheSame(other: MultiTypeBinder<*>): Boolean {
return other is FamilyItemBinder && other.item.joinType != item.joinType
}
override fun onBindViewHolder(binding: ItemCommunityFamilyBinding, position: Int) {
//成员
binding.mCommunityFamilyNumberTv.setTextWithFormat(
R.string.community_family_number, formatCount(item.numberCount))
//顶部分割线
if (position == goneLinePosition) {
binding.mCommunityFamilyTopLineView.gone()
} else {
binding.mCommunityFamilyTopLineView.visible()
}
//按钮
binding.mCommunityFamilyBtnFl.visible(
item.joinType != FamilyItem.JOIN_TYPE_BLACKLIST) //黑名单用户隐藏按钮
when (item.joinType) {
//已加入
FamilyItem.JOIN_TYPE_JOINED -> {
ShapeExt.setShapeCorner2Color2Stroke(
binding.mCommunityFamilyBtnFl,
R.color.color_00ffffff,
30,
R.color.color_20a0da,
1
)
binding.mCommunityFamilyBtnTv.setTextColorRes(R.color.color_20a0da)
binding.mCommunityFamilyBtnTv.setCompoundDrawablesAndPadding(
leftResId = R.drawable.ic_checkb,
padding = 3
)
binding.mCommunityFamilyBtnTv.setText(R.string.community_join_btn)
}
//加入中
FamilyItem.JOIN_TYPE_JOINING -> {
ShapeExt.setShapeCorner2Color2Stroke(
binding.mCommunityFamilyBtnFl,
R.color.color_00ffffff,
30,
R.color.color_20a0da,
1
)
binding.mCommunityFamilyBtnTv.setTextColorRes(R.color.color_20a0da)
binding.mCommunityFamilyBtnTv.setCompoundDrawablesAndPadding()
binding.mCommunityFamilyBtnTv.setText(R.string.community_joining_btn)
}
//未加入
FamilyItem.JOIN_TYPE_NO_JOIN -> {
ShapeExt.setGradientColor(
binding.mCommunityFamilyBtnFl,
GradientDrawable.Orientation.TOP_BOTTOM,
R.color.color_20a0da,
R.color.color_1bafe0,
30)
binding.mCommunityFamilyBtnTv.setTextColorRes(R.color.color_ffffff)
binding.mCommunityFamilyBtnTv.setCompoundDrawablesAndPadding()
binding.mCommunityFamilyBtnTv.setText(R.string.community_join_btn)
}
}
}
override fun onClick(view: View) {
when (view.id) {
R.id.mCommunityFamilyItemRoot -> {
FamilyDetailActivity.start(view.context, item.id)
}
R.id.mCommunityFamilyBtnFl -> {
joinBtnClick(view)
}
else -> {
super.onClick(view)
}
}
}
//按钮点击事件
private fun joinBtnClick(view: View) {
//按钮
when (item.joinType) {
//已加入
FamilyItem.JOIN_TYPE_JOINED -> {
exitFamily(view)
}
//加入中
FamilyItem.JOIN_TYPE_JOINING -> {
showToast(R.string.community_joining_family_hint)
}
//未加入
FamilyItem.JOIN_TYPE_NO_JOIN -> {
super.onClick(view)
}
}
}
//退出家族相关逻辑处理
private fun exitFamily(view: View) {
val listener = DialogInterface.OnClickListener { dialog, which ->
dialog.cancel()
if (which == -1) {
//确定退出家族
super.onClick(view)
}
}
BaseDialog.Builder(view.context)
.setContent(R.string.community_exit_family_hint)
.setNegativeButton(R.string.widget_cancel, listener)
.setPositiveButton(R.string.widget_sure, listener)
.create()
.show()
}
//加入成功的回调处理
fun joinChanged(result: CommonResult) {
when (result.status) {
CommConstant.JOIN_FAMILY_RESULT_STATUS_SUCCEED,
CommConstant.JOIN_FAMILY_RESULT_STATUS_JOINED -> {
item.numberCount++
item.joinType = FamilyItem.JOIN_TYPE_JOINED
notifyAdapterSelfChanged()
}
CommConstant.JOIN_FAMILY_RESULT_STATUS_JOINING -> {
item.numberCount++
item.joinType = FamilyItem.JOIN_TYPE_JOINING
notifyAdapterSelfChanged()
}
CommConstant.JOIN_FAMILY_RESULT_STATUS_BLACKLIST -> {
item.joinType = FamilyItem.JOIN_TYPE_BLACKLIST
notifyAdapterSelfChanged()
}
else -> {
showToast(result.failMsg)
}
}
}
//退出成功的回调处理
fun outChanged() {
item.numberCount--
item.joinType = FamilyItem.JOIN_TYPE_NO_JOIN
notifyAdapterSelfChanged()
}
} | 0 | Kotlin | 0 | 1 | e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28 | 6,620 | Mtime | Apache License 2.0 |
utsjekk-oppdrag-app/src/test/kotlin/no/nav/utsjekk/oppdrag/TestOppdragDb.kt | navikt | 596,541,750 | false | {"Kotlin": 160026, "Dockerfile": 265} | package no.nav.dagpenger.oppdrag
import org.springframework.boot.test.util.TestPropertyValues
import org.springframework.context.ApplicationContextInitializer
import org.springframework.context.ConfigurableApplicationContext
import java.io.Closeable
class TestOppdragDb : ApplicationContextInitializer<ConfigurableApplicationContext>, Closeable {
override fun close() {
PostgreSQLInitializer.container.close()
}
override fun initialize(applicationContext: ConfigurableApplicationContext) {
PostgreSQLInitializer.container.start()
TestPropertyValues.of(
"spring.datasource.url=${PostgreSQLInitializer.container.jdbcUrl}",
"spring.datasource.username=${PostgreSQLInitializer.container.username}",
"spring.datasource.password=${PostgreSQLInitializer.container.password}",
).applyTo(applicationContext.environment)
}
}
| 0 | Kotlin | 0 | 0 | 49115757e04bd9bc1f5f14fe8c442185ae6249b4 | 903 | utsjekk-oppdrag | MIT License |
library/src/main/kotlin/xyz/tynn/coana/CoanaValue.kt | tynn-xyz | 205,385,704 | false | null | // Copyright 2019 <NAME>
// SPDX-License-Identifier: Apache-2.0
package xyz.tynn.coana
/**
* Supported values for [Coana] scope, context and properties.
*
* This type serves as a generic marker for [CoanaPropertyKey].
*/
public sealed class CoanaValue<Value> {
internal abstract val value: Value
internal data class Double(
override val value: kotlin.Double,
) : CoanaValue<kotlin.Double>()
internal data class Long(
override val value: kotlin.Long,
) : CoanaValue<kotlin.Long>()
internal data class String(
override val value: kotlin.String,
) : CoanaValue<kotlin.String>()
}
| 0 | Kotlin | 0 | 0 | 40c5f56d34202ed634bf2f423c3da5605145d5fd | 640 | Coana | Apache License 2.0 |
library/src/main/kotlin/xyz/tynn/coana/CoanaValue.kt | tynn-xyz | 205,385,704 | false | null | // Copyright 2019 <NAME>
// SPDX-License-Identifier: Apache-2.0
package xyz.tynn.coana
/**
* Supported values for [Coana] scope, context and properties.
*
* This type serves as a generic marker for [CoanaPropertyKey].
*/
public sealed class CoanaValue<Value> {
internal abstract val value: Value
internal data class Double(
override val value: kotlin.Double,
) : CoanaValue<kotlin.Double>()
internal data class Long(
override val value: kotlin.Long,
) : CoanaValue<kotlin.Long>()
internal data class String(
override val value: kotlin.String,
) : CoanaValue<kotlin.String>()
}
| 0 | Kotlin | 0 | 0 | 40c5f56d34202ed634bf2f423c3da5605145d5fd | 640 | Coana | Apache License 2.0 |
client/android/div-data/src/main/java/com/yandex/div/internal/util/JsonUtils.kt | divkit | 523,491,444 | false | {"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38} | package com.yandex.div.internal.util
import org.json.JSONArray
import org.json.JSONObject
inline fun <reified T> JSONObject.forEach(action: (String, T) -> Unit) {
val keys = keys()
for (key in keys) {
val value = get(key)
if (value is T) action(key, value)
}
}
inline fun <reified T> JSONArray.forEach(action: (Int, T) -> Unit) {
val length = length()
for (i in 0 until length) {
val value = get(i)
if (value is T) action(i, value)
}
}
inline fun <reified T> JSONObject.forEachNullable(action: (String, T?) -> Unit) {
val keys = keys()
for (key in keys) {
val value = opt(key)
if (value is T?) action(key, value)
}
}
inline fun <reified T> JSONArray.forEachNullable(action: (Int, T?) -> Unit) {
val length = length()
for (i in 0 until length) {
val value = opt(i)
if (value is T?) action(i, value)
}
}
inline fun <R> JSONArray.map(mapping: (Any) -> R): List<R> {
val length = length()
val result = ArrayList<R>(length)
for (i in 0 until length) {
result.add(mapping(get(i)))
}
return result
}
inline fun <R> JSONArray.mapNotNull(mapping: (Any) -> R?): List<R> {
val length = length()
val result = ArrayList<R>(length)
for (i in 0 until length) {
mapping(get(i))?.let { result.add(it) }
}
return result
}
@Suppress("UNCHECKED_CAST")
fun <R : Any> JSONArray.asList(): List<R> = mapNotNull { it as? R }
/**
* Gets optional string value for the given key.
*
* Unlike [JSONObject.optString] this method does not convert not string values to string.
*/
fun JSONObject.getStringOrEmpty(name: String): String {
val value = opt(name)
return if (value is String) value else ""
}
fun JSONObject.getStringOrNull(key: String): String? {
val value = opt(key)
return if (value is String) value else null
}
fun JSONObject.summary(indentSpaces: Int = 0): String {
return JsonPrinter(indentSpaces = indentSpaces, nestingLimit = 1).print(this)
}
fun JSONArray.summary(indentSpaces: Int = 0): String {
return JsonPrinter(indentSpaces = indentSpaces, nestingLimit = 1).print(this)
}
fun JSONObject.isEmpty(): Boolean = length() == 0
fun JSONArray.isEmpty(): Boolean = length() == 0
| 5 | Kotlin | 128 | 2,240 | dd102394ed7b240ace9eaef9228567f98e54d9cf | 2,272 | divkit | Apache License 2.0 |
src/test/aoc2016/Day10Test.kt | nibarius | 154,152,607 | false | {"Kotlin": 976889} | package test.aoc2016
import aoc2016.Day10
import org.junit.Assert
import org.junit.Test
import resourceAsList
class Day10Test {
private val exampleInput = listOf("value 5 goes to bot 2",
"bot 2 gives low to bot 1 and high to bot 0",
"value 3 goes to bot 1",
"bot 1 gives low to output 1 and high to bot 0",
"bot 0 gives low to output 2 and high to output 0",
"value 2 goes to bot 2")
@Test
fun partOneExample() {
Assert.assertEquals(2, Day10(exampleInput).solvePart1(2, 5))
}
@Test
fun partOneRealInput() {
Assert.assertEquals(47, Day10(resourceAsList("2016/day10.txt")).solvePart1(17, 61))
}
@Test
fun partTwoExample() {
Assert.assertEquals(30, Day10(exampleInput).solvePart2())
}
@Test
fun partTwoRealInput() {
Assert.assertEquals(2666, Day10(resourceAsList("2016/day10.txt")).solvePart2())
}
} | 0 | Kotlin | 0 | 6 | c93a84c1c9c789d42b19369ad7972449b4a9e982 | 946 | aoc | MIT License |
app/src/main/java/com/battlelancer/seriesguide/movies/similar/SimilarMoviesAdapter.kt | UweTrottmann | 1,990,682 | false | null | // Copyright 2023 <NAME>
// SPDX-License-Identifier: Apache-2.0
package com.battlelancer.seriesguide.movies.similar
import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import com.battlelancer.seriesguide.movies.MovieClickListenerImpl
import com.battlelancer.seriesguide.movies.MovieViewHolder
import com.battlelancer.seriesguide.movies.tools.MovieTools
import com.battlelancer.seriesguide.settings.TmdbSettings
import com.uwetrottmann.tmdb2.entities.BaseMovie
class SimilarMoviesAdapter(
private val context: Context,
) : ListAdapter<BaseMovie, MovieViewHolder>(
MovieViewHolder.DIFF_CALLBACK_BASE_MOVIE
) {
private val dateFormatMovieReleaseDate = MovieTools.getMovieShortDateFormat()
private val posterBaseUrl = TmdbSettings.getPosterBaseUrl(context)
private val itemClickListener = MovieClickListenerImpl(context)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
return MovieViewHolder.inflate(parent, itemClickListener)
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
holder.bindTo(getItem(position), context, dateFormatMovieReleaseDate, posterBaseUrl)
}
} | 50 | null | 403 | 1,935 | 44d84fe516e42cc178e0583c7b28bdabe62a199a | 1,238 | SeriesGuide | Apache License 2.0 |
kmdc/kmdc-drawer/src/jsMain/kotlin/MDCDrawerHeader.kt | mpetuska | 430,798,310 | false | null | package dev.petuska.kmdc.drawer
import androidx.compose.runtime.Composable
import dev.petuska.kmdc.core.ComposableBuilder
import dev.petuska.kmdc.core.MDCDsl
import org.jetbrains.compose.web.dom.AttrBuilderContext
import org.jetbrains.compose.web.dom.ContentBuilder
import org.jetbrains.compose.web.dom.Div
import org.jetbrains.compose.web.dom.ElementScope
import org.jetbrains.compose.web.dom.H3
import org.jetbrains.compose.web.dom.H6
import org.jetbrains.compose.web.dom.Text
import org.w3c.dom.HTMLDivElement
import org.w3c.dom.HTMLHeadingElement
public class MDCDrawerHeaderScope(scope: ElementScope<HTMLDivElement>) : ElementScope<HTMLDivElement> by scope
/**
* [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-drawer)
*/
@MDCDsl
@Composable
public fun MDCDrawerScope.MDCDrawerHeader(
attrs: AttrBuilderContext<HTMLDivElement>? = null,
content: ComposableBuilder<MDCDrawerHeaderScope>? = null,
) {
Div(
attrs = {
classes("mdc-drawer__header")
attrs?.invoke(this)
},
content = content?.let { { MDCDrawerHeaderScope(this).it() } },
)
}
/**
* [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-drawer)
*/
@MDCDsl
@Composable
public fun MDCDrawerScope.MDCDrawerHeader(
text: String,
attrs: AttrBuilderContext<HTMLDivElement>? = null,
): Unit = MDCDrawerHeader(attrs) { Text(text) }
/**
* [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-drawer)
*/
@MDCDsl
@Composable
public fun MDCDrawerScope.MDCDrawerTitle(
attrs: AttrBuilderContext<HTMLHeadingElement>? = null,
content: ContentBuilder<HTMLHeadingElement>? = null
) {
H3(
attrs = {
classes("mdc-drawer__title")
attrs?.invoke(this)
},
content = content,
)
}
/**
* [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-drawer)
*/
@MDCDsl
@Composable
public fun MDCDrawerScope.MDCDrawerTitle(
text: String,
attrs: AttrBuilderContext<HTMLHeadingElement>? = null,
): Unit = MDCDrawerTitle(attrs) { Text(text) }
/**
* [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-drawer)
*/
@MDCDsl
@Composable
public fun MDCDrawerScope.MDCDrawerSubtitle(
attrs: AttrBuilderContext<HTMLHeadingElement>? = null,
content: ContentBuilder<HTMLHeadingElement>? = null
) {
H6(
attrs = {
classes("mdc-drawer__subtitle")
attrs?.invoke(this)
},
content = content,
)
}
/**
* [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-drawer)
*/
@MDCDsl
@Composable
public fun MDCDrawerScope.MDCDrawerSubtitle(
text: String,
attrs: AttrBuilderContext<HTMLHeadingElement>? = null,
): Unit = MDCDrawerSubtitle(attrs) { Text(text) }
| 22 | Kotlin | 8 | 29 | 67b31502b5f76b64f7571821fdd0b78a3df0a68c | 2,860 | kmdc | Apache License 2.0 |
app/src/main/java/com/example/testbank/view/main/more/MoreFragment.kt | aucd29 | 406,299,316 | false | {"Kotlin": 170385} | package com.example.testbank.view.main.more
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.example.testbank.R
import com.example.testbank.base.BaseFragment
import com.example.testbank.base.adapter.BaseTypeListAdapter
import com.example.testbank.databinding.FragmentMoreBinding
import com.example.testbank.deviceapi.user.UserViewModel
import com.example.testbank.repository.local.model.more.BaseMoreModel
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MoreFragment : BaseFragment<FragmentMoreBinding>(R.layout.fragment_more) {
private val viewmodel: MoreViewModel by viewModels()
private val userViewModel: UserViewModel by activityViewModels()
@Inject @HiltMoreFragment
lateinit var adapter: BaseTypeListAdapter<BaseMoreModel>
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
vm = viewmodel
userVm = userViewModel
moreRecycler.adapter = adapter.apply {
viewModel = viewmodel
}
}
viewmodel.init()
}
} | 0 | Kotlin | 0 | 0 | 7b82096b854f200928a2c1c528f287c80f1a963f | 1,261 | testbank | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/TurnSlightRightRounded.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/TurnSlightRightRounded")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val TurnSlightRightRounded: SvgIconComponent
| 12 | null | 5 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 226 | kotlin-wrappers | Apache License 2.0 |
util/src/main/java/com/arcadan/util/math/QuadraticEquation.kt | ArcaDone | 351,158,574 | false | null | package com.arcadan.util.math
import java.lang.Math.*
import kotlin.math.pow
data class QuadraticEquation(val a: Double, val b: Double, val c: Double) {
data class Complex(val r: Double, val i: Double) {
override fun toString() = when {
i == 0.0 -> r.toString()
r == 0.0 -> "${i}i"
else -> "$r + ${i}i"
}
}
data class Solution(val x1: Any, val x2: Any) {
override fun toString() = when(x1) {
x2 -> "X1,2 = $x1"
else -> "X1 = $x1, X2 = $x2"
}
}
val quadraticRoots by lazy {
val _2a = a + a
val d = b * b - 4.0 * a * c // discriminant
if (d < 0.0) {
val r = -b / _2a
val i = kotlin.math.sqrt(-d) / _2a
Solution(Complex(r, i), Complex(r, -i))
} else {
// avoid calculating -b +/- sqrt(d), to avoid any
// subtractive cancellation when it is near zero.
val r = if (b < 0.0) (-b + kotlin.math.sqrt(d)) / _2a else (-b - kotlin.math.sqrt(d)) / _2a
Solution(r, c / (a * r))
}
}
fun obtainYForXValue(x: Double) : Double = ((x.pow(2) * a) + (x * b) + c)
}
| 0 | Kotlin | 0 | 2 | 24133757b19f2b2fea64542347b339f8621284f6 | 1,196 | DodgeTheEnemies | MIT License |
core/designsystem/src/main/kotlin/com/seosh817/moviehub/core/designsystem/component/IconToggleButton.kt | seosh817 | 722,390,551 | false | {"Kotlin": 319379} | package com.seosh817.moviehub.core.designsystem.component
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material3.Icon
import androidx.compose.material3.IconToggleButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun LikeToggleButton(
modifier: Modifier = Modifier,
checked: Boolean = false,
onCheckedClick: ((Boolean) -> Unit)? = null
) {
IconToggleButton(
checked = checked,
onCheckedChange = {
onCheckedClick?.invoke(it)
},
enabled = onCheckedClick != null,
modifier = modifier
.size(24.dp)
) {
Icon(
imageVector = Icons.Default.Favorite,
contentDescription = "Favorite icon toggle",
tint = if (checked) Color.Red else Color.White
)
}
} | 12 | Kotlin | 0 | 1 | a2bb34b1321f72bdb8e8bf38edadb6e81ae9a2c1 | 1,031 | MovieHub | Apache License 2.0 |
app/src/main/java/com/eyther/lumbridge/launcher/viewmodel/IMainActivityViewModel.kt | ruialmeida51 | 249,223,684 | false | {"Kotlin": 687400} | package com.eyther.lumbridge.launcher.viewmodel
import com.eyther.lumbridge.launcher.model.MainScreenViewState
import kotlinx.coroutines.flow.StateFlow
interface IMainActivityViewModel {
val viewState: StateFlow<MainScreenViewState>
/**
* Check if the user has stored preferences. If the user has stored preferences,
* the app will use the stored preferences to set the theme settings. If the user
* has not stored preferences, the app will use the default theme settings.
*
* @return true if the user has stored theme settings, false otherwise.
*/
suspend fun hasStoredPreferences(): Boolean
/**
* This assumes that the user has stored preferences. It will update the user's settings
* with the new settings provided.
*
* If, for some reason, the user has not stored preferences, the app will create try to create a default
* with these settings as a best effort.
*
* @param isDarkMode true if the dark mode setting is enabled, false otherwise. If it is null, the setting will not be updated and instead
* read from the stored preferences.
* @param appLanguageCountryCode the country code for the language setting. If it is null, the setting will not be updated and instead
* read from the system defaults or stored preferences.
*/
suspend fun updateSettings(
isDarkMode: Boolean? = null,
appLanguageCountryCode: String? = null
)
}
| 8 | Kotlin | 0 | 7 | 8e35f83c34e4b29eae1b048d3fda6aaa81b04858 | 1,462 | lumbridge-android | MIT License |
implementation/src/main/kotlin/com/aoc/intcode/droid/cryo/command/item/TakeCommand.kt | TomPlum | 227,887,094 | false | null | package com.aoc.intcode.droid.cryo.command.item
import com.aoc.intcode.droid.cryo.command.runtime.CommandRuntime
import com.aoc.intcode.droid.cryo.command.types.ItemCommand
import com.aoc.intcode.droid.cryo.droid.CryostasisDroid
import com.aoc.intcode.droid.cryo.droid.Item
import com.aoc.intcode.droid.cryo.droid.Inventory
import com.aoc.intcode.droid.cryo.map.Room
import com.aoc.intcode.droid.cryo.command.CommandParser
/**
* An [ItemCommand] issued to the [CryostasisDroid] via the [CommandRuntime] instructing it to take an [Item]
* from the current [Room] and store it in it's [Inventory].
* @see CommandParser
*/
data class TakeCommand(private val itemName: String) : ItemCommand("take", itemName) | 7 | Kotlin | 1 | 2 | 12d47cc9c50aeb9e20bcf110f53d097d8dc3762f | 710 | advent-of-code-2019 | Apache License 2.0 |
ethereum-rpc/src/test/java/pm/gnosis/ethereum/rpc/RpcEthereumRepositoryTest.kt | vanderian | 171,901,954 | false | null | package pm.gnosis.ethereum.rpc
import io.reactivex.Observable
import io.reactivex.observers.TestObserver
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.BDDMockito.given
import org.mockito.BDDMockito.then
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import pm.gnosis.ethereum.*
import pm.gnosis.ethereum.models.EthereumBlock
import pm.gnosis.ethereum.models.TransactionData
import pm.gnosis.ethereum.models.TransactionParameters
import pm.gnosis.ethereum.models.TransactionReceipt
import pm.gnosis.ethereum.rpc.models.*
import pm.gnosis.model.Solidity
import pm.gnosis.models.Transaction
import pm.gnosis.models.Wei
import pm.gnosis.tests.utils.ImmediateSchedulersRule
import pm.gnosis.tests.utils.MockUtils
import pm.gnosis.utils.asEthereumAddress
import pm.gnosis.utils.hexAsBigInteger
import pm.gnosis.utils.toHexString
import java.math.BigInteger
@RunWith(MockitoJUnitRunner::class)
class RpcEthereumRepositoryTest {
@JvmField
@Rule
val rule = ImmediateSchedulersRule()
@Mock
private lateinit var apiMock: EthereumRpcConnector
private lateinit var repository: RpcEthereumRepository
@Before
fun setUp() {
repository = RpcEthereumRepository(apiMock)
}
@Test
fun bulk() {
given(apiMock.post(MockUtils.any<Collection<JsonRpcRequest>>()))
.willReturn(
Observable.just(
listOf(
rpcResult("0x", 0),
rpcResult(Wei.ether("1").value.toHexString(), 1),
rpcResult(Wei.ether("0.000000001").value.toHexString(), 2),
rpcResult("0x0a", 3),
rpcResult(
"0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1",
4
)
)
)
)
val tx = Transaction(Solidity.Address(BigInteger.TEN), value = Wei.ether("0.001"))
val bulk = BulkRequest(
EthCall(Solidity.Address(BigInteger.ONE), tx, 0),
EthBalance(Solidity.Address(BigInteger.ONE), 1),
EthGasPrice(2),
EthGetTransactionCount(Solidity.Address(BigInteger.ONE), 3),
EthSendRawTransaction("some_signed_data", 4)
)
val testObserver = TestObserver<BulkRequest>()
repository.request(bulk).subscribe(testObserver)
testObserver.assertResult(bulk)
assertEquals(EthRequest.Response.Success("0x"), bulk.requests[0].response)
assertEquals(EthRequest.Response.Success(Wei.ether("1")), bulk.requests[1].response)
assertEquals(
EthRequest.Response.Success(Wei.ether("0.000000001").value),
bulk.requests[2].response
)
assertEquals(
EthRequest.Response.Success("0x0a".hexAsBigInteger()),
bulk.requests[3].response
)
assertEquals(
EthRequest.Response.Success("0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1"),
bulk.requests[4].response
)
then(apiMock).should().post(bulk.requests.map { it.toRpcRequest().request() })
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun bulkSameId() {
given(apiMock.post(MockUtils.any<Collection<JsonRpcRequest>>()))
.willReturn(
Observable.just(
listOf(
rpcResult(
"0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1",
0
)
)
)
)
val tx = Transaction(Solidity.Address(BigInteger.TEN), value = Wei.ether("0.001"))
val bulk = BulkRequest(
EthCall(Solidity.Address(BigInteger.ONE), tx, 0),
EthSendRawTransaction("some_signed_data", 0)
)
val testObserver = TestObserver<BulkRequest>()
repository.request(bulk).subscribe(testObserver)
testObserver.assertResult(bulk)
val requests = bulk.requests
assertNull("First request should be overwritten by second request", requests[0].response)
assertEquals(
EthRequest.Response.Success("0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1"),
requests[1].response
)
then(apiMock).should().post(listOf(requests[1].toRpcRequest().request()))
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun bulkWithFailure() {
given(apiMock.post(MockUtils.any<Collection<JsonRpcRequest>>()))
.willReturn(
Observable.just(
listOf(
rpcResult("0x", 0),
rpcResult(Wei.ether("1").value.toHexString(), 1),
rpcResult("0x", 2, error = "revert; But I won't tell you why")
)
)
)
val tx = Transaction(Solidity.Address(BigInteger.TEN), value = Wei.ether("0.001"))
val bulk = BulkRequest(
EthCall(Solidity.Address(BigInteger.ONE), tx, 0),
EthBalance(Solidity.Address(BigInteger.ONE), 1),
EthSendRawTransaction("some_signed_data", 2)
)
val testObserver = TestObserver<BulkRequest>()
repository.request(bulk).subscribe(testObserver)
testObserver.assertResult(bulk)
val requests = bulk.requests
assertEquals(EthRequest.Response.Success("0x"), requests[0].response)
assertEquals(EthRequest.Response.Success(Wei.ether("1")), requests[1].response)
assertEquals(
EthRequest.Response.Failure<String>("revert; But I won't tell you why"),
requests[2].response
)
then(apiMock).should().post(requests.map { it.toRpcRequest().request() })
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun request() {
given(apiMock.post(MockUtils.any<JsonRpcRequest>()))
.willReturn(
Observable.just(
rpcResult(Wei.ether("1").value.toHexString(), 1)
)
)
val request = EthBalance(Solidity.Address(BigInteger.ONE), 1)
val testObserver = TestObserver<EthRequest<*>>()
repository.request(request).subscribe(testObserver)
testObserver.assertResult(request)
assertEquals(
EthRequest.Response.Success(Wei.ether("1")),
request.response
)
then(apiMock).should().post(request.toRpcRequest().request())
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun requestFailure() {
given(apiMock.post(MockUtils.any<JsonRpcRequest>()))
.willReturn(
Observable.just(
rpcResult("0x", 1, "eth_getBalance should never error")
)
)
val request = EthBalance(Solidity.Address(BigInteger.ONE), 1)
val testObserver = TestObserver<EthRequest<*>>()
repository.request(request).subscribe(testObserver)
testObserver.assertResult(request)
assertEquals(
EthRequest.Response.Failure<Wei>("eth_getBalance should never error"),
request.response
)
then(apiMock).should().post(request.toRpcRequest().request())
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun getBalance() {
given(apiMock.post(MockUtils.any<JsonRpcRequest>()))
.willReturn(
Observable.just(
rpcResult(Wei.ether("1").value.toHexString())
)
)
val testObserver = TestObserver<Wei>()
repository.getBalance(Solidity.Address(BigInteger.ONE)).subscribe(testObserver)
testObserver.assertResult(Wei.ether("1"))
then(apiMock).should().post(EthBalance(Solidity.Address(BigInteger.ONE)).toRpcRequest().request())
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun getBalanceFailure() {
given(apiMock.post(MockUtils.any<JsonRpcRequest>()))
.willReturn(
Observable.just(
rpcResult("0x", 0, "eth_getBalance should never error")
)
)
val testObserver = TestObserver<Wei>()
repository.getBalance(Solidity.Address(BigInteger.ONE)).subscribe(testObserver)
testObserver.assertError { it is RequestFailedException && it.message == "eth_getBalance should never error" }
then(apiMock).should().post(EthBalance(Solidity.Address(BigInteger.ONE)).toRpcRequest().request())
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun sendRawTransaction() {
given(apiMock.post(MockUtils.any<JsonRpcRequest>()))
.willReturn(
Observable.just(
rpcResult("0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1")
)
)
val testObserver = TestObserver<String>()
repository.sendRawTransaction("0xSomeSignedManager").subscribe(testObserver)
testObserver.assertResult("0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1")
then(apiMock).should()
.post(EthSendRawTransaction("0xSomeSignedManager").toRpcRequest().request())
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun sendRawTransactionFailure() {
given(apiMock.post(MockUtils.any<JsonRpcRequest>()))
.willReturn(
Observable.just(
rpcResult("0x", 0, "revert; But I won't tell you why")
)
)
val testObserver = TestObserver<String>()
repository.sendRawTransaction("0xSomeSignedManager").subscribe(testObserver)
testObserver.assertError {
it is RequestFailedException &&
it.message == "revert; But I won't tell you why (Could not send raw transaction)"
}
then(apiMock).should()
.post(EthSendRawTransaction("0xSomeSignedManager").toRpcRequest().request())
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun getTransactionReceipt() {
val transactionHash = "0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1"
val data = "0x0000000000000000000000009205b8f1a21a3cee0f6a629fd83cee0f6a629fd8"
val topic0 = "0x4db17dd5e4732fb6da34a148104a592783ca119a1e7bb8829eba6cbadef0b511"
given(apiMock.receipt(MockUtils.any()))
.willReturn(
Observable.just(
JsonRpcTransactionReceiptResult(
1, "2.0",
result = JsonRpcTransactionReceiptResult.TransactionReceipt(
BigInteger.ONE,
transactionHash,
BigInteger.valueOf(23),
"block-hash",
BigInteger.valueOf(31),
"0x32".asEthereumAddress()!!,
"0x55".asEthereumAddress()!!,
BigInteger.valueOf(115),
BigInteger.valueOf(11),
"0x31415925".asEthereumAddress(),
listOf(
JsonRpcTransactionReceiptResult.TransactionReceipt.Event(
BigInteger.ZERO, data, listOf(topic0)
)
)
)
)
)
)
val testObserver = TestObserver<TransactionReceipt>()
repository.getTransactionReceipt(transactionHash).subscribe(testObserver)
testObserver.assertResult(
TransactionReceipt(
BigInteger.ONE,
transactionHash,
BigInteger.valueOf(23),
"block-hash",
BigInteger.valueOf(31),
"0x32".asEthereumAddress()!!,
"0x55".asEthereumAddress()!!,
BigInteger.valueOf(115),
BigInteger.valueOf(11),
"0x31415925".asEthereumAddress(),
listOf(
TransactionReceipt.Event(
BigInteger.ZERO, data, listOf(topic0)
)
)
)
)
then(apiMock).should()
.receipt(
JsonRpcRequest(
method = "eth_getTransactionReceipt",
params = listOf(transactionHash)
)
)
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun getTransactionReceiptFailure() {
val transactionHash = "0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1"
given(apiMock.receipt(MockUtils.any()))
.willReturn(
Observable.just(
JsonRpcTransactionReceiptResult(
1, "2.0",
result = null
)
)
)
val testObserver = TestObserver<TransactionReceipt>()
repository.getTransactionReceipt(transactionHash).subscribe(testObserver)
testObserver.assertError { it is TransactionReceiptNotFound }
then(apiMock).should()
.receipt(
JsonRpcRequest(
method = "eth_getTransactionReceipt",
params = listOf(transactionHash)
)
)
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun getTransactionByHash() {
val transactionHash = "0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1"
val data = "0x0000000000000000000000009205b8f1a21a3cee0f6a629fd83cee0f6a629fd8"
given(apiMock.transaction(MockUtils.any()))
.willReturn(
Observable.just(
JsonRpcTransactionResult(
1, "2.0",
result = JsonRpcTransactionResult.JsonTransaction(
transactionHash,
BigInteger.valueOf(23),
"block-hash",
BigInteger.valueOf(31),
BigInteger.valueOf(32),
"0x32".asEthereumAddress()!!,
"0x55".asEthereumAddress()!!,
BigInteger.ONE,
BigInteger.valueOf(11),
BigInteger.valueOf(115),
data
)
)
)
)
val testObserver = TestObserver<TransactionData>()
repository.getTransactionByHash(transactionHash).subscribe(testObserver)
testObserver.assertResult(
TransactionData(
transactionHash,
"0x32".asEthereumAddress()!!,
Transaction(
"0x55".asEthereumAddress()!!,
Wei(BigInteger.ONE),
BigInteger.valueOf(115),
BigInteger.valueOf(11),
data,
BigInteger.valueOf(23)
),
BigInteger.valueOf(32),
"block-hash",
BigInteger.valueOf(31)
)
)
then(apiMock).should()
.transaction(
JsonRpcRequest(
method = "eth_getTransactionByHash",
params = listOf(transactionHash)
)
)
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun getTransactionByHashFailure() {
val transactionHash = "0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1"
given(apiMock.transaction(MockUtils.any()))
.willReturn(
Observable.just(
JsonRpcTransactionResult(
1, "2.0",
result = null
)
)
)
val testObserver = TestObserver<TransactionData>()
repository.getTransactionByHash(transactionHash).subscribe(testObserver)
testObserver.assertError { it is TransactionNotFound }
then(apiMock).should()
.transaction(
JsonRpcRequest(
method = "eth_getTransactionByHash",
params = listOf(transactionHash)
)
)
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun getBlockByHash() {
val blockHash = "0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1"
given(apiMock.block(MockUtils.any()))
.willReturn(
Observable.just(
JsonRpcBlockResult(
1, "2.0",
result = JsonRpcBlockResult.JsonBlock(
BigInteger.ONE,
blockHash,
"parent-hash",
"weird-nonce",
"uncles-hash",
"logsBloom",
"transactionsRoot",
"stateRoot",
"receiptRoot",
"0x1234".asEthereumAddress()!!,
BigInteger.valueOf(31),
BigInteger.valueOf(1331),
"extra-data",
BigInteger.valueOf(1989),
BigInteger.valueOf(115),
BigInteger.valueOf(11),
BigInteger.valueOf(987654321)
)
)
)
)
val testObserver = TestObserver<EthereumBlock>()
repository.getBlockByHash(blockHash).subscribe(testObserver)
testObserver.assertResult(
EthereumBlock(
BigInteger.ONE,
blockHash,
"parent-hash",
"weird-nonce",
"uncles-hash",
"logsBloom",
"transactionsRoot",
"stateRoot",
"receiptRoot",
"0x1234".asEthereumAddress()!!,
BigInteger.valueOf(31),
BigInteger.valueOf(1331),
"extra-data",
BigInteger.valueOf(1989),
BigInteger.valueOf(115),
BigInteger.valueOf(11),
BigInteger.valueOf(987654321)
)
)
then(apiMock).should()
.block(
JsonRpcRequest(
method = "eth_getBlockByHash",
params = listOf(blockHash, false)
)
)
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun getBlockByHashFailure() {
val blockHash = "0x2709205b8f1a21a3cee0f6a629fd8dcfee589733741a877aba873cb379e97fa1"
given(apiMock.block(MockUtils.any()))
.willReturn(
Observable.just(
JsonRpcBlockResult(
1, "2.0",
result = null
)
)
)
val testObserver = TestObserver<EthereumBlock>()
repository.getBlockByHash(blockHash).subscribe(testObserver)
testObserver.assertError { it is BlockNotFound }
then(apiMock).should()
.block(
JsonRpcRequest(
method = "eth_getBlockByHash",
params = listOf(blockHash, false)
)
)
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun getTransactionParameters() {
given(apiMock.post(MockUtils.any<Collection<JsonRpcRequest>>()))
.willReturn(
Observable.just(
listOf(
rpcResult(BigInteger.valueOf(55000).toHexString(), 0),
rpcResult(Wei.ether("0.000000001").value.toHexString(), 1),
rpcResult("0x0a", 2)
)
)
)
val transaction = Transaction(Solidity.Address(BigInteger.ONE), value = Wei.ether("1"), data = "0x42cde4e8")
val testObserver = TestObserver<TransactionParameters>()
repository.getTransactionParameters(
Solidity.Address(BigInteger.TEN),
transaction.address,
transaction.value,
transaction.data
).subscribe(testObserver)
testObserver.assertResult(
TransactionParameters(
BigInteger.valueOf(77000),
Wei.ether("0.000000001").value,
BigInteger.valueOf(10)
)
)
then(apiMock).should().post(
listOf(
EthEstimateGas(Solidity.Address(BigInteger.TEN), transaction, 0).toRpcRequest().request(),
EthGasPrice(1).toRpcRequest().request(),
EthGetTransactionCount(Solidity.Address(BigInteger.TEN), 2).toRpcRequest().request()
)
)
then(apiMock).shouldHaveNoMoreInteractions()
}
private fun testTransactionParametersFailure(rpcResults: List<JsonRpcResult>) {
given(apiMock.post(MockUtils.any<Collection<JsonRpcRequest>>()))
.willReturn(Observable.just(rpcResults))
val transaction = Transaction(Solidity.Address(BigInteger.ONE), value = Wei.ether("1"), data = "0x42cde4e8")
val testObserver = TestObserver<TransactionParameters>()
repository.getTransactionParameters(
Solidity.Address(BigInteger.TEN),
transaction.address,
transaction.value,
transaction.data
).subscribe(testObserver)
testObserver.assertError { it is RequestFailedException }
then(apiMock).should().post(
listOf(
EthEstimateGas(Solidity.Address(BigInteger.TEN), transaction, 0).toRpcRequest().request(),
EthGasPrice(1).toRpcRequest().request(),
EthGetTransactionCount(Solidity.Address(BigInteger.TEN), 2).toRpcRequest().request()
)
)
then(apiMock).shouldHaveNoMoreInteractions()
}
@Test
fun getTransactionParametersEstimateFailure() {
testTransactionParametersFailure(
listOf(
rpcResult(error = "Something went wrong", id = 0),
rpcResult(Wei.ether("0.000000001").value.toHexString(), 1),
rpcResult("0x0a", 2)
)
)
}
@Test
fun getTransactionParametersGasPriceFailure() {
testTransactionParametersFailure(
listOf(
rpcResult(BigInteger.valueOf(55000).toHexString(), 0),
rpcResult(error = "Something went wrong", id = 1),
rpcResult("0x0a", 2)
)
)
}
@Test
fun getTransactionParametersNonceFailure() {
testTransactionParametersFailure(
listOf(
rpcResult(BigInteger.valueOf(55000).toHexString(), 0),
rpcResult(Wei.ether("0.000000001").value.toHexString(), 1),
rpcResult(error = "Something went wrong", id = 2)
)
)
}
private fun rpcResult(result: String = "0x", id: Int = 0, error: String? = null) =
JsonRpcResult(id, "2.0", error?.let { JsonRpcError(23, it) }, result)
private fun <T> EthRequest<T>.toRpcRequest() =
when (this) {
is EthCall -> RpcCallRequest(this)
is EthBalance -> RpcBalanceRequest(this)
is EthEstimateGas -> RpcEstimateGasRequest(this)
is EthGasPrice -> RpcGasPriceRequest(this)
is EthGetTransactionCount -> RpcTransactionCountRequest(this)
is EthSendRawTransaction -> RpcSendRawTransaction(this)
else -> throw IllegalArgumentException()
}
}
| 1 | null | 1 | 1 | 68371db16857c7420697ed1a54d1f074c7fd4f8e | 24,481 | svalinn-kotlin | MIT License |
ki-shell/src/main/kotlin/org/jetbrains/kotlinx/ki/shell/plugins/KotlinHighlighter.kt | Kotlin | 88,049,426 | false | null | package org.jetbrains.kotlinx.ki.shell.plugins
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.CommonTokenStream
import org.jetbrains.kotlinx.ki.shell.parser.KotlinLexer
import org.jetbrains.kotlinx.ki.shell.parser.KotlinParser
import org.jetbrains.kotlinx.ki.shell.parser.KotlinParserListenerForHighlighting
import org.jline.utils.AttributedString
import org.jline.utils.AttributedStringBuilder
import org.jline.utils.AttributedStyle
import java.util.regex.Pattern
class KotlinHighlighter(private val styles: SyntaxPlugin.HighlightStyles): BaseHighlighter {
private var lastCodeCausingError: String? = null
override fun highlight(buffer: String, offset: Int): AttributedString {
require(offset >= 0)
return AttributedStringBuilder().run {
buildHighlighting(buffer, offset)
toAttributedString()
}
}
private fun AttributedStringBuilder.buildHighlighting(buffer: String, offset: Int) {
if (offset != 0) append(buffer.substring(0, offset))
if (offset >= buffer.length) return
val code = buffer.substring(offset)
if (code.isBlank()) return
val listener = KotlinParserListenerForHighlighting()
if (lastCodeCausingError != code) {
lastCodeCausingError = null
try {
with(KotlinParserForHighlighting(code)) {
addParseListener(listener)
script()
}
} catch (e: Throwable) {
lastCodeCausingError = code
throw e
}
}
for (i in code.indices) {
val element = listener.result.firstOrNull { i >= it.start && i <= it.end }?.element
val st = when (element) {
null -> null
KotlinParserListenerForHighlighting.RecognizedElements.Keyword -> styles.keyword
KotlinParserListenerForHighlighting.RecognizedElements.FunctionIdentifier -> styles.function
KotlinParserListenerForHighlighting.RecognizedElements.Number -> styles.number
KotlinParserListenerForHighlighting.RecognizedElements.String -> styles.string
KotlinParserListenerForHighlighting.RecognizedElements.StringTemplate -> styles.stringTemplate
KotlinParserListenerForHighlighting.RecognizedElements.TypeIdentifier -> styles.type
KotlinParserListenerForHighlighting.RecognizedElements.Parenthesis -> styles.parenthesis
KotlinParserListenerForHighlighting.RecognizedElements.TypeParameter -> styles.typeParameter
else -> null
} ?: AttributedStyle.DEFAULT
style(st)
append(code[i])
}
}
override fun setErrorPattern(p0: Pattern?) {}
override fun setErrorIndex(p0: Int) {}
private class KotlinParserForHighlighting(code: String) :
KotlinParser(
CommonTokenStream(
KotlinLexer(CharStreams.fromString(code)).also {
it.removeErrorListeners()
}
)
)
{
init {
_buildParseTrees = false
removeErrorListeners()
}
}
}
| 38 | null | 38 | 573 | 5b1ff4d821895f5881a7d389ee92dedff189d2a0 | 3,262 | kotlin-interactive-shell | Apache License 2.0 |
app/src/main/java/com/shehuan/wanandroid/apis/WanAndroidApis.kt | shehuan | 153,994,354 | false | null | package com.shehuan.wanandroid.apis
import com.shehuan.wanandroid.base.BaseResponse
import com.shehuan.wanandroid.bean.*
import com.shehuan.wanandroid.bean.article.ArticleBean
import com.shehuan.wanandroid.bean.navi.NaviBean
import com.shehuan.wanandroid.bean.project.ProjectBean
import com.shehuan.wanandroid.bean.chapter.ChapterArticleBean
import com.shehuan.wanandroid.bean.query.QueryBean
import com.shehuan.wanandroid.bean.tree.TreeBean
import com.shehuan.wanandroid.bean.treeDetail.TreeDetailBean
import io.reactivex.Observable
import retrofit2.http.*
interface WanAndroidApis {
/**
* 登录
*/
@POST("user/login")
fun login(@QueryMap param: Map<String, String>): Observable<BaseResponse<LoginBean>>
/**
* 注册
*/
@POST("user/register")
fun register(@QueryMap param: Map<String, String>): Observable<BaseResponse<RegisterBean>>
/**
* 退出
*/
@GET("user/logout/json")
fun logout(): Observable<BaseResponse<String>>
/**
* 首页banner
*/
@GET("banner/json")
fun banner(): Observable<BaseResponse<List<BannerBean>>>
/**
* 常用网站
*/
@GET("friend/json")
fun friend(): Observable<BaseResponse<List<FriendBean>>>
/**
* 首页文章列表
*/
@GET("article/list/{pageNum}/json")
fun articleList(@Path("pageNum") pageNum: Int): Observable<BaseResponse<ArticleBean>>
/**
* 热词(目前搜索最多的关键词)
*/
@GET("/hotkey/json")
fun hotKey(): Observable<BaseResponse<List<HotKeyBean>>>
/**
* 搜索(支持多个关键词,用空格隔开)
*/
@POST("article/query/{pageNum}/json")
fun query(@Path("pageNum") pageNum: Int, @Query("k") k: String): Observable<BaseResponse<QueryBean>>
/**
* 体系结构
*/
@GET("tree/json")
fun tree(): Observable<BaseResponse<List<TreeBean>>>
/**
* 体系下的文章
*/
@GET("article/list/{pageNum}/json")
fun treeDetail(@Path("pageNum") pageNum: Int, @Query("cid") cid: Int): Observable<BaseResponse<TreeDetailBean>>
/**
* 最新项目
*/
@GET("article/listproject/{pageNum}/json")
fun newProject(@Path("pageNum") pageNum: Int): Observable<BaseResponse<ProjectBean>>
/**
* 项目分类
*/
@GET("project/tree/json")
fun projectCategory(): Observable<BaseResponse<List<ProjectCategoryBean>>>
/**
* 项目分类详情列表
*/
@GET("project/list/{pageNum}/json")
fun projectDetail(@Path("pageNum") pageNum: Int, @Query("cid") cid: Int): Observable<BaseResponse<ProjectBean>>
/**
* 导航
*/
@GET("navi/json")
fun nav(): Observable<BaseResponse<List<NaviBean>>>
/**
* 微信公众号列表
*/
@GET("wxarticle/chapters/json")
fun chapter(): Observable<BaseResponse<List<ChapterBean>>>
/**
* 微信公众号文章列表
*/
@GET("wxarticle/list/{chapterId}/{pageNum}/json")
fun chapterArticleList(@Path("chapterId") chapterId: Int, @Path("pageNum") pageNum: Int): Observable<BaseResponse<ChapterArticleBean>>
/**
* 微信公众号文章搜索
*/
@GET("wxarticle/list/{chapterId}/{pageNum}/json")
fun queryChapterArticle(@Path("chapterId") chapterId: Int, @Path("pageNum") pageNum: Int, @Query("k") k: String): Observable<BaseResponse<ChapterArticleBean>>
/**
* 收藏文章列表
*/
@GET("lg/collect/list/{pageNum}/json")
fun collectArticleList(@Path("pageNum") pageNum: Int): Observable<BaseResponse<ArticleBean>>
/**
* 收藏站内文章
*/
@POST("lg/collect/{id}/json")
fun collectArticle(@Path("id") id: Int): Observable<BaseResponse<String>>
/**
* 在文章列表取消收藏
*/
@POST("lg/uncollect_originId/{id}/json")
fun uncollectArticle(@Path("id") id: Int): Observable<BaseResponse<String>>
/**
* 在收藏列表取消收藏
*/
@POST("lg/uncollect/{id}/json")
fun cancelMyCollection(@Path("id") id: Int, @Query("originId") originId: Int): Observable<BaseResponse<String>>
} | 1 | null | 10 | 39 | 6d8e12117dc0b5cdf3df98f28df2e7a8dd3e03fd | 3,852 | WanAndroid | Apache License 2.0 |
arrow-libs/fx/arrow-fx-stm/src/commonTest/kotlin/arrow/fx/stm/TMVarTest.kt | arrow-kt | 86,057,409 | false | null | package arrow.fx.stm
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.ints.shouldBeExactly
import io.kotest.matchers.shouldBe
import io.kotest.property.Arb
import io.kotest.property.arbitrary.int
import io.kotest.property.arbitrary.orNull
import io.kotest.property.checkAll
class TMVarTest : StringSpec({
"empty creates an empty TMVar" {
val t1 = TMVar.empty<Int>()
atomically { t1.tryTake() } shouldBe null
val t2 = atomically { newEmptyTMVar<Int>() }
atomically { t2.tryTake() } shouldBe null
}
"new creates a filled TMVar" {
val t1 = TMVar.new(100)
atomically { t1.take() } shouldBe 100
val t2 = atomically { newTMVar(10) }
atomically { t2.take() } shouldBe 10
}
"take leaves the TMVar empty" {
val tm = TMVar.new(500)
atomically { tm.take() } shouldBeExactly 500
atomically { tm.tryTake() } shouldBe null
}
"isEmpty = tryRead == null" {
checkAll(Arb.int().orNull()) { i ->
val tm = when (i) {
null -> TMVar.empty()
else -> TMVar.new(i)
}
atomically { tm.isEmpty() } shouldBe
atomically { tm.tryRead() == null }
atomically { tm.isEmpty() } shouldBe
(i == null)
}
}
"isEmpty = tryRead != null" {
checkAll(Arb.int().orNull()) { i ->
val tm = when (i) {
null -> TMVar.empty()
else -> TMVar.new(i)
}
atomically { tm.isNotEmpty() } shouldBe
atomically { tm.tryRead() != null }
atomically { tm.isNotEmpty() } shouldBe
(i != null)
}
}
"take retries on empty" {
val tm = TMVar.empty<Int>()
atomically {
stm { tm.take().let { true } } orElse { false }
} shouldBe false
atomically { tm.tryTake() } shouldBe null
}
"tryTake behaves like take if there is a value" {
val tm = TMVar.new(100)
atomically {
tm.tryTake()
} shouldBe 100
atomically { tm.tryTake() } shouldBe null
}
"tryTake returns null on empty" {
val tm = TMVar.empty<Int>()
atomically { tm.tryTake() } shouldBe null
}
"read retries on empty" {
val tm = TMVar.empty<Int>()
atomically {
stm { tm.read().let { true } } orElse { false }
} shouldBe false
atomically { tm.tryTake() } shouldBe null
}
"read returns the value if not empty and does not remove it" {
val tm = TMVar.new(10)
atomically {
tm.read()
} shouldBe 10
atomically { tm.tryTake() } shouldBe 10
}
"tryRead behaves like read if there is a value" {
val tm = TMVar.new(100)
atomically { tm.tryRead() } shouldBe
atomically { tm.read() }
atomically { tm.tryTake() } shouldBe 100
}
"tryRead returns null if there is no value" {
val tm = TMVar.empty<Int>()
atomically { tm.tryRead() } shouldBe null
atomically { tm.tryTake() } shouldBe null
}
"put retries if there is already a value" {
val tm = TMVar.new(5)
atomically {
stm { tm.put(100).let { true } } orElse { false }
} shouldBe false
atomically { tm.tryTake() } shouldBe 5
}
"put replaces the value if it was empty" {
val tm = TMVar.empty<Int>()
atomically {
tm.put(100)
tm.tryTake()
} shouldBe 100
}
"tryPut behaves like put if there is no value" {
val tm = TMVar.empty<Int>()
atomically {
tm.tryPut(100)
tm.tryTake()
} shouldBe atomically {
tm.put(100)
tm.tryTake()
}
atomically { tm.tryPut(30) } shouldBe true
atomically { tm.tryTake() } shouldBe 30
}
"tryPut returns false if there is already a value" {
val tm = TMVar.new(30)
atomically { tm.tryPut(20) } shouldBe false
atomically { tm.tryTake() } shouldBe 30
}
"swap replaces the current value only if it is not null" {
val tm = TMVar.new(30)
atomically { tm.swap(25) } shouldBeExactly 30
atomically { tm.take() } shouldBeExactly 25
}
"swap should retry if there is no value" {
val tm = TMVar.empty<Int>()
atomically {
stm { tm.swap(10).let { true } } orElse { false }
} shouldBe false
atomically { tm.tryTake() } shouldBe null
}
}
)
| 38 | null | 436 | 5,958 | 5f0da6334b834bad481c7e3c906bee5a34c1237b | 4,343 | arrow | Apache License 2.0 |
platform/platform-cloudnet-v3/src/main/kotlin/taboolib/platform/type/CloudNetV3CommandSender.kt | TabooLib | 120,413,612 | false | null | package taboolib.platform.type
import de.dytanic.cloudnet.CloudNet
import de.dytanic.cloudnet.command.ICommandSender
import taboolib.common.platform.ProxyCommandSender
/**
* TabooLib
* taboolib.platform.type.BungeeConsole
*
* @author CziSKY
* @since 2021/6/21 13:35
*/
class CloudNetV3CommandSender(val sender: ICommandSender) : ProxyCommandSender {
override val origin: Any
get() = sender
override val name: String
get() = sender.name
override var isOp: Boolean
get() = error("unsupported")
set(_) {
error("unsupported")
}
override fun isOnline(): Boolean {
return true
}
override fun sendMessage(message: String) {
sender.sendMessage(message)
}
override fun performCommand(command: String): Boolean {
CloudNet.getInstance().nodeInfoProvider.sendCommandLineAsync(command)
return true
}
override fun hasPermission(permission: String): Boolean {
return sender.hasPermission(permission)
}
} | 9 | null | 90 | 246 | 7379dbcca4b50edcd2b9a756b7ebc503fcf0da4e | 1,039 | taboolib | MIT License |
python/src/com/jetbrains/python/console/PyConsoleParameters.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.console
import org.jetbrains.annotations.ApiStatus
import com.intellij.openapi.module.Module
@ApiStatus.Internal
data class PyConsoleParameters(
val module: Module,
val projectRoot: String,
val consoleSettings: PyConsoleOptions.PyConsoleSettings,
val consoleType: PyConsoleType,
)
| 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 442 | intellij-community | Apache License 2.0 |
data/src/main/java/com/duccnv/cleanmoviedb/data/remote/response/SearchRepoResponse.kt | duccnv-1684 | 260,399,969 | false | null | package com.duccnv.cleanmoviedb.data.remote.response
import com.duccnv.cleanmoviedb.data.model.ItemEntity
import com.google.gson.annotations.SerializedName
data class SearchRepoResponse(
@SerializedName("total_count") val total: Int = 0,
@SerializedName("items") val items: List<ItemEntity>
) | 1 | Kotlin | 1 | 1 | d157e2f275b20c8601766ce36c8a91841c133faa | 302 | clean_movie_db | Apache License 2.0 |
jcv-core/src/main/kotlin/com/ekino/oss/jcv/core/validator/Validators.kt | ekino | 163,856,313 | false | {"Kotlin": 91322, "Java": 13695, "Mustache": 746} | /*
* Copyright (c) 2019 ekino (https://www.ekino.com/)
*/
package com.ekino.oss.jcv.core.validator
import com.ekino.oss.jcv.core.JsonValidator
import com.ekino.oss.jcv.core.comparator.ContainsComparator
import com.ekino.oss.jcv.core.comparator.EndsWithComparator
import com.ekino.oss.jcv.core.comparator.NotEmptyComparator
import com.ekino.oss.jcv.core.comparator.NotNullComparator
import com.ekino.oss.jcv.core.comparator.RegexComparator
import com.ekino.oss.jcv.core.comparator.StartsWithComparator
import com.ekino.oss.jcv.core.comparator.TemplatedURLComparator
import com.ekino.oss.jcv.core.comparator.TypeComparator
import com.ekino.oss.jcv.core.comparator.URLComparator
import com.ekino.oss.jcv.core.comparator.UUIDComparator
import com.ekino.oss.jcv.core.initializer.DateTimeFormatComparatorInitializer
import org.json.JSONArray
import org.json.JSONObject
import org.skyscreamer.jsonassert.ValueMatcher
/**
* Prepared validators.
*
* @author <NAME>
*/
object Validators {
/**
* Validator for a specific json field path.
*
* @param path the json field path
* @param comparator a json value comparator
* @param <T> the field value type
*
* @return the validator
*/
@JvmStatic
fun <T> forPath(path: String, comparator: ValueMatcher<T>): JsonValidator<T> =
DefaultJsonValidator(PrefixMatcher(path), comparator)
/**
* Validator for a specific json field value type.
*
* @param id the validator id
* @param expectedType the expected value type
*
* @return the validator
*/
@JvmStatic
fun type(id: String, expectedType: Class<*>): JsonValidator<Any> =
templatedValidator(id, TypeComparator(expectedType))
/**
* Prepare "templated" validator for a given comparator.
*
* @param id the validator id
* @param comparator a custom comparator
* @param <T> the field value type
*
* @return the validator
*/
@JvmStatic
fun <T> templatedValidator(id: String, comparator: ValueMatcher<T>): JsonValidator<T> =
DefaultValueTemplateIdValidator(id, comparator)
/**
* Default validators.
*
* @return a list of prepared validators
*/
@JvmStatic
fun defaultValidators(): List<JsonValidator<*>> = validators {
+templatedValidator<String>("contains") {
comparatorWith1RequiredParameter(::ContainsComparator)
}
+templatedValidator<String>("starts_with") {
comparatorWith1RequiredParameter(::StartsWithComparator)
}
+templatedValidator<String>("ends_with") {
comparatorWith1RequiredParameter(::EndsWithComparator)
}
+templatedValidator<String>("regex") {
comparatorWith1RequiredParameter {
RegexComparator(it.toRegex().toPattern())
}
}
+templatedValidator("uuid", UUIDComparator())
+templatedValidator("not_null", NotNullComparator())
+templatedValidator("not_empty", NotEmptyComparator())
+templatedValidator("url", URLComparator())
+templatedValidator<String>("url_ending") {
allOf {
+URLComparator()
+comparatorWith1RequiredParameter(::EndsWithComparator)
}
}
+templatedValidator<String>("url_regex") {
allOf {
+URLComparator()
+comparatorWith1RequiredParameter {
RegexComparator(it.toRegex().toPattern())
}
}
}
+templatedValidator("templated_url", TemplatedURLComparator())
+templatedValidator<String>("templated_url_ending") {
allOf {
+TemplatedURLComparator()
+comparatorWith1RequiredParameter(::EndsWithComparator)
}
}
+templatedValidator<String>("templated_url_regex") {
allOf {
+TemplatedURLComparator()
+comparatorWith1RequiredParameter {
RegexComparator(it.toRegex().toPattern())
}
}
}
+templatedValidator("boolean_type", typeComparator<Boolean>())
+templatedValidator("string_type", typeComparator<String>())
+templatedValidator("number_type", typeComparator<Number>())
+templatedValidator("array_type", typeComparator<JSONArray>())
+templatedValidator("object_type", typeComparator<JSONObject>())
+templatedValidator<String>("date_time_format") {
comparatorWithParameters {
DateTimeFormatComparatorInitializer().initComparator(getFirstRequiredParam(), getSecondParam())
}
}
}
}
| 2 | Kotlin | 0 | 21 | b97778ecb73a9e018f2d366d56ac98f9379419d8 | 4,332 | jcv | MIT License |
compat/agp-70x/src/main/kotlin/net/twisterrob/gradle/internal/android/Lint-fatalCompat70x.kt | TWiStErRob | 116,494,236 | false | null | package net.twisterrob.gradle.internal.android
import com.android.build.api.dsl.Lint
import org.gradle.api.Incubating
@Incubating
fun Lint.fatalCompat70x(id: String) {
this.fatal(id)
}
| 88 | null | 5 | 18 | 0fe42207df500f114e21fc438212b5fbaaf2f30f | 188 | net.twisterrob.gradle | The Unlicense |
app/src/main/java/com/rogertalk/roger/helper/ProgressDialogHelper.kt | rogertalk | 207,123,525 | false | {"Gradle": 4, "Java Properties": 3, "Markdown": 7, "Text": 6, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "XML": 157, "Proguard": 2, "Kotlin": 408, "Java": 2, "JSON": 1, "Makefile": 2, "C": 105, "C++": 11} | package com.rogertalk.roger.helper
import android.app.ProgressDialog
import android.content.Context
import com.rogertalk.roger.R
import com.rogertalk.roger.utils.extensions.safeShow
import com.rogertalk.roger.utils.extensions.stringResource
/**
* Use this class add Progress dialog handling to a screen.
*/
class ProgressDialogHelper(val context: Context) {
private var pd: ProgressDialog? = null
fun dismiss() {
pd?.dismiss()
}
fun showWaiting() {
showProgressDialog(R.string.wait_generic.stringResource())
}
fun showProgressDialog(title: String) {
// Dismiss previous one if any
pd?.dismiss()
pd = ProgressDialog(context)
pd?.setTitle(title)
pd?.setCancelable(false)
pd?.setCanceledOnTouchOutside(false)
pd?.isIndeterminate = true
pd?.safeShow()
}
}
| 0 | C | 0 | 1 | 55c9922947311d9d8a1e930463b9ac2a1332e006 | 871 | roger-android | MIT License |
data_binding_app/src/main/java/com/booknara/android/apps/patterns/databinding/data/SampleWeatherData.kt | booknara | 164,749,143 | false | null | package com.booknara.android.apps.patterns.databinding.data
data class SampleWeatherData(
val temp: Int,
val conditions: String,
val windchill: Int,
val units: String) {
fun convertToF() = (temp * (9 / 5.0)) + 32
}
| 1 | null | 1 | 1 | 86c1cb7ee80cef093b181b88203c9fecf7336a1c | 227 | android-implementation-patterns | The Unlicense |
katalog-plugins/katalog-plugin-gcp/src/test/kotlin/com/bol/katalog/plugin/gcp/TestApplication.kt | fossabot | 171,489,498 | false | null | package com.bol.katalog.plugin.gcp
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class TestApplication
| 1 | Kotlin | 2 | 1 | 1b432560afae25a4058be7e311b44108d94c85c2 | 150 | katalog | Apache License 2.0 |
desk360/src/main/java/com/teknasyon/desk360/themev2/Desk360PreScreenSubTitle.kt | Teknasyon-Teknoloji | 188,395,069 | false | {"Kotlin": 248180, "Java": 13519} | package com.teknasyon.desk360.themev2
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.teknasyon.desk360.helper.Desk360SDK
class Desk360PreScreenSubTitle : AppCompatTextView {
init {
this.setTextColor(Color.parseColor(Desk360SDK.config?.data?.create_pre_screen?.sub_title_color))
this.text = Desk360SDK.config?.data?.create_pre_screen?.sub_title
this.textSize =
Desk360SDK.config?.data?.create_pre_screen?.sub_title_font_size!!.toFloat()
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
context,
attrs,
defStyle
)
} | 2 | Kotlin | 2 | 14 | 6ba432bc667adc17c235b1d0a00e51f29a17ed00 | 861 | desk360-android-sdk | MIT License |
src/main/kotlin/org/codetome/zircon/builder/TextColorFactory.kt | geldrin | 100,421,392 | true | {"Kotlin": 279173, "Java": 22751} | package org.codetome.zircon.builder
import org.codetome.zircon.ANSITextColor
import org.codetome.zircon.TextColor
import java.awt.Color
import java.util.regex.Pattern
object TextColorFactory {
val DEFAULT_FOREGROUND_COLOR = ANSITextColor.WHITE
val DEFAULT_BACKGROUND_COLOR = ANSITextColor.BLACK
val DEFAULT_ALPHA = 255
private val RGB_COLOR_PATTERN = Pattern.compile("#[0-9a-fA-F]{6}")
@JvmStatic
fun fromAWTColor(color: Color) = TextColorImpl(color.red, color.green, color.blue, color.alpha)
/**
* Creates a [TextColor] from a <code>red</code>, <code>green</code>, <code>blue</code> triple.
*/
@JvmStatic
@JvmOverloads
fun fromRGB(red: Int, green: Int, blue: Int, alpha: Int = 255) = TextColorImpl(red, green, blue, alpha)
/**
* Parses a string into a color. Formats:
* * *blue* - Constant value from the [ANSI] enum
* * *#1a1a1a* - Hash character followed by three hex-decimal tuples; creates a [TextColorImpl] color entry by
* parsing the tuples as Red, Green and Blue.
*/
@JvmStatic
fun fromString(value: String): TextColor {
value.trim { it <= ' ' }.let { cleanValue ->
return if (RGB_COLOR_PATTERN.matcher(cleanValue).matches()) {
val r = Integer.parseInt(cleanValue.substring(1, 3), 16)
val g = Integer.parseInt(cleanValue.substring(3, 5), 16)
val b = Integer.parseInt(cleanValue.substring(5, 7), 16)
TextColorImpl(r, g, b)
} else {
try {
ANSITextColor.valueOf(cleanValue.toUpperCase())
} catch (e: Exception) {
throw IllegalArgumentException("Unknown color definition \"" + cleanValue + "\"", e)
}
}
}
}
data class TextColorImpl(private val red: Int,
private val green: Int,
private val blue: Int,
private val alpha: Int = DEFAULT_ALPHA) : TextColor {
private val color: Color = Color(red, green, blue, alpha)
override fun toAWTColor() = color
override fun getRed() = red
override fun getGreen() = green
override fun getBlue() = blue
override fun getAlpha() = alpha
}
} | 0 | Kotlin | 0 | 0 | df7c38ac2e1f6a17124dcc5116831270ec38443c | 2,333 | zircon | MIT License |
cloudsdk/src/main/java/io/particle/android/sdk/utils/Enums.kt | particle-iot | 34,549,566 | false | null | package io.particle.android.sdk.utils
import androidx.collection.ArrayMap
import androidx.collection.SparseArrayCompat
import java.lang.Exception
// Errors for use with enum classes which use the functions below
class UnknownEnumIntValueException(intValue: Int) : Exception("Unknown enum value for $intValue")
class UnknownEnumStringValueException(stringValue: String) :
Exception("Unknown enum value for $stringValue")
/**
* Build a [SparseArray] which maps to the given set of array values.
*
* Useful for writing functions that turn known Ints into a matching enum value.
*/
fun <T> buildIntValueMap(values: Array<T>, transformer: (T) -> Int): SparseArrayCompat<T> {
val intValueMap = SparseArrayCompat<T>(values.size)
for (v in values) {
val key = transformer(v)
if (intValueMap.containsKey(key)) {
throw IllegalArgumentException("Duplicate key value found: key=$key")
}
intValueMap.put(key, v)
}
return intValueMap
}
/**
* Build an [ArrayMap] which maps to the given set of array values.
*
* Useful for writing functions that turn known strings into a matching enum value.
*/
fun <T> buildStringValueMap(values: Array<T>, transformer: (T) -> String): ArrayMap<String, T> {
return ArrayMap<String, T>().apply {
for (v in values) {
val key = transformer(v)
if (this.containsKey(key)) {
throw IllegalArgumentException("Duplicate key value found: key=$key")
}
this[key] = v
}
}
}
| 32 | C | 39 | 38 | 996d4dcbf085e6e13c438eaa4ebee546a5659ef0 | 1,550 | particle-android | Apache License 2.0 |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/pipelines/ManualApprovalStepPropsDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.pipelines
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.pipelines.ManualApprovalStepProps
@Generated
public fun buildManualApprovalStepProps(initializer: @AwsCdkDsl
ManualApprovalStepProps.Builder.() -> Unit): ManualApprovalStepProps =
ManualApprovalStepProps.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | e08d201715c6bd4914fdc443682badc2ccc74bea | 423 | aws-cdk-kt | Apache License 2.0 |
openrndr-application/src/jvmMain/kotlin/org/openrndr/platform/Platform.kt | ylegall | 254,515,360 | false | null | package org.openrndr.platform
import java.io.File
import java.util.*
actual object Platform {
private val driver : PlatformDriver = instantiateDriver()
private fun instantiateDriver(): PlatformDriver {
val os = System.getProperty("os.name").lowercase(Locale.getDefault())
return when {
os.startsWith("windows") -> WindowsPlatformDriver()
os.startsWith("mac") -> MacOSPlatformDriver()
else -> GenericPlatformDriver()
}
}
actual val type: PlatformType
get() {
val os = System.getProperty("os.name").lowercase(Locale.getDefault())
return when {
os.startsWith("windows") -> PlatformType.WINDOWS
os.startsWith("mac") -> PlatformType.MAC
else -> PlatformType.GENERIC
}
}
fun tempDirectory(): File {
return driver.temporaryDirectory()
}
fun cacheDirectory(programName: String): File {
return driver.cacheDirectory(programName)
}
fun supportDirectory(programName: String): File {
return driver.supportDirectory(programName)
}
} | 1 | null | 1 | 5 | 29a9045bc7676e330ea65be745d41fffe6e47b4b | 1,149 | openrndr | BSD 2-Clause FreeBSD License |
app/src/main/java/com/nexus/farmap/domain/use_cases/SmoothPath.kt | shivam-modi | 737,138,438 | false | {"Kotlin": 175094} | package com.example.festunavigator.domain.use_cases
import com.example.festunavigator.domain.hit_test.OrientatedPosition
import com.example.festunavigator.domain.smoothing.BezierPoint
import com.example.festunavigator.domain.tree.TreeNode
import com.google.ar.sceneform.math.Vector3
import dev.benedikt.math.bezier.curve.BezierCurve
import dev.benedikt.math.bezier.curve.Order
import dev.benedikt.math.bezier.math.DoubleMathHelper
import dev.benedikt.math.bezier.vector.Vector3D
import dev.romainguy.kotlin.math.Float3
import dev.romainguy.kotlin.math.Quaternion
import io.github.sceneview.math.toFloat3
import io.github.sceneview.math.toNewQuaternion
import io.github.sceneview.math.toVector3
private const val ROUTE_STEP = 0.3f
class SmoothPath {
operator fun invoke(
nodes: List<TreeNode>
): List<OrientatedPosition> {
val list = mutableListOf<OrientatedPosition>()
if (nodes.size > 3){
for (i in 1 until nodes.size-2) {
val node1 = nodes[i]
val node2 = nodes[i+1]
val fromVector = node1.position.toVector3()
val toVector = node2.position.toVector3()
val lineLength = Vector3.subtract(fromVector, toVector).length()
if (lineLength < ROUTE_STEP){
continue
}
val nodesAmount = (lineLength / ROUTE_STEP).toInt()
val dx = (toVector.x - fromVector.x) / nodesAmount
val dy = (toVector.y - fromVector.y) / nodesAmount
val dz = (toVector.z - fromVector.z) / nodesAmount
val difference = Vector3.subtract(toVector, fromVector)
val directionFromTopToBottom = difference.normalized()
val rotationFromAToB: com.google.ar.sceneform.math.Quaternion =
com.google.ar.sceneform.math.Quaternion.lookRotation(
directionFromTopToBottom,
Vector3.up()
)
val rotation = com.google.ar.sceneform.math.Quaternion.multiply(
rotationFromAToB,
com.google.ar.sceneform.math.Quaternion.axisAngle(Vector3(1.0f, 0.0f, 0.0f), 270f)
).toNewQuaternion()
val lowStep = if (nodesAmount < 3) 0 else if (nodesAmount == 3) 1 else 2
val highStep = if (nodesAmount < 3) 1 else if (nodesAmount == 3) 2 else 3
for (j in 0..nodesAmount-highStep) {
val position = Float3(
fromVector.x + dx * j,
fromVector.y + dy * j,
fromVector.z + dz * j
)
if (list.isEmpty() || i == 1){
val pos = OrientatedPosition(position, rotation)
list.add(pos)
}
else if (j == lowStep) {
list.addAll(
getBezierSmoothPoints(
list.removeLast().position,
position,
fromVector.toFloat3(),
ROUTE_STEP
)
)
}
else if (j > lowStep) {
val pos = OrientatedPosition(position, rotation)
list.add(pos)
}
}
if (i == nodes.size-3){
for (j in nodesAmount - highStep until nodesAmount) {
val position = Float3(
fromVector.x + dx * j,
fromVector.y + dy * j,
fromVector.z + dz * j
)
val pos = OrientatedPosition(position, rotation)
list.add(pos)
}
}
}
}
return list
}
private fun getBezierSmoothPoints(
start: Float3,
end: Float3,
point: Float3,
step: Float
): List<OrientatedPosition> {
val curve = bezierCurve(
start,
end,
point
)
val curveLen = curve.length
val rawPointsAmount = 50
val rawStep = curveLen/rawPointsAmount
val rawPoints = mutableListOf<BezierPoint>()
var i = 0.0
while (i < curveLen) {
val t = i/curveLen
val pos = curve.getCoordinatesAt(t)
rawPoints.add(BezierPoint(t, pos))
i += rawStep
}
val endPoint = BezierPoint(1.0, curve.getCoordinatesAt(1.0))
return walkCurve(endPoint, rawPoints, step.toDouble()).map { rawPoint ->
val pos = rawPoint.pos.toFloat3()
val tangent = curve.getTangentAt(rawPoint.t)
pos.x = pos.x
tangent.y = tangent.y
OrientatedPosition(
rawPoint.pos.toFloat3(),
Quaternion.lookRotation(curve.getTangentAt(rawPoint.t).toVector3())
)
}
}
private fun bezierCurve(
start: Float3,
end: Float3,
point: Float3
): BezierCurve<Double, Vector3D> {
val curve = BezierCurve(
Order.QUADRATIC,
start.toVector3D(),
end.toVector3D(),
listOf(point.toVector3D()),
20,
DoubleMathHelper()
)
curve.computeLength()
return curve
}
private fun walkCurve(
end: BezierPoint,
points: List<BezierPoint>,
spacing: Double,
offset: Double = 0.0
): List<BezierPoint>
{
val result = mutableListOf<BezierPoint>()
val space= if (spacing > 0.00001) spacing else 0.00001;
var distanceNeeded = offset
while (distanceNeeded < 0)
{
distanceNeeded += space;
}
var current = points[0]
var next = points[1]
var i = 1
val last = points.count() - 1
while (true)
{
val diff = next.pos - current.pos
val dist = diff.magnitude()
if (dist >= distanceNeeded)
{
current.pos += diff * (distanceNeeded / dist)
result.add(current)
distanceNeeded = spacing
}
else if (i != last)
{
distanceNeeded -= dist
current = next
next = points[++i]
}
else
{
break
}
}
val dist = (result.last().pos - end.pos).magnitude()
if (dist < spacing / 2) {
result.removeLast()
result.add(end)
}
else {
result.add(end)
}
return result
}
private fun Float3.toVector3D(): Vector3D {
return Vector3D(
this.x.toDouble(),
this.y.toDouble(),
this.z.toDouble()
)
}
private fun Vector3D.toFloat3(): Float3 {
return Float3(
this.x.toFloat(),
this.y.toFloat(),
this.z.toFloat()
)
}
private fun Vector3D.toVector3(): Vector3 {
return Vector3(
this.x.toFloat(),
this.y.toFloat(),
this.z.toFloat()
)
}
} | 0 | Kotlin | 0 | 0 | b54a8e700f7d9db8e4de5bfb3b94e9523acd9936 | 7,504 | nsut-navigator | MIT License |
app/src/main/java/com/example/waterfit/WaterEntity.kt | Nikhilrf24 | 551,749,053 | false | {"Kotlin": 7961} | package com.example.waterfit
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "water_table")
data class WaterEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
@ColumnInfo(name = "litres") val litres: String?,
@ColumnInfo(name = "date") val date: String?
) | 2 | Kotlin | 0 | 0 | 6fad8829d6a6adf5055ecb9a8f9587506c3bb40a | 341 | WaterFit | Apache License 2.0 |
library/src/test/java/com/ackee/mvp/library/DeliverToViewTest.kt | davidbilik | 73,558,508 | false | {"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "INI": 2, "Proguard": 3, "XML": 16, "Kotlin": 20, "Java": 1} | package com.ackee.mvp.library
import com.nhaarman.mockito_kotlin.mock
import io.reactivex.Notification
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import org.junit.Test
import kotlin.test.assertEquals
/**
* Test [DeliverToView] transformer.
*
* @author <NAME> (<EMAIL>)
* @since 4/17/2017
*/
class DeliverToViewTest {
@Test
fun deliver_to_view() {
val view = mock<MvpView>()
val deliverToView = DeliverToView<MvpView, Int>(Observable.just(OptionalView(view)))
val testObserver = Observable.fromIterable(listOf(1)).compose(deliverToView).test()
assertEquals(1, testObserver.events[0].size)
assertEquals(Delivery(view, Notification.createOnNext(1)), testObserver.events[0][0])
}
@Test
fun deliver_to_view_no_events() {
val view = mock<MvpView>()
val deliverToView = DeliverToView<MvpView, Int>(Observable.just(OptionalView(view)))
val testObserver = PublishSubject.create<Int>().compose(deliverToView).test()
assertEquals(0, testObserver.events[0].size)
}
@Test
fun deliver_to_null_view() {
val subject = PublishSubject.create<OptionalView<MvpView>>()
subject.onNext(OptionalView(null))
val deliverToView = DeliverToView<MvpView, Int>(subject)
val testObserver = Observable.fromIterable(listOf(1)).compose(deliverToView).test()
assertEquals(0, testObserver.events[0].size)
val view = mock<MvpView>()
subject.onNext(OptionalView(view))
assertEquals(1, testObserver.events[0].size)
assertEquals(Delivery(view, Notification.createOnNext(1)), testObserver.events[0][0])
}
@Test
fun deliver_to_view_only_actual() {
val subject = PublishSubject.create<OptionalView<MvpView>>()
subject.onNext(OptionalView(null))
val deliverToView = DeliverToView<MvpView, Int>(subject)
val testObserver = Observable.fromIterable(listOf(1, 2, 3)).compose(deliverToView).test()
assertEquals(0, testObserver.events[0].size)
val view = mock<MvpView>()
subject.onNext(OptionalView(view))
assertEquals(1, testObserver.events[0].size)
assertEquals(Delivery(view, Notification.createOnNext(3)), testObserver.events[0][0])
}
} | 1 | null | 1 | 1 | 4fe2259860e417658c1d1bc9076c66a9320946e8 | 2,298 | mvp | Apache License 2.0 |
app/src/main/java/com/kroraina/easyreader/modules/rank/RankListPresenter.kt | as1006 | 157,232,166 | false | null | package com.kroraina.easyreader.modules.rank
import com.kroraina.easyreader.base.rx.RxPresenter
import com.kroraina.easyreader.model.local.LocalRepository
import com.kroraina.easyreader.model.remote.RemoteRepository
import io.reactivex.SingleObserver
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
class RankListPresenter : RxPresenter<RankListContract.View>(), RankListContract.Presenter {
override fun loadBillboardList() {
//这个最好是设定一个默认时间采用Remote加载,如果Remote加载失败则采用数据中的数据。我这里先写死吧
val bean = LocalRepository.getInstance()
.billboardPackage
if (bean == null) {
RemoteRepository.getInstance()
.billboardPackage
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSuccess { value -> Schedulers.io().createWorker().schedule { LocalRepository.getInstance().saveBillboardPackage(value) } }
.subscribe(object : SingleObserver<RankListPackage> {
override fun onSubscribe(d: Disposable) {
addDisposable(d)
}
override fun onSuccess(value: RankListPackage) {
mView.finishRefresh(value)
mView.complete()
}
override fun onError(e: Throwable) {
mView.showError()
}
})
} else {
mView.finishRefresh(bean)
mView.complete()
}
}
}
| 1 | null | 1 | 6 | 10d5dd563dfb1010c7c6a3e8d9c893de7b20c1cb | 1,717 | EasyReader | MIT License |
src/jsMain/kotlin/baaahs/app/ui/editor/ShaderEditorStyles.kt | baaahs | 174,897,412 | false | null | package baaahs.app.ui.editor
import baaahs.app.ui.ShaderPreviewStyles
import baaahs.ui.child
import baaahs.ui.important
import kotlinx.css.*
import kotlinx.css.properties.deg
import kotlinx.css.properties.rotate
import kotlinx.css.properties.transform
import materialui.styles.muitheme.MuiTheme
import materialui.styles.palette.dark
import materialui.styles.palette.paper
import styled.StyleSheet
class ShaderEditorStyles(private val theme: MuiTheme) : StyleSheet("app-ui-editor-ShaderEditor", isStatic = true) {
val propsAndPreview by css {
display = Display.flex
gap = 1.em
marginTop = 1.em
paddingRight = 1.em
maxHeight = previewHeight
child(ShaderPreviewStyles.container) {
grow(Grow.NONE)
}
}
val propsTabsAndPanels by css {
grow(Grow.GROW)
display = Display.flex
flexDirection = FlexDirection.row
position = Position.relative
}
val tabsContainer by css {
backgroundColor = theme.palette.primary.dark
}
val propsPanel by css {
display = Display.flex
flexDirection = FlexDirection.row
marginLeft = 1.em
marginRight = 1.em
overflow = Overflow.scroll
child("TABLE") {
display = Display.block
}
}
val adjustGadgetsSwitch by css {
position = Position.absolute
right = 1.em
top = 0.px
transform { rotate((-90).deg) }
declarations["transformOrigin"] = "top right"
}
val shaderProperties by css {
display = Display.grid
gridTemplateColumns = GridTemplateColumns("50% 50%")
gridTemplateAreas = GridTemplateAreas("\"name name\" \"priority channel\" \"returnType returnType\"")
gap = 1.em
alignContent = Align.start
}
val shaderName by css {
declarations["gridArea"] = "name"
}
val shaderPriority by css {
declarations["gridArea"] = "priority"
}
val shaderChannel by css {
declarations["gridArea"] = "channel"
}
val shaderReturnType by css {
declarations["gridArea"] = "returnType"
}
val tab by css {
important(::backgroundColor, theme.palette.background.paper)
important(::textAlign, TextAlign.right)
}
val previewContainer by css {
position = Position.relative
width = previewWidth
height = previewHeight
}
val settingsMenuAffordance by css {
position = Position.absolute
padding(2.px)
backgroundColor = Color.white.withAlpha(.5)
width = 2.em
height = 2.em
right = .5.em
bottom = .5.em
}
val showAdvancedMenuItem by css {
paddingTop = 0.px
paddingBottom = 0.px
paddingLeft = 8.px
svg {
width = .75.em
height = .75.em
}
span {
fontSize = .95.em
}
}
companion object {
val previewWidth = 250.px
val previewHeight = 250.px
}
} | 88 | Kotlin | 6 | 26 | f449a11929ab2850f523ca0d3cb9e5dbbd1d6647 | 3,052 | sparklemotion | MIT License |
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/docs/methods/DocsGetMessagesUploadServerMethod.kt | alatushkin | 156,866,851 | false | null | package name.alatushkin.api.vk.generated.docs.methods
import com.fasterxml.jackson.core.type.TypeReference
import name.alatushkin.api.vk.VkMethod
import name.alatushkin.api.vk.api.VkSuccess
import name.alatushkin.api.vk.generated.common.UploadServer
import name.alatushkin.api.vk.generated.docs.GetMessagesUploadServerType
/**
* Returns the server address for document upload.
*
* [https://vk.com/dev/docs.getMessagesUploadServer]
* @property [type] Document type.
* @property [peer_id] Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + 'Chat ID', e.g. '2000000001'. For community: '- Community ID', e.g. '-12345'. "
*/
class DocsGetMessagesUploadServerMethod() : VkMethod<UploadServer>(
"docs.getMessagesUploadServer",
HashMap()
) {
var type: GetMessagesUploadServerType? by props
var peerId: Long? by props
constructor(
type: GetMessagesUploadServerType? = null,
peerId: Long? = null
) : this() {
this.type = type
this.peerId = peerId
}
fun setType(type: GetMessagesUploadServerType): DocsGetMessagesUploadServerMethod {
this.type = type
return this
}
fun setPeerId(peerId: Long): DocsGetMessagesUploadServerMethod {
this.peerId = peerId
return this
}
override val classRef = DocsGetMessagesUploadServerMethod.classRef
companion object {
val classRef = object : TypeReference<VkSuccess<UploadServer>>() {}
}
}
| 2 | Kotlin | 3 | 10 | 123bd61b24be70f9bbf044328b98a3901523cb1b | 1,485 | kotlin-vk-api | MIT License |
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/docs/methods/DocsGetMessagesUploadServerMethod.kt | alatushkin | 156,866,851 | false | null | package name.alatushkin.api.vk.generated.docs.methods
import com.fasterxml.jackson.core.type.TypeReference
import name.alatushkin.api.vk.VkMethod
import name.alatushkin.api.vk.api.VkSuccess
import name.alatushkin.api.vk.generated.common.UploadServer
import name.alatushkin.api.vk.generated.docs.GetMessagesUploadServerType
/**
* Returns the server address for document upload.
*
* [https://vk.com/dev/docs.getMessagesUploadServer]
* @property [type] Document type.
* @property [peer_id] Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + 'Chat ID', e.g. '2000000001'. For community: '- Community ID', e.g. '-12345'. "
*/
class DocsGetMessagesUploadServerMethod() : VkMethod<UploadServer>(
"docs.getMessagesUploadServer",
HashMap()
) {
var type: GetMessagesUploadServerType? by props
var peerId: Long? by props
constructor(
type: GetMessagesUploadServerType? = null,
peerId: Long? = null
) : this() {
this.type = type
this.peerId = peerId
}
fun setType(type: GetMessagesUploadServerType): DocsGetMessagesUploadServerMethod {
this.type = type
return this
}
fun setPeerId(peerId: Long): DocsGetMessagesUploadServerMethod {
this.peerId = peerId
return this
}
override val classRef = DocsGetMessagesUploadServerMethod.classRef
companion object {
val classRef = object : TypeReference<VkSuccess<UploadServer>>() {}
}
}
| 2 | Kotlin | 3 | 10 | 123bd61b24be70f9bbf044328b98a3901523cb1b | 1,485 | kotlin-vk-api | MIT License |
app/src/main/java/com/bennyjon/searchi/models/FlickrSearchResponse.kt | benny-jon | 154,925,162 | false | null | package com.bennyjon.searchi.models
data class FlickrSearchResponse(
val photos: FlickrPhotoList,
val stat: String
)
| 0 | Kotlin | 2 | 13 | 9488639ca098285a99592f31241b1ce31447be48 | 134 | searchi | Apache License 2.0 |
src/me/anno/ui/input/BooleanInput.kt | AntonioNoack | 266,471,164 | false | null | package me.anno.ui.input
import me.anno.ecs.prefab.PrefabSaveable
import me.anno.language.translation.Dict
import me.anno.ui.base.constraints.WrapAlign
import me.anno.ui.base.groups.PanelListX
import me.anno.ui.base.text.TextPanel
import me.anno.ui.base.text.TextStyleable
import me.anno.ui.input.components.Checkbox
import me.anno.ui.style.Style
import me.anno.utils.types.Strings.isBlank2
/**
* Checkbox with title
* in a Transform child class, all inputs should be created using the VI function, if possible,
* because it forces the programmer to set a tool tip text
* */
class BooleanInput(
title: String,
startValue: Boolean,
defaultValue: Boolean,
style: Style
) : PanelListX(style), InputPanel<Boolean>, TextStyleable {
constructor(style: Style) : this("", false, false, style)
constructor(
title: String, description: String, dictPath: String,
startValue: Boolean, defaultValue: Boolean, style: Style
) : this(Dict[title, dictPath], Dict[description, "$dictPath.desc"], startValue, defaultValue, style)
constructor(
title: String, description: String,
startValue: Boolean, defaultValue: Boolean, style: Style
) : this(title, startValue, defaultValue, style) {
setTooltip(description)
}
private val titleView = if (title.isBlank2()) null else TextPanel("$title:", style)
private val checkView = Checkbox(startValue, defaultValue, style.getSize("fontSize", 10), style)
init {
if (titleView != null) {
this += titleView
titleView.enableHoverColor = true
titleView.padding.right = 5
titleView.focusTextColor = titleView.textColor
}
this += checkView
this += WrapAlign.LeftTop
}
override val lastValue: Boolean get() = checkView.lastValue
// todo drawing & ignoring inputs
private var _isEnabled = true
override var isEnabled: Boolean
get() = _isEnabled
set(value) {
_isEnabled = value; invalidateDrawing()
}
override fun setBold(bold: Boolean) {
titleView?.setBold(bold)
}
override fun setItalic(italic: Boolean) {
titleView?.setItalic(italic)
}
fun setChangeListener(listener: (value: Boolean) -> Unit): BooleanInput {
checkView.setChangeListener(listener)
return this
}
override fun onDraw(x0: Int, y0: Int, x1: Int, y1: Int) {
super.onDraw(x0, y0, x1, y1)
if (isInFocus) isSelectedListener?.invoke()
}
private var isSelectedListener: (() -> Unit)? = null
fun setIsSelectedListener(listener: () -> Unit): BooleanInput {
isSelectedListener = listener
return this
}
fun setResetListener(listener: () -> Boolean?): BooleanInput {
checkView.setResetListener(listener)
return this
}
override fun setValue(value: Boolean, notify: Boolean): BooleanInput {
checkView.setValue(value, notify)
return this
}
override fun onCopyRequested(x: Float, y: Float) = checkView.isChecked.toString()
override fun clone(): BooleanInput {
val clone = BooleanInput(style)
copy(clone)
return clone
}
override fun copy(clone: PrefabSaveable) {
super.copy(clone)
clone as BooleanInput
clone.titleView?.text = titleView?.text ?: ""
// only works, if there is no references
clone.isSelectedListener = isSelectedListener
}
override val className: String = "BooleanInput"
} | 0 | Kotlin | 1 | 8 | e5f0bb17202552fa26c87c230e31fa44cd3dd5c6 | 3,545 | RemsStudio | Apache License 2.0 |
owntracks-android-2.4/project/app/src/main/java/org/owntracks/android/data/repos/MemoryContactsRepo.kt | wir3z | 737,346,188 | false | {"Kotlin": 577231, "Groovy": 303581, "Java": 233010, "Python": 1535, "Shell": 959} | package org.owntracks.android.data.repos
import androidx.annotation.MainThread
import androidx.lifecycle.MutableLiveData
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.owntracks.android.model.FusedContact
import org.owntracks.android.model.messages.MessageCard
import org.owntracks.android.model.messages.MessageLocation
import org.owntracks.android.support.ContactBitmapAndName
import org.owntracks.android.support.ContactBitmapAndNameMemoryCache
import org.owntracks.android.support.Events.*
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MemoryContactsRepo @Inject constructor(
private val eventBus: EventBus,
private val contactsBitmapAndNameMemoryCache: ContactBitmapAndNameMemoryCache
) : ContactsRepo {
private val contacts = mutableMapOf<String, FusedContact>()
override val all = MutableLiveData(contacts)
override fun getById(id: String): FusedContact? {
return contacts[id]
}
@Synchronized
private fun put(id: String, contact: FusedContact) {
Timber.v("new contact allocated id:%s, tid:%s", id, contact.trackerId)
contacts[id] = contact
all.postValue(contacts)
}
@MainThread
@Synchronized
override fun clearAll() {
contacts.clear()
contactsBitmapAndNameMemoryCache.evictAll()
all.postValue(contacts)
}
@Synchronized
override fun remove(id: String) {
Timber.v("removing contact: %s", id)
contacts.remove(id)
all.postValue(contacts)
}
@Synchronized
override fun update(id: String, messageCard: MessageCard) {
var contact = getById(id)
if (contact != null) {
contact.messageCard = messageCard
contactsBitmapAndNameMemoryCache.put(
contact.id,
ContactBitmapAndName.CardBitmap(messageCard.name, null)
)
eventBus.post(contact)
} else {
contact = FusedContact(id)
contact.messageCard = messageCard
contactsBitmapAndNameMemoryCache.put(
contact.id,
ContactBitmapAndName.CardBitmap(messageCard.name, null)
)
put(id, contact)
}
}
@Synchronized
override fun update(id: String, messageLocation: MessageLocation) {
var fusedContact = getById(id)
if (fusedContact != null) {
// If timestamp of last location message is <= the new location message, skip update. We either received an old or already known message.
if (fusedContact.setMessageLocation(messageLocation)) {
all.postValue(contacts)
eventBus.post(fusedContact)
}
} else {
fusedContact = FusedContact(id).apply {
setMessageLocation(messageLocation)
// We may have seen this contact id before, and it may have been removed from the repo
// Check the cache to see if we have a name
contactsBitmapAndNameMemoryCache[id]?.also {
if (it is ContactBitmapAndName.CardBitmap && it.name != null) {
this.messageCard = MessageCard().apply { name = it.name }
}
}
}
put(id, fusedContact)
}
}
@Subscribe(threadMode = ThreadMode.BACKGROUND)
fun onEventMainThread(@Suppress("UNUSED_PARAMETER") e: ModeChanged?) {
clearAll()
}
@Subscribe(threadMode = ThreadMode.BACKGROUND)
fun onEventMainThread(@Suppress("UNUSED_PARAMETER") e: EndpointChanged?) {
clearAll()
}
init {
eventBus.register(this)
}
}
| 0 | Kotlin | 3 | 4 | a515ba358d3467267e9d662564152f5d7613991a | 3,795 | hubitat | Apache License 2.0 |
SQotLin-library-core/src/main/java/ru/nehodov/sqotlin/extensions/SELECT_Ext.kt | Roux13 | 332,227,086 | false | null | package ru.nehodov.sqotlin.extensions
import ru.nehodov.sqotlin.select.ISelect
import ru.nehodov.sqotlin.select.Union
infix fun ISelect.UNION_ALL(other: ISelect): Union {
return Union("""
|${this.query()}
|UNION ALL
|${other.query()}
""")
}
infix fun String.UNION_ALL(other: ISelect): Union {
return Union("""
|${this}
|UNION ALL
|${other.query()}
""")
}
infix fun ISelect.UNION(other: ISelect): Union {
return Union("""
|${this.query()}
|UNION
|${other.query()}
""")
}
infix fun String.UNION(other: ISelect): Union {
return Union("""
|${this}
|UNION
|${other.query()}
""")
}
infix fun ISelect.UNION_ALL(other: String): Union {
return Union("""
|${this.query()}
|UNION ALL
|$other
""")
}
infix fun String.UNION_ALL(other: String): Union {
return Union("""
|$this
|UNION ALL
|$other
""")
}
infix fun ISelect.UNION(other: String): Union {
return Union("""
|${this.query()}
|UNION
|$other
""")
}
infix fun String.UNION(other: String): Union {
return Union("""
|$this
|UNION
|$other
""")
} | 1 | Kotlin | 0 | 1 | e710d3db539981a0f638fd73610008c97fedef0a | 1,250 | SQotLin | MIT License |
app/src/main/java/com/example/dunipool/feature/MarketActivity/Activity_Market.kt | mahdi8459 | 701,484,576 | false | {"Kotlin": 38164} | package com.example.dunipool.feature.MarketActivity
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.dunipool.ApiManager.model.AboutData
import com.example.dunipool.ApiManager.model.CoinAboutItem
import com.example.dunipool.databinding.ActivityMarketBinding
import com.example.dunipool.feature.CoinActivity.Activity_Coin
import com.google.gson.Gson
import ir.dunijet.dunipool.apiManager.ApiManager
import ir.dunijet.dunipool.apiManager.model.CoinsData
class Activity_Market : AppCompatActivity(), MarketAdapter.RecyclerCallBack {
lateinit var binding: ActivityMarketBinding
val apimanager = ApiManager()
lateinit var dataNews: ArrayList<Pair<String, String>>
lateinit var AboutDataMap: MutableMap<String, CoinAboutItem>
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMarketBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.layoutListMarket.btnShowMore.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.livecoinwatch.com/"))
startActivity(intent)
}
binding.swipeRefreshMain.setOnRefreshListener {
initUi()
Handler(Looper.getMainLooper()).postDelayed({
binding.swipeRefreshMain.isRefreshing = false
}, 1000)
}
getAboutDataFromAssets()
initUi()
}
override fun onResume() {
super.onResume()
initUi()
}
private fun initUi() {
getNewsFromApi()
getTopCoinsFromApi()
}
private fun getTopCoinsFromApi() {
apimanager.getCoinsList(object : ApiManager.ApiCallback<List<CoinsData.Data>> {
override fun onSuccess(data: List<CoinsData.Data>) {
showDataInRecycler(data)
}
override fun onError(errorMessage: String) {
Toast.makeText(this@Activity_Market, "error$errorMessage", Toast.LENGTH_LONG).show()
Log.e("test2" , errorMessage)
}
})
}
private fun showDataInRecycler(data: List<CoinsData.Data>) {
val marketadapter = MarketAdapter(ArrayList(data), this)
binding.layoutListMarket.recyclerViewMain.adapter = marketadapter
binding.layoutListMarket.recyclerViewMain.layoutManager = LinearLayoutManager(this)
}
private fun getNewsFromApi() {
apimanager.getNews(object : ApiManager.ApiCallback<ArrayList<Pair<String, String>>> {
override fun onSuccess(data: ArrayList<Pair<String, String>>) {
dataNews = data
refreshNews()
}
override fun onError(errorMessage: String) {
Toast.makeText(this@Activity_Market, "error $errorMessage", Toast.LENGTH_SHORT)
.show()
}
})
}
private fun refreshNews() {
val randomAccess = (0..49).random()
binding.layoutNewsMarket.txtNews.text = dataNews[randomAccess].first
binding.layoutNewsMarket.imgNews.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(dataNews[randomAccess].second))
startActivity(intent)
}
binding.layoutNewsMarket.txtNews.setOnClickListener {
refreshNews()
}
}
override fun onCoinItemClicked(dataCoin: CoinsData.Data) {
val intent = Intent(this, Activity_Coin::class.java)
val bundle = Bundle()
bundle.putParcelable("bundle1", dataCoin)
bundle.putParcelable("bundle2", AboutDataMap[dataCoin.coinInfo.name])
intent.putExtra("bundle", bundle)
startActivity(intent)
}
private fun getAboutDataFromAssets() {
val fileString = applicationContext.assets.open("currencyinfo.json").bufferedReader()
.use { it.readText() }
AboutDataMap = mutableMapOf()
val gson = Gson()
val dataAboutAll = gson.fromJson(fileString, AboutData::class.java)
dataAboutAll.forEach {
AboutDataMap[it.currencyName] = CoinAboutItem(
it.info.web,
it.info.github,
it.info.twt,
it.info.reddit,
it.info.desc
)
}
}
} | 0 | Kotlin | 0 | 0 | c6a2c2d5e0be6bb4c83c79359c8a0d4727c9f28a | 4,557 | project-digital-currency | MIT License |
app/src/main/java/com/sukacolab/app/ui/component/cards/ItemListProfile.kt | cahyadiantoni | 757,308,387 | false | {"Kotlin": 901754} | package com.sukacolab.app.ui.component.cards
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.VerticalAlignmentLine
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.sukacolab.app.R
import com.sukacolab.app.ui.navigation.Screen
import com.sukacolab.app.ui.theme.SukacolabBaseCoreTheme
import com.sukacolab.app.ui.theme.darkGold
import com.sukacolab.app.ui.theme.darkGreen
import com.sukacolab.app.ui.theme.tertiaryColor
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ItemListProfile(
navController: NavController,
userId: Int,
projectId: Int,
image: String?,
name: String,
summary: String?
) {
Card(
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 4.dp)
.fillMaxSize()
.clickable {
navController.navigate(
Screen.ProfileOther.createRoute(
userId, projectId
)
)
},
elevation = CardDefaults.cardElevation(
defaultElevation = 2.dp
)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
modifier = Modifier
.size(60.dp)
.clip(CircleShape)
) {
if (image == null) {
Image(
painter = painterResource(id = R.drawable.img_logo),
contentDescription = null,
modifier = Modifier.size(60.dp),
contentScale = ContentScale.Crop
)
} else {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(image)
.crossfade(true)
.build(),
contentDescription = null,
contentScale = ContentScale.Crop,
placeholder = painterResource(id = R.drawable.img_logo),
modifier = Modifier
.size(60.dp)
)
}
}
Spacer(modifier = Modifier.size(10.dp))
Column(
modifier = Modifier.fillMaxWidth(),
) {
Text(
text = name,
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
)
Text(
text = summary?: "",
fontWeight = FontWeight.Normal,
)
}
}
}
}
| 0 | Kotlin | 0 | 0 | e189385bc897cfe187d87d70138e260027a1a640 | 4,794 | sukacolab | MIT License |
src/main/kotlin/me/bytebeats/charts/desktop/line/render/point/IPointDrawer.kt | bytebeats | 468,312,472 | false | {"Kotlin": 84437} | package me.bytebeats.charts.desktop.line.render.point
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.drawscope.DrawScope
/**
* @Author bytebeats
* @Email <<EMAIL>>
* @Github https://github.com/bytebeats
* @Created at 2022/3/10 20:41
* @Version 1.0
* @Description TO-DO
*/
interface IPointDrawer {
fun drawPoint(drawScope: DrawScope, canvas: Canvas, center: Offset)
} | 1 | Kotlin | 2 | 28 | 840a040acc2470d14917af6566a141f75e9b2c99 | 455 | compose-charts-desktop | The Unlicense |
client/src/main/kotlin/io/titandata/remote/s3web/client/S3WebRemoteClient.kt | titan-data | 221,483,271 | false | null | /*
* Copyright The Titan Project Contributors.
*/
package io.titandata.remote.s3web.client
import io.titandata.remote.RemoteClient
import io.titandata.remote.RemoteClientUtil
import java.net.URI
/**
* The URI syntax for S3 web remotes is to basically replace the "s3web" portion with "http".
*
* s3://host[/path]
*
* Currently, we always use HTTP to access the resources, though a parameter could be provided to use HTTPS instead
* if needed.
*/
class S3WebRemoteClient : RemoteClient {
private val util = RemoteClientUtil()
override fun getProvider(): String {
return "s3web"
}
override fun parseUri(uri: URI, additionalProperties: Map<String, String>): Map<String, Any> {
val (username, password, host, port, path) = util.getConnectionInfo(uri)
if (password != null) {
throw IllegalArgumentException("Username and password cannot be specified for S3 remote")
}
if (username != null) {
throw IllegalArgumentException("Username cannot be specified for S3 remote")
}
if (host == null) {
throw IllegalArgumentException("Missing bucket in S3 remote")
}
for (p in additionalProperties.keys) {
throw IllegalArgumentException("Invalid remote property '$p'")
}
var url = "http://$host"
if (port != null) {
url += ":$port"
}
if (path != null) {
url += "$path"
}
return mapOf("url" to url)
}
override fun toUri(properties: Map<String, Any>): Pair<String, Map<String, String>> {
val url = properties["url"] as String
return Pair(url.replace("http", "s3web"), emptyMap())
}
override fun getParameters(remoteProperties: Map<String, Any>): Map<String, Any> {
return emptyMap()
}
}
| 0 | Kotlin | 1 | 0 | 82d32ed5ea045f6cf93b62f6463d28b3352c8511 | 1,855 | s3web-remote | Apache License 2.0 |
tangem-sdk/src/main/java/com/tangem/tangem_sdk_new/DefaultSessionViewDelegate.kt | Gimly-Blockchain | 267,425,784 | true | {"Java": 634349, "Kotlin": 432845, "HTML": 40960, "JavaScript": 15756, "CSS": 11340, "Ruby": 733, "Assembly": 39} | package com.tangem.tangem_sdk_new
import android.app.Activity
import android.view.ContextThemeWrapper
import com.tangem.*
import com.tangem.commands.PinType
import com.tangem.tangem_sdk_new.nfc.NfcReader
import com.tangem.tangem_sdk_new.ui.NfcSessionDialog
/**
* Default implementation of [SessionViewDelegate].
* If no customisation is required, this is the preferred way to use Tangem SDK.
*/
class DefaultSessionViewDelegate(private val reader: NfcReader) : SessionViewDelegate {
lateinit var activity: Activity
private var readingDialog: NfcSessionDialog? = null
init {
setLogger()
}
override fun onSessionStarted(cardId: String?, message: Message?) {
postUI {
if (readingDialog == null) createReadingDialog(activity)
readingDialog?.show(SessionViewDelegateState.Ready(cardId, message))
}
}
private fun createReadingDialog(activity: Activity) {
readingDialog = NfcSessionDialog(ContextThemeWrapper(activity, R.style.CardSdkTheme)).apply {
dismissWithAnimation = true
create()
setOnCancelListener {
reader.stopSession(true)
createReadingDialog(activity)
}
}
}
override fun onSecurityDelay(ms: Int, totalDurationSeconds: Int) {
postUI {
readingDialog?.show(SessionViewDelegateState.SecurityDelay(ms, totalDurationSeconds))
}
}
override fun onDelay(total: Int, current: Int, step: Int) {
postUI {
readingDialog?.show(SessionViewDelegateState.Delay(total, current, step))
}
}
override fun onTagLost() {
postUI { readingDialog?.show(SessionViewDelegateState.TagLost) }
}
override fun onTagConnected() {
postUI { readingDialog?.show(SessionViewDelegateState.TagConnected) }
}
override fun onWrongCard(wrongValueType: WrongValueType) {
postUI { readingDialog?.show(SessionViewDelegateState.WrongCard(wrongValueType)) }
}
override fun onSessionStopped(message: Message?) {
postUI { readingDialog?.show(SessionViewDelegateState.Success(message)) }
}
override fun onError(error: TangemError) {
postUI { readingDialog?.show(SessionViewDelegateState.Error(error)) }
}
override fun onPinRequested(pinType: PinType, callback: (pin: String) -> Unit) {
postUI { readingDialog?.show(SessionViewDelegateState.PinRequested(pinType, callback)) }
}
override fun onPinChangeRequested(pinType: PinType, callback: (pin: String) -> Unit) {
postUI {
if (readingDialog == null) { createReadingDialog(activity) }
readingDialog?.show(SessionViewDelegateState.PinChangeRequested(pinType, callback))
}
}
override fun dismiss() {
postUI { readingDialog?.dismiss() }
}
private fun setLogger() {
Log.setLogger(
object : LoggerInterface {
override fun i(logTag: String, message: String) {
android.util.Log.i(logTag, message)
}
override fun e(logTag: String, message: String) {
android.util.Log.e(logTag, message)
}
override fun v(logTag: String, message: String) {
android.util.Log.v(logTag, message)
}
}
)
}
} | 0 | Java | 0 | 1 | a94cb113f3aa720406fea0880bccf127702ac521 | 3,414 | tangem-sdk-android | MIT License |
emtehanak/src/main/java/ir/mahdighanbarpour/emtehanak/features/teachersStudentScreen/StudentTeachersFragment.kt | MahdiGhanbarpour | 735,064,418 | false | {"Kotlin": 708590} | package ir.mahdighanbarpour.emtehanak.features.teachersStudentScreen
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import ir.mahdighanbarpour.emtehanak.databinding.FragmentStudentTeachersBinding
import ir.mahdighanbarpour.emtehanak.utils.changeStatusBarColor
class StudentTeachersFragment : Fragment() {
private lateinit var binding: FragmentStudentTeachersBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = FragmentStudentTeachersBinding.inflate(layoutInflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
onFragmentShowed()
}
fun onFragmentShowed() {
changeStatusBarColor(requireActivity().window, "#FFFFFFFF", true)
}
} | 0 | Kotlin | 0 | 0 | 6fd6104330e500b9afee6f7f09fa1f80890e3c63 | 991 | Emtehanak | MIT License |
app/app/src/main/kotlin/tech/nagual/phoenix/tools/organizer/di/PreferencesModule.kt | overphoenix | 621,371,055 | false | null | package tech.nagual.phoenix.tools.organizer.di
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.ExperimentalCoroutinesApi
import tech.nagual.app.appDataStore
import tech.nagual.common.preferences.flow.FlowSharedPreferences
import tech.nagual.phoenix.tools.organizer.preferences.PreferenceRepository
import java.io.File
import java.security.KeyStore
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
@OptIn(ExperimentalCoroutinesApi::class)
object PreferencesModule {
@Provides
@Singleton
fun providePreferenceRepository(
dataStore: DataStore<Preferences>,
sharedPreferences: FlowSharedPreferences,
): PreferenceRepository {
return PreferenceRepository(dataStore, sharedPreferences)
}
@Provides
@Singleton
fun provideDataStore(@ApplicationContext context: Context) = context.appDataStore
@Provides
@Singleton
fun provideEncryptedSharedPreferences(@ApplicationContext context: Context): FlowSharedPreferences {
val filename = "encrypted_prefs"
fun createEncryptedSharedPreferences(context: Context): SharedPreferences {
val masterKey = MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
return EncryptedSharedPreferences.create(
context,
filename,
masterKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
@SuppressLint("ApplySharedPref")
fun deleteSharedPreferencesFileAndMasterKey(context: Context) {
try {
val keyStore = KeyStore.getInstance("AndroidKeyStore")
val appStorageDir = context.filesDir?.parent ?: return
val prefsFile = File("$appStorageDir/shared_prefs/$filename.xml")
context.getSharedPreferences(filename, Context.MODE_PRIVATE)
.edit()
.clear()
.commit()
keyStore.load(null)
keyStore.deleteEntry(MasterKey.DEFAULT_MASTER_KEY_ALIAS)
prefsFile.delete()
} catch (e: Throwable) {}
}
return FlowSharedPreferences(
try {
createEncryptedSharedPreferences(context)
} catch (e: Throwable) {
deleteSharedPreferencesFileAndMasterKey(context)
createEncryptedSharedPreferences(context)
}
)
}
}
| 0 | Kotlin | 0 | 0 | 64264f261c2138d5f1932789702661917bbfae28 | 3,113 | phoenix-android | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.