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
plugins/gradle/java/testSources/execution/test/events/fixture/GradleExecutionOutputFixture.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gradle.testFramework.fixture import com.intellij.openapi.Disposable import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationEvent import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener import com.intellij.openapi.externalSystem.model.task.event.ExternalSystemTaskExecutionEvent import com.intellij.openapi.externalSystem.model.task.event.TestOperationDescriptor import com.intellij.openapi.externalSystem.model.task.event.TestOperationDescriptorImpl import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtil import com.intellij.testFramework.common.runAll import com.intellij.testFramework.fixtures.IdeaTestFixture import com.intellij.util.containers.addIfNotNull import org.assertj.core.api.Assertions import org.assertj.core.api.ListAssert import org.jetbrains.plugins.gradle.testFramework.fixtures.tracker.OperationLeakTracker import org.jetbrains.plugins.gradle.util.getGradleTaskExecutionOperation import java.util.function.Function class GradleExecutionOutputFixture( private val project: Project ) : IdeaTestFixture { private lateinit var fixtureDisposable: Disposable private lateinit var taskExecutionLeakTracker: OperationLeakTracker private lateinit var output: Output override fun setUp() { fixtureDisposable = Disposer.newDisposable() taskExecutionLeakTracker = OperationLeakTracker { getGradleTaskExecutionOperation(project, it) } taskExecutionLeakTracker.setUp() installGradleEventsListener() } override fun tearDown() { runAll( { taskExecutionLeakTracker.tearDown() }, { Disposer.dispose(fixtureDisposable) } ) } fun <R> assertExecutionOutputIsReady(action: () -> R): R { return taskExecutionLeakTracker.withAllowedOperation(1, action) } suspend fun <R> assertExecutionOutputIsReadyAsync(action: suspend () -> R): R { return taskExecutionLeakTracker.withAllowedOperationAsync(1, action) } fun assertTestEventContain(className: String, methodName: String?) { Assertions.assertThat(output.testDescriptors) .transform { it.className to it.methodName } .contains(className to methodName) } fun assertTestEventDoesNotContain(className: String, methodName: String?) { Assertions.assertThat(output.testDescriptors) .transform { it.className to it.methodName } .doesNotContain(className to methodName) } fun assertTestEventsWasNotReceived() { Assertions.assertThat(output.testDescriptors) .transform { it.className to it.methodName } .isEmpty() } private fun installGradleEventsListener() { val listener = object : ExternalSystemTaskNotificationListener { override fun onStart(id: ExternalSystemTaskId, workingDir: String?) { output = Output() } override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) { output.testDescriptors.addAll( extractTestOperationDescriptors(text) ) } override fun onStatusChange(event: ExternalSystemTaskNotificationEvent) { output.testDescriptors.addIfNotNull( getTestOperationDescriptor(event) ) } } ExternalSystemProgressNotificationManager.getInstance() .addNotificationListener(listener, fixtureDisposable) } private fun getTestOperationDescriptor(event: ExternalSystemTaskNotificationEvent): TestOperationDescriptor? { val executionEvent = event as? ExternalSystemTaskExecutionEvent ?: return null val descriptor = executionEvent.progressEvent.descriptor as? TestOperationDescriptor ?: return null val className = descriptor.className ?: "" val methodName = descriptor.methodName?.removeSuffix("()") ?: "" return TestOperationDescriptorImpl("", -1, "", className, methodName) } private fun extractTestOperationDescriptors(text: String): List<TestOperationDescriptor> { val descriptors = ArrayList<TestOperationDescriptor>() for (rawDescriptor in text.split("<ijLogEol/>")) { val descriptor = parseTestOperationDescriptor(rawDescriptor) if (descriptor != null) { descriptors.add(descriptor) } } return descriptors } private fun parseTestOperationDescriptor(descriptor: String): TestOperationDescriptor? { val className = StringUtil.substringAfter(descriptor, "' className='") ?.let { StringUtil.substringBefore(it, "' />") } ?: return null val methodName = StringUtil.substringAfter(descriptor, "<descriptor name='") ?.let { StringUtil.substringBefore(it, "' displayName='") } ?.removeSuffix("()") ?: return null return TestOperationDescriptorImpl("", -1, "", className, methodName) } private class Output { val testDescriptors: MutableList<TestOperationDescriptor> = ArrayList() } companion object { fun <T, R> ListAssert<T>.transform(transform: (T) -> R): ListAssert<R> { return extracting(Function(transform)) as ListAssert<R> } } }
7
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
5,469
intellij-community
Apache License 2.0
navui/src/main/java/com/hutchins/navui/core/NavUIControllerViewModel.kt
taekwonjoe01
184,627,574
false
{"Kotlin": 136889}
/******************************************************************************* * Copyright 2019 <NAME> * * 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 com.hutchins.navui.core import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.navigation.NavDestination class NavUIControllerViewModel(val navUISettings: List<NavUISetting<*>>) : ViewModel(), NavUISettingListener { init { for (setting in navUISettings) { setting.listener = this } } private var destination: NavDestination? = null private var navViewDelegate: NavViewDelegate? = null fun onNavUIActive(destination: NavDestination, navViewDelegate: NavViewDelegate) { this.destination = destination this.navViewDelegate = navViewDelegate for (navUIPersistentSetting in navUISettings) { navUIPersistentSetting.onActive(destination, navViewDelegate) } } fun onNavUIInactive() { this.destination = null this.navViewDelegate = null } override fun onValueSet(navUISetting: NavUISetting<*>) { destination?.let { dest -> navViewDelegate?.let { viewDelegate -> navUISetting.onSettingSetWhileActive(dest, viewDelegate) } } } } class NavUIControllerViewModelFactory(private val baseNavUIController: BaseNavUIController) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return NavUIControllerViewModel(baseNavUIController.buildSettings()) as T } } internal interface NavUISettingListener { fun onValueSet(navUISetting: NavUISetting<*>) } abstract class NavUISetting<T : Any?> { internal lateinit var listener: NavUISettingListener var setting: T? = null set(value) { field = value listener.onValueSet(this) } internal fun onActive(destination: NavDestination, navViewDelegate: NavViewDelegate) { applySetting(destination, navViewDelegate, true, setting) } internal fun onSettingSetWhileActive(destination: NavDestination, navViewDelegate: NavViewDelegate) { applySetting(destination, navViewDelegate, false, setting) } abstract fun applySetting(destination: NavDestination, navViewDelegate: NavViewDelegate, isNavigationTransition: Boolean, setting: T?) }
3
Kotlin
0
1
34678141c021a4d775c0ce79d7bbd071fbfd01b9
3,568
BetterJetpackNav
MIT License
app/src/main/java/me/seebrock3r/elevationtester/widget/BitmapGenerator.kt
fossabot
153,639,520
true
{"Kotlin": 33611, "RenderScript": 2561}
package me.seebrock3r.elevationtester.widget import android.content.Context import android.graphics.Bitmap import android.renderscript.Allocation import android.renderscript.RenderScript import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.Deferred import kotlinx.coroutines.experimental.Job import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.launch import me.seebrock3r.elevationtester.widget.colorwheel.ScriptC_ColorWheel /* * This file was adapted from StylingAndroid's repo: https://github.com/StylingAndroid/ColourWheel */ class BitmapGenerator( private val androidContext: Context, private val config: Bitmap.Config, private val observer: (bitmap: Bitmap) -> Unit ) { private val size = Size(0, 0) var brightness = Byte.MAX_VALUE set(value) { field = value generate() } private var rsCreation: Deferred<RenderScript> = async(CommonPool) { RenderScript.create(androidContext).also { _renderscript = it } } private var _renderscript: RenderScript? = null private val renderscript: RenderScript get() { assert(rsCreation.isCompleted) return _renderscript as RenderScript } private var generateProcess: Job? = null private val generated = AutoCreate(Bitmap::recycle) { Bitmap.createBitmap(size.width, size.height, config) } private val generatedAllocation = AutoCreate(Allocation::destroy) { Allocation.createFromBitmap( renderscript, generated.value, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT ) } private val colourWheelScript = AutoCreate(ScriptC_ColorWheel::destroy) { ScriptC_ColorWheel(renderscript) } fun setSize(width: Int, height: Int) { size.takeIf { it.width != width || it.height != height }?.also { generated.clear() generatedAllocation.clear() } size.width = width size.height = height generate() } private fun generate() { if (size.hasDimensions && generateProcess?.isCompleted != false) { generateProcess = launch(CommonPool) { rsCreation.await() generated.value.also { draw(it) launch(UI) { observer(it) } } } } } private fun draw(bitmap: Bitmap) { generatedAllocation.value.apply { copyFrom(bitmap) colourWheelScript.value.invoke_colorWheel( colourWheelScript.value, this, brightness.toFloat() / Byte.MAX_VALUE.toFloat() ) copyTo(bitmap) } } fun stop() { generated.clear() generatedAllocation.clear() colourWheelScript.clear() _renderscript?.destroy() rsCreation.takeIf { it.isActive }?.cancel() } private data class Size(var width: Int, var height: Int) { val hasDimensions get() = width > 0 && height > 0 } }
0
Kotlin
0
0
8e69aa1c9f15deccaf08f52222d2cf9c4ef81d9a
3,286
uplift
Apache License 2.0
app/src/main/java/com/malibin/morse/data/service/response/SocketResponse.kt
cha7713
463,427,946
true
{"Kotlin": 121634, "PureBasic": 2910}
package com.malibin.morse.data.service.response /** * Created By Malibin * on 1월 20, 2021 */ data class SocketResponse( private val id: String, val response: String?, val sdpAnswer: String?, val candidate: Candidate?, val message: String, val success: Boolean, val from: String?, val roomIdx: Int?, val data: ViewerSocketResponse?, ) { val responseId: ID get() = ID.findBy(id) fun isRejected(): Boolean = response == "rejected" enum class ID( private val value: String ) { PRESENTER_RESPONSE("presenterResponse"), VIEWER_RESPONSE("viewerResponse"), ICE_CANDIDATE("iceCandidate"), STOP_COMMUNICATION("stopCommunication"), ERROR_RESPONSE("serverException"), USER_ERROR_RESPONSE("userException"); fun has(value: String): Boolean = this.value == value companion object { fun findBy(value: String): ID { return values().find { it.has(value) } ?: throw IllegalArgumentException("cannot find ID of $value") } } } }
0
null
0
0
8103c56b8079224aba8eedc7a4a4af40a1b92b4c
1,121
morse_android_stove_camp
Apache License 2.0
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsTrackingController.kt
nekomangaorg
182,704,531
false
{"Kotlin": 3442643}
package eu.kanade.tachiyomi.ui.setting import android.app.Activity import androidx.preference.Preference import androidx.preference.PreferenceGroup import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.TrackService import eu.kanade.tachiyomi.data.track.anilist.AnilistApi import eu.kanade.tachiyomi.data.track.myanimelist.MyAnimeListApi import eu.kanade.tachiyomi.jobs.tracking.TrackingSyncJob import eu.kanade.tachiyomi.util.system.launchIO import eu.kanade.tachiyomi.util.system.openInBrowser import eu.kanade.tachiyomi.util.view.snack import eu.kanade.tachiyomi.widget.preference.TrackLoginDialog import eu.kanade.tachiyomi.widget.preference.TrackLogoutDialog import eu.kanade.tachiyomi.widget.preference.TrackerPreference import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.nekomanga.R import org.nekomanga.constants.MdConstants import uy.kohesive.injekt.injectLazy class SettingsTrackingController : SettingsController(), TrackLoginDialog.Listener, TrackLogoutDialog.Listener { private val trackManager: TrackManager by injectLazy() override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply { titleRes = R.string.tracking switchPreference { key = Keys.autoUpdateTrack titleRes = R.string.update_tracking_after_reading defaultValue = true } switchPreference { key = Keys.trackMarkedAsRead titleRes = R.string.update_tracking_marked_read defaultValue = false } multiSelectListPreferenceMat(activity) { key = eu.kanade.tachiyomi.data.preference.PreferenceKeys.autoTrackContentRating titleRes = R.string.auto_track_content_rating_title summaryRes = R.string.auto_track_content_rating_summary entriesRes = arrayOf( R.string.content_rating_safe, R.string.content_rating_suggestive, R.string.content_rating_erotica, R.string.content_rating_pornographic, ) entryValues = listOf( MdConstants.ContentRating.safe, MdConstants.ContentRating.suggestive, MdConstants.ContentRating.erotica, MdConstants.ContentRating.pornographic, ) defValue = setOf( MdConstants.ContentRating.safe, MdConstants.ContentRating.suggestive, MdConstants.ContentRating.erotica, MdConstants.ContentRating.pornographic ) defaultValue = listOf( MdConstants.ContentRating.safe, MdConstants.ContentRating.suggestive, MdConstants.ContentRating.erotica, MdConstants.ContentRating.pornographic ) } preference { key = "refresh_tracking_meta" titleRes = R.string.refresh_tracking_metadata summaryRes = R.string.updates_tracking_details onClick { TrackingSyncJob.doWorkNow(context) } } preferenceCategory { titleRes = R.string.services trackPreference(trackManager.myAnimeList) { activity?.openInBrowser(MyAnimeListApi.authUrl()) } switchPreference { isPersistent = true isIconSpaceReserved = true title = context.getString( R.string.auto_track, ) preferences .getStringPref(Keys.trackUsername(trackManager.myAnimeList.id)) .changes() .onEach { isVisible = it.isNotEmpty() } .launchIn(viewScope) this.defaultValue = preferences .autoAddTracker() .get() .contains(TrackManager.MYANIMELIST.toString()) this.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> updateAutoAddTracker(newValue as Boolean, TrackManager.MYANIMELIST) } } trackPreference(trackManager.aniList) { activity?.openInBrowser(AnilistApi.authUrl()) } preference { key = "update_anilist_scoring" isPersistent = true isIconSpaceReserved = true title = context.getString( R.string.update_tracking_scoring_type, context.getString(R.string.anilist), ) preferences .getStringPref(Keys.trackUsername(trackManager.aniList.id)) .changes() .onEach { isVisible = it.isNotEmpty() } .launchIn(viewScope) onClick { viewScope.launchIO { val (result, error) = trackManager.aniList.updatingScoring() if (result) { view?.snack(R.string.scoring_type_updated) } else { view?.snack( context.getString( R.string.could_not_update_scoring_, error?.localizedMessage.orEmpty(), ), ) } } } } switchPreference { isPersistent = true isIconSpaceReserved = true title = context.getString( R.string.auto_track, ) preferences .getStringPref(Keys.trackUsername(trackManager.aniList.id)) .changes() .onEach { isVisible = it.isNotEmpty() } .launchIn(viewScope) this.defaultValue = preferences.autoAddTracker().get().contains(TrackManager.ANILIST.toString()) this.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> updateAutoAddTracker(newValue as Boolean, TrackManager.ANILIST) } } trackPreference(trackManager.kitsu) { val dialog = TrackLoginDialog(trackManager.kitsu, R.string.email) dialog.targetController = this@SettingsTrackingController dialog.showDialog(router) } switchPreference { key = "auto_add_kitsu" isPersistent = true isIconSpaceReserved = true title = context.getString( R.string.auto_track, ) preferences .getStringPref(Keys.trackUsername(trackManager.kitsu.id)) .changes() .onEach { isVisible = it.isNotEmpty() } .launchIn(viewScope) this.defaultValue = preferences.autoAddTracker().get().contains(TrackManager.KITSU.toString()) this.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> updateAutoAddTracker(newValue as Boolean, TrackManager.KITSU) } } trackPreference(trackManager.mangaUpdates) { val dialog = TrackLoginDialog(trackManager.mangaUpdates, R.string.username) dialog.targetController = this@SettingsTrackingController dialog.showDialog(router) } switchPreference { key = "auto_add_mangaupdates" isPersistent = true isIconSpaceReserved = true title = context.getString( R.string.auto_track, ) preferences .getStringPref(Keys.trackUsername(trackManager.mangaUpdates.id)) .changes() .onEach { isVisible = it.isNotEmpty() } .launchIn(viewScope) this.defaultValue = preferences .autoAddTracker() .get() .contains(TrackManager.MANGA_UPDATES.toString()) this.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> updateAutoAddTracker(newValue as Boolean, TrackManager.MANGA_UPDATES) } } } } private fun updateAutoAddTracker(newValue: Boolean, trackId: Int): Boolean { if (newValue) { preferences .autoAddTracker() .changes() .onEach { val mutableSet = it.toMutableSet() mutableSet.add(trackId.toString()) preferences.setAutoAddTracker(mutableSet) } .launchIn(viewScope) } else { preferences .autoAddTracker() .changes() .onEach { val mutableSet = it.toMutableSet() mutableSet.remove(trackId.toString()) preferences.setAutoAddTracker(mutableSet) } .launchIn(viewScope) } return true } private inline fun PreferenceGroup.trackPreference( service: TrackService, crossinline login: () -> Unit, ): TrackerPreference { return add( TrackerPreference(context).apply { key = Keys.trackUsername(service.id) title = context.getString(service.nameRes()) iconRes = service.getLogo() iconColor = service.getLogoColor() onClick { if (service.isLogged()) { val dialog = TrackLogoutDialog(service) dialog.targetController = this@SettingsTrackingController dialog.showDialog(router) } else { login() } } }, ) } override fun onActivityResumed(activity: Activity) { super.onActivityResumed(activity) updatePreference(trackManager.myAnimeList.id) updatePreference(trackManager.aniList.id) } private fun updatePreference(id: Int) { val pref = findPreference(Keys.trackUsername(id)) as? TrackerPreference pref?.notifyChanged() } override fun trackLoginDialogClosed(service: TrackService) { updatePreference(service.id) } override fun trackLogoutDialogClosed(service: TrackService) { updatePreference(service.id) } }
94
Kotlin
98
2,261
3e0f16dd125e6d173e29defa7fcb62410358239d
12,282
Neko
Apache License 2.0
app/src/main/java/br/com/alura/orgs/dao/ProdutosDao.kt
MizaelJR17
726,590,276
false
null
package br.com.alura.orgs.dao import br.com.alura.orgs.model.Produto class ProdutosDao { fun adiciona(produto: Produto){ produtos.add(produto) } fun buscaTodos() : List<Produto>{ return produtos.toList() } companion object { private val produtos = mutableListOf<Produto>() } }
0
null
0
1
ea27775abd79197b28960b0328d28a560367aa5e
331
Orgs
MIT License
amazon-chime-sdk/src/main/java/com/amazonaws/services/chime/sdk/meetings/internal/video/gl/DefaultEglRenderer.kt
aws
249,543,698
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.amazonaws.services.chime.sdk.meetings.internal.video.gl import android.graphics.Matrix import android.graphics.SurfaceTexture import android.opengl.EGL14 import android.opengl.GLES20 import android.os.Handler import android.os.HandlerThread import android.view.Surface import com.amazonaws.services.chime.sdk.meetings.audiovideo.video.VideoFrame import com.amazonaws.services.chime.sdk.meetings.audiovideo.video.gl.EglCore import com.amazonaws.services.chime.sdk.meetings.audiovideo.video.gl.EglCoreFactory import com.amazonaws.services.chime.sdk.meetings.utils.logger.Logger import kotlinx.coroutines.android.asCoroutineDispatcher import kotlinx.coroutines.runBlocking /** * [DefaultEglRenderer] uses EGL14 to support all functions in [EglRenderer]. It uses a single frame queue to render * [VideoFrame] objects passed to it. */ class DefaultEglRenderer(private val logger: Logger) : EglRenderer { // EGL and GL resources for drawing YUV/OES textures. After initialization, these are only // accessed from the render thread. These are reused within init/release cycles. private var eglCore: EglCore? = null private var surface: Any? = null // This handler is protected from onVideoFrameReceived calls during init and release cycles // by being synchronized on [ShareEglLock.Lock] private var renderHandler: Handler? = null // Cached matrix for draw command private val drawMatrix: Matrix = Matrix() // Pending frame to render. Serves as a queue with size 1. Synchronized on [ShareEglLock.Lock]. private var pendingFrame: VideoFrame? = null // If true, mirrors the video stream horizontally. Publicly accessible override var mirror = false // Synchronized on itself, as it may be modified when there renderHandler // is or is not running override var aspectRatio = 0f set(value) { synchronized(ShareEglLock.Lock) { logger.info(TAG, "Setting aspect ratio from $field to $value") field = value } } private var frameDrawer = DefaultGlVideoFrameDrawer() private val TAG = "DefaultEglRenderer" override fun init(eglCoreFactory: EglCoreFactory) { logger.info(TAG, "Initializing EGL renderer") if (renderHandler != null) { logger.warn(TAG, "Already initialized") return } val thread = HandlerThread("EglRenderer") thread.start() this.renderHandler = Handler(thread.looper) val validRenderHandler = renderHandler ?: throw UnknownError("No handler in init") runBlocking(validRenderHandler.asCoroutineDispatcher().immediate) { eglCore = eglCoreFactory.createEglCore() surface?.let { logger.info(TAG, "View already has surface, triggering EGL surface creation") createEglSurface(it) } } } override fun release() { logger.info(TAG, "Releasing EGL renderer") val validRenderHandler = renderHandler ?: run { logger.warn(TAG, "Already released") return } runBlocking(validRenderHandler.asCoroutineDispatcher().immediate) { eglCore?.release() eglCore = null } synchronized(ShareEglLock.Lock) { pendingFrame?.release() pendingFrame = null // Protect this within lock since onVideoFrameReceived can // occur from any frame validRenderHandler.looper.quitSafely() renderHandler = null } } override fun createEglSurface(inputSurface: Any) { check(inputSurface is SurfaceTexture || inputSurface is Surface) { "Surface must be SurfaceTexture or Surface" } surface = inputSurface renderHandler?.post { logger.info(TAG, "Request on handler thread to create EGL surface from input surface $surface") if (eglCore != null && eglCore?.eglSurface == EGL14.EGL_NO_SURFACE && surface != null) { val surfaceAttributess = intArrayOf(EGL14.EGL_NONE) eglCore?.eglSurface = EGL14.eglCreateWindowSurface( eglCore?.eglDisplay, eglCore?.eglConfig, surface, surfaceAttributess, 0 ) EGL14.eglMakeCurrent( eglCore?.eglDisplay, eglCore?.eglSurface, eglCore?.eglSurface, eglCore?.eglContext ) // Necessary for YUV frames with odd width. GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1) } // Discard any old frame synchronized(ShareEglLock.Lock) { pendingFrame?.release() pendingFrame = null } } } override fun releaseEglSurface() { surface = null // Can occur outside of init/release cycle val validRenderHandler = this.renderHandler ?: return runBlocking(validRenderHandler.asCoroutineDispatcher().immediate) { logger.info(TAG, "Releasing EGL surface") // Release frame drawer while we have a valid current context frameDrawer.release() EGL14.eglMakeCurrent( eglCore?.eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT ) EGL14.eglDestroySurface(eglCore?.eglDisplay, eglCore?.eglSurface) eglCore?.eglSurface = EGL14.EGL_NO_SURFACE } } override fun onVideoFrameReceived(frame: VideoFrame) { // Set pending frame from this thread and trigger a request to render synchronized(ShareEglLock.Lock) { // Release any current frame before setting to the latest if (pendingFrame != null) { pendingFrame?.release() } if (renderHandler != null) { pendingFrame = frame pendingFrame?.retain() renderHandler?.post(::renderPendingFrame) } else { logger.warn(TAG, "Skipping frame render request, no render handler thread") } } } private fun renderPendingFrame() { if (eglCore == null) { // May have been called after release logger.warn(TAG, "Skipping frame render, no EGL core") return } if (eglCore?.eglSurface == EGL14.EGL_NO_SURFACE) { // Verbose since this happens normally when running in background or when view is updating logger.verbose(TAG, "Skipping frame render, no EGL surface") return } // Fetch pending frame var frame: VideoFrame synchronized(ShareEglLock.Lock) { if (pendingFrame == null) { logger.verbose(TAG, "Skipping frame render, no pending frame to render") return } frame = pendingFrame as VideoFrame pendingFrame = null // Setup draw matrix transformations val frameAspectRatio = frame.getRotatedWidth().toFloat() / frame.getRotatedHeight() var drawnAspectRatio = frameAspectRatio synchronized(aspectRatio) { if (aspectRatio != 0f) { drawnAspectRatio = aspectRatio } } val scaleX: Float val scaleY: Float if (frameAspectRatio > drawnAspectRatio) { scaleX = drawnAspectRatio / frameAspectRatio scaleY = 1f } else { scaleX = 1f scaleY = frameAspectRatio / drawnAspectRatio } drawMatrix.reset() drawMatrix.preTranslate(0.5f, 0.5f) drawMatrix.preScale(if (mirror) -1f else 1f, 1f) drawMatrix.preScale(scaleX, scaleY) drawMatrix.preTranslate(-0.5f, -0.5f) // Get current surface size so we can set viewport correctly val widthArray = IntArray(1) EGL14.eglQuerySurface( eglCore?.eglDisplay, eglCore?.eglSurface, EGL14.EGL_WIDTH, widthArray, 0 ) val heightArray = IntArray(1) EGL14.eglQuerySurface( eglCore?.eglDisplay, eglCore?.eglSurface, EGL14.EGL_HEIGHT, heightArray, 0 ) try { // Draw frame and swap buffers, which will make it visible frameDrawer.drawFrame(frame, 0, 0, widthArray[0], heightArray[0], drawMatrix) EGL14.eglSwapBuffers(eglCore?.eglDisplay, eglCore?.eglSurface) } catch (e: Throwable) { logger.verbose(TAG, "Failed to draw frame, ignore...") } frame.release() } } }
33
null
53
99
eb9110d7d34a1a24d8e8162efa0ae1a094c421fd
9,059
amazon-chime-sdk-android
Apache License 2.0
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListMeasureResult.kt
androidx
256,589,781
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lazy import androidx.compose.foundation.gestures.Orientation import androidx.compose.ui.layout.MeasureResult import androidx.compose.ui.unit.IntSize import androidx.compose.ui.util.fastFirst import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastLastOrNull /** * The result of the measure pass for lazy list layout. */ internal class LazyListMeasureResult( // properties defining the scroll position: /** The new first visible item.*/ val firstVisibleItem: LazyListMeasuredItem?, /** The new value for [LazyListState.firstVisibleItemScrollOffset].*/ var firstVisibleItemScrollOffset: Int, /** True if there is some space available to continue scrolling in the forward direction.*/ val canScrollForward: Boolean, /** The amount of scroll consumed during the measure pass.*/ var consumedScroll: Float, /** MeasureResult defining the layout.*/ measureResult: MeasureResult, /** The amount of scroll-back that happened due to reaching the end of the list. */ val scrollBackAmount: Float, /** True when extra remeasure is required. */ val remeasureNeeded: Boolean, // properties representing the info needed for LazyListLayoutInfo: /** see [LazyListLayoutInfo.visibleItemsInfo] */ override val visibleItemsInfo: List<LazyListMeasuredItem>, /** see [LazyListLayoutInfo.viewportStartOffset] */ override val viewportStartOffset: Int, /** see [LazyListLayoutInfo.viewportEndOffset] */ override val viewportEndOffset: Int, /** see [LazyListLayoutInfo.totalItemsCount] */ override val totalItemsCount: Int, /** see [LazyListLayoutInfo.reverseLayout] */ override val reverseLayout: Boolean, /** see [LazyListLayoutInfo.orientation] */ override val orientation: Orientation, /** see [LazyListLayoutInfo.afterContentPadding] */ override val afterContentPadding: Int, /** see [LazyListLayoutInfo.mainAxisItemSpacing] */ override val mainAxisItemSpacing: Int ) : LazyListLayoutInfo, MeasureResult by measureResult { val canScrollBackward = (firstVisibleItem?.index ?: 0) != 0 || firstVisibleItemScrollOffset != 0 override val viewportSize: IntSize get() = IntSize(width, height) override val beforeContentPadding: Int get() = -viewportStartOffset /** * Tries to apply a scroll [delta] for this layout info. In some cases we can apply small * scroll deltas by just changing the offsets for each [visibleItemsInfo]. * But we can only do so if after applying the delta we would not need to compose a new item * or dispose an item which is currently visible. In this case this function will not apply * the [delta] and return false. * * @return true if we can safely apply a passed scroll [delta] to this layout info. * If true is returned, only the placement phase is needed to apply new offsets. * If false is returned, it means we have to rerun the full measure phase to apply the [delta]. */ fun tryToApplyScrollWithoutRemeasure(delta: Int): Boolean { if (remeasureNeeded || visibleItemsInfo.isEmpty() || firstVisibleItem == null || // applying this delta will change firstVisibleItem (firstVisibleItemScrollOffset - delta) !in 0 until firstVisibleItem.sizeWithSpacings ) { return false } val first = visibleItemsInfo.fastFirst { !it.nonScrollableItem } val last = visibleItemsInfo.fastLastOrNull { !it.nonScrollableItem }!! val canApply = if (delta < 0) { // scrolling forward val deltaToFirstItemChange = first.offset + first.sizeWithSpacings - viewportStartOffset val deltaToLastItemChange = last.offset + last.sizeWithSpacings - viewportEndOffset minOf(deltaToFirstItemChange, deltaToLastItemChange) > -delta } else { // scrolling backward val deltaToFirstItemChange = viewportStartOffset - first.offset val deltaToLastItemChange = viewportEndOffset - last.offset minOf(deltaToFirstItemChange, deltaToLastItemChange) > delta } return if (canApply) { firstVisibleItemScrollOffset -= delta visibleItemsInfo.fastForEach { it.applyScrollDelta(delta) } consumedScroll = delta.toFloat() true } else { false } } }
28
null
946
5,135
3669da61ebe3541ddfab37143d5067aa19789300
5,162
androidx
Apache License 2.0
example/android/app/src/main/kotlin/com/appsah/example/MainActivity.kt
ShrJamal
344,963,049
false
{"Dart": 53856, "HTML": 1503, "Swift": 1158, "Kotlin": 123, "Objective-C": 38}
package com.appsah.example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
9ac8723ae663fc6d744245bf2c5fd788ec8d51ca
123
flutter_countries_picker
MIT License
face-detect/src/main/java/soup/nolan/detect/face/internal/VisionImage.kt
NolanApp
197,888,252
false
null
package soup.nolan.detect.face.internal import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata import soup.nolan.detect.face.model.RawImage object VisionImage { fun from(rawImage: RawImage): FirebaseVisionImage { return FirebaseVisionImage.fromMediaImage( rawImage.image, rawImage.rotation() ) } private fun RawImage.rotation(): Int { return when (rotationDegrees) { 0 -> FirebaseVisionImageMetadata.ROTATION_0 90 -> FirebaseVisionImageMetadata.ROTATION_90 180 -> FirebaseVisionImageMetadata.ROTATION_180 270 -> FirebaseVisionImageMetadata.ROTATION_270 else -> FirebaseVisionImageMetadata.ROTATION_0 } } }
1
Kotlin
2
9
1c7d166034e19ca5774cab43d14a425fdc6fe03e
823
Nolan-Android
Apache License 2.0
kt/godot-library/src/main/kotlin/godot/gen/godot/VisualShaderNodeVec3Uniform.kt
utopia-rise
289,462,532
false
null
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE") package godot import godot.`annotation`.CoreTypeHelper import godot.`annotation`.GodotBaseType import godot.core.TransferContext import godot.core.VariantType.BOOL import godot.core.VariantType.NIL import godot.core.VariantType.VECTOR3 import godot.core.Vector3 import kotlin.Boolean import kotlin.Suppress import kotlin.Unit /** * A [godot.core.Vector3] uniform to be used within the visual shader graph. * * Translated to `uniform vec3` in the shader language. */ @GodotBaseType public open class VisualShaderNodeVec3Uniform : VisualShaderNodeUniform() { /** * A default value to be assigned within the shader. */ public open var defaultValue: Vector3 get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODEVEC3UNIFORM_GET_DEFAULT_VALUE, VECTOR3) return TransferContext.readReturnValue(VECTOR3, false) as Vector3 } set(`value`) { TransferContext.writeArguments(VECTOR3 to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODEVEC3UNIFORM_SET_DEFAULT_VALUE, NIL) } /** * Enables usage of the [defaultValue]. */ public open var defaultValueEnabled: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODEVEC3UNIFORM_GET_DEFAULT_VALUE_ENABLED, BOOL) return TransferContext.readReturnValue(BOOL, false) as Boolean } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_VISUALSHADERNODEVEC3UNIFORM_SET_DEFAULT_VALUE_ENABLED, NIL) } public override fun __new(): Unit { callConstructor(ENGINECLASS_VISUALSHADERNODEVEC3UNIFORM) } @CoreTypeHelper public open fun defaultValue(schedule: Vector3.() -> Unit): Vector3 = defaultValue.apply{ schedule(this) defaultValue = this } }
47
Kotlin
25
301
0d33ac361b354b26c31bb36c7f434e6455583738
2,264
godot-kotlin-jvm
MIT License
app/src/main/java/com/firbasedbdemo/api/APIService.kt
SinoKD
146,429,241
false
null
package com.firbasedbdemo.api import com.firbasedbdemo.constants.AppConstants.APIConstants.BASE_URL import com.firbasedbdemo.constants.AppConstants.APIConstants.TIME_OUT import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit class APIService { companion object { private lateinit var retrofit: Retrofit private var apiInterface: APIInterface? = null private fun getClient(): Retrofit { val okHttpClient: OkHttpClient = OkHttpClient().newBuilder() .connectTimeout(TIME_OUT, TimeUnit.MILLISECONDS) .readTimeout(TIME_OUT, TimeUnit.MILLISECONDS) .build() retrofit = Retrofit.Builder().baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(okHttpClient) .build() return retrofit } fun getAPIInterface(): APIInterface { if (apiInterface == null) apiInterface = getClient().create(APIInterface::class.java) return apiInterface!! } } }
0
Kotlin
0
0
475ddc7558fff711341eb013163f229613a3c411
1,357
Firebase-Real-Database-Dagger2-Retrofit-Rxjava-Kotlin
Apache License 2.0
packages/mongodb-linting-engine/src/test/kotlin/com/mongodb/jbplugin/linting/FieldCheckingLinterTest.kt
mongodb-js
797,134,624
false
{"Kotlin": 875749, "Java": 4035, "Shell": 1673, "HTML": 254}
package com.mongodb.jbplugin.linting import com.mongodb.jbplugin.accessadapter.MongoDbReadModelProvider import com.mongodb.jbplugin.accessadapter.slice.GetCollectionSchema import com.mongodb.jbplugin.mql.* import com.mongodb.jbplugin.mql.components.HasChildren import com.mongodb.jbplugin.mql.components.HasCollectionReference import com.mongodb.jbplugin.mql.components.HasFieldReference import com.mongodb.jbplugin.mql.components.HasValueReference import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertInstanceOf import org.junit.jupiter.api.Test import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import org.mockito.kotlin.any class FieldCheckingLinterTest { @Test fun `warns about a referenced field not in the specified collection`() { val readModelProvider = mock<MongoDbReadModelProvider<Unit>>() val collectionNamespace = Namespace("database", "collection") `when`(readModelProvider.slice(any(), any<GetCollectionSchema.Slice>())).thenReturn( GetCollectionSchema( CollectionSchema( collectionNamespace, BsonObject( mapOf( "myString" to BsonString, "myInt" to BsonInt32, ), ), ), ), ) val result = FieldCheckingLinter.lintQuery( Unit, readModelProvider, Node( null, listOf( HasCollectionReference(HasCollectionReference.Known(null, null, collectionNamespace)), HasChildren( listOf( Node(null, listOf(HasFieldReference(HasFieldReference.Known(null, "myString")))), Node(null, listOf(HasFieldReference(HasFieldReference.Known(null, "myBoolean")))), ), ), ), ), ) assertEquals(1, result.warnings.size) assertInstanceOf(FieldCheckWarning.FieldDoesNotExist::class.java, result.warnings[0]) val warning = result.warnings[0] as FieldCheckWarning.FieldDoesNotExist assertEquals("myBoolean", warning.field) } @Test fun `warns about a referenced field not in the specified collection (alongside a value reference)`() { val readModelProvider = mock<MongoDbReadModelProvider<Unit>>() val collectionNamespace = Namespace("database", "collection") `when`(readModelProvider.slice(any(), any<GetCollectionSchema.Slice>())).thenReturn( GetCollectionSchema( CollectionSchema( collectionNamespace, BsonObject( mapOf( "myString" to BsonString, "myInt" to BsonInt32, ), ), ), ), ) val result = FieldCheckingLinter.lintQuery( Unit, readModelProvider, Node( null, listOf( HasCollectionReference(HasCollectionReference.Known(null, null, collectionNamespace)), HasChildren( listOf( Node(null, listOf(HasFieldReference(HasFieldReference.Known(null, "myString")))), Node( null, listOf( HasFieldReference( HasFieldReference.Known(null, "myBoolean") ), HasValueReference( HasValueReference.Constant(null, true, BsonBoolean) ) ) ), ), ), ), ), ) assertEquals(1, result.warnings.size) assertInstanceOf(FieldCheckWarning.FieldDoesNotExist::class.java, result.warnings[0]) val warning = result.warnings[0] as FieldCheckWarning.FieldDoesNotExist assertEquals("myBoolean", warning.field) } @Test fun `warns about a value not matching the type of underlying field`() { val readModelProvider = mock<MongoDbReadModelProvider<Unit>>() val collectionNamespace = Namespace("database", "collection") `when`(readModelProvider.slice(any(), any<GetCollectionSchema.Slice>())).thenReturn( GetCollectionSchema( CollectionSchema( collectionNamespace, BsonObject( mapOf( "myString" to BsonString, "myInt" to BsonInt32, ), ), ), ), ) val result = FieldCheckingLinter.lintQuery( Unit, readModelProvider, Node( null, listOf( HasCollectionReference(HasCollectionReference.Known(null, null, collectionNamespace)), HasChildren( listOf( Node( null, listOf( HasFieldReference( HasFieldReference.Known(null, "myInt") ), HasValueReference( HasValueReference.Constant(null, null, BsonNull) ) ) ), ), ), ), ), ) assertEquals(1, result.warnings.size) assertInstanceOf(FieldCheckWarning.FieldValueTypeMismatch::class.java, result.warnings[0]) val warning = result.warnings[0] as FieldCheckWarning.FieldValueTypeMismatch assertEquals("myInt", warning.field) } }
2
Kotlin
0
4
b22403a93e5acb4c7d22383efd9d5bb2545369a5
6,581
intellij
Apache License 2.0
payments-core/src/main/java/com/stripe/android/model/parsers/DeferredSetupIntentJsonParser.kt
stripe
6,926,049
false
null
package com.stripe.android.model.parsers import androidx.annotation.RestrictTo import com.stripe.android.core.model.StripeJsonUtils.optString import com.stripe.android.core.model.parsers.ModelJsonParser import com.stripe.android.core.model.parsers.ModelJsonParser.Companion.jsonArrayToList import com.stripe.android.model.DeferredIntentParams import com.stripe.android.model.SetupIntent import org.json.JSONObject @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class DeferredSetupIntentJsonParser( private val elementsSessionId: String?, private val setupMode: DeferredIntentParams.Mode.Setup, private val apiKey: String, private val timeProvider: () -> Long ) : ModelJsonParser<SetupIntent> { override fun parse(json: JSONObject): SetupIntent { val paymentMethodTypes = jsonArrayToList( json.optJSONArray(FIELD_PAYMENT_METHOD_TYPES) ) val unactivatedPaymentMethods = jsonArrayToList( json.optJSONArray(FIELD_UNACTIVATED_PAYMENT_METHOD_TYPES) ) val linkFundingSources = jsonArrayToList(json.optJSONArray(FIELD_LINK_FUNDING_SOURCES)) .map { it.lowercase() } val countryCode = optString(json, FIELD_COUNTRY_CODE) return SetupIntent( id = elementsSessionId, cancellationReason = null, description = null, clientSecret = null, paymentMethodTypes = paymentMethodTypes, countryCode = countryCode, linkFundingSources = linkFundingSources, unactivatedPaymentMethods = unactivatedPaymentMethods, isLiveMode = apiKey.contains("live"), nextActionData = null, paymentMethodId = null, created = timeProvider(), status = null, usage = setupMode.setupFutureUsage, ) } private companion object { private const val FIELD_COUNTRY_CODE = "country_code" private const val FIELD_PAYMENT_METHOD_TYPES = "payment_method_types" private const val FIELD_UNACTIVATED_PAYMENT_METHOD_TYPES = "unactivated_payment_method_types" private const val FIELD_LINK_FUNDING_SOURCES = "link_funding_sources" } }
96
null
644
1,277
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
2,208
stripe-android
MIT License
downloader-lib/src/main/kotlin/dfialho/tveebot/downloader/libtorrent/ThreadSafeDownloadEngine.kt
dfialho
132,515,212
false
null
package dfialho.tveebot.downloader.libtorrent import dfialho.tveebot.downloader.api.Download import dfialho.tveebot.downloader.api.DownloadEngine import dfialho.tveebot.downloader.api.DownloadListener import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write /** * Download engine tha t ensure thread-safeness for each individual method. */ private class ThreadSafeDownloadEngine(private val engine: DownloadEngine) : DownloadEngine { /** * Lock to manage access to [engine]. */ private val lock = ReentrantReadWriteLock() override fun start() = lock.write { engine.start() } override fun stop() = lock.write { engine.stop() } override fun add(magnetLink: String): Download = lock.write { engine.add(magnetLink) } override fun getDownloads(): List<Download> = lock.read { engine.getDownloads() } override fun addListener(listener: DownloadListener) = lock.write { engine.addListener(listener) } override fun removeListener(listener: DownloadListener) = lock.write { engine.removeListener(listener) } } /** * Returns a thread-safe version of the [DownloadEngine] obtained from [supplier]. */ fun <T : DownloadEngine> threadSafe(supplier: () -> T): DownloadEngine { return ThreadSafeDownloadEngine(supplier()) }
3
Kotlin
0
0
9423027242154b4b199befcf4d8ee5f909861cb3
1,402
tveebot
MIT License
app/src/main/java/com/vitorpamplona/amethyst/model/Channel.kt
vitorpamplona
587,850,619
false
null
package com.vitorpamplona.amethyst.model import androidx.compose.runtime.Stable import androidx.lifecycle.LiveData import com.vitorpamplona.amethyst.service.NostrSingleChannelDataSource import com.vitorpamplona.amethyst.service.checkNotInMainThread import com.vitorpamplona.amethyst.service.model.ATag import com.vitorpamplona.amethyst.service.model.ChannelCreateEvent import com.vitorpamplona.amethyst.service.model.LiveActivitiesEvent import com.vitorpamplona.amethyst.service.toNote import com.vitorpamplona.amethyst.ui.components.BundledUpdate import com.vitorpamplona.amethyst.ui.note.toShortenHex import fr.acinq.secp256k1.Hex import kotlinx.coroutines.Dispatchers import java.util.concurrent.ConcurrentHashMap @Stable class PublicChatChannel(idHex: String) : Channel(idHex) { var info = ChannelCreateEvent.ChannelData(null, null, null) fun updateChannelInfo(creator: User, channelInfo: ChannelCreateEvent.ChannelData, updatedAt: Long) { this.creator = creator this.info = channelInfo this.updatedMetadataAt = updatedAt live.invalidateData() } override fun toBestDisplayName(): String { return info.name ?: super.toBestDisplayName() } override fun summary(): String? { return info.about } override fun profilePicture(): String? { if (info.picture.isNullOrBlank()) return super.profilePicture() return info.picture ?: super.profilePicture() } override fun anyNameStartsWith(prefix: String): Boolean { return listOfNotNull(info.name, info.about) .filter { it.contains(prefix, true) }.isNotEmpty() } } @Stable class LiveActivitiesChannel(val address: ATag) : Channel(address.toTag()) { var info: LiveActivitiesEvent? = null override fun idNote() = address.toNAddr() override fun idDisplayNote() = idNote().toShortenHex() fun address() = address fun updateChannelInfo(creator: User, channelInfo: LiveActivitiesEvent, updatedAt: Long) { this.info = channelInfo super.updateChannelInfo(creator, updatedAt) } override fun toBestDisplayName(): String { return info?.title() ?: super.toBestDisplayName() } override fun summary(): String? { return info?.summary() } override fun profilePicture(): String? { return info?.image()?.ifBlank { null } } override fun anyNameStartsWith(prefix: String): Boolean { return listOfNotNull(info?.title(), info?.summary()) .filter { it.contains(prefix, true) }.isNotEmpty() } } @Stable abstract class Channel(val idHex: String) { var creator: User? = null var updatedMetadataAt: Long = 0 val notes = ConcurrentHashMap<HexKey, Note>() open fun id() = Hex.decode(idHex) open fun idNote() = id().toNote() open fun idDisplayNote() = idNote().toShortenHex() open fun toBestDisplayName(): String { return idDisplayNote() } open fun summary(): String? { return null } open fun creatorName(): String? { return creator?.toBestDisplayName() } open fun profilePicture(): String? { return creator?.profilePicture() } open fun updateChannelInfo(creator: User, updatedAt: Long) { this.creator = creator this.updatedMetadataAt = updatedAt live.invalidateData() } fun addNote(note: Note) { notes[note.idHex] = note } fun removeNote(note: Note) { notes.remove(note.idHex) } fun removeNote(noteHex: String) { notes.remove(noteHex) } abstract fun anyNameStartsWith(prefix: String): Boolean // Observers line up here. val live: ChannelLiveData = ChannelLiveData(this) fun pruneOldAndHiddenMessages(account: Account): Set<Note> { val important = notes.values .filter { it.author?.let { it1 -> account.isHidden(it1) } == false } .sortedWith(compareBy({ it.createdAt() }, { it.idHex })) .reversed() .take(1000) .toSet() val toBeRemoved = notes.values.filter { it !in important }.toSet() toBeRemoved.forEach { notes.remove(it.idHex) } return toBeRemoved } } class ChannelLiveData(val channel: Channel) : LiveData<ChannelState>(ChannelState(channel)) { // Refreshes observers in batches. private val bundler = BundledUpdate(300, Dispatchers.IO) fun invalidateData() { checkNotInMainThread() bundler.invalidate() { checkNotInMainThread() if (hasActiveObservers()) { postValue(ChannelState(channel)) } } } override fun onActive() { super.onActive() if (channel is PublicChatChannel) { NostrSingleChannelDataSource.add(channel.idHex) } else { NostrSingleChannelDataSource.add(channel.idHex) } } override fun onInactive() { super.onInactive() if (channel is PublicChatChannel) { NostrSingleChannelDataSource.remove(channel.idHex) } else { NostrSingleChannelDataSource.remove(channel.idHex) } } } class ChannelState(val channel: Channel)
157
null
141
981
2de3d19a34b97c012e39b203070d9c1c0b1f0520
5,244
amethyst
MIT License
src/main/kotlin/org/lm/LmIcons.kt
mchernyavsky
112,193,727
false
null
package org.lm import com.intellij.icons.AllIcons import javax.swing.Icon object LmIcons { val LM_FILE: Icon = AllIcons.FileTypes.Idl }
0
Kotlin
0
0
a09526cec7d16ef34cd526f7069c6de0b669a56d
142
intellij-lm
MIT License
app/src/main/java/net/voussoir/trkpt/MapFragment.kt
voussoir
616,275,924
false
{"Kotlin": 198945, "Python": 2538}
/* * MapFragment.kt * Implements the MapFragment fragment * A MapFragment displays a map using osmdroid as well as the controls to start / stop a recording * * This file is part of * TRACKBOOK - Movement Recorder for Android * * Copyright (c) 2016-22 - Y20K.org * Licensed under the MIT-License * http://opensource.org/licenses/MIT * * Trackbook uses osmdroid - OpenStreetMap-Tools for Android * https://github.com/osmdroid/osmdroid */ /* * Modified by voussoir for trkpt, forked from Trackbook. */ package net.voussoir.trkpt import android.Manifest import android.app.Dialog import android.content.* import android.content.pm.PackageManager import android.graphics.Color import android.graphics.drawable.Drawable import android.location.Location import android.os.* import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.* import androidx.activity.result.contract.ActivityResultContracts.RequestPermission import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.fragment.app.Fragment import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import org.osmdroid.events.MapEventsReceiver import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.views.MapView import org.osmdroid.views.overlay.ItemizedIconOverlay import org.osmdroid.views.overlay.MapEventsOverlay import org.osmdroid.views.overlay.Overlay import org.osmdroid.views.overlay.OverlayItem import org.osmdroid.views.overlay.Polygon import org.osmdroid.views.overlay.Polyline import org.osmdroid.views.overlay.TilesOverlay import net.voussoir.trkpt.helpers.* class MapFragment : Fragment() { private lateinit var trackbook: Trackbook private var bound: Boolean = false val handler: Handler = Handler(Looper.getMainLooper()) var continuous_auto_center: Boolean = true private var trackerService: TrackerService? = null private lateinit var database_changed_listener: DatabaseChangedListener var show_debug: Boolean = false var thismapfragment: MapFragment? = null lateinit var rootView: View private lateinit var mapView: MapView lateinit var mainButton: ExtendedFloatingActionButton lateinit var zoom_in_button: FloatingActionButton lateinit var zoom_out_button: FloatingActionButton lateinit var currentLocationButton: FloatingActionButton lateinit var map_current_time: TextView private var current_track_overlay: Polyline? = null private var current_position_overlays = ArrayList<Overlay>() private var homepoints_overlays = ArrayList<Overlay>() private lateinit var locationErrorBar: Snackbar /* Overrides onCreate from Fragment */ override fun onCreate(savedInstanceState: Bundle?) { Log.i("VOUSSOIR", "MapFragment.onCreate") super.onCreate(savedInstanceState) thismapfragment = this this.trackbook = (requireContext().applicationContext as Trackbook) database_changed_listener = object: DatabaseChangedListener { override fun database_changed() { Log.i("VOUSSOIR", "MapFragment database_ready_changed to ${trackbook.database.ready}") if (trackbook.database.ready) { create_homepoint_overlays() } else { clear_homepoint_overlays() } update_main_button() } } } /* Overrides onStop from Fragment */ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { Log.i("VOUSSOIR", "MapFragment.onCreateView") rootView = inflater.inflate(R.layout.fragment_map, container, false) mapView = rootView.findViewById(R.id.map) currentLocationButton = rootView.findViewById(R.id.location_button) zoom_in_button = rootView.findViewById(R.id.zoom_in_button) zoom_out_button = rootView.findViewById(R.id.zoom_out_button) map_current_time = rootView.findViewById(R.id.map_current_time) mainButton = rootView.findViewById(R.id.main_button) locationErrorBar = Snackbar.make(mapView, String(), Snackbar.LENGTH_INDEFINITE) mapView.setOnLongClickListener{ Log.i("VOUSSOIR", "mapview longpress") true } mapView.isLongClickable = true mapView.isTilesScaledToDpi = true mapView.isVerticalMapRepetitionEnabled = false mapView.setTileSource(TileSourceFactory.MAPNIK) mapView.setMultiTouchControls(true) mapView.zoomController.setVisibility(org.osmdroid.views.CustomZoomButtonsController.Visibility.NEVER) mapView.controller.setZoom(Keys.DEFAULT_ZOOM_LEVEL) if (AppThemeHelper.isDarkModeOn(requireActivity())) { mapView.overlayManager.tilesOverlay.setColorFilter(TilesOverlay.INVERT_COLORS) } val receiver: MapEventsReceiver = object: MapEventsReceiver { override fun singleTapConfirmedHelper(p: GeoPoint?): Boolean { return true } override fun longPressHelper(point: GeoPoint): Boolean { Log.i("VOUSSOIR", "MapFragment MapEventsReceiver.longPressHelper") val dialog = Dialog(activity as Context) dialog.setContentView(R.layout.dialog_homepoint) dialog.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) dialog.setTitle("Homepoint") (dialog.findViewById(R.id.homepoint_dialog_title) as TextView).text = "Add a homepoint" val name_input: EditText = dialog.findViewById(R.id.homepoint_name_input) val radius_input: EditText = dialog.findViewById(R.id.homepoint_radius_input) val cancel_button: Button = dialog.findViewById(R.id.homepoint_delete_cancel_button) val save_button: Button = dialog.findViewById(R.id.homepoint_save_button) cancel_button.text = "Cancel" cancel_button.setOnClickListener { dialog.cancel() } save_button.setOnClickListener { val radius = radius_input.text.toString().toDoubleOrNull() ?: 25.0 trackbook.database.insert_homepoint( id=random_long(), name=name_input.text.toString(), latitude=point.latitude, longitude=point.longitude, radius=radius, commit=true, ) trackbook.load_homepoints() create_homepoint_overlays() dialog.dismiss() } dialog.show() return true } } mapView.overlays.add(MapEventsOverlay(receiver)) trackbook.load_homepoints() create_homepoint_overlays() if (database_changed_listener !in trackbook.database_changed_listeners) { trackbook.database_changed_listeners.add(database_changed_listener) } centerMap(getLastKnownLocation(requireContext())) current_track_overlay = null mapView.setOnTouchListener { v, event -> continuous_auto_center = false false } mainButton.setOnClickListener { val tracker = trackerService if (tracker == null) { return@setOnClickListener } if (tracker.tracking_state != Keys.STATE_STOP && tracker.tracking_state != Keys.STATE_MAPVIEW) { tracker.state_mapview() } else { startTracking() } handler.postDelayed(redraw_runnable, 0) } currentLocationButton.setOnClickListener { val tracker = trackerService if (tracker == null) { return@setOnClickListener } centerMap(tracker.currentBestLocation) } zoom_in_button.setOnClickListener { mapView.controller.setZoom(mapView.zoomLevelDouble + 0.5) } zoom_out_button.setOnClickListener { mapView.controller.setZoom(mapView.zoomLevelDouble - 0.5) } show_debug = PreferencesHelper.loadShowDebug() requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) handler.post(redraw_runnable) return rootView } /* Overrides onStart from Fragment */ override fun onStart() { Log.i("VOUSSOIR", "MapFragment.onStart") super.onStart() // request location permission if denied if (ContextCompat.checkSelfPermission(activity as Context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) { requestLocationPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION) } // bind to TrackerService activity?.bindService(Intent(activity, TrackerService::class.java), connection, Context.BIND_AUTO_CREATE) handler.post(redraw_runnable) } /* Overrides onResume from Fragment */ override fun onResume() { Log.i("VOUSSOIR", "MapFragment.onResume") super.onResume() handler.post(redraw_runnable) requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) // if (bound) { // trackerService.addGpsLocationListener() // trackerService.addNetworkLocationListener() // } } /* Overrides onPause from Fragment */ override fun onPause() { Log.i("VOUSSOIR", "MapFragment.onPause") super.onPause() requireActivity().window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) val tracker = trackerService if (tracker == null) { return } saveBestLocationState(tracker.currentBestLocation) if (bound && (tracker.tracking_state == Keys.STATE_MAPVIEW || tracker.tracking_state == Keys.STATE_STOP)) { tracker.remove_gps_location_listener() tracker.remove_network_location_listener() tracker.trackbook.database.commit() } handler.removeCallbacks(redraw_runnable) } /* Overrides onStop from Fragment */ override fun onStop() { super.onStop() // unbind from TrackerService if (bound) { activity?.unbindService(connection) handleServiceUnbind() } handler.removeCallbacks(redraw_runnable) } override fun onDestroyView() { Log.i("VOUSSOIR", "MapFragment.onDestroy") super.onDestroyView() if (database_changed_listener in trackbook.database_changed_listeners) { trackbook.database_changed_listeners.remove(database_changed_listener) } handler.removeCallbacks(redraw_runnable) } override fun onDestroy() { Log.i("VOUSSOIR", "MapFragment.onDestroy") super.onDestroy() requireActivity().window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) handler.removeCallbacks(redraw_runnable) } private val requestLocationPermissionLauncher = registerForActivityResult(RequestPermission()) { isGranted: Boolean -> if (isGranted) { // permission was granted - re-bind service activity?.unbindService(connection) activity?.bindService(Intent(activity, TrackerService::class.java), connection, Context.BIND_AUTO_CREATE) Log.i("VOUSSOIR", "Request result: Location permission has been granted.") } else { // permission denied - unbind service activity?.unbindService(connection) } val gpsProviderActive = if (trackerService == null) false else trackerService!!.gpsProviderActive val networkProviderActive = if (trackerService == null) false else trackerService!!.networkProviderActive toggleLocationErrorBar(gpsProviderActive, networkProviderActive) } private fun startTracking() { // start service via intent so that it keeps running after unbind val intent = Intent(activity, TrackerService::class.java) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // ... start service in foreground to prevent it being killed on Oreo activity?.startForegroundService(intent) } else { activity?.startService(intent) } if (trackerService != null) { trackerService!!.state_full_recording() } } /* Handles state when service is being unbound */ private fun handleServiceUnbind() { bound = false // unregister listener for changes in shared preferences PreferencesHelper.unregisterPreferenceChangeListener(sharedPreferenceChangeListener) } private val sharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key -> if (key == Keys.PREF_SHOW_DEBUG) { show_debug = sharedPreferences.getBoolean(Keys.PREF_SHOW_DEBUG, Keys.DEFAULT_SHOW_DEBUG) } redraw() } fun centerMap(location: Location) { val position = GeoPoint(location.latitude, location.longitude) mapView.controller.setCenter(position) continuous_auto_center = true } fun saveBestLocationState(currentBestLocation: Location) { PreferencesHelper.saveCurrentBestLocation(currentBestLocation) PreferencesHelper.saveZoomLevel(mapView.zoomLevelDouble) continuous_auto_center = true } fun clear_current_position_overlays() { for (ov in current_position_overlays) { if (ov in mapView.overlays) { mapView.overlays.remove(ov) } } current_position_overlays.clear() } /* Mark current position on map */ fun create_current_position_overlays() { clear_current_position_overlays() val tracker = trackerService if (tracker == null) { return } val locationIsOld: Boolean = !(isRecentEnough(tracker.currentBestLocation)) val newMarker: Drawable val fillcolor: Int val description: String if (tracker.tracking_state == Keys.STATE_DEAD) { fillcolor = Color.argb(64, 0, 0, 0) newMarker = ContextCompat.getDrawable(requireContext(), R.drawable.ic_skull_24dp)!! description = "GPS is struggling; disabled until movement" } else if (tracker.tracking_state == Keys.STATE_SLEEP) { fillcolor = Color.argb(64, 220, 61, 51) newMarker = ContextCompat.getDrawable(requireContext(), R.drawable.ic_sleep_24dp)!! description = "GPS sleeping until movement" } else if (locationIsOld) { fillcolor = Color.argb(64, 0, 0, 0) newMarker = ContextCompat.getDrawable(requireContext(), R.drawable.ic_marker_location_black_24dp)!! description = "GPS tracking at full power" } else if (tracker.tracking_state == Keys.STATE_FULL_RECORDING || tracker.tracking_state == Keys.STATE_ARRIVED_AT_HOME) { fillcolor = Color.argb(64, 220, 61, 51) newMarker = ContextCompat.getDrawable(requireContext(), R.drawable.ic_marker_location_red_24dp)!! description = "GPS tracking at full power" } else { fillcolor = Color.argb(64, 60, 152, 219) newMarker = ContextCompat.getDrawable(requireContext(), R.drawable.ic_marker_location_blue_24dp)!! description = "GPS tracking at full power" } val current_location_radius = Polygon() current_location_radius.points = Polygon.pointsAsCircle( GeoPoint(tracker.currentBestLocation.latitude, tracker.currentBestLocation.longitude), tracker.currentBestLocation.accuracy.toDouble() ) current_location_radius.fillPaint.color = fillcolor current_location_radius.outlinePaint.color = Color.argb(0, 0, 0, 0) current_position_overlays.add(current_location_radius) val overlayItems: java.util.ArrayList<OverlayItem> = java.util.ArrayList<OverlayItem>() val overlayItem: OverlayItem = createOverlayItem( tracker.currentBestLocation.latitude, tracker.currentBestLocation.longitude, title="Current location", description=description, ) overlayItem.setMarker(newMarker) overlayItems.add(overlayItem) current_position_overlays.add(createOverlay(requireContext(), overlayItems)) for (ov in current_position_overlays) { mapView.overlays.add(ov) } } fun clear_track_overlay() { mapView.overlays.remove(current_track_overlay) } fun create_track_overlay() { clear_track_overlay() val pl = Polyline(mapView) pl.outlinePaint.strokeWidth = Keys.POLYLINE_THICKNESS pl.outlinePaint.color = requireContext().getColor(R.color.fuchsia) pl.infoWindow = null mapView.overlays.add(pl) current_track_overlay = pl } fun clear_homepoint_overlays() { for (ov in homepoints_overlays) { if (ov in mapView.overlays) { mapView.overlays.remove(ov) } } homepoints_overlays.clear() } fun create_homepoint_overlays() { Log.i("VOUSSOIR", "MapFragmentLayoutHolder.createHomepointOverlays") val context = requireContext() val newMarker: Drawable = ContextCompat.getDrawable(context, R.drawable.ic_homepoint_24dp)!! clear_homepoint_overlays() for (homepoint in trackbook.homepoints) { val p = Polygon() p.points = Polygon.pointsAsCircle(GeoPoint(homepoint.location.latitude, homepoint.location.longitude), homepoint.location.accuracy.toDouble()) p.fillPaint.color = Color.argb(64, 255, 193, 7) p.outlinePaint.color = Color.argb(0, 0, 0, 0) homepoints_overlays.add(p) val overlayItems: java.util.ArrayList<OverlayItem> = java.util.ArrayList<OverlayItem>() val overlayItem: OverlayItem = createOverlayItem( homepoint.location.latitude, homepoint.location.longitude, title=homepoint.name, description="Radius ${homepoint.radius}" ) overlayItem.setMarker(newMarker) overlayItems.add(overlayItem) val homepoint_overlay = ItemizedIconOverlay<OverlayItem>(context, overlayItems, object : ItemizedIconOverlay.OnItemGestureListener<OverlayItem> { override fun onItemSingleTapUp(index: Int, item: OverlayItem): Boolean { return false } override fun onItemLongPress(index: Int, item: OverlayItem): Boolean { Log.i("VOUSSOIR", "MapFragment homepoint.longpress") val dialog = Dialog(activity as Context) dialog.setContentView(R.layout.dialog_homepoint) dialog.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) dialog.setTitle("Homepoint") (dialog.findViewById(R.id.homepoint_dialog_title) as TextView).text = "Edit homepoint" val name_input: EditText = dialog.findViewById(R.id.homepoint_name_input) name_input.setText(homepoint.name) val radius_input: EditText = dialog.findViewById(R.id.homepoint_radius_input) radius_input.setText(homepoint.radius.toString()) val delete_button: Button = dialog.findViewById(R.id.homepoint_delete_cancel_button) val save_button: Button = dialog.findViewById(R.id.homepoint_save_button) delete_button.text = "Delete" delete_button.setOnClickListener { trackbook.database.delete_homepoint(homepoint.id, commit=true) trackbook.load_homepoints() create_homepoint_overlays() dialog.dismiss() } save_button.setOnClickListener { val radius = radius_input.text.toString().toDoubleOrNull() ?: 25.0 trackbook.database.update_homepoint(homepoint.id, name=name_input.text.toString(), radius=radius, commit=true) trackbook.load_homepoints() create_homepoint_overlays() dialog.dismiss() } dialog.show() return true } } ) homepoints_overlays.add(homepoint_overlay) } for (ov in homepoints_overlays) { mapView.overlays.add(ov) } } fun update_main_button() { val tracker = trackerService mainButton.isEnabled = trackbook.database.ready currentLocationButton.isVisible = true if (! trackbook.database.ready) { mainButton.text = requireContext().getString(R.string.button_not_ready) mainButton.icon = null } else if (tracker == null || tracker.tracking_state == Keys.STATE_STOP || tracker.tracking_state == Keys.STATE_MAPVIEW) { mainButton.setIconResource(R.drawable.ic_fiber_manual_record_inactive_24dp) mainButton.text = requireContext().getString(R.string.button_start) mainButton.contentDescription = requireContext().getString(R.string.descr_button_start) } else { mainButton.setIconResource(R.drawable.ic_fiber_manual_stop_24dp) mainButton.text = requireContext().getString(R.string.button_pause) mainButton.contentDescription = requireContext().getString(R.string.descr_button_pause) } } fun toggleLocationErrorBar(gpsProviderActive: Boolean, networkProviderActive: Boolean) { if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) { // CASE: Location permission not granted locationErrorBar.setText(R.string.snackbar_message_location_permission_denied) if (!locationErrorBar.isShown) locationErrorBar.show() } else if (!gpsProviderActive && !networkProviderActive) { // CASE: Location setting is off locationErrorBar.setText(R.string.snackbar_message_location_offline) if (!locationErrorBar.isShown) locationErrorBar.show() } else { if (locationErrorBar.isShown) locationErrorBar.dismiss() } } private val connection = object : ServiceConnection { override fun onServiceConnected(className: ComponentName, service: IBinder) { // get reference to tracker service] val serviceref = (service as TrackerServiceBinder).service.get() if (serviceref == null) { return } bound = true trackerService = serviceref // get state of tracking and update button if necessary redraw() // register listener for changes in shared preferences PreferencesHelper.registerPreferenceChangeListener(sharedPreferenceChangeListener) } override fun onServiceDisconnected(arg0: ComponentName) { // service has crashed, or was killed by the system handleServiceUnbind() } } fun redraw() { // Log.i("VOUSSOIR", "MapFragment.redraw") update_main_button() val tracker = trackerService if (tracker == null) { return } create_current_position_overlays() if (current_track_overlay == null) { create_track_overlay() } current_track_overlay!!.setPoints(tracker.recent_trackpoints_for_mapview) if (continuous_auto_center) { centerMap(tracker.currentBestLocation) } if (show_debug) { map_current_time.text = """ state: ${state_name()} now: ${iso8601_local_noms(System.currentTimeMillis())} location: ${iso8601_local_noms(tracker.currentBestLocation.time)} listeners: ${iso8601_local_noms(tracker.listeners_enabled_at)} motion: ${iso8601_local_noms(tracker.last_significant_motion)} watchdog: ${iso8601_local_noms(tracker.last_watchdog)} home: ${iso8601_local_noms(tracker.arrived_at_home)} died: ${iso8601_local_noms(tracker.gave_up_at)} power: ${tracker.device_is_charging} wakelock: ${tracker.wakelock.isHeld} """.trimIndent() } else { map_current_time.text = iso8601_local_noms(tracker.currentBestLocation.time) } mapView.invalidate() } fun state_name(): String { val tracker = trackerService if (tracker == null) { return "null" } return when (tracker.tracking_state) { Keys.STATE_STOP -> "stop" Keys.STATE_FULL_RECORDING -> "recording" Keys.STATE_ARRIVED_AT_HOME -> "home" Keys.STATE_SLEEP -> "sleep" Keys.STATE_DEAD -> "dead" Keys.STATE_MAPVIEW -> "mapview" else -> tracker.tracking_state.toString() } } val redraw_runnable: Runnable = object : Runnable { override fun run() { handler.postDelayed(this, 975) redraw() } } }
0
Kotlin
0
0
a27b8713a9d59596ef4e44f0a505c60e4b14340f
27,047
trkpt
MIT License
.teamcity/generated/PushLocalWindows2004.kts
JetBrains
261,739,564
false
null
// NOTE: THIS IS AN AUTO-GENERATED FILE. IT HAD BEEN CREATED USING TEAMCITY.DOCKER PROJECT. ... // ... IF NEEDED, PLEASE, EDIT DSL GENERATOR RATHER THAN THE FILES DIRECTLY. ... // ... FOR MORE DETAILS, PLEASE, REFER TO DOCUMENTATION WITHIN THE REPOSITORY. package generated import jetbrains.buildServer.configs.kotlin.v2019_2.* import jetbrains.buildServer.configs.kotlin.v2019_2.ui.* import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.swabra import common.TeamCityDockerImagesRepo.TeamCityDockerImagesRepo import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.dockerSupport import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.freeDiskSpace import jetbrains.buildServer.configs.kotlin.v2019_2.failureConditions.BuildFailureOnText import jetbrains.buildServer.configs.kotlin.v2019_2.failureConditions.failOnText import jetbrains.buildServer.configs.kotlin.v2019_2.failureConditions.BuildFailureOnMetric import jetbrains.buildServer.configs.kotlin.v2019_2.failureConditions.failOnMetricChange import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.kotlinFile import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.gradle import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.script import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.dockerCommand import jetbrains.buildServer.configs.kotlin.v2019_2.Trigger import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.VcsTrigger import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.finishBuildTrigger import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.vcs object push_local_windows_2004 : BuildType({ name = "Build and push windows 2004" buildNumberPattern="%dockerImage.teamcity.buildNumber%-%build.counter%" description = "teamcity-server:EAP-nanoserver-2004,EAP teamcity-minimal-agent:EAP-nanoserver-2004,EAP teamcity-agent:EAP-windowsservercore-2004,EAP-windowsservercore,-windowsservercore:EAP-nanoserver-2004,EAP" vcs { root(TeamCityDockerImagesRepo) } steps { dockerCommand { name = "pull mcr.microsoft.com/powershell:nanoserver-2004" commandType = other { subCommand = "pull" commandArgs = "mcr.microsoft.com/powershell:nanoserver-2004" } } dockerCommand { name = "pull mcr.microsoft.com/windows/nanoserver:2004" commandType = other { subCommand = "pull" commandArgs = "mcr.microsoft.com/windows/nanoserver:2004" } } dockerCommand { name = "pull mcr.microsoft.com/dotnet/framework/sdk:4.8-windowsservercore-2004" commandType = other { subCommand = "pull" commandArgs = "mcr.microsoft.com/dotnet/framework/sdk:4.8-windowsservercore-2004" } } script { name = "context teamcity-server:EAP-nanoserver-2004" scriptContent = """ echo 2> context/.dockerignore echo TeamCity/buildAgent >> context/.dockerignore echo TeamCity/temp >> context/.dockerignore """.trimIndent() } dockerCommand { name = "build teamcity-server:EAP-nanoserver-2004" commandType = build { source = file { path = """context/generated/windows/Server/nanoserver/2004/Dockerfile""" } contextDir = "context" commandArgs = "--no-cache" namesAndTags = """ teamcity-server:EAP-nanoserver-2004 """.trimIndent() } param("dockerImage.platform", "windows") } script { name = "context teamcity-minimal-agent:EAP-nanoserver-2004" scriptContent = """ echo 2> context/.dockerignore echo TeamCity/webapps >> context/.dockerignore echo TeamCity/devPackage >> context/.dockerignore echo TeamCity/lib >> context/.dockerignore """.trimIndent() } dockerCommand { name = "build teamcity-minimal-agent:EAP-nanoserver-2004" commandType = build { source = file { path = """context/generated/windows/MinimalAgent/nanoserver/2004/Dockerfile""" } contextDir = "context" commandArgs = "--no-cache" namesAndTags = """ teamcity-minimal-agent:EAP-nanoserver-2004 """.trimIndent() } param("dockerImage.platform", "windows") } script { name = "context teamcity-agent:EAP-windowsservercore-2004" scriptContent = """ echo 2> context/.dockerignore echo TeamCity/webapps >> context/.dockerignore echo TeamCity/devPackage >> context/.dockerignore echo TeamCity/lib >> context/.dockerignore """.trimIndent() } dockerCommand { name = "build teamcity-agent:EAP-windowsservercore-2004" commandType = build { source = file { path = """context/generated/windows/Agent/windowsservercore/2004/Dockerfile""" } contextDir = "context" commandArgs = "--no-cache" namesAndTags = """ teamcity-agent:EAP-windowsservercore-2004 """.trimIndent() } param("dockerImage.platform", "windows") } script { name = "context teamcity-agent:EAP-nanoserver-2004" scriptContent = """ echo 2> context/.dockerignore echo TeamCity/webapps >> context/.dockerignore echo TeamCity/devPackage >> context/.dockerignore echo TeamCity/lib >> context/.dockerignore """.trimIndent() } dockerCommand { name = "build teamcity-agent:EAP-nanoserver-2004" commandType = build { source = file { path = """context/generated/windows/Agent/nanoserver/2004/Dockerfile""" } contextDir = "context" commandArgs = "--no-cache" namesAndTags = """ teamcity-agent:EAP-nanoserver-2004 """.trimIndent() } param("dockerImage.platform", "windows") } dockerCommand { name = "tag teamcity-server:EAP-nanoserver-2004" commandType = other { subCommand = "tag" commandArgs = "teamcity-server:EAP-nanoserver-2004 %docker.buildRepository%teamcity-server%docker.buildImagePostfix%:EAP-nanoserver-2004" } } dockerCommand { name = "tag teamcity-minimal-agent:EAP-nanoserver-2004" commandType = other { subCommand = "tag" commandArgs = "teamcity-minimal-agent:EAP-nanoserver-2004 %docker.buildRepository%teamcity-minimal-agent%docker.buildImagePostfix%:EAP-nanoserver-2004" } } dockerCommand { name = "tag teamcity-agent:EAP-windowsservercore-2004" commandType = other { subCommand = "tag" commandArgs = "teamcity-agent:EAP-windowsservercore-2004 %docker.buildRepository%teamcity-agent%docker.buildImagePostfix%:EAP-windowsservercore-2004" } } dockerCommand { name = "tag teamcity-agent:EAP-nanoserver-2004" commandType = other { subCommand = "tag" commandArgs = "teamcity-agent:EAP-nanoserver-2004 %docker.buildRepository%teamcity-agent%docker.buildImagePostfix%:EAP-nanoserver-2004" } } dockerCommand { name = "push teamcity-server:EAP-nanoserver-2004" commandType = push { namesAndTags = """ %docker.buildRepository%teamcity-server%docker.buildImagePostfix%:EAP-nanoserver-2004 """.trimIndent() removeImageAfterPush = false } } dockerCommand { name = "push teamcity-minimal-agent:EAP-nanoserver-2004" commandType = push { namesAndTags = """ %docker.buildRepository%teamcity-minimal-agent%docker.buildImagePostfix%:EAP-nanoserver-2004 """.trimIndent() removeImageAfterPush = false } } dockerCommand { name = "push teamcity-agent:EAP-windowsservercore-2004" commandType = push { namesAndTags = """ %docker.buildRepository%teamcity-agent%docker.buildImagePostfix%:EAP-windowsservercore-2004 """.trimIndent() removeImageAfterPush = false } } dockerCommand { name = "push teamcity-agent:EAP-nanoserver-2004" commandType = push { namesAndTags = """ %docker.buildRepository%teamcity-agent%docker.buildImagePostfix%:EAP-nanoserver-2004 """.trimIndent() removeImageAfterPush = false } } } features { freeDiskSpace { requiredSpace = "43gb" failBuild = true } dockerSupport { cleanupPushedImages = true loginToRegistry = on { dockerRegistryId = "PROJECT_EXT_774,PROJECT_EXT_315" } } swabra { forceCleanCheckout = true } } dependencies { dependency(AbsoluteId("TC_Trunk_BuildDistDocker")) { snapshot { onDependencyFailure = FailureAction.IGNORE reuseBuilds = ReuseBuilds.ANY } artifacts { artifactRules = "TeamCity.zip!/**=>context/TeamCity" } } } params { param("system.teamcity.agent.ensure.free.space", "43gb") } requirements { contains("teamcity.agent.jvm.os.name", "Windows 10") } })
7
C#
59
84
5857905411943ea5819df6abb5698428791ea8bb
8,579
teamcity-docker-images
Apache License 2.0
integration-tests/src/test/resources/on-error/on-error-processor/src/main/kotlin/ErrorProcessor.kt
google
297,744,725
false
null
import com.google.devtools.ksp.processing.* import com.google.devtools.ksp.symbol.* import java.io.OutputStream class ErrorProcessor : SymbolProcessor { lateinit var codeGenerator: CodeGenerator lateinit var logger: KSPLogger lateinit var file: OutputStream lateinit var exception: String fun init( options: Map<String, String>, kotlinVersion: KotlinVersion, codeGenerator: CodeGenerator, logger: KSPLogger ) { exception = if (options.containsKey("exception")) { options["exception"]!! } else { "" } if (exception == "init") { throw Exception("Test Exception in init") } this.logger = logger this.codeGenerator = codeGenerator } override fun process(resolver: Resolver): List<KSAnnotated> { if (exception == "createTwice") { codeGenerator.createNewFile(Dependencies.ALL_FILES, "create", "Twice").write("".toByteArray()) return emptyList() } if (exception == "process") { throw Exception("Test Exception in process") } return emptyList() } override fun finish() { if (exception == "finish") { throw Exception("Test Exception in finish") } } override fun onError() { if (exception == "error") { throw Exception("Test Exception in error") } } } class ErrorProcessorProvider : SymbolProcessorProvider { override fun create( env: SymbolProcessorEnvironment ): SymbolProcessor { return ErrorProcessor().apply { init(env.options, env.kotlinVersion, env.codeGenerator, env.logger) } } }
370
null
268
2,854
a977fb96b05ec9c3e15b5a0cf32e8e7ea73ab3b3
1,741
ksp
Apache License 2.0
screenmanager/dm/screenmanager-displaymask/src/main/java/com/microsoft/device/dualscreen/ScreenManagerProvider.kt
microsoft
262,129,243
false
null
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ package com.microsoft.device.dualscreen import android.app.Application import java.lang.IllegalStateException /** * Utility class used to initialize and retrieve [SurfaceDuoScreenManager] object. */ object ScreenManagerProvider { private var instance: SurfaceDuoScreenManager? = null /** * Use this method to initialize the screen manager object inside [Application.onCreate] */ @JvmStatic @Synchronized fun init(application: Application) { instance = SurfaceDuoScreenManagerImpl(application) } /** * @return the singleton instance of [SurfaceDuoScreenManager] */ @JvmStatic @Synchronized fun getScreenManager(): SurfaceDuoScreenManager { return instance ?: throw IllegalStateException(this::javaClass.toString() + " must be initialized inside Application#onCreate()") } }
4
Kotlin
16
63
059a23684baff99de1293d1f54119b611a5765a3
964
surface-duo-sdk
MIT License
mediator/src/main/kotlin/no/nav/dagpenger/saksbehandling/Configuration.kt
navikt
571,475,339
false
{"Kotlin": 116667, "Mustache": 8476, "PLpgSQL": 2764, "HTML": 699, "Dockerfile": 77}
package no.nav.dagpenger.saksbehandling import com.natpryce.konfig.ConfigurationMap import com.natpryce.konfig.ConfigurationProperties import com.natpryce.konfig.EnvironmentVariables import com.natpryce.konfig.Key import com.natpryce.konfig.overriding import com.natpryce.konfig.stringType import no.nav.dagpenger.oauth2.CachedOauth2Client import no.nav.dagpenger.oauth2.OAuth2Config internal object Configuration { const val APP_NAME = "dp-saksbehandling" private val defaultProperties = ConfigurationMap( mapOf( "RAPID_APP_NAME" to APP_NAME, "KAFKA_CONSUMER_GROUP_ID" to "dp-saksbehandling-v1", "KAFKA_RAPID_TOPIC" to "teamdagpenger.rapid.v1", "KAFKA_RESET_POLICY" to "latest", "GRUPPE_BESLUTTER" to "123", "GRUPPE_SAKSBEHANDLER" to "456", "DP_BEHANDLING_API_URL" to "http://dp-behandling", ), ) val properties = ConfigurationProperties.systemProperties() overriding EnvironmentVariables() overriding defaultProperties val config: Map<String, String> = properties.list().reversed().fold(emptyMap()) { map, pair -> map + pair.second } val behandlingUrl: String = properties[Key("DP_BEHANDLING_API_URL", stringType)] val behandlingScope by lazy { properties[Key("DP_BEHANDLING_API_SCOPE", stringType)] } val azureAdClient by lazy { val azureAdConfig = OAuth2Config.AzureAd(properties) CachedOauth2Client( tokenEndpointUrl = azureAdConfig.tokenEndpointUrl, authType = azureAdConfig.clientSecret(), ) } val tilOboToken = { token: String, scope: String -> azureAdClient.onBehalfOf(token, scope).accessToken } }
0
Kotlin
0
0
c33ed0b786e3a8618de8cadb3771ec203c2c0ec2
1,798
dp-saksbehandling
MIT License
app/src/main/java/io/horizontalsystems/bankwallet/core/managers/BaseTokenManager.kt
horizontalsystems
142,825,178
false
null
package io.deus.wallet.core.managers import io.deus.wallet.core.ICoinManager import io.deus.wallet.core.ILocalStorage import io.horizontalsystems.marketkit.models.BlockchainType import io.horizontalsystems.marketkit.models.Token import io.horizontalsystems.marketkit.models.TokenQuery import io.horizontalsystems.marketkit.models.TokenType import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update class BaseTokenManager( private val coinManager: ICoinManager, private val localStorage: ILocalStorage, ) { val tokens by lazy { listOf( TokenQuery(BlockchainType.Bitcoin, TokenType.Derived(TokenType.Derivation.Bip84)), TokenQuery(BlockchainType.Ethereum, TokenType.Native), TokenQuery(BlockchainType.BinanceSmartChain, TokenType.Native), ).mapNotNull { coinManager.getToken(it) } } var token = localStorage.balanceTotalCoinUid?.let { balanceTotalCoinUid -> tokens.find { it.coin.uid == balanceTotalCoinUid } } ?: tokens.firstOrNull() private set private val _baseTokenFlow = MutableStateFlow(token) val baseTokenFlow = _baseTokenFlow.asStateFlow() fun toggleBaseToken() { val indexOfNext = tokens.indexOf(token) + 1 setBaseToken(tokens.getOrNull(indexOfNext) ?: tokens.firstOrNull()) } fun setBaseToken(token: Token?) { this.token = token localStorage.balanceTotalCoinUid = token?.coin?.uid _baseTokenFlow.update { token } } fun setBaseTokenQueryId(tokenQueryId: String) { val token = TokenQuery.fromId(tokenQueryId)?.let { coinManager.getToken(it) } ?: tokens.first() setBaseToken(token) } }
58
null
364
895
218cd81423c570cdd92b1d5161a600d07c35c232
1,793
unstoppable-wallet-android
MIT License
demo-app/src/main/java/cash/z/ecc/android/sdk/demoapp/ui/screen/send/view/SendView.kt
zcash
151,763,639
false
null
package cash.z.ecc.android.sdk.demoapp.ui.screen.send.view import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import cash.z.ecc.android.sdk.demoapp.R import cash.z.ecc.android.sdk.demoapp.fixture.WalletSnapshotFixture import cash.z.ecc.android.sdk.demoapp.ui.common.MINIMAL_WEIGHT import cash.z.ecc.android.sdk.demoapp.ui.screen.home.viewmodel.SendState import cash.z.ecc.android.sdk.demoapp.ui.screen.home.viewmodel.WalletSnapshot import cash.z.ecc.android.sdk.demoapp.util.fromResources import cash.z.ecc.android.sdk.fixture.WalletFixture import cash.z.ecc.android.sdk.model.Memo import cash.z.ecc.android.sdk.model.MonetarySeparators import cash.z.ecc.android.sdk.model.ZcashNetwork import cash.z.ecc.android.sdk.model.ZecSend import cash.z.ecc.android.sdk.model.ZecSendExt import cash.z.ecc.android.sdk.model.ZecString import cash.z.ecc.android.sdk.model.ZecStringExt import cash.z.ecc.android.sdk.model.toZecString @Preview(name = "Send") @Composable @Suppress("ktlint:standard:function-naming") private fun ComposablePreview() { MaterialTheme { Send( walletSnapshot = WalletSnapshotFixture.new(), sendState = SendState.None, onSend = {}, onBack = {} ) } } @Composable @Suppress("ktlint:standard:function-naming") fun Send( walletSnapshot: WalletSnapshot, sendState: SendState, onSend: (ZecSend) -> Unit, onBack: () -> Unit ) { Scaffold(topBar = { SendTopAppBar(onBack) }) { paddingValues -> SendMainContent( paddingValues = paddingValues, walletSnapshot = walletSnapshot, sendState = sendState, onSend = onSend ) } } @Composable @OptIn(ExperimentalMaterial3Api::class) @Suppress("ktlint:standard:function-naming") private fun SendTopAppBar(onBack: () -> Unit) { TopAppBar( title = { Text(text = stringResource(id = R.string.menu_send)) }, navigationIcon = { IconButton( onClick = onBack ) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = null ) } } ) } @Composable @Suppress("LongMethod", "ktlint:standard:function-naming") private fun SendMainContent( paddingValues: PaddingValues, walletSnapshot: WalletSnapshot, sendState: SendState, onSend: (ZecSend) -> Unit ) { val context = LocalContext.current val monetarySeparators = MonetarySeparators.current() val allowedCharacters = ZecString.allowedCharacters(monetarySeparators) var amountZecString by rememberSaveable { mutableStateOf("") } var recipientAddressString by rememberSaveable { mutableStateOf("") } var memoString by rememberSaveable { mutableStateOf("") } var validation by rememberSaveable { mutableStateOf<Set<ZecSendExt.ZecSendValidation.Invalid.ValidationError>>(emptySet()) } Column( Modifier .fillMaxHeight() .verticalScroll(rememberScrollState()) .padding(top = paddingValues.calculateTopPadding()) ) { Text(text = stringResource(id = R.string.send_available_balance)) Row(Modifier.fillMaxWidth()) { Text(text = walletSnapshot.saplingBalance.available.toZecString()) } TextField( value = amountZecString, onValueChange = { newValue -> if (!ZecStringExt.filterContinuous(context, monetarySeparators, newValue)) { return@TextField } amountZecString = newValue.filter { allowedCharacters.contains(it) } }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), label = { Text(stringResource(id = R.string.send_amount)) } ) Spacer(Modifier.size(8.dp)) TextField( value = recipientAddressString, onValueChange = { recipientAddressString = it }, label = { Text(stringResource(id = R.string.send_to_address)) } ) val zcashNetwork = ZcashNetwork.fromResources(context) Column( Modifier .fillMaxWidth() ) { // Alice's addresses Row( Modifier .fillMaxWidth() .horizontalScroll(rememberScrollState()) ) { Button({ recipientAddressString = WalletFixture.Alice.getAddresses(zcashNetwork).unified }) { Text(text = stringResource(id = R.string.send_alyssa_unified)) } Spacer(Modifier.size(8.dp)) Button({ recipientAddressString = WalletFixture.Alice.getAddresses(zcashNetwork).sapling }) { Text(text = stringResource(id = R.string.send_alyssa_sapling)) } Spacer(Modifier.size(8.dp)) Button({ recipientAddressString = WalletFixture.Alice.getAddresses(zcashNetwork).transparent }) { Text(text = stringResource(id = R.string.send_alyssa_transparent)) } } // Bob's addresses Row( Modifier .fillMaxWidth() .horizontalScroll(rememberScrollState()) ) { Button({ recipientAddressString = WalletFixture.Ben.getAddresses(zcashNetwork).unified }) { Text(text = stringResource(id = R.string.send_ben_unified)) } Spacer(Modifier.size(8.dp)) Button({ recipientAddressString = WalletFixture.Ben.getAddresses(zcashNetwork).sapling }) { Text(text = stringResource(id = R.string.send_ben_sapling)) } Spacer(Modifier.size(8.dp)) Button({ recipientAddressString = WalletFixture.Ben.getAddresses(zcashNetwork).transparent }) { Text(text = stringResource(id = R.string.send_ben_transparent)) } } } Spacer(Modifier.size(8.dp)) TextField(value = memoString, onValueChange = { if (Memo.isWithinMaxLength(it)) { memoString = it } }, label = { Text(stringResource(id = R.string.send_memo)) }) Spacer(Modifier.fillMaxHeight(MINIMAL_WEIGHT)) if (validation.isNotEmpty()) { /* * Note: this is not localized in that it uses the enum constant name and joins the string * without regard for RTL. This will get resolved once we do proper validation for * the fields. */ Text(validation.joinToString(", ")) } Button( onClick = { val zecSendValidation = ZecSendExt.new( context, recipientAddressString, amountZecString, memoString, monetarySeparators ) when (zecSendValidation) { is ZecSendExt.ZecSendValidation.Valid -> onSend(zecSendValidation.zecSend) is ZecSendExt.ZecSendValidation.Invalid -> validation = zecSendValidation.validationErrors } }, // Needs actual validation enabled = amountZecString.isNotBlank() && recipientAddressString.isNotBlank() ) { Text(stringResource(id = R.string.send_button)) } Text(stringResource(id = R.string.send_status, sendState.toString())) } }
2
null
9
51
45f1c473b2531ca47213657c9ef26d25fffeda1d
9,294
zcash-android-wallet-sdk
MIT License
notes-common/src/commonMain/kotlin/models/Folder.kt
alex-avr
589,281,806
false
null
package org.avr.notes.common.models import kotlinx.datetime.Instant import org.avr.notes.common.NONE import org.avr.notes.common.models.folder.FolderId data class Folder( var id: FolderId = FolderId.NONE, var parentFolderId: FolderId? = FolderId.NONE, var title: String = "", var createTime: Instant = Instant.NONE, var updateTime: Instant = Instant.NONE, var version: Int = 1, var children: MutableList<IFolderChild> = mutableListOf(), override val folderChildType: FolderChildType = FolderChildType.FOLDER ) : IFolderChild { fun deepCopy() = copy( children = children.toMutableList() ) }
0
Kotlin
0
0
5fec7609497ed7e247817b83804b39251ba7a944
640
notes
Apache License 2.0
idea/testData/refactoring/extractFunction/parameters/misc/qualifiedTypeArg.kt
JakeWharton
99,388,807
false
null
// SIBLING: class MyClass { fun test() { <selection>val t: P<P.Q>? = null</selection> } public class P<T> { public class Q { } } }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
172
kotlin
Apache License 2.0
repos/cache/src/commonMain/kotlin/dev/inmo/micro_utils/repos/cache/full/FullKeyValueCacheRepo.kt
InsanusMokrassar
295,712,640
false
null
package dev.inmo.micro_utils.repos.cache.full import dev.inmo.micro_utils.common.* import dev.inmo.micro_utils.coroutines.SmartRWLocker import dev.inmo.micro_utils.coroutines.launchSafelyWithoutExceptions import dev.inmo.micro_utils.coroutines.withReadAcquire import dev.inmo.micro_utils.coroutines.withWriteLock import dev.inmo.micro_utils.pagination.Pagination import dev.inmo.micro_utils.pagination.PaginationResult import dev.inmo.micro_utils.repos.* import dev.inmo.micro_utils.repos.cache.util.ActualizeAllClearMode import dev.inmo.micro_utils.repos.cache.util.actualizeAll import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* open class FullReadKeyValueCacheRepo<Key,Value>( protected open val parentRepo: ReadKeyValueRepo<Key, Value>, protected open val kvCache: KeyValueRepo<Key, Value>, protected val locker: SmartRWLocker = SmartRWLocker() ) : ReadKeyValueRepo<Key, Value>, FullCacheRepo { protected suspend inline fun <T> doOrTakeAndActualize( action: KeyValueRepo<Key, Value>.() -> Optional<T>, actionElse: ReadKeyValueRepo<Key, Value>.() -> T, actualize: KeyValueRepo<Key, Value>.(T) -> Unit ): T { locker.withReadAcquire { kvCache.action().onPresented { return it } } return parentRepo.actionElse().also { kvCache.actualize(it) } } protected suspend inline fun <T> doOrTakeAndActualizeWithWriteLock( action: KeyValueRepo<Key, Value>.() -> Optional<T>, actionElse: ReadKeyValueRepo<Key, Value>.() -> T, actualize: KeyValueRepo<Key, Value>.(T) -> Unit ): T = doOrTakeAndActualize( action = action, actionElse = actionElse, actualize = { locker.withWriteLock { actualize(it) } } ) protected open suspend fun actualizeAll() { kvCache.actualizeAll(parentRepo, locker) } override suspend fun get(k: Key): Value? = doOrTakeAndActualizeWithWriteLock( { get(k) ?.optional ?: Optional.absent() }, { get(k) }, { kvCache.set(k, it ?: return@doOrTakeAndActualizeWithWriteLock) } ) override suspend fun values(pagination: Pagination, reversed: Boolean): PaginationResult<Value> = doOrTakeAndActualize( { values(pagination, reversed).takeIf { it.results.isNotEmpty() }.optionalOrAbsentIfNull }, { values(pagination, reversed) }, { if (it.results.isNotEmpty()) actualizeAll() } ) override suspend fun count(): Long = doOrTakeAndActualize( { count().takeIf { it != 0L }.optionalOrAbsentIfNull }, { count() }, { if (it != 0L) actualizeAll() } ) override suspend fun contains(key: Key): Boolean = doOrTakeAndActualizeWithWriteLock( { contains(key).takeIf { it }.optionalOrAbsentIfNull }, { contains(key) }, { if (it) parentRepo.get(key) ?.also { kvCache.set(key, it) } } ) override suspend fun getAll(): Map<Key, Value> = doOrTakeAndActualizeWithWriteLock( { getAll().takeIf { it.isNotEmpty() }.optionalOrAbsentIfNull }, { getAll() }, { kvCache.actualizeAll(clearMode = ActualizeAllClearMode.BeforeSet) { it } } ) override suspend fun keys(pagination: Pagination, reversed: Boolean): PaginationResult<Key> = doOrTakeAndActualize( { keys(pagination, reversed).takeIf { it.results.isNotEmpty() }.optionalOrAbsentIfNull }, { keys(pagination, reversed) }, { if (it.results.isNotEmpty()) actualizeAll() } ) override suspend fun keys(v: Value, pagination: Pagination, reversed: Boolean): PaginationResult<Key> = doOrTakeAndActualize( { keys(v, pagination, reversed).takeIf { it.results.isNotEmpty() }.optionalOrAbsentIfNull }, { parentRepo.keys(v, pagination, reversed) }, { if (it.results.isNotEmpty()) actualizeAll() } ) override suspend fun invalidate() { actualizeAll() } } fun <Key, Value> ReadKeyValueRepo<Key, Value>.cached( kvCache: KeyValueRepo<Key, Value>, locker: SmartRWLocker = SmartRWLocker() ) = FullReadKeyValueCacheRepo(this, kvCache, locker) open class FullWriteKeyValueCacheRepo<Key,Value>( parentRepo: WriteKeyValueRepo<Key, Value>, protected open val kvCache: KeyValueRepo<Key, Value>, scope: CoroutineScope = CoroutineScope(Dispatchers.Default), protected val locker: SmartRWLocker = SmartRWLocker() ) : WriteKeyValueRepo<Key, Value> by parentRepo, FullCacheRepo { protected val onNewJob = parentRepo.onNewValue.onEach { locker.withWriteLock { kvCache.set(it.first, it.second) } }.launchIn(scope) protected val onRemoveJob = parentRepo.onValueRemoved.onEach { locker.withWriteLock { kvCache.unset(it) } }.launchIn(scope) override suspend fun invalidate() { locker.withWriteLock { kvCache.clear() } } } fun <Key, Value> WriteKeyValueRepo<Key, Value>.caching( kvCache: KeyValueRepo<Key, Value>, scope: CoroutineScope = CoroutineScope(Dispatchers.Default) ) = FullWriteKeyValueCacheRepo(this, kvCache, scope) open class FullKeyValueCacheRepo<Key,Value>( protected open val parentRepo: KeyValueRepo<Key, Value>, kvCache: KeyValueRepo<Key, Value>, scope: CoroutineScope = CoroutineScope(Dispatchers.Default), skipStartInvalidate: Boolean = false, locker: SmartRWLocker = SmartRWLocker() ) : FullWriteKeyValueCacheRepo<Key,Value>(parentRepo, kvCache, scope), KeyValueRepo<Key,Value>, ReadKeyValueRepo<Key, Value> by FullReadKeyValueCacheRepo( parentRepo, kvCache, locker ) { init { if (!skipStartInvalidate) { scope.launchSafelyWithoutExceptions { invalidate() } } } override suspend fun unsetWithValues(toUnset: List<Value>) = parentRepo.unsetWithValues(toUnset) override suspend fun invalidate() { kvCache.actualizeAll(parentRepo, locker) } override suspend fun clear() { parentRepo.clear() kvCache.clear() } } fun <Key, Value> KeyValueRepo<Key, Value>.fullyCached( kvCache: KeyValueRepo<Key, Value> = MapKeyValueRepo(), scope: CoroutineScope = CoroutineScope(Dispatchers.Default), skipStartInvalidate: Boolean = false, locker: SmartRWLocker = SmartRWLocker() ) = FullKeyValueCacheRepo(this, kvCache, scope, skipStartInvalidate, locker) @Deprecated("Renamed", ReplaceWith("this.fullyCached(kvCache, scope)", "dev.inmo.micro_utils.repos.cache.full.fullyCached")) fun <Key, Value> KeyValueRepo<Key, Value>.cached( kvCache: KeyValueRepo<Key, Value>, scope: CoroutineScope = CoroutineScope(Dispatchers.Default), skipStartInvalidate: Boolean = false, locker: SmartRWLocker = SmartRWLocker() ) = fullyCached(kvCache, scope, skipStartInvalidate, locker)
7
null
3
32
f09d92be32a3f792818edc28bbb27a9826f262b2
6,858
MicroUtils
Apache License 2.0
tmp/arrays/youTrackTests/3188.kt
DaniilStepanov
228,623,440
false
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
// Original bug: KT-19106 class BClass{ fun f1(){} } fun f2(b: BClass) {} fun f3(param: BClass){ // call `Data Flow from here` for `param` val a1 = param val b1 = param.f1() val c1 = f2(param) }
1
null
8
1
602285ec60b01eee473dcb0b08ce497b1c254983
211
bbfgradle
Apache License 2.0
app/src/main/java/com/hazz/kotlinmvp/net/exception/ErrorStatus.kt
git-xuhao
111,071,830
false
null
package com.hazz.kuangji.net.exception /** * Created by xuhao on 2017/12/5. * desc: */ object ErrorStatus { /** * 响应成功 */ @JvmField val SUCCESS = 0 /** * 未知错误 */ @JvmField val UNKNOWN_ERROR = 1002 /** * 服务器内部错误 */ @JvmField val SERVER_ERROR = 1003 /** * 网络连接超时 */ @JvmField val NETWORK_ERROR = 1004 /** * API解析异常(或者第三方数据结构更改)等其他异常 */ @JvmField val API_ERROR = 1005 }
17
null
920
3,606
7b55819ca1ca026002463c0003b2638903727efc
485
KotlinMvp
Apache License 2.0
app/src/main/java/com/yeahush/quickquest/ui/trivia/TriviaPlayViewModel.kt
d04nhtu
285,921,095
false
null
package com.yeahush.quickquest.ui.trivia import android.os.CountDownTimer import android.os.Handler import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import com.yeahush.quickquest.data.local.prefs.AppPreferences import com.yeahush.quickquest.data.remote.TriviaQuestion import com.yeahush.quickquest.utilities.NONE import com.yeahush.quickquest.utilities.ONE_SECOND import com.yeahush.quickquest.utilities.TIME_PER_QUESTION import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withContext import timber.log.Timber import javax.inject.Inject class TriviaPlayViewModel @Inject constructor( private val repository: TriviaRepository, private val appPreferences: AppPreferences ) : ViewModel() { private var timer: CountDownTimer private var handler = Handler() // The current score private val _score = MutableLiveData(0) val score: LiveData<Int> get() = _score private var _currentQuestion = MutableLiveData<TriviaQuestion>() val currentQuestion: LiveData<TriviaQuestion> get() = _currentQuestion val options = Transformations.map(_currentQuestion) { it.incorrectAnswers.toMutableList().apply { add(it.correctAnswer) shuffle() } } private val _currentTime = MutableLiveData<Int>() val currentTime: LiveData<Int> get() = _currentTime private var _eventLoaded = MutableLiveData<Boolean>(false) val eventLoaded: LiveData<Boolean> get() = _eventLoaded private var _eventQueryEmpty = MutableLiveData<Boolean>(false) val eventQueryEmpty: LiveData<Boolean> get() = _eventQueryEmpty private var _eventNetworkError = MutableLiveData<Boolean>(false) val eventNetworkError: LiveData<Boolean> get() = _eventNetworkError private var _eventStart = MutableLiveData<Boolean>(false) val eventStart: LiveData<Boolean> get() = _eventStart private val _eventFinish = MutableLiveData<Boolean>() val eventFinish: LiveData<Boolean> get() = _eventFinish private val _questionNumber = MutableLiveData(0) val questionNumber: LiveData<Int> get() = _questionNumber private lateinit var questionList: MutableList<TriviaQuestion> private var _params = emptyArray<String>() init { timer = object : CountDownTimer(TIME_PER_QUESTION, ONE_SECOND) { override fun onTick(millisUntilFinished: Long) { _currentTime.value = (millisUntilFinished / ONE_SECOND).toInt() } override fun onFinish() { _eventStart.value = false handler.postDelayed({ nextQuestion() }, 600) } } } suspend fun setParams(params: Array<String>) { if (!_params.contentEquals(params)) { _params = params try { withContext(NonCancellable) { val res = repository.getQuestionResponse(params[0].toInt(), params[1], params[2]) Timber.d(res.toString()) if (res.isSuccessful) { questionList = res.body()?.results?.toMutableList()!! if (questionList.isEmpty()) { _eventQueryEmpty.value = true } else { _eventLoaded.value = true nextQuestion() } } } } catch (e: Exception) { Timber.e(e, "Error get Trivia questions") _eventNetworkError.value = true } } } /** * Callback called when the ViewModel is destroyed */ override fun onCleared() { super.onCleared() timer.cancel() handler.removeCallbacksAndMessages(null) } private fun nextQuestion() { if (questionList.isEmpty()) { _eventFinish.value = true } else { _eventStart.value = true _questionNumber.value = _questionNumber.value?.plus(1) _currentQuestion.value = questionList.removeAt(questionList.size - 1) timer.start() } } fun onOptionClick(pos: Int) { _eventStart.value = false if (pos != NONE && options.value!![pos] == _currentQuestion.value?.correctAnswer) { _score.value = (_score.value)?.plus(1) } timer.cancel() Handler().postDelayed({ nextQuestion() }, 600) } fun isSoundEnable() = appPreferences.isSoundEnable() fun isVibrateEnable() = appPreferences.isVibrateEnable() fun getSignature() = appPreferences.getSignature() }
0
Kotlin
0
1
33317c38d0fcd48ef5c34ecbdcc9ff06f898add9
4,812
quick_quest
MIT License
ktx-datetime/src/commonTest/kotlin/tech/antibytes/kfixture/mock/DateTimeGeneratorStub.kt
bitPogo
471,069,650
false
null
/* * Copyright (c) 2022 <NAME> (bitPogo) / All rights reserved. * * Use of this source code is governed by Apache v2.0 */ package tech.antibytes.kfixture.mock import kotlin.js.JsName import kotlinx.datetime.Instant import kotlinx.datetime.TimeZone import tech.antibytes.kfixture.ktx.datetime.KtxDateTimeContract class DateTimeGeneratorStub<T : Any>( @JsName("onGenerate") var generate: Function0<T>? = null, @JsName("onGenerateWithGenerators") var generateWithGenerators: Function2<(Function0<Instant>)?, Function0<TimeZone>?, T>? = null, ) : KtxDateTimeContract.LocalizedDateTimeGenerator<T> { override fun generate(): T { return generate?.invoke() ?: throw RuntimeException("Missing Stub for generate!") } override fun generate( instantGenerator: Function0<Instant>?, timeZoneGenerator: Function0<TimeZone>?, ): T { return generateWithGenerators?.invoke(instantGenerator, timeZoneGenerator) ?: throw RuntimeException("Missing Stub for generateWithGenerators!") } fun clear() { generate = null generateWithGenerators = null } }
0
null
1
12
52ccc8a29b0429fc07335cd4926169d254a78551
1,154
kfixture
Apache License 2.0
app/network/src/main/java/app/emmabritton/cibusana/network/models/ResponseError.kt
emmabritton
559,135,688
false
null
package app.emmabritton.cibusana.network.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class ResponseError( @Json(name = "error_codes") val codes: List<Int>, @Json(name = "error_message") val message: String )
0
Kotlin
0
0
1e2bf6836a97b8f4b92d00656c113a27ace1185c
296
cibusana
MIT License
rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding2/widget/RxRatingBar.kt
widegalaxy
98,282,798
true
{"Gradle": 17, "Markdown": 3, "INI": 14, "Shell": 2, "Ignore List": 1, "Text": 1, "YAML": 1, "XML": 20, "Java": 182, "Java Properties": 1, "Kotlin": 26, "Groovy": 3}
package com.jakewharton.rxbinding2.widget import android.widget.RatingBar import io.reactivex.Observable import io.reactivex.functions.Consumer /** * Create an observable of the rating changes on `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Note:* A value will be emitted immediately on subscribe. */ inline fun RatingBar.ratingChanges(): Observable<Float> = RxRatingBar.ratingChanges(this) /** * Create an observable of the rating change events on `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Note:* A value will be emitted immediately on subscribe. */ inline fun RatingBar.ratingChangeEvents(): Observable<RatingBarChangeEvent> = RxRatingBar.ratingChangeEvents(this) /** * An action which sets the rating of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ inline fun RatingBar.rating(): Consumer<in Float> = RxRatingBar.rating(this) /** * An action which sets whether `view` is an indicator (thus non-changeable by the user). * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ inline fun RatingBar.isIndicator(): Consumer<in Boolean> = RxRatingBar.isIndicator(this)
1
Java
1
1
edcf58a98be61a8ae369658b4ae585216b9a757f
1,396
RxBinding
Apache License 2.0
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt
whitemike889
219,032,316
true
null
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.updateSettings.impl import com.intellij.diagnostic.IdeErrorsDialog import com.intellij.externalDependencies.DependencyOnPlugin import com.intellij.externalDependencies.ExternalDependenciesManager import com.intellij.ide.IdeBundle import com.intellij.ide.externalComponents.ExternalComponentManager import com.intellij.ide.plugins.* import com.intellij.ide.util.PropertiesComponent import com.intellij.internal.statistic.service.fus.collectors.FUSApplicationUsageTrigger import com.intellij.notification.* import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.LogUtil import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.ActionCallback import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.util.Url import com.intellij.util.Urls import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.MultiMap import com.intellij.util.io.HttpRequests import com.intellij.util.io.URLUtil import com.intellij.util.loadElement import com.intellij.util.ui.UIUtil import com.intellij.xml.util.XmlStringUtil import gnu.trove.THashMap import org.jdom.JDOMException import java.io.File import java.io.IOException import java.util.* import kotlin.collections.HashSet import kotlin.collections.set /** * See XML file by [ApplicationInfoEx.getUpdateUrls] for reference. */ object UpdateChecker { private val LOG = Logger.getInstance("#com.intellij.openapi.updateSettings.impl.UpdateChecker") @JvmField val NOTIFICATIONS: NotificationGroup = NotificationGroup(IdeBundle.message("update.notifications.title"), NotificationDisplayType.STICKY_BALLOON, true) private const val DISABLED_UPDATE = "disabled_update.txt" private enum class NotificationUniqueType { PLATFORM, PLUGINS, EXTERNAL } private var ourDisabledToUpdatePlugins: MutableSet<String>? = null private val ourAdditionalRequestOptions = THashMap<String, String>() private val ourUpdatedPlugins = hashMapOf<String, PluginDownloader>() private val ourShownNotifications = MultiMap<NotificationUniqueType, Notification>() /** * Adding a plugin ID to this collection allows to exclude a plugin from a regular update check. * Has no effect on non-bundled or "essential" (i.e. required for one of open projects) plugins. */ @Suppress("MemberVisibilityCanBePrivate") val excludedFromUpdateCheckPlugins: HashSet<String> = hashSetOf() private val updateUrl: String get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls.checkingUrl /** * For scheduled update checks. */ @JvmStatic fun updateAndShowResult(): ActionCallback { val callback = ActionCallback() ApplicationManager.getApplication().executeOnPooledThread { doUpdateAndShowResult(null, true, false, UpdateSettings.getInstance(), null, callback) } return callback } /** * For manual update checks (Help | Check for Updates, Settings | Updates | Check Now) * (the latter action may pass customised update settings). */ @JvmStatic fun updateAndShowResult(project: Project?, customSettings: UpdateSettings?) { val settings = customSettings ?: UpdateSettings.getInstance() val fromSettings = customSettings != null ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) { override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult(getProject(), fromSettings, true, settings, indicator, null) override fun isConditionalModal(): Boolean = fromSettings override fun shouldStartInBackground(): Boolean = !fromSettings }) } /** * An immediate check for plugin updates for use from a command line (read "Toolbox"). */ @JvmStatic fun getPluginUpdates(): Collection<PluginDownloader>? = checkPluginsUpdate(UpdateSettings.getInstance(), EmptyProgressIndicator(), null, BuildNumber.currentVersion()) private fun doUpdateAndShowResult(project: Project?, fromSettings: Boolean, manualCheck: Boolean, updateSettings: UpdateSettings, indicator: ProgressIndicator?, callback: ActionCallback?) { // check platform update indicator?.text = IdeBundle.message("updates.checking.platform") val result = checkPlatformUpdate(updateSettings) if (result.state == UpdateStrategy.State.CONNECTION_ERROR) { val e = result.error if (e != null) LOG.debug(e) showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e?.message ?: "internal error")) callback?.setRejected() return } // check plugins update (with regard to potential platform update) indicator?.text = IdeBundle.message("updates.checking.plugins") val buildNumber: BuildNumber? = result.newBuild?.apiVersion val incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>? = if (buildNumber != null) HashSet() else null val updatedPlugins: Collection<PluginDownloader>? val externalUpdates: Collection<ExternalUpdate>? try { updatedPlugins = checkPluginsUpdate(updateSettings, indicator, incompatiblePlugins, buildNumber) externalUpdates = checkExternalUpdates(manualCheck, updateSettings, indicator) } catch (e: IOException) { showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e.message)) callback?.setRejected() return } // show result UpdateSettings.getInstance().saveLastCheckedInfo() ApplicationManager.getApplication().invokeLater({ showUpdateResult(project, result, updateSettings, updatedPlugins, incompatiblePlugins, externalUpdates, !fromSettings, manualCheck) callback?.setDone() }, if (fromSettings) ModalityState.any() else ModalityState.NON_MODAL) } private fun checkPlatformUpdate(settings: UpdateSettings): CheckForUpdateResult { val updateInfo: UpdatesInfo? try { var updateUrl = Urls.newFromEncoded(updateUrl) if (updateUrl.scheme != URLUtil.FILE_PROTOCOL) { updateUrl = prepareUpdateCheckArgs(updateUrl, settings.packageManagerName) } LogUtil.debug(LOG, "load update xml (UPDATE_URL='%s')", updateUrl) updateInfo = HttpRequests.request(updateUrl) .forceHttps(settings.canUseSecureConnection()) .connect { try { if (settings.isPlatformUpdateEnabled) UpdatesInfo(loadElement(it.reader)) else null } catch (e: JDOMException) { // corrupted content, don't bother telling user LOG.info(e) null } } } catch (e: Exception) { LOG.info(e) return CheckForUpdateResult(UpdateStrategy.State.CONNECTION_ERROR, e) } if (updateInfo == null) { return CheckForUpdateResult(UpdateStrategy.State.NOTHING_LOADED, null) } val strategy = UpdateStrategy(ApplicationInfo.getInstance().build, updateInfo, settings) return strategy.checkForUpdates() } @JvmStatic @Throws(IOException::class) fun getUpdatesInfo(settings: UpdateSettings): UpdatesInfo? { val updateUrl = Urls.newFromEncoded(updateUrl) LogUtil.debug(LOG, "load update xml (UPDATE_URL='%s')", updateUrl) return HttpRequests.request(updateUrl) .forceHttps(settings.canUseSecureConnection()) .connect { try { UpdatesInfo(loadElement(it.reader)) } catch (e: JDOMException) { // corrupted content, don't bother telling user LOG.info(e) null } } } private fun checkPluginsUpdate(updateSettings: UpdateSettings, indicator: ProgressIndicator?, incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?, buildNumber: BuildNumber?): Collection<PluginDownloader>? { val updateable = collectUpdateablePlugins() val kotlinId = PluginId.findId("org.jetbrains.kotlin") LOG.info("=== Kotlin: ${updateable[kotlinId]?.version} in update list ===") if (updateable.isEmpty()) return null val toUpdate = ContainerUtil.newTroveMap<PluginId, PluginDownloader>() val state = InstalledPluginsState.getInstance() outer@ for (host in RepositoryHelper.getPluginHosts()) { try { val forceHttps = host == null && updateSettings.canUseSecureConnection() val list = RepositoryHelper.loadPlugins(host, buildNumber, forceHttps, indicator) for (descriptor in list) { val id = descriptor.pluginId if (id.idString == kotlinId?.idString) { LOG.info("=== New Kotlin: ${descriptor.version} from: ${host} ===") } if (updateable.containsKey(id)) { updateable.remove(id) state.onDescriptorDownload(descriptor) val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber, forceHttps) checkAndPrepareToInstall(downloader, state, toUpdate, incompatiblePlugins, indicator) if (toUpdate.containsKey(kotlinId)) { LOG.info("=== In result list new Kotlin: ${descriptor.version} from: ${host} ===") } if (updateable.isEmpty()) { break@outer } } } } catch (e: IOException) { LOG.debug(e) LOG.info("failed to load plugin descriptions from ${host ?: "default repository"}: ${e.message}") } } return if (toUpdate.isEmpty) null else toUpdate.values } /** * Returns a list of plugins which are currently installed or were installed in the previous installation from which * we're importing the settings. */ private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor> { val updateable = ContainerUtil.newTroveMap<PluginId, IdeaPluginDescriptor>() updateable += PluginManagerCore.getPlugins().filter { !it.isBundled || it.allowBundledUpdate()}.associateBy { it.pluginId } val onceInstalled = PluginManager.getOnceInstalledIfExists() if (onceInstalled != null) { try { FileUtil.loadLines(onceInstalled) .map { line -> PluginId.getId(line.trim { it <= ' ' }) } .filter { it !in updateable } .forEach { updateable[it] = null } } catch (e: IOException) { LOG.error(onceInstalled.path, e) } //noinspection SSBasedInspection onceInstalled.deleteOnExit() } if (!excludedFromUpdateCheckPlugins.isEmpty()) { val required = ProjectManager.getInstance().openProjects .flatMap { ExternalDependenciesManager.getInstance(it).getDependencies(DependencyOnPlugin::class.java) } .map { PluginId.getId(it.pluginId) } .toSet() excludedFromUpdateCheckPlugins.forEach { val excluded = PluginId.getId(it) if (excluded !in required) { val plugin = updateable[excluded] if (plugin != null && plugin.isBundled) { updateable.remove(excluded) } } } } return updateable } private fun checkExternalUpdates(manualCheck: Boolean, updateSettings: UpdateSettings, indicator: ProgressIndicator?) : Collection<ExternalUpdate> { val result = arrayListOf<ExternalUpdate>() val manager = ExternalComponentManager.getInstance() indicator?.text = IdeBundle.message("updates.external.progress") for (source in manager.componentSources) { indicator?.checkCanceled() if (source.name in updateSettings.enabledExternalUpdateSources) { try { val siteResult = source.getAvailableVersions(indicator, updateSettings) .filter { it.isUpdateFor(manager.findExistingComponentMatching(it, source)) } if (!siteResult.isEmpty()) { result += ExternalUpdate(siteResult, source) } } catch (e: Exception) { LOG.warn(e) showErrorMessage(manualCheck, IdeBundle.message("updates.external.error.message", source.name, e.message ?: "internal error")) } } } return result } @Throws(IOException::class) @JvmStatic fun checkAndPrepareToInstall(downloader: PluginDownloader, state: InstalledPluginsState, toUpdate: MutableMap<PluginId, PluginDownloader>, incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?, indicator: ProgressIndicator?) { @Suppress("NAME_SHADOWING") var downloader = downloader val pluginId = downloader.pluginId if (PluginManagerCore.getDisabledPlugins().contains(pluginId)) return val pluginVersion = downloader.pluginVersion val installedPlugin = PluginManager.getPlugin(PluginId.getId(pluginId)) if (installedPlugin == null || pluginVersion == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(installedPlugin, pluginVersion) > 0) { var descriptor: IdeaPluginDescriptor? val oldDownloader = ourUpdatedPlugins[pluginId] if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) { descriptor = downloader.descriptor if (descriptor is PluginNode && descriptor.isIncomplete) { if (downloader.prepareToInstall(indicator ?: EmptyProgressIndicator())) { descriptor = downloader.descriptor } ourUpdatedPlugins[pluginId] = downloader } } else { downloader = oldDownloader descriptor = oldDownloader.descriptor } if (PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) { toUpdate[PluginId.getId(pluginId)] = downloader } } // collect plugins which were not updated and would be incompatible with new version if (incompatiblePlugins != null && installedPlugin != null && installedPlugin.isEnabled && !toUpdate.containsKey(installedPlugin.pluginId) && !PluginManagerCore.isCompatible(installedPlugin, downloader.buildNumber)) { incompatiblePlugins += installedPlugin } } private fun showErrorMessage(showDialog: Boolean, message: String) { LOG.info(message) if (showDialog) { UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(message, IdeBundle.message("updates.error.connection.title")) } } } private fun showUpdateResult(project: Project?, checkForUpdateResult: CheckForUpdateResult, updateSettings: UpdateSettings, updatedPlugins: Collection<PluginDownloader>?, incompatiblePlugins: Collection<IdeaPluginDescriptor>?, externalUpdates: Collection<ExternalUpdate>?, enableLink: Boolean, alwaysShowResults: Boolean) { val updatedChannel = checkForUpdateResult.updatedChannel val newBuild = checkForUpdateResult.newBuild if (updatedChannel != null && newBuild != null) { val runnable = { val patches = checkForUpdateResult.patches val forceHttps = updateSettings.canUseSecureConnection() UpdateInfoDialog(updatedChannel, newBuild, patches, enableLink, forceHttps, updatedPlugins, incompatiblePlugins).show() } ourShownNotifications.remove(NotificationUniqueType.PLATFORM)?.forEach { it.expire() } if (alwaysShowResults) { runnable.invoke() } else { FUSApplicationUsageTrigger.getInstance().trigger(IdeUpdateUsageTriggerCollector::class.java, "notification.shown") val message = IdeBundle.message("updates.ready.message", ApplicationNamesInfo.getInstance().fullProductName) showNotification(project, message, { FUSApplicationUsageTrigger.getInstance().trigger(IdeUpdateUsageTriggerCollector::class.java, "notification.clicked") runnable() }, NotificationUniqueType.PLATFORM) } return } var updateFound = false if (updatedPlugins != null && !updatedPlugins.isEmpty()) { updateFound = true val runnable = { PluginUpdateInfoDialog(updatedPlugins, enableLink).show() } ourShownNotifications.remove(NotificationUniqueType.PLUGINS)?.forEach { it.expire() } if (alwaysShowResults) { runnable.invoke() } else { val plugins = updatedPlugins.joinToString { downloader -> downloader.pluginName } val message = IdeBundle.message("updates.plugins.ready.message", updatedPlugins.size, plugins) showNotification(project, message, runnable, NotificationUniqueType.PLUGINS) } } if (externalUpdates != null && !externalUpdates.isEmpty()) { updateFound = true ourShownNotifications.remove(NotificationUniqueType.EXTERNAL)?.forEach { it.expire() } for (update in externalUpdates) { val runnable = { update.source.installUpdates(update.components) } if (alwaysShowResults) { runnable.invoke() } else { val updates = update.components.joinToString(", ") val message = IdeBundle.message("updates.external.ready.message", update.components.size, updates) showNotification(project, message, runnable, NotificationUniqueType.EXTERNAL) } } } if (!updateFound && alwaysShowResults) { NoUpdatesDialog(enableLink).show() } } private fun showNotification(project: Project?, message: String, action: () -> Unit, notificationType: NotificationUniqueType) { val listener = NotificationListener { notification, _ -> notification.expire() action.invoke() } val title = IdeBundle.message("update.notifications.title") val notification = NOTIFICATIONS.createNotification(title, XmlStringUtil.wrapInHtml(message), NotificationType.INFORMATION, listener) notification.whenExpired { ourShownNotifications.remove(notificationType, notification) } notification.notify(project) ourShownNotifications.putValue(notificationType, notification) } @JvmStatic fun addUpdateRequestParameter(name: String, value: String) { ourAdditionalRequestOptions[name] = value } private fun prepareUpdateCheckArgs(url: Url, packageManagerName: String?): Url { addUpdateRequestParameter("build", ApplicationInfo.getInstance().build.asString()) addUpdateRequestParameter("uid", PermanentInstallationID.get()) addUpdateRequestParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION) if (packageManagerName != null) { addUpdateRequestParameter("manager", packageManagerName) } if (ApplicationInfoEx.getInstanceEx().isEAP) { addUpdateRequestParameter("eap", "") } return url.addParameters(ourAdditionalRequestOptions) } @Deprecated("Replaced", ReplaceWith("PermanentInstallationID.get()", "com.intellij.openapi.application.PermanentInstallationID")) @JvmStatic @Suppress("unused", "UNUSED_PARAMETER") fun getInstallationUID(c: PropertiesComponent): String = PermanentInstallationID.get() @JvmStatic val disabledToUpdatePlugins: Set<String> get() { if (ourDisabledToUpdatePlugins == null) { ourDisabledToUpdatePlugins = TreeSet() if (!ApplicationManager.getApplication().isUnitTestMode) { try { val file = File(PathManager.getConfigPath(), DISABLED_UPDATE) if (file.isFile) { FileUtil.loadFile(file) .split("[\\s]".toRegex()) .map { it.trim() } .filterTo(ourDisabledToUpdatePlugins!!) { it.isNotEmpty() } } } catch (e: IOException) { LOG.error(e) } } } return ourDisabledToUpdatePlugins!! } @JvmStatic fun saveDisabledToUpdatePlugins() { val plugins = File(PathManager.getConfigPath(), DISABLED_UPDATE) try { PluginManagerCore.savePluginsList(disabledToUpdatePlugins, false, plugins) } catch (e: IOException) { LOG.error(e) } } private var ourHasFailedPlugins = false @JvmStatic fun checkForUpdate(event: IdeaLoggingEvent) { if (!ourHasFailedPlugins) { val app = ApplicationManager.getApplication() if (app != null && !app.isDisposed && !app.isDisposeInProgress && UpdateSettings.getInstance().isCheckNeeded) { val pluginDescriptor = PluginManager.getPlugin(IdeErrorsDialog.findPluginId(event.throwable)) if (pluginDescriptor != null && !pluginDescriptor.isBundled) { ourHasFailedPlugins = true updateAndShowResult() } } } } /** A helper method for manually testing platform updates (see [com.intellij.internal.ShowUpdateInfoDialogAction]). */ fun testPlatformUpdate(updateInfoText: String, patchFilePath: String?, forceUpdate: Boolean) { if (!ApplicationManager.getApplication().isInternal) { throw IllegalStateException() } val channel: UpdateChannel? val newBuild: BuildInfo? val patches: UpdateChain? if (forceUpdate) { val node = loadElement(updateInfoText).getChild("product")?.getChild("channel") ?: throw IllegalArgumentException("//channel missing") channel = UpdateChannel(node) newBuild = channel.builds.firstOrNull() ?: throw IllegalArgumentException("//build missing") patches = newBuild.patches.firstOrNull()?.let { UpdateChain(listOf(it.fromBuild, newBuild.number), it.size) } } else { val updateInfo = UpdatesInfo(loadElement(updateInfoText)) val strategy = UpdateStrategy(ApplicationInfo.getInstance().build, updateInfo, UpdateSettings.getInstance()) val checkForUpdateResult = strategy.checkForUpdates() channel = checkForUpdateResult.updatedChannel newBuild = checkForUpdateResult.newBuild patches = checkForUpdateResult.patches } if (channel != null && newBuild != null) { val patchFile = if (patchFilePath != null) File(FileUtil.toSystemDependentName(patchFilePath)) else null UpdateInfoDialog(channel, newBuild, patches, patchFile).show() } else { NoUpdatesDialog(true).show() } } }
5
null
1
1
fca081d21dcb659c5ecc31db2d7a038966070d4c
23,308
intellij-community
Apache License 2.0
educational-core/src/com/jetbrains/edu/learning/codeforces/checker/CodeforcesTaskWithFileIOTaskChecker.kt
JetBrains
43,696,115
false
null
package com.jetbrains.edu.learning.codeforces.checker import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.jetbrains.edu.learning.EduBrowser import com.jetbrains.edu.learning.courseFormat.CheckResult import com.jetbrains.edu.learning.checker.TaskChecker import com.jetbrains.edu.learning.codeforces.courseFormat.CodeforcesTask.Companion.codeforcesSubmitLink import com.jetbrains.edu.learning.codeforces.courseFormat.CodeforcesTaskWithFileIO import com.jetbrains.edu.learning.courseFormat.CheckStatus import com.jetbrains.edu.learning.selectedEditor import java.awt.datatransfer.StringSelection class CodeforcesTaskWithFileIOTaskChecker(task: CodeforcesTaskWithFileIO, project: Project) : TaskChecker<CodeforcesTaskWithFileIO>(task, project) { override fun check(indicator: ProgressIndicator): CheckResult { val selectedEditor = project.selectedEditor ?: error("no selected editor for Codeforces check") val solution = selectedEditor.document.text val url = codeforcesSubmitLink(task) CopyPasteManager.getInstance().setContents(StringSelection(solution)) EduBrowser.getInstance().browse(url) return CheckResult(CheckStatus.Unchecked, "") } }
6
Kotlin
48
99
cfc24fe13318de446b8adf6e05d1a7c15d9511b5
1,280
educational-plugin
Apache License 2.0
integration-test-core/src/main/kotlin/integration/core/Dbms.kt
komapper
349,909,214
false
null
package integration.core enum class Dbms { H2, MARIADB, MYSQL, ORACLE, POSTGRESQL, SQLSERVER }
7
Kotlin
4
97
851b313c66645d60f2e86934a5036efbe435396a
100
komapper
Apache License 2.0
myddd-vertx-ioc/myddd-vertx-ioc-guice/src/main/kotlin/org/myddd/vertx/ioc/guice/GuiceInstanceProvider.kt
mydddOrg
394,671,816
false
null
package org.myddd.vertx.ioc.guice import com.google.inject.Injector import com.google.inject.Key import com.google.inject.name.Names import org.myddd.vertx.ioc.InstanceProvider class GuiceInstanceProvider(injector: Injector?): InstanceProvider { private var injector: Injector? = null init { this.injector = injector this.injector } override fun <T> getInstance(beanType: Class<T>?): T { requireNotNull(injector) return injector!!.getInstance(beanType) } override fun <T> getInstance(beanType: Class<T>?, beanName: String?): T { requireNotNull(injector) return injector!!.getInstance(Key.get(beanType,Names.named(beanName))) } }
0
Kotlin
0
6
2f03041f4a8984f6acba1f6ec31a22185f0fcb0e
711
myddd-vertx
MIT License
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/cloudwatch/GaugeWidget.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 142794926}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.cloudwatch import io.cloudshiftdev.awscdk.Duration import io.cloudshiftdev.awscdk.common.CdkDslMarker import kotlin.Any import kotlin.Boolean import kotlin.Number import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlin.jvm.JvmName /** * A dashboard gauge widget that displays metrics. * * Example: * * ``` * Dashboard dashboard; * Alarm errorAlarm; * Metric gaugeMetric; * dashboard.addWidgets(GaugeWidget.Builder.create() * .metrics(List.of(gaugeMetric)) * .leftYAxis(YAxisProps.builder() * .min(0) * .max(1000) * .build()) * .build()); * ``` */ public open class GaugeWidget( cdkObject: software.amazon.awscdk.services.cloudwatch.GaugeWidget, ) : ConcreteWidget(cdkObject) { public constructor(props: GaugeWidgetProps) : this(software.amazon.awscdk.services.cloudwatch.GaugeWidget(props.let(GaugeWidgetProps.Companion::unwrap)) ) public constructor(props: GaugeWidgetProps.Builder.() -> Unit) : this(GaugeWidgetProps(props) ) /** * Add another metric to the left Y axis of the GaugeWidget. * * @param metric the metric to add. */ public open fun addMetric(metric: IMetric) { unwrap(this).addMetric(metric.let(IMetric.Companion::unwrap)) } /** * Return the widget JSON for use in the dashboard. */ public override fun toJson(): List<Any> = unwrap(this).toJson() /** * A fluent builder for [io.cloudshiftdev.awscdk.services.cloudwatch.GaugeWidget]. */ @CdkDslMarker public interface Builder { /** * Annotations for the left Y axis. * * Default: - No annotations * * @param annotations Annotations for the left Y axis. */ public fun annotations(annotations: List<HorizontalAnnotation>) /** * Annotations for the left Y axis. * * Default: - No annotations * * @param annotations Annotations for the left Y axis. */ public fun annotations(vararg annotations: HorizontalAnnotation) /** * The end of the time range to use for each widget independently from those of the dashboard. * * If you specify a value for end, you must also specify a value for start. * Specify an absolute time in the ISO 8601 format. For example, 2018-12-17T06:00:00.000Z. * * Default: When the dashboard loads, the end date will be the current time. * * @param end The end of the time range to use for each widget independently from those of the * dashboard. */ public fun end(end: String) /** * Height of the widget. * * Default: - 6 for Alarm and Graph widgets. * 3 for single value widgets where most recent value of a metric is displayed. * * @param height Height of the widget. */ public fun height(height: Number) /** * Left Y axis. * * Default: - None * * @param leftYAxis Left Y axis. */ public fun leftYAxis(leftYAxis: YAxisProps) /** * Left Y axis. * * Default: - None * * @param leftYAxis Left Y axis. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("1ea22e824d60340f70a8c7b8af9dca98342321dd5906ff9f481b308e4fe2abe1") public fun leftYAxis(leftYAxis: YAxisProps.Builder.() -> Unit) /** * Position of the legend. * * Default: - bottom * * @param legendPosition Position of the legend. */ public fun legendPosition(legendPosition: LegendPosition) /** * Whether the graph should show live data. * * Default: false * * @param liveData Whether the graph should show live data. */ public fun liveData(liveData: Boolean) /** * Metrics to display on left Y axis. * * Default: - No metrics * * @param metrics Metrics to display on left Y axis. */ public fun metrics(metrics: List<IMetric>) /** * Metrics to display on left Y axis. * * Default: - No metrics * * @param metrics Metrics to display on left Y axis. */ public fun metrics(vararg metrics: IMetric) /** * The default period for all metrics in this widget. * * The period is the length of time represented by one data point on the graph. * This default can be overridden within each metric definition. * * Default: cdk.Duration.seconds(300) * * @param period The default period for all metrics in this widget. */ public fun period(period: Duration) /** * Whether to show the value from the entire time range. Only applicable for Bar and Pie charts. * * If false, values will be from the most recent period of your chosen time range; * if true, shows the value from the entire time range. * * Default: false * * @param setPeriodToTimeRange Whether to show the value from the entire time range. Only * applicable for Bar and Pie charts. */ public fun periodToTimeRange(setPeriodToTimeRange: Boolean) /** * The region the metrics of this graph should be taken from. * * Default: - Current region * * @param region The region the metrics of this graph should be taken from. */ public fun region(region: String) /** * The start of the time range to use for each widget independently from those of the dashboard. * * You can specify start without specifying end to specify a relative time range that ends with * the current time. * In this case, the value of start must begin with -P, and you can use M, H, D, W and M as * abbreviations for * minutes, hours, days, weeks and months. For example, -PT8H shows the last 8 hours and -P3M * shows the last three months. * You can also use start along with an end field, to specify an absolute time range. * When specifying an absolute time range, use the ISO 8601 format. For example, * 2018-12-17T06:00:00.000Z. * * Default: When the dashboard loads, the start time will be the default time range. * * @param start The start of the time range to use for each widget independently from those of * the dashboard. */ public fun start(start: String) /** * The default statistic to be displayed for each metric. * * This default can be overridden within the definition of each individual metric * * Default: - The statistic for each metric is used * * @param statistic The default statistic to be displayed for each metric. */ public fun statistic(statistic: String) /** * Title for the graph. * * Default: - None * * @param title Title for the graph. */ public fun title(title: String) /** * Width of the widget, in a grid of 24 units wide. * * Default: 6 * * @param width Width of the widget, in a grid of 24 units wide. */ public fun width(width: Number) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.cloudwatch.GaugeWidget.Builder = software.amazon.awscdk.services.cloudwatch.GaugeWidget.Builder.create() /** * Annotations for the left Y axis. * * Default: - No annotations * * @param annotations Annotations for the left Y axis. */ override fun annotations(annotations: List<HorizontalAnnotation>) { cdkBuilder.annotations(annotations.map(HorizontalAnnotation.Companion::unwrap)) } /** * Annotations for the left Y axis. * * Default: - No annotations * * @param annotations Annotations for the left Y axis. */ override fun annotations(vararg annotations: HorizontalAnnotation): Unit = annotations(annotations.toList()) /** * The end of the time range to use for each widget independently from those of the dashboard. * * If you specify a value for end, you must also specify a value for start. * Specify an absolute time in the ISO 8601 format. For example, 2018-12-17T06:00:00.000Z. * * Default: When the dashboard loads, the end date will be the current time. * * @param end The end of the time range to use for each widget independently from those of the * dashboard. */ override fun end(end: String) { cdkBuilder.end(end) } /** * Height of the widget. * * Default: - 6 for Alarm and Graph widgets. * 3 for single value widgets where most recent value of a metric is displayed. * * @param height Height of the widget. */ override fun height(height: Number) { cdkBuilder.height(height) } /** * Left Y axis. * * Default: - None * * @param leftYAxis Left Y axis. */ override fun leftYAxis(leftYAxis: YAxisProps) { cdkBuilder.leftYAxis(leftYAxis.let(YAxisProps.Companion::unwrap)) } /** * Left Y axis. * * Default: - None * * @param leftYAxis Left Y axis. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("1ea22e824d60340f70a8c7b8af9dca98342321dd5906ff9f481b308e4fe2abe1") override fun leftYAxis(leftYAxis: YAxisProps.Builder.() -> Unit): Unit = leftYAxis(YAxisProps(leftYAxis)) /** * Position of the legend. * * Default: - bottom * * @param legendPosition Position of the legend. */ override fun legendPosition(legendPosition: LegendPosition) { cdkBuilder.legendPosition(legendPosition.let(LegendPosition.Companion::unwrap)) } /** * Whether the graph should show live data. * * Default: false * * @param liveData Whether the graph should show live data. */ override fun liveData(liveData: Boolean) { cdkBuilder.liveData(liveData) } /** * Metrics to display on left Y axis. * * Default: - No metrics * * @param metrics Metrics to display on left Y axis. */ override fun metrics(metrics: List<IMetric>) { cdkBuilder.metrics(metrics.map(IMetric.Companion::unwrap)) } /** * Metrics to display on left Y axis. * * Default: - No metrics * * @param metrics Metrics to display on left Y axis. */ override fun metrics(vararg metrics: IMetric): Unit = metrics(metrics.toList()) /** * The default period for all metrics in this widget. * * The period is the length of time represented by one data point on the graph. * This default can be overridden within each metric definition. * * Default: cdk.Duration.seconds(300) * * @param period The default period for all metrics in this widget. */ override fun period(period: Duration) { cdkBuilder.period(period.let(Duration.Companion::unwrap)) } /** * Whether to show the value from the entire time range. Only applicable for Bar and Pie charts. * * If false, values will be from the most recent period of your chosen time range; * if true, shows the value from the entire time range. * * Default: false * * @param setPeriodToTimeRange Whether to show the value from the entire time range. Only * applicable for Bar and Pie charts. */ override fun periodToTimeRange(setPeriodToTimeRange: Boolean) { cdkBuilder.setPeriodToTimeRange(setPeriodToTimeRange) } /** * The region the metrics of this graph should be taken from. * * Default: - Current region * * @param region The region the metrics of this graph should be taken from. */ override fun region(region: String) { cdkBuilder.region(region) } /** * The start of the time range to use for each widget independently from those of the dashboard. * * You can specify start without specifying end to specify a relative time range that ends with * the current time. * In this case, the value of start must begin with -P, and you can use M, H, D, W and M as * abbreviations for * minutes, hours, days, weeks and months. For example, -PT8H shows the last 8 hours and -P3M * shows the last three months. * You can also use start along with an end field, to specify an absolute time range. * When specifying an absolute time range, use the ISO 8601 format. For example, * 2018-12-17T06:00:00.000Z. * * Default: When the dashboard loads, the start time will be the default time range. * * @param start The start of the time range to use for each widget independently from those of * the dashboard. */ override fun start(start: String) { cdkBuilder.start(start) } /** * The default statistic to be displayed for each metric. * * This default can be overridden within the definition of each individual metric * * Default: - The statistic for each metric is used * * @param statistic The default statistic to be displayed for each metric. */ override fun statistic(statistic: String) { cdkBuilder.statistic(statistic) } /** * Title for the graph. * * Default: - None * * @param title Title for the graph. */ override fun title(title: String) { cdkBuilder.title(title) } /** * Width of the widget, in a grid of 24 units wide. * * Default: 6 * * @param width Width of the widget, in a grid of 24 units wide. */ override fun width(width: Number) { cdkBuilder.width(width) } public fun build(): software.amazon.awscdk.services.cloudwatch.GaugeWidget = cdkBuilder.build() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): GaugeWidget { val builderImpl = BuilderImpl() return GaugeWidget(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.cloudwatch.GaugeWidget): GaugeWidget = GaugeWidget(cdkObject) internal fun unwrap(wrapped: GaugeWidget): software.amazon.awscdk.services.cloudwatch.GaugeWidget = wrapped.cdkObject as software.amazon.awscdk.services.cloudwatch.GaugeWidget } }
1
Kotlin
0
4
eb3eef728b34da593a3e55dc423d4f5fa3668e9c
14,459
kotlin-cdk-wrapper
Apache License 2.0
merlin-core/src/main/kotlin/de/micromata/merlin/excel/PoiHelper.kt
micromata
145,080,847
false
null
package de.micromata.merlin.excel import org.apache.poi.ss.usermodel.Cell import org.apache.poi.ss.usermodel.CellType import org.apache.poi.ss.usermodel.DataFormatter import org.apache.poi.ss.usermodel.DateUtil import org.slf4j.LoggerFactory import java.text.NumberFormat import java.time.LocalDateTime import java.util.* /** * Some helper classes. */ object PoiHelper { private val log = LoggerFactory.getLogger(PoiHelper::class.java) /** * @param locale Used for number format. * @param trimValue If true, the result string will be trimmed. Default is false. */ @JvmStatic @JvmOverloads fun getValueAsString(cell: Cell?, locale: Locale = Locale.getDefault(), trimValue: Boolean = false): String? { cell ?: return null val value = getValue(cell) ?: return null return when (value) { is String -> if (trimValue) value.trim { it <= ' ' } else value is Number -> NumberFormat.getInstance(locale).format(value) is LocalDateTime -> DataFormatter().formatCellValue(cell) else -> value.toString() } } /** * @param localDateTime If true, any dates will be returned as [LocalDateTime], otherwise as [java.util.Date] */ @JvmStatic @JvmOverloads fun getValue(cell: Cell?, localDateTime: Boolean = true): Any? { return if (cell == null) { null } else when (cell.cellType) { CellType.BOOLEAN -> cell.booleanCellValue CellType.NUMERIC -> { if (DateUtil.isCellDateFormatted(cell)) { if (localDateTime) cell.localDateTimeCellValue else cell.dateCellValue } else cell.numericCellValue } CellType.STRING -> cell.stringCellValue CellType.BLANK -> null else -> { log.warn("Unsupported Excel cell type: " + cell.cellType) getValueAsString(cell) } } } @JvmStatic fun isEmpty(cell: Cell?): Boolean { if (cell == null) { return true } if (cell.cellType == CellType.BLANK) { return true } return cell.cellType == CellType.STRING && cell.stringCellValue.trim { it <= ' ' }.isEmpty() } @JvmStatic @JvmOverloads fun setComment(cell: ExcelCell, message: String?, author: String? = null) { setComment(cell.cell, message, author) } @JvmStatic @JvmOverloads fun setComment(cell: Cell, message: String?, author: String? = null) { val actComment = cell.cellComment if (actComment != null) { log.error("Cell comment does already exist. Can't add cell comment twice.") return } val drawing = cell.sheet.createDrawingPatriarch() val factory = cell.sheet.workbook.creationHelper // When the comment box is visible, have it show in a 1x3 space val anchor = factory.createClientAnchor() anchor.setCol1(cell.columnIndex) anchor.setCol2(cell.columnIndex + 3) anchor.row1 = cell.rowIndex anchor.row2 = cell.rowIndex + 3 // Create the comment and set the text+author val comment = drawing.createCellComment(anchor) val str = factory.createRichTextString(message) comment.string = str if (!author.isNullOrBlank()) comment.author = author // Assign the comment to the cell cell.cellComment = comment } }
5
null
4
16
091890ab85f625f76216aacda4b4ce04e42ad98e
3,585
Merlin
Apache License 2.0
data/src/main/java/com/ravnnerdery/data/di/DatabaseModule.kt
hunter4466
469,840,001
false
{"Kotlin": 39470}
package com.ravnnerdery.data.di import android.content.Context import androidx.room.Room import com.ravnnerdery.data.database.DatabaseDao import com.ravnnerdery.data.database.DbWrapper import com.ravnnerdery.data.database.DbWrapperImpl import com.ravnnerdery.data.database.MessagesDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton private const val CHAT_CHALLENGE_DATABASE = "Chat_challenge_db" @InstallIn(SingletonComponent::class) @Module class DatabaseModule { @Provides @Singleton fun provideDatabaseDao(articlesDatabase: MessagesDatabase): DatabaseDao { return articlesDatabase.databaseDao() } @Provides @Singleton fun provideMessagesDatabase(@ApplicationContext appContext: Context): MessagesDatabase { return Room.databaseBuilder( appContext, MessagesDatabase::class.java, CHAT_CHALLENGE_DATABASE ) .fallbackToDestructiveMigration() .build() } @Provides @Singleton fun provideDbWrapper( dbWrapperImpl: DbWrapperImpl ): DbWrapper { return dbWrapperImpl } }
0
Kotlin
0
0
8460b3215b08b832c0874cd613b84fc60a669953
1,289
chat_challenge
MIT License
app/src/main/java/com/example/reciepe_app_kt/domain/model/Recipe.kt
Jatin-Shihora
446,821,502
false
null
package xyz.teamgravity.composerecipeapp.model import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class RecipeModel( val id: Int? = null, val title: String? = null, val publisher: String? = null, val featuredImage: String? = null, val rating: Int? = 0, val sourceUrl: String? = null, val description: String? = null, val cookingInstructions: String? = null, val ingredients: List<String> = listOf(), val dateAdded: String? = null, val dateUpdated: String? = null ) : Parcelable
0
Kotlin
0
1
42fe7623f80c70d00f177c313f0be26ada6a48a3
554
Recipe-App
Apache License 2.0
app/src/main/java/ir/mahdi/circulars/IntroActivity.kt
ghost1372
243,591,964
false
null
package ir.mahdi.circulars import android.content.Context import android.content.Intent import android.os.Bundle import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.view.Window import android.view.WindowManager import android.widget.ImageView import android.widget.LinearLayout import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.get import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.button.MaterialButton import com.google.android.material.textview.MaterialTextView import io.github.inflationx.viewpump.ViewPumpContextWrapper import ir.mahdi.circulars.Adapter.IntroSliderAdapter import ir.mahdi.circulars.Helper.Prefs import ir.mahdi.circulars.Model.IntroSliderModel class IntroActivity : AppCompatActivity() { lateinit var introSliderViewPager: ViewPager2 lateinit var indicatorsContainer: LinearLayout lateinit var btnNext: MaterialButton lateinit var txtSkip: MaterialTextView private val introSliderAdapter = IntroSliderAdapter( listOf( IntroSliderModel( "به اپلیکیشن بخشنامه خوش آمدید", "دریافت بخشنامه های آموزش و پرورش در گوشی همراه شما", R.drawable.appicon ), IntroSliderModel( "ساده، سریع، زیبا", "در یک محیط ساده و زیبا به سرعت بخشنامه های منطقه دلخواهت رو دریافت و مشاهده کن", R.drawable.slider1 ), IntroSliderModel( "پشتیبانی از وزارت و شهرستان ها", "بخشنامه های وزارت آموزش پرورش و تمامی شهرستان هایی که بصورت آنلاین بخشنامه ها رو قرار میدن قابل دریافته", R.drawable.slider2 ), IntroSliderModel( "مشاهده آفلاین", "بعد از دانلود بدون نیاز به اینترنت بخشنامه ها رو مشاهده کن", R.drawable.slider3 ), IntroSliderModel( "اشتراک گذاری", "بخشنامه دلخواهت رو با دیگران به اشتراک بزار", R.drawable.slider4 ), IntroSliderModel( "پشتیبانی سریع", "مشکل داری؟ ما در سریعترین زمان به سوالاتت پاسخ میدیم", R.drawable.slider5 ) ) ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Prefs(applicationContext).getIsFirstRun()){ requestWindowFeature(Window.FEATURE_NO_TITLE) window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN) setContentView(R.layout.intro_activity) initIntro() }else{ startMainActivity() } } fun initIntro(){ introSliderViewPager = findViewById(R.id.introSliderViewPager) indicatorsContainer = findViewById(R.id.indicatorsContainer) btnNext = findViewById(R.id.buttonNext) txtSkip = findViewById(R.id.textSkipIntro) introSliderViewPager.adapter = introSliderAdapter setupIndicators() setCurrentIndicator(0) introSliderViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){ override fun onPageSelected(position: Int) { super.onPageSelected(position) setCurrentIndicator(position) } }) btnNext.setOnClickListener{ if (introSliderViewPager.currentItem + 1 < introSliderAdapter.itemCount){ introSliderViewPager.currentItem += 1 }else{ startMainActivity() } } txtSkip.setOnClickListener{ startMainActivity() } } fun startMainActivity(){ Intent(applicationContext, MainActivity::class.java).also { startActivity(it) finish() } } fun setupIndicators(){ val indicators = arrayOfNulls<ImageView>(introSliderAdapter.itemCount) val layoutParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT) layoutParams.setMargins(8,0,8,0) for (i in indicators.indices){ indicators[i] = ImageView(applicationContext) indicators[i].apply { this?.setImageDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.indicator_inactive) ) this?.layoutParams = layoutParams } indicatorsContainer.addView(indicators[i]) } } fun setCurrentIndicator(index: Int){ val childCount = indicatorsContainer.childCount for (i in 0 until childCount){ val imageView = indicatorsContainer[i] as ImageView if (i == index){ imageView.setImageDrawable( ContextCompat.getDrawable( applicationContext, R.drawable.indicator_active) ) }else{ imageView.setImageDrawable( ContextCompat.getDrawable( applicationContext, R.drawable.indicator_inactive) ) } } } // Set Application Font override fun attachBaseContext(newBase: Context?) { super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase!!)) } }
0
null
1
8
73480a524b651711cc1d51a06859beba63c6ba9a
5,523
Circulars
MIT License
app/src/main/java/com/udeshcoffee/android/data/remote/itunes/SearchResponse.kt
m760622
163,887,222
true
{"Kotlin": 579238, "Java": 35200, "HTML": 12682}
package com.udeshcoffee.android.data.remote.itunes import com.google.gson.annotations.SerializedName /** * Created by Udathari on 12/5/2017. */ class SearchResponse( @SerializedName("resultCount") var resultCount: Int = 0, @SerializedName("results") var results: List<Results>? = null ) { class Results { @SerializedName("wrapperType") var wrapperType: String? = null @SerializedName("kind") var kind: String? = null @SerializedName("artistId") var artistId: Int = 0 @SerializedName("collectionId") var collectionId: Int = 0 @SerializedName("trackId") var trackId: Int = 0 @SerializedName("artistName") var artistName: String? = null @SerializedName("collectionName") var collectionName: String? = null @SerializedName("trackName") var trackName: String? = null @SerializedName("collectionCensoredName") var collectionCensoredName: String? = null @SerializedName("trackCensoredName") var trackCensoredName: String? = null @SerializedName("artistViewUrl") var artistViewUrl: String? = null @SerializedName("collectionViewUrl") var collectionViewUrl: String? = null @SerializedName("trackViewUrl") var trackViewUrl: String? = null @SerializedName("previewUrl") var previewUrl: String? = null @SerializedName("artworkUrl30") var artworkUrl30: String? = null @SerializedName("artworkUrl60") var artworkUrl60: String? = null @SerializedName("artworkUrl100") var artworkUrl100: String? = null @SerializedName("collectionPrice") var collectionPrice: Double = 0.toDouble() @SerializedName("trackPrice") var trackPrice: Double = 0.toDouble() @SerializedName("releaseDate") var releaseDate: String? = null @SerializedName("collectionExplicitness") var collectionExplicitness: String? = null @SerializedName("trackExplicitness") var trackExplicitness: String? = null @SerializedName("discCount") var discCount: Int = 0 @SerializedName("discNumber") var discNumber: Int = 0 @SerializedName("trackCount") var trackCount: Int = 0 @SerializedName("trackNumber") var trackNumber: Int = 0 @SerializedName("trackTimeMillis") var trackTimeMillis: Int = 0 @SerializedName("country") var country: String? = null @SerializedName("currency") var currency: String? = null @SerializedName("primaryGenreName") var primaryGenreName: String? = null @SerializedName("isStreamable") var isStreamable: Boolean = false } }
0
Kotlin
1
1
928bd65fd6064a26cbb758a0604ed5718a1ea55f
2,833
CoffeeMusicPlayer
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/models/ForecastViewModel.kt
tritter
349,919,462
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.models import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch class ForecastViewModel : ViewModel() { var dayViewModels by mutableStateOf(emptyList<DayRowViewModel>()) var location by mutableStateOf("") init { viewModelScope.launch { fetchData() } } private fun fetchData() { val appointments = generateAppointments() val forecast = generateForecast() location = forecast.location dayViewModels = forecast.days.map { DayRowViewModel(it, appointments) } } }
0
Kotlin
0
1
3e6c1190b97ac47e838461e4aabf4ddd825e82c0
1,385
android-dev-challenge-weather
Apache License 2.0
rxhttp-compiler/src/main/java/com/rxhttp/compiler/ksp/RxHttpGenerator.kt
liujingxing
167,158,553
false
null
package com.rxhttp.compiler.ksp import com.google.devtools.ksp.KspExperimental import com.google.devtools.ksp.processing.CodeGenerator import com.google.devtools.ksp.processing.Dependencies import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.symbol.KSFile import com.rxhttp.compiler.RXHttp import com.rxhttp.compiler.getKClassName import com.rxhttp.compiler.isDependenceRxJava import com.rxhttp.compiler.rxHttpPackage import com.rxhttp.compiler.rxhttpKClassName import com.squareup.kotlinpoet.ANY import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.BOOLEAN import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.LIST import com.squareup.kotlinpoet.LONG import com.squareup.kotlinpoet.MAP import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.STRING import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.TypeVariableName import com.squareup.kotlinpoet.WildcardTypeName import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.jvm.throws import com.squareup.kotlinpoet.ksp.writeTo import java.io.IOException class RxHttpGenerator( private val logger: KSPLogger, private val ksFiles: Collection<KSFile> ) { var paramsVisitor: ParamsVisitor? = null var parserVisitor: ParserVisitor? = null var domainVisitor: DomainVisitor? = null var converterVisitor: ConverterVisitor? = null var okClientVisitor: OkClientVisitor? = null var defaultDomainVisitor: DefaultDomainVisitor? = null //生成RxHttp类 @KspExperimental @Throws(IOException::class) fun generateCode(codeGenerator: CodeGenerator) { val paramClassName = ClassName("rxhttp.wrapper.param", "Param") val typeVariableP = TypeVariableName("P", paramClassName.parameterizedBy("P")) //泛型P val typeVariableR = TypeVariableName("R", rxhttpKClassName.parameterizedBy("P","R")) //泛型R val okHttpClientName = ClassName("okhttp3", "OkHttpClient") val requestName = ClassName("okhttp3", "Request") val headerName = ClassName("okhttp3", "Headers") val headerBuilderName = ClassName("okhttp3", "Headers.Builder") val cacheControlName = ClassName("okhttp3", "CacheControl") val callName = ClassName("okhttp3", "Call") val responseName = ClassName("okhttp3", "Response") val timeUnitName = ClassName("java.util.concurrent", "TimeUnit") val rxHttpPluginsName = ClassName("rxhttp", "RxHttpPlugins") val converterName = ClassName("rxhttp.wrapper.callback", "IConverter") val cacheInterceptorName = ClassName("rxhttp.wrapper.intercept", "CacheInterceptor") val cacheModeName = ClassName("rxhttp.wrapper.cahce", "CacheMode") val cacheStrategyName = ClassName("rxhttp.wrapper.cahce", "CacheStrategy") val downloadOffSizeName = ClassName("rxhttp.wrapper.entity", "DownloadOffSize") val t = TypeVariableName("T") val className = Class::class.asClassName() val superT = WildcardTypeName.consumerOf(t) val classTName = className.parameterizedBy("T") val classSuperTName = className.parameterizedBy(superT) val wildcard = TypeVariableName("*") val listName = LIST.parameterizedBy("*") val mapName = MAP.parameterizedBy(STRING, wildcard) val mapStringName = MAP.parameterizedBy(STRING, STRING) val listTName = LIST.parameterizedBy("T") val parserName = ClassName("rxhttp.wrapper.parse", "Parser") val progressName = ClassName("rxhttp.wrapper.entity", "Progress") val logUtilName = ClassName("rxhttp.wrapper.utils", "LogUtil") val logInterceptorName = ClassName("rxhttp.wrapper.intercept", "LogInterceptor") val parserTName = parserName.parameterizedBy("T") val simpleParserName = ClassName("rxhttp.wrapper.parse", "SimpleParser") val parameterizedType = ClassName("rxhttp.wrapper.entity", "ParameterizedTypeImpl") val methodList = ArrayList<FunSpec>() //方法集合 //添加构造方法 val constructorFun = FunSpec.constructorBuilder() .addModifiers(KModifier.PROTECTED) .addParameter("param", typeVariableP) .build() val propertySpecs = mutableListOf<PropertySpec>() PropertySpec.builder("connectTimeoutMillis", LONG, KModifier.PRIVATE) .initializer("0L") .mutable(true) .build() .let { propertySpecs.add(it) } PropertySpec.builder("readTimeoutMillis", LONG, KModifier.PRIVATE) .initializer("0L") .mutable(true) .build() .let { propertySpecs.add(it) } PropertySpec.builder("writeTimeoutMillis", LONG, KModifier.PRIVATE) .initializer("0L") .mutable(true) .build() .let { propertySpecs.add(it) } PropertySpec.builder("converter", converterName, KModifier.PRIVATE) .mutable(true) .initializer("%T.getConverter()", rxHttpPluginsName) .build() .let { propertySpecs.add(it) } PropertySpec.builder("okClient", okHttpClientName, KModifier.PRIVATE) .mutable(true) .initializer("%T.getOkHttpClient()", rxHttpPluginsName) .build() .let { propertySpecs.add(it) } PropertySpec.builder("isAsync", BOOLEAN, KModifier.PROTECTED) .mutable(true) .initializer("true") .build() .let { propertySpecs.add(it) } PropertySpec.builder("param", typeVariableP) .initializer("param") .build() .let { propertySpecs.add(it) } PropertySpec.builder("request", requestName.copy(true)) .mutable(true) .initializer("null") .build() .let { propertySpecs.add(it) } val getUrlFun = FunSpec.getterBuilder() .addStatement("addDefaultDomainIfAbsent()") .addStatement("return param.getUrl()") .build() PropertySpec.builder("url", STRING) .addAnnotation(getJvmName("getUrl")) .getter(getUrlFun) .build() .let { propertySpecs.add(it) } val simpleUrlFun = FunSpec.getterBuilder() .addStatement("return param.getSimpleUrl()") .build() PropertySpec.builder("simpleUrl", STRING) .addAnnotation(getJvmName("getSimpleUrl")) .getter(simpleUrlFun) .build() .let { propertySpecs.add(it) } val headersFun = FunSpec.getterBuilder() .addStatement("return param.getHeaders()") .build() PropertySpec.builder("headers", headerName) .addAnnotation(getJvmName("getHeaders")) .getter(headersFun) .build() .let { propertySpecs.add(it) } val headersBuilderFun = FunSpec.getterBuilder() .addStatement("return param.getHeadersBuilder()") .build() PropertySpec.builder("headersBuilder", headerBuilderName) .addAnnotation(getJvmName("getHeadersBuilder")) .getter(headersBuilderFun) .build() .let { propertySpecs.add(it) } val cacheStrategyFun = FunSpec.getterBuilder() .addStatement("return param.getCacheStrategy()") .build() PropertySpec.builder("cacheStrategy", cacheStrategyName) .addAnnotation(getJvmName("getCacheStrategy")) .getter(cacheStrategyFun) .build() .let { propertySpecs.add(it) } val okClientFun = FunSpec.getterBuilder() .addCode( """ if (_okHttpClient != null) return _okHttpClient!! val okClient = this.okClient var builder : OkHttpClient.Builder? = null if (%T.isDebug()) { val b = builder ?: okClient.newBuilder().also { builder = it } b.addInterceptor(%T(okClient)) } if (connectTimeoutMillis != 0L) { val b = builder ?: okClient.newBuilder().also { builder = it } b.connectTimeout(connectTimeoutMillis, %T.MILLISECONDS) } if (readTimeoutMillis != 0L) { val b = builder ?: okClient.newBuilder().also { builder = it } b.readTimeout(readTimeoutMillis, %T.MILLISECONDS) } if (writeTimeoutMillis != 0L) { val b = builder ?: okClient.newBuilder().also { builder = it } b.writeTimeout(writeTimeoutMillis, %T.MILLISECONDS) } if (param.getCacheMode() != CacheMode.ONLY_NETWORK) { val b = builder ?: okClient.newBuilder().also { builder = it } b.addInterceptor(%T(cacheStrategy)) } _okHttpClient = builder?.build() ?: okClient return _okHttpClient!! """.trimIndent(), logUtilName, logInterceptorName, timeUnitName, timeUnitName, timeUnitName, cacheInterceptorName ) .build() PropertySpec.builder("_okHttpClient", okHttpClientName.copy(true), KModifier.PRIVATE) .mutable(true) .initializer("null") .build() .let { propertySpecs.add(it) } PropertySpec.builder("okHttpClient", okHttpClientName) .addAnnotation(getJvmName("getOkHttpClient")) .getter(okClientFun) .build() .let { propertySpecs.add(it) } FunSpec.builder("connectTimeout") .addParameter("connectTimeout", LONG) .addStatement("connectTimeoutMillis = connectTimeout") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("readTimeout") .addParameter("readTimeout", LONG) .addStatement("readTimeoutMillis = readTimeout") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("writeTimeout") .addParameter("writeTimeout", LONG) .addStatement("writeTimeoutMillis = writeTimeout") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } val methodMap = LinkedHashMap<String, String>() methodMap["get"] = "RxHttpNoBodyParam" methodMap["head"] = "RxHttpNoBodyParam" methodMap["postBody"] = "RxHttpBodyParam" methodMap["putBody"] = "RxHttpBodyParam" methodMap["patchBody"] = "RxHttpBodyParam" methodMap["deleteBody"] = "RxHttpBodyParam" methodMap["postForm"] = "RxHttpFormParam" methodMap["putForm"] = "RxHttpFormParam" methodMap["patchForm"] = "RxHttpFormParam" methodMap["deleteForm"] = "RxHttpFormParam" methodMap["postJson"] = "RxHttpJsonParam" methodMap["putJson"] = "RxHttpJsonParam" methodMap["patchJson"] = "RxHttpJsonParam" methodMap["deleteJson"] = "RxHttpJsonParam" methodMap["postJsonArray"] = "RxHttpJsonArrayParam" methodMap["putJsonArray"] = "RxHttpJsonArrayParam" methodMap["patchJsonArray"] = "RxHttpJsonArrayParam" methodMap["deleteJsonArray"] = "RxHttpJsonArrayParam" val codeBlock = """ For example: ``` RxHttp.get("/service/%L/...", 1) .addQuery("size", 20) ... ``` url = /service/1/...?size=20 """.trimIndent() val companionBuilder = TypeSpec.companionObjectBuilder() for ((key, value) in methodMap) { val methodBuilder = FunSpec.builder(key) if (key == "get") { methodBuilder.addKdoc(codeBlock, "%d") } methodBuilder.addAnnotation(JvmStatic::class) .addParameter("url", STRING) .addParameter("formatArgs", ANY, true, KModifier.VARARG) .addStatement( "return $value(%T.${key}(format(url, *formatArgs)))", paramClassName, ) .build() .let { companionBuilder.addFunction(it) } } paramsVisitor?.apply { companionBuilder.addFunctions(getFunList(codeGenerator)) } FunSpec.builder("format") .addKdoc("Returns a formatted string using the specified format string and arguments.") .addModifiers(KModifier.PRIVATE) .addParameter("url", STRING) .addParameter("formatArgs", ANY, true, KModifier.VARARG) .addStatement("return if(formatArgs.isNullOrEmpty()) url else String.format(url, *formatArgs)") .build() .let { companionBuilder.addFunction(it) } FunSpec.builder("setUrl") .addParameter("url", STRING) .addStatement("param.setUrl(url)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addPath") .addKdoc( """ For example: ``` RxHttp.get("/service/{page}/...") .addPath("page", 1) ... ``` url = /service/1/... """.trimIndent() ) .addParameter("name", STRING) .addParameter("value", ANY) .addStatement("param.addPath(name, value)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addEncodedPath") .addParameter("name", STRING) .addParameter("value", ANY) .addStatement("param.addEncodedPath(name, value)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addQuery") .addParameter("key", STRING) .addStatement("param.addQuery(key, null)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addEncodedQuery") .addParameter("key", STRING) .addStatement("param.addEncodedQuery(key, null)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addQuery") .addParameter("key", STRING) .addParameter("value", ANY, true) .addStatement("param.addQuery(key, value)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addEncodedQuery") .addParameter("key", STRING) .addParameter("value", ANY, true) .addStatement("param.addEncodedQuery(key, value)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addAllQuery") .addParameter("key", STRING) .addParameter("list", listName) .addStatement("param.addAllQuery(key, list)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addAllEncodedQuery") .addParameter("key", STRING) .addParameter("list", listName) .addStatement("param.addAllEncodedQuery(key, list)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addAllQuery") .addParameter("map", mapName) .addStatement("param.addAllQuery(map)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addAllEncodedQuery") .addParameter("map", mapName) .addStatement("param.addAllEncodedQuery(map)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } val isAddParam = ParameterSpec.builder("isAdd", BOOLEAN) .defaultValue("true") .build() FunSpec.builder("addHeader") .addAnnotation(JvmOverloads::class) .addParameter("line", STRING) .addParameter(isAddParam) .addCode( """ if (isAdd) param.addHeader(line) return this as R """.trimIndent() ) .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addNonAsciiHeader") .addKdoc("Add a header with the specified name and value. Does validation of header names, allowing non-ASCII values.") .addParameter("key", STRING) .addParameter("value", STRING) .addStatement("param.addNonAsciiHeader(key,value)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("setNonAsciiHeader") .addKdoc("Set a header with the specified name and value. Does validation of header names, allowing non-ASCII values.") .addParameter("key", STRING) .addParameter("value", STRING) .addStatement("param.setNonAsciiHeader(key,value)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addHeader") .addAnnotation(JvmOverloads::class) .addParameter("key", STRING) .addParameter("value", STRING) .addParameter(isAddParam) .addCode( """ if (isAdd) param.addHeader(key, value) return this as R """.trimIndent() ) .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addAllHeader") .addParameter("headers", mapStringName) .addStatement("param.addAllHeader(headers)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("addAllHeader") .addParameter("headers", headerName) .addStatement("param.addAllHeader(headers)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("setHeader") .addParameter("key", STRING) .addParameter("value", STRING) .addStatement("param.setHeader(key,value)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("setAllHeader") .addParameter("headers", mapStringName) .addStatement("param.setAllHeader(headers)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } val endIndex = ParameterSpec.builder("endIndex", LONG) .defaultValue("-1L") .build() FunSpec.builder("setRangeHeader") .addAnnotation(JvmOverloads::class) .addParameter("startIndex", LONG) .addParameter(endIndex) .addStatement("return setRangeHeader(startIndex, endIndex, false)") .build() .let { methodList.add(it) } FunSpec.builder("setRangeHeader") .addParameter("startIndex", LONG) .addParameter("connectLastProgress", BOOLEAN) .addStatement("return setRangeHeader(startIndex, -1, connectLastProgress)") .build() .let { methodList.add(it) } FunSpec.builder("setRangeHeader") .addKdoc( """ 设置断点下载开始/结束位置 @param startIndex 断点下载开始位置 @param endIndex 断点下载结束位置,默认为-1,即默认结束位置为文件末尾 @param connectLastProgress 是否衔接上次的下载进度,该参数仅在带进度断点下载时生效 """.trimIndent() ) .addModifiers(KModifier.OVERRIDE) .addParameter("startIndex", LONG) .addParameter("endIndex", LONG) .addParameter("connectLastProgress", BOOLEAN) .addCode( """ param.setRangeHeader(startIndex, endIndex) if (connectLastProgress) param.tag(DownloadOffSize::class.java, %T(startIndex)) return this as R """.trimIndent(), downloadOffSizeName ) .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("removeAllHeader") .addParameter("key", STRING) .addStatement("param.removeAllHeader(key)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("setHeadersBuilder") .addParameter("builder", headerBuilderName) .addStatement("param.setHeadersBuilder(builder)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("setAssemblyEnabled") .addKdoc( """ 设置单个接口是否需要添加公共参数, 即是否回调通过{@link RxHttpPlugins#setOnParamAssembly(Function)}方法设置的接口,默认为true """.trimIndent() ) .addParameter("enabled", BOOLEAN) .addStatement("param.setAssemblyEnabled(enabled)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("setDecoderEnabled") .addKdoc( """ 设置单个接口是否需要对Http返回的数据进行解码/解密, 即是否回调通过{@link RxHttpPlugins#setResultDecoder(Function)}方法设置的接口,默认为true """.trimIndent() ) .addParameter("enabled", BOOLEAN) .addStatement( "param.addHeader(%T.DATA_DECRYPT, enabled.toString())", paramClassName ) .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("isAssemblyEnabled") .addStatement("return param.isAssemblyEnabled()") .build() .let { methodList.add(it) } FunSpec.builder("getHeader") .addParameter("key", STRING) .addStatement("return param.getHeader(key)") .build() .let { methodList.add(it) } FunSpec.builder("tag") .addParameter("tag", ANY) .addStatement("param.tag(tag)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("tag") .addTypeVariable(t) .addParameter("type", classSuperTName) .addParameter("tag", t) .addStatement("param.tag(type, tag)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("cacheControl") .addParameter("cacheControl", cacheControlName) .addStatement("param.cacheControl(cacheControl)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("setCacheKey") .addParameter("cacheKey", STRING) .addStatement("param.setCacheKey(cacheKey)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("setCacheValidTime") .addParameter("cacheValidTime", LONG) .addStatement("param.setCacheValidTime(cacheValidTime)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("setCacheMode") .addParameter("cacheMode", cacheModeName) .addStatement("param.setCacheMode(cacheMode)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("execute") .throws(IOException::class) .addStatement("return newCall().execute()") .returns(responseName) .build() .let { methodList.add(it) } FunSpec.builder("execute") .addTypeVariable(t) .throws(IOException::class) .addParameter("parser", parserTName) .addStatement("return parser.onParse(execute())") .returns(t) .build() .let { methodList.add(it) } FunSpec.builder("executeString") .throws(IOException::class) .addStatement("return executeClass(String::class.java)") .returns(STRING) .build() .let { methodList.add(it) } FunSpec.builder("executeList") .addTypeVariable(t) .throws(IOException::class) .addParameter("type", classTName) .addStatement("val tTypeList = %T.get(List::class.java, type)", parameterizedType) .addStatement("return execute(%T(tTypeList))", simpleParserName) .returns(listTName) .build() .let { methodList.add(it) } FunSpec.builder("executeClass") .addTypeVariable(t) .throws(IOException::class) .addParameter("type", classTName) .addStatement("return execute(%T(type))", simpleParserName) .returns(t) .build() .let { methodList.add(it) } FunSpec.builder("newCall") .addModifiers(KModifier.OVERRIDE) .addCode( """ val request = buildRequest() return okHttpClient.newCall(request) """.trimIndent() ) .returns(callName) .build() .let { methodList.add(it) } FunSpec.builder("buildRequest") .addCode( """ if (request == null) { doOnStart() request = param.buildRequest() } return request!! """.trimIndent() ) .returns(requestName) .build() .let { methodList.add(it) } FunSpec.builder("doOnStart") .addModifiers(KModifier.PRIVATE) .addKdoc("请求开始前内部调用,用于添加默认域名等操作\n") .addStatement("setConverterToParam(converter)") .addStatement("addDefaultDomainIfAbsent()") .build() .let { methodList.add(it) } if (isDependenceRxJava()) { val schedulerName = getKClassName("Scheduler") val observableName = getKClassName("Observable") val consumerName = getKClassName("Consumer") val deprecatedAnnotation = AnnotationSpec.builder(Deprecated::class) .addMember( """ "please use `setSync()` instead", ReplaceWith("setSync()"), DeprecationLevel.ERROR """.trimIndent() ) .build() FunSpec.builder("subscribeOnCurrent") .addAnnotation(deprecatedAnnotation) .addStatement("return setSync()") .build() .let { methodList.add(it) } FunSpec.builder("setSync") .addKdoc("sync request \n") .addStatement("isAsync = false") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } val observableTName = observableName.parameterizedBy(t) val consumerProgressName = consumerName.parameterizedBy(progressName) FunSpec.builder("asParser") .addModifiers(KModifier.OVERRIDE) .addTypeVariable(t) .addParameter("parser", parserTName) .addParameter("scheduler", schedulerName.copy(true)) .addParameter("progressConsumer", consumerProgressName.copy(true)) .addCode( """ val observableCall = if(isAsync) ObservableCallEnqueue(this) else ObservableCallExecute(this) return observableCall.asParser(parser, scheduler, progressConsumer) """.trimIndent() ) .returns(observableTName) .build() .let { methodList.add(it) } } parserVisitor?.apply { methodList.addAll(getFunList(codeGenerator)) } converterVisitor?.apply { methodList.addAll(getFunList()) } FunSpec.builder("setConverter") .addParameter("converter", converterName) .addCode( """ this.converter = converter return this as R """.trimIndent() ) .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("setConverterToParam") .addKdoc("给Param设置转换器,此方法会在请求发起前,被RxHttp内部调用\n") .addModifiers(KModifier.PRIVATE) .addParameter("converter", converterName) .addStatement("param.tag(IConverter::class.java, converter)") .addStatement("return this as R") .returns(typeVariableR) .build() .let { methodList.add(it) } FunSpec.builder("setOkClient") .addParameter("okClient", okHttpClientName) .addCode( """ this.okClient = okClient return this as R """.trimIndent() ) .returns(typeVariableR) .build() .let { methodList.add(it) } okClientVisitor?.apply { methodList.addAll(getFunList()) } defaultDomainVisitor?.apply { methodList.add(getFun()) } domainVisitor?.apply { methodList.addAll(getFunList()) } FunSpec.builder("setDomainIfAbsent") .addParameter("domain", STRING) .addCode( """ val newUrl = addDomainIfAbsent(param.getSimpleUrl(), domain) param.setUrl(newUrl) return this as R """.trimIndent() ) .returns(typeVariableR) .build() .let { methodList.add(it) } //对url添加域名方法 FunSpec.builder("addDomainIfAbsent") .addModifiers(KModifier.PRIVATE) .addParameter("url", STRING) .addParameter("domain", STRING) .addStatement( """ return if (url.startsWith("http")) { url } else if (url.startsWith("/")) { if (domain.endsWith("/")) domain + url.substring(1) else domain + url } else if (domain.endsWith("/")) { domain + url } else { domain + "/" + url } """.trimIndent() ) .returns(STRING) .build() .let { methodList.add(it) } val baseRxHttpName = ClassName(rxHttpPackage, "BaseRxHttp") val suppressAnnotation = AnnotationSpec.builder(Suppress::class) .addMember("\"UNCHECKED_CAST\", \"UPPER_BOUND_VIOLATED_BASED_ON_JAVA_ANNOTATIONS\"") .build() val rxHttpBuilder = TypeSpec.classBuilder(RXHttp) .addAnnotation(suppressAnnotation) .primaryConstructor(constructorFun) .addType(companionBuilder.build()) .addKdoc( """ Github https://github.com/liujingxing/rxhttp https://github.com/liujingxing/rxlife https://github.com/liujingxing/rxhttp/wiki/FAQ https://github.com/liujingxing/rxhttp/wiki/更新日志 """.trimIndent() ) .addModifiers(KModifier.OPEN) .addTypeVariable(typeVariableP) .addTypeVariable(typeVariableR) .superclass(baseRxHttpName) .addProperties(propertySpecs) .addFunctions(methodList) .build() val dependencies = Dependencies(true, *ksFiles.toTypedArray()) FileSpec.builder(rxHttpPackage, RXHttp) .addType(rxHttpBuilder) .build() .writeTo(codeGenerator, dependencies) } }
0
Kotlin
399
3,304
a8125226fc624a89240ae572d9b784e2d4c9d70e
35,365
rxhttp
Apache License 2.0
telegram-bot-core/src/main/kotlin/io/github/dehuckakpyt/telegrambot/model/telegram/internal/UnpinAllGeneralForumTopicMessages.kt
DEHuckaKpyT
670,859,055
false
null
package io.github.dehuckakpyt.telegrambot.model.telegram.`internal` import com.fasterxml.jackson.`annotation`.JsonProperty import kotlin.String /** * @author KScript */ internal data class UnpinAllChatMessages( @get:JsonProperty("chat_id") public val chatId: String, )
1
null
3
24
5912e61857da3f63a7bb383490730f47f7f1f8c6
281
telegram-bot
Apache License 2.0
telegram-bot-core/src/main/kotlin/io/github/dehuckakpyt/telegrambot/model/telegram/internal/UnpinAllGeneralForumTopicMessages.kt
DEHuckaKpyT
670,859,055
false
null
package io.github.dehuckakpyt.telegrambot.model.telegram.`internal` import com.fasterxml.jackson.`annotation`.JsonProperty import kotlin.String /** * @author KScript */ internal data class UnpinAllChatMessages( @get:JsonProperty("chat_id") public val chatId: String, )
1
null
3
24
5912e61857da3f63a7bb383490730f47f7f1f8c6
281
telegram-bot
Apache License 2.0
retrofit2/src/main/java/com/rui/retrofit2/module/RetrofitModule.kt
nanfanglr
519,809,906
false
{"Kotlin": 103415}
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rui.retrofit2.module import android.content.res.AssetManager import com.google.gson.Gson import com.rui.retrofit2.ApiConfigurationLoader import com.rui.retrofit2.intercepter.AuthenticationInterceptor import dagger.Module import dagger.Provides import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Named import javax.inject.Singleton internal const val HTTP_LOGGING_INTERCEPTOR = "httpLoggingInterceptor" internal const val AUTHENTICATION_INTERCEPTOR = "AuthenticationInterceptor" internal const val API_CONFIGURATION_FILE = "apiConfiguration.json" internal const val BASE_URL = "BaseUrl" internal const val IS_DEBUG = "debug" internal const val TIMEOUT_CONFIG = (15 * 1000).toLong() @Module class RetrofitModule { @Provides @Named(HTTP_LOGGING_INTERCEPTOR) internal fun providesHttpLoggingInterceptor( @Named(IS_DEBUG) isDebug: Boolean ): Interceptor { val interceptor = HttpLoggingInterceptor() if (isDebug) { interceptor.level = HttpLoggingInterceptor.Level.BODY } else { interceptor.level = HttpLoggingInterceptor.Level.NONE } return interceptor } @Provides @Singleton internal fun providesApiConfigurationLoader( assetManager: AssetManager, gson: Gson ): ApiConfigurationLoader { return ApiConfigurationLoader(assetManager, gson) } @Provides @Named(BASE_URL) internal fun providesBaseUrl( apiConfigurationLoader: ApiConfigurationLoader ): String { return apiConfigurationLoader.loadConfig(API_CONFIGURATION_FILE)?.host ?: "" } @Provides internal fun providesGson(): Gson = Gson() @Provides @Singleton internal fun provideOkHttpClient( @Named(HTTP_LOGGING_INTERCEPTOR) httpLoggingInterceptor: Interceptor, @Named(AUTHENTICATION_INTERCEPTOR) authenticationInterceptor: Interceptor ): OkHttpClient { val okHttpBuilder = OkHttpClient.Builder().apply { connectTimeout(TIMEOUT_CONFIG, TimeUnit.MILLISECONDS) writeTimeout(TIMEOUT_CONFIG, TimeUnit.MILLISECONDS) readTimeout(TIMEOUT_CONFIG, TimeUnit.MILLISECONDS) // Adds authentication headers when required in network calls addInterceptor(authenticationInterceptor) // Logs network calls for debug builds addInterceptor(httpLoggingInterceptor) } return okHttpBuilder.build() } @Provides @Singleton internal fun providesRetrofit( okHttpClient: OkHttpClient, @Named(BASE_URL) baseUrl: String, @Named(IS_DEBUG) isDebug: Boolean ): Retrofit { return Retrofit.Builder() .baseUrl(baseUrl) .validateEagerly(isDebug)// Fail early: check Retrofit configuration at creation time in Debug build. .addConverterFactory(GsonConverterFactory.create()) // .addConverterFactory(MyGsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(okHttpClient) .build() } @Provides @Named(AUTHENTICATION_INTERCEPTOR) internal fun providesAuthenticationInterceptor(): Interceptor { return AuthenticationInterceptor() } }
0
Kotlin
0
0
85eafb6c1a7b02dc68bf31df0957128424933d14
4,175
android-kotlin-mvvm-v2
Apache License 2.0
modules/kenerator/configuration/src/main/kotlin/com/flipperdevices/ifrmvp/generator/config/device/api/DefaultDeviceConfigGenerator.kt
flipperdevices
824,125,673
false
{"Kotlin": 146248, "Dockerfile": 695}
package com.flipperdevices.ifrmvp.generator.config.device.api import com.flipperdevices.ifrmvp.backend.model.DeviceConfiguration import com.flipperdevices.ifrmvp.generator.config.device.api.DeviceKeyNamesProvider.Companion.getKey import com.flipperdevices.ifrmvp.model.IfrKeyIdentifier import com.flipperdevices.infrared.editor.encoding.ByteArrayEncoder import com.flipperdevices.infrared.editor.encoding.JvmEncoder import com.flipperdevices.infrared.editor.encoding.InfraredRemoteEncoder import java.io.File class DefaultDeviceConfigGenerator(private val keyNamesProvider: DeviceKeyNamesProvider) : DeviceConfigGenerator { override fun generate(irFile: File): DeviceConfiguration { val remotes = DeviceConfigGenerator.parseRemotes(irFile) val deviceKeyToInstance = remotes.mapNotNull { val name = it.name val deviceKey = keyNamesProvider.getKey(name) ?: return@mapNotNull null val byteArray = InfraredRemoteEncoder.encode(it) val hash = JvmEncoder(ByteArrayEncoder.Algorithm.SHA_256).encode(byteArray) val identifier = IfrKeyIdentifier.Sha256(name = name, hash = hash) deviceKey to identifier }.associate { pair -> pair } return DeviceConfiguration(deviceKeyToInstance) } }
0
Kotlin
0
1
c789c5ebacb35902f9054fa5ff39d5563f3f585f
1,289
IRDB-Backend
MIT License
src/main/kotlin/net/transgene/mylittlebudget/tg/bot/commands/ExpenseCommand.kt
transgene
266,603,341
false
null
package net.transgene.mylittlebudget.tg.bot.commands import net.transgene.mylittlebudget.tg.bot.sheets.Cell import net.transgene.mylittlebudget.tg.bot.sheets.SheetsService class ExpenseCommand(private val sheetsService: SheetsService) : ExpenseIncomeCommand(sheetsService) { override fun getGroups(): List<Cell> = sheetsService.getExpenseGroups() override fun getFirstOperationInMonthMessage(amount: Long): String = "Поздравляю! Вы потратили $amount рублей на \"${chosenCategoryCell!!.name}\"." override fun getOperationMessage(amount: Long): String = "Поздравляю! Вы потратили еще $amount рублей на \"${chosenCategoryCell!!.name}\"." }
4
Kotlin
0
0
4aefe452d4eb35b016c10bb19abcd7702bd6fe18
670
mylittlebudget-bot-tg
MIT License
app/src/main/java/ru/gdlbo/parcelradar/app/core/network/api/request/Params.kt
gdlbo
839,512,469
false
{"Kotlin": 322281}
package ru.gdlbo.parcelradar.app.core.network.api.request interface Params
0
Kotlin
0
7
bffdef535d8056455568fc4ad3f2fb763509d89f
75
packageradar
MIT License
app/src/main/java/com/jsom/dentgame/SelectDevicesFragment.kt
JoseSom
795,326,369
false
{"Kotlin": 12575}
package com.jsom.dentgame import android.Manifest import android.R import android.bluetooth.BluetoothManager import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.jsom.dentgame.databinding.FragmentSelectDevicesBinding class SelectDevicesFragment : Fragment() { private lateinit var binding: FragmentSelectDevicesBinding private lateinit var viewModel: BaseViewModel lateinit var addressDevices: ArrayAdapter<String> lateinit var nameDevices: ArrayAdapter<String> lateinit var devices: Map<String,String> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val bluetoothManager = (requireContext().getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager) val factory = BaseViewModelFactory(BluetoothDispatcher(bluetoothManager)) viewModel = ViewModelProvider(requireActivity(), factory)[BaseViewModel::class.java] if (ActivityCompat.checkSelfPermission( requireContext(), Manifest.permission.BLUETOOTH_CONNECT ) == PackageManager.PERMISSION_DENIED ) { if (Build.VERSION.SDK_INT >= 31) { ActivityCompat.requestPermissions( requireActivity(), arrayOf(Manifest.permission.BLUETOOTH_CONNECT), 100 ) } } addressDevices = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1) nameDevices = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1) addressDevices.clear() nameDevices.clear() } private fun initListeners() { devices = viewModel.displayBluetoothDevices() binding.sdConnect.setOnClickListener { viewModel.checkBluetooth() if (binding.sdSpinner.selectedItem != null){ val nameDevice = binding.sdSpinner.selectedItem.toString() devices[nameDevice]?.let {mac-> viewModel.connectBluetooth(mac) } } } viewModel.isConnected.observe(viewLifecycleOwner){ isConnected -> if (isConnected){ Toast.makeText(requireContext(), "Me movi", Toast.LENGTH_SHORT).show() } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentSelectDevicesBinding.inflate(inflater, container, false) initListeners() val nameDevicesAdapter = devices.map { it.key } binding.sdSpinner.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, nameDevicesAdapter) return binding.root } }
0
Kotlin
0
0
2109e52657bf03210f1e17d2823cc56ea627668c
3,199
dentgame
MIT License
src/main/kotlin/me/earth/headlessforge/command/CommandCompleter.kt
3arthqu4ke
351,243,674
false
null
package me.earth.headlessforge.command import org.jline.reader.Candidate import org.jline.reader.Completer import org.jline.reader.LineReader import org.jline.reader.ParsedLine open class CommandCompleter: Completer { override fun complete(reader: LineReader?, line: ParsedLine?, candidates: MutableList<Candidate>?) { TODO("Implement when JLine CommandLine works.") } }
2
Kotlin
2
33
4897961cfb037ab02cb4d51540fc6c5343d30eb1
389
HeadlessForge
MIT License
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinLocalClassDerivedLocalClasses.0.kt
ingokegel
72,937,917
false
null
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass // OPTIONS: derivedClasses fun foo() { open class <caret>A class B : A() open class T : A() fun bar() { class C : A() class D : T() } }
191
null
4372
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
225
intellij-community
Apache License 2.0
app/src/main/java/com/example/satu/data/local/UserPreferences.kt
synrgy-satu
829,466,485
false
{"Kotlin": 221544}
package com.example.satu.data.local import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.example.satu.data.model.response.auth.DataUser import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "token_user") class UserPreferences private constructor(private val dataStore: DataStore<Preferences>) { private val userTokenKey = stringPreferencesKey(USER_TOKEN_KEY) private val refreshTokenKey = stringPreferencesKey(REFRESH_TOKEN_KEY) fun getSession(): Flow<DataUser> = dataStore.data.map { DataUser( accessToken = it[userTokenKey] ?: "", refreshToken = it[refreshTokenKey] ?: "" ) } suspend fun saveSession(data: DataUser) = dataStore.edit { with(it) { this[userTokenKey] = data.accessToken this[refreshTokenKey] = data.refreshToken } } suspend fun deleteSession() = dataStore.edit { it.clear() } companion object { @Volatile private var INSTANCE: UserPreferences? = null fun getInstance(dataStore: DataStore<Preferences>): UserPreferences { return INSTANCE ?: synchronized(this) { val instance = UserPreferences(dataStore) INSTANCE = instance instance } } private const val USER_TOKEN_KEY = "access_token" private const val REFRESH_TOKEN_KEY = "refresh_token" } }
1
Kotlin
0
0
f26cf59385a8112a8649b449d964cc50933ba568
1,748
android-satu
Open Market License
src/main/kotlin/uk/matvey/slon/query/Query.kt
msmych
809,301,120
false
{"Kotlin": 60883}
package uk.matvey.slon.query import uk.matvey.slon.RecordReader import uk.matvey.slon.value.PgValue interface Query<T> { fun sql(): String fun params(): List<PgValue> fun read(reader: RecordReader): T companion object { fun <T> plainQuery(sql: String, params: List<PgValue> = listOf(), read: (RecordReader) -> T): Query<T> { return object : Query<T> { override fun sql() = sql override fun params() = params override fun read(reader: RecordReader) = read(reader) } } } }
0
Kotlin
0
0
4ee0763f402c0323d6f31ba2659c515677aba7f6
585
slon
Apache License 2.0
app/src/main/kotlin/com/fpliu/newton/video/player/sample/ErrorHandler.kt
leleliu008
208,230,961
false
null
package com.fpliu.newton.video.player.sample import android.text.TextUtils import com.fpliu.newton.log.Logger import com.fpliu.newton.util.appContext import com.umeng.analytics.MobclickAgent object ErrorHandler { private val TAG = ErrorHandler::class.java.simpleName fun onError(e: Throwable, extraInfo: String? = null) { Logger.e(TAG, "onError() extraInfo = $extraInfo", e) StringBuilder().apply { append(Logger.getExceptionTrace(e)) append('\n') // append("公网IP:${IPManager.ipInfo} record when ${IPManager.time}") append('\n') // append("网络配置:${Environment.getInstance().networkInfo}") if (!TextUtils.isEmpty(extraInfo)) { append('\n') append(extraInfo) } }.let { MobclickAgent.reportError(appContext, it.toString()) } } }
0
null
1
3
0a514ff79846622ca2a1f325e9821ac6c8ad481f
898
Android-VideoPlayer
Apache License 2.0
src/main/kotlin/collectionlambda/Operations5.kt
softbluecursoscode
603,710,984
false
{"Kotlin": 53437}
package collectionlambda /** * OBJETIVO * -------- * * Obter a quantidade de pessoas cujo nome começa com a letra 'R'. */ fun main() { // val count = Person // .data() // .filter { it.name.uppercase().startsWith("R") } // .count() // println(count) val count = Person .data() .count { it.name.uppercase().startsWith("R") } println(count) }
0
Kotlin
2
5
d9d3b179af5fcf851947fe59fe4e13a825532417
400
kotlin
MIT License
app/src/main/java/com/xeniac/fifaultimateteamcoin_dsfut_sell_fut/feature_pick_up_player/presentation/pick_up_player/utils/PlatformErrorAsUiText.kt
WilliamGates99
543,831,202
false
{"Kotlin": 898249}
package com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.feature_pick_up_player.presentation.pick_up_player.utils import com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.R import com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.core.presentation.utils.UiText import com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.feature_pick_up_player.domain.utils.PlatformError fun PlatformError.asUiText(): UiText = when (this) { PlatformError.SomethingWentWrong -> UiText.StringResource(R.string.error_something_went_wrong) }
0
Kotlin
0
1
a0b03bf204e6e681bbe587fdc928bff81e7e67e6
512
FUTSale
Apache License 2.0
offix/src/main/java/org/aerogear/offix/persistence/MutationDao.kt
aerogear
184,272,184
false
null
package org.aerogear.offix.persistence import android.arch.persistence.room.* @Dao interface MutationDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertMutation(mutation: Mutation): Long @Delete fun deleteMutation(mutation: Mutation) @Query("SELECT * FROM MutationOffline") fun getAllMutations(): List<Mutation> @Query("SELECT * FROM MutationOffline WHERE sNo =:sno") fun getAMutation(sno: Int): Mutation @Query("DELETE FROM MutationOffline WHERE sNo= :sno ") fun deleteCurrentMutation(sno: Int) @Query("DELETE FROM MutationOffline") fun deleteAllMutations() }
36
null
16
38
7d110d4d0143e1ba4d2676d80506c80463c2edc5
631
offix-android
Apache License 2.0
feature/about/view/implementation/src/main/kotlin/com/savvasdalkitsis/uhuruphotos/feature/about/view/implementation/ui/About.kt
savvasdalkitsis
485,908,521
false
{"Kotlin": 2667755, "Ruby": 1294, "PowerShell": 325, "Shell": 158}
/* Copyright 2023 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.savvasdalkitsis.uhuruphotos.feature.about.view.implementation.ui import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement.spacedBy 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.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedButton import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.mikepenz.aboutlibraries.ui.compose.LibrariesContainer import com.savvasdalkitsis.uhuruphotos.feature.about.view.implementation.seam.actions.AboutAction import com.savvasdalkitsis.uhuruphotos.feature.about.view.implementation.seam.actions.Donate import com.savvasdalkitsis.uhuruphotos.feature.about.view.implementation.seam.actions.NavigateToGithub import com.savvasdalkitsis.uhuruphotos.feature.about.view.implementation.seam.actions.NavigateToPrivacyPolicy import com.savvasdalkitsis.uhuruphotos.feature.about.view.implementation.seam.actions.SendFeedback import com.savvasdalkitsis.uhuruphotos.feature.about.view.implementation.ui.state.AboutState import com.savvasdalkitsis.uhuruphotos.foundation.compose.api.recomposeHighlighter import com.savvasdalkitsis.uhuruphotos.foundation.icons.api.R.drawable import com.savvasdalkitsis.uhuruphotos.foundation.strings.api.R.string import com.savvasdalkitsis.uhuruphotos.foundation.theme.api.PreviewAppTheme import com.savvasdalkitsis.uhuruphotos.foundation.theme.api.ThemeMode import com.savvasdalkitsis.uhuruphotos.foundation.ui.api.ui.scaffold.CommonScaffold import com.savvasdalkitsis.uhuruphotos.foundation.ui.api.ui.button.IconOutlineButton import com.savvasdalkitsis.uhuruphotos.foundation.ui.api.ui.scaffold.UpNavButton import my.nanihadesuka.compose.InternalLazyColumnScrollbar import my.nanihadesuka.compose.ScrollbarSelectionMode @OptIn(ExperimentalFoundationApi::class) @Composable internal fun About( state: AboutState, action: (AboutAction) -> Unit, ) { CommonScaffold( title = { Text(stringResource(string.about)) }, navigationIcon = { UpNavButton() }, ) { contentPadding -> val listState = rememberLazyListState() LibrariesContainer( modifier = Modifier .recomposeHighlighter() .fillMaxSize(), contentPadding = contentPadding, lazyListState = listState, header = { stickyHeader { AboutHeader(state, action) } } ) Box(modifier = Modifier .recomposeHighlighter() .padding(contentPadding) ) { InternalLazyColumnScrollbar( listState = listState, thickness = 8.dp, selectionMode = ScrollbarSelectionMode.Thumb, thumbColor = MaterialTheme.colors.primary.copy(alpha = 0.7f), thumbSelectedColor = MaterialTheme.colors.primary, ) } } } @Composable private fun AboutHeader( state: AboutState, action: (AboutAction) -> Unit, ) { Column( modifier = Modifier .recomposeHighlighter() .fillMaxWidth() .background(MaterialTheme.colors.background) .padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = spacedBy(8.dp), ) { Icon( modifier = Modifier .recomposeHighlighter() .size(80.dp) .background(Color.White, CircleShape), tint = Color.Black, painter = painterResource(drawable.ic_logo), contentDescription = null, ) Text( text = "UhuruPhotos", style = MaterialTheme.typography.h3, ) Text( text = state.appVersion, style = MaterialTheme.typography.subtitle1, ) Row( modifier = Modifier .recomposeHighlighter() .fillMaxWidth(), horizontalArrangement = spacedBy(8.dp), ) { OutlinedButton( modifier = Modifier .recomposeHighlighter() .weight(1f), onClick = { action(NavigateToGithub )}, ) { Icon( painter = painterResource(drawable.ic_github), contentDescription = null ) Spacer(modifier = Modifier .recomposeHighlighter() .width(8.dp)) Text(text = "Github") } OutlinedButton( modifier = Modifier .recomposeHighlighter() .weight(1f), onClick = { action(Donate) }, ) { Icon( painter = painterResource(drawable.ic_money), contentDescription = null ) Spacer(modifier = Modifier .recomposeHighlighter() .width(8.dp)) Text(text = stringResource(string.donate)) } } Row( modifier = Modifier .recomposeHighlighter() .fillMaxWidth(), horizontalArrangement = spacedBy(8.dp), ) { OutlinedButton( modifier = Modifier .recomposeHighlighter() .weight(1f), onClick = { action(SendFeedback) }, ) { Icon( painter = painterResource(drawable.ic_feedback), contentDescription = null ) Spacer( modifier = Modifier .recomposeHighlighter() .width(8.dp) ) Text(text = stringResource(string.feedback)) } IconOutlineButton( modifier = Modifier.weight(1f), icon = drawable.ic_book_open, onClick = { action(NavigateToPrivacyPolicy) }, text = stringResource(string.privacy_policy) ) } } } @Preview @Composable private fun AboutHeaderPreview() { PreviewAppTheme { AboutHeader(AboutState("0.0.999")) {} } } @Preview @Composable private fun AboutHeaderDarkPreview() { PreviewAppTheme(theme = ThemeMode.DARK_MODE) { AboutHeader(AboutState("0.0.999")) {} } }
92
Kotlin
26
358
22c2ac7d953f88b4d60fb74953667ef0c4beacc5
8,005
uhuruphotos-android
Apache License 2.0
Exercicios Com Coleções ou Listas/Exercicio19.kt
DenertSousa
613,699,145
false
null
/*Este programa faz um pesquisa sobre qual é o melhor sistema operacional. No final, ele imprime a quantidade de votos que cada sistema operacional recebeu o mais votado, a quantidade de votos recebidas por ele, e a porcentagem de todos os votos, e a porcentagem do mais votado. */ fun main () { var survey: MutableList<Int> = mutableListOf() var optionOne: MutableList<Int> = mutableListOf() var optionTwo: MutableList<Int> = mutableListOf() var optionThree: MutableList<Int> = mutableListOf() var optionFour: MutableList<Int> = mutableListOf() var optionFive: MutableList<Int> = mutableListOf() var optionSix: MutableList<Int> = mutableListOf() do { println(""" Qual é o melhor Sistema Operacional para uso em servidores? 1 - Windows Server 2 - Unix 3 - Linux 4 - Netware 5 - Mac OS 6 - Outro """.trimIndent() ) var input: Int = readLine()!!.toInt() if (input in 1..6) { survey.add(input) } else if (input <= -1 || input >=7){ println("Este número que você escolheu não é válido.") } } while (input != 0) survey.filterTo(optionOne){it == 1} survey.filterTo(optionTwo){it == 2} survey.filterTo(optionThree){it == 3} survey.filterTo(optionFour){it == 4} survey.filterTo(optionFive){it == 5} survey.filterTo(optionSix){it == 6} var surveyFinalResult: MutableList<Int> = mutableListOf(optionOne.size, optionTwo.size, optionThree.size, optionFour.size, optionFive.size, optionSix.size) var mostVoted = Int.MIN_VALUE var systemMostVotedIndice = 0 for (i in surveyFinalResult.indices) { if (surveyFinalResult[i] >= mostVoted) { mostVoted = surveyFinalResult[i] systemMostVotedIndice = i } } var systemMostVoted: String = when ( systemMostVotedIndice) { 0 -> "Windows Server" 1 -> "Unix" 2 -> "Linux" 3 -> "Netware" 4 -> "Mac Os" 5 -> "Outro" else -> "" } println(""" Sistema Operacional Votos % ------------------- ------- ----- WindowsServer ${optionOne.size} ${optionOne.size * 100 / survey.size} % Unix ${optionTwo.size} ${optionTwo.size * 100 / survey.size} % Linux ${optionThree.size} ${optionThree.size * 100 / survey.size} % Netware ${optionFour.size} ${optionFour.size * 100 / survey.size} % Mac OS ${optionFive.size} ${optionFive.size * 100 / survey.size} % Outro ${optionSix.size} ${optionSix.size * 100 / survey.size} % ------------------- ------- Total ${survey.size} O Sistema Operacional mais votado foi o $systemMostVoted, com $mostVoted, correspondendo a ${mostVoted * 100 /survey.size} dos votos """.trimIndent()) }
0
Kotlin
0
0
6905448b0e662fafcc27316ac4390036d49d6b17
3,236
Programando-em-Kotlin
MIT License
app/src/main/java/com/malibin/morse/presentation/viewer/BroadCastFinishedDialog.kt
cha7713
463,427,946
true
{"Kotlin": 121634, "PureBasic": 2910}
package com.malibin.morse.presentation.viewer import android.app.Dialog import android.content.Context import android.os.Bundle import com.malibin.morse.R import com.malibin.morse.databinding.DialogBroadcastFinishBinding /** * Created By Malibin * on 2월 05, 2021 */ class BroadCastFinishedDialog(context: Context) : Dialog(context) { var onButtonClickListener: (() -> Unit)? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = DialogBroadcastFinishBinding.inflate(layoutInflater).apply { buttonBack.setOnClickListener { onButtonClickListener?.invoke() dismiss() } } setContentView(binding.root) setCancelable(false) window?.setBackgroundDrawableResource(R.color.transparent) } }
0
null
0
0
8103c56b8079224aba8eedc7a4a4af40a1b92b4c
861
morse_android_stove_camp
Apache License 2.0
app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupCreateFlags.kt
Quickdesh
468,685,161
true
{"Kotlin": 2997580}
package eu.kanade.tachiyomi.data.backup internal object BackupCreateFlags { const val BACKUP_CATEGORY = 0x1 const val BACKUP_CHAPTER = 0x2 const val BACKUP_HISTORY = 0x4 const val BACKUP_TRACK = 0x8 const val BACKUP_PREFS = 0x10 const val BACKUP_EXT_PREFS = 0x20 const val BACKUP_EXTENSIONS = 0x40 // AM (CU) --> internal const val BACKUP_CUSTOM_INFO = 0x80 // <-- AM (CU) const val AutomaticDefaults = BACKUP_CATEGORY or BACKUP_CHAPTER or BACKUP_HISTORY or BACKUP_TRACK or BACKUP_PREFS or BACKUP_EXT_PREFS }
24
Kotlin
8
379
ed992717aa02a48ea2df3e3e0b70e678535829f4
596
Animiru
Apache License 2.0
src/test/kotlin/no/nav/pensjon/opptjening/omsorgsopptjening/bestem/pensjonsopptjening/brev/BrevProsesseringTest.kt
navikt
593,529,397
false
{"Kotlin": 589332, "Dockerfile": 97}
package no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.brev import com.github.tomakehurst.wiremock.client.WireMock import com.github.tomakehurst.wiremock.stubbing.Scenario import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.brev.external.PENBrevClient.Companion.sendBrevUrl import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.brev.model.Brev import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.brev.model.BrevClient import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.brev.model.BrevService import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.brev.repository.BrevRepository import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.common.* import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.omsorgsopptjening.repository.BehandlingRepo import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.oppgave.repository.OppgaveRepo import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.persongrunnlag.model.GyldigOpptjeningår import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.persongrunnlag.model.PersongrunnlagMelding import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.persongrunnlag.model.PersongrunnlagMeldingService import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.persongrunnlag.repository.PersongrunnlagRepo import no.nav.pensjon.opptjening.omsorgsopptjening.felles.CorrelationId import no.nav.pensjon.opptjening.omsorgsopptjening.felles.InnlesingId import no.nav.pensjon.opptjening.omsorgsopptjening.felles.domene.kafka.Rådata import no.nav.pensjon.opptjening.omsorgsopptjening.felles.domene.kafka.messages.domene.Kilde import no.nav.pensjon.opptjening.omsorgsopptjening.felles.domene.kafka.messages.domene.Landstilknytning import no.nav.pensjon.opptjening.omsorgsopptjening.felles.domene.kafka.messages.domene.Omsorgstype import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertInstanceOf import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension import org.mockito.BDDMockito.given import org.mockito.BDDMockito.willAnswer import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.boot.test.mock.mockito.MockBean import java.net.URL import java.time.Clock import java.time.Instant import java.time.Month import java.time.YearMonth import java.time.temporal.ChronoUnit import kotlin.test.assertContains import no.nav.pensjon.opptjening.omsorgsopptjening.felles.domene.kafka.messages.domene.PersongrunnlagMelding as PersongrunnlagMeldingKafka class BrevProsesseringTest( @Value("\${PEN_BASE_URL}") private val baseUrl: String, ) : SpringContextTest.NoKafka() { @Autowired private lateinit var persongrunnlagRepo: PersongrunnlagRepo @Autowired private lateinit var behandlingRepo: BehandlingRepo @Autowired private lateinit var persongrunnlagMeldingService: PersongrunnlagMeldingService @MockBean private lateinit var clock: Clock @MockBean private lateinit var gyldigOpptjeningår: GyldigOpptjeningår @Autowired private lateinit var oppgaveRepo: OppgaveRepo @Autowired private lateinit var brevRepository: BrevRepository @Autowired private lateinit var brevService: BrevService @Autowired private lateinit var brevClient: BrevClient companion object { @JvmField @RegisterExtension val wiremock = wiremockWithPdlTransformer() } @Test fun `gitt at en rad feiler, så skal den kunne retryes og gå bra på et senere tidspunkt`() { wiremock.stubForPdlTransformer() wiremock.ingenPensjonspoeng("12345678910") //mor wiremock.ingenPensjonspoeng("04010012797") //far wiremock.bestemSakOk() val sendBrevPath = URL(sendBrevUrl(baseUrl, "12345")).path wiremock.givenThat( WireMock.post(WireMock.urlPathEqualTo(sendBrevPath)) .inScenario("retry") .whenScenarioStateIs(Scenario.STARTED) .willReturn( WireMock.forbidden() ) .willSetStateTo("feil 2") ) wiremock.givenThat( WireMock.post(WireMock.urlPathEqualTo(sendBrevPath)) .inScenario("retry") .whenScenarioStateIs("feil 2") .willReturn( WireMock.notFound() ) .willSetStateTo("ok") ) wiremock.givenThat( WireMock.post(WireMock.urlPathEqualTo(sendBrevPath)) .inScenario("retry") .whenScenarioStateIs("ok") .willReturn( WireMock.aResponse() .withHeader("Content-Type", "application/json") .withBody( """ { "journalpostId": "acoc2323o" } """.trimIndent() ) ) ) /** * Stiller klokka litt fram i tid for å unngå at [Brev.Status.Retry.karanteneTil] fører til at vi hopper over raden. */ given(clock.instant()).willReturn(Instant.now().plus(10, ChronoUnit.DAYS)) willAnswer { true }.given(gyldigOpptjeningår).erGyldig(2020) val (behandling, brev) = persongrunnlagRepo.lagre( PersongrunnlagMelding.Lest( innhold = PersongrunnlagMeldingKafka( omsorgsyter = "12345678910", persongrunnlag = listOf( PersongrunnlagMeldingKafka.Persongrunnlag( omsorgsyter = "12345678910", omsorgsperioder = listOf( PersongrunnlagMeldingKafka.Omsorgsperiode( fom = YearMonth.of(2018, Month.JANUARY), tom = YearMonth.of(2030, Month.DECEMBER), omsorgstype = Omsorgstype.FULL_BARNETRYGD, omsorgsmottaker = "03041212345", kilde = Kilde.BARNETRYGD, utbetalt = 7234, landstilknytning = Landstilknytning.NORGE ), ), hjelpestønadsperioder = listOf( PersongrunnlagMeldingKafka.Hjelpestønadperiode( fom = YearMonth.of(2018, Month.JANUARY), tom = YearMonth.of(2030, Month.DECEMBER), omsorgstype = Omsorgstype.HJELPESTØNAD_FORHØYET_SATS_3, omsorgsmottaker = "03041212345", kilde = Kilde.BARNETRYGD, ) ) ), ), rådata = Rådata(), innlesingId = InnlesingId.generate(), correlationId = CorrelationId.generate(), ) ), ).let { persongrunnlagMeldingService.process()!!.first().single().let { behandling -> Assertions.assertTrue(behandling.erInnvilget()) behandling to brevRepository.findForBehandling(behandling.id).singleOrNull()!! } } assertInstanceOf(Brev.Status.Klar::class.java, brevRepository.find(brev.id).status) brevService.process() brevRepository.find(brev.id).let { m -> assertInstanceOf(Brev.Status.Retry::class.java, m.status).let { assertEquals(1, it.antallForsøk) assertEquals(3, it.maxAntallForsøk) assertContains(it.melding, "Forbidden") } } brevService.process() brevRepository.find(brev.id).let { m -> assertInstanceOf(Brev.Status.Retry::class.java, m.status).let { assertEquals(2, it.antallForsøk) assertEquals(3, it.maxAntallForsøk) assertThat(it.melding).contains("Feil fra brevtjenesten: vedtak finnes ikke") } } brevService.process()!!.first().also { b -> assertEquals(2020, b.omsorgsår) assertEquals("12345678910", b.omsorgsyter) assertEquals(behandling.id, b.behandlingId) assertEquals(behandling.meldingId, b.meldingId) assertInstanceOf(Brev.Status.Ferdig::class.java, b.status).also { assertEquals("acoc2323o", it.journalpost) } assertEquals(1, brevRepository.findForBehandling(behandling.id).count()) } } @Test fun `gitt at en melding har blitt prosessert på nytt uten hell maks antall ganger skal det opprettes en oppgave`() { val sendBrevPath = URL(sendBrevUrl(baseUrl, "42")).path wiremock.stubForPdlTransformer() wiremock.ingenPensjonspoeng("12345678910") //mor wiremock.ingenPensjonspoeng("04010012797") //far wiremock.bestemSakOk() wiremock.givenThat( WireMock.post(WireMock.urlPathEqualTo(sendBrevPath)) .willReturn( WireMock.forbidden() ) ) /** * Stiller klokka litt fram i tid for å unngå at [Brev.Status.Retry.karanteneTil] fører til at vi hopper over raden. */ given(clock.instant()).willReturn(Instant.now().plus(10, ChronoUnit.DAYS)) willAnswer { true }.given(gyldigOpptjeningår).erGyldig(2020) val (behandling, brev) = persongrunnlagRepo.lagre( PersongrunnlagMelding.Lest( innhold = PersongrunnlagMeldingKafka( omsorgsyter = "12345678910", persongrunnlag = listOf( PersongrunnlagMeldingKafka.Persongrunnlag( omsorgsyter = "12345678910", omsorgsperioder = listOf( PersongrunnlagMeldingKafka.Omsorgsperiode( fom = YearMonth.of(2018, Month.JANUARY), tom = YearMonth.of(2030, Month.DECEMBER), omsorgstype = Omsorgstype.FULL_BARNETRYGD, omsorgsmottaker = "03041212345", kilde = Kilde.BARNETRYGD, utbetalt = 7234, landstilknytning = Landstilknytning.NORGE ), ), hjelpestønadsperioder = listOf( PersongrunnlagMeldingKafka.Hjelpestønadperiode( fom = YearMonth.of(2018, Month.JANUARY), tom = YearMonth.of(2030, Month.DECEMBER), omsorgstype = Omsorgstype.HJELPESTØNAD_FORHØYET_SATS_3, omsorgsmottaker = "03041212345", kilde = Kilde.BARNETRYGD, ) ) ), ), rådata = Rådata(), innlesingId = InnlesingId.generate(), correlationId = CorrelationId.generate(), ) ), ).let { persongrunnlagMeldingService.process()!!.first().single().let { behandling -> Assertions.assertTrue(behandling.erInnvilget()) behandling to brevRepository.findForBehandling(behandling.id).singleOrNull()!! } } assertInstanceOf(Brev.Status.Klar::class.java, brevRepository.find(brev.id).status) brevService.process() brevService.process() brevService.process() brevService.process() brevRepository.find(brev.id).also { b -> assertEquals(2020, b.omsorgsår) assertEquals("12345678910", b.omsorgsyter) assertEquals(behandling.id, b.behandlingId) assertEquals(behandling.meldingId, b.meldingId) assertInstanceOf(Brev.Status.Feilet::class.java, b.status) assertEquals(1, brevRepository.findForBehandling(behandling.id).count()) } } }
3
Kotlin
1
0
d70ec64e9bc1c2c9e03928f2e1dac68f9e6ef9c8
12,945
omsorgsopptjening-bestem-pensjonsopptjening
MIT License
src/main/kotlin/eZmaxApi/models/EzsignbulksendMinusCreateEzsignbulksendtransmissionMinusV1MinusRequest.kt
eZmaxinc
271,950,932
false
null
/** * eZmax API Definition (Full) * * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.9 * Contact: <EMAIL> * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package eZmaxApi.models import eZmaxApi.models.FieldMinusEEzsignfolderSendreminderfrequency import com.squareup.moshi.Json /** * Request for POST /1/object/ezsignbulksend/{pkiEzsignbulksendID}/createEzsignbulksendtransmission * * @param fkiUserlogintypeID The unique ID of the Userlogintype Valid values: |Value|Description|Detail| |-|-|-| |1|**Email Only**|The Ezsignsigner will receive a secure link by email| |2|**Email and phone or SMS**|The Ezsignsigner will receive a secure link by email and will need to authenticate using SMS or Phone call. **Additional fee applies**| |3|**Email and secret question**|The Ezsignsigner will receive a secure link by email and will need to authenticate using a predefined question and answer| |4|**In person only**|The Ezsignsigner will only be able to sign \"In-Person\" and there won't be any authentication. No email will be sent for invitation to sign. Make sure you evaluate the risk of signature denial and at minimum, we recommend you use a handwritten signature type| |5|**In person with phone or SMS**|The Ezsignsigner will only be able to sign \"In-Person\" and will need to authenticate using SMS or Phone call. No email will be sent for invitation to sign. **Additional fee applies**| * @param sEzsignbulksendtransmissionDescription The description of the Ezsignbulksendtransmission * @param dtEzsigndocumentDuedate The maximum date and time at which the Ezsigndocument can be signed. * @param eEzsignfolderSendreminderfrequency * @param tExtraMessage A custom text message that will be added to the email sent. * @param sCsvBase64 The Base64 encoded binary content of the CSV file. * @param fkiEzsigntsarequirementID The unique ID of the Ezsigntsarequirement. Determine if a Time Stamping Authority should add a timestamp on each of the signature. Valid values: |Value|Description| |-|-| |1|No. TSA Timestamping will requested. This will make all signatures a lot faster since no round-trip to the TSA server will be required. Timestamping will be made using eZsign server's time.| |2|Best effort. Timestamping from a Time Stamping Authority will be requested but is not mandatory. In the very improbable case it cannot be completed, the timestamping will be made using eZsign server's time. **Additional fee applies**| |3|Mandatory. Timestamping from a Time Stamping Authority will be requested and is mandatory. In the very improbable case it cannot be completed, the signature will fail and the user will be asked to retry. **Additional fee applies**| */ data class EzsignbulksendMinusCreateEzsignbulksendtransmissionMinusV1MinusRequest ( /* The unique ID of the Userlogintype Valid values: |Value|Description|Detail| |-|-|-| |1|**Email Only**|The Ezsignsigner will receive a secure link by email| |2|**Email and phone or SMS**|The Ezsignsigner will receive a secure link by email and will need to authenticate using SMS or Phone call. **Additional fee applies**| |3|**Email and secret question**|The Ezsignsigner will receive a secure link by email and will need to authenticate using a predefined question and answer| |4|**In person only**|The Ezsignsigner will only be able to sign \"In-Person\" and there won't be any authentication. No email will be sent for invitation to sign. Make sure you evaluate the risk of signature denial and at minimum, we recommend you use a handwritten signature type| |5|**In person with phone or SMS**|The Ezsignsigner will only be able to sign \"In-Person\" and will need to authenticate using SMS or Phone call. No email will be sent for invitation to sign. **Additional fee applies**| */ @Json(name = "fkiUserlogintypeID") val fkiUserlogintypeID: kotlin.Int, /* The description of the Ezsignbulksendtransmission */ @Json(name = "sEzsignbulksendtransmissionDescription") val sEzsignbulksendtransmissionDescription: kotlin.String, /* The maximum date and time at which the Ezsigndocument can be signed. */ @Json(name = "dtEzsigndocumentDuedate") val dtEzsigndocumentDuedate: kotlin.String, @Json(name = "eEzsignfolderSendreminderfrequency") val eEzsignfolderSendreminderfrequency: FieldMinusEEzsignfolderSendreminderfrequency, /* A custom text message that will be added to the email sent. */ @Json(name = "tExtraMessage") val tExtraMessage: kotlin.String, /* The Base64 encoded binary content of the CSV file. */ @Json(name = "sCsvBase64") val sCsvBase64: kotlin.ByteArray, /* The unique ID of the Ezsigntsarequirement. Determine if a Time Stamping Authority should add a timestamp on each of the signature. Valid values: |Value|Description| |-|-| |1|No. TSA Timestamping will requested. This will make all signatures a lot faster since no round-trip to the TSA server will be required. Timestamping will be made using eZsign server's time.| |2|Best effort. Timestamping from a Time Stamping Authority will be requested but is not mandatory. In the very improbable case it cannot be completed, the timestamping will be made using eZsign server's time. **Additional fee applies**| |3|Mandatory. Timestamping from a Time Stamping Authority will be requested and is mandatory. In the very improbable case it cannot be completed, the signature will fail and the user will be asked to retry. **Additional fee applies**| */ @Json(name = "fkiEzsigntsarequirementID") val fkiEzsigntsarequirementID: kotlin.Int? = null )
0
Kotlin
0
0
fad1a7a8b3f744256968e67e5f60044063cb551c
5,874
eZmax-SDK-kotlin
MIT License
kotlin-electron/src/jsMain/generated/electron/utility/DidNavigateInPageEvent.kt
JetBrains
93,250,841
false
{"Kotlin": 12159121, "JavaScript": 330528}
// Generated by Karakum - do not modify it manually! package electron.utility typealias DidNavigateInPageEvent = electron.core.DidNavigateInPageEvent
40
Kotlin
165
1,319
a8a1947d73e3ed26426f1e27b641bff427dfd6a0
154
kotlin-wrappers
Apache License 2.0
library/src/main/java/com/jaredrummler/cyanea/delegate/CyaneaDelegateImplV24.kt
evozi
184,425,041
true
{"Kotlin": 258629}
/* * Copyright (C) 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 com.jaredrummler.cyanea.delegate import android.annotation.SuppressLint import android.annotation.TargetApi import android.app.Activity import android.content.res.ColorStateList import android.os.Build import android.os.Bundle import androidx.annotation.RequiresApi import com.jaredrummler.cyanea.Cyanea import com.jaredrummler.cyanea.R import com.jaredrummler.cyanea.getKey import com.jaredrummler.cyanea.utils.Reflection @RequiresApi(Build.VERSION_CODES.N) @TargetApi(Build.VERSION_CODES.N) internal open class CyaneaDelegateImplV24( private val activity: Activity, private val cyanea: Cyanea, themeResId: Int ) : CyaneaDelegateImplV23(activity, cyanea, themeResId) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (cyanea.isThemeModified) { preloadColors() } } @SuppressLint("PrivateApi") private fun preloadColors() { try { val klass = Class.forName("android.content.res.ColorStateList\$ColorStateListFactory") val constructor = klass.getConstructor(ColorStateList::class.java).apply { if (!isAccessible) isAccessible = true } val mResourcesImpl = Reflection.getFieldValue<Any?>(activity.resources, "mResourcesImpl") ?: return val cache = Reflection.getFieldValue<Any?>(mResourcesImpl, "sPreloadedComplexColors") ?: return val method = Reflection.getMethod(cache, "put", Long::class.java, Object::class.java) ?: return for ((id, color) in hashMapOf<Int, Int>().apply { put(R.color.cyanea_accent, cyanea.accent) }) { constructor.newInstance(ColorStateList.valueOf(color))?.let { factory -> val key = activity.resources.getKey(id) method.invoke(cache, key, factory) } } } catch (ex: Throwable) { Cyanea.log(TAG, "Error preloading colors", ex) } } companion object { private const val TAG = "CyaneaDelegateImplV24" } }
39
Kotlin
3
6
8fc901fc7dfeab2b044625fb2bf7091d956215c2
2,755
Cyanea
Apache License 2.0
compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrCommonMemberStorage.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.backend import org.jetbrains.kotlin.fir.declarations.* import org.jetbrains.kotlin.fir.signaturer.FirBasedSignatureComposer import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.impl.IrFactoryImpl import org.jetbrains.kotlin.ir.util.IdSignatureComposer import org.jetbrains.kotlin.ir.util.SymbolTable import java.util.concurrent.ConcurrentHashMap class Fir2IrCommonMemberStorage( signatureComposer: IdSignatureComposer, firMangler: FirMangler ) { val firSignatureComposer = FirBasedSignatureComposer(firMangler) val symbolTable = SymbolTable(signaturer = signatureComposer, irFactory = IrFactoryImpl) val classCache: MutableMap<FirRegularClass, IrClass> = mutableMapOf() val typeParameterCache: MutableMap<FirTypeParameter, IrTypeParameter> = mutableMapOf() val enumEntryCache: MutableMap<FirEnumEntry, IrEnumEntry> = mutableMapOf() val localClassCache: MutableMap<FirClass, IrClass> = mutableMapOf() val functionCache: ConcurrentHashMap<FirFunction, IrSimpleFunction> = ConcurrentHashMap() val constructorCache: ConcurrentHashMap<FirConstructor, IrConstructor> = ConcurrentHashMap() val propertyCache: ConcurrentHashMap<FirProperty, IrProperty> = ConcurrentHashMap() val fakeOverridesInClass: MutableMap<IrClass, MutableMap<Fir2IrDeclarationStorage.FakeOverrideKey, FirCallableDeclaration>> = mutableMapOf() val irFakeOverridesForFirFakeOverrideMap: MutableMap<Fir2IrDeclarationStorage.FakeOverrideIdentifier, IrDeclaration> = mutableMapOf() }
155
null
5608
45,423
2db8f31966862388df4eba2702b2f92487e1d401
1,788
kotlin
Apache License 2.0
client/slack-api-client/src/main/kotlin/com/kreait/slack/api/group/conversations/ConversationsOpenMethod.kt
ironaraujo
249,748,914
true
{"Kotlin": 1212878, "Shell": 935}
package com.kreait.slack.api.group.conversations import com.kreait.slack.api.contract.jackson.group.conversations.ConversationsOpenRequest import com.kreait.slack.api.contract.jackson.group.conversations.ErrorConversationOpenResponse import com.kreait.slack.api.contract.jackson.group.conversations.SuccessfulConversationOpenResponse import com.kreait.slack.api.group.ApiCallMethod /** * Abstract representation of an slack api operation * https://api.slack.com/methods/conversations.open */ abstract class ConversationsOpenMethod : ApiCallMethod<ConversationsOpenMethod, SuccessfulConversationOpenResponse, ErrorConversationOpenResponse, ConversationsOpenRequest>() { }
0
null
0
0
07edb441421961b0d84d8f95e97f8b25f48a360e
677
slack-spring-boot-starter
MIT License
src/main/java/tech/sirwellington/alchemy/http/mock/MockAlchemyHttp.kt
SirWellington
48,623,588
false
null
/* * Copyright © 2019. <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 tech.sirwellington.alchemy.http.mock import com.google.gson.JsonNull import junit.framework.Assert.fail import sir.wellington.alchemy.collections.lists.Lists import sir.wellington.alchemy.collections.maps.Maps import tech.sirwellington.alchemy.annotations.access.Internal import tech.sirwellington.alchemy.annotations.arguments.Required import tech.sirwellington.alchemy.annotations.designs.StepMachineDesign import tech.sirwellington.alchemy.annotations.designs.StepMachineDesign.Role.MACHINE import tech.sirwellington.alchemy.arguments.AlchemyAssertion import tech.sirwellington.alchemy.arguments.Arguments.checkThat import tech.sirwellington.alchemy.arguments.assertions.instanceOf import tech.sirwellington.alchemy.arguments.assertions.nonNullReference import tech.sirwellington.alchemy.arguments.assertions.notNull import tech.sirwellington.alchemy.http.AlchemyHttp import tech.sirwellington.alchemy.http.AlchemyRequestSteps import tech.sirwellington.alchemy.http.HttpResponse import tech.sirwellington.alchemy.http.exceptions.AlchemyHttpException import tech.sirwellington.alchemy.http.mock.MockRequest.Companion.ANY_BODY import tech.sirwellington.alchemy.http.mock.MockRequest.Companion.NO_BODY import java.lang.String.format import java.util.concurrent.Callable /** * * @author SirWellington */ @Internal @StepMachineDesign(role = MACHINE) internal open class MockAlchemyHttp(expectedActions: Map<MockRequest, Callable<*>>) : AlchemyHttp { private val expectedActions: MutableMap<MockRequest, Callable<*>> = Maps.createSynchronized() private val requestsMade = Lists.create<MockRequest>() override val defaultHeaders: Map<String, String> @Required get() = emptyMap() init { checkThat(expectedActions).isA(nonNullReference()) this.expectedActions.putAll(expectedActions) } @Required override fun usingDefaultHeader(key: String, value: String): AlchemyHttp { return this } override fun go(): AlchemyRequestSteps.Step1 { return MockSteps.MockStep1(this) } @Internal @Throws(AlchemyHttpException::class) open fun getResponseFor(request: MockRequest): HttpResponse { checkThat(request).isA(expectedRequest()) requestsMade.add(request) val action = findMatchingActionFor(request)!! val response: Any try { response = action.call() } catch (ex: AlchemyHttpException) { throw ex } catch (ex: Exception) { throw AlchemyHttpException(ex) } checkThat(response) .usingMessage(format("Response Type Wanted: %s but actual: null", HttpResponse::class.java)) .isA(notNull()) .usingMessage(format("Response Type Wanted: %s but actual: %s", HttpResponse::class.java, response.javaClass)) .isA(instanceOf(HttpResponse::class.java)) return response as HttpResponse } @Internal @Throws(AlchemyHttpException::class) open fun <T> getResponseFor(request: MockRequest, expectedClass: Class<T>): T { checkThat(request, expectedClass) .are(notNull()) requestsMade.add(request) checkThat(request) .usingMessage("Unexpected Request: " + request) .isA(expectedRequest()) val operation = findMatchingActionFor(request) val responseObject: Any try { responseObject = operation!!.call() } catch (ex: AlchemyHttpException) { throw ex } catch (ex: Exception) { throw AlchemyHttpException(ex) } checkThat(responseObject) .usingMessage(format("Response Type Wanted: %s but actual: %s", responseObject.javaClass, expectedClass)) .isA(instanceOf(expectedClass)) return responseObject as T } @Internal open fun verifyAllRequestsMade() { expected@ for (expectedRequest in expectedActions.keys) { made@ for (requestMade in requestsMade) { if (requestsMatch(expectedRequest, requestMade)) { continue@expected } } //Reaching here means no match was found fail("Request never made: " + expectedRequest) } } private fun expectedRequest(): AlchemyAssertion<MockRequest> { return AlchemyAssertion { request -> checkThat(request).isA(nonNullReference()) val action = findMatchingActionFor(request) checkThat(action) .usingMessage("request was not expected: [$request]") .isA(nonNullReference()) } } private fun findMatchingActionFor(request: MockRequest): Callable<*>? { val foundInMap = expectedActions[request] if (foundInMap != null) { return foundInMap } for (element in expectedActions.keys) { if (requestsMatch(element, request)) { return expectedActions[element] } } return null } private fun requestsMatch(expected: MockRequest, actual: MockRequest): Boolean { if (expected.method != actual.method) { return false } if (expected.queryParams != actual.queryParams) { return false } //If the URL is null, this means any if (expected.url != MockRequest.ANY_URL) { if (expected.url.toString() != actual.url.toString()) { return false } } //Now comparing bodies //Any body matches to anything if (expected.body === ANY_BODY) { return true } if (expected.body === NO_BODY) { return actual.body == null || actual.body === NO_BODY || actual.body === JsonNull.INSTANCE } //Try a shallow equality first if (expected.body === actual.body) { return true } //Then fallback to equals() if all else fails return expected.body == actual.body } }
1
Kotlin
0
1
1dc43665baa938ded1cd8a8dd8b23a4c3bf2550b
7,014
alchemy-http-mock
Apache License 2.0
kt/godot-library/src/main/kotlin/godot/gen/godot/PackedDataContainer.kt
utopia-rise
289,462,532
false
null
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT", "RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate") package godot import godot.`annotation`.GodotBaseType import godot.common.interop.VoidPtr import godot.core.TypeManager import godot.core.VariantCaster.ANY import godot.core.VariantParser.LONG import godot.core.memory.TransferContext import kotlin.Any import kotlin.Int import kotlin.Long import kotlin.Suppress import kotlin.Unit /** * [PackedDataContainer] can be used to efficiently store data from untyped containers. The data is * packed into raw bytes and can be saved to file. Only [Array] and [Dictionary] can be stored this * way. * You can retrieve the data by iterating on the container, which will work as if iterating on the * packed data itself. If the packed container is a [Dictionary], the data can be retrieved by key * names ([String]/[StringName] only). * [codeblock] * var data = { "key": "value", "another_key": 123, "lock": Vector2() } * var packed = PackedDataContainer.new() * packed.pack(data) * ResourceSaver.save(packed, "packed_data.res") * [/codeblock] * [codeblock] * var container = load("packed_data.res") * for key in container: * prints(key, container[key]) * * # Prints: * # key value * # lock (0, 0) * # another_key 123 * [/codeblock] * Nested containers will be packed recursively. While iterating, they will be returned as * [PackedDataContainerRef]. */ @GodotBaseType public open class PackedDataContainer : Resource() { public override fun new(scriptIndex: Int): Unit { callConstructor(ENGINECLASS_PACKEDDATACONTAINER, scriptIndex) } /** * Packs the given container into a binary representation. The [value] must be either [Array] or * [Dictionary], any other type will result in invalid data error. * **Note:** Subsequent calls to this method will overwrite the existing data. */ public final fun pack(`value`: Any?): Error { TransferContext.writeArguments(ANY to value) TransferContext.callMethod(ptr, MethodBindings.packPtr, LONG) return Error.from(TransferContext.readReturnValue(LONG) as Long) } /** * Returns the size of the packed container (see [Array.size] and [Dictionary.size]). */ public final fun size(): Int { TransferContext.writeArguments() TransferContext.callMethod(ptr, MethodBindings.sizePtr, LONG) return (TransferContext.readReturnValue(LONG) as Long).toInt() } public companion object internal object MethodBindings { public val packPtr: VoidPtr = TypeManager.getMethodBindPtr("PackedDataContainer", "pack", 966674026) public val sizePtr: VoidPtr = TypeManager.getMethodBindPtr("PackedDataContainer", "size", 3905245786) } }
64
null
45
634
ac2a1bd5ea931725e2ed19eb5093dea171962e3f
3,019
godot-kotlin-jvm
MIT License
server/src/main/kotlin/net/horizonsend/ion/server/features/starship/PilotedStarships.kt
HorizonsEndMC
461,042,096
false
null
package net.horizonsend.ion.server.features.starship import net.horizonsend.ion.common.database.schema.misc.SLPlayer import net.horizonsend.ion.common.database.schema.starships.Blueprint import net.horizonsend.ion.common.database.schema.starships.PlayerStarshipData import net.horizonsend.ion.common.database.schema.starships.StarshipData import net.horizonsend.ion.common.extensions.information import net.horizonsend.ion.common.extensions.success import net.horizonsend.ion.common.extensions.successActionMessage import net.horizonsend.ion.common.extensions.userError import net.horizonsend.ion.common.extensions.userErrorActionMessage import net.horizonsend.ion.common.utils.configuration.redis import net.horizonsend.ion.server.IonServerComponent import net.horizonsend.ion.server.features.starship.active.ActiveControlledStarship import net.horizonsend.ion.server.features.starship.active.ActiveStarships import net.horizonsend.ion.server.features.starship.ai.spawning.AISpawner import net.horizonsend.ion.server.features.starship.control.controllers.Controller import net.horizonsend.ion.server.features.starship.control.controllers.NoOpController import net.horizonsend.ion.server.features.starship.control.controllers.player.ActivePlayerController import net.horizonsend.ion.server.features.starship.control.controllers.player.PlayerController import net.horizonsend.ion.server.features.starship.control.controllers.player.UnpilotedController import net.horizonsend.ion.server.features.starship.event.StarshipPilotEvent import net.horizonsend.ion.server.features.starship.event.StarshipPilotedEvent import net.horizonsend.ion.server.features.starship.event.StarshipUnpilotEvent import net.horizonsend.ion.server.features.starship.event.StarshipUnpilotedEvent import net.horizonsend.ion.server.features.starship.hyperspace.Hyperspace import net.horizonsend.ion.server.features.starship.subsystem.LandingGearSubsystem import net.horizonsend.ion.server.features.starship.subsystem.MiningLaserSubsystem import net.horizonsend.ion.server.features.starship.subsystem.shield.ShieldSubsystem import net.horizonsend.ion.server.features.starship.subsystem.shield.StarshipShields import net.horizonsend.ion.server.features.transport.Extractors import net.horizonsend.ion.server.miscellaneous.utils.Tasks import net.horizonsend.ion.server.miscellaneous.utils.Vec3i import net.horizonsend.ion.server.miscellaneous.utils.actualType import net.horizonsend.ion.server.miscellaneous.utils.blockKeyX import net.horizonsend.ion.server.miscellaneous.utils.blockKeyY import net.horizonsend.ion.server.miscellaneous.utils.blockKeyZ import net.horizonsend.ion.server.miscellaneous.utils.bukkitWorld import net.horizonsend.ion.server.miscellaneous.utils.createData import net.horizonsend.ion.server.miscellaneous.utils.isPilot import net.horizonsend.ion.server.miscellaneous.utils.listen import net.kyori.adventure.audience.Audience import net.kyori.adventure.key.Key import net.kyori.adventure.sound.Sound import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.NamedTextColor import net.kyori.adventure.text.minimessage.MiniMessage import org.bukkit.Bukkit import org.bukkit.Material import org.bukkit.World import org.bukkit.block.data.BlockData import org.bukkit.boss.BarColor import org.bukkit.boss.BarStyle import org.bukkit.boss.BossBar import org.bukkit.entity.Player import org.bukkit.event.player.PlayerJoinEvent import org.bukkit.event.player.PlayerQuitEvent import java.util.Locale import java.util.UUID import kotlin.collections.component1 import kotlin.collections.component2 import kotlin.collections.set object PilotedStarships : IonServerComponent() { internal val map = mutableMapOf<Controller, ActiveControlledStarship>() override fun onEnable() { listen<PlayerQuitEvent> { event -> val loc = Vec3i(event.player.location) val controller = ActiveStarships.findByPilot(event.player)?.controller ?: return@listen val starship = map[controller] ?: return@listen unpilot(starship) // release the player's starship if they are piloting one starship.pilotDisconnectLocation = loc } listen<PlayerJoinEvent> { event -> val starship = getUnpiloted(event.player) ?: return@listen val loc = starship.pilotDisconnectLocation ?: return@listen tryPilot(event.player, starship.data) event.player.teleport(loc.toLocation(starship.world)) event.player.success("Since you logged out while piloting, you were teleported back to your starship") } } fun pilot(starship: ActiveControlledStarship, controller: Controller, callback: (ActiveControlledStarship) -> Unit = {}) { Tasks.checkMainThread() check(!starship.isExploding) map[controller] = starship starship.setController(controller) setupPassengers(starship) setupShieldDisplayIndicators(starship) StarshipShields.updateShieldBars(starship) removeExtractors(starship) callback(starship) } fun pilot(starship: ActiveControlledStarship, player: Player) { ActiveStarships.findByPilot(player)?.controller?.let { check(!map.containsKey(it)) { "${player.name} is already piloting a starship" } } check(starship.isWithinHitbox(player)) { "${player.name} is not in their ship!" } removeFromCurrentlyRidingShip(player) pilot(starship, ActivePlayerController(player, starship)) { ship -> saveLoadshipData(ship, player) StarshipPilotedEvent(ship, player).callEvent() } } fun changeController(starship: ActiveControlledStarship, newController: Controller) { map.remove(starship.controller) map[newController] = starship } private fun removeFromCurrentlyRidingShip(player: Player) { ActiveStarships.findByPassenger(player)?.removePassenger(player.uniqueId) } private fun setupPassengers(starship: ActiveControlledStarship) { starship.playerPilot?.let { starship.addPassenger(it.uniqueId) } for (otherPlayer in starship.world.players) { if (!starship.isWithinHitbox(otherPlayer)) { continue } if (ActiveStarships.findByPassenger(otherPlayer) != null) { continue } starship.addPassenger(otherPlayer.uniqueId) } } private fun setupShieldDisplayIndicators(starship: ActiveControlledStarship) { starship.shields .distinctBy(ShieldSubsystem::name) .associateByTo(starship.shieldBars, ShieldSubsystem::name) { shield: ShieldSubsystem -> // create the actualStyle boss bar val bar: BossBar = Bukkit.createBossBar(shield.name, BarColor.GREEN, BarStyle.SEGMENTED_10) if (shield.isReinforcementActive()) bar.color = BarColor.PURPLE // add all passengers starship.onlinePassengers.forEach(bar::addPlayer) starship.shieldBars[shield.name] = bar bar } } private fun saveLoadshipData(starship: ActiveControlledStarship, player: Player) { val schematic = StarshipSchematic.createSchematic(starship) val key = "starships.lastpiloted.${player.uniqueId}.${starship.world.name.lowercase(Locale.getDefault())}" Tasks.async { redis { set(key, Blueprint.createData(schematic)) } } } private fun removeExtractors(starship: ActiveControlledStarship) { starship.iterateBlocks { x, y, z -> if (starship.world.getBlockAt(x, y, z).type == Material.CRAFTING_TABLE) { Extractors.remove(starship.world, Vec3i(x, y, z)) } } } fun isPiloted(starship: ActiveControlledStarship): Boolean { if (starship.controller is UnpilotedController) return false if (starship.controller is NoOpController) return false return true } fun canTakeControl(starship: ActiveControlledStarship, player: Player): Boolean { return (starship.controller as? PlayerController)?.player?.uniqueId == player.uniqueId } fun unpilot(starship: ActiveControlledStarship) { Tasks.checkMainThread() val controller = starship.controller starship.setDirectControlEnabled(false) val unpilotedController = when (controller) { is PlayerController -> UnpilotedController(controller) else -> NoOpController(starship, starship.controller.damager) } map.remove(starship.controller) starship.setController(unpilotedController, updateMap = false) starship.lastUnpilotTime = System.nanoTime() starship.clearPassengers() starship.shieldBars.values.forEach { it.removeAll() } starship.shieldBars.clear() starship.iterateBlocks { x, y, z -> if (starship.world.getBlockAt(x, y, z).type == Material.CRAFTING_TABLE) { Extractors.add(starship.world, Vec3i(x, y, z)) } } StarshipUnpilotedEvent(starship, controller).callEvent() } fun getUnpiloted(player: Player): ActiveControlledStarship? = map.filter { (controller, _) -> controller is UnpilotedController && controller.player.uniqueId == player.uniqueId }.values.firstOrNull() operator fun get(player: Player): ActiveControlledStarship? = get(player.uniqueId) operator fun get(player: UUID): ActiveControlledStarship? = map.entries.firstOrNull { (controller, _) -> (controller as? PlayerController)?.player?.uniqueId == player }?.value operator fun get(controller: Controller) = map[controller] fun activateWithoutPilot( feedbackDestination: Audience, data: StarshipData, createController: (ActiveControlledStarship) -> Controller, callback: (ActiveControlledStarship) -> Unit = {} ): Boolean { val world: World = data.bukkitWorld() val state: StarshipState = DeactivatedPlayerStarships.getSavedState(data) ?: throw AISpawner.SpawningException("Not detected.", world, Vec3i(data.blockKey)) for ((key: Long, blockData: BlockData) in state.blockMap) { val x: Int = blockKeyX(key) val y: Int = blockKeyY(key) val z: Int = blockKeyZ(key) val foundData: BlockData = world.getBlockAt(x, y, z).blockData if (blockData.material != foundData.material) { val expected: String = blockData.material.name val found: String = foundData.material.name throw AISpawner.SpawningException( "Block at $x, $y, $z does not match! Expected $expected but found $found", world, Vec3i(data.blockKey) ) } if (foundData.material == StarshipComputers.COMPUTER_TYPE) { if (ActiveStarships.getByComputerLocation(world, x, y, z) != null) { throw AISpawner.SpawningException( "Block at $x, $y, $z is the computer of a piloted ship!", world, Vec3i(data.blockKey) ) } } } DeactivatedPlayerStarships.activateAsync(feedbackDestination, data, state, listOf()) { activePlayerStarship -> pilot(activePlayerStarship, createController(activePlayerStarship)) activePlayerStarship.sendMessage( Component.text("Activated and piloted ").color(NamedTextColor.GREEN) .append(getDisplayName(data)) .append(Component.text(" with ${activePlayerStarship.initialBlockCount} blocks.")) ) callback(activePlayerStarship) } return true } fun tryPilot(player: Player, data: StarshipData, callback: (ActiveControlledStarship) -> Unit = {}): Boolean { if (data !is PlayerStarshipData) { player.userError("You cannot pilot a non-player starship!") return false } if (!data.isPilot(player)) { val captain = SLPlayer.getName(data.captain) ?: "null, <red>something's gone wrong, please contact staff" player.userErrorActionMessage("You're not a pilot of this, the captain is $captain") return false } if (!data.starshipType.actualType.canUse(player)) { player.userErrorActionMessage("You are not high enough level to pilot this!") return false } val pilotedStarship = PilotedStarships[player] if (pilotedStarship != null) { if (pilotedStarship.dataId == data._id) { tryRelease(pilotedStarship) return false } player.userErrorActionMessage("You're already piloting a starship!") return false } if (!StarshipPilotEvent(player, data).callEvent()) { return false } // handle starship being already activated val activeStarship = ActiveStarships[data._id] if (activeStarship != null) { if (!canTakeControl(activeStarship, player)) { player.userErrorActionMessage("That starship is already being piloted!") return false } if (!activeStarship.isWithinHitbox(player)) { player.userError("You need to be inside the ship to pilot it") return false } pilot(activeStarship, player) player.successActionMessage("Piloted already activated starship") return false } val world: World = data.bukkitWorld() val state: StarshipState? = DeactivatedPlayerStarships.getSavedState(data) if (state == null) { player.userErrorActionMessage("Starship has not been detected") return false } for (nearbyPlayer in player.world.getNearbyPlayers(player.location, 500.0)) { nearbyPlayer.playSound(Sound.sound(Key.key("minecraft:block.beacon.activate"), Sound.Source.AMBIENT, 5f, 0.05f)) } val carriedShips = mutableListOf<StarshipData>() for ((key: Long, blockData: BlockData) in state.blockMap) { val x: Int = blockKeyX(key) val y: Int = blockKeyY(key) val z: Int = blockKeyZ(key) val foundData: BlockData = world.getBlockAt(x, y, z).blockData if (blockData.material != foundData.material) { val expected: String = blockData.material.name val found: String = foundData.material.name player.userError( "Block at $x, $y, $z does not match! Expected $expected but found $found" ) return false } if (foundData.material == StarshipComputers.COMPUTER_TYPE) { if (ActiveStarships.getByComputerLocation(world, x, y, z) != null) { player.userError( "Block at $x, $y, $z is the computer of a piloted ship!" ) return false } DeactivatedPlayerStarships[world, x, y, z]?.takeIf { it._id != data._id }?.also { carried -> if (carried is PlayerStarshipData) { //TODO access system for non-player ships if (!carried.isPilot(player)) { player.userError( "Block at $x $y $z is a ship computer which you are not a pilot of!" ) return false } carriedShips.add(carried) } else { player.userError("Block at $x, $y, $z is a non-player ship computer!") return false } } } } DeactivatedPlayerStarships.activateAsync(player, data, state, carriedShips) { activePlayerStarship -> // if the player logs out while it is piloting, deactivate it if (!player.isOnline) { DeactivatedPlayerStarships.deactivateAsync(activePlayerStarship) return@activateAsync } if (!activePlayerStarship.isWithinHitbox(player)) { player.userError("You need to be inside the ship to pilot it") DeactivatedPlayerStarships.deactivateAsync(activePlayerStarship) return@activateAsync } if (activePlayerStarship.drillCount > 16) { player.userError("Ships can not have more that 16 drills! Count: ${activePlayerStarship.drillCount}") DeactivatedPlayerStarships.deactivateAsync(activePlayerStarship) return@activateAsync } val miningLasers = activePlayerStarship.subsystems.filterIsInstance<MiningLaserSubsystem>() if (miningLasers.any { it.multiblock.tier != activePlayerStarship.type.miningLaserTier }) { player.userError("Your starship can only support tier ${activePlayerStarship.type.miningLaserTier} mining lasers!") DeactivatedPlayerStarships.deactivateAsync(activePlayerStarship) return@activateAsync } val landingGear = activePlayerStarship.subsystems.filterIsInstance<LandingGearSubsystem>() for (landingGearSubsystem in landingGear) { landingGearSubsystem.setExtended(false) } pilot(activePlayerStarship, player) player.sendMessage( Component.text("Activated and piloted ").color(NamedTextColor.GREEN) .append(activePlayerStarship.getDisplayName()) .append(Component.text(" with ${activePlayerStarship.initialBlockCount} blocks.")) ) if (carriedShips.any()) { player.information( "${carriedShips.size} carried ship${if (carriedShips.size != 1) "s" else ""}." ) } callback(activePlayerStarship) } return true } fun tryRelease(starship: ActiveControlledStarship): Boolean { val controller = starship.controller if (!StarshipUnpilotEvent(starship, controller).callEvent()) return false if (Hyperspace.isMoving(starship)) { starship.userError("Cannot release while moving through hyperspace! You'd be lost to the void!") return false } unpilot(starship) DeactivatedPlayerStarships.deactivateAsync(starship) for (nearbyPlayer in starship.world.getNearbyPlayers(starship.centerOfMass.toLocation(starship.world), 500.0)) { nearbyPlayer.playSound(Sound.sound(Key.key("minecraft:block.beacon.deactivate"), Sound.Source.AMBIENT, 5f, 0.05f)) } controller.successActionMessage("Released ${starship.getDisplayNameMiniMessage()}") return true } fun getDisplayName(data: StarshipData): Component = data.name?.let { MiniMessage.miniMessage().deserialize(it) } ?: data.starshipType.actualType.displayNameComponent }
9
null
36
9
6b1c7ef99d08424b4e9dec08e2611e823af0ddc8
16,835
Ion
MIT License
dependency-analyzer/src/test/kotlin/de/accso/dependencyanalyzer/testset/testpackage6/TargetUsedInCompanionObject.kt
accso
417,084,915
false
{"Shell": 2, "Maven POM": 6, "Text": 3, "Ignore List": 3, "Markdown": 1, "INI": 3, "Java": 175, "XML": 2, "Kotlin": 31, "Java Properties": 1, "SQL": 3, "YAML": 1}
package de.accso.dependencyanalyzer.testset.testpackage6 class ClazzHavingCompanionObjectUsingTarget { companion object { val target = TargetUsedInCompanionObject("foo") } } class TargetUsedInCompanionObject(val s: String)
0
Java
0
2
24d330e6469b72d07fb3e44f56b404bd4123c298
240
static-code-analysis-archunit
Apache License 2.0
src/main/java/com/vladsch/md/nav/actions/styling/ListToggleStateSelectionAction.kt
vsch
32,095,357
false
null
// Copyright (c) 2015-2023 <NAME> <<EMAIL>> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.actions.styling import com.intellij.lang.ASTNode import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.project.DumbAware import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.vladsch.flexmark.util.sequence.Range import com.vladsch.md.nav.actions.handlers.util.CaretContextInfo import com.vladsch.md.nav.actions.styling.util.DisabledConditionBuilder import com.vladsch.md.nav.actions.styling.util.ElementListBag import com.vladsch.md.nav.actions.styling.util.ElementType import com.vladsch.md.nav.actions.styling.util.MdActionUtil import com.vladsch.md.nav.psi.element.* import com.vladsch.md.nav.psi.util.MdPsiImplUtil import com.vladsch.md.nav.psi.util.MdTokenSets import com.vladsch.md.nav.psi.util.MdTypes import com.vladsch.plugin.util.maxLimit import com.vladsch.plugin.util.minLimit import com.vladsch.plugin.util.psi.isTypeIn import java.util.* import java.util.function.Function abstract class ListToggleStateSelectionAction : ToggleAction(), DumbAware, Function<PsiElement, ElementType> { protected abstract fun performAction(editContext: CaretContextInfo, elementBag: ElementListBag<ElementType>) protected abstract fun wantElement(element: PsiElement): Boolean protected abstract fun isSelected(editContext: CaretContextInfo, elementBag: ElementListBag<ElementType>): Boolean protected abstract fun wantUnselectedChildItems(): Boolean private fun adjustNoSelectionRange(editContext: CaretContextInfo): Range { var element = editContext.findElementAt((editContext.caretLineEnd - 1).minLimit(editContext.caretLineStart)) if (element?.node?.elementType === MdTypes.EOL) { // take the element at previous caret position element = editContext.findElementAt((editContext.caretLineEnd - 2).minLimit(editContext.caretLineStart)) } if (element != null) { var parent = element.parent while (parent !is PsiFile && parent !is MdList && parent !is MdListItem) parent = parent.parent if (parent is MdListItem) { return if (wantUnselectedChildItems()) { editContext.nodeRange(parent.node) } else { // just take the first line val postEditNodeStart = editContext.postEditNodeStart(parent.node) Range.of(postEditNodeStart, editContext.offsetLineEnd(postEditNodeStart)!!) } } else if (parent is MdList) { return if (wantUnselectedChildItems()) { // take the first list item of the list editContext.nodeRange(parent.firstChild.node) } else { // just take the first line val postEditNodeStart = editContext.postEditNodeStart(parent.firstChild.node) Range.of(postEditNodeStart, editContext.offsetLineEnd(postEditNodeStart)!!) } } } return Range.of(editContext.caretLineStart, editContext.caretLineEnd) } override fun isSelected(e: AnActionEvent): Boolean { var state = false editContext(e, true) { editContext -> val elementBag = ElementListBag<ElementType>(this) if (collectSelectedElements(editContext, true, elementBag) && elementBag.size > 0) { state = isSelected(editContext, elementBag) } } return state } open fun isEnabled(editContext: CaretContextInfo, elementBag: ElementListBag<ElementType>): Boolean { return elementBag.size > 0 } open fun conditionDone(conditionBuilder: DisabledConditionBuilder) { conditionBuilder.done(true, false) } override fun update(e: AnActionEvent) { val conditionBuilder = MdActionUtil.getConditionBuilder(e, this) { it, (_, _, _) -> caretContextInfoOrNull(e, true) { editContext -> it.notNull(editContext) { val elementBag = ElementListBag(this) collectSelectedElements(editContext!!, true, elementBag) it.and(isEnabled(editContext, elementBag), "No compatible list items in context") } } } conditionDone(conditionBuilder) super.update(e) } override fun isDumbAware(): Boolean { return false } override fun apply(element: PsiElement): ElementType { if (element is MdListItem) { val taskItemMarker = element.taskItemMarker return when { taskItemMarker?.elementType == MdTypes.TASK_ITEM_MARKER -> ElementType.TASK_LIST_ITEM taskItemMarker?.elementType == MdTypes.TASK_DONE_ITEM_MARKER -> ElementType.TASK_LIST_DONE_ITEM element is MdOrderedListItem -> ElementType.ORDERED_LIST_ITEM else -> ElementType.UNORDERED_LIST_ITEM } } else if (element is MdParagraph) { return ElementType.PARAGRAPH_BLOCK } return ElementType.NONE } private fun wantChildren(startOffset: Int, endOffset: Int, topElement: PsiElement, limitTime: Boolean, elementBag: ElementListBag<ElementType>): Boolean { var element = topElement.firstChild while (element != null) { if (element.node.startOffset >= endOffset) break if (element.node.startOffset + element.node.textLength < startOffset) { element = element.nextSibling continue } if (element.node.startOffset >= startOffset) { if (wantElement(element)) { elementBag.add(element) if (limitTime && elementBag.size > 100) return false } } wantChildren(startOffset, endOffset, element, limitTime, elementBag) element = element.nextSibling } return true } private fun collectSelectedElements(editContext: CaretContextInfo, limitTime: Boolean, elementBag: ElementListBag<ElementType>): Boolean { val editor = editContext.editor val psiFile = editContext.file val startOffset: Int val endOffset: Int if (editContext.editor.caretModel.primaryCaret.hasSelection()) { startOffset = editor.caretModel.primaryCaret.selectionStart endOffset = editor.caretModel.primaryCaret.selectionEnd } else { val range = adjustNoSelectionRange(editContext) startOffset = range.start endOffset = range.end } var element = psiFile.firstChild val topElements = ArrayList<PsiElement>() while (element != null) { if (element.node.startOffset >= endOffset) break if (element.node.startOffset + element.node.textLength <= startOffset) { element = element.nextSibling continue } topElements.add(element) if (limitTime && topElements.size > 100) return false element = element.nextSibling } for (topElement in topElements) { if (wantElement(topElement)) { elementBag.add(topElement) if (limitTime && elementBag.size > 100) return false } if (!wantChildren(startOffset, endOffset, topElement, limitTime, elementBag)) return false } return true } override fun setSelected(e: AnActionEvent, state: Boolean) { editContext(e, true) { editContext -> WriteCommandAction.runWriteCommandAction(editContext.file.project) { val psiFile = editContext.file val editor = editContext.editor val document = editor.document // here we have to extract elements that are desired for processing by the action // take all block elements and sub-elements that intersect the selection val elementBag = ElementListBag<ElementType>(this) collectSelectedElements(editContext, false, elementBag) performAction(editContext, elementBag) PsiDocumentManager.getInstance(psiFile.project).commitDocument(document) } } } private fun editContext(e: AnActionEvent, wantSelection: Boolean, runnable: (CaretContextInfo) -> Unit) { caretContextInfoOrNull(e, wantSelection) { if (it != null) runnable.invoke(it) } } private fun caretContextInfoOrNull(e: AnActionEvent, wantSelection: Boolean, runnable: (CaretContextInfo?) -> Unit) { MdActionUtil.getProjectEditorPsiFile(e)?.let { (_, editor, psiFile) -> var handled = false if (editor.caretModel.caretCount == 1 && (wantSelection || !editor.caretModel.primaryCaret.hasSelection())) { CaretContextInfo.withContext(psiFile, editor, null, false, editor.caretModel.primaryCaret.offset) { caretContext -> runnable.invoke(caretContext) handled = true } if (!handled) runnable.invoke(null) } } } fun togglePrefix(editContext: CaretContextInfo, elementBag: ElementListBag<ElementType>, PREFIX: CharSequence, removePrefix: Boolean, secondMarkerOnly: Boolean) { // if all items are paragraphs then we make them into items // otherwise we take all list items and we make them into our item type val allParagraphs = elementBag.countMapped(ElementType.PARAGRAPH_BLOCK) == elementBag.size val caretOffset = editContext.adjustedDocumentPosition(editContext.caretOffset) val document = editContext.editor.document if (allParagraphs) { if (elementBag.size == 1 && editContext.editor.selectionModel.hasSelection()) { // special case convert all lines to items val element = elementBag[0] val itemLines = MdPsiImplUtil.linesForWrapping(element, true, true, true, editContext) val selectionStart = editContext.editor.selectionModel.selectionStart val selectionEnd = editContext.editor.selectionModel.selectionEnd for (info in itemLines) { val sourceStart = info.text.startOffset val sourceEnd = info.text.endOffset if (sourceEnd <= selectionStart || sourceStart >= selectionEnd) { // not included, gets no prefix } else { // NOTE: add prefix as text so that it is not lost when copying without prefixes below itemLines.setLine(info.index, info.prefix, info.text.prefixWith(PREFIX)) } } val prefixes = MdPsiImplUtil.getBlockPrefixes(element, null, editContext) val prefixedLines = itemLines.copyAppendable() MdPsiImplUtil.addLinePrefix(prefixedLines, prefixes.childPrefix, prefixes.childContPrefix) document.replaceString(element.node.startOffset, element.node.startOffset + element.node.textLength, prefixedLines.toSequence()) } else { val selectionStart = editContext.editor.selectionModel.selectionStart for (element in elementBag.reversed()) { document.insertString(element.node.startOffset, PREFIX) } if (editContext.editor.selectionModel.hasSelection()) { val selectionEnd = editContext.editor.selectionModel.selectionEnd editContext.editor.selectionModel.setSelection(selectionStart, selectionEnd) } } } else if (removePrefix && !secondMarkerOnly) { val blankLines = HashSet<Int>() var insertBlankLines = false // need to handle a special case of tight list with all elements being one line for ((index, element) in elementBag.withIndex()) { if (element is MdListItem) { if (index + 1 < elementBag.size && MdPsiImplUtil.isFollowedByBlankLine(element)) { insertBlankLines = true break } val textLinesToWrap = MdPsiImplUtil.linesForWrapping(element, true, true, true, editContext) if (textLinesToWrap.lineCount > 1) { insertBlankLines = true break } } } for (element in elementBag.reversed()) { if (element is MdListItem) { val itemMarker = element.listItemMarker ?: continue var taskItemMarker = element.taskItemMarker ?: itemMarker if (!taskItemMarker.isTypeIn(MdTokenSets.TASK_LIST_ITEM_MARKERS)) taskItemMarker = itemMarker val insertBlankLineBefore = insertBlankLines && element.node.startOffset > 0 && !MdPsiImplUtil.isPrecededByBlankLine(element) if (insertBlankLines && !MdPsiImplUtil.isFollowedByBlankLine(element)) { val lineNumber = editContext.offsetLineNumber(editContext.postEditNodeEnd(element.node) - 1) if (lineNumber != null && !blankLines.contains(lineNumber + 1)) { blankLines.add(lineNumber + 1) MdPsiImplUtil.insertBlankLineAfter(editContext.document, element, null, editContext) } } if (insertBlankLineBefore) { val lineNumber = editContext.offsetLineNumber(editContext.postEditNodeStart(element.node)) if (lineNumber != null && !blankLines.contains(lineNumber)) { blankLines.add(lineNumber) val prefixes = MdPsiImplUtil.getBlockPrefixes(element, null, editContext) document.deleteString(itemMarker.startOffset, taskItemMarker.startOffset + taskItemMarker.textLength) val offsetLineStart = editContext.offsetLineStart(editContext.postEditNodeStart(element.node)) if (offsetLineStart != null && offsetLineStart > 0) { document.insertString(offsetLineStart, prefixes.childPrefix.suffixWithEOL()) } } } else { document.deleteString(itemMarker.startOffset, taskItemMarker.startOffset + taskItemMarker.textLength) } } } } else { for (element in elementBag.reversed()) { if (element is MdListItemImpl) { val itemMarker = element.listItemMarker ?: continue if (!secondMarkerOnly || !removePrefix) { var taskItemMarker = element.taskItemMarker ?: itemMarker var endOffset = taskItemMarker.startOffset if (!taskItemMarker.isTypeIn(MdTokenSets.TASK_LIST_ITEM_MARKERS)) { taskItemMarker = itemMarker endOffset = itemMarker.startOffset + itemMarker.textLength if (endOffset < document.textLength && document.charsSequence[endOffset] == ' ') endOffset++ } val prefix = adjustItemPrefix(element, itemMarker, taskItemMarker, PREFIX, removePrefix) if (secondMarkerOnly) { if (taskItemMarker == itemMarker) return endOffset = taskItemMarker.startOffset + taskItemMarker.textLength if (endOffset < document.textLength && document.charsSequence[endOffset] == ' ') endOffset++ document.replaceString(taskItemMarker.startOffset, endOffset, prefix) } else { document.replaceString(itemMarker.startOffset, endOffset, prefix) } } else { val taskItemMarker = MdPsiImplUtil.nextNonWhiteSpaceSibling(itemMarker) ?: continue if (!taskItemMarker.isTypeIn(MdTokenSets.TASK_LIST_ITEM_MARKERS)) continue val prefix = adjustItemPrefix(element, itemMarker, taskItemMarker, PREFIX, removePrefix) document.replaceString(itemMarker.startOffset, (taskItemMarker.startOffset + taskItemMarker.textLength.minLimit(4)).maxLimit(document.textLength), prefix) } } } } editContext.editor.caretModel.moveToOffset(caretOffset.adjustedOffset) } protected open fun adjustItemPrefix(element: MdListItemImpl, itemMarker: ASTNode?, taskItemMarker: ASTNode?, prefix: CharSequence, removePrefix: Boolean): CharSequence { return prefix } }
134
null
131
809
ec413c0e1b784ff7309ef073ddb4907d04345073
17,506
idea-multimarkdown
Apache License 2.0
core/src/commonMain/kotlin/bruhcollective/itaysonlab/ksteam/AuthPrivateIpLogic.kt
iTaysonLab
585,761,817
false
{"Kotlin": 605935}
package bruhcollective.itaysonlab.ksteam /** * Specifies a source of private IP used when creating a session. * * It's recommended to use the default value of [UsePrivateIp] to avoid being logged out if another client will try to sign in. */ enum class AuthPrivateIpLogic { /** * Uses current machine's private IP. * * This is the recommended approach which is used in the official client and other Steam Network libraries. * Note that this method can cause collisions - mostly in the situations when an official Steam client is launched on a PC with a running kSteam instance (or vice versa). * * On Apple platforms, it will fall back to [Generate] because current API usage can lead to the App Store rules violation. */ UsePrivateIp, /** * Generates a random integer and passes this as an IP. * * Not recommended because there is no guarantee Steam would accept a session with "faked" IP. */ Generate, /** * Do not send any private IP. * * This can be used for some "privacy", but note that any sign-in from other device/application might log you out of this kSteam instance. */ None }
1
Kotlin
1
35
69f547a200a6eb4d89463d7ccd1e89f5ebae2162
1,193
kSteam
MIT License
app/src/main/java/com/daya/taha/presentation/splash/SplashFragment.kt
daya-pangestu
308,078,972
false
{"Kotlin": 140694}
package com.daya.taha.presentation.splash import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.daya.shared.taha.data.Resource import com.daya.taha.R import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.delay import kotlinx.coroutines.launch import timber.log.Timber @AndroidEntryPoint class SplashFragment : Fragment(R.layout.fragment_splash) { private val viewModel by viewModels<SplashViewModel>() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) lifecycleScope.launch { Timber.i("starting to delay") delay(1000) Timber.i("delayed loading for 300 ms") observeLoginStatus() } } private fun observeLoginStatus() { viewModel.isUserLoggedIn.observe(viewLifecycleOwner){ when (it) { is Resource.Loading -> Timber.wtf("impossible loading state : ") is Resource.Success -> { if (it.data) { findNavController().navigate(R.id.action_splashFragment_to_home) } else { findNavController().navigate(R.id.action_splashFragment_to_loginFragment) } } is Resource.Error -> Timber.wtf("impossible error state : ${it.exceptionMessage} ") } } } }
0
Kotlin
0
1
a52e7e6f0c5343e491db3a1551ac183ac9f72ed8
1,606
push-notif
MIT License
image-loader/src/commonMain/kotlin/com/seiko/imageloader/cache/CachePolicy.kt
qdsfdhvh
502,954,331
false
null
package com.seiko.imageloader.cache /** * Represents the read/write policy for a cache source. */ enum class CachePolicy( val readEnabled: Boolean, val writeEnabled: Boolean ) { ENABLED(true, true), READ_ONLY(true, false), WRITE_ONLY(false, true), DISABLED(false, false) }
8
Kotlin
4
90
d9c86b3bb21817f1c0d2517dc2bebcd7ebf8642a
300
compose-imageloader
MIT License
samples/tictactoe/app/src/main/java/com/squareup/sample/mainactivity/MainActivity.kt
zradke
274,298,365
true
{"Kotlin": 1241660, "Swift": 490818, "Ruby": 19852, "Shell": 7472, "Java": 850}
/* * Copyright 2017 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.sample.mainactivity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.test.espresso.IdlingResource import com.squareup.sample.authworkflow.AuthViewBindings import com.squareup.sample.container.SampleContainers import com.squareup.sample.gameworkflow.TicTacToeViewBindings import com.squareup.workflow.diagnostic.SimpleLoggingDiagnosticListener import com.squareup.workflow.diagnostic.andThen import com.squareup.workflow.diagnostic.tracing.TracingDiagnosticListener import com.squareup.workflow.ui.WorkflowRunner import com.squareup.workflow.ui.plus import com.squareup.workflow.ui.setContentWorkflow import io.reactivex.disposables.Disposables import timber.log.Timber class MainActivity : AppCompatActivity() { private var loggingSub = Disposables.disposed() private lateinit var component: MainComponent /** Exposed for use by espresso tests. */ lateinit var idlingResource: IdlingResource override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // TODO: https://github.com/square/workflow/issues/603 Remove use of deprecated property. @Suppress("DEPRECATION") component = lastCustomNonConfigurationInstance as? MainComponent ?: MainComponent() idlingResource = component.idlingResource val traceFile = getExternalFilesDir(null)?.resolve("workflow-trace-tictactoe.json")!! val workflowRunner = setContentWorkflow( registry = viewRegistry, configure = { WorkflowRunner.Config( component.mainWorkflow, diagnosticListener = object : SimpleLoggingDiagnosticListener() { override fun println(text: String) = Timber.v(text) }.andThen(TracingDiagnosticListener(traceFile)) ) }, // The sample MainWorkflow emits a Unit output when it is done, which means it's // time to end the activity. onResult = { finish() } ) loggingSub = workflowRunner.renderings.subscribe { Timber.d("rendering: %s", it) } } override fun onRetainCustomNonConfigurationInstance(): Any = component override fun onDestroy() { loggingSub.dispose() super.onDestroy() } private companion object { val viewRegistry = SampleContainers + AuthViewBindings + TicTacToeViewBindings } }
0
null
0
0
cffc161ed2f24414d1abba7a2a07dc79fbefb919
2,948
workflow-kotlin
Apache License 2.0
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/kotlin/org/jetbrains/kotlin/gradle/KotlinDaemonJvmArgsTest.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle import org.gradle.api.logging.LogLevel import org.gradle.testkit.runner.BuildResult import org.gradle.tooling.internal.consumer.ConnectorServices import org.gradle.util.GradleVersion import org.jetbrains.kotlin.gradle.testbase.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.DisplayName @DisplayName("Kotlin daemon JVM args") class KotlinDaemonJvmArgsTest : KGPDaemonsBaseTest() { override val defaultBuildOptions: BuildOptions get() = super.defaultBuildOptions.copy(logLevel = LogLevel.DEBUG) @GradleTest @DisplayName("Kotlin daemon by default should inherit Gradle daemon max jvm heap size") internal fun shouldInheritGradleDaemonArgsByDefault(gradleVersion: GradleVersion) { project("simpleProject", gradleVersion) { gradleProperties.append( """ org.gradle.jvmargs = -Xmx758m """.trimIndent() ) build("assemble") { assertKotlinDaemonJvmOptions( listOf("-Xmx758m") ) } } } @DisplayName("Kotlin daemon should allow to define own jvm options via gradle daemon jvm args system property") @GradleTest internal fun shouldAllowToRedefineViaDGradleOption(gradleVersion: GradleVersion) { project("simpleProject", gradleVersion) { gradleProperties.append( """ org.gradle.jvmargs =-Xmx758m -Dkotlin.daemon.jvm.options=Xmx1g,Xms128m """.trimIndent() ) build("assemble") { assertKotlinDaemonJvmOptions( listOf("-Xmx1g", "--Xms128m") ) } } } @DisplayName("Jvm args defined in gradle.properties should override Gradle daemon jvm arguments inheritance") @GradleTest internal fun shouldUseArgumentsFromGradleProperties(gradleVersion: GradleVersion) { project("simpleProject", gradleVersion) { gradleProperties.append( """ org.gradle.jvmargs =-Xmx758m -Xms128m kotlin.daemon.jvmargs = -Xmx486m -Xms256m """.trimIndent() ) build("assemble") { assertKotlinDaemonJvmOptions( listOf("-Xmx486m", "--Xms256m") ) } } } @DisplayName("Should use arguments from extension DSL") @GradleTest internal fun shouldUseDslArguments(gradleVersion: GradleVersion) { project("simpleProject", gradleVersion) { gradleProperties.append( """ org.gradle.jvmargs =-Xmx758m -Xms128m """.trimIndent() ) //language=Groovy buildGradle.append( """ kotlin { kotlinDaemonJvmArgs = ["-Xmx486m", "-Xms256m", "-Duser.country=US"] } """.trimIndent() ) build("assemble") { assertKotlinDaemonJvmOptions( listOf("-Xmx486m", "--Xms256m", "--Duser.country=US") ) } } } @DisplayName("Should allow to override global arguments for specific task") @GradleTest internal fun allowOverrideArgsForSpecificTask(gradleVersion: GradleVersion) { project( projectName = "simpleProject", gradleVersion = gradleVersion ) { gradleProperties.append( """ org.gradle.jvmargs = -Xmx758m -Xms128m kotlin.daemon.jvmargs = -Xmx486m -Xms256m """.trimIndent() ) //language=Groovy buildGradle.append( """ import org.jetbrains.kotlin.gradle.tasks.CompileUsingKotlinDaemon tasks .matching { it.name == "compileTestKotlin" && it instanceof CompileUsingKotlinDaemon } .configureEach { kotlinDaemonJvmArguments.set(["-Xmx1g", "-Xms512m"]) } """.trimIndent() ) build("build") { assertKotlinDaemonJvmOptions( listOf("-Xmx486m", "--Xms256m") ) assertKotlinDaemonJvmOptions( listOf("-Xmx1g", "--Xms512m") ) } } } @DisplayName("Should inherit Gradle memory settings if it is not set in Kotlin daemon jvm args") @GradleTest fun inheritGradleMemorySettingsIfKotlinArgsNotContain(gradleVersion: GradleVersion) { project("simpleProject", gradleVersion) { gradleProperties.append( """ org.gradle.jvmargs =-Xmx758m -Xms128m """.trimIndent() ) //language=Groovy buildGradle.append( """ kotlin { kotlinDaemonJvmArgs = ["-Duser.country=US"] } """.trimIndent() ) build("assemble") { assertKotlinDaemonJvmOptions( listOf("-Xmx758m", "--Duser.country=US") ) } } } private fun BuildResult.assertKotlinDaemonJvmOptions( expectedOptions: List<String> ) { val jvmArgsCommonMessage = "Kotlin compile daemon JVM options: " assertOutputContains(jvmArgsCommonMessage) val argsRegex = "\\[.+?]".toRegex() val argsStrings = output.lineSequence() .filter { it.contains(jvmArgsCommonMessage) } .map { argsRegex.findAll(it).last().value.removePrefix("[").removeSuffix("]").split(", ") } val containsArgs = argsStrings.any { it.containsAll(expectedOptions) } assert(containsArgs) { printBuildOutput() "${argsStrings.toList()} does not contain expected args: $expectedOptions" } } }
34
null
4903
39,894
0ad440f112f353cd2c72aa0a0619f3db2e50a483
6,527
kotlin
Apache License 2.0
modulecheck-core/src/test/kotlin/modulecheck/core/SortPluginsTest.kt
RBusarow
316,627,145
false
null
/* * Copyright (C) 2021-2022 Rick Busarow * 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 modulecheck.core import modulecheck.api.test.TestChecksSettings import modulecheck.api.test.TestSettings import modulecheck.core.rule.ModuleCheckRuleFactory import modulecheck.core.rule.MultiRuleFindingFactory import modulecheck.project.test.writeGroovy import modulecheck.project.test.writeKotlin import modulecheck.runtime.test.RunnerTest import org.junit.jupiter.api.Test import java.io.File class SortPluginsTest : RunnerTest() { val ruleFactory by resets { ModuleCheckRuleFactory() } override val settings by resets { TestSettings(checks = TestChecksSettings(sortPlugins = true)) } val findingFactory by resets { MultiRuleFindingFactory( settings, ruleFactory.create(settings) ) } @Test fun `kts out-of-order plugins should be sorted`() { val runner = runner( autoCorrect = true, findingFactory = findingFactory ) val lib1 = project(":lib1") { buildFile.writeKotlin( """ plugins { id("io.gitlab.arturbosch.detekt") version "1.15.0" javaLibrary kotlin("jvm") } """ ) } runner.run(allProjects()).isSuccess shouldBe true lib1.buildFile.readText() shouldBe """ plugins { kotlin("jvm") javaLibrary id("io.gitlab.arturbosch.detekt") version "1.15.0" } """ logger.collectReport() .joinToString() .clean() shouldBe """ :lib1 dependency name source build file ✔ unsortedPlugins /lib1/build.gradle.kts: ModuleCheck found 1 issue """.trimIndent() } @Test fun `kts sorting should be idempotent`() { val runner = runner( autoCorrect = true, findingFactory = findingFactory ) val lib1 = project(":lib1") { buildFile.writeKotlin( """ plugins { id("io.gitlab.arturbosch.detekt") version "1.15.0" javaLibrary kotlin("jvm") } """ ) } runner.run(allProjects()).isSuccess shouldBe true lib1.buildFile.readText() shouldBe """ plugins { kotlin("jvm") javaLibrary id("io.gitlab.arturbosch.detekt") version "1.15.0" } """ logger.collectReport() .joinToString() .clean() shouldBe """ :lib1 dependency name source build file ✔ unsortedPlugins /lib1/build.gradle.kts: ModuleCheck found 1 issue """.trimIndent() logger.clear() runner.run(allProjects()).isSuccess shouldBe true lib1.buildFile.readText() shouldBe """ plugins { kotlin("jvm") javaLibrary id("io.gitlab.arturbosch.detekt") version "1.15.0" } """ logger.collectReport() .joinToString() .clean() shouldBe """ModuleCheck found 0 issues""" } @Test fun `groovy out-of-order plugins should be sorted`() { val runner = runner( autoCorrect = true, findingFactory = findingFactory ) val lib1 = project(":lib1") { buildFile.delete() buildFile = File(projectDir, "build.gradle") buildFile.writeGroovy( """ plugins { id 'io.gitlab.arturbosch.detekt' version '1.15.0' javaLibrary id 'org.jetbrains.kotlin.jvm' } """ ) } runner.run(allProjects()).isSuccess shouldBe true lib1.buildFile.readText() shouldBe """ plugins { javaLibrary id 'io.gitlab.arturbosch.detekt' version '1.15.0' id 'org.jetbrains.kotlin.jvm' } """ logger.collectReport() .joinToString() .clean() shouldBe """ :lib1 dependency name source build file ✔ unsortedPlugins /lib1/build.gradle: ModuleCheck found 1 issue """.trimIndent() } @Test fun `groovy sorting should be idempotent`() { val runner = runner( autoCorrect = true, findingFactory = findingFactory ) val lib1 = project(":lib1") { buildFile.delete() buildFile = File(projectDir, "build.gradle") buildFile.writeGroovy( """ plugins { id 'io.gitlab.arturbosch.detekt' version '1.15.0' javaLibrary id 'org.jetbrains.kotlin.jvm' } """ ) } runner.run(allProjects()).isSuccess shouldBe true lib1.buildFile.readText() shouldBe """ plugins { javaLibrary id 'io.gitlab.arturbosch.detekt' version '1.15.0' id 'org.jetbrains.kotlin.jvm' } """ logger.collectReport() .joinToString() .clean() shouldBe """ :lib1 dependency name source build file ✔ unsortedPlugins /lib1/build.gradle: ModuleCheck found 1 issue """.trimIndent() logger.clear() runner.run(allProjects()).isSuccess shouldBe true lib1.buildFile.readText() shouldBe """ plugins { javaLibrary id 'io.gitlab.arturbosch.detekt' version '1.15.0' id 'org.jetbrains.kotlin.jvm' } """ logger.collectReport() .joinToString() .clean() shouldBe """ModuleCheck found 0 issues""" } }
8
null
2
8
d408e8fb5a2244b752821a93324abe773a2b7ed0
5,959
ModuleCheck
Apache License 2.0
app/src/main/java/com/samkt/filmio/navigation/BottomNavItems.kt
Sam-muigai
698,566,485
false
{"Kotlin": 257745}
package com.samkt.filmio.navigation import androidx.annotation.DrawableRes import com.samkt.filmio.R data class BottomNavItem( val label: String, val screen: Screens, @DrawableRes val unselectedIcon: Int, @DrawableRes val selectedIcon: Int ) val navigationItems = listOf( BottomNavItem( "Home", Screens.HomeScreen, R.drawable.ic_outline_home, R.drawable.ic_filled_home ), BottomNavItem( "Movies", Screens.MovieScreen, R.drawable.ic_movie_outlined, R.drawable.ic_movie_filled ), BottomNavItem( "TV Series", Screens.TvSeriesScreen, R.drawable.ic_tv_outlined, R.drawable.ic_tv_filled ), BottomNavItem( "Watch List", Screens.WatchListScreen, R.drawable.ic_outline_bookmark, R.drawable.ic_filled_bookmark ), BottomNavItem( "More", Screens.SettingsScreen, R.drawable.ic_outline_settings, R.drawable.ic_filled_settings ) )
0
Kotlin
0
0
404350965297225420445e0ef47c9170ad720e0e
1,035
Filmio
Apache License 2.0
navigation/integration-tests/testapp/src/main/java/androidx/navigation/testapp/TwoPaneAdapter.kt
RikkaW
389,105,112
true
{"Java": 49060640, "Kotlin": 36832495, "Python": 336507, "AIDL": 179831, "Shell": 150493, "C++": 38342, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation.testapp import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class TwoPaneAdapter( private val dataSet: Array<String>, private val onClick: (CharSequence) -> Unit ) : RecyclerView.Adapter<TwoPaneAdapter.ViewHolder>() { class ViewHolder(view: View, val onClick: (CharSequence) -> Unit) : RecyclerView.ViewHolder(view) { val textView: TextView = view.findViewById(R.id.list_pane_row_item) init { textView.setOnClickListener { onClick(textView.text) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TwoPaneAdapter.ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.list_pane_row_item, parent, false) return ViewHolder(view, onClick) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.textView.text = dataSet[position] } override fun getItemCount() = dataSet.size }
29
Java
937
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
1,722
androidx
Apache License 2.0
host/src/jvmMain/kotlin/jvm/JvmMonotonicClock.kt
illarionov
848,247,126
false
{"Kotlin": 1306808, "ANTLR": 6038, "TypeScript": 3148, "CSS": 1042, "FreeMarker": 450, "JavaScript": 89}
/* * Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package at.released.weh.host.jvm import at.released.weh.host.MonotonicClock internal object JvmMonotonicClock : MonotonicClock { override fun getTimeMarkNanoseconds(): Long = System.nanoTime() }
0
Kotlin
0
4
8cb136a17cbece15d9e2b0cc9286f35613a149a4
471
wasi-emscripten-host
Apache License 2.0
android/src/main/kotlin/com/vonage/tutorial/opentok/opentok_flutter_samples/OpenTokPlugin.kt
Mohammad-Abureesh
644,325,368
false
null
package com.vonage.tutorial.opentok.opentok_flutter_samples import android.os.Handler import android.os.Looper import androidx.annotation.NonNull import com.pcnc2000.flutter_open_tok_video_chat.archiving.Archiving import com.pcnc2000.flutter_open_tok_video_chat.archiving.ArchivingFactory import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel import com.pcnc2000.flutter_open_tok_video_chat.config.SdkState import com.pcnc2000.flutter_open_tok_video_chat.multi_video.MultiVideo import com.pcnc2000.flutter_open_tok_video_chat.multi_video.MultiVideoFactory import com.pcnc2000.flutter_open_tok_video_chat.one_to_one_video.OneToOneVideo import com.pcnc2000.flutter_open_tok_video_chat.one_to_one_video.OpentokVideoFactory import com.pcnc2000.flutter_open_tok_video_chat.screen_sharing.ScreenSharing import com.pcnc2000.flutter_open_tok_video_chat.screen_sharing.ScreenSharingFactory import com.pcnc2000.flutter_open_tok_video_chat.singaling.Signalling import io.flutter.plugin.common.BinaryMessenger import io.flutter.embedding.engine.plugins.FlutterPlugin class OpenTokPlugin:FlutterPlugin{ val oneToOneVideoMethodChannel = "com.vonage.one_to_one_video" val signallingMethodChannel = "com.vonage.signalling" val screenSharingMethodChannel = "com.vonage.screen_sharing" val archivingMethodChannel = "com.vonage.archiving" val multiVideoMethodChannel = "com.vonage.multi_video" private var oneToOneVideo: OneToOneVideo? = null private var signalling: Signalling? = null private var screenSharing: ScreenSharing? = null private var archiving: Archiving? = null private var multiVideo: MultiVideo? = null override fun onAttachedToEngine(flutterEngine: FlutterPlugin.FlutterPluginBinding) { oneToOneVideo = OneToOneVideo(this) signalling = Signalling(this) screenSharing = ScreenSharing(this) archiving = Archiving(this) multiVideo = MultiVideo(this) flutterEngine .platformViewRegistry .registerViewFactory("opentok-video-container", OpentokVideoFactory()) flutterEngine .platformViewRegistry .registerViewFactory("opentok-screenshare-container", ScreenSharingFactory()) flutterEngine .platformViewRegistry .registerViewFactory("opentok-archiving-container", ArchivingFactory()) flutterEngine .platformViewRegistry .registerViewFactory("opentok-multi-video-container", MultiVideoFactory()) addFlutterChannelListener() } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { } private fun addFlutterChannelListener() { flutterEngine?.dartExecutor?.binaryMessenger?.let { setOneToOneVideoMethodChannel(it) setSignallingMethodChannel(it) setScreenSharingMethodChannel(it) setArchivingMethodChannel(it) setMultiVideoMethodChannel(it) } } private fun setMultiVideoMethodChannel(it: BinaryMessenger) { MethodChannel(it, multiVideoMethodChannel).setMethodCallHandler { call, result -> when (call.method) { "initSession" -> { val apiKey = requireNotNull(call.argument<String>("apiKey")) val sessionId = requireNotNull(call.argument<String>("sessionId")) val token = requireNotNull(call.argument<String>("token")) updateFlutterState(SdkState.wait, multiVideoMethodChannel) multiVideo?.initSession(apiKey, sessionId, token) result.success("") } else -> { result.notImplemented() } } } } private fun setArchivingMethodChannel(it: BinaryMessenger) { MethodChannel(it, archivingMethodChannel).setMethodCallHandler { call, result -> when (call.method) { "initSession" -> { updateFlutterState(SdkState.wait, archivingMethodChannel) archiving?.getSession() result.success("") } "startArchive" -> { archiving?.startArchive() result.success("") } "stopArchive" -> { archiving?.stopArchive() result.success("") } "playArchive" -> { archiving?.playArchive() result.success("") } else -> { result.notImplemented() } } } } private fun setOneToOneVideoMethodChannel(it: BinaryMessenger) { MethodChannel(it, oneToOneVideoMethodChannel).setMethodCallHandler { call, result -> when (call.method) { "initSession" -> { val apiKey = requireNotNull(call.argument<String>("apiKey")) val sessionId = requireNotNull(call.argument<String>("sessionId")) val token = requireNotNull(call.argument<String>("token")) updateFlutterState(SdkState.wait, oneToOneVideoMethodChannel) oneToOneVideo?.initSession(apiKey, sessionId, token) result.success("") } "swapCamera" -> { oneToOneVideo?.swapCamera() result.success("") } "toggleAudio" -> { val publishAudio = requireNotNull(call.argument<Boolean>("publishAudio")) oneToOneVideo?.toggleAudio(publishAudio) result.success("") } "toggleVideo" -> { val publishVideo = requireNotNull(call.argument<Boolean>("publishVideo")) oneToOneVideo?.toggleVideo(publishVideo) result.success("") } "sendMessage" -> { val message = requireNotNull(call.argument<String>("message")) oneToOneVideo?.sendMessage(message) result.success("") } else -> { result.notImplemented() } } } } private fun setSignallingMethodChannel(it: BinaryMessenger) { MethodChannel(it, signallingMethodChannel).setMethodCallHandler { call, result -> when (call.method) { "initSession" -> { val apiKey = requireNotNull(call.argument<String>("apiKey")) val sessionId = requireNotNull(call.argument<String>("sessionId")) val token = requireNotNull(call.argument<String>("token")) signalling?.initSession(apiKey, sessionId, token) result.success("") } "sendMessage" -> { val message = requireNotNull(call.argument<String>("message")) signalling?.sendMessage(message) result.success("") } else -> { result.notImplemented() } } } } private fun setScreenSharingMethodChannel(it: BinaryMessenger) { MethodChannel(it, screenSharingMethodChannel).setMethodCallHandler { call, result -> when (call.method) { "initSession" -> { val apiKey = requireNotNull(call.argument<String>("apiKey")) val sessionId = requireNotNull(call.argument<String>("sessionId")) val token = requireNotNull(call.argument<String>("token")) updateFlutterState(SdkState.wait, screenSharingMethodChannel) screenSharing?.initSession(apiKey, sessionId, token) result.success("") } else -> { result.notImplemented() } } } } fun updateFlutterState(state: SdkState, channel: String) { Handler(Looper.getMainLooper()).post { flutterEngine?.dartExecutor?.binaryMessenger?.let { MethodChannel(it, channel) .invokeMethod("updateState", state.toString()) } } } fun updateFlutterMessages(arguments: HashMap<String, Any>, channel: String){ Handler(Looper.getMainLooper()).post { flutterEngine?.dartExecutor?.binaryMessenger?.let { MethodChannel(it, channel) .invokeMethod("updateMessages", arguments) } } } fun updateFlutterArchiving(isArchiving: Boolean, channel: String){ Handler(Looper.getMainLooper()).post { flutterEngine?.dartExecutor?.binaryMessenger?.let { MethodChannel(it, channel) .invokeMethod("updateArchiving", isArchiving) } } } }
0
Kotlin
0
0
002f1a14ac5e4a987bf64984b7883f46ee004546
9,211
flutter_open_tok_video_chat
Apache License 2.0
src/main/kotlin/com/github/oowekyala/ijcc/lang/psi/stubs/indices/JjtreeQNameStubIndex.kt
oowekyala
160,946,520
false
{"Kotlin": 636577, "HTML": 12321, "Lex": 10654, "Shell": 1940, "Just": 101}
package com.github.oowekyala.ijcc.lang.psi.stubs.indices import com.github.oowekyala.ijcc.lang.psi.JjtNodeClassOwner import com.intellij.psi.stubs.StringStubIndexExtension import com.intellij.psi.stubs.StubIndexKey /** * Indexes the node class owners of a grammar by qname, to provide * links from the node classes to the productions. * * @author <NAME> * @since 1.2 */ object JjtreeQNameStubIndex : StringStubIndexExtension<JjtNodeClassOwner>() { private val Key = StubIndexKey.createIndexKey<String, JjtNodeClassOwner>("jjtree.qname.owner") override fun getKey(): StubIndexKey<String, JjtNodeClassOwner> = Key override fun getVersion(): Int = 1 }
9
Kotlin
6
44
c514083a161db56537d2473e42f2a1d4bf57eee1
674
intellij-javacc
MIT License
compose/recomposehighlighter/src/main/java/com/example/android/compose/recomposehighlighter/RecomposeHighlighter.kt
android
138,043,025
false
null
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.compose.recomposehighlighter import androidx.compose.runtime.Stable import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.drawscope.ContentDrawScope import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.lerp import androidx.compose.ui.node.DrawModifierNode import androidx.compose.ui.node.ModifierNodeElement import androidx.compose.ui.node.invalidateDraw import androidx.compose.ui.platform.InspectorInfo import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.unit.dp import java.util.Objects import kotlin.math.min import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch /** * A [Modifier] that draws a border around elements that are recomposing. The border increases in * size and interpolates from red to green as more recompositions occur before a timeout. */ @Stable fun Modifier.recomposeHighlighter(): Modifier = this.then(RecomposeHighlighterElement()) private class RecomposeHighlighterElement : ModifierNodeElement<RecomposeHighlighterModifier>() { override fun InspectorInfo.inspectableProperties() { debugInspectorInfo { name = "recomposeHighlighter" } } override fun create(): RecomposeHighlighterModifier = RecomposeHighlighterModifier() override fun update(node: RecomposeHighlighterModifier) { node.incrementCompositions() } // It's never equal, so that every recomposition triggers the update function. override fun equals(other: Any?): Boolean = false override fun hashCode(): Int = Objects.hash(this) } private class RecomposeHighlighterModifier : Modifier.Node(), DrawModifierNode { private var timerJob: Job? = null /** * The total number of compositions that have occurred. */ private var totalCompositions: Long = 0 set(value) { if (field == value) return restartTimer() field = value invalidateDraw() } fun incrementCompositions() { totalCompositions++ } override fun onAttach() { super.onAttach() restartTimer() } override val shouldAutoInvalidate: Boolean = false override fun onDetach() { timerJob?.cancel() } /** * Start the timeout, and reset everytime there's a recomposition. */ private fun restartTimer() { if (!isAttached) return timerJob?.cancel() timerJob = coroutineScope.launch { delay(3000) totalCompositions = 0 invalidateDraw() } } override fun ContentDrawScope.draw() { // Draw actual content. drawContent() // Below is to draw the highlight, if necessary. A lot of the logic is copied from Modifier.border val hasValidBorderParams = size.minDimension > 0f if (!hasValidBorderParams || totalCompositions <= 0) { return } val (color, strokeWidthPx) = when (totalCompositions) { // We need at least one composition to draw, so draw the smallest border // color in blue. 1L -> Color.Blue to 1f // 2 compositions is _probably_ okay. 2L -> Color.Green to 2.dp.toPx() // 3 or more compositions before timeout may indicate an issue. lerp the // color from yellow to red, and continually increase the border size. else -> { lerp( Color.Yellow.copy(alpha = 0.8f), Color.Red.copy(alpha = 0.5f), min(1f, (totalCompositions - 1).toFloat() / 100f) ) to totalCompositions.toInt().dp.toPx() } } val halfStroke = strokeWidthPx / 2 val topLeft = Offset(halfStroke, halfStroke) val borderSize = Size(size.width - strokeWidthPx, size.height - strokeWidthPx) val fillArea = (strokeWidthPx * 2) > size.minDimension val rectTopLeft = if (fillArea) Offset.Zero else topLeft val size = if (fillArea) size else borderSize val style = if (fillArea) Fill else Stroke(strokeWidthPx) drawRect( brush = SolidColor(color), topLeft = rectTopLeft, size = size, style = style ) } }
28
null
655
666
514653c318c747c557f70e32aad2cc7051d44115
5,265
snippets
Apache License 2.0
cli/src/main/kotlin/dev/whyoleg/ktd/cli/tdlib/DispatchCommand.kt
whyoleg
202,767,670
false
null
package dev.whyoleg.ktd.cli.tdlib import dev.whyoleg.ktd.cli.* import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.request.* import io.ktor.client.response.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.util.* import kotlinx.cli.* import kotlinx.coroutines.* import kotlinx.serialization.json.* import java.util.* @UseExperimental(ExperimentalCli::class) class DispatchCommand : Subcommand("dispatch") { private val version by option(ArgType.String, "version", "v", "Version of tdlib").required() private val type by option(ArgType.Choice(listOf("api", "tdlib")), "type", "t", "Type of event").required() @UseExperimental(KtorExperimentalAPI::class) override fun execute() { val client = HttpClient(CIO) runBlocking { val response = client.post<HttpResponse>("https://api.github.com/repos/whyoleg/ktd/dispatches") { val token = System.getenv("GITHUB_ACCESS_TOKEN")!! headers["Accept"] = "application/vnd.github.everest-preview+json" headers["Authorization"] = "Basic " + Base64.getEncoder().encodeToString("whyoleg:$token".toByteArray()) body = TextContent(json { "event_type" to "generate_$type" "client_payload" to json { "version" to version "ref" to tdVersionRefs.getValue(version) "versions" to jsonArray { tdVersions.forEach { +it } } "refs" to json { tdVersionRefs.forEach { (v, ref) -> v to ref } } } }.toString(), ContentType.Application.Json) } println(response) println(response.status) } } }
7
Kotlin
11
45
7284eeabef0bd002dc72634351ab751b048900e9
1,950
ktd
Apache License 2.0
compiler/testData/compileKotlinAgainstCustomBinaries/replaceAnnotationClassWithInterface/library-1/Ann.kt
JakeWharton
99,388,807
false
null
package test import kotlin.annotation.AnnotationTarget.* @Target(CLASS, ANNOTATION_CLASS, TYPE_PARAMETER, PROPERTY, FIELD, LOCAL_VARIABLE, VALUE_PARAMETER, CONSTRUCTOR, FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER, TYPE, FILE) annotation class Ann(val s: String)
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
263
kotlin
Apache License 2.0
src/test/kotlin/reader/TestNodes.kt
fiddlededee
835,952,301
false
null
package reader import common.AsciidoctorAdapter import common.asciidocAsHtml import common.prettySerialize import converter.FodtConverter import fodt.parseStringAsXML import model.Document import org.junit.jupiter.api.Test import verify class TestNodes { @Test fun table() { FodtConverter { html = "<table><tr><td>A1</td><td>A2</td></tr></table>" parse() ast?.toYamlString()!!.verify() } } @Test fun image() { FodtConverter { html = "<img src='my-images/image.png' width='10pt'></img>" parse() ast?.toYamlString()!!.verify() } } @Test fun IncludeTags() { FodtConverter { html = "<p class='tag--content-1 tag--c2'><span class='tag--c3'>some text</span></p>" parse() ast?.toYamlString()!!.verify() } } @Test fun IncludeTagsAsciidoc() { FodtConverter { html = """ [.tag--content-1] Some paragraph """.trimIndent().asciidocAsHtml() xpath = "/html/body" unknownTagProcessingRule = AsciidoctorAdapter.unknownTagProcessingRule println(html) parse() ast?.toYamlString()!! .replace(""".*Last update.*""".toRegex(), "") .verify() } } @Test fun IncludeTagsPre() { FodtConverter { ast = Document().apply { p { +"some text 1" } p { includeTags = mutableSetOf("content-1") +"some text 2" span { includeTags = mutableSetOf("content-2, content-3") } } } generatePre() preList.joinToString("\n") { arrayOf( it.includeTags.joinToString(","), it.pre.parseStringAsXML().prettySerialize() ).joinToString("\n") }.verify() } } }
1
null
1
6
0ba6f2df325707b561f0db1cc76dcba44398b2dd
2,095
unidoc-publisher
Apache License 2.0
library/src/main/java/com/svga/glide/GlideSVGAParser.kt
zzechao
712,350,242
false
{"Kotlin": 342487, "Java": 162652}
package com.svga.glide import com.bumptech.glide.load.model.GlideUrl import com.opensource.svgaplayer.SVGAVideoEntity import com.opensource.svgaplayer.proto.MovieEntity import com.opensource.svgaplayer.utils.SVGARect import com.opensource.svgaplayer.utils.log.LogUtils import com.svga.glide.SVGAGlideEx.arrayPool import okio.Buffer import okio.buffer import okio.inflate import okio.sink import okio.source import org.json.JSONObject import java.io.ByteArrayInputStream import java.io.File import java.io.FileInputStream import java.io.IOException import java.io.InputStream import java.security.MessageDigest import java.util.zip.Inflater import java.util.zip.ZipInputStream /** * Time:2022/11/30 00:25 * Author: * Description: */ const val movieBinary = "movie.binary" const val movieSpec = "movie.spec" class GlideSVGAParser { private val TAG = "GlideSVGAParser" fun decodeFromInputStream( inputStream: InputStream, cacheDir: String, mFrameWidth: Int, mFrameHeight: Int, tag: String ): SVGAVideoEntity? { LogUtils.debug(TAG, "decodeFromInputStream mFrameWidth:$mFrameWidth mFrameHeight:$mFrameHeight $tag") val file = File(cacheDir + File.separatorChar + cacheKey(GlideUrl(tag))) file.takeIf { !it.exists() }?.mkdirs() val path = file.absolutePath var svgaVideoEntity: SVGAVideoEntity? = null try { readAsBytes(inputStream)?.let { bytes -> if (isZipFile(bytes)) { LogUtils.debug(TAG, "decodeFromInputStream isZipFile true $tag") ByteArrayInputStream(bytes).use { unzip(it, path) } val binaryFile = File(path, movieBinary) val jsonFile = File(path, movieSpec) svgaVideoEntity = if (binaryFile.isFile) { parseBinaryFile( path, binaryFile, mFrameWidth, mFrameHeight ) } else if (jsonFile.isFile) { parseSpecFile( path, jsonFile, mFrameWidth, mFrameHeight ) } else { null } LogUtils.debug(TAG, "decodeFromInputStream end") } else { LogUtils.debug(TAG, "decodeFromInputStream isZipFile false $tag") inflate(bytes)?.let { val videoEntity = MovieEntity.ADAPTER.decode(it) val width = minOf(mFrameWidth, videoEntity.params.viewBoxWidth.toInt()) val height = minOf(mFrameHeight, videoEntity.params.viewBoxHeight.toInt()) svgaVideoEntity = SVGAVideoEntity( videoEntity, File(path), width, height, true ) } LogUtils.debug(TAG, "decodeFromInputStream end") } } } catch (e: Throwable) { LogUtils.error(TAG, "decodeFromInputStream error", e) } return svgaVideoEntity } private fun parseBinaryFile( source: String, binaryFile: File, frameWidth: Int, frameHeight: Int ): SVGAVideoEntity? { LogUtils.info(TAG, "parseSpecFile frameWidth:$frameWidth frameHeight:$frameHeight") try { FileInputStream(binaryFile).use { val videoEntity = MovieEntity.ADAPTER.decode(it) val width = minOf(frameWidth, videoEntity.params.viewBoxWidth.toInt()) val height = minOf(frameHeight, videoEntity.params.viewBoxHeight.toInt()) return SVGAVideoEntity( videoEntity, File(source), width, height, true ) } } catch (e: Exception) { binaryFile.delete() return null } finally { } } private fun parseSpecFile( source: String, jsonFile: File, frameWidth: Int, frameHeight: Int ): SVGAVideoEntity? { LogUtils.info(TAG, "parseSpecFile frameWidth:$frameWidth frameHeight:$frameHeight") val buffer = arrayPool.get(1024, ByteArray::class.java) try { jsonFile.source().buffer().use { fileInputStream -> Buffer().use { byteArrayOutputStream -> while (true) { val size = fileInputStream.read(buffer) if (size == -1) { break } byteArrayOutputStream.write(buffer, 0, size) } val jsonObj = JSONObject(byteArrayOutputStream.readString(Charsets.UTF_8)) var width = frameWidth var height = frameHeight jsonObj.setupByJson()?.let { width = minOf(it.width.toInt(), frameWidth) height = minOf(it.height.toInt(), frameHeight) } return SVGAVideoEntity(jsonObj, File(source), width, height, true) } } } catch (e: Exception) { jsonFile.delete() return null } finally { arrayPool.put(buffer) } } private fun unzip(inputStream: ByteArrayInputStream, cacheDir: String) { ZipInputStream(inputStream).use { zipInputStream -> while (true) { val zipItem = zipInputStream.nextEntry ?: break if (zipItem.name.contains("../")) { // 解压路径存在路径穿越问题,直接过滤 continue } if (zipItem.name.contains("/")) { continue } val fileZip = File(cacheDir, zipItem.name) ensureUnzipSafety(fileZip, cacheDir) val reader = zipInputStream.source().buffer() val buffer = arrayPool.get(1024, ByteArray::class.java) try { if (!fileZip.exists() || fileZip.length() == 0L) { LogUtils.debug(TAG, "fileZip:$fileZip") fileZip.sink().buffer().use { fileOutputStream -> while (true) { val readBytes = reader.read(buffer) if (readBytes <= 0) break fileOutputStream.write(buffer, 0, readBytes) } arrayPool.put(buffer) } } else { LogUtils.debug(TAG, "fileZip:$fileZip exists") } } catch (_: Throwable) { } finally { arrayPool.put(buffer) } } zipInputStream.closeEntry() } } private fun inflate(byteArray: ByteArray): ByteArray? { val inflater = Inflater() inflater.setInput(byteArray, 0, byteArray.size) Buffer().use { inflatedOutputStream -> Buffer().inflate(inflater).buffer().use { val buffer = arrayPool.get(1024, ByteArray::class.java) try { while (true) { val count = it.read(buffer) if (count <= 0) break inflatedOutputStream.write(buffer, 0, count) } } catch (_: Throwable) { } finally { inflater.end() arrayPool.put(buffer) } } return inflatedOutputStream.readByteArray() } } private fun readAsBytes(inputStream: InputStream): ByteArray? { Buffer().use { byteArrayOutputStream -> val buffer = arrayPool.get(1024, ByteArray::class.java) try { inputStream.source().buffer().use { while (true) { val cnt = it.read(buffer) if (cnt <= 0) break byteArrayOutputStream.write(buffer, 0, cnt) } } } catch (_: Throwable) { } finally { arrayPool.put(buffer) } return byteArrayOutputStream.readByteArray() } } // 是否是 zip 文件 private fun isZipFile(bytes: ByteArray): Boolean { return bytes.size > 4 && bytes[0].toInt() == 80 && bytes[1].toInt() == 75 && bytes[2].toInt() == 3 && bytes[3].toInt() == 4 } // 检查 zip 路径穿透 private fun ensureUnzipSafety(outputFile: File, dstDirPath: String) { val dstDirCanonicalPath = File(dstDirPath).canonicalPath val outputFileCanonicalPath = outputFile.canonicalPath if (!outputFileCanonicalPath.startsWith(dstDirCanonicalPath)) { throw IOException("Found Zip Path Traversal Vulnerability with $dstDirCanonicalPath") } } private fun cacheKey(glideUrl: GlideUrl): String { val messageDigest = MessageDigest.getInstance("MD5") messageDigest.update(glideUrl.toStringUrl().toByteArray(charset("UTF-8"))) val digest = messageDigest.digest() var sb = "" for (b in digest) { sb += String.format("%02x", b) } return sb } // 获取 private fun JSONObject.setupByJson(): SVGARect? { return optJSONObject("viewBox")?.let { viewBoxObject -> val width = viewBoxObject.optDouble("width", 0.0) val height = viewBoxObject.optDouble("height", 0.0) SVGARect(0.0, 0.0, width, height) } } }
1
Kotlin
0
4
6688dcf6abd8429bde325473c6fb8cc7c0873d36
10,102
svgaplayer-android-glide_feature
Apache License 2.0
sdk/src/androidTest/java/co/omise/android/ui/InstallmentChooserFragmentTest.kt
omise
25,964,531
false
{"Kotlin": 566629, "Java": 34215}
package co.omise.android.ui import androidx.test.core.app.ActivityScenario import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.hasDescendant import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import co.omise.android.R import co.omise.android.models.PaymentMethod import co.omise.android.utils.itemCount import co.omise.android.utils.withListId import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class InstallmentChooserFragmentTest { private val paymentMethods = listOf( PaymentMethod(name = "installment_bay"), PaymentMethod(name = "installment_bbl"), PaymentMethod(name = "installment_ezypay"), PaymentMethod(name = "installment_first_choice"), PaymentMethod(name = "installment_kbank"), PaymentMethod(name = "installment_ktc"), PaymentMethod(name = "installment_scb") ) private val mockNavigation: PaymentCreatorNavigation = mock() private val fragment = InstallmentChooserFragment.newInstance(paymentMethods).apply { navigation = mockNavigation } @Before fun setUp() { ActivityScenario.launch(TestFragmentActivity::class.java).onActivity { it.replaceFragment(fragment) } onView(withText(R.string.installments_title)).check(matches(isDisplayed())) } @Test fun displayAllowedInstallmentBanks_showAllowedInstallmentBanksFromArgument() { onView(withListId(R.id.recycler_view).atPosition(0)).check(matches(hasDescendant(withText(R.string.payment_method_installment_bay_title)))) onView(withListId(R.id.recycler_view).atPosition(1)).check(matches(hasDescendant(withText(R.string.payment_method_installment_bbl_title)))) onView(withListId(R.id.recycler_view).atPosition(2)).check(matches(hasDescendant(withText(R.string.payment_method_installment_ezypay_title)))) onView(withListId(R.id.recycler_view).atPosition(3)).check(matches(hasDescendant(withText(R.string.payment_method_installment_first_choice_title)))) onView(withListId(R.id.recycler_view).atPosition(4)).check(matches(hasDescendant(withText(R.string.payment_method_installment_kasikorn_title)))) onView(withListId(R.id.recycler_view).atPosition(5)).check(matches(hasDescendant(withText(R.string.payment_method_installment_ktc_title)))) onView(withListId(R.id.recycler_view).atPosition(6)).check(matches(hasDescendant(withText(R.string.payment_method_installment_scb_title)))) onView(withId(R.id.recycler_view)).check(matches(itemCount(paymentMethods.size))) } @Test fun clickBankInstallmentMethod_shouldNavigateToInstallmentTermChooserFragment() { onView(withListId(R.id.recycler_view).atPosition(0)).perform(click()) verify(mockNavigation).navigateToInstallmentTermChooser(PaymentMethod(name = "installment_bay")) } }
5
Kotlin
32
51
08363dff04cbd2ba76184ea4789f8378614d2a12
3,314
omise-android
MIT License
app/src/main/java/com/stratagile/qlink/ui/activity/topup/module/TopupSelectDeductionTokenModule.kt
qlcchain
115,608,966
false
null
package com.stratagile.qlink.ui.activity.topup.module import com.stratagile.qlink.data.api.HttpAPIWrapper import com.stratagile.qlink.ui.activity.base.ActivityScope import com.stratagile.qlink.ui.activity.topup.TopupSelectDeductionTokenActivity import com.stratagile.qlink.ui.activity.topup.contract.TopupSelectDeductionTokenContract import com.stratagile.qlink.ui.activity.topup.presenter.TopupSelectDeductionTokenPresenter import dagger.Module; import dagger.Provides; /** * @author hzp * @Package com.stratagile.qlink.ui.activity.topup * @Description: The moduele of TopupSelectDeductionTokenActivity, provide field for TopupSelectDeductionTokenActivity * @date 2020/02/13 20:41:09 */ @Module class TopupSelectDeductionTokenModule (private val mView: TopupSelectDeductionTokenContract.View) { @Provides @ActivityScope fun provideTopupSelectDeductionTokenPresenter(httpAPIWrapper: HttpAPIWrapper) :TopupSelectDeductionTokenPresenter { return TopupSelectDeductionTokenPresenter(httpAPIWrapper, mView) } @Provides @ActivityScope fun provideTopupSelectDeductionTokenActivity() : TopupSelectDeductionTokenActivity { return mView as TopupSelectDeductionTokenActivity } }
1
Java
18
46
1c8066e4ebbb53c7401751ea3887a6315ccbe5eb
1,225
QWallet-Android
MIT License
analyzer/src/funTest/kotlin/managers/SbtFunTest.kt
codeakki
354,880,826
true
{"Kotlin": 2934213, "JavaScript": 337630, "HTML": 34185, "CSS": 24865, "Python": 21694, "FreeMarker": 13132, "Shell": 7793, "Dockerfile": 7023, "Scala": 6656, "Ruby": 3515, "ANTLR": 1877, "Go": 1071, "Rust": 280}
/* * Copyright (C) 2017-2019 HERE Europe B.V. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.ossreviewtoolkit.analyzer.managers import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import java.io.File import org.ossreviewtoolkit.analyzer.Analyzer import org.ossreviewtoolkit.downloader.VersionControlSystem import org.ossreviewtoolkit.downloader.vcs.Git import org.ossreviewtoolkit.utils.Ci import org.ossreviewtoolkit.utils.normalizeVcsUrl import org.ossreviewtoolkit.utils.test.DEFAULT_ANALYZER_CONFIGURATION import org.ossreviewtoolkit.utils.test.patchActualResult import org.ossreviewtoolkit.utils.test.patchExpectedResult class SbtFunTest : StringSpec({ "Dependencies of the external 'directories' single project should be detected correctly".config( enabled = !Ci.isAzureWindows // Disabled as a prompt in Sbt 1.5.0 blocks execution when getting the version. ) { val projectName = "directories" val projectDir = File("src/funTest/assets/projects/external/$projectName").absoluteFile val expectedOutputFile = projectDir.resolveSibling("$projectName-expected-output.yml") // Clean any previously generated POM files / target directories. Git().run(projectDir, "clean", "-fd") val ortResult = Analyzer(DEFAULT_ANALYZER_CONFIGURATION).analyze(projectDir, listOf(Sbt.Factory())) val actualResult = ortResult.toYaml() val expectedResult = patchExpectedResult(expectedOutputFile) patchActualResult(actualResult, patchStartAndEndTime = true) shouldBe expectedResult } "Dependencies of the external 'sbt-multi-project-example' multi-project should be detected correctly".config( enabled = !Ci.isAzureWindows // Disabled as a prompt in Sbt 1.5.0 blocks execution when getting the version. ) { val projectName = "sbt-multi-project-example" val projectDir = File("src/funTest/assets/projects/external/$projectName").absoluteFile val expectedOutputFile = projectDir.parentFile.resolve("$projectName-expected-output.yml") // Clean any previously generated POM files / target directories. Git().run(projectDir, "clean", "-fd") val ortResult = Analyzer(DEFAULT_ANALYZER_CONFIGURATION).analyze(projectDir, listOf(Sbt.Factory())) val actualResult = ortResult.toYaml() val expectedResult = patchExpectedResult(expectedOutputFile) patchActualResult(actualResult, patchStartAndEndTime = true) shouldBe expectedResult } "Dependencies of the synthetic 'http4s-template' project should be detected correctly".config( enabled = !Ci.isAzureWindows // Disabled as a prompt in Sbt 1.5.0 blocks execution when getting the version. ) { val projectName = "sbt-http4s-template" val projectDir = File("src/funTest/assets/projects/synthetic/$projectName").absoluteFile val expectedOutputFile = projectDir.parentFile.resolve("$projectName-expected-output.yml") val vcsDir = VersionControlSystem.forDirectory(projectDir)!! val vcsUrl = vcsDir.getRemoteUrl() val vcsRevision = vcsDir.getRevision() // Clean any previously generated POM files / target directories. Git().run(projectDir, "clean", "-fd") val ortResult = Analyzer(DEFAULT_ANALYZER_CONFIGURATION).analyze(projectDir, listOf(Sbt.Factory())) val actualResult = ortResult.toYaml() val expectedResult = patchExpectedResult( expectedOutputFile, url = vcsUrl, revision = vcsRevision, urlProcessed = normalizeVcsUrl(vcsUrl) ) patchActualResult(actualResult, patchStartAndEndTime = true) shouldBe expectedResult } })
0
null
0
2
edbb46cb1dab1529d5ffb81cba18d365b98ef23e
4,340
ort
Apache License 2.0
theme-m3/style/theme/src/commonMain/kotlin/org/gdglille/devfest/android/theme/m3/style/tags/GravelTagTokens.kt
GerardPaligot
444,230,272
false
{"Kotlin": 834594, "Swift": 125581, "Shell": 1148, "Dockerfile": 542}
package org.gdglille.devfest.android.theme.m3.style.tags import org.gdglille.devfest.android.theme.m3.style.DecorativeColorSchemeTokens internal object GravelTagTokens { val ContainerColor = DecorativeColorSchemeTokens.Gravel val ContentColor = DecorativeColorSchemeTokens.OnGravel }
8
Kotlin
5
141
d6e23529843f956d0c4c1ca7cca6a275422d3c22
294
conferences4hall
Apache License 2.0
idea/testData/refactoring/move/kotlin/moveNestedClass/objectToTopLevel/before/usages2.kt
JakeWharton
99,388,807
true
null
package test2 import test.A.B fun foo(): B { return B() }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
63
kotlin
Apache License 2.0
compiler/testData/diagnostics/tests/coroutines/suspendFunctionAsSupertype/simple/mixingSuspendAndNonSuspendSupertypesThruSuperinterface.kt
JetBrains
3,432,266
false
null
// FIR_IDENTICAL // !LANGUAGE: +SuspendFunctionAsSupertype // SKIP_TXT // DIAGNOSTICS: -CONFLICTING_INHERITED_MEMBERS, -CONFLICTING_OVERLOADS, -ABSTRACT_MEMBER_NOT_IMPLEMENTED, -FUN_INTERFACE_WRONG_COUNT_OF_ABSTRACT_MEMBERS interface ISuper: () -> Unit class C: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>suspend () -> Unit, ISuper<!> { override suspend fun invoke() { } } fun interface FI: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>suspend () -> Unit, ISuper<!> { } interface I: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>suspend () -> Unit, ISuper<!> { } object O: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>suspend () -> Unit, ISuper<!> { override suspend fun invoke() { } } interface SISuper: suspend () -> Unit class C1: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>SISuper, () -> Unit<!> { override suspend fun invoke() { } } fun interface FI1: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>SISuper, () -> Unit<!> { } interface I1: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>SISuper, () -> Unit<!> { } object O1: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>SISuper, () -> Unit<!> { override suspend fun invoke() { } } class C2: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>SISuper, ISuper<!> { override suspend fun invoke() { } } fun interface FI2: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>SISuper, ISuper<!> { } interface I2: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>SISuper, ISuper<!> { } object O2: <!MIXING_SUSPEND_AND_NON_SUSPEND_SUPERTYPES!>SISuper, ISuper<!> { override suspend fun invoke() { } }
7
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,591
kotlin
Apache License 2.0
spotify-clone-frontend/app/src/main/java/com/spotifyclone/tools/utils/MathUtils.kt
Ridersk
257,694,555
false
{"Kotlin": 144598, "Java": 12300}
package com.spotifyclone.tools.utils import kotlin.math.abs class MathUtils { companion object { fun calculateProportion(piece: Number, total: Number, weight: Float): Float { return ((piece.toFloat() / total.toFloat()) * weight) + 1.0F - weight } fun calculateReverseProportion(piece: Number, total: Number, weight: Float): Float { return ((abs(piece.toFloat() - total.toFloat()) / total.toFloat() * weight) + 1.0F - weight) } } }
4
Kotlin
0
1
68617849bca5416100c85578ad42e12775c04865
539
spotify-music-player-kotlin
MIT License
spotify-clone-frontend/app/src/main/java/com/spotifyclone/tools/utils/MathUtils.kt
Ridersk
257,694,555
false
{"Kotlin": 144598, "Java": 12300}
package com.spotifyclone.tools.utils import kotlin.math.abs class MathUtils { companion object { fun calculateProportion(piece: Number, total: Number, weight: Float): Float { return ((piece.toFloat() / total.toFloat()) * weight) + 1.0F - weight } fun calculateReverseProportion(piece: Number, total: Number, weight: Float): Float { return ((abs(piece.toFloat() - total.toFloat()) / total.toFloat() * weight) + 1.0F - weight) } } }
4
Kotlin
0
1
68617849bca5416100c85578ad42e12775c04865
539
spotify-music-player-kotlin
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/RemoveBackground.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: RemoveBackground * * Full name: System`RemoveBackground * * RemoveBackground[image] returns an image with an alpha channel where the background is transparent. * Usage: RemoveBackground[image, model] uses foreground or background model specification. * * Options: None * * Protected * Attributes: ReadProtected * * local: paclet:ref/RemoveBackground * Documentation: web: http://reference.wolfram.com/language/ref/RemoveBackground.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun removeBackground(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("RemoveBackground", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,156
mathemagika
Apache License 2.0