content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package io.mockk.it import io.mockk.every import io.mockk.mockk import kotlin.test.Test import kotlin.test.assertEquals class ParametersWhitDefaultTest { private val target = mockk<DefaultParam>() /** * See issue #312. * * Mocking a function with default parameter should match without specifying its * parameters. */ @Test fun testAgainstDefaultParam() { every { target.foo() } returns STUB_STRING assertEquals(target.foo(), STUB_STRING) } private companion object { const val STUB_STRING = "A string" } interface DefaultParam { fun foo(param: String = "default"): String } }
modules/mockk/src/commonTest/kotlin/io/mockk/it/ParametersWhitDefaultTest.kt
3273029109
/* * Copyright (c) 2016-present. Drakeet Xu * * 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.drakeet.multitype.sample.weibo import com.google.gson.* import com.drakeet.multitype.sample.weibo.content.SimpleImage import com.drakeet.multitype.sample.weibo.content.SimpleText import java.lang.reflect.Type /** * @author Drakeet Xu */ class WeiboContentDeserializer : JsonDeserializer<WeiboContent> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): WeiboContent? { val gson = WeiboJsonParser.GSON val jsonObject = json as JsonObject val contentType = stringOrEmpty(jsonObject.get("content_type")) var content: WeiboContent? = null if (SimpleText.TYPE == contentType) { content = gson.fromJson(json, SimpleText::class.java) } else if (SimpleImage.TYPE == contentType) { content = gson.fromJson(json, SimpleImage::class.java) } return content } private fun stringOrEmpty(jsonElement: JsonElement): String { return if (jsonElement.isJsonNull) "" else jsonElement.asString } }
sample/src/main/kotlin/com/drakeet/multitype/sample/weibo/WeiboContentDeserializer.kt
2650452418
package de.xikolo.utils import android.os.Build object DeviceUtil { @JvmStatic val deviceName: String get() { val manufacturer = Build.MANUFACTURER val model = Build.MODEL return if (model.startsWith(manufacturer)) { model.capitalize() } else { manufacturer.capitalize() + " " + model } } }
app/src/main/java/de/xikolo/utils/DeviceUtil.kt
2128895578
/* * Copyright (C) 2017 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 android.dktv.com.luffysubber import java.io.Serializable /** * Movie class represents video entity with title, description, image thumbs and video url. */ data class Movie( var id: Long = 0, var title: String? = null, var description: String? = null, var backgroundImageUrl: String? = null, var cardImageUrl: String? = null, var videoUrl: String? = null, var studio: String? = null ) : Serializable { override fun toString(): String { return "Movie{" + "id=" + id + ", title='" + title + '\'' + ", videoUrl='" + videoUrl + '\'' + ", backgroundImageUrl='" + backgroundImageUrl + '\'' + ", cardImageUrl='" + cardImageUrl + '\'' + '}' } companion object { internal const val serialVersionUID = 727566175075960653L } }
code/LuffySubber/app/新建文件夹/Movie.kt
3374470172
package com.soywiz.korge.ext.spriter.com.brashmonkey.spriter @Suppress("unused", "MemberVisibilityCanBePrivate") /** * Represents all the data which necessary to animate a Spriter generated SCML file. * An instance of this class holds [Folder]s and [Entity] instances. * Specific [Folder] and [Entity] instances can be accessed via the corresponding methods, i.e. getEntity() * and getFolder(). * @author Trixt0r */ class Data( val scmlVersion: String, val generator: String, val generatorVersion: String, val pixelMode: PixelMode, folders: Int, entities: Int, val atlases: List<String> ) { /** * Represents the rendering mode stored in the spriter data root. */ enum class PixelMode { NONE, PIXEL_ART; companion object { /** * @param mode * * * @return The pixel mode for the given int value. Default is [NONE]. */ operator fun get(mode: Int): PixelMode { when (mode) { 1 -> return PIXEL_ART else -> return NONE } } } } val folders: Array<Folder> = Array(folders) { Folder.DUMMY } val entities: Array<Entity> = Array(entities) { Entity.DUMMY } private var folderPointer = 0 private var entityPointer = 0 fun addFolder(folder: Folder) { this.folders[folderPointer++] = folder } fun addEntity(entity: Entity) { this.entities[entityPointer++] = entity } fun getFolder(name: String): Folder? { val index = getFolderIndex(name) return if (index >= 0) getFolder(index) else null } fun getFolderIndex(name: String): Int = this.folders.firstOrNull { it.name == name }?.id ?: -1 fun getFolder(index: Int): Folder = this.folders[index] fun getEntity(index: Int): Entity = this.entities[index] fun getEntity(name: String): Entity? { val index = getEntityIndex(name) return if (index >= 0) getEntity(index) else null } fun getEntityIndex(name: String): Int = this.entities.firstOrNull { it.name == name }?.id ?: -1 fun getFile(folder: Folder, file: Int): File = folder.getFile(file) fun getFile(folder: Int, file: Int): File = getFile(this.getFolder(folder), file) fun getFile(ref: FileReference): File = this.getFile(ref.folder, ref.file) /** * @return The string representation of this spriter data */ override fun toString(): String { var toReturn = "" + this::class + "|[Version: " + scmlVersion + ", Generator: " + generator + " (" + generatorVersion + ")]" for (folder in folders) toReturn += "\n" + folder for (entity in entities) toReturn += "\n" + entity toReturn += "]" return toReturn } }
@old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/com/brashmonkey/spriter/Data.kt
1471154216
/* * Copyright (c) 2011 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.moe.client.config import com.google.devtools.moe.client.InvalidProject import com.google.devtools.moe.client.config.EditorType.renamer import com.google.devtools.moe.client.config.EditorType.scrubber import com.google.devtools.moe.client.config.EditorType.shell import com.squareup.moshi.Json /** * Configuration for a MOE Editor. */ data class EditorConfig( val type: EditorType, @Json(name = "scrubber_config") val scrubberConfig: ScrubberConfig? = null, @Json(name = "command_string") val commandString: String? = null, val mappings: Map<String, String> = mapOf(), @Json(name = "use_regex") val useRegex: Boolean = false ) : ValidatingConfig { val regexMappings: Map<Regex, String> by lazy { mappings.map { (p, r) -> p.toRegex() to r }.toMap() } @Throws(InvalidProject::class) override fun validate() { InvalidProject.assertNotNull(type, "Missing type in editor") when (type) { scrubber -> InvalidProject.assertNotNull( scrubberConfig, "Failed to specify a \"scrubber_config\" in scrubbing editor." ) shell -> InvalidProject.assertNotNull( commandString, "Failed to specify a \"command_string\" in shell editor." ) renamer -> InvalidProject.assertNotNull( mappings, "Failed to specify \"mappings\" in renamer editor." ) } } }
client/src/main/java/com/google/devtools/moe/client/config/EditorConfig.kt
3782305925
package com.github.ivan_osipov.clabo.api.model import com.google.gson.annotations.SerializedName class Audio : AbstractFileDescriptor() { @SerializedName("duration") private var _duration: Int? = null val duration: Int get() = _duration!! @SerializedName("performer") var performer: String? = null @SerializedName("title") var title: String? = null @SerializedName("mime_type") var mimeType: String? = null }
src/main/kotlin/com/github/ivan_osipov/clabo/api/model/Audio.kt
2322893053
package com.telenav.osv.data.collector.datatype.datatypes import androidx.annotation.NonNull import com.telenav.osv.data.collector.datatype.util.LibraryUtil import com.telenav.osv.data.collector.datatype.util.LibraryUtil.AvailableData /** * This class represents the super class of all data types inside the DataCollector library * @param <T> </T> */ open class BaseObject<T> { var timestamp = System.currentTimeMillis() protected var actualValue: T? = null open var statusCode = -1 var dataSource = "" protected set private var sensorType = "" constructor() {} constructor(value: T, statusCode: Int) { actualValue = value this.statusCode = statusCode } protected constructor(value: T, statusCode: Int, @NonNull @AvailableData sensorType: String) : this(value, statusCode) { this.sensorType = sensorType } open fun getSensorType(): String? { return sensorType } val errorCodeDescription: String get() { var status = " " status += when (statusCode) { LibraryUtil.OBD_NOT_AVAILABLE, LibraryUtil.PHONE_SENSOR_NOT_AVAILABLE -> LibraryUtil.SENSOR_NOT_AVAILABLE_DESCRIPTION LibraryUtil.OBD_READ_SUCCESS, LibraryUtil.PHONE_SENSOR_READ_SUCCESS -> LibraryUtil.SENSOR_READ_SUCCESS_DESCRIPTION LibraryUtil.OBD_INITIALIZATION_FAILURE -> LibraryUtil.SENSOR_INITIALIZATION_FAILURE_DESCRIPTION LibraryUtil.OBD_AVAILABLE -> LibraryUtil.SENSOR_AVAILABLE_DESCRIPTION LibraryUtil.OBD_READ_FAILURE -> LibraryUtil.SENSOR_READ_FAILURE_DESCRIPTION else -> LibraryUtil.SENSOR_READ_FAILURE_DESCRIPTION } return status } }
app/src/main/java/com/telenav/osv/data/collector/datatype/datatypes/BaseObject.kt
3949407867
package by.dev.madhead.doktor.model.confluence import com.google.gson.Gson data class CreatePageRequest( val type: String = "page", val title: String, val ancestors: List<ContentReference>? = null, val space: SpaceReference, val body: Body ) { fun asJSON() = Gson().toJson(this) }
src/main/kotlin/by/dev/madhead/doktor/model/confluence/CreatePageRequest.kt
1523179635
/* * Copyright 2017 Vladimir Jovanovic * * 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.vlad1m1r.kotlintest.presentation.base import android.os.Bundle import android.support.v4.app.Fragment abstract class BaseFragment<P : IBasePresenter> : Fragment() { open var presenter: P? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.retainInstance = retainInstance() } protected fun retainInstance(): Boolean { return true } }
app/src/main/java/com/vlad1m1r/kotlintest/presentation/base/BaseFragment.kt
2567519349
package com.ddiehl.rgsc import android.content.Context object ContextProvider { private lateinit var _context: Context public fun set(context: Context) { _context = context } public fun get(): Context = _context }
app/src/main/java/com/ddiehl/rgsc/ContextProvider.kt
2490308195
package dolvic.gw2.api.achievements enum class AchievementType { Default, ItemSet }
types/src/main/kotlin/dolvic/gw2/api/achievements/AchievementType.kt
2047952189
/* * Copyright (C) 2018 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. */ @file:JvmName("KotlinExtensions") package retrofit2 import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.yield import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException inline fun <reified T> Retrofit.create(): T = create(T::class.java) suspend fun <T : Any> Call<T>.await(): T { return suspendCancellableCoroutine { continuation -> continuation.invokeOnCancellation { cancel() } enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { if (response.isSuccessful) { val body = response.body() if (body == null) { val invocation = call.request().tag(Invocation::class.java)!! val method = invocation.method() val e = KotlinNullPointerException("Response from " + method.declaringClass.name + '.' + method.name + " was null but response body type was declared as non-null") continuation.resumeWithException(e) } else { continuation.resume(body) } } else { continuation.resumeWithException(HttpException(response)) } } override fun onFailure(call: Call<T>, t: Throwable) { continuation.resumeWithException(t) } }) } } @JvmName("awaitNullable") suspend fun <T : Any> Call<T?>.await(): T? { return suspendCancellableCoroutine { continuation -> continuation.invokeOnCancellation { cancel() } enqueue(object : Callback<T?> { override fun onResponse(call: Call<T?>, response: Response<T?>) { if (response.isSuccessful) { continuation.resume(response.body()) } else { continuation.resumeWithException(HttpException(response)) } } override fun onFailure(call: Call<T?>, t: Throwable) { continuation.resumeWithException(t) } }) } } suspend fun <T : Any> Call<T>.awaitResponse(): Response<T> { return suspendCancellableCoroutine { continuation -> continuation.invokeOnCancellation { cancel() } enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { continuation.resume(response) } override fun onFailure(call: Call<T>, t: Throwable) { continuation.resumeWithException(t) } }) } } internal suspend fun Exception.yieldAndThrow(): Nothing { yield() throw this }
retrofit/src/main/java/retrofit2/KotlinExtensions.kt
761756717
package com.lch.menote.note.data.db import android.content.Context import android.content.ContextWrapper import android.database.DatabaseErrorHandler import android.database.sqlite.SQLiteDatabase import android.util.Log import com.apkfuns.logutils.LogUtils import com.lch.menote.note.data.db.gen.DaoMaster import com.lch.menote.ConstantUtil import com.lchli.utils.tool.ExtFileUtils import org.apache.commons.io.FileUtils import org.greenrobot.greendao.database.Database import java.io.File class AppDbOpenHelper : DaoMaster.DevOpenHelper { constructor(context: Context, name: String, factory: SQLiteDatabase.CursorFactory, isSdcardDatabase: Boolean = false) : super(chooseContext(context, isSdcardDatabase), name, factory) constructor(context: Context, name: String, isSdcardDatabase: Boolean = false) : super(chooseContext(context, isSdcardDatabase), name) /** * in production environment,you can Override this to impl your needs. * * * note:when upgrade you must modify DaoMaster#SCHEMA_VERSION. * * @param db * @param oldVersion * @param newVersion */ override fun onUpgrade(db: Database?, oldVersion: Int, newVersion: Int) { Log.e("greenDAO", "Upgrading schema from version $oldVersion to $newVersion by dropping all tables") if (oldVersion == 1) { db!!.execSQL("ALTER TABLE note ADD CATEGORY integer") } else { DaoMaster.dropAllTables(db, true) onCreate(db) } } companion object { private fun chooseContext(context: Context, isSdcardDatabase: Boolean): Context { return if (!isSdcardDatabase) { context } else object : ContextWrapper(context) { override fun getDatabasePath(name: String): File { try { FileUtils.forceMkdir(File(ConstantUtil.DB_DIR)) } catch (e: Exception) { e.printStackTrace() } val noteDb = File(ConstantUtil.DB_DIR, name) LogUtils.e("DB_DIR exists:" + File(ConstantUtil.DB_DIR).exists()) ExtFileUtils.makeFile(noteDb.absolutePath) LogUtils.e("db:" + noteDb.absolutePath) return noteDb } override fun openOrCreateDatabase(name: String, mode: Int, factory: SQLiteDatabase.CursorFactory?): SQLiteDatabase { return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory) } override fun openOrCreateDatabase(name: String, mode: Int, factory: SQLiteDatabase.CursorFactory?, errorHandler: DatabaseErrorHandler?): SQLiteDatabase { return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name).path, factory, errorHandler) } } } } }
host/src/main/java/com/lch/menote/note/data/db/AppDbOpenHelper.kt
3442854330
package com.sapuseven.untis.models.untis.params import com.sapuseven.untis.models.untis.UntisAuth import kotlinx.serialization.Serializable @Serializable data class SubmitLessonTopicParams( val lessonTopic: String, val ttId: Int, val auth: UntisAuth ) : BaseParams()
app/src/main/java/com/sapuseven/untis/models/untis/params/SubmitLessonTopicParams.kt
2321688177
package com.bl_lia.kirakiratter.domain.interactor.config import com.bl_lia.kirakiratter.domain.executor.PostExecutionThread import com.bl_lia.kirakiratter.domain.executor.ThreadExecutor import com.bl_lia.kirakiratter.domain.interactor.SingleUseCase import com.bl_lia.kirakiratter.domain.repository.ConfigRepository import io.reactivex.Single class SetSimpleModeUseCase( private val configRepository: ConfigRepository, private val threadExecutor: ThreadExecutor, private val postExecutionThread: PostExecutionThread ) : SingleUseCase<Boolean>(threadExecutor, postExecutionThread) { override fun build(params: Array<out Any>): Single<Boolean> = configRepository.setSimpleMode(params[0] as Boolean) }
app/src/main/kotlin/com/bl_lia/kirakiratter/domain/interactor/config/SetSimpleModeUseCase.kt
977195218
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.matchers import android.graphics.Bitmap import android.graphics.Typeface import androidx.compose.ui.text.font.TypefaceResult import androidx.compose.ui.geometry.Rect import com.google.common.truth.IntegerSubject import com.google.common.truth.Truth.assertAbout internal fun assertThat(bitmap: Bitmap?): BitmapSubject { return assertAbout(BitmapSubject.SUBJECT_FACTORY).that(bitmap)!! } internal fun assertThat(typeface: Typeface?): TypefaceSubject { return assertAbout(TypefaceSubject.SUBJECT_FACTORY).that(typeface)!! } internal fun assertThat(array: Array<Rect>?): RectArraySubject { return assertAbout(RectArraySubject.SUBJECT_FACTORY).that(array)!! } internal fun assertThat(rect: Rect?): RectSubject { return assertAbout(RectSubject.SUBJECT_FACTORY).that(rect)!! } internal fun assertThat(charSequence: CharSequence?): CharSequenceSubject { return assertAbout(CharSequenceSubject.SUBJECT_FACTORY).that(charSequence)!! } internal fun assertThat(typefaceResult: TypefaceResult?): TypefaceResultSubject { return assertAbout(TypefaceResultSubject.SUBJECT_FACTORY).that(typefaceResult)!! } internal fun IntegerSubject.isZero() { this.isEqualTo(0) }
compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/matchers/ComposeMatchers.kt
2733385858
package abi43_0_0.expo.modules.imageloader import android.content.Context import abi43_0_0.expo.modules.core.BasePackage import abi43_0_0.expo.modules.core.interfaces.InternalModule class ImageLoaderPackage : BasePackage() { override fun createInternalModules(context: Context): List<InternalModule> = listOf(ImageLoaderModule(context)) }
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/imageloader/ImageLoaderPackage.kt
3301774164
/* * 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.collection import androidx.benchmark.junit4.BenchmarkRule import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Parameterized.Parameters @RunWith(Parameterized::class) class CircularArrayBenchmarkTest(size: Int) { private val seed = createSeed(size) @get:Rule val benchmark = BenchmarkRule() @Test fun addFromHeadAndPopFromTail() { benchmark.runCollectionBenchmark(CircularyArrayAddFromHeadAndPopFromTailBenchmark(seed)) } companion object { @JvmStatic @Parameters(name = "size={0}") fun parameters() = buildParameters( listOf(10, 100, 1_000, 10_000), ) } }
collection/collection-benchmark/src/androidTest/java/androidx/collection/CircularArrayBenchmarkTest.kt
222427925
package com.vimeo.networking2.enums /** * The type of video projection being used for a 360 video. */ enum class SpatialProjectionType(override val value: String?) : StringValue { /** * The spatial projection is cubical. */ CUBICAL("cubical"), /** * The spatial projection is cylindrical. */ CYLINDRICAL("cylindrical"), /** * The spatial projection is dome-shaped. */ DOME("dome"), /** * The spatial projection is equirectangular. */ EQUIRECTANGULAR("equirectangular"), /** * The spatial projection is pyramid-shaped. */ PYRAMID("pyramid"), /** * Unknown type of spatial projection. */ UNKNOWN(null) }
models/src/main/java/com/vimeo/networking2/enums/SpatialProjectionType.kt
233804103
package tech.salroid.filmy.ui.activities import android.content.Intent import android.os.Build import android.os.Bundle import android.text.Html import android.view.MenuItem import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.preference.PreferenceManager import androidx.recyclerview.widget.GridLayoutManager import com.bumptech.glide.Glide import org.json.JSONException import tech.salroid.filmy.R import tech.salroid.filmy.data.local.model.CastDetailsResponse import tech.salroid.filmy.data.local.model.CastMovie import tech.salroid.filmy.data.local.model.CastMovieDetailsResponse import tech.salroid.filmy.data.network.NetworkUtil import tech.salroid.filmy.databinding.ActivityDetailedCastBinding import tech.salroid.filmy.ui.activities.fragment.FullReadFragment import tech.salroid.filmy.ui.adapters.CharacterDetailsActivityAdapter import tech.salroid.filmy.utility.toReadableDate class CharacterDetailsActivity : AppCompatActivity() { private var characterId: String? = null private var characterTitle: String? = null private var moviesList: ArrayList<CastMovie>? = null private var characterBio: String? = null private var fullReadFragment: FullReadFragment? = null private var nightMode = false private lateinit var binding: ActivityDetailedCastBinding override fun onCreate(savedInstanceState: Bundle?) { val sp = PreferenceManager.getDefaultSharedPreferences(this) nightMode = sp.getBoolean("dark", false) if (nightMode) setTheme(R.style.AppTheme_Base_Dark) else setTheme(R.style.AppTheme_Base) super.onCreate(savedInstanceState) binding = ActivityDetailedCastBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = "" binding.more.setOnClickListener { if (!(moviesList == null && characterTitle == null)) { val intent = Intent(this@CharacterDetailsActivity, FullMovieActivity::class.java) intent.putExtra("cast_movies", moviesList) intent.putExtra("toolbar_title", characterTitle) startActivity(intent) } } binding.characterMovies.layoutManager = GridLayoutManager(this@CharacterDetailsActivity, 3) binding.characterMovies.isNestedScrollingEnabled = false binding.overviewContainer.setOnClickListener { if (characterTitle != null && characterBio != null) { fullReadFragment = FullReadFragment() val args = Bundle() args.putString("title", characterTitle) args.putString("desc", characterBio) fullReadFragment!!.arguments = args supportFragmentManager.beginTransaction() .replace(R.id.main, fullReadFragment!!).addToBackStack("DESC").commit() } } val intent = intent if (intent != null) { characterId = intent.getStringExtra("id") } characterId?.let { NetworkUtil.getCastDetails(it, { details -> details?.let { it1 -> showPersonalDetails(it1) } }, { }) NetworkUtil.getCastMovieDetails(it, { details -> details?.let { it1 -> this.moviesList = it1.castMovies showPersonMovies(it1) } }, { }) } } override fun onResume() { super.onResume() val sp = PreferenceManager.getDefaultSharedPreferences(this) val nightModeNew = sp.getBoolean("dark", false) if (nightMode != nightModeNew) recreate() } private fun showPersonalDetails(details: CastDetailsResponse) { try { val dataName = details.name val dataProfile = "http://image.tmdb.org/t/p/w185" + details.profilePath val dataOverview = details.biography val dataBirthday = details.birthday val dataBirthPlace = details.placeOfBirth characterTitle = dataName characterBio = dataOverview binding.name.text = dataName if (dataBirthday == "null") { binding.dob.visibility = View.GONE } else { binding.dob.text = dataBirthday?.toReadableDate() } if (dataBirthPlace == "null") { binding.birthPlace.visibility = View.GONE } else { binding.birthPlace.text = dataBirthPlace } if (dataOverview?.isEmpty() == true) { binding.overviewContainer.visibility = View.GONE binding.overview.visibility = View.GONE } else { if (Build.VERSION.SDK_INT >= 24) { binding.overview.text = Html.fromHtml(dataOverview, Html.FROM_HTML_MODE_LEGACY) } } try { Glide.with(this) .load(dataProfile) .fitCenter().into(binding.displayProfile) } catch (e: Exception) { } } catch (e: JSONException) { e.printStackTrace() } } private fun showPersonMovies(castMovieDetails: CastMovieDetailsResponse) { val charAdapter = CharacterDetailsActivityAdapter(castMovieDetails.castMovies, true) { movie, _ -> val intent = Intent(this, MovieDetailsActivity::class.java) intent.putExtra("id", movie.id.toString()) intent.putExtra("title", movie.title) intent.putExtra("network_applicable", true) intent.putExtra("activity", false) startActivity(intent) } binding.characterMovies.adapter = charAdapter if (castMovieDetails.castMovies.size > 4) { binding.more.visibility = View.VISIBLE } else { binding.more.visibility = View.INVISIBLE } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { supportFinishAfterTransition() } return super.onOptionsItemSelected(item) } override fun onBackPressed() { val fragment = supportFragmentManager.findFragmentByTag("DESC") as FullReadFragment? if (fragment != null && fragment.isVisible) { supportFragmentManager.beginTransaction().remove(fullReadFragment!!).commit() } else { super.onBackPressed() } } }
app/src/main/java/tech/salroid/filmy/ui/activities/CharacterDetailsActivity.kt
1693533540
package de.reiss.bible2net.theword.downloader.list interface DownloadListCallback { fun onListDownloadFinished(success: Boolean, data: List<Twd11>? = null) }
app/src/main/java/de/reiss/bible2net/theword/downloader/list/DownloadListCallback.kt
1219362960
/* * Copyright (C) 2016 Mantas Varnagiris. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package com.mvcoding.expensius.feature.settings import android.content.Context import android.util.AttributeSet import android.widget.LinearLayout import kotlinx.android.synthetic.main.item_view_settings.view.* class SettingsItemView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : LinearLayout(context, attrs, defStyleAttr) { fun setTitle(title: String) = with(titleTextView) { text = title } fun setSubtitle(subtitle: String) = with(subtitleTextView) { text = subtitle; visibility = if (subtitle.isBlank()) GONE else VISIBLE } }
app/src/main/kotlin/com/mvcoding/expensius/feature/settings/SettingsItemView.kt
1496632986
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.debugger.lang import org.antlr.v4.runtime.* import org.antlr.v4.runtime.misc.ParseCancellationException import org.jetbrains.annotations.TestOnly import org.rust.debugger.lang.RsTypeNameParser.TypeNameContext object RsTypeNameParserFacade { fun parse(typeName: String): TypeNameContext? = doParse(typeName) { it.parseTypeName().typeName() } @TestOnly fun parseToStringTree(typeName: String): String? = doParse(typeName) { it.parseTypeName().typeName().toStringTree(it) } private fun <T> doParse(typeName: String, block: (RsTypeNameParser) -> T?): T? { val stream = CharStreams.fromString(typeName) val lexer = RsTypeNameLexer(stream).apply { configureErrorListeners() } val tokens = CommonTokenStream(lexer) val parser = RsTypeNameParser(tokens).apply { configureErrorListeners() } return try { block(parser) } catch (e: RuntimeException) { when (e) { is ParseCancellationException, is RecognitionException -> return null else -> throw e } } } private fun Recognizer<*, *>.configureErrorListeners() { removeErrorListeners() addErrorListener(object : BaseErrorListener() { override fun syntaxError( recognizer: Recognizer<*, *>, offendingSymbol: Any?, line: Int, charPositionInLine: Int, msg: String, e: RecognitionException? ) { throw ParseCancellationException("($line:$charPositionInLine)") } }) } }
debugger/src/main/kotlin/org/rust/debugger/lang/RsTypeNameParserFacade.kt
1538451567
/* * Copyright (C) 2016 Mantas Varnagiris. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package com.mvcoding.expensius.feature.currency import com.mvcoding.expensius.model.Currency import com.mvcoding.expensius.model.CurrencyFormat interface CurrencyFormatsProvider { fun getCurrencyFormat(currency: Currency): CurrencyFormat }
app-core/src/main/kotlin/com/mvcoding/expensius/feature/currency/CurrencyFormatsProvider.kt
2964431903
package com.twitter.meil_mitu.twitter4hk.api.lists.members import com.twitter.meil_mitu.twitter4hk.AbsOauth import com.twitter.meil_mitu.twitter4hk.AbsPost import com.twitter.meil_mitu.twitter4hk.OauthType import com.twitter.meil_mitu.twitter4hk.converter.IUserListConverter import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException class Destroy<TUserList>( oauth: AbsOauth, protected val json: IUserListConverter<TUserList>) : AbsPost<TUserList>(oauth) { var listId: Long? by longParam("list_id") var slug: String? by stringParam("slug") var userId: Long? by longParam("user_id") var screenName: String? by stringParam("screen_name") var ownerScreenName: String? by stringParam("owner_screen_name") var ownerId: Long? by longParam("owner_id") override val url = "https://api.twitter.com/1.1/lists/members/destroy.json" override val allowOauthType = OauthType.oauth1 override val isAuthorization = true @Throws(Twitter4HKException::class) override fun call(): TUserList { return json.toUserList(oauth.post(this)) } }
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/lists/members/Destroy.kt
3354521348
package com.github.petropavel13.twophoto.adapters import android.content.Context import android.support.v4.view.PagerAdapter import android.support.v4.view.ViewPager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.petropavel13.twophoto.R import com.github.petropavel13.twophoto.model.Post import com.github.petropavel13.twophoto.views.EntryView import java.util.HashMap /** * Created by petropavel on 31/03/15. */ class PostEntriesPagerAdapter(ctx: Context, var entries: List<Post.Entry>): PagerAdapter() { private val inflater = ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater private var _onEntryTapListener: View.OnClickListener? = null var onEntryTapListener: View.OnClickListener? get() = _onEntryTapListener set(newValue) { _onEntryTapListener = newValue _positionViewMap.values.forEach { it.onTapListener = newValue } } private var _showEntriesDescription = true var showEntriesDescription: Boolean get() = _showEntriesDescription set(newValue) { _showEntriesDescription = newValue _positionViewMap.values.forEach { it.showDescriptionText = newValue } } private val _positionViewMap = HashMap<Int, EntryView>(3) fun getViewForAtPosition(position: Int): EntryView? = _positionViewMap.get(position) override fun getCount() = entries.count() override fun isViewFromObject(view: View?, obj: Any?): Boolean { return obj === view } override fun instantiateItem(container: View?, position: Int): Any? { with(inflater.inflate(R.layout.entry_layout, container as? ViewGroup, false) as EntryView) { entry = entries[position] onTapListener = _onEntryTapListener showDescriptionText = showEntriesDescription (container as ViewPager).addView(this, 0) _positionViewMap.put(position, this) return this } } override fun destroyItem(container: View?, position: Int, item: Any?) { with(item as EntryView) { (container as ViewPager).removeView(this) _positionViewMap.remove(position) } } }
TwoPhoto/app/src/main/java/com/github/petropavel13/twophoto/adapters/PostEntriesPagerAdapter.kt
3289082298
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko.render import org.jetbrains.android.anko.config.GeneratorContext import org.jetbrains.android.anko.config.AnkoFile import org.jetbrains.android.anko.config.ConfigurationKey import org.jetbrains.android.anko.generator.GenerationState import org.jetbrains.android.anko.generator.ServiceGenerator class ServiceRenderer(context: GeneratorContext) : Renderer(context) { override val renderIf: Array<ConfigurationKey<Boolean>> = arrayOf(AnkoFile.SERVICES) override fun processElements(state: GenerationState) = generatedFile("Suppress(\"unused\")") { importList -> append(render("services", importList) { "services" % state[ServiceGenerator::class.java] }) } }
anko/library/generator/src/org/jetbrains/android/anko/render/ServiceRenderer.kt
3656911303
package com.quijotelui.electronico.comprobantes.guia import javax.xml.bind.annotation.XmlElement import javax.xml.bind.annotation.XmlRootElement @XmlRootElement class Detalles { @XmlElement private var detalle: MutableCollection<Detalle> = mutableListOf() fun setDetalle(detalle : Detalle){ this.detalle.add(detalle) } }
src/main/kotlin/com/quijotelui/electronico/comprobantes/guia/Detalles.kt
3629623811
package domain.loggedincheck import domain.interactor.SingleDisposableUseCase import io.reactivex.Scheduler import io.reactivex.Single class LoggedInUserCheckUseCase( asyncExecutionScheduler: Scheduler, postExecutionScheduler: Scheduler) : SingleDisposableUseCase<Boolean>(asyncExecutionScheduler, postExecutionScheduler) { override fun buildUseCase(): Single<Boolean> = Single.just(LoggedInCheckHolder.loggedInCheck.isThereALoggedInUser()) }
domain/src/main/kotlin/domain/loggedincheck/LoggedInUserCheckUseCase.kt
3795530711
/* * 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.ui.test import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.util.BoundaryNode import androidx.compose.ui.test.util.expectErrorMessageStartsWith import androidx.compose.ui.text.input.ImeAction import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.FlakyTest import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) class TextActionsTest { private val fieldTag = "Field" @get:Rule val rule = createComposeRule() @Composable @OptIn(ExperimentalFoundationApi::class) fun TextFieldUi( imeAction: ImeAction = ImeAction.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, textCallback: (String) -> Unit = {} ) { val state = remember { mutableStateOf("") } BasicTextField( modifier = Modifier.testTag(fieldTag), value = state.value, keyboardOptions = KeyboardOptions(imeAction = imeAction), keyboardActions = keyboardActions, onValueChange = { state.value = it textCallback(it) } ) } @Test fun sendText_clearText() { var lastSeenText = "" rule.setContent { TextFieldUi { lastSeenText = it } } rule.onNodeWithTag(fieldTag) .performTextInput("Hello!") rule.runOnIdle { assertThat(lastSeenText).isEqualTo("Hello!") } rule.onNodeWithTag(fieldTag) .performTextClearance() rule.runOnIdle { assertThat(lastSeenText).isEqualTo("") } } @FlakyTest(bugId = 215584831) @Test fun sendTextTwice_shouldAppend() { var lastSeenText = "" rule.setContent { TextFieldUi { lastSeenText = it } } rule.onNodeWithTag(fieldTag) .performTextInput("Hello ") rule.onNodeWithTag(fieldTag) .performTextInput("world!") rule.runOnIdle { assertThat(lastSeenText).isEqualTo("Hello world!") } } // @Test - not always appends, seems to be flaky fun sendTextTwice_shouldAppend_ver2() { var lastSeenText = "" rule.setContent { TextFieldUi { lastSeenText = it } } rule.onNodeWithTag(fieldTag) .performTextInput("Hello") // This helps. So there must be some timing issue. // Thread.sleep(3000) rule.onNodeWithTag(fieldTag) .performTextInput(" world!") rule.runOnIdle { assertThat(lastSeenText).isEqualTo("Hello world!") } } @Test fun replaceText() { var lastSeenText = "" rule.setContent { TextFieldUi { lastSeenText = it } } rule.onNodeWithTag(fieldTag) .performTextInput("Hello") rule.runOnIdle { assertThat(lastSeenText).isEqualTo("Hello") } rule.onNodeWithTag(fieldTag) .performTextReplacement("world") rule.runOnIdle { assertThat(lastSeenText).isEqualTo("world") } } @Test fun sendImeAction_search() { var actionPerformed = false rule.setContent { TextFieldUi( imeAction = ImeAction.Search, keyboardActions = KeyboardActions(onSearch = { actionPerformed = true }) ) } assertThat(actionPerformed).isFalse() rule.onNodeWithTag(fieldTag) .performImeAction() rule.runOnIdle { assertThat(actionPerformed).isTrue() } } @Test fun sendImeAction_actionNotDefined_shouldFail() { var actionPerformed = false rule.setContent { TextFieldUi( imeAction = ImeAction.Default, keyboardActions = KeyboardActions { actionPerformed = true } ) } assertThat(actionPerformed).isFalse() expectErrorMessageStartsWith( "" + "Failed to perform IME action as current node does not specify any.\n" + "Semantics of the node:" ) { rule.onNodeWithTag(fieldTag) .performImeAction() } } @Test fun sendImeAction_inputNotSupported_shouldFail() { rule.setContent { BoundaryNode(testTag = "node") } expectErrorMessageStartsWith( "" + "Failed to perform IME action.\n" + "Failed to assert the following: (SetText is defined)\n" + "Semantics of the node:" ) { rule.onNodeWithTag("node") .performImeAction() } } }
compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/TextActionsTest.kt
4055038545
/* * 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 * * 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.credentials import android.os.Bundle import androidx.annotation.VisibleForTesting /** * A response of a public key credential (passkey) flow. * * @property registrationResponseJson the public key credential registration response in JSON format * @throws NullPointerException If [registrationResponseJson] is null * @throws IllegalArgumentException If [registrationResponseJson] is blank */ class CreatePublicKeyCredentialResponse( val registrationResponseJson: String ) : CreateCredentialResponse( PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL, toBundle(registrationResponseJson) ) { init { require(registrationResponseJson.isNotEmpty()) { "registrationResponseJson must not be " + "empty" } } /** @hide */ companion object { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) const val BUNDLE_KEY_REGISTRATION_RESPONSE_JSON = "androidx.credentials.BUNDLE_KEY_REGISTRATION_RESPONSE_JSON" @JvmStatic internal fun toBundle(registrationResponseJson: String): Bundle { val bundle = Bundle() bundle.putString(BUNDLE_KEY_REGISTRATION_RESPONSE_JSON, registrationResponseJson) return bundle } } }
credentials/credentials/src/main/java/androidx/credentials/CreatePublicKeyCredentialResponse.kt
922778807
object Acronym { fun generate(s: String) : String { val l = s.split(Regex("\\W+")) var acronym = "" for (word in l) { acronym += word[0].toUpperCase() val remainer = word.drop(1) val upperRemainer = remainer.replace(Regex("[^A-Z]"), "") if (!upperRemainer.isEmpty() && remainer != upperRemainer) acronym += upperRemainer } return acronym } }
kotlin/acronym/src/main/kotlin/Acronym.kt
1717706756
/* * 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.ui.hapticfeedback /** * Interface for haptic feedback. */ interface HapticFeedback { /** * Provide haptic feedback to the user. */ fun performHapticFeedback(hapticFeedbackType: HapticFeedbackType) }
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/hapticfeedback/HapticFeedback.kt
948596426
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.unit import androidx.compose.ui.geometry.Offset import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class IntOffsetTest { @Test fun lerpPosition() { val a = IntOffset(3, 10) val b = IntOffset(5, 8) assertEquals(IntOffset(4, 9), lerp(a, b, 0.5f)) assertEquals(IntOffset(3, 10), lerp(a, b, 0f)) assertEquals(IntOffset(5, 8), lerp(a, b, 1f)) } @Test fun positionMinus() { val a = IntOffset(3, 10) val b = IntOffset(5, 8) assertEquals(IntOffset(-2, 2), a - b) assertEquals(IntOffset(2, -2), b - a) } @Test fun positionPlus() { val a = IntOffset(3, 10) val b = IntOffset(5, 8) assertEquals(IntOffset(8, 18), a + b) assertEquals(IntOffset(8, 18), b + a) } @Test fun toOffset() { assertEquals(Offset(3f, 10f), IntOffset(3, 10).toOffset()) } }
compose/ui/ui-unit/src/test/kotlin/androidx/compose/ui/unit/IntOffsetTest.kt
3592505782
@file:Suppress("UNUSED") package de.holisticon.ranked.view.leaderboard import de.holisticon.ranked.model.Elo import de.holisticon.ranked.model.UserName import de.holisticon.ranked.model.event.PlayerRankingChanged import mu.KLogging import org.axonframework.config.ProcessingGroup import org.axonframework.eventhandling.EventHandler import org.axonframework.eventhandling.Timestamp import org.springframework.stereotype.Component import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId import java.util.concurrent.atomic.AtomicReference import java.util.function.Supplier const val PROCESSING_GROUP = "PlayerLeaderBoard" /** * The rest controller just provides a facade for [PlayerRankingByEloHandler.get]. */ @RestController @RequestMapping(value = ["/view/elo"]) class PlayerLeaderBoardView( private val playerRankingByElo: PlayerRankingByEloHandler ) { @GetMapping(path = ["/player"]) fun userListByEloRank() : List<PlayerElo> = playerRankingByElo.get() @GetMapping(path = ["/player/{userName}"]) fun eloHistoryByPlayer(@PathVariable("userName") userName: String): MutableList<Pair<LocalDateTime, Elo>> = playerRankingByElo.getHistory(userName) } /** * The business logic for elo-rankings, handles axon events that affect players and elo and provides a sorted list * descending by elo value. */ @Component @ProcessingGroup(PROCESSING_GROUP) class PlayerRankingByEloHandler : Supplier<List<PlayerElo>> { companion object : KLogging() /** * Holds a mutable list of userName->elo, this is the data store that is updated with every elo change. */ private val ranking = mutableMapOf<UserName, Elo>() /** * Holds a mutable list of userName->List<timestamp, elo>, this is the history of elo values that is updated with every elo change. */ private val rankingHistory = mutableMapOf<UserName, MutableList<Pair<LocalDateTime, Elo>>>() /** * The cache holds an immutable list of [PlayerElo] for the json return. It is sorted descending by elo value. * A cache is used because we only need to sort once per update and can return the same immutable sorted list * for every get request after that. */ private val cache = AtomicReference<List<PlayerElo>>(listOf()) @EventHandler fun on(e: PlayerRankingChanged, @Timestamp t: Instant) { logger.debug { "Player '${e.player}' new rating is '${e.eloRanking}'" } ranking[e.player] = e.eloRanking rankingHistory.putIfAbsent(e.player, mutableListOf()) rankingHistory[e.player]!!.add(Pair(LocalDateTime.ofInstant(t, ZoneId.of("Europe/Berlin")), e.eloRanking)) cache.set(ranking.map { it.toPair() }.map { PlayerElo(it.first, it.second) }.sorted()) } override fun get() = cache.get()!! fun getHistory(userName: String) = rankingHistory[UserName(userName)] ?: mutableListOf() } /** * The return value for the player ranking provides a username (string) and an elo value (int). */ data class PlayerElo(val userName: UserName, val elo: Elo) : Comparable<PlayerElo> { constructor(userName: String, elo: Elo) : this(UserName(userName), elo) override fun compareTo(other: PlayerElo): Int = other.elo.compareTo(elo) }
backend/views/leaderboard/src/main/kotlin/PlayerRankingByElo.kt
2630915332
/* * Copyright 2017 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.trigger import com.pyamsoft.pydroid.util.presenter.ViewPresenter import javax.inject.Inject class TriggerCreatePresenter @Inject internal constructor() : ViewPresenter()
powermanager-trigger/src/main/java/com/pyamsoft/powermanager/trigger/TriggerCreatePresenter.kt
4034420246
package me.proxer.app.news.widget import android.app.PendingIntent import android.app.PendingIntent.FLAG_UPDATE_CURRENT import android.appwidget.AppWidgetManager import android.content.ComponentName import android.content.Context import android.view.View import android.widget.RemoteViews import androidx.work.Constraints import androidx.work.ExistingWorkPolicy import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.Worker import androidx.work.WorkerParameters import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial import com.mikepenz.iconics.utils.colorRes import com.mikepenz.iconics.utils.paddingDp import com.mikepenz.iconics.utils.sizeDp import com.squareup.moshi.Moshi import me.proxer.app.BuildConfig import me.proxer.app.MainActivity import me.proxer.app.R import me.proxer.app.forum.TopicActivity import me.proxer.app.util.ErrorUtils import me.proxer.app.util.ErrorUtils.ErrorAction import me.proxer.app.util.extension.intentFor import me.proxer.app.util.extension.safeInject import me.proxer.app.util.extension.toInstantBP import me.proxer.app.util.extension.unsafeLazy import me.proxer.app.util.wrapper.MaterialDrawerWrapper import me.proxer.library.ProxerApi import me.proxer.library.ProxerCall import org.koin.core.KoinComponent import timber.log.Timber /** * @author Ruben Gees */ class NewsWidgetUpdateWorker( context: Context, workerParams: WorkerParameters ) : Worker(context, workerParams), KoinComponent { companion object : KoinComponent { private const val NAME = "NewsWidgetUpdateWorker" private val workManager by safeInject<WorkManager>() fun enqueueWork() { val workRequest = OneTimeWorkRequestBuilder<NewsWidgetUpdateWorker>() .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() ) .build() workManager.beginUniqueWork(NAME, ExistingWorkPolicy.REPLACE, workRequest).enqueue() } } private val api by safeInject<ProxerApi>() private val moshi by safeInject<Moshi>() private val appWidgetManager by unsafeLazy { AppWidgetManager.getInstance(applicationContext) } private val widgetIds by unsafeLazy { appWidgetManager.getAppWidgetIds(ComponentName(applicationContext, NewsWidgetProvider::class.java)) } private val darkWidgetIds by unsafeLazy { appWidgetManager.getAppWidgetIds(ComponentName(applicationContext, NewsWidgetDarkProvider::class.java)) } private var currentCall: ProxerCall<*>? = null override fun doWork(): Result { widgetIds.forEach { id -> bindLoadingLayout(appWidgetManager, id, false) } darkWidgetIds.forEach { id -> bindLoadingLayout(appWidgetManager, id, true) } return try { val news = if (!isStopped) { api.notifications.news() .build() .also { currentCall = it } .safeExecute() .map { SimpleNews(it.id, it.threadId, it.categoryId, it.subject, it.category, it.date.toInstantBP()) } } else { emptyList() } if (!isStopped) { if (news.isEmpty()) { val noDataAction = ErrorAction(R.string.error_no_data_news) widgetIds.forEach { id -> bindErrorLayout(appWidgetManager, id, noDataAction, false) } darkWidgetIds.forEach { id -> bindErrorLayout(appWidgetManager, id, noDataAction, true) } } else { widgetIds.forEach { id -> bindListLayout(appWidgetManager, id, news, false) } darkWidgetIds.forEach { id -> bindListLayout(appWidgetManager, id, news, true) } } } Result.success() } catch (error: Throwable) { Timber.e(error) if (!isStopped) { val action = ErrorUtils.handle(error) widgetIds.forEach { id -> bindErrorLayout(appWidgetManager, id, action, false) } darkWidgetIds.forEach { id -> bindErrorLayout(appWidgetManager, id, action, true) } } return Result.failure() } } override fun onStopped() { currentCall?.cancel() currentCall = null } private fun bindListLayout(appWidgetManager: AppWidgetManager, id: Int, news: List<SimpleNews>, dark: Boolean) { val views = RemoteViews( BuildConfig.APPLICATION_ID, when (dark) { true -> R.layout.layout_widget_news_dark_list false -> R.layout.layout_widget_news_list } ) val serializedNews = news .map { moshi.adapter(SimpleNews::class.java).toJson(it) } .toTypedArray() val intent = when (dark) { true -> applicationContext.intentFor<NewsWidgetDarkService>( NewsWidgetDarkService.ARGUMENT_NEWS to serializedNews ) false -> applicationContext.intentFor<NewsWidgetService>( NewsWidgetService.ARGUMENT_NEWS to serializedNews ) } val detailIntent = applicationContext.intentFor<TopicActivity>() val detailPendingIntent = PendingIntent.getActivity(applicationContext, 0, detailIntent, FLAG_UPDATE_CURRENT) bindBaseLayout(id, views) views.setPendingIntentTemplate(R.id.list, detailPendingIntent) views.setRemoteAdapter(R.id.list, intent) appWidgetManager.updateAppWidget(id, views) } private fun bindErrorLayout(appWidgetManager: AppWidgetManager, id: Int, errorAction: ErrorAction, dark: Boolean) { val views = RemoteViews( BuildConfig.APPLICATION_ID, when (dark) { true -> R.layout.layout_widget_news_dark_error false -> R.layout.layout_widget_news_error } ) val errorIntent = errorAction.toIntent() bindBaseLayout(id, views) views.setTextViewText(R.id.errorText, applicationContext.getString(errorAction.message)) if (errorIntent != null) { val errorPendingIntent = PendingIntent.getActivity(applicationContext, 0, errorIntent, FLAG_UPDATE_CURRENT) views.setTextViewText(R.id.errorButton, applicationContext.getString(errorAction.buttonMessage)) views.setOnClickPendingIntent(R.id.errorButton, errorPendingIntent) } else { views.setViewVisibility(R.id.errorButton, View.GONE) } appWidgetManager.updateAppWidget(id, views) } private fun bindLoadingLayout(appWidgetManager: AppWidgetManager, id: Int, dark: Boolean) { val views = RemoteViews( BuildConfig.APPLICATION_ID, when (dark) { true -> R.layout.layout_widget_news_dark_loading false -> R.layout.layout_widget_news_loading } ) bindBaseLayout(id, views) appWidgetManager.updateAppWidget(id, views) } private fun bindBaseLayout(id: Int, views: RemoteViews) { val intent = MainActivity.getSectionIntent(applicationContext, MaterialDrawerWrapper.DrawerItem.NEWS) val pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, FLAG_UPDATE_CURRENT) val updateIntent = applicationContext.intentFor<NewsWidgetProvider>() .setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE) .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(id)) val updatePendingIntent = PendingIntent.getBroadcast(applicationContext, 0, updateIntent, FLAG_UPDATE_CURRENT) views.setOnClickPendingIntent(R.id.title, pendingIntent) views.setOnClickPendingIntent(R.id.refresh, updatePendingIntent) views.setImageViewBitmap( R.id.refresh, IconicsDrawable(applicationContext, CommunityMaterial.Icon.cmd_refresh) .colorRes(android.R.color.white) .sizeDp(32) .paddingDp(8) .toBitmap() ) } }
src/main/kotlin/me/proxer/app/news/widget/NewsWidgetUpdateWorker.kt
2677111213
package org.wordpress.aztec.util import android.text.Spannable import org.wordpress.android.util.AppLog class SpanWrapper<T>(var spannable: Spannable, var span: T) { private var frozenStart: Int = -1 private var frozenEnd: Int = -1 private var frozenFlags: Int = -1 fun remove() { frozenStart = start frozenEnd = end frozenFlags = flags spannable.removeSpan(span) } fun reapply() { if (frozenFlags != -1 && frozenEnd != -1 && frozenStart != -1) { setSpanOrLogError(span, frozenStart, frozenEnd, frozenFlags) } } var start: Int get() { return spannable.getSpanStart(span) } set(start) { setSpanOrLogError(span, start, end, flags) } var end: Int get() { return spannable.getSpanEnd(span) } set(end) { setSpanOrLogError(span, start, end, flags) } var flags: Int get() { return spannable.getSpanFlags(span) } set(flags) { setSpanOrLogError(span, start, end, flags) } private fun setSpanOrLogError(span: T, start: Int, end: Int, flags: Int) { // Silently ignore invalid PARAGRAPH spans that don't start or end at paragraph boundary if (isInvalidParagraph(spannable, start, end, flags)) return spannable.setSpan(span, start, end, flags) } companion object { // Copied from SpannableStringBuilder private val START_MASK = 0xF0 private val END_MASK = 0x0F private val START_SHIFT = 4 private val PARAGRAPH = 3 fun isInvalidParagraph(spannable: Spannable, start: Int, end: Int, flags: Int) : Boolean { // Copied from SpannableStringBuilder that throws an exception in this case. val flagsStart = flags and START_MASK shr START_SHIFT if (isInvalidParagraph(spannable, start, flagsStart)) { AppLog.w(AppLog.T.EDITOR, "PARAGRAPH span must start at paragraph boundary" + " (" + start + " follows " + spannable.get(start - 1) + ")") return true } val flagsEnd = flags and END_MASK if (isInvalidParagraph(spannable, end, flagsEnd)) { AppLog.w(AppLog.T.EDITOR, "PARAGRAPH span must end at paragraph boundary" + " (" + end + " follows " + spannable.get(end - 1) + ")") return true } return false } private fun isInvalidParagraph(spannable: Spannable, index: Int, flag: Int): Boolean { return flag == PARAGRAPH && index != 0 && index != spannable.length && spannable.get(index - 1) != '\n' } inline fun <reified T : Any> getSpans(spannable: Spannable, start: Int, end: Int): List<SpanWrapper<T>> { return getSpans(spannable, spannable.getSpans(start, end, T::class.java)) } fun <T> getSpans(spannable: Spannable, start: Int, end: Int, type: Class<T>): List<SpanWrapper<T>> { return getSpans(spannable, spannable.getSpans(start, end, type)) } fun <T> getSpans(spannable: Spannable, spanObjects: Array<T>): List<SpanWrapper<T>> { return spanObjects.map { it -> SpanWrapper(spannable, it) } } } }
aztec/src/main/kotlin/org/wordpress/aztec/util/SpanWrapper.kt
4243849383
package ru.fantlab.android.ui.widgets import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import androidx.viewpager.widget.PagerAdapter import androidx.viewpager.widget.ViewPager /** * Created by kosh20111 on 10/8/2015. * * * Viewpager that has scrolling animation by default */ class ViewPagerView : ViewPager { private var isEnabled: Boolean = false constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { val attrsArray = intArrayOf(android.R.attr.enabled) val array = context.obtainStyledAttributes(attrs, attrsArray) isEnabled = array.getBoolean(0, true) array.recycle() } override fun isEnabled(): Boolean { return isEnabled } override fun setEnabled(enabled: Boolean) { this.isEnabled = enabled requestLayout() } override fun setAdapter(adapter: PagerAdapter?) { super.setAdapter(adapter) if (isInEditMode) return adapter?.let { offscreenPageLimit = it.count } } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { try { return !isEnabled() || super.onTouchEvent(event) } catch (ex: IllegalArgumentException) { ex.printStackTrace() } return false } override fun onInterceptTouchEvent(event: MotionEvent): Boolean { try { return isEnabled() && super.onInterceptTouchEvent(event) } catch (ex: IllegalArgumentException) { ex.printStackTrace() } return false } }
app/src/main/kotlin/ru/fantlab/android/ui/widgets/ViewPagerView.kt
3153613107
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.application.options.PathMacrosImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.openapi.components.* import com.intellij.openapi.components.impl.stores.StoreUtil import com.intellij.openapi.components.impl.stores.StreamProvider import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.io.systemIndependentPath import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.testFramework.FixtureRule import com.intellij.testFramework.TemporaryDirectory import com.intellij.testFramework.exists import com.intellij.util.xmlb.XmlSerializerUtil import gnu.trove.THashMap import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.not import org.hamcrest.MatcherAssert.assertThat import org.intellij.lang.annotations.Language import org.junit.Before import org.junit.Rule import org.junit.Test import java.io.ByteArrayInputStream import java.io.File import java.io.InputStream import kotlin.properties.Delegates class ApplicationStoreTest { private val fixtureManager = FixtureRule() public Rule fun getFixtureManager(): FixtureRule = fixtureManager private val tempDirManager = TemporaryDirectory() public Rule fun getTemporaryFolder(): TemporaryDirectory = tempDirManager private var testAppConfig: File by Delegates.notNull() private var componentStore: MyComponentStore by Delegates.notNull() public Before fun setUp() { testAppConfig = tempDirManager.newDirectory() componentStore = MyComponentStore(FileUtilRt.toSystemIndependentName(testAppConfig.systemIndependentPath)) } public Test fun `stream provider save if several storages configured`() { val component = SeveralStoragesConfigured() val streamProvider = MyStreamProvider() componentStore.getStateStorageManager().setStreamProvider(streamProvider) componentStore.initComponent(component, false) component.foo = "newValue" StoreUtil.save(componentStore, null) assertThat<String>(streamProvider.data.get(RoamingType.PER_USER)!!.get(StoragePathMacros.APP_CONFIG + "/proxy.settings.xml"), equalTo("<application>\n" + " <component name=\"HttpConfigurable\">\n" + " <option name=\"foo\" value=\"newValue\" />\n" + " </component>\n" + "</application>")) } public Test fun testLoadFromStreamProvider() { val component = SeveralStoragesConfigured() val streamProvider = MyStreamProvider() val map = THashMap<String, String>() map.put(StoragePathMacros.APP_CONFIG + "/proxy.settings.xml", "<application>\n" + " <component name=\"HttpConfigurable\">\n" + " <option name=\"foo\" value=\"newValue\" />\n" + " </component>\n" + "</application>") streamProvider.data.put(RoamingType.PER_USER, map) componentStore.getStateStorageManager().setStreamProvider(streamProvider) componentStore.initComponent(component, false) assertThat(component.foo, equalTo("newValue")) } public Test fun `remove deprecated storage on write`() { } public Test fun `remove deprecated storage on write 2`() { doRemoveDeprecatedStorageOnWrite(ActualStorageLast()) } private fun doRemoveDeprecatedStorageOnWrite(component: Foo) { val oldFile = saveConfig("other.xml", "<application>" + " <component name=\"HttpConfigurable\">\n" + " <option name=\"foo\" value=\"old\" />\n" + " </component>\n" + "</application>") saveConfig("proxy.settings.xml", "<application>\n" + " <component name=\"HttpConfigurable\">\n" + " <option name=\"foo\" value=\"new\" />\n" + " </component>\n" + "</application>") componentStore.initComponent(component, false) assertThat(component.foo, equalTo("new")) component.foo = "new2" invokeAndWaitIfNeed { StoreUtil.save(componentStore, null) } assertThat(oldFile, not(exists())) } private fun saveConfig(fileName: String, Language("XML") data: String): File { val file = File(testAppConfig, fileName) FileUtil.writeToFile(file, data) return file } private class MyStreamProvider : StreamProvider { public val data: MutableMap<RoamingType, MutableMap<String, String>> = THashMap() override fun saveContent(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { getMap(roamingType).put(fileSpec, String(content, 0, size, CharsetToolkit.UTF8_CHARSET)) } private fun getMap(roamingType: RoamingType): MutableMap<String, String> { var map = data.get(roamingType) if (map == null) { map = THashMap<String, String>() data.put(roamingType, map) } return map } override fun loadContent(fileSpec: String, roamingType: RoamingType): InputStream? { val data = getMap(roamingType).get(fileSpec) ?: return null return ByteArrayInputStream(data.toByteArray()) } override fun delete(fileSpec: String, roamingType: RoamingType) { data.get(roamingType)?.remove(fileSpec) } } class MyComponentStore(testAppConfigPath: String) : ComponentStoreImpl() { private val storageManager = object : StateStorageManagerImpl("application") { override fun getMacroSubstitutor(fileSpec: String): TrackingPathMacroSubstitutor? { if (fileSpec == "${StoragePathMacros.APP_CONFIG}/${PathMacrosImpl.EXT_FILE_NAME}.xml") { return null } return super.getMacroSubstitutor(fileSpec) } } init { setPath(testAppConfigPath) } override fun setPath(path: String) { storageManager.addMacro(StoragePathMacros.APP_CONFIG, path) } override fun getStateStorageManager() = storageManager override fun getMessageBus() = ApplicationManager.getApplication().getMessageBus() } abstract class Foo { public var foo: String = "defaultValue" } State(name = "HttpConfigurable", storages = arrayOf(Storage(file = StoragePathMacros.APP_CONFIG + "/proxy.settings.xml"), Storage(file = StoragePathMacros.APP_CONFIG + "/other.xml", deprecated = true))) class SeveralStoragesConfigured : Foo(), PersistentStateComponent<SeveralStoragesConfigured> { override fun getState(): SeveralStoragesConfigured? { return this } override fun loadState(state: SeveralStoragesConfigured) { XmlSerializerUtil.copyBean(state, this) } } State(name = "HttpConfigurable", storages = arrayOf(Storage(file = StoragePathMacros.APP_CONFIG + "/other.xml", deprecated = true), Storage(file = StoragePathMacros.APP_CONFIG + "/proxy.settings.xml"))) class ActualStorageLast : Foo(), PersistentStateComponent<ActualStorageLast> { override fun getState() = this override fun loadState(state: ActualStorageLast) { XmlSerializerUtil.copyBean(state, this) } } }
platform/configuration-store-impl/testSrc/ApplicationStoreTest.kt
2830322615
package argparser import argparser.exception.NotAllowedValueException import argparser.exception.NotDeclaredException import argparser.exception.RequiredNotPassedException /** * This is a simple argument parser for command line * tools. * * @param description Description for the program * @param programName Name of the program */ class Argparser(var description: String = "", var programName: String = "") { private var arguments: HashMap<String, Argument> = HashMap() /** * Add an option to the parser. * * @param description Description * @param option The name of the option * @param hasValue Should there be a value after the option */ fun addArgument(description: String, option: String, defaultValue: String = "", optional: Boolean = false, hasValue: Boolean = true) { val a = Argument( defaultValue = defaultValue, description = description, hasValue = hasValue, optional = optional ) arguments.put(option.replace("--", ""), a) } /** * Parse the arguments passed to the program. * * @param args Arguments from the command line */ fun parse(args: Array<String>): Map<String, String> { var cmd: String var lastArg: Argument? = null // Is there a help option? if (args.contains("--help")) { printHelp() return emptyMap() } // Reset arguments arguments.forEach { _, a -> a.isSet = false a.value = a.defaultValue } // Parse each argument args.forEach { arg -> // Is it a option? if (arg.startsWith("--")) { cmd = arg.replace("--", "") if (!arguments.containsKey(cmd)) throw NotDeclaredException("The option '$arg' was not declared.") lastArg = arguments[cmd] lastArg?.isSet = true } else { if (lastArg!!.hasValue) lastArg!!.value += "$arg " else throw NotAllowedValueException("There mustn't be a value after the option ${lastArg!!.value}") } } return transformOptions() } /** * Print all arguments and values if the command * 'help' was used. */ private fun printHelp() { if (programName.isNotEmpty()) println("usage:\n\t$programName [option_1] [value_1] ...") // Filter the arguments val opt = arguments.filterValues { argument -> argument.optional } val req = arguments.filterValues { argument -> !argument.optional } println("") println("description:\n\t$description") if (req.isNotEmpty()) { println("") println("required arguments: ") req.forEach { k, v -> if (!v.optional) println("\t--$k\t\t${v.description}") } } if (opt.isNotEmpty()) { println("") println("optional arguments: ") opt.forEach { k, v -> if (v.optional) println("\t--$k\t\t${v.description}") } } } /** * Transform the arguments list into a map. * * @return option list as map */ private fun transformOptions(): Map<String, String> { val result: HashMap<String, String> = HashMap() arguments.forEach { k, v -> if (!v.isSet && !v.optional) throw RequiredNotPassedException("Required argument was not passed.") result.put(k, v.value.trim()) } return result } }
src/main/kotlin/argparser/Argparser.kt
2065136739
package ru.fantlab.android.ui.modules.award.nominations import android.os.Bundle import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import ru.fantlab.android.data.dao.model.Award import ru.fantlab.android.ui.base.mvp.BaseMvp import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder interface AwardNominationsMvp { interface View : BaseMvp.View, SwipeRefreshLayout.OnRefreshListener, android.view.View.OnClickListener { fun onNotifyAdapter(items: List<Award.Nominations>?) fun onSetTabCount(allCount: Int) fun onItemClicked(item: Award.Nominations) } interface Presenter : BaseMvp.Presenter, BaseViewHolder.OnItemClickListener<Award.Nominations> { fun onFragmentCreated(bundle: Bundle) fun getNominations(force: Boolean) } }
app/src/main/kotlin/ru/fantlab/android/ui/modules/award/nominations/AwardNominationsMvp.kt
3591000075
package ru.fantlab.android.data.dao.model import ru.fantlab.android.R import ru.fantlab.android.ui.widgets.treeview.LayoutItemType class WorkAwardsParent(var title: String) : LayoutItemType { override val layoutId = R.layout.work_awards_parent_row_item }
app/src/main/kotlin/ru/fantlab/android/data/dao/model/WorkAwardsParent.kt
2337262953
package com.designdemo.uaha.view.product.device import android.app.Activity import android.content.Context import android.content.Intent import android.os.Build import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.designdemo.uaha.view.detail.DetailActivity import com.support.android.designlibdemo.R import androidx.core.app.ActivityOptionsCompat import androidx.recyclerview.widget.RecyclerView import com.designdemo.uaha.data.model.product.ProductEntity import kotlinx.android.synthetic.main.list_item_device.view.* class DeviceTypeAdapter(private val activity: Activity, context: Context, private val values: List<ProductEntity>) : RecyclerView.Adapter<DeviceTypeAdapter.ViewHolder>() { private val typedValue = TypedValue() private val background: Int class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) { var boundString: String? = null val imageView: ImageView = view.device_item_avatar val titleText: TextView = view.device_item_title val subTitleText: TextView = view.device_item_subtext override fun toString() = super.toString() + " '" + titleText.text } fun getValueAt(position: Int) = values[position] init { context.theme.resolveAttribute(R.attr.selectableItemBackground, typedValue, true) background = typedValue.resourceId } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_device, parent, false) view.setBackgroundResource(background) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.boundString = values[position].title holder.titleText.text = values[position].title holder.subTitleText.text = values[position].subTitle holder.view.setOnClickListener { v -> val context = v.context val intent = Intent(context, DetailActivity::class.java) val intentString = "${values[position].title}-${values[position].subTitle}" intent.putExtra(DetailActivity.EXTRA_APP_NAME, intentString) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val transitionName = context.getString(R.string.transition_string) val options = ActivityOptionsCompat.makeSceneTransitionAnimation( activity, holder.imageView, transitionName) context.startActivity(intent, options.toBundle()) } else { context.startActivity(intent) } } Glide.with(holder.imageView.context) .load(values[position].imgId) .fitCenter() .into(holder.imageView) } override fun getItemCount() = values.size }
app/src/main/java/com/designdemo/uaha/view/product/device/DeviceTypeAdapter.kt
4023095161
package eu.kanade.tachiyomi.extension.all.hitomi import eu.kanade.tachiyomi.extension.all.hitomi.Hitomi.Companion.LTN_BASE_URL import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservable import eu.kanade.tachiyomi.network.asObservableSuccess import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import rx.Observable import rx.Single import java.security.MessageDigest private typealias HashedTerm = ByteArray private data class DataPair(val offset: Long, val length: Int) private data class Node( val keys: List<ByteArray>, val datas: List<DataPair>, val subnodeAddresses: List<Long> ) /** * Kotlin port of the hitomi.la search algorithm * @author NerdNumber9 */ class HitomiNozomi( private val client: OkHttpClient, private val tagIndexVersion: Long, private val galleriesIndexVersion: Long ) { fun getGalleryIdsForQuery(query: String, language: String, popular: Boolean): Single<List<Int>> { if (':' in query) { val sides = query.split(':') val namespace = sides[0] var tag = sides[1] var area: String? = namespace if (namespace == "female" || namespace == "male") { area = "tag" tag = query } else if (namespace == "language") { return getGalleryIdsFromNozomi(null, "index", tag, popular) } return getGalleryIdsFromNozomi(area, tag, language, popular) } val key = hashTerm(query) val field = "galleries" return getNodeAtAddress(field, 0).flatMap { node -> if (node == null) { Single.just(null) } else { BSearch(field, key, node).flatMap { data -> if (data == null) { Single.just(null) } else { getGalleryIdsFromData(data) } } } } } private fun getGalleryIdsFromData(data: DataPair?): Single<List<Int>> { if (data == null) { return Single.just(emptyList()) } val url = "$LTN_BASE_URL/$GALLERIES_INDEX_DIR/galleries.$galleriesIndexVersion.data" val (offset, length) = data if (length > 100000000 || length <= 0) { return Single.just(emptyList()) } return client.newCall(rangedGet(url, offset, offset + length - 1)) .asObservable() .map { it.body?.bytes() ?: ByteArray(0) } .onErrorReturn { ByteArray(0) } .map { inbuf -> if (inbuf.isEmpty()) { return@map emptyList<Int>() } val view = ByteCursor(inbuf) val numberOfGalleryIds = view.nextInt() val expectedLength = numberOfGalleryIds * 4 + 4 if (numberOfGalleryIds > 10000000 || numberOfGalleryIds <= 0 || inbuf.size != expectedLength ) { return@map emptyList<Int>() } (1..numberOfGalleryIds).map { view.nextInt() } }.toSingle() } @Suppress("FunctionName") private fun BSearch(field: String, key: ByteArray, node: Node?): Single<DataPair?> { fun compareByteArrays(dv1: ByteArray, dv2: ByteArray): Int { val top = dv1.size.coerceAtMost(dv2.size) for (i in 0 until top) { val dv1i = dv1[i].toInt() and 0xFF val dv2i = dv2[i].toInt() and 0xFF if (dv1i < dv2i) { return -1 } else if (dv1i > dv2i) { return 1 } } return 0 } fun locateKey(key: ByteArray, node: Node): Pair<Boolean, Int> { var cmpResult = -1 var lastI = 0 for (nodeKey in node.keys) { cmpResult = compareByteArrays(key, nodeKey) if (cmpResult <= 0) break lastI++ } return (cmpResult == 0) to lastI } fun isLeaf(node: Node): Boolean { return !node.subnodeAddresses.any { it != 0L } } if (node == null || node.keys.isEmpty()) { return Single.just(null) } val (there, where) = locateKey(key, node) if (there) { return Single.just(node.datas[where]) } else if (isLeaf(node)) { return Single.just(null) } return getNodeAtAddress(field, node.subnodeAddresses[where]).flatMap { newNode -> BSearch(field, key, newNode) } } private fun decodeNode(data: ByteArray): Node { val view = ByteCursor(data) val numberOfKeys = view.nextInt() val keys = (1..numberOfKeys).map { val keySize = view.nextInt() view.next(keySize) } val numberOfDatas = view.nextInt() val datas = (1..numberOfDatas).map { val offset = view.nextLong() val length = view.nextInt() DataPair(offset, length) } val numberOfSubnodeAddresses = B + 1 val subnodeAddresses = (1..numberOfSubnodeAddresses).map { view.nextLong() } return Node(keys, datas, subnodeAddresses) } private fun getNodeAtAddress(field: String, address: Long): Single<Node?> { var url = "$LTN_BASE_URL/$INDEX_DIR/$field.$tagIndexVersion.index" if (field == "galleries") { url = "$LTN_BASE_URL/$GALLERIES_INDEX_DIR/galleries.$galleriesIndexVersion.index" } return client.newCall(rangedGet(url, address, address + MAX_NODE_SIZE - 1)) .asObservableSuccess() .map { it.body?.bytes() ?: ByteArray(0) } .onErrorReturn { ByteArray(0) } .map { nodedata -> if (nodedata.isNotEmpty()) { decodeNode(nodedata) } else null }.toSingle() } fun getGalleryIdsFromNozomi(area: String?, tag: String, language: String, popular: Boolean): Single<List<Int>> { val replacedTag = tag.replace('_', ' ') var nozomiAddress = "$LTN_BASE_URL/$COMPRESSED_NOZOMI_PREFIX/$replacedTag-$language$NOZOMI_EXTENSION" if (area != null) { nozomiAddress = if (popular) { "$LTN_BASE_URL/$COMPRESSED_NOZOMI_PREFIX/$area/popular/$replacedTag-$language$NOZOMI_EXTENSION" } else { "$LTN_BASE_URL/$COMPRESSED_NOZOMI_PREFIX/$area/$replacedTag-$language$NOZOMI_EXTENSION" } } return client.newCall( Request.Builder() .url(nozomiAddress) .build() ) .asObservableSuccess() .map { resp -> val body = resp.body!!.bytes() val cursor = ByteCursor(body) (1..body.size / 4).map { cursor.nextInt() } }.toSingle() } private fun hashTerm(query: String): HashedTerm { val md = MessageDigest.getInstance("SHA-256") md.update(query.toByteArray(HASH_CHARSET)) return md.digest().copyOf(4) } companion object { private const val INDEX_DIR = "tagindex" private const val GALLERIES_INDEX_DIR = "galleriesindex" private const val COMPRESSED_NOZOMI_PREFIX = "n" private const val NOZOMI_EXTENSION = ".nozomi" private const val MAX_NODE_SIZE = 464 private const val B = 16 private val HASH_CHARSET = Charsets.UTF_8 fun rangedGet(url: String, rangeBegin: Long, rangeEnd: Long?): Request { return GET( url, Headers.Builder() .add("Range", "bytes=$rangeBegin-${rangeEnd ?: ""}") .build() ) } fun getIndexVersion(httpClient: OkHttpClient, name: String): Observable<Long> { return httpClient.newCall(GET("$LTN_BASE_URL/$name/version?_=${System.currentTimeMillis()}")) .asObservableSuccess() .map { it.body!!.string().toLong() } } } }
src/all/hitomi/src/eu/kanade/tachiyomi/extension/all/hitomi/HitomiNozomi.kt
238247943
/* * Copyright 2016 Thomas Nappo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jire.arrowhead.linux import com.sun.jna.Pointer import com.sun.jna.Structure class iovec(@JvmField var iov_base: Pointer? = null, @JvmField var iov_len: Int = 0) : Structure() { override fun getFieldOrder() = arrayListOf("iov_base", "iov_len") }
src/main/kotlin/org/jire/arrowhead/linux/iovec.kt
1414309868
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.plsqlopen.api.annotations @Retention @Target(AnnotationTarget.CLASS, AnnotationTarget.FILE) annotation class RuleTemplate
zpa-core/src/main/kotlin/org/sonar/plugins/plsqlopen/api/annotations/RuleTemplate.kt
455711861
package com.echsylon.atlantis.request import org.amshove.kluent.`should be equal to` import org.amshove.kluent.`should not be equal to` import org.junit.Test class PatternTest { @Test fun `When comparing two patterns with same verb expressions, true is returned`() { val first = Pattern(verb = "(GET|POST)") val second = Pattern(verb = "(GET|POST)") first `should be equal to` second } @Test fun `When comparing two patterns with different verb expressions, false is returned`() { val first = Pattern(verb = "(GET|POST)") val second = Pattern(verb = "POST") first `should not be equal to` second } @Test fun `When comparing two patterns with same path expressions, true is returned`() { val first = Pattern(path = ".*") val second = Pattern(path = ".*") first `should be equal to` second } @Test fun `When comparing two patterns with different path expressions, false is returned`() { val first = Pattern(path = ".*") val second = Pattern(path = ".+") first `should not be equal to` second } @Test fun `When comparing two patterns with same headers, true is returned`() { val first = Pattern().apply { headers.add("A: B") } val second = Pattern().apply { headers.add("A: B") } first `should be equal to` second } @Test fun `When comparing two patterns with different headers, false is returned`() { val first = Pattern().apply { headers.add("A: B") } val second = Pattern().apply { headers.add("C: D") } first `should not be equal to` second } @Test fun `When testing for a request with matching verb, success is presented`() { val pattern = Pattern(verb = "(GET|POST)") val request = Request("GET", "/success", "HTTP/1.1") pattern.match(request) `should be equal to` true } @Test fun `When testing for a request with non-matching verb, failure is presented`() { val pattern = Pattern(verb = "(GET|POST)") val request = Request("PATCH", "/failure", "HTTP/1.1") pattern.match(request) `should be equal to` false } @Test fun `When testing for a request with matching path, success is presented`() { val pattern = Pattern(path = "/success") val request = Request("GET", "/success", "HTTP/1.1") pattern.match(request) `should be equal to` true } @Test fun `When testing for a request with non-matching path, failure is presented`() { val pattern = Pattern(path = "/success") val request = Request("GET", "/failure", "HTTP/1.1") pattern.match(request) `should be equal to` false } @Test fun `When testing for a request with matching headers, success is presented`() { val pattern = Pattern() .apply { headers.add("A: B") } val request = Request() .apply { headers.add("A: B") } .apply { headers.add("C: D") } pattern.match(request) `should be equal to` true } @Test fun `When testing for a request with non-matching headers, failure is presented`() { val pattern = Pattern() .apply { headers.add("A: B") } val request = Request() .apply { headers.add("C: D") } .apply { headers.add("E: F") } pattern.match(request) `should be equal to` false } }
library/lib/src/test/kotlin/com/echsylon/atlantis/request/PatternTest.kt
2565374879
package com.hakimlabs.rumahfiqih import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
app/src/test/java/com/hakimlabs/rumahfiqih/ExampleUnitTest.kt
3473220844
package com.mxt.anitrend.model.api.retro.anilist import com.mxt.anitrend.model.entity.anilist.ExternalLink import com.mxt.anitrend.model.entity.anilist.FeedList import com.mxt.anitrend.model.entity.anilist.Media import com.mxt.anitrend.model.entity.anilist.edge.CharacterEdge import com.mxt.anitrend.model.entity.anilist.edge.MediaEdge import com.mxt.anitrend.model.entity.anilist.edge.StaffEdge import com.mxt.anitrend.model.entity.base.MediaBase import com.mxt.anitrend.model.entity.container.body.AniListContainer import com.mxt.anitrend.model.entity.container.body.ConnectionContainer import com.mxt.anitrend.model.entity.container.body.EdgeContainer import com.mxt.anitrend.model.entity.container.body.PageContainer import io.github.wax911.library.annotation.GraphQuery import io.github.wax911.library.model.request.QueryContainerBuilder import retrofit2.Call import retrofit2.http.Body import retrofit2.http.Headers import retrofit2.http.POST /** * Created by max on 2018/03/20. * Series queries */ interface MediaModel { @POST("/") @GraphQuery("MediaBase") @Headers("Content-Type: application/json") fun getMediaBase(@Body request: QueryContainerBuilder?): Call<AniListContainer<MediaBase>> @POST("/") @GraphQuery("MediaOverview") @Headers("Content-Type: application/json") fun getMediaOverview(@Body request: QueryContainerBuilder?): Call<AniListContainer<Media>> @POST("/") @GraphQuery("MediaRelations") @Headers("Content-Type: application/json") fun getMediaRelations(@Body request: QueryContainerBuilder?): Call<AniListContainer<ConnectionContainer<EdgeContainer<MediaEdge>>>> @POST("/") @GraphQuery("MediaStats") @Headers("Content-Type: application/json") fun getMediaStats(@Body request: QueryContainerBuilder?): Call<AniListContainer<Media>> @POST("/") @GraphQuery("MediaEpisodes") @Headers("Content-Type: application/json") fun getMediaEpisodes(@Body request: QueryContainerBuilder?): Call<AniListContainer<ConnectionContainer<List<ExternalLink>>>> @POST("/") @GraphQuery("MediaCharacters") @Headers("Content-Type: application/json") fun getMediaCharacters(@Body request: QueryContainerBuilder?): Call<AniListContainer<ConnectionContainer<EdgeContainer<CharacterEdge>>>> @POST("/") @GraphQuery("MediaStaff") @Headers("Content-Type: application/json") fun getMediaStaff(@Body request: QueryContainerBuilder?): Call<AniListContainer<ConnectionContainer<EdgeContainer<StaffEdge>>>> @POST("/") @GraphQuery("MediaSocial") @Headers("Content-Type: application/json") fun getMediaSocial(@Body request: QueryContainerBuilder?): Call<AniListContainer<PageContainer<FeedList>>> }
app/src/main/java/com/mxt/anitrend/model/api/retro/anilist/MediaModel.kt
2898785496
package com.eden.orchid.taxonomies.menus import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.options.annotations.StringDefault import com.eden.orchid.api.theme.menus.MenuItem import com.eden.orchid.api.theme.menus.OrchidMenuFactory import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.taxonomies.models.TaxonomiesModel @Description("Links to all the Taxonomy landing pages.", name = "All Taxonomies") class TaxonomiesMenuType : OrchidMenuFactory("taxonomies") { @Option @StringDefault("Taxonomies") @Description("The menu item title.") lateinit var title: String override fun getMenuItems( context: OrchidContext, page: OrchidPage ): List<MenuItem> { val model = context.resolve(TaxonomiesModel::class.java) val items = ArrayList<MenuItem>() model.taxonomies.values.forEach { items.add( MenuItem.Builder(context) .title(it.title) .page(it.archivePages.first()) .build() ) } return items } }
plugins/OrchidTaxonomies/src/main/kotlin/com/eden/orchid/taxonomies/menus/TaxonomiesMenuType.kt
3728084640
package org.worldcubeassociation.tnoodle.server.model.cache import kotlinx.atomicfu.atomic import kotlinx.coroutines.* import kotlinx.coroutines.channels.produce import org.worldcubeassociation.tnoodle.scrambles.Puzzle import java.util.concurrent.Executors import java.util.concurrent.ThreadFactory import kotlin.coroutines.CoroutineContext class CoroutineScrambleCacher(val puzzle: Puzzle, capacity: Int) : CoroutineScope { override val coroutineContext: CoroutineContext get() = JOB_CONTEXT @ExperimentalCoroutinesApi private val buffer = produce(capacity = capacity) { while (true) { send(puzzle.generateScramble()) .also { size += 1 } } } private val size = atomic(0) val available: Int get() = size.value suspend fun yieldScramble(): String = buffer.receive() .also { size -= 1 } fun getScramble(): String = runBlocking { yieldScramble() } companion object { private val DAEMON_FACTORY = ThreadFactory { Executors.defaultThreadFactory().newThread(it).apply { isDaemon = true } } private val JOB_CONTEXT = Executors.newFixedThreadPool(2, DAEMON_FACTORY).asCoroutineDispatcher() } }
tnoodle-server/src/main/kotlin/org/worldcubeassociation/tnoodle/server/model/cache/CoroutineScrambleCacher.kt
328964459
package com.habitrpg.android.habitica.models.inventory import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class Food : RealmObject(), Item { @PrimaryKey override var key: String = "" override var text: String = "" override var event: ItemEvent? = null var notes: String? = null override var value: Int = 0 var target: String? = null var article: String? = null var canDrop: Boolean? = null override val type: String get() = "food" }
Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/Food.kt
2841122902
/* * Copyright (C) 2016-2017, 2020 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.psi.impl.update.facility import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.intellij.lang.UpdateFacilitySpec import uk.co.reecedunn.intellij.plugin.intellij.lang.Version import uk.co.reecedunn.intellij.plugin.intellij.lang.VersionConformance import uk.co.reecedunn.intellij.plugin.xquery.ast.update.facility.UpdateFacilityDeleteExpr class UpdateFacilityDeleteExprPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), UpdateFacilityDeleteExpr, VersionConformance { override val expressionElement: PsiElement get() = this override val requiresConformance: List<Version> get() = listOf(UpdateFacilitySpec.REC_1_0_20110317) override val conformanceElement: PsiElement get() = firstChild }
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/update/facility/UpdateFacilityDeleteExprPsiImpl.kt
3314497356
package de.westnordost.streetcomplete.quests.sidewalk import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.widget.ImageView import android.widget.TextView import androidx.annotation.AnyThread import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment import de.westnordost.streetcomplete.quests.StreetSideRotater import de.westnordost.streetcomplete.view.ListAdapter import kotlinx.android.synthetic.main.quest_street_side_puzzle.* class AddSidewalkForm : AbstractQuestFormAnswerFragment<SidewalkAnswer>() { override val contentLayoutResId = R.layout.quest_street_side_puzzle override val contentPadding = false private var streetSideRotater: StreetSideRotater? = null private var leftSide: Sidewalk? = null private var rightSide: Sidewalk? = null // just a shortcut private val isLeftHandTraffic get() = countryInfo.isLeftHandTraffic override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState?.getString(SIDEWALK_RIGHT)?.let { rightSide = Sidewalk.valueOf(it) } savedInstanceState?.getString(SIDEWALK_LEFT)?.let { leftSide = Sidewalk.valueOf(it) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) puzzleView.listener = { isRight -> showSidewalkSelectionDialog(isRight) } streetSideRotater = StreetSideRotater(puzzleView, compassNeedle, elementGeometry) val defaultResId = if (isLeftHandTraffic) R.drawable.ic_sidewalk_unknown_l else R.drawable.ic_sidewalk_unknown puzzleView.setLeftSideImageResource(leftSide?.iconResId ?: defaultResId) puzzleView.setRightSideImageResource(rightSide?.iconResId ?: defaultResId) checkIsFormComplete() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) rightSide?.let { outState.putString(SIDEWALK_RIGHT, it.name) } leftSide?.let { outState.putString(SIDEWALK_LEFT, it.name) } } @AnyThread override fun onMapOrientation(rotation: Float, tilt: Float) { streetSideRotater?.onMapOrientation(rotation, tilt) } override fun onClickOk() { applyAnswer(SidewalkAnswer( left = leftSide == Sidewalk.YES, right = rightSide == Sidewalk.YES )) } override fun isFormComplete() = leftSide != null && rightSide != null private fun showSidewalkSelectionDialog(isRight: Boolean) { val recyclerView = RecyclerView(activity!!) recyclerView.layoutParams = RecyclerView.LayoutParams(MATCH_PARENT, MATCH_PARENT) recyclerView.layoutManager = GridLayoutManager(activity, 2) val alertDialog = AlertDialog.Builder(activity!!) .setTitle(R.string.quest_select_hint) .setView(recyclerView) .create() recyclerView.adapter = createAdapter(Sidewalk.values().toList()) { sidewalk -> alertDialog.dismiss() if (isRight) { puzzleView.replaceRightSideImageResource(sidewalk.puzzleResId) rightSide = sidewalk } else { puzzleView.replaceLeftSideImageResource(sidewalk.puzzleResId) leftSide = sidewalk } checkIsFormComplete() } alertDialog.show() } private fun createAdapter(items: List<Sidewalk>, callback: (Sidewalk) -> Unit) = object : ListAdapter<Sidewalk>(items) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = object : ListAdapter.ViewHolder<Sidewalk>( LayoutInflater.from(parent.context).inflate(R.layout.labeled_icon_button_cell, parent, false) ) { override fun onBind(with: Sidewalk) { val imageView = itemView.findViewById<ImageView>(R.id.imageView) val textView = itemView.findViewById<TextView>(R.id.textView) imageView.setImageDrawable(resources.getDrawable(with.iconResId)) textView.setText(with.nameResId) itemView.setOnClickListener { callback(with) } } } } private enum class Sidewalk(val iconResId: Int, val puzzleResId: Int, val nameResId: Int) { NO(R.drawable.ic_sidewalk_no, R.drawable.ic_sidewalk_puzzle_no, R.string.quest_sidewalk_value_no), YES(R.drawable.ic_sidewalk_yes, R.drawable.ic_sidewalk_puzzle_yes, R.string.quest_sidewalk_value_yes) } companion object { private const val SIDEWALK_LEFT = "sidewalk_left" private const val SIDEWALK_RIGHT = "sidewalk_right" } }
app/src/main/java/de/westnordost/streetcomplete/quests/sidewalk/AddSidewalkForm.kt
3146675306
package org.stepic.droid.testUtils import org.mockito.Mockito.mock import org.mockito.stubbing.OngoingStubbing import retrofit2.Call import retrofit2.Response import org.mockito.Mockito.`when` as on @JvmOverloads fun <T> useMockInsteadCall(callOngoingStubbing: OngoingStubbing<Call<T>>, responseBodyMock: T, isSuccess: Boolean = true) { val call: Call<T> = mock<Call<*>>(Call::class.java) as Call<T> val retrofitResponse = mock<Response<*>>(Response::class.java) as Response<T> callOngoingStubbing.thenReturn(call) on(call.execute()).thenReturn(retrofitResponse) on(retrofitResponse.body()).thenReturn(responseBodyMock) on(retrofitResponse.isSuccessful).thenReturn(isSuccess) }
app/src/test/java/org/stepic/droid/testUtils/ResponseGenerator.kt
2043601935
package org.granchi.whatnow.framework.dagger import dagger.Component import org.granchi.whatnow.DebugWhatNowApplication import javax.inject.Singleton /** * Dagger component for the debug build variant of the app. */ @Singleton @Component(modules = arrayOf(DebugWhatNowModule::class)) interface DebugWhatNowComponent : WhatNowComponent { fun inject(app: DebugWhatNowApplication) }
sample-app/src/debug/kotlin/org/granchi/whatnow/framework/dagger/DebugWhatNowComponent.kt
1790728851
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.android.ext.koin import android.app.Application import android.content.Context import org.koin.android.logger.AndroidLogger import org.koin.core.KoinApplication import org.koin.core.annotation.KoinInternalApi import org.koin.core.logger.Level import org.koin.core.registry.saveProperties import org.koin.dsl.bind import org.koin.dsl.binds import org.koin.dsl.module import java.util.* /** * Koin extensions for Android * * @author Arnaud Giuliani */ /** * Setup Android Logger for Koin * @param level */ @OptIn(KoinInternalApi::class) fun KoinApplication.androidLogger( level: Level = Level.INFO, ): KoinApplication { koin.setupLogger(AndroidLogger(level)) return this } /** * Add Context instance to Koin container * @param androidContext - Context */ fun KoinApplication.androidContext(androidContext: Context): KoinApplication { if (koin.logger.isAt(Level.INFO)) { koin.logger.info("[init] declare Android Context") } if (androidContext is Application) { koin.loadModules(listOf(module { single { androidContext } binds arrayOf(Context::class,Application::class) })) } else { koin.loadModules(listOf(module { single{ androidContext } })) } return this } /** * Load properties file from Assets * @param androidContext * @param koinPropertyFile */ @OptIn(KoinInternalApi::class) fun KoinApplication.androidFileProperties( koinPropertyFile: String = "koin.properties", ): KoinApplication { val koinProperties = Properties() val androidContext = koin.get<Context>() try { val hasFile = androidContext.assets?.list("")?.contains(koinPropertyFile) ?: false if (hasFile) { try { androidContext.assets.open(koinPropertyFile).use { koinProperties.load(it) } val nb = koin.propertyRegistry.saveProperties(koinProperties) if (koin.logger.isAt(Level.INFO)) { koin.logger.info("[Android-Properties] loaded $nb properties from assets/$koinPropertyFile") } } catch (e: Exception) { koin.logger.error("[Android-Properties] error for binding properties : $e") } } else { if (koin.logger.isAt(Level.INFO)) { koin.logger.info("[Android-Properties] no assets/$koinPropertyFile file to load") } } } catch (e: Exception) { koin.logger.error("[Android-Properties] error while loading properties from assets/$koinPropertyFile : $e") } return this }
android/koin-android/src/main/java/org/koin/android/ext/koin/KoinExt.kt
1809238669
package org.stepik.android.domain.course_calendar.repository import io.reactivex.Completable import io.reactivex.Single import org.stepik.android.domain.course_calendar.model.SectionDateEvent interface CourseCalendarRepository { fun getSectionDateEventsByIds(vararg ids: Long): Single<List<SectionDateEvent>> fun saveSectionDateEvents(events: List<SectionDateEvent>): Completable fun removeSectionDateEventsByIds(vararg ids: Long): Completable }
app/src/main/java/org/stepik/android/domain/course_calendar/repository/CourseCalendarRepository.kt
792195934
package app.test import app.user.User import org.springframework.data.repository.CrudRepository /** * Created by michal on 15/05/2017. */ interface TestRepository : CrudRepository<Test, Long> { fun findByTitle(titles: String): Test fun findByUser(user: User): MutableIterable<Test> fun findByUserId(userId:Long): MutableIterable<Test> }
backend/src/main/kotlin/app/test/TestRepository.kt
1114291382
package jp.keita.kagurazaka.rxproperty.sample.todo import jp.keita.kagurazaka.rxproperty.NoParameter import jp.keita.kagurazaka.rxproperty.RxCommand import jp.keita.kagurazaka.rxproperty.RxProperty import jp.keita.kagurazaka.rxproperty.sample.BR import jp.keita.kagurazaka.rxproperty.sample.R import jp.keita.kagurazaka.rxproperty.sample.ViewModelBase import jp.keita.kagurazaka.rxproperty.toRxCommand import me.tatarka.bindingcollectionadapter2.ItemBinding class TodoViewModel : ViewModelBase() { val todoList: TodoList = TodoList() val todoListItem: ItemBinding<TodoItemViewModel> = ItemBinding.of(BR.todoListItemVM, R.layout.item_todo) val viewModeIndex: RxProperty<Int> = RxProperty(0).asManaged() val inputTodoItem: RxProperty<TodoItemViewModel> = RxProperty(TodoItemViewModel()).asManaged() val addCommand: RxCommand<NoParameter> = inputTodoItem .switchMap { it.onHasErrorChanged } .map { !it } .toRxCommand<NoParameter>(false) .asManaged() val deleteDoneCommand: RxCommand<Any> = RxCommand() init { val updateTodoList: (Int) -> Unit = { val list = when (it) { 0 -> TodoRepository.all 1 -> TodoRepository.active 2 -> TodoRepository.done else -> throw IllegalStateException() } todoList.replace(list) } TodoRepository.onChanged .subscribe { updateTodoList(viewModeIndex.get()) } // Not smart :( .asManaged() viewModeIndex .subscribe { updateTodoList(it) } .asManaged() addCommand.subscribe { inputTodoItem.get().let { TodoRepository.store(it.model) it.dispose() inputTodoItem.set(TodoItemViewModel()) } }.asManaged() deleteDoneCommand.subscribe { TodoRepository.deleteDone() }.asManaged() } override fun dispose() { TodoRepository.clear() super.dispose() } }
sample/src/main/kotlin/jp/keita/kagurazaka/rxproperty/sample/todo/TodoViewModel.kt
2270853975
package iii_conventions import util.TODO class Invokable(var invocations: Int = 0) operator fun Invokable.invoke(): Invokable { invocations++ return this } fun Invokable.getNumberOfInvocations(): Int = invocations fun todoTask31(): Nothing = TODO( """ Task 31. Change class Invokable to count the number of invocations (round brackets). Uncomment the commented code - it should return 4. """, references = { invokable: Invokable -> }) fun task31(invokable: Invokable): Int { // todoTask31() return invokable()()()().getNumberOfInvocations() }
src/iii_conventions/_31_Invoke_.kt
2363834712
package eu.kanade.tachiyomi.ui.catalogue.browse import android.support.v7.widget.RecyclerView import android.view.Gravity import android.view.View import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.widget.FrameLayout import com.f2prateek.rx.preferences.Preference import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractFlexibleItem import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.widget.AutofitRecyclerView import kotlinx.android.synthetic.main.catalogue_grid_item.view.* class CatalogueItem(val manga: Manga, private val catalogueAsList: Preference<Boolean>) : AbstractFlexibleItem<CatalogueHolder>() { override fun getLayoutRes(): Int { return if (catalogueAsList.getOrDefault()) R.layout.catalogue_list_item else R.layout.catalogue_grid_item } override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): CatalogueHolder { val parent = adapter.recyclerView return if (parent is AutofitRecyclerView) { view.apply { card.layoutParams = FrameLayout.LayoutParams( MATCH_PARENT, parent.itemWidth / 3 * 4) gradient.layoutParams = FrameLayout.LayoutParams( MATCH_PARENT, parent.itemWidth / 3 * 4 / 2, Gravity.BOTTOM) } CatalogueGridHolder(view, adapter) } else { CatalogueListHolder(view, adapter) } } override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>, holder: CatalogueHolder, position: Int, payloads: List<Any?>?) { holder.onSetValues(manga) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other is CatalogueItem) { return manga.id!! == other.manga.id!! } return false } override fun hashCode(): Int { return manga.id!!.hashCode() } }
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CatalogueItem.kt
1412492054
/** * Copyright 2017 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.workspace.serialization import com.google.gson.* import com.savvasdalkitsis.gameframe.feature.composition.model.AvailablePorterDuffOperator import com.savvasdalkitsis.gameframe.feature.composition.model.PorterDuffOperator import java.lang.reflect.Type class PorterDuffAdapter : JsonSerializer<PorterDuffOperator>, JsonDeserializer<PorterDuffOperator> { override fun serialize(src: PorterDuffOperator, typeOfSrc: Type?, context: JsonSerializationContext?) = JsonPrimitive(AvailablePorterDuffOperator.from(src).name) override fun deserialize(json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext?) = AvailablePorterDuffOperator.fromName(json.asString) }
workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/serialization/PorterDuffAdapter.kt
506204542
package org.mtransit.parser.mt import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.mockito.junit.MockitoJUnitRunner import org.mtransit.parser.gtfs.data.GIDs @RunWith(MockitoJUnitRunner::class) class MDirectionSplitterTest { companion object { const val RID = 1L } private val t1 = GIDs.getInt("trip_1") private val t2 = GIDs.getInt("trip_2") private val t3 = GIDs.getInt("trip_3") private val t4 = GIDs.getInt("trip_4") private val t5 = GIDs.getInt("trip_5") private val t6 = GIDs.getInt("trip_6") private val t7 = GIDs.getInt("trip_7") private val t8 = GIDs.getInt("trip_8") private val t9 = GIDs.getInt("trip_9") private val s0 = GIDs.getInt("stop_00") private val s1 = GIDs.getInt("stop_01") private val s2 = GIDs.getInt("stop_02") private val s3 = GIDs.getInt("stop_03") private val s4 = GIDs.getInt("stop_04") private val s5 = GIDs.getInt("stop_05") private val s6 = GIDs.getInt("stop_06") private val s7 = GIDs.getInt("stop_07") private val s8 = GIDs.getInt("stop_08") private val s9 = GIDs.getInt("stop_09") private val s11 = GIDs.getInt("stop_11") private val s22 = GIDs.getInt("stop_22") @Test fun testSplitDirections_Simple_1() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4, s5), t2 to listOf(s0, s1, s2, s3, s4, s5) ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(1, result.size) } @Test fun testSplitDirections_Simple_90pt() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4, s5, s6, s7, s8, s9), t2 to listOf(s0, s1, s2, s3, s4, s5, s6, s7, s8, s11), ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(1, result.size) } @Test fun testSplitDirections_Simple_2Ways() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s11, s0, s1, s2, s3, s4, s22), t2 to listOf(s22, s5, s6, s7, s8, s9, s11) ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(2, result.size) } @Test fun testSplitDirections_Simple_2Ways_NotCircle() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s11, s0, s1, s2, s3, s4, s22), t2 to listOf(s22, s5, s6, s7, s8, s9) ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(2, result.size) } @Test fun testSplitDirections_OtherTripWith2StopsRightOrder() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4, s5), t2 to listOf(/**/s1, /**/ /**/s4/**/) ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(1, result.size) } @Test fun testSplitDirections_OtherTripWith3StopsRightOrder() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4, s5), t2 to listOf(s0, s1, /**/s3, /**/s5) ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(1, result.size) } @Test fun testSplitDirections_OtherTripWith2StopsWrongOrder() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4, s5), t2 to listOf(s5, s3, s1, s0) ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(2, result.size) } @Test fun testSplitDirections_OtherTripWith2StopsWrongOrderShort() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2), t2 to listOf(s2, s1, s0) ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(2, result.size) } @Test fun testSplitDirections_Complex2Directions() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4, s5), // new t2 to listOf(s0, s1, s2, s3, s4, s5), // exact match t3 to listOf(s5, s6, s7, s8, s9/**/), // new t4 to listOf(s5, s6, s7, s8, s9/**/), // exact match t5 to listOf(s0, s1, /**/s3, s4, s5), t6 to listOf(s0, s1 /**/), t7 to listOf(/**/ s6, s7, s8, s9), t8 to listOf(/**/s8, s9, s11), t9 to listOf(/**/s6, s7, s8, s9/**/), ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(2, result.size) } @Test fun testSplitDirections_ContinuationBefore() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s1, s2, s3, s4, s5, s6), t2 to listOf(s0, s1), ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(1, result.size) } @Test fun testSplitDirections_ContinuationAfter() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4, s5), t2 to listOf(s5, s6), ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(1, result.size) } @Test fun testSplitDirections_SignificantBetterMatch1() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4), t2 to listOf(s5, s6, s7, s8, s9), t3 to listOf(s1, s6, s7, s8, s9) ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(2, result.size) } @Test fun testSplitDirections_SignificantBetterMatch2() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s5, s6, s7, s8, s9), t2 to listOf(s0, s1, s2, s3, s4), t3 to listOf(s1, s6, s7, s8, s9) ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(2, result.size) } @Test fun testSplitDirections_Complex_Loops_Overlap() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4, s5, s6, s7, s8, s9), t2 to listOf(s5, s6, s7, s8, s9, s0, s1, s2, s3, s4), ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(1, result.size) } @Test fun testSplitDirections_Complex_Loops_Overlap_From_Middle() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4, s5, s6, s7, s8, s9), t2 to listOf(s5, s6, s7, s8, s9), ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(1, result.size) } @Test fun testSplitDirections_Complex_Loops_Overlap_Incomplete() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4, s5, s6, s7, s8, s9), t2 to listOf(s5, s6, s7, s8, s9, s0, s1), ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(1, result.size) } @Test fun testSplitDirections_Complex_Loops_Overlap_First_Middle_Last_Repeat() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s11, s0, s1, s2, s3, s4, s22, s5, s6, s7, s8, s9, s11), t2 to listOf(s22, s5, s6, s7, s8, s9, s11, s0, s1, s2, s3, s4, s22), ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert // FIXME later, split in to 2 trips (w/o loosing trips.txt#trip_id to link w/ other data) assertEquals(1, result.size) } @Test fun testSplitDirections_Almost_the_same_expect_1_stop() { // Arrange val gTripIdIntStopIdInts = listOf( t1 to listOf(s0, s1, s2, s3, s4, s11, s6, s7, s8, s9), t2 to listOf(s0, s1, s2, s3, s4, s22, s6, s7, s8, s9), ) // Act val result = MDirectionSplitter.splitDirections(RID, gTripIdIntStopIdInts) // Assert assertEquals(1, result.size) } }
src/test/java/org/mtransit/parser/mt/MDirectionSplitterTest.kt
2116813586
package me.liuqingwen.android.projectamap import android.content.Context import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.text.Editable import android.text.TextWatcher import android.view.View import android.view.WindowManager import android.view.inputmethod.InputMethodManager import android.widget.ArrayAdapter import com.amap.api.maps.AMap import com.amap.api.maps.CameraUpdateFactory import com.amap.api.maps.model.LatLng import com.amap.api.maps.model.LatLngBounds import com.amap.api.maps.model.MarkerOptions import com.amap.api.maps.model.MyLocationStyle import com.amap.api.services.core.LatLonPoint import com.amap.api.services.core.PoiItem import com.amap.api.services.help.Inputtips import com.amap.api.services.help.InputtipsQuery import com.amap.api.services.poisearch.PoiResult import com.amap.api.services.poisearch.PoiSearch import kotlinx.android.synthetic.main.layout_activity_main.* import org.jetbrains.anko.toast //Log:73-135, Lat:17-53 val LatLonPoint.latLon:LatLng get() { return LatLng(this.latitude, this.longitude) } const val CITY = "长沙" class MainActivity : AppCompatActivity() { private var isFullScreen = false private var isSearching = false private lateinit var map:AMap private val searchItems by lazy(LazyThreadSafetyMode.NONE) { arrayListOf<String>() } private val searchAdapter by lazy(LazyThreadSafetyMode.NONE) { ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, this.searchItems) } private var poiQuery:PoiSearch.Query? = null private val poiSearch by lazy(LazyThreadSafetyMode.NONE) { PoiSearch(this, this.poiQuery).apply { this.setOnPoiSearchListener([email protected]) } } private val searchListener = object : PoiSearch.OnPoiSearchListener { override fun onPoiItemSearched(item: PoiItem?, code: Int) { [email protected] = false } override fun onPoiSearched(result: PoiResult?, code: Int) { if (code == 1000 && result?.pois != null) { [email protected](result.pois) } else { [email protected]("Search failed!") } [email protected] = false } } private fun showResult(poiItems:List<PoiItem>) { this.map.clear() if (poiItems.isNotEmpty()) { poiItems.forEach { val info = "Lat:${it.latLonPoint.latitude}, Log:${it.latLonPoint.longitude}" val marker = this.map.addMarker(MarkerOptions().infoWindowEnable(true).snippet(info).position(it.latLonPoint.latLon).title(it.title)) marker.hideInfoWindow() } val longitude1 = poiItems.maxBy { it.latLonPoint.longitude }!!.latLonPoint.longitude val longitude2 = poiItems.minBy { it.latLonPoint.longitude }!!.latLonPoint.longitude val latitude1 = poiItems.maxBy { it.latLonPoint.latitude }!!.latLonPoint.latitude val latitude2 = poiItems.minBy { it.latLonPoint.latitude }!!.latLonPoint.latitude val bounds = LatLngBounds.builder().include(LatLng(latitude1, longitude1)).include(LatLng(latitude2, longitude2)).build() this.map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50)) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_activity_main) this.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN) this.mapView.onCreate(savedInstanceState) this.init() } private fun init() { this.isFullScreen = true this.supportActionBar?.hide() this.window.decorView.setOnSystemUiVisibilityChangeListener {visibility -> this.isFullScreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0 } this.switchMapType.setOnClickListener { this.map.mapType = if (this.switchMapType.isChecked) AMap.MAP_TYPE_NORMAL else AMap.MAP_TYPE_SATELLITE } this.buttonSearch.setOnClickListener { this.hideKeyboard() val text = this.textSearch.text.toString() this.searchMap(text) } this.textSearch.setAdapter(this.searchAdapter) this.textSearch.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) {} override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (s?.isNotBlank() == true && s.length >= 2) { [email protected](s.toString()) } } }) this.textSearch.setOnItemClickListener { _, _, _, _ -> this.hideKeyboard() this.searchMap(this.textSearch.text.toString()) } this.textSearch.setOnClickListener { this.textSearch.showDropDown() } this.config() } private fun queryInputTips(text:String) { val inputTipsQuery = InputtipsQuery(text, CITY) inputTipsQuery.cityLimit = true val inputTips = Inputtips(this, inputTipsQuery) inputTips.setInputtipsListener { list, code -> if (code == 1000 && list?.isNotEmpty() == true) { this.searchAdapter.clear() list.map { it.name }.let { this.searchAdapter.addAll(it) } this.searchAdapter.notifyDataSetChanged() } } inputTips.requestInputtipsAsyn() } private fun hideKeyboard() { this.currentFocus?.let { val inputManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManager.hideSoftInputFromWindow(it.windowToken, 0) } } private fun searchMap(searchText:String) { if (this.isSearching || searchText.isBlank()) { return } this.isSearching = true this.poiQuery = PoiSearch.Query(searchText, "", CITY) this.poiQuery?.pageSize = 10 this.poiQuery?.pageNum = 1 this.poiSearch.searchPOIAsyn() } private fun config() { this.map = this.mapView.map this.map.setOnMapLoadedListener { } this.map.setOnMapClickListener { if (! this.isFullScreen) { this.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN } } val myLocationStyle = MyLocationStyle().apply { this.interval(5000) this.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER) this.showMyLocation(true) } this.map.myLocationStyle = myLocationStyle this.map.isMyLocationEnabled = true this.map.setOnMyLocationChangeListener { if (it.latitude in 17.0..53.0 && it.longitude in 73.0..135.0) { this.map.moveCamera(CameraUpdateFactory.changeLatLng(LatLng(it.latitude, it.longitude))) } } this.map.uiSettings.isCompassEnabled = true this.map.uiSettings.isZoomControlsEnabled = true this.map.uiSettings.isMyLocationButtonEnabled = true /*this.map.setLocationSource(object : LocationSource{ override fun deactivate() { info("------------------>setLocationSource: deactivate") } override fun activate(p0: LocationSource.OnLocationChangedListener?) { info("------------------>setLocationSource: activate") } })*/ this.map.setOnMarkerClickListener { this.map.animateCamera(CameraUpdateFactory.newLatLngZoom(it.position, 17.0f)) it.showInfoWindow() false } } override fun onDestroy() { super.onDestroy() this.mapView.onDestroy() } override fun onResume() { super.onResume() this.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN this.hideKeyboard() this.mapView.onResume() } override fun onPause() { super.onPause() this.mapView.onPause() } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) this.mapView.onSaveInstanceState(outState) } }
ProjectAMap/app/src/main/java/me/liuqingwen/android/projectamap/MainActivity.kt
1347095856
/** * Copyright 2017 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.workspace.element.palette.view import android.content.Context import android.support.v7.app.AlertDialog import android.util.AttributeSet import android.view.LayoutInflater import android.view.ViewGroup import android.widget.EditText import android.widget.LinearLayout import com.savvasdalkitsis.gameframe.feature.workspace.R import com.savvasdalkitsis.gameframe.feature.workspace.element.palette.model.Palette import com.savvasdalkitsis.gameframe.feature.workspace.element.palette.model.PaletteSettings class PaletteSettingsView : LinearLayout { private lateinit var title: EditText constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun onFinishInflate() { super.onFinishInflate() title = findViewById(R.id.view_palette_title) } fun bindTo(palette: Palette) { title.setText(palette.title) } val paletteSettings: PaletteSettings get() = PaletteSettings(title = title.text.toString()) companion object { internal fun show(context: Context, palette: Palette, root: ViewGroup, paletteSettingsSetListener: PaletteSettingsSetListener) { val settingsView = LayoutInflater.from(context).inflate(R.layout.view_palette_settings, root, false) as PaletteSettingsView settingsView.bindTo(palette) AlertDialog.Builder(context, R.style.AppTheme_Dialog) .setTitle(R.string.palette_settings) .setView(settingsView) .setPositiveButton(android.R.string.ok) { _, _ -> paletteSettingsSetListener.onPaletteSettingsSet(settingsView.paletteSettings) } .setNegativeButton(android.R.string.cancel) { _, _ -> } .create() .show() } } }
workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/element/palette/view/PaletteSettingsView.kt
3297549927
/* * LogHelper.kt * Implements the LogHelper object * A LogHelper wraps the logging calls to be able to strip them out of release versions * * 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 */ package org.y20k.trackbook.helpers import android.util.Log import org.y20k.trackbook.BuildConfig /* * LogHelper object */ object LogHelper { private const val TESTING: Boolean = true // set to "false" private const val LOG_PREFIX: String = "trackbook_" private const val MAX_LOG_TAG_LENGTH: Int = 64 private const val LOG_PREFIX_LENGTH: Int = LOG_PREFIX.length fun makeLogTag(str: String): String { return if (str.length > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1) } else LOG_PREFIX + str } fun makeLogTag(cls: Class<*>): String { // don't use this when obfuscating class names return makeLogTag(cls.simpleName) } fun v(tag: String, vararg messages: Any) { // Only log VERBOSE if build type is DEBUG or if TESTING is true if (BuildConfig.DEBUG || TESTING) { log(tag, Log.VERBOSE, null, *messages) } } fun d(tag: String, vararg messages: Any) { // Only log DEBUG if build type is DEBUG or if TESTING is true if (BuildConfig.DEBUG || TESTING) { log(tag, Log.DEBUG, null, *messages) } } fun i(tag: String, vararg messages: Any) { log(tag, Log.INFO, null, *messages) } fun w(tag: String, vararg messages: Any) { log(tag, Log.WARN, null, *messages) } fun w(tag: String, t: Throwable, vararg messages: Any) { log(tag, Log.WARN, t, *messages) } fun e(tag: String, vararg messages: Any) { log(tag, Log.ERROR, null, *messages) } fun e(tag: String, t: Throwable, vararg messages: Any) { log(tag, Log.ERROR, t, *messages) } private fun log(tag: String, level: Int, t: Throwable?, vararg messages: Any) { val message: String if (t == null && messages.size == 1) { // handle this common case without the extra cost of creating a stringbuffer: message = messages[0].toString() } else { val sb = StringBuilder() for (m in messages) { sb.append(m) } if (t != null) { sb.append("\n").append(Log.getStackTraceString(t)) } message = sb.toString() } Log.println(level, tag, message) // if (Log.isLoggable(tag, level)) { // val message: String // if (t == null && messages != null && messages.size == 1) { // // handle this common case without the extra cost of creating a stringbuffer: // message = messages[0].toString() // } else { // val sb = StringBuilder() // if (messages != null) // for (m in messages) { // sb.append(m) // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)) // } // message = sb.toString() // } // Log.println(level, tag, message) // } } }
app/src/main/java/org/y20k/trackbook/helpers/LogHelper.kt
4192506275
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.appdistributioncodelab.kotlin import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.google.firebase.appdistribution.FirebaseAppDistribution import com.google.firebase.appdistribution.ktx.appDistribution import com.google.firebase.appdistributioncodelab.databinding.ActivityMainBinding import com.google.firebase.ktx.Firebase class MainActivity : AppCompatActivity() { private lateinit var firebaseAppDistribution: FirebaseAppDistribution private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) firebaseAppDistribution = Firebase.appDistribution binding.updatebutton.setOnClickListener { view -> checkForUpdate() } binding.signinButton.setOnClickListener { view -> signIn() } } private fun checkForUpdate() { } private fun signIn() { } private fun isTesterSignedIn() : Boolean { return false } private fun configureUpdateButton() { binding.updatebutton.visibility = if (isTesterSignedIn()) View.VISIBLE else View.GONE } private fun configureSigninButton() { binding.signinButton.text = if (isTesterSignedIn()) "Sign Out" else "Sign In" binding.signinButton.visibility = View.VISIBLE } companion object { private const val TAG = "AppDistribution-Codelab" } }
start/app/src/main/java/com/google/firebase/appdistributioncodelab/kotlin/MainActivity.kt
2241767916
package eu.kanade.tachiyomi.data.track.bangumi import kotlinx.serialization.Serializable @Serializable data class Collection( val `private`: Int? = 0, val comment: String? = "", val ep_status: Int? = 0, val lasttouch: Int? = 0, val rating: Float? = 0f, val status: Status? = Status(), val tag: List<String?>? = listOf(), val user: User? = User(), val vol_status: Int? = 0, )
app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/Collection.kt
1509540029
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus import org.apache.commons.codec.DecoderException import org.apache.commons.codec.binary.Hex import org.junit.Assert import org.junit.Test class AlarmStatusResponseTest { @Test @Throws(DecoderException::class) fun testValidResponse() { val encoded = Hex.decodeHex("021602080100000501BD00000003FF01950000000000670A") val response = AlarmStatusResponse(encoded) Assert.assertArrayEquals(encoded, response.encoded) Assert.assertNotSame(encoded, response.encoded) Assert.assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE, response.responseType) Assert.assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE.value, response.messageType) Assert.assertEquals(ResponseType.StatusResponseType.ALARM_STATUS, response.statusResponseType) Assert.assertEquals(ResponseType.StatusResponseType.ALARM_STATUS.value, response.additionalStatusResponseType) Assert.assertEquals(PodStatus.RUNNING_ABOVE_MIN_VOLUME, response.podStatus) Assert.assertEquals(DeliveryStatus.BASAL_ACTIVE, response.deliveryStatus) Assert.assertEquals(0.toShort(), response.bolusPulsesRemaining) Assert.assertEquals(5.toShort(), response.sequenceNumberOfLastProgrammingCommand) Assert.assertEquals(445.toShort(), response.totalPulsesDelivered) Assert.assertEquals(AlarmType.NONE, response.alarmType) Assert.assertEquals(0.toShort(), response.alarmTime) Assert.assertEquals(1023.toShort(), response.reservoirPulsesRemaining) Assert.assertEquals(405.toShort(), response.minutesSinceActivation) Assert.assertEquals(0, response.activeAlerts.size) Assert.assertFalse(response.occlusionAlarm) Assert.assertFalse(response.pulseInfoInvalid) Assert.assertEquals(PodStatus.UNINITIALIZED, response.podStatusWhenAlarmOccurred) Assert.assertFalse(response.immediateBolusWhenAlarmOccurred) Assert.assertEquals(0x00.toByte(), response.occlusionType) Assert.assertFalse(response.occurredWhenFetchingImmediateBolusActiveInformation) Assert.assertEquals(0.toShort(), response.rssi) Assert.assertEquals(0.toShort(), response.receiverLowerGain) Assert.assertEquals(PodStatus.UNINITIALIZED, response.podStatusWhenAlarmOccurred2) Assert.assertEquals(26378.toShort(), response.returnAddressOfPodAlarmHandlerCaller) } }
omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt
1412791583
package info.nightscout.androidaps.database.transactions import info.nightscout.androidaps.database.entities.TemporaryBasal /** * Creates or updates the TemporaryBasal from pump synchronization */ class SyncTemporaryBasalWithTempIdTransaction( private val bolus: TemporaryBasal, private val newType: TemporaryBasal.Type? ) : Transaction<SyncTemporaryBasalWithTempIdTransaction.TransactionResult>() { override fun run(): TransactionResult { bolus.interfaceIDs.temporaryId ?: bolus.interfaceIDs.pumpType ?: bolus.interfaceIDs.pumpSerial ?: throw IllegalStateException("Some pump ID is null") val result = TransactionResult() val current = database.temporaryBasalDao.findByPumpTempIds(bolus.interfaceIDs.temporaryId!!, bolus.interfaceIDs.pumpType!!, bolus.interfaceIDs.pumpSerial!!) if (current != null) { val old = current.copy() current.timestamp = bolus.timestamp current.rate = bolus.rate current.duration = bolus.duration current.isAbsolute = bolus.isAbsolute current.type = newType ?: current.type current.interfaceIDs.pumpId = bolus.interfaceIDs.pumpId database.temporaryBasalDao.updateExistingEntry(current) result.updated.add(Pair(old, current)) } return result } class TransactionResult { val updated = mutableListOf<Pair<TemporaryBasal, TemporaryBasal>>() } }
database/src/main/java/info/nightscout/androidaps/database/transactions/SyncTemporaryBasalWithTempIdTransaction.kt
2169727575
package com.rey.dependency import android.app.Application import dagger.Module import dagger.Provides import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Singleton /** * Created by Rey on 12/7/2015. */ @Module open class AppModule(private val application: Application) { @Provides @Singleton internal fun provideApplication(): Application = application @Provides @IOScheduler internal open fun provideIoScheduler(): Scheduler = Schedulers.io() @Provides @ComputationScheduler internal open fun provideComputationScheduler(): Scheduler = Schedulers.computation() @Provides @MainScheduler internal open fun provideMainScheduler(): Scheduler = AndroidSchedulers.mainThread() }
app/src/main/kotlin/com/rey/dependency/AppModule.kt
2694868848
package info.nightscout.androidaps.plugins.general.automation.actions import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.automation.elements.InputString import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.TimerUtil import info.nightscout.androidaps.interfaces.ResourceHelper import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers import org.mockito.Mock import org.mockito.Mockito.`when` class ActionAlarmTest : TestBase() { @Mock lateinit var rh: ResourceHelper @Mock lateinit var rxBus: RxBus @Mock lateinit var context: Context @Mock lateinit var timerUtil: TimerUtil @Mock lateinit var dateUtil: DateUtil private lateinit var sut: ActionAlarm var injector: HasAndroidInjector = HasAndroidInjector { AndroidInjector { if (it is ActionAlarm) { it.rh = rh it.rxBus = rxBus it.context = context it.timerUtil = timerUtil it.dateUtil = dateUtil } if (it is PumpEnactResult) { it.rh = rh } } } @Before fun setup() { `when`(rh.gs(R.string.ok)).thenReturn("OK") `when`(rh.gs(R.string.alarm)).thenReturn("Alarm") `when`(rh.gs(ArgumentMatchers.eq(R.string.alarm_message), ArgumentMatchers.anyString())).thenReturn("Alarm: %s") sut = ActionAlarm(injector) } @Test fun friendlyNameTest() { Assert.assertEquals(R.string.alarm, sut.friendlyName()) } @Test fun shortDescriptionTest() { sut.text = InputString("Asd") Assert.assertEquals("Alarm: %s", sut.shortDescription()) } @Test fun iconTest() { Assert.assertEquals(R.drawable.ic_access_alarm_24dp, sut.icon()) } @Test fun doActionTest() { sut.doAction(object : Callback() { override fun run() { Assert.assertTrue(result.success) } }) } @Test fun hasDialogTest() { Assert.assertTrue(sut.hasDialog()) } @Test fun toJSONTest() { sut.text = InputString("Asd") Assert.assertEquals("{\"data\":{\"text\":\"Asd\"},\"type\":\"info.nightscout.androidaps.plugins.general.automation.actions.ActionAlarm\"}", sut.toJSON()) } @Test fun fromJSONTest() { sut.text = InputString("Asd") sut.fromJSON("{\"text\":\"Asd\"}") Assert.assertEquals("Asd", sut.text.value) } }
automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt
1058886392
package venus.riscv.insts.dsl.formats class UTypeFormat(opcode: Int) : OpcodeFormat(opcode)
src/main/kotlin/venus/riscv/insts/dsl/formats/UTypeFormat.kt
4201660669
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption class DanaRSPacketHistoryTemporary( injector: HasAndroidInjector, from: Long = 0 ) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY aapsLogger.debug(LTag.PUMPCOMM, "New message") } override val friendlyName: String = "REVIEW__TEMPORARY" }
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryTemporary.kt
536046442
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.data.proto import arcs.core.data.Recipe.Handle import arcs.core.data.TypeVariable /** Converts [HandleProto.Fate] into [Handle.Fate]. */ fun HandleProto.Fate.decode() = when (this) { HandleProto.Fate.UNSPECIFIED -> throw IllegalArgumentException("HandleProto.Fate value not set.") HandleProto.Fate.CREATE -> Handle.Fate.CREATE HandleProto.Fate.USE -> Handle.Fate.USE HandleProto.Fate.MAP -> Handle.Fate.MAP HandleProto.Fate.COPY -> Handle.Fate.COPY HandleProto.Fate.JOIN -> Handle.Fate.JOIN HandleProto.Fate.UNRECOGNIZED -> throw IllegalArgumentException("Invalid HandleProto.Fate value.") } /** Converts [Handle.Fate] into [HandleProto.Fate] enum. */ fun Handle.Fate.encode(): HandleProto.Fate = when (this) { Handle.Fate.CREATE -> HandleProto.Fate.CREATE Handle.Fate.USE -> HandleProto.Fate.USE Handle.Fate.MAP -> HandleProto.Fate.MAP Handle.Fate.COPY -> HandleProto.Fate.COPY Handle.Fate.JOIN -> HandleProto.Fate.JOIN } /** * Converts [HandleProto] into [Handle]. * * If a type is not set in the [HandleProto], it is initialized to a newly created TypeVariable. * @param knownHandles is a map of [Handle]s used the the recipe level to decode associatedHandles. */ fun HandleProto.decode(knownHandles: Map<String, Handle> = emptyMap()) = Handle( name = name, id = id, fate = fate.decode(), tags = tagsList, storageKey = storageKey, type = if (hasType()) type.decode() else TypeVariable(name), annotations = annotationsList.map { it.decode() }, associatedHandles = associatedHandlesList.map { requireNotNull(knownHandles[it]) } ) /** Converts a [Handle] to a [HandleProto]. */ fun Handle.encode(): HandleProto { val builder = HandleProto.newBuilder() .setName(name) .setId(id) .setFate(fate.encode()) .addAllTags(tags) .setType(type.encode()) .addAllAnnotations(annotations.map { it.encode() }) .addAllAssociatedHandles(associatedHandles.map { it.name }) storageKey?.let { builder.setStorageKey(it) } return builder.build() }
java/arcs/core/data/proto/HandleProtoDecoder.kt
3171078524
package com.bajdcc.LALR1.interpret.test import com.bajdcc.LALR1.grammar.Grammar import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage import com.bajdcc.LALR1.grammar.runtime.RuntimeException import com.bajdcc.LALR1.interpret.Interpreter import com.bajdcc.LALR1.syntax.handler.SyntaxException import com.bajdcc.util.lexer.error.RegexException import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream object TestInterpret8 { @JvmStatic fun main(args: Array<String>) { try { val codes = arrayOf( "import \"sys.base\"; import \"sys.list\";\n" + "var a = [];\n" + "call g_array_add(a, 5);\n" + "call g_array_set(a, 0, 4);\n" + "call g_printn(call g_array_get(a, 0));\n" + "call g_array_remove(a, 0);\n" + "call g_array_add(a, 50);\n" + "call g_array_add(a, 100);\n" + "call g_array_set(a, 1, 400);\n" + "call g_printn(call g_array_get(a, 1));\n" + "call g_array_pop(a);\n" + "call g_array_pop(a);\n" + "call g_printn(call g_array_size(a));\n" + "\n" + "let a = {};\n" + "call g_map_put(a, \"x\", 5);\n" + "call g_map_put(a, \"y\", 10);\n" + "call g_map_put(a, \"x\", 50);\n" + "call g_printn(call g_map_size(a));\n" + "call g_printn(call g_map_get(a, \"x\"));\n" + "call g_printn(call g_map_get(a, \"y\"));\n" + "call g_printn(call g_map_contains(a, \"x\"));\n" + "call g_map_remove(a, \"x\");\n" + "call g_printn(call g_map_contains(a, \"x\"));\n" + "call g_printn(call g_map_size(a));\n" + "\n", "import \"sys.base\"; import \"sys.list\";\n" + "var create_node = func ~(data) {\n" + " var new_node = g_new_map;\n" + " call g_map_put(new_node, \"data\", data);\n" + " call g_map_put(new_node, \"prev\", g_null);\n" + " call g_map_put(new_node, \"next\", g_null);\n" + " return new_node;\n" + "};\n" + "var append = func ~(head, obj) {\n" + " var new_node = call create_node(obj);\n" + " call g_map_put(new_node, \"next\", head);\n" + " call g_map_put(head, \"prev\", new_node);\n" + " return new_node;" + "};\n" + "var head = call create_node(0);\n" + "foreach (var i : call g_range(1, 10)) {\n" + " let head = call append(head, i);\n" + "}\n" + "var p = head;\n" + "while (!call g_is_null(p)) {\n" + " call g_printn(call g_map_get(p, \"data\"));\n" + " let p = call g_map_get(p, \"next\");\n" + "}\n" + "\n") println(codes[codes.size - 1]) val interpreter = Interpreter() val grammar = Grammar(codes[codes.size - 1]) //System.out.println(grammar.toString()); val page = grammar.codePage //System.out.println(page.toString()); val baos = ByteArrayOutputStream() RuntimeCodePage.exportFromStream(page, baos) val bais = ByteArrayInputStream(baos.toByteArray()) interpreter.run("test_1", bais) } catch (e: RegexException) { System.err.println() System.err.println(e.position.toString() + "," + e.message) e.printStackTrace() } catch (e: SyntaxException) { System.err.println() System.err.println(e.position.toString() + "," + e.message + " " + e.info) e.printStackTrace() } catch (e: RuntimeException) { System.err.println() System.err.println(e.position.toString() + ": " + e.info) e.printStackTrace() } catch (e: Exception) { System.err.println() System.err.println(e.message) e.printStackTrace() } } }
src/main/kotlin/com/bajdcc/LALR1/interpret/test/TestInterpret8.kt
957440068
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.pullUp import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.impl.light.LightField import com.intellij.psi.search.GlobalSearchScope import com.intellij.refactoring.classMembers.MemberInfoBase import com.intellij.refactoring.memberPullUp.PullUpData import com.intellij.refactoring.memberPullUp.PullUpHelper import com.intellij.refactoring.util.RefactoringUtil import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.dropDefaultValue import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.core.setType import org.jetbrains.kotlin.idea.inspections.CONSTRUCTOR_VAL_VAR_MODIFIERS import org.jetbrains.kotlin.idea.refactoring.createJavaField import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary import org.jetbrains.kotlin.idea.refactoring.isAbstract import org.jetbrains.kotlin.idea.refactoring.isCompanionMemberOf import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper import org.jetbrains.kotlin.idea.refactoring.memberInfo.toKtDeclarationWrapperAware import org.jetbrains.kotlin.idea.refactoring.safeDelete.removeOverrideModifier import org.jetbrains.kotlin.idea.util.anonymousObjectSuperTypeOrNull import org.jetbrains.kotlin.idea.util.hasComments import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.Variance class KotlinPullUpHelper( private val javaData: PullUpData, private val data: KotlinPullUpData ) : PullUpHelper<MemberInfoBase<PsiMember>> { companion object { private val MODIFIERS_TO_LIFT_IN_SUPERCLASS = listOf(KtTokens.PRIVATE_KEYWORD) private val MODIFIERS_TO_LIFT_IN_INTERFACE = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.PROTECTED_KEYWORD, KtTokens.INTERNAL_KEYWORD) } private fun KtExpression.isMovable(): Boolean { return accept( object : KtVisitor<Boolean, Nothing?>() { override fun visitKtElement(element: KtElement, arg: Nothing?): Boolean { return element.allChildren.all { (it as? KtElement)?.accept(this, arg) ?: true } } override fun visitKtFile(file: KtFile, data: Nothing?) = false override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, arg: Nothing?): Boolean { val resolvedCall = expression.getResolvedCall(data.resolutionFacade.analyze(expression)) ?: return true val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression if (receiver != null && receiver !is KtThisExpression && receiver !is KtSuperExpression) return true var descriptor: DeclarationDescriptor = resolvedCall.resultingDescriptor if (descriptor is ConstructorDescriptor) { descriptor = descriptor.containingDeclaration } // todo: local functions if (descriptor is ValueParameterDescriptor) return true if (descriptor is ClassDescriptor && !descriptor.isInner) return true if (descriptor is MemberDescriptor) { if (descriptor.source.getPsi() in propertiesToMoveInitializers) return true descriptor = descriptor.containingDeclaration } return descriptor is PackageFragmentDescriptor || (descriptor is ClassDescriptor && DescriptorUtils.isSubclass(data.targetClassDescriptor, descriptor)) } }, null ) } private fun getCommonInitializer( currentInitializer: KtExpression?, scope: KtBlockExpression?, propertyDescriptor: PropertyDescriptor, elementsToRemove: MutableSet<KtElement> ): KtExpression? { if (scope == null) return currentInitializer var initializerCandidate: KtExpression? = null for (statement in scope.statements) { statement.asAssignment()?.let body@{ val lhs = KtPsiUtil.safeDeparenthesize(it.left ?: return@body) val receiver = (lhs as? KtQualifiedExpression)?.receiverExpression if (receiver != null && receiver !is KtThisExpression) return@body val resolvedCall = lhs.getResolvedCall(data.resolutionFacade.analyze(it)) ?: return@body if (resolvedCall.resultingDescriptor != propertyDescriptor) return@body if (initializerCandidate == null) { if (currentInitializer == null) { if (!statement.isMovable()) return null initializerCandidate = statement elementsToRemove.add(statement) } else { if (!KotlinPsiUnifier.DEFAULT.unify(statement, currentInitializer).isMatched) return null initializerCandidate = currentInitializer elementsToRemove.add(statement) } } else if (!KotlinPsiUnifier.DEFAULT.unify(statement, initializerCandidate).isMatched) return null } } return initializerCandidate } private data class InitializerInfo( val initializer: KtExpression?, val usedProperties: Set<KtProperty>, val usedParameters: Set<KtParameter>, val elementsToRemove: Set<KtElement> ) private fun getInitializerInfo( property: KtProperty, propertyDescriptor: PropertyDescriptor, targetConstructor: KtElement ): InitializerInfo? { val sourceConstructors = targetToSourceConstructors[targetConstructor] ?: return null val elementsToRemove = LinkedHashSet<KtElement>() val commonInitializer = sourceConstructors.fold(null as KtExpression?) { commonInitializer, constructor -> val body = (constructor as? KtSecondaryConstructor)?.bodyExpression getCommonInitializer(commonInitializer, body, propertyDescriptor, elementsToRemove) } if (commonInitializer == null) { elementsToRemove.clear() } val usedProperties = LinkedHashSet<KtProperty>() val usedParameters = LinkedHashSet<KtParameter>() val visitor = object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val context = data.resolutionFacade.analyze(expression) val resolvedCall = expression.getResolvedCall(context) ?: return val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression if (receiver != null && receiver !is KtThisExpression) return when (val target = (resolvedCall.resultingDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi()) { is KtParameter -> usedParameters.add(target) is KtProperty -> usedProperties.add(target) } } } commonInitializer?.accept(visitor) if (targetConstructor == ((data.targetClass as? KtClass)?.primaryConstructor ?: data.targetClass)) { property.initializer?.accept(visitor) } return InitializerInfo(commonInitializer, usedProperties, usedParameters, elementsToRemove) } private val propertiesToMoveInitializers = with(data) { membersToMove .filterIsInstance<KtProperty>() .filter { val descriptor = memberDescriptors[it] as? PropertyDescriptor descriptor != null && data.sourceClassContext[BindingContext.BACKING_FIELD_REQUIRED, descriptor] ?: false } } private val targetToSourceConstructors = LinkedHashMap<KtElement, MutableList<KtElement>>().let { result -> if (!data.isInterfaceTarget && data.targetClass is KtClass) { result[data.targetClass.primaryConstructor ?: data.targetClass] = ArrayList() data.sourceClass.accept( object : KtTreeVisitorVoid() { private fun processConstructorReference(expression: KtReferenceExpression, callingConstructorElement: KtElement) { val descriptor = data.resolutionFacade.analyze(expression)[BindingContext.REFERENCE_TARGET, expression] val constructorElement = (descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return if (constructorElement == data.targetClass || (constructorElement as? KtConstructor<*>)?.getContainingClassOrObject() == data.targetClass) { result.getOrPut(constructorElement as KtElement) { ArrayList() }.add(callingConstructorElement) } } override fun visitSuperTypeCallEntry(specifier: KtSuperTypeCallEntry) { val constructorRef = specifier.calleeExpression.constructorReferenceExpression ?: return val containingClass = specifier.getStrictParentOfType<KtClassOrObject>() ?: return val callingConstructorElement = containingClass.primaryConstructor ?: containingClass processConstructorReference(constructorRef, callingConstructorElement) } override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) { val constructorRef = constructor.getDelegationCall().calleeExpression ?: return processConstructorReference(constructorRef, constructor) } } ) } result } private val targetConstructorToPropertyInitializerInfoMap = LinkedHashMap<KtElement, Map<KtProperty, InitializerInfo>>().let { result -> for (targetConstructor in targetToSourceConstructors.keys) { val propertyToInitializerInfo = LinkedHashMap<KtProperty, InitializerInfo>() for (property in propertiesToMoveInitializers) { val propertyDescriptor = data.memberDescriptors[property] as? PropertyDescriptor ?: continue propertyToInitializerInfo[property] = getInitializerInfo(property, propertyDescriptor, targetConstructor) ?: continue } val unmovableProperties = RefactoringUtil.transitiveClosure( object : RefactoringUtil.Graph<KtProperty> { override fun getVertices() = propertyToInitializerInfo.keys override fun getTargets(source: KtProperty) = propertyToInitializerInfo[source]?.usedProperties } ) { !propertyToInitializerInfo.containsKey(it) } propertyToInitializerInfo.keys.removeAll(unmovableProperties) result[targetConstructor] = propertyToInitializerInfo } result } private var dummyField: PsiField? = null private fun addMovedMember(newMember: KtNamedDeclaration) { if (newMember is KtProperty) { // Add dummy light field since PullUpProcessor won't invoke moveFieldInitializations() if no PsiFields are present if (dummyField == null) { val factory = JavaPsiFacade.getElementFactory(newMember.project) val dummyField = object : LightField( newMember.manager, factory.createField("dummy", PsiType.BOOLEAN), factory.createClass("Dummy") ) { // Prevent processing by JavaPullUpHelper override fun getLanguage() = KotlinLanguage.INSTANCE } javaData.movedMembers.add(dummyField) } } when (newMember) { is KtProperty, is KtNamedFunction -> { newMember.getRepresentativeLightMethod()?.let { javaData.movedMembers.add(it) } } is KtClassOrObject -> { newMember.toLightClass()?.let { javaData.movedMembers.add(it) } } } } private fun liftVisibility(declaration: KtNamedDeclaration, ignoreUsages: Boolean = false) { val newModifier = if (data.isInterfaceTarget) KtTokens.PUBLIC_KEYWORD else KtTokens.PROTECTED_KEYWORD val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS val currentModifier = declaration.visibilityModifierTypeOrDefault() if (currentModifier !in modifiersToLift) return if (ignoreUsages || willBeUsedInSourceClass(declaration, data.sourceClass, data.membersToMove)) { if (newModifier != KtTokens.DEFAULT_VISIBILITY_KEYWORD) { declaration.addModifier(newModifier) } else { declaration.removeModifier(currentModifier) } } } override fun setCorrectVisibility(info: MemberInfoBase<PsiMember>) { val member = info.member.namedUnwrappedElement as? KtNamedDeclaration ?: return if (data.isInterfaceTarget) { member.removeModifier(KtTokens.PUBLIC_KEYWORD) } val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS if (member.visibilityModifierTypeOrDefault() in modifiersToLift) { member.accept( object : KtVisitorVoid() { override fun visitNamedDeclaration(declaration: KtNamedDeclaration) { when (declaration) { is KtClass -> { liftVisibility(declaration) declaration.declarations.forEach { it.accept(this) } } is KtNamedFunction, is KtProperty -> { liftVisibility(declaration, declaration == member && info.isToAbstract) } } } } ) } } override fun encodeContextInfo(info: MemberInfoBase<PsiMember>) { } private fun fixOverrideAndGetClashingSuper( sourceMember: KtCallableDeclaration, targetMember: KtCallableDeclaration ): KtCallableDeclaration? { val memberDescriptor = data.memberDescriptors[sourceMember] as CallableMemberDescriptor if (memberDescriptor.overriddenDescriptors.isEmpty()) { targetMember.removeOverrideModifier() return null } val clashingSuperDescriptor = data.getClashingMemberInTargetClass(memberDescriptor) ?: return null if (clashingSuperDescriptor.overriddenDescriptors.isEmpty()) { targetMember.removeOverrideModifier() } return clashingSuperDescriptor.source.getPsi() as? KtCallableDeclaration } private fun moveSuperInterface(member: PsiNamedElement, substitutor: PsiSubstitutor) { val realMemberPsi = (member as? KtPsiClassWrapper)?.psiClass ?: member val classDescriptor = data.memberDescriptors[member] as? ClassDescriptor ?: return val currentSpecifier = data.sourceClass.getSuperTypeEntryByDescriptor(classDescriptor, data.sourceClassContext) ?: return when (data.targetClass) { is KtClass -> { data.sourceClass.removeSuperTypeListEntry(currentSpecifier) addSuperTypeEntry( currentSpecifier, data.targetClass, data.targetClassDescriptor, data.sourceClassContext, data.sourceToTargetClassSubstitutor ) } is PsiClass -> { val elementFactory = JavaPsiFacade.getElementFactory(member.project) val sourcePsiClass = data.sourceClass.toLightClass() ?: return val superRef = sourcePsiClass.implementsList ?.referenceElements ?.firstOrNull { it.resolve()?.unwrapped == realMemberPsi } ?: return val superTypeForTarget = substitutor.substitute(elementFactory.createType(superRef)) data.sourceClass.removeSuperTypeListEntry(currentSpecifier) if (DescriptorUtils.isSubclass(data.targetClassDescriptor, classDescriptor)) return val refList = if (data.isInterfaceTarget) data.targetClass.extendsList else data.targetClass.implementsList refList?.add(elementFactory.createReferenceFromText(superTypeForTarget.canonicalText, null)) } } return } private fun removeOriginalMemberOrAddOverride(member: KtCallableDeclaration) { if (member.isAbstract()) { member.deleteWithCompanion() } else { member.addModifier(KtTokens.OVERRIDE_KEYWORD) KtTokens.VISIBILITY_MODIFIERS.types.forEach { member.removeModifier(it as KtModifierKeywordToken) } (member as? KtNamedFunction)?.valueParameters?.forEach { it.dropDefaultValue() } } } private fun moveToJavaClass(member: KtNamedDeclaration, substitutor: PsiSubstitutor) { if (!(data.targetClass is PsiClass && member.canMoveMemberToJavaClass(data.targetClass))) return // TODO: Drop after PsiTypes in light elements are properly generated if (member is KtCallableDeclaration && member.typeReference == null) { val returnType = (data.memberDescriptors[member] as CallableDescriptor).returnType returnType?.anonymousObjectSuperTypeOrNull()?.let { member.setType(it, false) } } val project = member.project val elementFactory = JavaPsiFacade.getElementFactory(project) val lightMethod = member.getRepresentativeLightMethod()!! val movedMember: PsiMember = when (member) { is KtProperty, is KtParameter -> { val newType = substitutor.substitute(lightMethod.returnType) val newField = createJavaField(member, data.targetClass) newField.typeElement?.replace(elementFactory.createTypeElement(newType)) if (member.isCompanionMemberOf(data.sourceClass)) { newField.modifierList?.setModifierProperty(PsiModifier.STATIC, true) } if (member is KtParameter) { (member.parent as? KtParameterList)?.removeParameter(member) } else { member.deleteWithCompanion() } newField } is KtNamedFunction -> { val newReturnType = substitutor.substitute(lightMethod.returnType) val newParameterTypes = lightMethod.parameterList.parameters.map { substitutor.substitute(it.type) } val objectType = PsiType.getJavaLangObject(PsiManager.getInstance(project), GlobalSearchScope.allScope(project)) val newTypeParameterBounds = lightMethod.typeParameters.map { it.superTypes.map { type -> substitutor.substitute(type) as? PsiClassType ?: objectType } } val newMethod = org.jetbrains.kotlin.idea.refactoring.createJavaMethod(member, data.targetClass) RefactoringUtil.makeMethodAbstract(data.targetClass, newMethod) newMethod.returnTypeElement?.replace(elementFactory.createTypeElement(newReturnType)) newMethod.parameterList.parameters.forEachIndexed { i, parameter -> parameter.typeElement?.replace(elementFactory.createTypeElement(newParameterTypes[i])) } newMethod.typeParameters.forEachIndexed { i, typeParameter -> typeParameter.extendsList.referenceElements.forEachIndexed { j, referenceElement -> referenceElement.replace(elementFactory.createReferenceElementByType(newTypeParameterBounds[i][j])) } } removeOriginalMemberOrAddOverride(member) if (!data.isInterfaceTarget && !data.targetClass.hasModifierProperty(PsiModifier.ABSTRACT)) { data.targetClass.modifierList?.setModifierProperty(PsiModifier.ABSTRACT, true) } newMethod } else -> return } JavaCodeStyleManager.getInstance(project).shortenClassReferences(movedMember) } override fun move(info: MemberInfoBase<PsiMember>, substitutor: PsiSubstitutor) { val member = info.member.toKtDeclarationWrapperAware() ?: return if ((member is KtClass || member is KtPsiClassWrapper) && info.overrides != null) { moveSuperInterface(member, substitutor) return } if (data.targetClass is PsiClass) { moveToJavaClass(member, substitutor) return } val markedElements = markElements(member, data.sourceClassContext, data.sourceClassDescriptor, data.targetClassDescriptor) val memberCopy = member.copy() as KtNamedDeclaration fun moveClassOrObject(member: KtClassOrObject, memberCopy: KtClassOrObject): KtClassOrObject { if (data.isInterfaceTarget) { memberCopy.removeModifier(KtTokens.INNER_KEYWORD) } val movedMember = addMemberToTarget(memberCopy, data.targetClass as KtClass) as KtClassOrObject member.deleteWithCompanion() return movedMember } fun moveCallableMember(member: KtCallableDeclaration, memberCopy: KtCallableDeclaration): KtCallableDeclaration { data.targetClass as KtClass val movedMember: KtCallableDeclaration val clashingSuper = fixOverrideAndGetClashingSuper(member, memberCopy) val psiFactory = KtPsiFactory(member) val originalIsAbstract = member.hasModifier(KtTokens.ABSTRACT_KEYWORD) val toAbstract = when { info.isToAbstract -> true !data.isInterfaceTarget -> false member is KtProperty -> member.mustBeAbstractInInterface() else -> false } val classToAddTo = if (member.isCompanionMemberOf(data.sourceClass)) data.targetClass.getOrCreateCompanionObject() else data.targetClass if (toAbstract) { if (!originalIsAbstract) { makeAbstract( memberCopy, data.memberDescriptors[member] as CallableMemberDescriptor, data.sourceToTargetClassSubstitutor, data.targetClass ) } movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo) if (member.typeReference == null) { movedMember.typeReference?.addToShorteningWaitSet() } if (movedMember.nextSibling.hasComments()) { movedMember.parent.addAfter(psiFactory.createNewLine(), movedMember) } removeOriginalMemberOrAddOverride(member) } else { movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo) if (member is KtParameter && movedMember is KtParameter) { member.valOrVarKeyword?.delete() CONSTRUCTOR_VAL_VAR_MODIFIERS.forEach { member.removeModifier(it) } val superEntry = data.superEntryForTargetClass val superResolvedCall = data.targetClassSuperResolvedCall if (superResolvedCall != null) { val superCall = if (superEntry !is KtSuperTypeCallEntry || superEntry.valueArgumentList == null) { superEntry!!.replaced(psiFactory.createSuperTypeCallEntry("${superEntry.text}()")) } else superEntry val argumentList = superCall.valueArgumentList!! val parameterIndex = movedMember.parameterIndex() val prevParameterDescriptor = superResolvedCall.resultingDescriptor.valueParameters.getOrNull(parameterIndex - 1) val prevArgument = superResolvedCall.valueArguments[prevParameterDescriptor]?.arguments?.singleOrNull() as? KtValueArgument val newArgumentName = if (prevArgument != null && prevArgument.isNamed()) Name.identifier(member.name!!) else null val newArgument = psiFactory.createArgument(psiFactory.createExpression(member.name!!), newArgumentName) if (prevArgument == null) { argumentList.addArgument(newArgument) } else { argumentList.addArgumentAfter(newArgument, prevArgument) } } } else { member.deleteWithCompanion() } } if (originalIsAbstract && data.isInterfaceTarget) { movedMember.removeModifier(KtTokens.ABSTRACT_KEYWORD) } if (movedMember.hasModifier(KtTokens.ABSTRACT_KEYWORD)) { data.targetClass.makeAbstract() } return movedMember } try { val movedMember = when (member) { is KtCallableDeclaration -> moveCallableMember(member, memberCopy as KtCallableDeclaration) is KtClassOrObject -> moveClassOrObject(member, memberCopy as KtClassOrObject) else -> return } movedMember.modifierList?.reformatted() applyMarking(movedMember, data.sourceToTargetClassSubstitutor, data.targetClassDescriptor) addMovedMember(movedMember) } finally { clearMarking(markedElements) } } override fun postProcessMember(member: PsiMember) { val declaration = member.unwrapped as? KtNamedDeclaration ?: return dropOverrideKeywordIfNecessary(declaration) } override fun moveFieldInitializations(movedFields: LinkedHashSet<PsiField>) { val psiFactory = KtPsiFactory(data.sourceClass) fun KtClassOrObject.getOrCreateClassInitializer(): KtAnonymousInitializer { getOrCreateBody().declarations.lastOrNull { it is KtAnonymousInitializer }?.let { return it as KtAnonymousInitializer } return addDeclaration(psiFactory.createAnonymousInitializer()) } fun KtElement.getConstructorBodyBlock(): KtBlockExpression? { return when (this) { is KtClassOrObject -> { getOrCreateClassInitializer().body } is KtPrimaryConstructor -> { getContainingClassOrObject().getOrCreateClassInitializer().body } is KtSecondaryConstructor -> { bodyExpression ?: add(psiFactory.createEmptyBody()) } else -> null } as? KtBlockExpression } fun KtClassOrObject.getDelegatorToSuperCall(): KtSuperTypeCallEntry? { return superTypeListEntries.singleOrNull { it is KtSuperTypeCallEntry } as? KtSuperTypeCallEntry } fun addUsedParameters(constructorElement: KtElement, info: InitializerInfo) { if (info.usedParameters.isEmpty()) return val constructor: KtConstructor<*> = when (constructorElement) { is KtConstructor<*> -> constructorElement is KtClass -> constructorElement.createPrimaryConstructorIfAbsent() else -> return } with(constructor.getValueParameterList()!!) { info.usedParameters.forEach { val newParameter = addParameter(it) val originalType = data.sourceClassContext[BindingContext.VALUE_PARAMETER, it]!!.type newParameter.setType( data.sourceToTargetClassSubstitutor.substitute(originalType, Variance.INVARIANT) ?: originalType, false ) newParameter.typeReference!!.addToShorteningWaitSet() } } targetToSourceConstructors[constructorElement]!!.forEach { val superCall: KtCallElement? = when (it) { is KtClassOrObject -> it.getDelegatorToSuperCall() is KtPrimaryConstructor -> it.getContainingClassOrObject().getDelegatorToSuperCall() is KtSecondaryConstructor -> { if (it.hasImplicitDelegationCall()) { it.replaceImplicitDelegationCallWithExplicit(false) } else { it.getDelegationCall() } } else -> null } superCall?.valueArgumentList?.let { args -> info.usedParameters.forEach { parameter -> args.addArgument(psiFactory.createArgument(psiFactory.createExpression(parameter.name ?: "_"))) } } } } for ((constructorElement, propertyToInitializerInfo) in targetConstructorToPropertyInitializerInfoMap.entries) { val properties = propertyToInitializerInfo.keys.sortedWith( Comparator { property1, property2 -> val info1 = propertyToInitializerInfo[property1]!! val info2 = propertyToInitializerInfo[property2]!! when { property2 in info1.usedProperties -> -1 property1 in info2.usedProperties -> 1 else -> 0 } } ) for (oldProperty in properties) { val info = propertyToInitializerInfo.getValue(oldProperty) addUsedParameters(constructorElement, info) info.initializer?.let { val body = constructorElement.getConstructorBodyBlock() body?.addAfter(it, body.statements.lastOrNull() ?: body.lBrace!!) } info.elementsToRemove.forEach { it.delete() } } } } override fun updateUsage(element: PsiElement) { } } internal fun KtNamedDeclaration.deleteWithCompanion() { val containingClass = this.containingClassOrObject if (containingClass is KtObjectDeclaration && containingClass.isCompanion() && containingClass.declarations.size == 1 && containingClass.getSuperTypeList() == null ) { containingClass.delete() } else { this.delete() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt
1258617849
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.api import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.helper.SearchOptions import java.util.* interface VimSearchHelper { fun findNextParagraph( editor: VimEditor, caret: VimCaret, count: Int, allowBlanks: Boolean, ): Int fun findNextSentenceStart( editor: VimEditor, caret: VimCaret, count: Int, countCurrent: Boolean, requireAll: Boolean, ): Int fun findSection( editor: VimEditor, caret: VimCaret, type: Char, dir: Int, count: Int, ): Int fun findNextCamelEnd( editor: VimEditor, caret: VimCaret, count: Int, ): Int fun findNextSentenceEnd( editor: VimEditor, caret: VimCaret, count: Int, countCurrent: Boolean, requireAll: Boolean, ): Int fun findNextCamelStart( editor: VimEditor, caret: VimCaret, count: Int, ): Int fun findMethodEnd( editor: VimEditor, caret: VimCaret, count: Int, ): Int fun findMethodStart( editor: VimEditor, caret: VimCaret, count: Int, ): Int fun findUnmatchedBlock( editor: VimEditor, caret: VimCaret, type: Char, count: Int, ): Int fun findNextWordEnd( editor: VimEditor, caret: VimCaret, count: Int, bigWord: Boolean, ): Int fun findNextWordEnd( chars: CharSequence, pos: Int, size: Int, count: Int, bigWord: Boolean, spaceWords: Boolean, ): Int fun findNextWord(editor: VimEditor, searchFrom: Int, count: Int, bigWord: Boolean): Long fun findPattern( editor: VimEditor, pattern: String?, startOffset: Int, count: Int, searchOptions: EnumSet<SearchOptions>?, ): TextRange? fun findNextCharacterOnLine( editor: VimEditor, caret: VimCaret, count: Int, ch: Char, ): Int fun findWordUnderCursor( editor: VimEditor, caret: VimCaret, count: Int, dir: Int, isOuter: Boolean, isBig: Boolean, hasSelection: Boolean, ): TextRange fun findSentenceRange( editor: VimEditor, caret: VimCaret, count: Int, isOuter: Boolean, ): TextRange fun findParagraphRange( editor: VimEditor, caret: VimCaret, count: Int, isOuter: Boolean, ): TextRange? fun findBlockTagRange( editor: VimEditor, caret: VimCaret, count: Int, isOuter: Boolean, ): TextRange? fun findBlockQuoteInLineRange( editor: VimEditor, caret: VimCaret, quote: Char, isOuter: Boolean, ): TextRange? fun findBlockRange( editor: VimEditor, caret: VimCaret, type: Char, count: Int, isOuter: Boolean, ): TextRange? }
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/VimSearchHelper.kt
2095546216
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.commands import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.ex.ExException import com.maddyhome.idea.vim.ex.ranges.Ranges import com.maddyhome.idea.vim.helper.Msg import com.maddyhome.idea.vim.option.ToggleOption import com.maddyhome.idea.vim.options.OptionScope import com.maddyhome.idea.vim.vimscript.model.ExecutionResult import java.util.* import kotlin.math.ceil import kotlin.math.min /** * see "h :set" */ data class SetCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges, argument) { override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, Access.READ_ONLY) override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult { val result = parseOptionLine(editor, argument, OptionScope.GLOBAL, failOnBad = true) return if (result) { ExecutionResult.Success } else { ExecutionResult.Error } } } data class SetLocalCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges, argument) { override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, Access.READ_ONLY) override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult { return if (parseOptionLine(editor, argument, OptionScope.LOCAL(editor), failOnBad = true)) { ExecutionResult.Success } else { ExecutionResult.Error } } } /** * This parses a set of :set commands. The following types of commands are supported: * * * :set - show all changed options * * :set all - show all options * * :set all& - reset all options to default values * * :set {option} - set option of boolean, display others * * :set {option}? - display option * * :set no{option} - reset boolean option * * :set inv{option} - toggle boolean option * * :set {option}! - toggle boolean option * * :set {option}& - set option to default * * :set {option}={value} - set option to new value * * :set {option}:{value} - set option to new value * * :set {option}+={value} - append or add to option value * * :set {option}-={value} - remove or subtract from option value * * :set {option}^={value} - prepend or multiply option value * * * @param editor The editor the command was entered for, null if no editor - reading .ideavimrc * @param args The :set command arguments * @param failOnBad True if processing should stop when a bad argument is found, false if a bad argument is simply * skipped and processing continues. * @return True if no errors were found, false if there were any errors */ // todo is failOnBad used anywhere? fun parseOptionLine(editor: VimEditor, args: String, scope: OptionScope, failOnBad: Boolean): Boolean { // No arguments so we show changed values val optionService = injector.optionService when { args.isEmpty() -> { val changedOptions = optionService.getOptions().filter { !optionService.isDefault(scope, it) } showOptions(editor, changedOptions.map { Pair(it, it) }, scope, true) return true } args == "all" -> { showOptions(editor, optionService.getOptions().map { Pair(it, it) }, scope, true) return true } args == "all&" -> { optionService.resetAllOptions() return true } } // We now have 1 or more option operators separator by spaces var error: String? = null var token = "" val tokenizer = StringTokenizer(args) val toShow = mutableListOf<Pair<String, String>>() while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken() // See if a space has been backslashed, if no get the rest of the text while (token.endsWith("\\")) { token = token.substring(0, token.length - 1) + ' ' if (tokenizer.hasMoreTokens()) { token += tokenizer.nextToken() } } when { token.endsWith("?") -> toShow.add(Pair(token.dropLast(1), token)) token.startsWith("no") -> optionService.unsetOption(scope, token.substring(2), token) token.startsWith("inv") -> optionService.toggleOption(scope, token.substring(3), token) token.endsWith("!") -> optionService.toggleOption(scope, token.dropLast(1), token) token.endsWith("&") -> optionService.resetDefault(scope, token.dropLast(1), token) else -> { // This must be one of =, :, +=, -=, or ^= // Look for the = or : first var eq = token.indexOf('=') if (eq == -1) { eq = token.indexOf(':') } // No operator so only the option name was given if (eq == -1) { val option = optionService.getOptionByNameOrAbbr(token) when (option) { null -> error = Msg.unkopt is ToggleOption -> optionService.setOption(scope, token, token) else -> toShow.add(Pair(option.name, option.abbrev)) } } else { // Make sure there is an option name if (eq > 0) { // See if an operator before the equal sign val op = token[eq - 1] var end = eq if (op in "+-^") { end-- } // Get option name and value after operator val option = token.take(end) val value = token.substring(eq + 1) when (op) { '+' -> optionService.appendValue(scope, option, value, token) '-' -> optionService.removeValue(scope, option, value, token) '^' -> optionService.prependValue(scope, option, value, token) else -> optionService.setOptionValue(scope, option, value, token) } } else { error = Msg.unkopt } } } } if (failOnBad && error != null) { break } } // Now show all options that were individually requested if (toShow.size > 0) { showOptions(editor, toShow, scope, false) } if (error != null) { throw ExException(injector.messages.message(error, token)) } return true } private fun showOptions(editor: VimEditor, nameAndToken: Collection<Pair<String, String>>, scope: OptionScope, showIntro: Boolean) { val optionService = injector.optionService val optionsToShow = mutableListOf<String>() var unknownOption: Pair<String, String>? = null for (pair in nameAndToken) { val myOption = optionService.getOptionByNameOrAbbr(pair.first) if (myOption != null) { optionsToShow.add(myOption.name) } else { unknownOption = pair break } } val cols = mutableListOf<String>() val extra = mutableListOf<String>() for (option in optionsToShow) { val optionAsString = optionToString(scope, option) if (optionAsString.length > 19) extra.add(optionAsString) else cols.add(optionAsString) } cols.sort() extra.sort() var width = injector.engineEditorHelper.getApproximateScreenWidth(editor) if (width < 20) { width = 80 } val colCount = width / 20 val height = ceil(cols.size.toDouble() / colCount.toDouble()).toInt() var empty = cols.size % colCount empty = if (empty == 0) colCount else empty val res = StringBuilder() if (showIntro) { res.append("--- Options ---\n") } for (h in 0 until height) { for (c in 0 until colCount) { if (h == height - 1 && c >= empty) { break } var pos = c * height + h if (c > empty) { pos -= c - empty } val opt = cols[pos] res.append(opt.padEnd(20)) } res.append("\n") } for (opt in extra) { val seg = (opt.length - 1) / width for (j in 0..seg) { res.append(opt, j * width, min(j * width + width, opt.length)) res.append("\n") } } injector.exOutputPanel.getPanel(editor).output(res.toString()) if (unknownOption != null) { throw ExException("E518: Unknown option: ${unknownOption.second}") } } private fun optionToString(scope: OptionScope, name: String): String { val value = injector.optionService.getOptionValue(scope, name) return if (injector.optionService.isToggleOption(name)) { if (value.asBoolean()) " $name" else "no$name" } else { "$name=$value" } }
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/SetCommand.kt
1779032662
package org.wordpress.android.viewmodel.activitylog import androidx.annotation.VisibleForTesting import androidx.core.util.Pair import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.collect import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import org.wordpress.android.R import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.activity.ActivityTypeModel import org.wordpress.android.fluxc.store.ActivityLogStore import org.wordpress.android.fluxc.store.ActivityLogStore.OnActivityLogFetched import org.wordpress.android.ui.activitylog.ActivityLogNavigationEvents import org.wordpress.android.ui.activitylog.list.ActivityLogListItem import org.wordpress.android.ui.jetpack.JetpackCapabilitiesUseCase import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState import org.wordpress.android.ui.jetpack.backup.download.usecases.GetBackupDownloadStatusUseCase import org.wordpress.android.ui.jetpack.backup.download.usecases.PostDismissBackupDownloadUseCase import org.wordpress.android.ui.jetpack.common.JetpackBackupDownloadActionState.PROGRESS import org.wordpress.android.ui.jetpack.restore.RestoreRequestState import org.wordpress.android.ui.jetpack.restore.usecases.GetRestoreStatusUseCase import org.wordpress.android.ui.stats.refresh.utils.StatsDateUtils import org.wordpress.android.ui.utils.UiString import org.wordpress.android.ui.utils.UiString.UiStringRes import org.wordpress.android.ui.utils.UiString.UiStringResWithParams import org.wordpress.android.ui.utils.UiString.UiStringText import org.wordpress.android.util.AppLog import org.wordpress.android.util.analytics.ActivityLogTracker import org.wordpress.android.util.extensions.toFormattedDateString import org.wordpress.android.util.extensions.toFormattedTimeString import org.wordpress.android.viewmodel.Event import org.wordpress.android.viewmodel.ResourceProvider import org.wordpress.android.viewmodel.SingleLiveEvent import org.wordpress.android.viewmodel.activitylog.ActivityLogViewModel.FiltersUiState.FiltersHidden import org.wordpress.android.viewmodel.activitylog.ActivityLogViewModel.FiltersUiState.FiltersShown import java.util.Date import javax.inject.Inject const val ACTIVITY_LOG_REWINDABLE_ONLY_KEY = "activity_log_rewindable_only" private const val DAY_IN_MILLIS = 1000 * 60 * 60 * 24 private const val ONE_SECOND_IN_MILLIS = 1000 private const val TIMEZONE_GMT_0 = "GMT+0" typealias DateRange = Pair<Long, Long> /** * It was decided to reuse the 'Activity Log' screen instead of creating a new 'Backup' screen. This was due to the * fact that there will be lots of code that would need to be duplicated for the new 'Backup' screen. On the other * hand, not much more complexity would be introduced if the 'Activity Log' screen is reused (mainly some 'if/else' * code branches here and there). * * However, should more 'Backup' related additions are added to the 'Activity Log' screen, then it should become a * necessity to split those features in separate screens in order not to increase further the complexity of this * screen's architecture. */ @Suppress("LargeClass") class ActivityLogViewModel @Inject constructor( private val activityLogStore: ActivityLogStore, private val getRestoreStatusUseCase: GetRestoreStatusUseCase, private val getBackupDownloadStatusUseCase: GetBackupDownloadStatusUseCase, private val postDismissBackupDownloadUseCase: PostDismissBackupDownloadUseCase, private val resourceProvider: ResourceProvider, private val statsDateUtils: StatsDateUtils, private val activityLogTracker: ActivityLogTracker, private val jetpackCapabilitiesUseCase: JetpackCapabilitiesUseCase ) : ViewModel() { enum class ActivityLogListStatus { CAN_LOAD_MORE, DONE, ERROR, FETCHING, LOADING_MORE } private var isStarted = false private val _events = MutableLiveData<List<ActivityLogListItem>>() val events: LiveData<List<ActivityLogListItem>> get() = _events private val _eventListStatus = MutableLiveData<ActivityLogListStatus>() val eventListStatus: LiveData<ActivityLogListStatus> get() = _eventListStatus private val _filtersUiState = MutableLiveData<FiltersUiState>(FiltersHidden) val filtersUiState: LiveData<FiltersUiState> get() = _filtersUiState private val _emptyUiState = MutableLiveData<EmptyUiState>(EmptyUiState.ActivityLog.EmptyFilters) val emptyUiState: LiveData<EmptyUiState> = _emptyUiState private val _showActivityTypeFilterDialog = SingleLiveEvent<ShowActivityTypePicker>() val showActivityTypeFilterDialog: LiveData<ShowActivityTypePicker> get() = _showActivityTypeFilterDialog private val _showDateRangePicker = SingleLiveEvent<ShowDateRangePicker>() val showDateRangePicker: LiveData<ShowDateRangePicker> get() = _showDateRangePicker private val _moveToTop = SingleLiveEvent<Unit>() val moveToTop: SingleLiveEvent<Unit> get() = _moveToTop private val _showItemDetail = SingleLiveEvent<ActivityLogListItem>() val showItemDetail: LiveData<ActivityLogListItem> get() = _showItemDetail private val _showSnackbarMessage = SingleLiveEvent<String>() val showSnackbarMessage: LiveData<String> get() = _showSnackbarMessage private val _navigationEvents = MutableLiveData<Event<ActivityLogNavigationEvents>>() val navigationEvents: LiveData<Event<ActivityLogNavigationEvents>> get() = _navigationEvents private val isRestoreProgressItemShown: Boolean get() = events.value?.find { it is ActivityLogListItem.Progress && it.progressType == ActivityLogListItem.Progress.Type.RESTORE } != null private val isBackupDownloadProgressItemShown: Boolean get() = events.value?.find { it is ActivityLogListItem.Progress && it.progressType == ActivityLogListItem.Progress.Type.BACKUP_DOWNLOAD } != null private val isDone: Boolean get() = eventListStatus.value == ActivityLogListStatus.DONE private var fetchActivitiesJob: Job? = null private var restoreStatusJob: Job? = null private var backupDownloadStatusJob: Job? = null private var currentDateRangeFilter: DateRange? = null private var currentActivityTypeFilter: List<ActivityTypeModel> = listOf() lateinit var site: SiteModel var rewindableOnly: Boolean = false private var currentRestoreEvent = RestoreEvent(false) private var currentBackupDownloadEvent = BackupDownloadEvent(displayProgress = false, displayNotice = false) fun start(site: SiteModel, rewindableOnly: Boolean) { if (isStarted) { return } isStarted = true this.site = site this.rewindableOnly = rewindableOnly reloadEvents(true) requestEventsUpdate(false) showFiltersIfSupported() } @Suppress("LongMethod", "ComplexMethod") @VisibleForTesting fun reloadEvents( done: Boolean = isDone, restoreEvent: RestoreEvent = currentRestoreEvent, backupDownloadEvent: BackupDownloadEvent = currentBackupDownloadEvent ) { currentRestoreEvent = restoreEvent currentBackupDownloadEvent = backupDownloadEvent val eventList = activityLogStore.getActivityLogForSite( site = site, ascending = false, rewindableOnly = rewindableOnly ) val items = mutableListOf<ActivityLogListItem>() var moveToTop = false val withRestoreProgressItem = restoreEvent.displayProgress && !restoreEvent.isCompleted val withBackupDownloadProgressItem = backupDownloadEvent.displayProgress && !backupDownloadEvent.isCompleted val withBackupDownloadNoticeItem = backupDownloadEvent.displayNotice if (withRestoreProgressItem || withBackupDownloadProgressItem) { items.add(ActivityLogListItem.Header(resourceProvider.getString(R.string.now))) moveToTop = eventListStatus.value != ActivityLogListStatus.LOADING_MORE } if (withRestoreProgressItem) { items.add(getRestoreProgressItem(restoreEvent.rewindId, restoreEvent.published)) } if (withBackupDownloadProgressItem) { items.add(getBackupDownloadProgressItem(backupDownloadEvent.rewindId, backupDownloadEvent.published)) } if (withBackupDownloadNoticeItem) { getBackupDownloadNoticeItem(backupDownloadEvent)?.let { items.add(it) moveToTop = true } } eventList.forEach { model -> val currentItem = ActivityLogListItem.Event( model = model, rewindDisabled = withRestoreProgressItem || withBackupDownloadProgressItem, isRestoreHidden = restoreEvent.isRestoreHidden ) val lastItem = items.lastOrNull() as? ActivityLogListItem.Event if (lastItem == null || lastItem.formattedDate != currentItem.formattedDate) { items.add(ActivityLogListItem.Header(currentItem.formattedDate)) } items.add(currentItem) } if (eventList.isNotEmpty() && !done) { items.add(ActivityLogListItem.Loading) } if (eventList.isNotEmpty() && site.hasFreePlan && done) { items.add(ActivityLogListItem.Footer) } _events.value = items if (moveToTop) { _moveToTop.call() } if (restoreEvent.isCompleted) { showRestoreFinishedMessage(restoreEvent.rewindId, restoreEvent.published) currentRestoreEvent = RestoreEvent(false) } } private fun getRestoreProgressItem(rewindId: String?, published: Date?): ActivityLogListItem.Progress { val rewindDate = published ?: rewindId?.let { activityLogStore.getActivityLogItemByRewindId(it)?.published } return rewindDate?.let { ActivityLogListItem.Progress( resourceProvider.getString(R.string.activity_log_currently_restoring_title), resourceProvider.getString( R.string.activity_log_currently_restoring_message, rewindDate.toFormattedDateString(), rewindDate.toFormattedTimeString() ), ActivityLogListItem.Progress.Type.RESTORE ) } ?: ActivityLogListItem.Progress( resourceProvider.getString(R.string.activity_log_currently_restoring_title), resourceProvider.getString(R.string.activity_log_currently_restoring_message_no_dates), ActivityLogListItem.Progress.Type.RESTORE ) } private fun getBackupDownloadProgressItem(rewindId: String?, published: Date?): ActivityLogListItem.Progress { val rewindDate = published ?: rewindId?.let { activityLogStore.getActivityLogItemByRewindId(it)?.published } return rewindDate?.let { ActivityLogListItem.Progress( resourceProvider.getString(R.string.activity_log_currently_backing_up_title), resourceProvider.getString( R.string.activity_log_currently_backing_up_message, rewindDate.toFormattedDateString(), rewindDate.toFormattedTimeString() ), ActivityLogListItem.Progress.Type.BACKUP_DOWNLOAD ) } ?: ActivityLogListItem.Progress( resourceProvider.getString(R.string.activity_log_currently_backing_up_title), resourceProvider.getString(R.string.activity_log_currently_backing_up_message_no_dates), ActivityLogListItem.Progress.Type.BACKUP_DOWNLOAD ) } private fun getBackupDownloadNoticeItem(backupDownloadEvent: BackupDownloadEvent): ActivityLogListItem.Notice? { val rewindDate = backupDownloadEvent.published ?: backupDownloadEvent.rewindId?.let { activityLogStore.getActivityLogItemByRewindId(it)?.published } return rewindDate?.let { ActivityLogListItem.Notice( label = resourceProvider.getString( R.string.activity_log_backup_download_notice_description_with_two_params, rewindDate.toFormattedDateString(), rewindDate.toFormattedTimeString() ), primaryAction = { onDownloadBackupFileClicked(backupDownloadEvent.url as String) }, secondaryAction = { dismissNoticeClicked(backupDownloadEvent.downloadId as Long) } ) } } private fun showRestoreFinishedMessage(rewindId: String?, published: Date?) { val rewindDate = published ?: rewindId?.let { activityLogStore.getActivityLogItemByRewindId(it)?.published } if (rewindDate != null) { _showSnackbarMessage.value = resourceProvider.getString( R.string.activity_log_rewind_finished_snackbar_message, rewindDate.toFormattedDateString(), rewindDate.toFormattedTimeString() ) } else { _showSnackbarMessage.value = resourceProvider.getString(R.string.activity_log_rewind_finished_snackbar_message_no_dates) } } private fun showBackupDownloadFinishedMessage(rewindId: String?) { val rewindDate = rewindId?.let { activityLogStore.getActivityLogItemByRewindId(it)?.published } if (rewindDate != null) { _showSnackbarMessage.value = resourceProvider.getString( R.string.activity_log_backup_finished_snackbar_message, rewindDate.toFormattedDateString(), rewindDate.toFormattedTimeString() ) } else { _showSnackbarMessage.value = resourceProvider.getString(R.string.activity_log_backup_finished_snackbar_message_no_dates) } } private fun requestEventsUpdate( loadMore: Boolean, restoreEvent: RestoreEvent = currentRestoreEvent, backupDownloadEvent: BackupDownloadEvent = currentBackupDownloadEvent ) { val isLoadingMore = fetchActivitiesJob != null && eventListStatus.value == ActivityLogListStatus.LOADING_MORE val canLoadMore = eventListStatus.value == ActivityLogListStatus.CAN_LOAD_MORE if (loadMore && (isLoadingMore || !canLoadMore)) { // Ignore loadMore request when already loading more items or there are no more items to load return } fetchActivitiesJob?.cancel() val newStatus = if (loadMore) ActivityLogListStatus.LOADING_MORE else ActivityLogListStatus.FETCHING _eventListStatus.value = newStatus val payload = ActivityLogStore.FetchActivityLogPayload( site, loadMore, currentDateRangeFilter?.first?.let { Date(it) }, currentDateRangeFilter?.second?.let { Date(it) }, currentActivityTypeFilter.map { it.key } ) fetchActivitiesJob = viewModelScope.launch { val result = activityLogStore.fetchActivities(payload) if (isActive) { onActivityLogFetched(result, loadMore, restoreEvent, backupDownloadEvent) fetchActivitiesJob = null } } } private fun onActivityLogFetched( event: OnActivityLogFetched, loadingMore: Boolean, restoreEvent: RestoreEvent, backupDownloadEvent: BackupDownloadEvent ) { if (event.isError) { _eventListStatus.value = ActivityLogListStatus.ERROR AppLog.e(AppLog.T.ACTIVITY_LOG, "An error occurred while fetching the Activity log events") return } if (event.rowsAffected > 0) { reloadEvents( done = !event.canLoadMore, restoreEvent = restoreEvent, backupDownloadEvent = backupDownloadEvent ) if (!loadingMore) { moveToTop.call() } if (!restoreEvent.isCompleted) queryRestoreStatus() if (!backupDownloadEvent.isCompleted) queryBackupDownloadStatus() } if (event.canLoadMore) { _eventListStatus.value = ActivityLogListStatus.CAN_LOAD_MORE } else { _eventListStatus.value = ActivityLogListStatus.DONE } } private fun showFiltersIfSupported() { when { !site.hasFreePlan -> refreshFiltersUiState() else -> { viewModelScope.launch { val purchasedProducts = jetpackCapabilitiesUseCase.getCachedJetpackPurchasedProducts(site.siteId) if (purchasedProducts.backup) { refreshFiltersUiState() } } } } } override fun onCleared() { if (currentDateRangeFilter != null || currentActivityTypeFilter.isNotEmpty()) { /** * Clear cache when filters are not empty. Filters are not retained across sessions, therefore the data is * not relevant when the screen is accessed next time. */ activityLogStore.clearActivityLogCache(site) } jetpackCapabilitiesUseCase.clear() super.onCleared() } private fun refreshFiltersUiState() { val (activityTypeLabel, activityTypeLabelContentDescription) = createActivityTypeFilterLabel() val (dateRangeLabel, dateRangeLabelContentDescription) = createDateRangeFilterLabel() _filtersUiState.value = FiltersShown( dateRangeLabel, dateRangeLabelContentDescription, activityTypeLabel, activityTypeLabelContentDescription, currentDateRangeFilter?.let { ::onClearDateRangeFilterClicked }, currentActivityTypeFilter.takeIf { it.isNotEmpty() }?.let { ::onClearActivityTypeFilterClicked } ) refreshEmptyUiState() } private fun refreshEmptyUiState() { if (rewindableOnly) { refreshBackupEmptyUiState() } else { refreshActivityLogEmptyUiState() } } private fun refreshBackupEmptyUiState() { if (currentDateRangeFilter != null) { _emptyUiState.value = EmptyUiState.Backup.ActiveFilters } else { _emptyUiState.value = EmptyUiState.Backup.EmptyFilters } } private fun refreshActivityLogEmptyUiState() { if (currentDateRangeFilter != null || currentActivityTypeFilter.isNotEmpty()) { _emptyUiState.value = EmptyUiState.ActivityLog.ActiveFilters } else { _emptyUiState.value = EmptyUiState.ActivityLog.EmptyFilters } } private fun createDateRangeFilterLabel(): kotlin.Pair<UiString, UiString> { return currentDateRangeFilter?.let { val label = UiStringText( statsDateUtils.formatDateRange(requireNotNull(it.first), requireNotNull(it.second), TIMEZONE_GMT_0) ) kotlin.Pair(label, label) } ?: kotlin.Pair( UiStringRes(R.string.activity_log_date_range_filter_label), UiStringRes(R.string.activity_log_date_range_filter_label_content_description) ) } private fun createActivityTypeFilterLabel(): kotlin.Pair<UiString, UiString> { return currentActivityTypeFilter.takeIf { it.isNotEmpty() }?.let { if (it.size == 1) { kotlin.Pair( UiStringText(it[0].name), UiStringResWithParams( R.string.activity_log_activity_type_filter_single_item_selected_content_description, listOf(UiStringText(it[0].name), UiStringText(it[0].count.toString())) ) ) } else { kotlin.Pair( UiStringResWithParams( R.string.activity_log_activity_type_filter_active_label, listOf(UiStringText("${it.size}")) ), UiStringResWithParams( R.string.activity_log_activity_type_filter_multiple_items_selected_content_description, listOf(UiStringText("${it.size}")) ) ) } } ?: kotlin.Pair( UiStringRes(R.string.activity_log_activity_type_filter_label), UiStringRes(R.string.activity_log_activity_type_filter_no_item_selected_content_description) ) } fun onScrolledToBottom() { requestEventsUpdate(true) } fun onPullToRefresh() { requestEventsUpdate(false) } fun onItemClicked(item: ActivityLogListItem) { if (item is ActivityLogListItem.Event) { _showItemDetail.value = item } } fun onSecondaryActionClicked( secondaryAction: ActivityLogListItem.SecondaryAction, item: ActivityLogListItem ): Boolean { if (item is ActivityLogListItem.Event) { val navigationEvent = when (secondaryAction) { ActivityLogListItem.SecondaryAction.RESTORE -> { ActivityLogNavigationEvents.ShowRestore(item) } ActivityLogListItem.SecondaryAction.DOWNLOAD_BACKUP -> { ActivityLogNavigationEvents.ShowBackupDownload(item) } } _navigationEvents.value = Event(navigationEvent) } return true } private fun onDownloadBackupFileClicked(url: String) { activityLogTracker.trackDownloadBackupDownloadButtonClicked(rewindableOnly) _navigationEvents.value = Event(ActivityLogNavigationEvents.DownloadBackupFile(url)) } /** Reload events first to remove the notice item, as it shows progress to the user. Then trigger the dismiss (this is an optimistic call). If the dismiss fails it will show again on the next reload. */ private fun dismissNoticeClicked(downloadId: Long) { activityLogTracker.trackDownloadBackupDismissButtonClicked(rewindableOnly) reloadEvents(backupDownloadEvent = BackupDownloadEvent(displayNotice = false, displayProgress = false)) viewModelScope.launch { postDismissBackupDownloadUseCase.dismissBackupDownload(downloadId, site) } } fun dateRangePickerClicked() { activityLogTracker.trackDateRangeFilterButtonClicked(rewindableOnly) _showDateRangePicker.value = ShowDateRangePicker(initialSelection = currentDateRangeFilter) } fun onDateRangeSelected(dateRange: DateRange?) { val adjustedDateRange = dateRange?.let { // adjust time of the end of the date range to 23:59:59 Pair(dateRange.first, dateRange.second?.let { it + DAY_IN_MILLIS - ONE_SECOND_IN_MILLIS }) } activityLogTracker.trackDateRangeFilterSelected(dateRange, rewindableOnly) currentDateRangeFilter = adjustedDateRange refreshFiltersUiState() requestEventsUpdate(false) } fun onClearDateRangeFilterClicked() { activityLogTracker.trackDateRangeFilterCleared(rewindableOnly) currentDateRangeFilter = null refreshFiltersUiState() requestEventsUpdate(false) } fun onActivityTypeFilterClicked() { activityLogTracker.trackActivityTypeFilterButtonClicked() _showActivityTypeFilterDialog.value = ShowActivityTypePicker( RemoteId(site.siteId), currentActivityTypeFilter.map { it.key }, currentDateRangeFilter ) } fun onActivityTypesSelected(selectedTypes: List<ActivityTypeModel>) { activityLogTracker.trackActivityTypeFilterSelected(selectedTypes) currentActivityTypeFilter = selectedTypes refreshFiltersUiState() requestEventsUpdate(false) } fun onClearActivityTypeFilterClicked() { activityLogTracker.trackActivityTypeFilterCleared() currentActivityTypeFilter = listOf() refreshFiltersUiState() requestEventsUpdate(false) } fun onQueryRestoreStatus(rewindId: String, restoreId: Long) { queryRestoreStatus(restoreId) showRestoreStartedMessage(rewindId) } private fun queryRestoreStatus(restoreId: Long? = null) { restoreStatusJob?.cancel() restoreStatusJob = viewModelScope.launch { getRestoreStatusUseCase.getRestoreStatus(site, restoreId) .collect { handleRestoreStatus(it) } } } private fun handleRestoreStatus(state: RestoreRequestState) { when (state) { is RestoreRequestState.Multisite -> handleRestoreStatusForMultisite() is RestoreRequestState.Progress -> handleRestoreStatusForProgress(state) is RestoreRequestState.Complete -> handleRestoreStatusForComplete(state) else -> Unit // Do nothing } } private fun handleRestoreStatusForMultisite() { reloadEvents( restoreEvent = RestoreEvent( displayProgress = false, isRestoreHidden = true ) ) } private fun handleRestoreStatusForProgress(state: RestoreRequestState.Progress) { if (!isRestoreProgressItemShown) { reloadEvents( restoreEvent = RestoreEvent( displayProgress = true, isCompleted = false, rewindId = state.rewindId, published = state.published ) ) } } private fun handleRestoreStatusForComplete(state: RestoreRequestState.Complete) { if (isRestoreProgressItemShown) { requestEventsUpdate( loadMore = false, restoreEvent = RestoreEvent( displayProgress = false, isCompleted = true, rewindId = state.rewindId, published = state.published ) ) } } private fun showRestoreStartedMessage(rewindId: String) { activityLogStore.getActivityLogItemByRewindId(rewindId)?.published?.let { _showSnackbarMessage.value = resourceProvider.getString( R.string.activity_log_rewind_started_snackbar_message, it.toFormattedDateString(), it.toFormattedTimeString() ) } } fun onQueryBackupDownloadStatus(rewindId: String, downloadId: Long, actionState: Int) { queryBackupDownloadStatus(downloadId) if (actionState == PROGRESS.id) { showBackupDownloadStartedMessage(rewindId) } else { showBackupDownloadFinishedMessage(rewindId) } } private fun queryBackupDownloadStatus(downloadId: Long? = null) { backupDownloadStatusJob?.cancel() backupDownloadStatusJob = viewModelScope.launch { getBackupDownloadStatusUseCase.getBackupDownloadStatus(site, downloadId) .collect { state -> handleBackupDownloadStatus(state) } } } private fun handleBackupDownloadStatus(state: BackupDownloadRequestState) { when (state) { is BackupDownloadRequestState.Progress -> handleBackupDownloadStatusForProgress(state) is BackupDownloadRequestState.Complete -> handleBackupDownloadStatusForComplete(state) else -> Unit // Do nothing } } private fun handleBackupDownloadStatusForProgress(state: BackupDownloadRequestState.Progress) { if (!isBackupDownloadProgressItemShown) { reloadEvents( backupDownloadEvent = BackupDownloadEvent( displayProgress = true, displayNotice = false, isCompleted = false, rewindId = state.rewindId, published = state.published ) ) } } private fun handleBackupDownloadStatusForComplete(state: BackupDownloadRequestState.Complete) { val backupDownloadEvent = BackupDownloadEvent( displayProgress = false, displayNotice = state.isValid, isCompleted = true, rewindId = state.rewindId, published = state.published, url = state.url, validUntil = state.validUntil, downloadId = state.downloadId ) if (isBackupDownloadProgressItemShown) { requestEventsUpdate(loadMore = false, backupDownloadEvent = backupDownloadEvent) } else { reloadEvents(backupDownloadEvent = backupDownloadEvent) } } private fun showBackupDownloadStartedMessage(rewindId: String) { activityLogStore.getActivityLogItemByRewindId(rewindId)?.published?.let { _showSnackbarMessage.value = resourceProvider.getString( R.string.activity_log_backup_started_snackbar_message, it.toFormattedDateString(), it.toFormattedTimeString() ) } } data class ShowDateRangePicker(val initialSelection: DateRange?) data class ShowActivityTypePicker( val siteId: RemoteId, val initialSelection: List<String>, val dateRange: DateRange? ) data class RestoreEvent( val displayProgress: Boolean, val isRestoreHidden: Boolean = false, val isCompleted: Boolean = false, val rewindId: String? = null, val published: Date? = null ) data class BackupDownloadEvent( val displayProgress: Boolean, val displayNotice: Boolean, val isCompleted: Boolean = false, val rewindId: String? = null, val published: Date? = null, val downloadId: Long? = null, val url: String? = null, val validUntil: Date? = null ) sealed class FiltersUiState(val visibility: Boolean) { object FiltersHidden : FiltersUiState(visibility = false) data class FiltersShown( val dateRangeLabel: UiString, val dateRangeLabelContentDescription: UiString, val activityTypeLabel: UiString, val activityTypeLabelContentDescription: UiString, val onClearDateRangeFilterClicked: (() -> Unit)?, val onClearActivityTypeFilterClicked: (() -> Unit)? ) : FiltersUiState(visibility = true) } sealed class EmptyUiState { abstract val emptyScreenTitle: UiString abstract val emptyScreenSubtitle: UiString object ActivityLog { object EmptyFilters : EmptyUiState() { override val emptyScreenTitle = UiStringRes(R.string.activity_log_empty_title) override val emptyScreenSubtitle = UiStringRes(R.string.activity_log_empty_subtitle) } object ActiveFilters : EmptyUiState() { override val emptyScreenTitle = UiStringRes(R.string.activity_log_active_filter_empty_title) override val emptyScreenSubtitle = UiStringRes(R.string.activity_log_active_filter_empty_subtitle) } } object Backup { object EmptyFilters : EmptyUiState() { override val emptyScreenTitle = UiStringRes(R.string.backup_empty_title) override val emptyScreenSubtitle = UiStringRes(R.string.backup_empty_subtitle) } object ActiveFilters : EmptyUiState() { override val emptyScreenTitle = UiStringRes(R.string.backup_active_filter_empty_title) override val emptyScreenSubtitle = UiStringRes(R.string.backup_active_filter_empty_subtitle) } } } }
WordPress/src/main/java/org/wordpress/android/viewmodel/activitylog/ActivityLogViewModel.kt
3012259066
package org.geryon.examples.kotlin import java.util.* import java.util.concurrent.Executors import org.geryon.Http.* /** * @author Gabriel Francisco <[email protected]> */ object SimpleServer { @JvmStatic fun main(args: Array<String>) { //defining the expose http port //default is 8080 port(8888) //default response content-type //default is text/plain defaultContentType("application/json") //you can define how many threads netty will use for its event loop eventLoopThreadNumber(1) // you can define some headers to be sent with any response defaultHeader("X-Powered-By", "geryon") //you can also define exception handlers for exceptions occurred on the future completion handlerFor(Exception::class.java) { exception, request -> internalServerError("ups, you called ${request.url()} and it seems that an exception occurred: ${exception.message}") } get("/hello") { r -> val name = r.queryParameters().get("name") // since you cannot block your handler, // you need to return a CompletableFuture with a response, instead of only a response supply { ok("{\"name\": \"$name\"}") } } //over here we are using a matcher //a matcher is a function<request, boolean> which returns if the request //matched the route, so, you can have the same method and path mapped //to different routes, since you also implemented different matchers. get("/hello/withMatcher", { r -> "1" == r.headers().get("Version") }) { r -> val name = r.queryParameters().get("name") // since you cannot block your handler, // you need to return a CompletableFuture with a response, instead of only a response supply { ok("{\"name\": \"$name\"}") } } get("/hello/:name") { r -> //getting the path parameter val name = r.pathParameters()["name"] // since you cannot block your handler, // you need to return a CompletableFuture with a response, instead of only a response supply { ok("{\"name\": \"$name\"}") } } //this example is using matrix parameters //matrix parameters are evaluated lazily, since getting them is more costly than other parameters get("/hello/matrix") { r -> //so, if the client sends a GET: http://host:port/hello;name=gabriel;age=24/matrix //we are extracting over here name and size parameters from "hello" path. val name = r.matrixParameters()["hello"]!!["name"] val age = r.matrixParameters()["hello"]!!["age"] supply { ok("{\"name\": \"$name\", \"age\":$age}") } } post("/hello") { r -> val jsonBody = r.body() // since you cannot block your handler, // you need to return a CompletableFuture with a response, instead of only a response supply { created("/hello/" + UUID.randomUUID().toString(), jsonBody) } } val singleThreadExecutor = Executors.newSingleThreadExecutor() put("/hello") { r -> val jsonBody = r.body() //in this case, we are using a specific executor service to avoid blocking operations in the global executor supply(singleThreadExecutor) { accepted(jsonBody) } } } }
kotlin-examples/src/main/kotlin/org/geryon/examples/kotlin/SimpleServer.kt
2322672653
package com.kelsos.mbrc.networking.client import com.fasterxml.jackson.annotation.JsonProperty class GenericSocketMessage<T>( @param:JsonProperty var context: String, @param:JsonProperty var data: T ) where T : Any
app/src/main/kotlin/com/kelsos/mbrc/networking/client/GenericSocketMessage.kt
3052859470
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.inline import com.google.gson.JsonObject import com.intellij.lang.refactoring.InlineActionHandler import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor import org.jetbrains.kotlin.idea.refactoring.AbstractMultifileRefactoringTest import org.jetbrains.kotlin.idea.refactoring.runRefactoringTest abstract class AbstractInlineMultiFileTest : AbstractMultifileRefactoringTest() { override fun runRefactoring(path: String, config: JsonObject, rootDir: VirtualFile, project: Project) { runRefactoringTest(path, config, rootDir, project, InlineAction) } } object InlineAction: AbstractMultifileRefactoringTest.RefactoringAction { override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) { val targetElement = elementsAtCaret.single() InlineActionHandler.EP_NAME.extensions.firstOrNull { it.canInlineElement(targetElement) }?.inlineElement( targetElement.project, targetElement.findExistingEditor(), targetElement, ) } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/inline/AbstractInlineMultiFileTest.kt
184008512
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.sdk import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl import com.intellij.openapi.util.NullableComputable /** * @author vlan */ class PyLazySdk(name: String, private val create: NullableComputable<Sdk>) : ProjectJdkImpl(name, PythonSdkType.getInstance(), null, null) { fun create(): Sdk? = create.compute() }
python/src/com/jetbrains/python/sdk/PyLazySdk.kt
1922696716
// Copyright 2000-2019 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.grazie import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.extensions.PluginId import java.nio.file.Path internal object GraziePlugin { const val id = "tanvd.grazi" object LanguageTool { const val version = "5.7" const val url = "https://resources.jetbrains.com/grazie/model/language-tool" } private val descriptor: IdeaPluginDescriptor get() = PluginManagerCore.getPlugin(PluginId.getId(id))!! val group: String get() = GrazieBundle.message("grazie.group.name") val settingsPageName: String get() = GrazieBundle.message("grazie.settings.page.name") val isBundled: Boolean get() = descriptor.isBundled val classLoader: ClassLoader get() = descriptor.classLoader val libFolder: Path get() = descriptor.pluginPath.resolve("lib") }
plugins/grazie/src/main/kotlin/com/intellij/grazie/GraziePlugin.kt
2281061322
package org.jetbrains.plugins.notebooks.visualization import com.intellij.mock.MockDocument import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.event.MockDocumentEvent import com.intellij.util.EventDispatcher import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.catchThrowable import org.assertj.core.api.Descriptable import org.assertj.core.description.Description import org.jetbrains.plugins.notebooks.visualization.NotebookCellLines.Interval import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class NotebookIntervalPointerTest { private val exampleIntervals = listOf( makeIntervals(), makeIntervals(0..1), makeIntervals(0..1, 2..4), makeIntervals(0..1, 2..4, 5..8), ) @Test fun testInitialization() { for (intervals in exampleIntervals) { val env = TestEnv(intervals) env.shouldBeValid(intervals) env.shouldBeInvalid(makeInterval(10, 10..11)) } } @Test fun testAddAllIntervals() { for (intervals in exampleIntervals) { val env = TestEnv(listOf()) env.shouldBeInvalid(intervals) env.changeSegment(listOf(), intervals, intervals) env.shouldBeValid(intervals) } } @Test fun testRemoveAllIntervals() { for (intervals in exampleIntervals) { val env = TestEnv(intervals) env.shouldBeValid(intervals) env.changeSegment(intervals, listOf(), listOf()) env.shouldBeInvalid(intervals) } } @Test fun testChangeElements() { val initialIntervals = makeIntervals(0..1, 2..4, 5..8, 9..13) val optionsToRemove = listOf( listOf(), initialIntervals.subList(1, 2), initialIntervals.subList(1, 3), initialIntervals.subList(1, 4) ) val optionsToAdd = listOf( listOf(), makeIntervals(2..10).map { it.copy(ordinal = it.ordinal + 1, type = NotebookCellLines.CellType.CODE) }, makeIntervals(2..10, 11..20).map { it.copy(ordinal = it.ordinal + 1, type = NotebookCellLines.CellType.CODE) } ) for (toRemove in optionsToRemove) { for (toAdd in optionsToAdd) { val start = initialIntervals.subList(0, 1) val end = initialIntervals.subList(1 + toRemove.size, 4) val finalIntervals = fixOrdinalsAndOffsets(start + toAdd + end) val env = TestEnv(initialIntervals) val pointersToUnchangedIntervals = (start + end).map { env.pointersFactory.create(it) } val pointersToRemovedIntervals = toRemove.map { env.pointersFactory.create(it) } pointersToUnchangedIntervals.forEach { assertThat(it.get()).isNotNull() } pointersToRemovedIntervals.forEach { assertThat(it.get()).isNotNull } env.changeSegment(toRemove, toAdd, finalIntervals) pointersToUnchangedIntervals.forEach { pointer -> assertThat(pointer.get()).isNotNull() } pointersToRemovedIntervals.forEach { pointer -> assertThat(pointer.get()).isNull() } env.shouldBeValid(finalIntervals) env.shouldBeInvalid(toRemove) } } } @Test fun testReuseInterval() { val initialIntervals = makeIntervals(0..1, 2..19, 20..199) for ((i, selected) in initialIntervals.withIndex()) { val dsize = 1 val changed = selected.copy(lines = selected.lines.first..selected.lines.last + dsize) val allIntervals = fixOrdinalsAndOffsets(initialIntervals.subList(0, i) + listOf(changed) + initialIntervals.subList(i + 1, initialIntervals.size)) val env = TestEnv(initialIntervals) val pointers = initialIntervals.map { env.pointersFactory.create(it) } pointers.zip(initialIntervals).forEach { (pointer, interval) -> assertThat(pointer.get()).isEqualTo(interval) } env.changeSegment(listOf(selected), listOf(changed), allIntervals) pointers.zip(allIntervals).forEach { (pointer, interval) -> assertThat(pointer.get()).isEqualTo(interval)} } } private fun fixOrdinalsAndOffsets(intervals: List<Interval>): List<Interval> { val result = mutableListOf<Interval>() for ((index, interval) in intervals.withIndex()) { val expectedOffset = result.lastOrNull()?.let { it.lines.last + 1 } ?: 0 val correctInterval = if (interval.lines.first == expectedOffset && interval.ordinal == index) interval else interval.copy(ordinal = index, lines = expectedOffset..(expectedOffset + interval.lines.last - interval.lines.first)) result.add(correctInterval) } return result } private fun makeInterval(ordinal: Int, lines: IntRange) = Interval(ordinal, NotebookCellLines.CellType.RAW, lines, NotebookCellLines.MarkersAtLines.NO) private fun makeIntervals(vararg lines: IntRange): List<Interval> = lines.withIndex().map { (index, lines) -> makeInterval(index, lines) } } private class TestEnv(intervals: List<Interval>, val document: Document = MockDocument()) { val notebookCellLines = MockNotebookCellLines(intervals = mutableListOf(*intervals.toTypedArray())) val pointersFactory = NotebookIntervalPointerFactoryImpl(notebookCellLines) fun changeSegment(old: List<Interval>, new: List<Interval>, allIntervals: List<Interval>) { old.firstOrNull()?.let { firstOld -> new.firstOrNull()?.let { firstNew -> assertThat(firstOld.ordinal).isEqualTo(firstNew.ordinal) } } notebookCellLines.intervals.clear() notebookCellLines.intervals.addAll(allIntervals) val documentEvent = MockDocumentEvent(document, 0) val event = NotebookCellLinesEvent(documentEvent, old, old, new, new, 0) notebookCellLines.intervalListeners.multicaster.segmentChanged(event) } fun shouldBeValid(interval: Interval) { assertThat(pointersFactory.create(interval).get()) .describedAs { "pointer for ${interval} should be valid, but current pointers = ${describe(notebookCellLines.intervals)}" } .isEqualTo(interval) } fun shouldBeInvalid(interval: Interval) { val error = catchThrowable { pointersFactory.create(interval).get() } assertThat(error) .describedAs { "pointer for ${interval} should be null, but current pointers = ${describe(notebookCellLines.intervals)}" } .isNotNull() } fun shouldBeValid(intervals: List<Interval>): Unit = intervals.forEach { shouldBeValid(it) } fun shouldBeInvalid(intervals: List<Interval>): Unit = intervals.forEach { shouldBeInvalid(it) } } private class MockNotebookCellLines(override val intervals: MutableList<Interval> = mutableListOf()) : NotebookCellLines { init { checkIntervals(intervals) } override val intervalListeners = EventDispatcher.create(NotebookCellLines.IntervalListener::class.java) override fun intervalsIterator(startLine: Int): ListIterator<Interval> = TODO("stub") override val modificationStamp: Long get() = TODO("stub") } private fun describe(intervals: List<Interval>): String = intervals.joinToString(separator = ",", prefix = "[", postfix = "]") private fun checkIntervals(intervals: List<Interval>) { intervals.zipWithNext().forEach { (prev, next) -> assertThat(prev.lines.last + 1).describedAs { "wrong intervals: ${describe(intervals)}" }.isEqualTo(next.lines.first) } intervals.withIndex().forEach { (index, interval) -> assertThat(interval.ordinal).describedAs { "wrong interval ordinal: ${describe(intervals)}" }.isEqualTo(index) } } fun <Self> Descriptable<Self>.describedAs(lazyMsg: () -> String): Self = describedAs(object : Description() { override fun value(): String = lazyMsg() })
notebooks/visualization/test/org/jetbrains/plugins/notebooks/visualization/NotebookIntervalPointerTest.kt
2848969361
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("StartupUtil") @file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE", "ReplacePutWithAssignment", "KDocUnresolvedReference") package com.intellij.idea import com.intellij.BundleBase import com.intellij.accessibility.AccessibilityUtils import com.intellij.diagnostic.* import com.intellij.diagnostic.opentelemetry.TraceManager import com.intellij.ide.* import com.intellij.ide.customize.CommonCustomizeIDEWizardDialog import com.intellij.ide.gdpr.ConsentOptions import com.intellij.ide.gdpr.EndUserAgreement import com.intellij.ide.gdpr.showDataSharingAgreement import com.intellij.ide.gdpr.showEndUserAndDataSharingAgreements import com.intellij.ide.instrument.WriteIntentLockInstrumenter import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.ui.html.GlobalStyleSheetHolder import com.intellij.ide.ui.laf.IdeaLaf import com.intellij.ide.ui.laf.IntelliJLaf import com.intellij.ide.ui.laf.darcula.DarculaLaf import com.intellij.idea.SocketLock.ActivationStatus import com.intellij.jna.JnaLoader import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.ConfigImportHelper import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.application.impl.AWTExceptionHandler import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.ShutDownTracker import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.win32.IdeaWin32 import com.intellij.openapi.wm.WeakFocusStackManager import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.ui.AppUIUtil import com.intellij.ui.CoreIconManager import com.intellij.ui.IconManager import com.intellij.ui.mac.MacOSApplicationProvider import com.intellij.ui.scale.JBUIScale import com.intellij.util.EnvironmentUtil import com.intellij.util.PlatformUtils import com.intellij.util.ReflectionUtil import com.intellij.util.lang.Java11Shim import com.intellij.util.lang.ZipFilePool import com.intellij.util.ui.EDT import com.intellij.util.ui.StartupUiUtil import com.intellij.util.ui.accessibility.ScreenReader import kotlinx.coroutines.* import org.jetbrains.annotations.VisibleForTesting import org.jetbrains.io.BuiltInServer import sun.awt.AWTAutoShutdown import java.awt.EventQueue import java.awt.Font import java.awt.GraphicsEnvironment import java.awt.Toolkit import java.awt.dnd.DragSource import java.io.File import java.io.IOError import java.io.IOException import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType import java.lang.management.ManagementFactory import java.nio.channels.FileChannel import java.nio.file.Files import java.nio.file.InvalidPathException import java.nio.file.Path import java.nio.file.StandardOpenOption import java.nio.file.attribute.PosixFileAttributeView import java.nio.file.attribute.PosixFilePermission import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.* import java.util.function.BiConsumer import java.util.function.BiFunction import java.util.function.Function import java.util.logging.ConsoleHandler import java.util.logging.Level import javax.swing.* import kotlin.coroutines.CoroutineContext import kotlin.system.exitProcess internal const val IDE_STARTED = "------------------------------------------------------ IDE STARTED ------------------------------------------------------" private const val IDE_SHUTDOWN = "------------------------------------------------------ IDE SHUTDOWN ------------------------------------------------------" @JvmField internal var EXTERNAL_LISTENER: BiFunction<String, Array<String>, Int> = BiFunction { _, _ -> AppExitCodes.ACTIVATE_NOT_INITIALIZED } private const val IDEA_CLASS_BEFORE_APPLICATION_PROPERTY = "idea.class.before.app" // see `ApplicationImpl#USE_SEPARATE_WRITE_THREAD` private const val USE_SEPARATE_WRITE_THREAD_PROPERTY = "idea.use.separate.write.thread" private const val MAGIC_MAC_PATH = "/AppTranslocation/" private var socketLock: SocketLock? = null // checked - using Deferred type doesn't lead to loading this class on StartupUtil init internal var shellEnvDeferred: Deferred<Boolean?>? = null private set // mainDispatcher is a sequential - use it with care fun CoroutineScope.startApplication(args: List<String>, appStarterDeferred: Deferred<AppStarter>, mainScope: CoroutineScope, busyThread: Thread) { val appInfoDeferred = async(CoroutineName("app info") + Dispatchers.IO) { // required for DisabledPluginsState and EUA ApplicationInfoImpl.getShadowInstance() } val euaDocumentDeferred = loadEuaDocument(appInfoDeferred) // this must happen before LaF loading val checkGraphicsJob = checkGraphics() val pathDeferred = async(CoroutineName("config path computing") + Dispatchers.IO) { Pair(canonicalPath(PathManager.getConfigPath()), canonicalPath(PathManager.getSystemPath())) } val isHeadless = AppMode.isHeadless() val configImportNeededDeferred = async { val (configPath, _) = pathDeferred.await() !isHeadless && (!Files.exists(configPath) || Files.exists(configPath.resolve(ConfigImportHelper.CUSTOM_MARKER_FILE_NAME))) } // this should happen before UI initialization - if we're not going to show UI (in case another IDE instance is already running), // we shouldn't initialize AWT toolkit in order to avoid unnecessary focus stealing and space switching on macOS. val lockSystemDirsJob = lockSystemDirs(configImportNeededDeferred = configImportNeededDeferred, pathDeferred = pathDeferred, args = args, mainScope = mainScope) val consoleLoggerJob = configureJavaUtilLogging() launch { LoadingState.setStrictMode() LoadingState.errorHandler = BiConsumer { message, throwable -> logger<LoadingState>().error(message, throwable) } } val preloadLafClassesJob = preloadLafClasses() // LookAndFeel type is not specified to avoid class loading val initUiDeferred = async { checkGraphicsJob?.join() lockSystemDirsJob.join() initUi(preloadLafClassesJob, busyThread = busyThread) } val zipFilePoolDeferred = async(Dispatchers.IO) { // ZipFilePoolImpl uses Guava for Striped lock - load in parallel val result = ZipFilePoolImpl() ZipFilePool.POOL = result result } val schedulePluginDescriptorLoading = launch { ComponentManagerImpl.mainScope = mainScope // plugins cannot be loaded when a config import is needed, because plugins may be added after importing Java11Shim.INSTANCE = Java11ShimImpl() if (!configImportNeededDeferred.await()) { PluginManagerCore.scheduleDescriptorLoading(mainScope, zipFilePoolDeferred) } } // system dirs checking must happen after locking system dirs val checkSystemDirJob = checkSystemDirs(lockSystemDirsJob, pathDeferred) // log initialization must happen only after locking the system directory val logDeferred = setupLogger(consoleLoggerJob, checkSystemDirJob) val showEuaIfNeededJob = showEuaIfNeeded(euaDocumentDeferred, initUiDeferred) val patchHtmlStyleJob = if (isHeadless) null else patchHtmlStyle(initUiDeferred) shellEnvDeferred = async(CoroutineName("environment loading") + Dispatchers.IO) { EnvironmentUtil.loadEnvironment() } if (!isHeadless) { showSplashIfNeeded(initUiDeferred, showEuaIfNeededJob, appInfoDeferred, args) // must happen after initUi updateFrameClassAndWindowIconAndPreloadSystemFonts(initUiDeferred) } if (java.lang.Boolean.getBoolean("idea.enable.coroutine.dump")) { launch(CoroutineName("coroutine debug probes init")) { enableCoroutineDump() } } loadSystemLibsAndLogInfoAndInitMacApp(logDeferred, appInfoDeferred, initUiDeferred, args) val telemetryInitJob = launch { appInfoDeferred.join() runActivity("opentelemetry configuration") { TraceManager.init() } } val isInternal = java.lang.Boolean.getBoolean(ApplicationManagerEx.IS_INTERNAL_PROPERTY) if (isInternal) { launch(CoroutineName("assert on missed keys enabling")) { BundleBase.assertOnMissedKeys(true) } } launch(CoroutineName("disposer debug mode enabling if needed")) { if (isInternal || Disposer.isDebugDisposerOn()) { Disposer.setDebugMode(true) } } val appDeferred = async { // logging must be initialized before creating application val log = logDeferred.await() if (!configImportNeededDeferred.await()) { runPreAppClass(log, args) } // we must wait for UI before creating application and before AppStarter.start (some appStarter dialogs) - EDT thread is required runActivity("prepare ui waiting") { initUiDeferred.join() } val app = runActivity("app instantiation") { ApplicationImpl(isInternal, AppMode.isHeadless(), AppMode.isCommandLine(), EDT.getEventDispatchThread()) } runActivity("telemetry waiting") { telemetryInitJob.join() } app to patchHtmlStyleJob } mainScope.launch { // required for appStarter.prepareStart appInfoDeferred.join() val appStarter = runActivity("main class loading waiting") { appStarterDeferred.await() } appStarter.prepareStart(args) // before config importing and license check showEuaIfNeededJob.join() if (!isHeadless && configImportNeededDeferred.await()) { initUiDeferred.join() val imported = importConfig( args = args, log = logDeferred.await(), appStarter = appStarterDeferred.await(), agreementShown = showEuaIfNeededJob, ) if (imported) { PluginManagerCore.scheduleDescriptorLoading(mainScope, zipFilePoolDeferred) } } // must be scheduled before starting app schedulePluginDescriptorLoading.join() // with main dispatcher (appStarter uses runBlocking - block main thread and not some coroutine thread) appStarter.start(args, appDeferred) } } private fun CoroutineScope.loadSystemLibsAndLogInfoAndInitMacApp(logDeferred: Deferred<Logger>, appInfoDeferred: Deferred<ApplicationInfoEx>, initUiDeferred: Job, args: List<String>) { launch { // this must happen after locking system dirs val log = logDeferred.await() runActivity("system libs setup") { setupSystemLibraries() } withContext(Dispatchers.IO) { runActivity("system libs loading") { JnaLoader.load(log) if (SystemInfoRt.isWindows) { IdeaWin32.isAvailable() } } } val appInfo = appInfoDeferred.await() launch(CoroutineName("essential IDE info logging") + Dispatchers.IO) { logEssentialInfoAboutIde(log, appInfo, args) } if (!AppMode.isHeadless() && SystemInfoRt.isMac) { // JNA and Swing are used - invoke only after both are loaded initUiDeferred.join() launch(CoroutineName("mac app init")) { MacOSApplicationProvider.initApplication(log) } } } } private fun CoroutineScope.showSplashIfNeeded(initUiDeferred: Deferred<Any>, showEuaIfNeededJob: Deferred<Boolean>, appInfoDeferred: Deferred<ApplicationInfoEx>, args: List<String>) { if (AppMode.isLightEdit()) { return } launch { // A splash instance must not be created before base LaF is created. // It is important on Linux, where GTK LaF must be initialized (to properly set up the scale factor). // https://youtrack.jetbrains.com/issue/IDEA-286544 initUiDeferred.join() // before showEuaIfNeededJob to prepare during showing EUA dialog val runnable = prepareSplash(appInfoDeferred, args) ?: return@launch showEuaIfNeededJob.join() withContext(SwingDispatcher) { runnable.run() } } } private fun CoroutineScope.patchHtmlStyle(initUiJob: Deferred<Any>): Job { return launch { initUiJob.join() withContext(SwingDispatcher) { runActivity("html style patching") { // patch html styles val uiDefaults = UIManager.getDefaults() // create a separate copy for each case val globalStyleSheet = GlobalStyleSheetHolder.getGlobalStyleSheet() uiDefaults.put("javax.swing.JLabel.userStyleSheet", globalStyleSheet) uiDefaults.put("HTMLEditorKit.jbStyleSheet", globalStyleSheet) runActivity("global styleSheet updating") { GlobalStyleSheetHolder.updateGlobalSwingStyleSheet() } } } } } private suspend fun prepareSplash(appInfoDeferred: Deferred<ApplicationInfoEx>, args: List<String>): Runnable? { var showSplash = false for (arg in args) { if (CommandLineArgs.SPLASH == arg) { showSplash = true break } else if (CommandLineArgs.NO_SPLASH == arg) { return null } } // products may specify `splash` VM property; `nosplash` is deprecated and should be checked first if (!showSplash && (java.lang.Boolean.getBoolean(CommandLineArgs.NO_SPLASH) || !java.lang.Boolean.getBoolean(CommandLineArgs.SPLASH))) { return null } val appInfo = appInfoDeferred.await() return runActivity("splash preparation") { SplashManager.scheduleShow(appInfo) } } private fun CoroutineScope.checkGraphics(): Job? { if (AppMode.isHeadless()) { return null } return launch { runActivity("graphics environment checking") { if (GraphicsEnvironment.isHeadless()) { StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.startup.error"), BootstrapBundle.message("bootstrap.error.message.no.graphics.environment"), true) exitProcess(AppExitCodes.NO_GRAPHICS) } } } } /** Called via reflection from [WindowsCommandLineProcessor.processWindowsLauncherCommandLine]. */ @Suppress("unused") fun processWindowsLauncherCommandLine(currentDirectory: String, args: Array<String>): Int { return EXTERNAL_LISTENER.apply(currentDirectory, args) } internal val isUsingSeparateWriteThread: Boolean get() = java.lang.Boolean.getBoolean(USE_SEPARATE_WRITE_THREAD_PROPERTY) // called by the app after startup @Synchronized fun addExternalInstanceListener(processor: Function<List<String>, Future<CliResult>>) { if (socketLock == null) { throw AssertionError("Not initialized yet") } socketLock!!.setCommandProcessor(processor) } // used externally by TeamCity plugin (as TeamCity cannot use modern API to support old IDE versions) @Synchronized @Deprecated("") fun getServer(): BuiltInServer? = socketLock?.getServer() @Synchronized fun getServerFutureAsync(): Deferred<BuiltInServer?> = socketLock?.serverFuture ?: CompletableDeferred(value = null) // On startup 2 dialogs must be shown: // - gdpr agreement // - eu(l)a private fun CoroutineScope.loadEuaDocument(appInfoDeferred: Deferred<ApplicationInfoEx>): Deferred<Any?>? { if (AppMode.isHeadless()) { return null } return async(CoroutineName("eua document") + Dispatchers.IO) { val vendorAsProperty = System.getProperty("idea.vendor.name", "") if (if (vendorAsProperty.isEmpty()) !appInfoDeferred.await().isVendorJetBrains else vendorAsProperty != "JetBrains") { null } else { val document = runActivity("eua getting") { EndUserAgreement.getLatestDocument() } if (runActivity("eua is accepted checking") { document.isAccepted }) null else document } } } private fun runPreAppClass(log: Logger, args: List<String>) { val classBeforeAppProperty = System.getProperty(IDEA_CLASS_BEFORE_APPLICATION_PROPERTY) ?: return runActivity("pre app class running") { try { val aClass = AppStarter::class.java.classLoader.loadClass(classBeforeAppProperty) MethodHandles.lookup() .findStatic(aClass, "invoke", MethodType.methodType(Void.TYPE, Array<String>::class.java)) .invoke(args.toTypedArray()) } catch (e: Exception) { log.error("Failed pre-app class init for class $classBeforeAppProperty", e) } } } private suspend fun importConfig(args: List<String>, log: Logger, appStarter: AppStarter, agreementShown: Deferred<Boolean>): Boolean { var activity = StartUpMeasurer.startActivity("screen reader checking") try { withContext(SwingDispatcher) { AccessibilityUtils.enableScreenReaderSupportIfNecessary() } } catch (e: Throwable) { log.error(e) } activity = activity.endAndStart("config importing") appStarter.beforeImportConfigs() val newConfigDir = PathManager.getConfigDir() val veryFirstStartOnThisComputer = agreementShown.await() withContext(SwingDispatcher) { if (UIManager.getLookAndFeel() !is IntelliJLaf) { UIManager.setLookAndFeel(IntelliJLaf()) } ConfigImportHelper.importConfigsTo(veryFirstStartOnThisComputer, newConfigDir, args, log) } appStarter.importFinished(newConfigDir) activity.end() return !PlatformUtils.isRider() || ConfigImportHelper.isConfigImported() } // return type (LookAndFeel) is not specified to avoid class loading private suspend fun initUi(preloadLafClassesJob: Job, busyThread: Thread): Any { // calls `sun.util.logging.PlatformLogger#getLogger` - it takes enormous time (up to 500 ms) // only non-logging tasks can be executed before `setupLogger` val activityQueue = StartUpMeasurer.startActivity("base LaF preparation") val isHeadless = AppMode.isHeadless() coroutineScope { launch { checkHiDPISettings() blockATKWrapper() @Suppress("SpellCheckingInspection") System.setProperty("sun.awt.noerasebackground", "true") activityQueue.startChild("awt toolkit creating").let { activity -> Toolkit.getDefaultToolkit() activity.end() } } // IdeaLaF uses AllIcons - icon manager must be activated if (!isHeadless) { launch(CoroutineName("icon manager activation")) { IconManager.activate(CoreIconManager()) } } launch(CoroutineName("IdeEventQueue class preloading")) { val classLoader = AppStarter::class.java.classLoader // preload class not in EDT Class.forName(IdeEventQueue::class.java.name, true, classLoader) } } preloadLafClassesJob.join() // SwingDispatcher must be used after Toolkit init val baseLaF = withContext(SwingDispatcher) { activityQueue.end() // we don't need Idea LaF to show splash, but we do need some base LaF to compute system font data (see below for what) var activity = StartUpMeasurer.startActivity("base LaF creation") val baseLaF = DarculaLaf.createBaseLaF() activity = activity.endAndStart("base LaF initialization") // LaF is useless until initialized (`getDefaults` "should only be invoked ... after `initialize` has been invoked.") baseLaF.initialize() // to compute the system scale factor on non-macOS (JRE HiDPI is not enabled), we need to know system font data, // and to compute system font data we need to know `Label.font` UI default (that's why we compute base LaF first) activity = activity.endAndStart("system font data initialization") if (!isHeadless) { JBUIScale.getSystemFontData { runActivity("base LaF defaults getting") { baseLaF.defaults } } activity = activity.endAndStart("scale initialization") JBUIScale.scale(1f) } StartUpMeasurer.setCurrentState(LoadingState.BASE_LAF_INITIALIZED) activity = activity.endAndStart("awt thread busy notification") /* Make EDT to always persist while the main thread is alive. Otherwise, it's possible to have EDT being terminated by [AWTAutoShutdown], which will break a `ReadMostlyRWLock` instance. [AWTAutoShutdown.notifyThreadBusy(Thread)] will put the main thread into the thread map, and thus will effectively disable auto shutdown behavior for this application. */ AWTAutoShutdown.getInstance().notifyThreadBusy(busyThread) activity.end() patchSystem(isHeadless) baseLaF } if (isUsingSeparateWriteThread) { runActivity("Write Intent Lock UI class transformer loading") { WriteIntentLockInstrumenter.instrument() } } DarculaLaf.setPreInitializedBaseLaf(baseLaF) return baseLaF } private fun CoroutineScope.preloadLafClasses(): Job { val classLoader = AppStarter::class.java.classLoader return launch(CoroutineName("LaF class preloading")) { // preload class not in EDT Class.forName(DarculaLaf::class.java.name, true, classLoader) Class.forName(IdeaLaf::class.java.name, true, classLoader) Class.forName(JBUIScale::class.java.name, true, classLoader) } } /* * The method should be called before `Toolkit#initAssistiveTechnologies`, which is called from `Toolkit#getDefaultToolkit`. */ private fun blockATKWrapper() { // the registry must not be used here, because this method is called before application loading @Suppress("SpellCheckingInspection") if (!SystemInfoRt.isLinux || !java.lang.Boolean.parseBoolean(System.getProperty("linux.jdk.accessibility.atkwrapper.block", "true"))) { return } val activity = StartUpMeasurer.startActivity("atk wrapper blocking") if (ScreenReader.isEnabled(ScreenReader.ATK_WRAPPER)) { // Replacing `AtkWrapper` with a dummy `Object`. It'll be instantiated & garbage collected right away, a NOP. System.setProperty("javax.accessibility.assistive_technologies", "java.lang.Object") Logger.getInstance(StartupUiUtil::class.java).info(ScreenReader.ATK_WRAPPER + " is blocked, see IDEA-149219") } activity.end() } private fun CoroutineScope.showEuaIfNeeded(euaDocumentDeferred: Deferred<Any?>?, initUiJob: Deferred<Any>): Deferred<Boolean> { return async { if (euaDocumentDeferred == null) { return@async true } val euaDocument = euaDocumentDeferred.await() initUiJob.join() runActivity("eua showing") { val document = euaDocument as EndUserAgreement.Document? withContext(Dispatchers.IO) { EndUserAgreement.updateCachedContentToLatestBundledVersion() } if (document != null) { withContext(SwingDispatcher) { UIManager.setLookAndFeel(IntelliJLaf()) showEndUserAndDataSharingAgreements(document) } true } else if (ConsentOptions.needToShowUsageStatsConsent()) { withContext(SwingDispatcher) { UIManager.setLookAndFeel(IntelliJLaf()) showDataSharingAgreement() } false } else { false } } } } /** Do not use it. For start-up code only. */ internal object SwingDispatcher : CoroutineDispatcher() { override fun isDispatchNeeded(context: CoroutineContext): Boolean = !EventQueue.isDispatchThread() override fun dispatch(context: CoroutineContext, block: Runnable): Unit = EventQueue.invokeLater(block) override fun toString() = "Swing" } private fun CoroutineScope.updateFrameClassAndWindowIconAndPreloadSystemFonts(initUiDeferred: Job) { launch { initUiDeferred.join() launch(CoroutineName("system fonts loading") + Dispatchers.IO) { // forces loading of all system fonts; the following statement alone might not do it (see JBR-1825) Font("N0nEx1st5ntF0nt", Font.PLAIN, 1).family // caches available font family names for the default locale to speed up editor reopening (see `ComplementaryFontsRegistry`) GraphicsEnvironment.getLocalGraphicsEnvironment().availableFontFamilyNames } if (!SystemInfoRt.isWindows && !SystemInfoRt.isMac) { launch(CoroutineName("frame class updating")) { try { val toolkit = Toolkit.getDefaultToolkit() val aClass = toolkit.javaClass if (aClass.name == "sun.awt.X11.XToolkit") { val field = ReflectionUtil.findAssignableField(aClass, null, "awtAppClassName") field.set(toolkit, AppUIUtil.getFrameClass()) } } catch (ignore: Exception) { } } } launch(CoroutineName("update window icon")) { // `updateWindowIcon` should be called after `initUiJob`, because it uses computed system font data for scale context if (!AppUIUtil.isWindowIconAlreadyExternallySet() && !PluginManagerCore.isRunningFromSources()) { // most of the time is consumed by loading SVG and can be done in parallel AppUIUtil.updateWindowIcon(JOptionPane.getRootFrame()) } } // preload cursors used by drag-n-drop AWT subsystem, run on SwingDispatcher to avoid a possible deadlock - see RIDER-80810 launch(CoroutineName("DnD setup") + SwingDispatcher) { DragSource.getDefaultDragSource() } launch(SwingDispatcher) { WeakFocusStackManager.getInstance() } } } private fun CoroutineScope.configureJavaUtilLogging(): Job { return launch(CoroutineName("console logger configuration")) { val rootLogger = java.util.logging.Logger.getLogger("") if (rootLogger.handlers.isEmpty()) { rootLogger.level = Level.WARNING val consoleHandler = ConsoleHandler() consoleHandler.level = Level.WARNING rootLogger.addHandler(consoleHandler) } } } @VisibleForTesting fun checkHiDPISettings() { if (!java.lang.Boolean.parseBoolean(System.getProperty("hidpi", "true"))) { // suppress JRE-HiDPI mode System.setProperty("sun.java2d.uiScale.enabled", "false") } } private fun CoroutineScope.checkSystemDirs(lockSystemDirJob: Job, pathDeferred: Deferred<Pair<Path, Path>>): Job { return launch { lockSystemDirJob.join() val (configPath, systemPath) = pathDeferred.await() runActivity("system dirs checking") { if (!doCheckSystemDirs(configPath, systemPath)) { exitProcess(AppExitCodes.DIR_CHECK_FAILED) } } } } private suspend fun doCheckSystemDirs(configPath: Path, systemPath: Path): Boolean { if (configPath == systemPath) { StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.invalid.config.or.system.path"), BootstrapBundle.message("bootstrap.error.message.config.0.and.system.1.paths.must.be.different", PathManager.PROPERTY_CONFIG_PATH, PathManager.PROPERTY_SYSTEM_PATH), true) return false } return withContext(Dispatchers.IO) { val logPath = Path.of(PathManager.getLogPath()).normalize() val tempPath = Path.of(PathManager.getTempPath()).normalize() listOf( async { checkDirectory(directory = configPath, kind = "Config", property = PathManager.PROPERTY_CONFIG_PATH, checkWrite = true, checkLock = true, checkExec = false) }, async { checkDirectory(directory = systemPath, kind = "System", property = PathManager.PROPERTY_SYSTEM_PATH, checkWrite = true, checkLock = true, checkExec = false) }, async { checkDirectory(directory = logPath, kind = "Log", property = PathManager.PROPERTY_LOG_PATH, checkWrite = !logPath.startsWith(systemPath), checkLock = false, checkExec = false) }, async { checkDirectory(directory = tempPath, kind = "Temp", property = PathManager.PROPERTY_SYSTEM_PATH, checkWrite = !tempPath.startsWith(systemPath), checkLock = false, checkExec = SystemInfoRt.isUnix && !SystemInfoRt.isMac) } ).awaitAll().all { it } } } private fun checkDirectory(directory: Path, kind: String, property: String, checkWrite: Boolean, checkLock: Boolean, checkExec: Boolean): Boolean { var problem = "bootstrap.error.message.check.ide.directory.problem.cannot.create.the.directory" var reason = "bootstrap.error.message.check.ide.directory.possible.reason.path.is.incorrect" var tempFile: Path? = null try { if (!Files.isDirectory(directory)) { problem = "bootstrap.error.message.check.ide.directory.problem.cannot.create.the.directory" reason = "bootstrap.error.message.check.ide.directory.possible.reason.directory.is.read.only.or.the.user.lacks.necessary.permissions" Files.createDirectories(directory) } if (checkWrite || checkLock || checkExec) { problem = "bootstrap.error.message.check.ide.directory.problem.the.ide.cannot.create.a.temporary.file.in.the.directory" reason = "bootstrap.error.message.check.ide.directory.possible.reason.directory.is.read.only.or.the.user.lacks.necessary.permissions" tempFile = directory.resolve("ij${Random().nextInt(Int.MAX_VALUE)}.tmp") Files.writeString(tempFile, "#!/bin/sh\nexit 0", StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE) if (checkLock) { problem = "bootstrap.error.message.check.ide.directory.problem.the.ide.cannot.create.a.lock.in.directory" reason = "bootstrap.error.message.check.ide.directory.possible.reason.the.directory.is.located.on.a.network.disk" FileChannel.open(tempFile, EnumSet.of(StandardOpenOption.WRITE)).use { channel -> channel.tryLock().use { lock -> if (lock == null) { throw IOException("File is locked") } } } } else if (checkExec) { problem = "bootstrap.error.message.check.ide.directory.problem.the.ide.cannot.execute.test.script" reason = "bootstrap.error.message.check.ide.directory.possible.reason.partition.is.mounted.with.no.exec.option" Files.getFileAttributeView(tempFile!!, PosixFileAttributeView::class.java) .setPermissions(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE)) val exitCode = ProcessBuilder(tempFile.toAbsolutePath().toString()).start().waitFor() if (exitCode != 0) { throw IOException("Unexpected exit value: $exitCode") } } } return true } catch (e: Exception) { val title = BootstrapBundle.message("bootstrap.error.title.invalid.ide.directory.type.0.directory", kind) val advice = if (SystemInfoRt.isMac && PathManager.getSystemPath().contains(MAGIC_MAC_PATH)) { BootstrapBundle.message("bootstrap.error.message.invalid.ide.directory.trans.located.macos.directory.advice") } else { BootstrapBundle.message("bootstrap.error.message.invalid.ide.directory.ensure.the.modified.property.0.is.correct", property) } val message = BootstrapBundle.message( "bootstrap.error.message.invalid.ide.directory.problem.0.possible.reason.1.advice.2.location.3.exception.class.4.exception.message.5", BootstrapBundle.message(problem), BootstrapBundle.message(reason), advice, directory, e.javaClass.name, e.message) StartupErrorReporter.showMessage(title, message, true) return false } finally { if (tempFile != null) { try { Files.deleteIfExists(tempFile) } catch (ignored: Exception) { } } } } // returns `true` when `checkConfig` is requested and config import is needed private fun CoroutineScope.lockSystemDirs(configImportNeededDeferred: Job, pathDeferred: Deferred<Pair<Path, Path>>, args: List<String>, mainScope: CoroutineScope): Job { if (socketLock != null) { throw AssertionError("Already initialized") } return launch(Dispatchers.IO) { val (configPath, systemPath) = pathDeferred.await() configImportNeededDeferred.join() runActivity("system dirs locking") { // this check must be performed before system directories are locked socketLock = SocketLock(configPath, systemPath) val status = socketLock!!.lockAndTryActivate(args = args, mainScope = mainScope) when (status.first) { ActivationStatus.NO_INSTANCE -> { ShutDownTracker.getInstance().registerShutdownTask { synchronized(AppStarter::class.java) { socketLock!!.dispose() socketLock = null } } } ActivationStatus.ACTIVATED -> { val result = status.second!! println(result.message ?: "Already running") exitProcess(result.exitCode) } ActivationStatus.CANNOT_ACTIVATE -> { val message = BootstrapBundle.message("bootstrap.error.message.only.one.instance.of.0.can.be.run.at.a.time", ApplicationNamesInfo.getInstance().productName) StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.too.many.instances"), message, true) exitProcess(AppExitCodes.INSTANCE_CHECK_FAILED) } } } } } private fun CoroutineScope.setupLogger(consoleLoggerJob: Job, checkSystemDirJob: Job): Deferred<Logger> { return async { consoleLoggerJob.join() checkSystemDirJob.join() runActivity("file logger configuration") { try { Logger.setFactory(LoggerFactory()) } catch (e: Exception) { e.printStackTrace() } val log = Logger.getInstance(AppStarter::class.java) log.info(IDE_STARTED) ShutDownTracker.getInstance().registerShutdownTask { log.info(IDE_SHUTDOWN) } if (java.lang.Boolean.parseBoolean(System.getProperty("intellij.log.stdout", "true"))) { System.setOut(PrintStreamLogger("STDOUT", System.out)) System.setErr(PrintStreamLogger("STDERR", System.err)) } log } } } @Suppress("SpellCheckingInspection") private fun setupSystemLibraries() { val ideTempPath = PathManager.getTempPath() if (System.getProperty("jna.tmpdir") == null) { // to avoid collisions and work around no-exec /tmp System.setProperty("jna.tmpdir", ideTempPath) } if (System.getProperty("jna.nosys") == null) { // prefer bundled JNA dispatcher lib System.setProperty("jna.nosys", "true") } if (SystemInfoRt.isWindows && System.getProperty("winp.folder.preferred") == null) { System.setProperty("winp.folder.preferred", ideTempPath) } if (System.getProperty("pty4j.tmpdir") == null) { System.setProperty("pty4j.tmpdir", ideTempPath) } if (System.getProperty("pty4j.preferred.native.folder") == null) { System.setProperty("pty4j.preferred.native.folder", Path.of(PathManager.getLibPath(), "pty4j-native").toAbsolutePath().toString()) } } private fun logEssentialInfoAboutIde(log: Logger, appInfo: ApplicationInfo, args: List<String>) { val buildDate = SimpleDateFormat("dd MMM yyyy HH:mm", Locale.US).format(appInfo.buildDate.time) log.info("IDE: ${ApplicationNamesInfo.getInstance().fullProductName} (build #${appInfo.build.asString()}, $buildDate)") log.info("OS: ${SystemInfoRt.OS_NAME} (${SystemInfoRt.OS_VERSION}, ${System.getProperty("os.arch")})") log.info("JRE: ${System.getProperty("java.runtime.version", "-")} (${System.getProperty("java.vendor", "-")})") log.info("JVM: ${System.getProperty("java.vm.version", "-")} (${System.getProperty("java.vm.name", "-")})") log.info("PID: ${ProcessHandle.current().pid()}") if (SystemInfoRt.isXWindow) { log.info("desktop: ${System.getenv("XDG_CURRENT_DESKTOP")}") } ManagementFactory.getRuntimeMXBean().inputArguments?.let { log.info("JVM options: $it") } log.info("args: ${args.joinToString(separator = " ")}") log.info("library path: ${System.getProperty("java.library.path")}") log.info("boot library path: ${System.getProperty("sun.boot.library.path")}") logEnvVar(log, "_JAVA_OPTIONS") logEnvVar(log, "JDK_JAVA_OPTIONS") logEnvVar(log, "JAVA_TOOL_OPTIONS") log.info( """locale=${Locale.getDefault()} JNU=${System.getProperty("sun.jnu.encoding")} file.encoding=${System.getProperty("file.encoding")} ${PathManager.PROPERTY_CONFIG_PATH}=${logPath(PathManager.getConfigPath())} ${PathManager.PROPERTY_SYSTEM_PATH}=${logPath(PathManager.getSystemPath())} ${PathManager.PROPERTY_PLUGINS_PATH}=${logPath(PathManager.getPluginsPath())} ${PathManager.PROPERTY_LOG_PATH}=${logPath(PathManager.getLogPath())}""" ) val cores = Runtime.getRuntime().availableProcessors() val pool = ForkJoinPool.commonPool() log.info("CPU cores: $cores; ForkJoinPool.commonPool: $pool; factory: ${pool.factory}") } private fun logEnvVar(log: Logger, variable: String) { val value = System.getenv(variable) if (value != null) { log.info("$variable=$value") } } private fun logPath(path: String): String { try { val configured = Path.of(path) val real = configured.toRealPath() if (configured != real) { return "$path -> $real" } } catch (ignored: IOException) { } catch (ignored: InvalidPathException) { } return path } fun runStartupWizard() { val stepsDialogName = ApplicationInfoImpl.getShadowInstance().welcomeWizardDialog ?: return try { val dialogClass = Class.forName(stepsDialogName) val ctor = dialogClass.getConstructor(AppStarter::class.java) (ctor.newInstance(null) as CommonCustomizeIDEWizardDialog).showIfNeeded() } catch (e: Throwable) { StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.configuration.wizard.failed"), e) return } PluginManagerCore.invalidatePlugins() PluginManagerCore.scheduleDescriptorLoading(ComponentManagerImpl.mainScope!!) } // the method must be called on EDT private fun patchSystem(isHeadless: Boolean) { var activity = StartUpMeasurer.startActivity("event queue replacing") // replace system event queue IdeEventQueue.getInstance() if (!isHeadless && "true" == System.getProperty("idea.check.swing.threading")) { activity = activity.endAndStart("repaint manager set") RepaintManager.setCurrentManager(AssertiveRepaintManager()) } // do not crash AWT on exceptions AWTExceptionHandler.register() activity.end() } fun canonicalPath(path: String): Path { return try { // `toRealPath` doesn't restore a canonical file name on case-insensitive UNIX filesystems Path.of(File(path).canonicalPath) } catch (ignore: IOException) { val file = Path.of(path) try { file.toAbsolutePath() } catch (ignored: IOError) { } file.normalize() } } interface AppStarter { fun prepareStart(args: List<String>) {} /* called from IDE init thread */ suspend fun start(args: List<String>, appDeferred: Deferred<Any>) /* called from IDE init thread */ fun beforeImportConfigs() {} /* called from IDE init thread */ fun importFinished(newConfigDir: Path) {} } class Java11ShimImpl : Java11Shim() { override fun <K : Any, V : Any> copyOf(map: Map<out K, V>): Map<K, V> = java.util.Map.copyOf(map) override fun <E : Any> copyOf(collection: Set<E>): Set<E> = java.util.Set.copyOf(collection) override fun <E : Any> copyOfCollection(collection: Collection<E>): List<E> = java.util.List.copyOf(collection) }
platform/platform-impl/src/com/intellij/idea/StartupUtil.kt
1604541304
package com.kelsos.mbrc.repository.data import com.kelsos.mbrc.data.db.RemoteDatabase import com.kelsos.mbrc.data.library.Genre import com.kelsos.mbrc.data.library.Genre_Table import com.kelsos.mbrc.di.modules.AppDispatchers import com.kelsos.mbrc.extensions.escapeLike import com.raizlabs.android.dbflow.kotlinextensions.database import com.raizlabs.android.dbflow.kotlinextensions.delete import com.raizlabs.android.dbflow.kotlinextensions.from import com.raizlabs.android.dbflow.kotlinextensions.modelAdapter import com.raizlabs.android.dbflow.kotlinextensions.select import com.raizlabs.android.dbflow.kotlinextensions.where import com.raizlabs.android.dbflow.list.FlowCursorList import com.raizlabs.android.dbflow.sql.language.OperatorGroup.clause import com.raizlabs.android.dbflow.sql.language.SQLite import com.raizlabs.android.dbflow.structure.database.transaction.FastStoreModelTransaction import kotlinx.coroutines.withContext import javax.inject.Inject class LocalGenreDataSource @Inject constructor(private val dispatchers: AppDispatchers) : LocalDataSource<Genre> { override suspend fun deleteAll() = withContext(dispatchers.db) { delete(Genre::class).execute() } override suspend fun saveAll(list: List<Genre>) = withContext(dispatchers.db) { val adapter = modelAdapter<Genre>() val transaction = FastStoreModelTransaction.insertBuilder(adapter) .addAll(list) .build() database<RemoteDatabase>().executeTransaction(transaction) } override suspend fun loadAllCursor(): FlowCursorList<Genre> = withContext(dispatchers.db) { val query = (select from Genre::class).orderBy(Genre_Table.genre, true) return@withContext FlowCursorList.Builder(Genre::class.java).modelQueriable(query).build() } override suspend fun search(term: String): FlowCursorList<Genre> = withContext(dispatchers.db) { val query = (select from Genre::class where Genre_Table.genre.like("%${term.escapeLike()}%")) .orderBy(Genre_Table.genre, true) return@withContext FlowCursorList.Builder(Genre::class.java).modelQueriable(query).build() } override suspend fun isEmpty(): Boolean = withContext(dispatchers.db) { return@withContext SQLite.selectCountOf().from(Genre::class.java).longValue() == 0L } override suspend fun count(): Long = withContext(dispatchers.db) { return@withContext SQLite.selectCountOf().from(Genre::class.java).longValue() } override suspend fun removePreviousEntries(epoch: Long) { withContext(dispatchers.io) { SQLite.delete() .from(Genre::class.java) .where(clause(Genre_Table.date_added.lessThan(epoch)).or(Genre_Table.date_added.isNull)) .execute() } } }
app/src/main/kotlin/com/kelsos/mbrc/repository/data/LocalGenreDataSource.kt
334724126
/* * NextfareConfigRecord.kt * * Copyright 2016-2019 Michael Farrell <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.nextfare.record import au.id.micolous.metrodroid.multi.Log import au.id.micolous.metrodroid.multi.Parcelable import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.time.MetroTimeZone import au.id.micolous.metrodroid.time.Timestamp import au.id.micolous.metrodroid.util.ImmutableByteArray import au.id.micolous.metrodroid.util.hexString /** * Represents a configuration record on Nextfare MFC. * https://github.com/micolous/metrodroid/wiki/Cubic-Nextfare-MFC */ @Parcelize class NextfareConfigRecord (val ticketType: Int, val expiry: Timestamp): NextfareRecord, Parcelable { companion object { private const val TAG = "NextfareConfigRecord" fun recordFromBytes(input: ImmutableByteArray, timeZone: MetroTimeZone): NextfareConfigRecord { //if (input[0] != 0x01) throw new AssertionError(); // Expiry date val record = NextfareConfigRecord( expiry = NextfareRecord.unpackDate(input, 4, timeZone), // Treat ticket type as little-endian ticketType = input.byteArrayToIntReversed(8, 2) ) Log.d(TAG, "Ticket type = ${record.ticketType.hexString}, expires ${record.expiry}") return record } } }
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/nextfare/record/NextfareConfigRecord.kt
2874237951
/* * 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.google.samples.apps.nowinandroid.core.data.test import com.google.samples.apps.nowinandroid.core.data.util.NetworkMonitor import javax.inject.Inject import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf class AlwaysOnlineNetworkMonitor @Inject constructor() : NetworkMonitor { override val isOnline: Flow<Boolean> = flowOf(true) }
core/data-test/src/main/java/com/google/samples/apps/nowinandroid/core/data/test/AlwaysOnlineNetworkMonitor.kt
2373231215
package com.eden.orchid.api.resources.resource import com.eden.orchid.api.OrchidContext import java.io.InputStream /** * A Resource type that wraps another resource, optionally applying a transformation along the way. */ abstract class ResourceWrapper(private val resource: OrchidResource) : OrchidResource(resource.reference) { override fun getContentStream(): InputStream { return resource.getContentStream() } override fun shouldPrecompile(): Boolean { return resource.shouldPrecompile() } override fun shouldRender(): Boolean { return resource.shouldRender() } override fun compileContent(context: OrchidContext, data: Any?): String { return resource.compileContent(context, data) } override val precompilerExtension: String get() = resource.precompilerExtension override fun canUpdate(): Boolean { return resource.canUpdate() } override fun canDelete(): Boolean { return resource.canDelete() } override fun update(newContent: InputStream) { resource.update(newContent) } override fun delete() { resource.delete() } override fun toString(): String { return resource.toString() } override val content: String get() = resource.content override val embeddedData: Map<String, Any?> get() = resource.embeddedData override fun free() { resource.free() } override fun equals(other: Any?): Boolean { return resource.equals(other) } override fun hashCode(): Int { return resource.hashCode() } }
OrchidCore/src/main/kotlin/com/eden/orchid/api/resources/resource/ResourceWrapper.kt
1901935804
// EXTRACTION_TARGET: property with initializer class A(val n: Int = 1) { val m: Int = 2 fun foo(): Int { return <selection>m + n + 1</selection> } }
plugins/kotlin/idea/tests/testData/refactoring/introduceProperty/extractWithInitializerToClass.kt
623524877
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.j2k.post.processing.processings import com.intellij.psi.PsiElement import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.idea.j2k.post.processing.ElementsBasedPostProcessing import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.BoundTypeCalculatorImpl import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ByInfoSuperFunctionsProvider import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintsCollectorAggregator import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.InferenceFacade import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.CallExpressionConstraintCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.CommonConstraintsCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.FunctionConstraintsCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.mutability.* import org.jetbrains.kotlin.idea.j2k.post.processing.inference.nullability.* import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.psi.KtElement internal abstract class InferenceProcessing : ElementsBasedPostProcessing() { override fun runProcessing(elements: List<PsiElement>, converterContext: NewJ2kConverterContext) { val kotlinElements = elements.filterIsInstance<KtElement>() if (kotlinElements.isEmpty()) return val resolutionFacade = runReadAction { KotlinCacheService.getInstance(converterContext.project).getResolutionFacade(kotlinElements) } createInferenceFacade(resolutionFacade, converterContext).runOn(kotlinElements) } abstract fun createInferenceFacade( resolutionFacade: ResolutionFacade, converterContext: NewJ2kConverterContext ): InferenceFacade } internal class NullabilityInferenceProcessing : InferenceProcessing() { override fun createInferenceFacade( resolutionFacade: ResolutionFacade, converterContext: NewJ2kConverterContext ): InferenceFacade = InferenceFacade( NullabilityContextCollector(resolutionFacade, converterContext), ConstraintsCollectorAggregator( resolutionFacade, NullabilityConstraintBoundProvider(), listOf( CommonConstraintsCollector(), CallExpressionConstraintCollector(), FunctionConstraintsCollector(ByInfoSuperFunctionsProvider(resolutionFacade, converterContext)), NullabilityConstraintsCollector() ) ), BoundTypeCalculatorImpl(resolutionFacade, NullabilityBoundTypeEnhancer(resolutionFacade)), NullabilityStateUpdater(), NullabilityDefaultStateProvider() ) } internal class MutabilityInferenceProcessing : InferenceProcessing() { override fun createInferenceFacade( resolutionFacade: ResolutionFacade, converterContext: NewJ2kConverterContext ): InferenceFacade = InferenceFacade( MutabilityContextCollector(resolutionFacade, converterContext), ConstraintsCollectorAggregator( resolutionFacade, MutabilityConstraintBoundProvider(), listOf( CommonConstraintsCollector(), CallExpressionConstraintCollector(), FunctionConstraintsCollector(ByInfoSuperFunctionsProvider(resolutionFacade, converterContext)), MutabilityConstraintsCollector() ) ), MutabilityBoundTypeCalculator(resolutionFacade, MutabilityBoundTypeEnhancer()), MutabilityStateUpdater(), MutabilityDefaultStateProvider() ) }
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/processings/InferenceProcessing.kt
3933824906
// "Create class 'Foo'" "true" // ERROR: Unresolved reference: Foo fun test() { val a = J.<caret>Foo(2) }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/callExpression/callWithJavaClassQualifier.before.Main.kt
2085146645
package co.timecrypt.android.activities import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v4.text.util.LinkifyCompat import android.support.v7.app.AppCompatActivity import android.text.util.Linkify import android.util.Log import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.Toast import co.timecrypt.android.R import co.timecrypt.android.v2.api.TimecryptController import kotlinx.android.synthetic.main.activity_read_message.* /** * An activity that handles displaying (and unlocking) for one Timecrypt message. */ class ReadMessageActivity : AppCompatActivity(), View.OnClickListener { @Suppress("PrivatePropertyName") private val TAG = ReadMessageActivity::class.simpleName!! companion object { const val KEY_MESSAGE_ID = "MESSAGE_ID" } private var controller: TimecryptController? = null private var messageId: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // check preconditions, must find a message ID val extras = intent.extras val uri = intent.data if (extras == null && uri == null) { Log.e(TAG, "No URL data provided") finish() return } messageId = extras?.getString(KEY_MESSAGE_ID, null) ?: parseMessageUrl(uri) if (messageId == null) { Log.e(TAG, "No message ID provided") finish() return } setContentView(R.layout.activity_read_message) // activity is ready, create business logic components controller = TimecryptController(TimecryptController.Companion.DEFAULT_API_URL) controller?.lockCheck(this, messageId!!, lockCheckListener) // setup initial Views progressOverlay.visibility = View.VISIBLE listOf(buttonCancel, buttonCreateNew, buttonUnlock).forEach { it.setOnClickListener(this) } } /** * Tries to find the message ID by parsing the given [Uri]. * * @param url An Intent [Uri] that represents the message link */ private fun parseMessageUrl(url: Uri?): String? { try { if (url == null) return null val query = url.query ?: return null query.split("&").forEach { val param = it.split("=") if (param[0].trim() == "c" || param[0].trim() == "id") { return param[1].trim() } } return null } catch (t: Throwable) { return null } } override fun onClick(view: View) { when (view.id) { buttonCancel.id -> { stopReading() finish() } buttonCreateNew.id -> { startActivity(Intent(this, CreateMessageActivity::class.java)) finish() } buttonUnlock.id -> { currentFocus?.let { val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManager.hideSoftInputFromWindow(it.windowToken, 0) } progressOverlay.visibility = View.VISIBLE readMessagePassword.visibility = View.GONE buttonUnlock.visibility = View.GONE controller?.read(this, messageId!!, readMessagePassword.text.toString(), readCompleteListener) readMessagePassword.setText("") readInformation.text = "" } } } /** * Used to listen for changes from the [TimecryptController.lockCheck] operation. */ private val lockCheckListener = object : TimecryptController.LockCheckListener { override fun onLockCheckCompleted(locked: Boolean) { if (locked) { progressOverlay.visibility = View.GONE readMessagePassword.visibility = View.VISIBLE buttonUnlock.visibility = View.VISIBLE readInformation.text = getString(R.string.read_locked) } else { controller?.read(this@ReadMessageActivity, messageId!!, null, readCompleteListener) } } override fun onLockCheckFailed(message: String) { Log.e(TAG, message) progressOverlay.visibility = View.GONE Toast.makeText(this@ReadMessageActivity, message, Toast.LENGTH_LONG).show() finish() } } /** * Used to listen for changes from the [TimecryptController.read] operation. */ private val readCompleteListener = object : TimecryptController.ReadCompleteListener { override fun onReadComplete(text: String, title: String?, destructDate: String, views: Int) { progressOverlay.visibility = View.GONE buttonCreateNew.visibility = View.VISIBLE val viewsCount = resources.getQuantityString(R.plurals.views_left, views, views) readInformation.text = getString(R.string.read_info, viewsCount, destructDate) // append title on top if present var finalText = text title?.let { finalText = "- $it -\n\n$finalText" } readMessageText.text = finalText LinkifyCompat.addLinks(readMessageText, Linkify.WEB_URLS) readMessageText.visibility = View.VISIBLE } override fun onReadFailed(message: String) { Log.e(TAG, message) progressOverlay.visibility = View.GONE Toast.makeText(this@ReadMessageActivity, message, Toast.LENGTH_LONG).show() finish() } } private fun stopReading() { controller?.stopAll() progressOverlay.visibility = View.GONE } override fun onStop() { super.onStop() stopReading() } }
Android/app/src/main/java/co/timecrypt/android/activities/ReadMessageActivity.kt
657412803
/* * Ad Free * Copyright (c) 2017 by abertschi, www.abertschi.ch * See the file "LICENSE" for the full license governing this code. */ package ch.abertschi.adfree.detector /** * Created by abertschi on 17.04.17. * * Detector which checks for number of control buttons */ class NotificationActionDetector : AbstractSpStatusBarDetector() { override fun canHandle(payload: AdPayload): Boolean = super.canHandle(payload) && payload?.statusbarNotification?.notification?.actions != null override fun flagAsAdvertisement(payload: AdPayload): Boolean = payload.statusbarNotification.notification.actions.size <= 3 override fun getMeta(): AdDetectorMeta = AdDetectorMeta( "Notification actions", "spotify generic inspection of notification actions", category = "Spotify" ) }
app/src/main/java/ch/abertschi/adfree/detector/NotificationActionDetector.kt
2398933567
package project2 import java.io.* class FileHandler { fun getReader(path: String): Reader { return InputStreamReader(this.javaClass.getResourceAsStream(path),"UTF-8") } fun getWriter(path: String): Writer { val file = File(path) return FileWriter(file) } }
src/main/kotlin/project2/FileHandler.kt
20544781