content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.ddu.ui.activity.phrase import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.text.style.StrikethroughSpan import android.text.style.StyleSpan import android.text.style.UnderlineSpan import androidx.appcompat.app.AppCompatActivity import com.ddu.R import com.ddu.icore.util.StylePhrase import kotlinx.android.synthetic.main.activity_one_separator.* class TwoSeparatorActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_one_separator) val twoSeparatorString = getString(R.string.text_phrase_two) tv_description.text = "二种分割符" tv_original.text = twoSeparatorString // 设置字体和颜色 val colorAndSize = StylePhrase(twoSeparatorString) .setInnerFirstColor(Color.BLUE) .setInnerFirstSize(20) .setInnerSecondColor(Color.RED) .setInnerSecondSize(25) tv_content.text = colorAndSize.format() // 设置粗斜体 val boldPhrase = StylePhrase(twoSeparatorString) boldPhrase.setInnerFirstColor(Color.RED) boldPhrase.setInnerSecondColor(Color.BLUE) boldPhrase.setInnerSecondSize(13) boldPhrase.secondBuilder.addParcelableSpan(StyleSpan(Typeface.BOLD_ITALIC)) tv_content_bold_italic.text = boldPhrase.format() // 设置删除线 val strikeThroughPhrase = StylePhrase(twoSeparatorString) strikeThroughPhrase.firstBuilder.setColor(Color.BLUE) strikeThroughPhrase.firstBuilder.addParcelableSpan(StrikethroughSpan()) strikeThroughPhrase.setInnerSecondSize(25) tv_content_strike_through.text = strikeThroughPhrase.format() // 设置下划线 val underlinePhrase = StylePhrase(twoSeparatorString) underlinePhrase.secondBuilder.addParcelableSpan(UnderlineSpan()) tv_content_underline.text = underlinePhrase.format() tv_separator.text = "${colorAndSize.firstBuilder.separator} ${colorAndSize.secondBuilder.separator}" } }
app/src/main/java/com/ddu/ui/activity/phrase/TwoSeparatorActivity.kt
736901071
package org.goskyer.service.impl import org.goskyer.domain.User import org.goskyer.mapping.UserMapper import org.goskyer.security.JwtTokenUtils import org.goskyer.service.UserSer import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.stereotype.Service /** * Created by zohar on 2017/3/31. * desc: */ @Service public class UserSerImpl : UserSer { private lateinit var userMapper: UserMapper; private lateinit var jwtTokenUtil: JwtTokenUtils private lateinit var authenticationManager: AuthenticationManager private lateinit var userDetailsService: UserDetailsService @Autowired constructor(userMapper: UserMapper, jwtTokenUtil: JwtTokenUtils, authenticationManager: AuthenticationManager, userDetailsService: UserDetailsService) { this.userMapper = userMapper this.jwtTokenUtil = jwtTokenUtil this.authenticationManager = authenticationManager this.userDetailsService = userDetailsService } override fun register(user: User): Int? { var userEmail = user.userEmail if (userMapper.selectByEmail(userEmail!!) !== null) { throw RuntimeException("该邮箱已被注册") } val bCryptPasswordEncoder = BCryptPasswordEncoder() user.password = bCryptPasswordEncoder.encode(user.password) user.role = "ROLE_USER" return userMapper.insert(user) } override fun getUsers(): List<User> { var a: List<String> return userMapper.selectAll(); } override fun selectByEmail(email: String): User? { return userMapper.selectByEmail(email) } override fun login(email: String, password: String): String { var authenticationToken = UsernamePasswordAuthenticationToken(email, password)//根据用户名密码获取authenticationToken //根据authenticationToken获取authenticate 这个里面存储每个用户对应的信息,用户名密码不对获取不到会抛出异常 var authenticate = authenticationManager.authenticate(authenticationToken) SecurityContextHolder.getContext().authentication = authenticate// 保存到SecurityContextHolder里 // 生成登陆用的token val userDetail = userDetailsService.loadUserByUsername(email) val token = jwtTokenUtil.generateToken(userDetailsService.loadUserByUsername(email)) return token } }
src/main/kotlin/org/goskyer/service/impl/UserSerImpl.kt
2898940284
/* * 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.resourceinspection.processor import com.squareup.javapoet.ClassName import javax.lang.model.element.AnnotationMirror import javax.lang.model.element.ExecutableElement import javax.lang.model.element.TypeElement /** Represents a view with annotated attributes, mostly a convenience class. */ internal data class View( val type: TypeElement, val attributes: List<Attribute> ) { val className: ClassName = ClassName.get(type) } @JvmDefaultWithCompatibility internal interface Attribute { val name: String val namespace: String val type: AttributeType val intMapping: List<IntMap> val invocation: String val qualifiedName: String get() = "$namespace:$name" } /** Represents an `Attribute` with its getter. */ internal data class GetterAttribute( val getter: ExecutableElement, val annotation: AnnotationMirror, override val namespace: String, override val name: String, override val type: AttributeType, override val intMapping: List<IntMap> = emptyList() ) : Attribute { override val invocation: String get() = "${getter.simpleName}()" } /** * Represents a shadowed platform attribute in a different namespace, mainly for AppCompat. * * The constructor has some reasonable defaults to make defining these as constants less toilsome. */ internal data class ShadowedAttribute( override val name: String, override val invocation: String, override val type: AttributeType = AttributeType.OBJECT, override val intMapping: List<IntMap> = emptyList(), override val namespace: String = "androidx.appcompat" ) : Attribute /** Represents an `Attribute.IntMap` entry. */ internal data class IntMap( val name: String, val value: Int, val mask: Int = 0, val annotation: AnnotationMirror? = null ) /** Represents the type of the attribute, determined from context and the annotation itself. */ internal enum class AttributeType(val apiSuffix: String) { BOOLEAN("Boolean"), BYTE("Byte"), CHAR("Char"), DOUBLE("Double"), FLOAT("Float"), INT("Int"), LONG("Long"), SHORT("Short"), OBJECT("Object"), COLOR("Color"), GRAVITY("Gravity"), RESOURCE_ID("ResourceId"), INT_FLAG("IntFlag"), INT_ENUM("IntEnum") }
resourceinspection/resourceinspection-processor/src/main/kotlin/androidx/resourceinspection/processor/Models.kt
649216669
/* * 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.camera.core.imagecapture import android.graphics.ImageFormat import android.graphics.Matrix import android.graphics.Rect import android.os.Build import android.util.Pair import android.util.Size import androidx.camera.core.ImageCapture import androidx.camera.core.ImageInfo import androidx.camera.core.ImageProxy import androidx.camera.core.impl.CaptureBundle import androidx.camera.core.impl.ImageCaptureConfig import androidx.camera.core.impl.ImageInputConfig import androidx.camera.core.impl.TagBundle import androidx.camera.core.internal.CameraCaptureResultImageInfo import androidx.camera.testing.fakes.FakeCameraCaptureResult import androidx.camera.testing.fakes.FakeCaptureStage import androidx.camera.testing.fakes.FakeImageProxy import java.io.File import java.util.UUID import org.robolectric.util.ReflectionHelpers.setStaticField /** * Utility methods for testing image capture. */ object Utils { internal const val WIDTH = 640 internal const val HEIGHT = 480 internal const val EXIF_DESCRIPTION = "description" internal const val ROTATION_DEGREES = 180 internal const val ALTITUDE = 0.1 internal const val JPEG_QUALITY = 90 internal const val TIMESTAMP = 9999L internal val SENSOR_TO_BUFFER = Matrix().also { it.setScale(-1F, 1F, 320F, 240F) } internal val SIZE = Size(WIDTH, HEIGHT) // The crop rect is the lower half of the image. internal val CROP_RECT = Rect(0, 240, WIDTH, HEIGHT) internal val FULL_RECT = Rect(0, 0, WIDTH, HEIGHT) internal val TEMP_FILE = File.createTempFile( "unit_test_" + UUID.randomUUID().toString(), ".temp" ).also { it.deleteOnExit() } internal val OUTPUT_FILE_OPTIONS = ImageCapture.OutputFileOptions.Builder( TEMP_FILE ).build() internal val CAMERA_CAPTURE_RESULT = FakeCameraCaptureResult().also { it.timestamp = TIMESTAMP } internal fun createProcessingRequest( takePictureCallback: TakePictureCallback = FakeTakePictureCallback() ): ProcessingRequest { return ProcessingRequest( { listOf() }, OUTPUT_FILE_OPTIONS, CROP_RECT, ROTATION_DEGREES, /*jpegQuality=*/100, SENSOR_TO_BUFFER, takePictureCallback ) } /** * Inject a ImageCaptureRotationOptionQuirk. */ fun injectRotationOptionQuirk() { setStaticField(Build::class.java, "BRAND", "HUAWEI") setStaticField(Build::class.java, "MODEL", "SNE-LX1") } /** * Creates an empty [ImageCaptureConfig] so [ImagePipeline] constructor won't crash. */ fun createEmptyImageCaptureConfig(): ImageCaptureConfig { val builder = ImageCapture.Builder().setCaptureOptionUnpacker { _, _ -> } builder.mutableConfig.insertOption(ImageInputConfig.OPTION_INPUT_FORMAT, ImageFormat.JPEG) return builder.useCaseConfig } fun createCaptureBundle(stageIds: IntArray): CaptureBundle { return CaptureBundle { stageIds.map { stageId -> FakeCaptureStage(stageId, null) } } } fun createFakeImage(tagBundleKey: String, stageId: Int): ImageProxy { return FakeImageProxy(createCameraCaptureResultImageInfo(tagBundleKey, stageId)) } fun createCameraCaptureResultImageInfo(tagBundleKey: String, stageId: Int): ImageInfo { return CameraCaptureResultImageInfo(FakeCameraCaptureResult().also { it.setTag(TagBundle.create(Pair(tagBundleKey, stageId))) }) } }
camera/camera-core/src/test/java/androidx/camera/core/imagecapture/Utils.kt
4003936912
package com.antyzero.cardcheck.ui.inputfilter import android.text.InputFilter import android.text.SpannableString import android.text.Spanned import android.text.TextUtils object OnlyDigitsInputFilter : InputFilter { override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence? { val stringBuilder = StringBuilder() (start until end) .filter { source[it].isDigit() } .forEach { stringBuilder.append(source[it]) } val string = stringBuilder.toString() return if (source is Spanned) { val spannableString = SpannableString(string) TextUtils.copySpansFrom(source, start, end, null, spannableString, 0) spannableString } else { string } } }
app/src/main/kotlin/com/antyzero/cardcheck/ui/inputfilter/OnlyDigitsInputFilter.kt
4201316635
package com.github.willjgriff.ethereumwallet.utils.resettablelazy import java.util.* /** * Created by williamgriffiths on 28/04/2017. */ class ResettableLazyManager { // we synchronize to make sure the timing of a reset() call and new inits do not collide val managedDelegates = LinkedList<Resettable>() fun register(managed: Resettable) { synchronized (managedDelegates) { managedDelegates.add(managed) } } fun reset() { synchronized (managedDelegates) { managedDelegates.forEach { it.reset() } managedDelegates.clear() } } interface Resettable { fun reset() } }
app/src/main/kotlin/com/github/willjgriff/ethereumwallet/utils/resettablelazy/ResettableLazyManager.kt
2860512144
package com.irateam.vkplayer.fragment import android.os.Bundle import com.irateam.vkplayer.R import com.irateam.vkplayer.api.Query import com.irateam.vkplayer.model.VKAudio class VKRecommendationAudioFragment : VKAudioListFragment() { override lateinit var query: Query<List<VKAudio>> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) query = audioService.getRecommendation() } override fun getTitleRes(): Int { return R.string.navigation_drawer_recommendation } companion object { @JvmStatic fun newInstance() = VKRecommendationAudioFragment() } }
app/src/main/java/com/irateam/vkplayer/fragment/VKRecommendationAudioFragment.kt
2075474877
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.psi.mixins import com.demonwav.mcdev.nbt.lang.psi.NbttElement import com.demonwav.mcdev.nbt.tags.TagLong interface NbttLongMixin : NbttElement { fun getLongTag(): TagLong }
src/main/kotlin/nbt/lang/psi/mixins/NbttLongMixin.kt
2205222170
// automatically generated by the FlatBuffers compiler, do not modify package optional_scalars import java.nio.* import kotlin.math.sign import com.google.flatbuffers.* @Suppress("unused") @ExperimentalUnsignedTypes class ScalarStuff : Table() { fun __init(_i: Int, _bb: ByteBuffer) { __reset(_i, _bb) } fun __assign(_i: Int, _bb: ByteBuffer) : ScalarStuff { __init(_i, _bb) return this } val justI8 : Byte get() { val o = __offset(4) return if(o != 0) bb.get(o + bb_pos) else 0 } val maybeI8 : Byte? get() { val o = __offset(6) return if(o != 0) bb.get(o + bb_pos) else null } val defaultI8 : Byte get() { val o = __offset(8) return if(o != 0) bb.get(o + bb_pos) else 42 } val justU8 : UByte get() { val o = __offset(10) return if(o != 0) bb.get(o + bb_pos).toUByte() else 0u } val maybeU8 : UByte? get() { val o = __offset(12) return if(o != 0) bb.get(o + bb_pos).toUByte() else null } val defaultU8 : UByte get() { val o = __offset(14) return if(o != 0) bb.get(o + bb_pos).toUByte() else 42u } val justI16 : Short get() { val o = __offset(16) return if(o != 0) bb.getShort(o + bb_pos) else 0 } val maybeI16 : Short? get() { val o = __offset(18) return if(o != 0) bb.getShort(o + bb_pos) else null } val defaultI16 : Short get() { val o = __offset(20) return if(o != 0) bb.getShort(o + bb_pos) else 42 } val justU16 : UShort get() { val o = __offset(22) return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u } val maybeU16 : UShort? get() { val o = __offset(24) return if(o != 0) bb.getShort(o + bb_pos).toUShort() else null } val defaultU16 : UShort get() { val o = __offset(26) return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 42u } val justI32 : Int get() { val o = __offset(28) return if(o != 0) bb.getInt(o + bb_pos) else 0 } val maybeI32 : Int? get() { val o = __offset(30) return if(o != 0) bb.getInt(o + bb_pos) else null } val defaultI32 : Int get() { val o = __offset(32) return if(o != 0) bb.getInt(o + bb_pos) else 42 } val justU32 : UInt get() { val o = __offset(34) return if(o != 0) bb.getInt(o + bb_pos).toUInt() else 0u } val maybeU32 : UInt? get() { val o = __offset(36) return if(o != 0) bb.getInt(o + bb_pos).toUInt() else null } val defaultU32 : UInt get() { val o = __offset(38) return if(o != 0) bb.getInt(o + bb_pos).toUInt() else 42u } val justI64 : Long get() { val o = __offset(40) return if(o != 0) bb.getLong(o + bb_pos) else 0L } val maybeI64 : Long? get() { val o = __offset(42) return if(o != 0) bb.getLong(o + bb_pos) else null } val defaultI64 : Long get() { val o = __offset(44) return if(o != 0) bb.getLong(o + bb_pos) else 42L } val justU64 : ULong get() { val o = __offset(46) return if(o != 0) bb.getLong(o + bb_pos).toULong() else 0UL } val maybeU64 : ULong? get() { val o = __offset(48) return if(o != 0) bb.getLong(o + bb_pos).toULong() else null } val defaultU64 : ULong get() { val o = __offset(50) return if(o != 0) bb.getLong(o + bb_pos).toULong() else 42UL } val justF32 : Float get() { val o = __offset(52) return if(o != 0) bb.getFloat(o + bb_pos) else 0.0f } val maybeF32 : Float? get() { val o = __offset(54) return if(o != 0) bb.getFloat(o + bb_pos) else null } val defaultF32 : Float get() { val o = __offset(56) return if(o != 0) bb.getFloat(o + bb_pos) else 42.0f } val justF64 : Double get() { val o = __offset(58) return if(o != 0) bb.getDouble(o + bb_pos) else 0.0 } val maybeF64 : Double? get() { val o = __offset(60) return if(o != 0) bb.getDouble(o + bb_pos) else null } val defaultF64 : Double get() { val o = __offset(62) return if(o != 0) bb.getDouble(o + bb_pos) else 42.0 } val justBool : Boolean get() { val o = __offset(64) return if(o != 0) 0.toByte() != bb.get(o + bb_pos) else false } val maybeBool : Boolean? get() { val o = __offset(66) return if(o != 0) 0.toByte() != bb.get(o + bb_pos) else null } val defaultBool : Boolean get() { val o = __offset(68) return if(o != 0) 0.toByte() != bb.get(o + bb_pos) else true } val justEnum : Byte get() { val o = __offset(70) return if(o != 0) bb.get(o + bb_pos) else 0 } val maybeEnum : Byte? get() { val o = __offset(72) return if(o != 0) bb.get(o + bb_pos) else null } val defaultEnum : Byte get() { val o = __offset(74) return if(o != 0) bb.get(o + bb_pos) else 1 } companion object { fun validateVersion() = Constants.FLATBUFFERS_1_12_0() fun getRootAsScalarStuff(_bb: ByteBuffer): ScalarStuff = getRootAsScalarStuff(_bb, ScalarStuff()) fun getRootAsScalarStuff(_bb: ByteBuffer, obj: ScalarStuff): ScalarStuff { _bb.order(ByteOrder.LITTLE_ENDIAN) return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) } fun ScalarStuffBufferHasIdentifier(_bb: ByteBuffer) : Boolean = __has_identifier(_bb, "NULL") fun createScalarStuff(builder: FlatBufferBuilder, justI8: Byte, maybeI8: Byte?, defaultI8: Byte, justU8: UByte, maybeU8: UByte?, defaultU8: UByte, justI16: Short, maybeI16: Short?, defaultI16: Short, justU16: UShort, maybeU16: UShort?, defaultU16: UShort, justI32: Int, maybeI32: Int?, defaultI32: Int, justU32: UInt, maybeU32: UInt?, defaultU32: UInt, justI64: Long, maybeI64: Long?, defaultI64: Long, justU64: ULong, maybeU64: ULong?, defaultU64: ULong, justF32: Float, maybeF32: Float?, defaultF32: Float, justF64: Double, maybeF64: Double?, defaultF64: Double, justBool: Boolean, maybeBool: Boolean?, defaultBool: Boolean, justEnum: Byte, maybeEnum: Byte?, defaultEnum: Byte) : Int { builder.startTable(36) addDefaultF64(builder, defaultF64) maybeF64?.run { addMaybeF64(builder, maybeF64) } addJustF64(builder, justF64) addDefaultU64(builder, defaultU64) maybeU64?.run { addMaybeU64(builder, maybeU64) } addJustU64(builder, justU64) addDefaultI64(builder, defaultI64) maybeI64?.run { addMaybeI64(builder, maybeI64) } addJustI64(builder, justI64) addDefaultF32(builder, defaultF32) maybeF32?.run { addMaybeF32(builder, maybeF32) } addJustF32(builder, justF32) addDefaultU32(builder, defaultU32) maybeU32?.run { addMaybeU32(builder, maybeU32) } addJustU32(builder, justU32) addDefaultI32(builder, defaultI32) maybeI32?.run { addMaybeI32(builder, maybeI32) } addJustI32(builder, justI32) addDefaultU16(builder, defaultU16) maybeU16?.run { addMaybeU16(builder, maybeU16) } addJustU16(builder, justU16) addDefaultI16(builder, defaultI16) maybeI16?.run { addMaybeI16(builder, maybeI16) } addJustI16(builder, justI16) addDefaultEnum(builder, defaultEnum) maybeEnum?.run { addMaybeEnum(builder, maybeEnum) } addJustEnum(builder, justEnum) addDefaultBool(builder, defaultBool) maybeBool?.run { addMaybeBool(builder, maybeBool) } addJustBool(builder, justBool) addDefaultU8(builder, defaultU8) maybeU8?.run { addMaybeU8(builder, maybeU8) } addJustU8(builder, justU8) addDefaultI8(builder, defaultI8) maybeI8?.run { addMaybeI8(builder, maybeI8) } addJustI8(builder, justI8) return endScalarStuff(builder) } fun startScalarStuff(builder: FlatBufferBuilder) = builder.startTable(36) fun addJustI8(builder: FlatBufferBuilder, justI8: Byte) = builder.addByte(0, justI8, 0) fun addMaybeI8(builder: FlatBufferBuilder, maybeI8: Byte) = builder.addByte(1, maybeI8, 0) fun addDefaultI8(builder: FlatBufferBuilder, defaultI8: Byte) = builder.addByte(2, defaultI8, 42) fun addJustU8(builder: FlatBufferBuilder, justU8: UByte) = builder.addByte(3, justU8.toByte(), 0) fun addMaybeU8(builder: FlatBufferBuilder, maybeU8: UByte) = builder.addByte(4, maybeU8.toByte(), 0) fun addDefaultU8(builder: FlatBufferBuilder, defaultU8: UByte) = builder.addByte(5, defaultU8.toByte(), 42) fun addJustI16(builder: FlatBufferBuilder, justI16: Short) = builder.addShort(6, justI16, 0) fun addMaybeI16(builder: FlatBufferBuilder, maybeI16: Short) = builder.addShort(7, maybeI16, 0) fun addDefaultI16(builder: FlatBufferBuilder, defaultI16: Short) = builder.addShort(8, defaultI16, 42) fun addJustU16(builder: FlatBufferBuilder, justU16: UShort) = builder.addShort(9, justU16.toShort(), 0) fun addMaybeU16(builder: FlatBufferBuilder, maybeU16: UShort) = builder.addShort(10, maybeU16.toShort(), 0) fun addDefaultU16(builder: FlatBufferBuilder, defaultU16: UShort) = builder.addShort(11, defaultU16.toShort(), 42) fun addJustI32(builder: FlatBufferBuilder, justI32: Int) = builder.addInt(12, justI32, 0) fun addMaybeI32(builder: FlatBufferBuilder, maybeI32: Int) = builder.addInt(13, maybeI32, 0) fun addDefaultI32(builder: FlatBufferBuilder, defaultI32: Int) = builder.addInt(14, defaultI32, 42) fun addJustU32(builder: FlatBufferBuilder, justU32: UInt) = builder.addInt(15, justU32.toInt(), 0) fun addMaybeU32(builder: FlatBufferBuilder, maybeU32: UInt) = builder.addInt(16, maybeU32.toInt(), 0) fun addDefaultU32(builder: FlatBufferBuilder, defaultU32: UInt) = builder.addInt(17, defaultU32.toInt(), 42) fun addJustI64(builder: FlatBufferBuilder, justI64: Long) = builder.addLong(18, justI64, 0L) fun addMaybeI64(builder: FlatBufferBuilder, maybeI64: Long) = builder.addLong(19, maybeI64, 0) fun addDefaultI64(builder: FlatBufferBuilder, defaultI64: Long) = builder.addLong(20, defaultI64, 42L) fun addJustU64(builder: FlatBufferBuilder, justU64: ULong) = builder.addLong(21, justU64.toLong(), 0) fun addMaybeU64(builder: FlatBufferBuilder, maybeU64: ULong) = builder.addLong(22, maybeU64.toLong(), 0) fun addDefaultU64(builder: FlatBufferBuilder, defaultU64: ULong) = builder.addLong(23, defaultU64.toLong(), 42) fun addJustF32(builder: FlatBufferBuilder, justF32: Float) = builder.addFloat(24, justF32, 0.0) fun addMaybeF32(builder: FlatBufferBuilder, maybeF32: Float) = builder.addFloat(25, maybeF32, 0.0) fun addDefaultF32(builder: FlatBufferBuilder, defaultF32: Float) = builder.addFloat(26, defaultF32, 42.0) fun addJustF64(builder: FlatBufferBuilder, justF64: Double) = builder.addDouble(27, justF64, 0.0) fun addMaybeF64(builder: FlatBufferBuilder, maybeF64: Double) = builder.addDouble(28, maybeF64, 0.0) fun addDefaultF64(builder: FlatBufferBuilder, defaultF64: Double) = builder.addDouble(29, defaultF64, 42.0) fun addJustBool(builder: FlatBufferBuilder, justBool: Boolean) = builder.addBoolean(30, justBool, false) fun addMaybeBool(builder: FlatBufferBuilder, maybeBool: Boolean) = builder.addBoolean(31, maybeBool, false) fun addDefaultBool(builder: FlatBufferBuilder, defaultBool: Boolean) = builder.addBoolean(32, defaultBool, true) fun addJustEnum(builder: FlatBufferBuilder, justEnum: Byte) = builder.addByte(33, justEnum, 0) fun addMaybeEnum(builder: FlatBufferBuilder, maybeEnum: Byte) = builder.addByte(34, maybeEnum, 0) fun addDefaultEnum(builder: FlatBufferBuilder, defaultEnum: Byte) = builder.addByte(35, defaultEnum, 1) fun endScalarStuff(builder: FlatBufferBuilder) : Int { val o = builder.endTable() return o } fun finishScalarStuffBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset, "NULL") fun finishSizePrefixedScalarStuffBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset, "NULL") } }
tests/optional_scalars/ScalarStuff.kt
4100652554
/* * Copyright (c) 2019 52inc. * * 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.ftinc.kit.arch.presentation.delegates import androidx.lifecycle.Lifecycle import androidx.lifecycle.OnLifecycleEvent import android.os.Bundle import com.ftinc.kit.arch.presentation.Stateful import com.ftinc.kit.arch.presentation.renderers.DisposableStateRenderer class StatefulActivityDelegate( private val state: Stateful, private val lifecycle: Lifecycle.Event = Lifecycle.Event.ON_CREATE ) : ActivityDelegate { override fun onCreate(savedInstanceState: Bundle?) { tryStart(Lifecycle.Event.ON_CREATE) } override fun onSaveInstanceState(outState: Bundle) { } override fun onResume() { tryStart(Lifecycle.Event.ON_RESUME) } override fun onStart() { tryStart(Lifecycle.Event.ON_START) } override fun onStop() { tryStop(Lifecycle.Event.ON_STOP) } override fun onPause() { tryStop(Lifecycle.Event.ON_PAUSE) } override fun onDestroy() { tryStop(Lifecycle.Event.ON_DESTROY) } private fun tryStart(event: Lifecycle.Event) { if (event == lifecycle) { state.start() } } private fun tryStop(event: Lifecycle.Event) { val opposite = when(lifecycle) { Lifecycle.Event.ON_CREATE -> Lifecycle.Event.ON_DESTROY Lifecycle.Event.ON_START -> Lifecycle.Event.ON_STOP else -> Lifecycle.Event.ON_PAUSE } if (opposite == event) { state.stop() } } }
library-arch/src/main/java/com/ftinc/kit/arch/presentation/delegates/StatefulActivityDelegate.kt
376087624
package at.ac.tuwien.caa.docscan.ui.docviewer import android.net.Uri import android.os.Bundle import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import at.ac.tuwien.caa.docscan.db.model.DocumentWithPages import at.ac.tuwien.caa.docscan.db.model.error.DBErrorCode import at.ac.tuwien.caa.docscan.db.model.isUploaded import at.ac.tuwien.caa.docscan.logic.* import at.ac.tuwien.caa.docscan.repository.DocumentRepository import at.ac.tuwien.caa.docscan.repository.ExportFileRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import java.util.* class DocumentViewerViewModel( private val repository: DocumentRepository, private val exportFileRepository: ExportFileRepository ) : ViewModel() { val selectedScreen = MutableLiveData(DocumentViewerScreen.DOCUMENTS) val observableInitDocumentOptions = MutableLiveData<Event<DocumentWithPages>>() val observableInitCamera = MutableLiveData<Event<Unit>>() val observableNumOfSelectedElements = MutableLiveData<Int>() private val observableDocumentAtImages = MutableLiveData<DocumentWithPages?>() val observableResourceAction = MutableLiveData<Event<DocumentViewerModel>>() val observableResourceConfirmation = MutableLiveData<Event<DocumentConfirmationModel>>() val observableNewExportCount = MutableLiveData<Int>() init { viewModelScope.launch(Dispatchers.IO) { exportFileRepository.getExportFileCount().collectLatest { observableNewExportCount.postValue(it.toInt()) } } } /** * This function needs to be called every time the selected fragment in the bottom nav changes. */ fun changeScreen(screen: DocumentViewerScreen) { // every time the screen is changed, the selected elements will get deleted. observableNumOfSelectedElements.postValue(0) selectedScreen.postValue(screen) } fun informAboutImageViewer(documentWithPages: DocumentWithPages?) { observableDocumentAtImages.postValue(documentWithPages) } fun initDocumentOptions(documentWithPages: DocumentWithPages) { observableInitDocumentOptions.postValue(Event(documentWithPages)) } fun setSelectedElements(selectedElements: Int) { observableNumOfSelectedElements.postValue(selectedElements) } fun addNewImages(uris: List<Uri>) { viewModelScope.launch(Dispatchers.IO) { val doc = run { if (selectedScreen.value == DocumentViewerScreen.IMAGES) { observableDocumentAtImages.value?.document } else { null } } ?: return@launch repository.saveNewImportedImageForDocument(doc, uris) } } /** * Starts imaging with a document, there are several scenarios. * - If [docId] is available, then this will be the next active document. * - If [docId] is null but [selectedScreen] is [DocumentViewerScreen.IMAGES], then * the currently selected document will become active. * - If none of the previous cases occur, imaging will be continued with the active document. */ fun startImagingWith(docId: UUID? = null) { viewModelScope.launch(Dispatchers.IO) { val docIdToBecomeActive = docId ?: run { if (selectedScreen.value == DocumentViewerScreen.IMAGES) { observableDocumentAtImages.value?.document?.id } else { null } } docIdToBecomeActive?.let { repository.setDocumentAsActive(it) } observableInitCamera.postValue(Event(Unit)) } } fun uploadSelectedDocument() { val docWithPages = if (selectedScreen.value == DocumentViewerScreen.IMAGES) { observableDocumentAtImages.value ?: kotlin.run { null } } else { null } docWithPages ?: kotlin.run { observableResourceAction.postValue( Event( DocumentViewerModel( DocumentAction.UPLOAD, DBErrorCode.ENTRY_NOT_AVAILABLE.asFailure<Unit>(), Bundle() ) ) ) return } applyActionFor( action = DocumentAction.UPLOAD, documentActionArguments = Bundle().appendDocWithPages(docWithPages), documentWithPages = docWithPages ) } fun applyActionFor( action: DocumentAction, documentActionArguments: Bundle ) { val documentWithPages = documentActionArguments.extractDocWithPages() ?: kotlin.run { observableResourceAction.postValue( Event( DocumentViewerModel( action, DBErrorCode.ENTRY_NOT_AVAILABLE.asFailure<Unit>(), documentActionArguments ) ) ) return } applyActionFor(action, documentActionArguments, documentWithPages) } private fun applyActionFor( action: DocumentAction, documentActionArguments: Bundle, documentWithPages: DocumentWithPages ) { viewModelScope.launch(Dispatchers.IO) { if (!skipConfirmation(action, documentWithPages)) { // ask for confirmation first, if forceAction, then confirmation is not necessary anymore. if (action.needsConfirmation && !documentActionArguments.extractIsConfirmed()) { observableResourceConfirmation.postValue( Event( DocumentConfirmationModel( action, documentWithPages, documentActionArguments.appendDocWithPages(documentWithPages) ) ) ) return@launch } } val resource = when (action) { DocumentAction.SHARE -> { repository.shareDocument(documentWithPages.document.id) } DocumentAction.DELETE -> { repository.removeDocument(documentWithPages) } DocumentAction.EXPORT_ZIP -> { repository.exportDocument( documentWithPages, skipCropRestriction = true, ExportFormat.ZIP ) } DocumentAction.EXPORT -> { repository.exportDocument( documentWithPages, skipCropRestriction = documentActionArguments.extractSkipCropRestriction(), if(documentActionArguments.extractUseOCR()) ExportFormat.PDF_WITH_OCR else ExportFormat.PDF ) } DocumentAction.CROP -> { repository.cropDocument(documentWithPages) } DocumentAction.UPLOAD -> { repository.uploadDocument( documentWithPages, skipCropRestriction = documentActionArguments.extractSkipCropRestriction(), skipAlreadyUploadedRestriction = documentActionArguments.extractSkipAlreadyUploadedRestriction() ) } DocumentAction.CANCEL_UPLOAD -> { repository.cancelDocumentUpload(documentWithPages.document.id) } } observableResourceAction.postValue( Event( DocumentViewerModel( action, resource, documentActionArguments ) ) ) } } } /** * Evaluates if the confirmation can be skipped. */ private fun skipConfirmation( action: DocumentAction, documentWithPages: DocumentWithPages, ): Boolean { return when (action) { DocumentAction.UPLOAD -> { // if the doc is already uploaded, we do not need to ask for further confirmation documentWithPages.isUploaded() } else -> false } } data class DocumentViewerModel( val action: DocumentAction, val resource: Resource<*>, val arguments: Bundle ) data class DocumentConfirmationModel( val action: DocumentAction, val documentWithPages: DocumentWithPages, val arguments: Bundle ) enum class DocumentAction(val needsConfirmation: Boolean, val showSuccessMessage: Boolean) { DELETE(true, false), EXPORT_ZIP(false, true), EXPORT(true, true), CROP(true, false), UPLOAD(true, true), CANCEL_UPLOAD(true, false), SHARE(false, false) } enum class DocumentViewerScreen { DOCUMENTS, IMAGES, PDFS }
app/src/main/java/at/ac/tuwien/caa/docscan/ui/docviewer/DocumentViewerViewModel.kt
2707422765
/* * Copyright (c) 2017. tangzx([email protected]) * * 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.tang.intellij.lua.hierarchy.call import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.ide.hierarchy.HierarchyNodeDescriptor import com.intellij.openapi.roots.ui.util.CompositeAppearance import com.intellij.openapi.util.Comparing import com.intellij.pom.Navigatable import com.intellij.psi.NavigatablePsiElement import com.intellij.psi.PsiElement import com.tang.intellij.lua.psi.LuaLocalFuncDef class LuaHierarchyNodeDescriptor(parentDescriptor: HierarchyNodeDescriptor?, element: PsiElement, isBase: Boolean) : HierarchyNodeDescriptor(element.project, parentDescriptor, element, isBase), Navigatable { override fun navigate(requestFocus: Boolean) { val element = psiElement if (element is Navigatable && element.canNavigate()) { element.navigate(requestFocus) } } override fun canNavigate(): Boolean { return psiElement is Navigatable } override fun canNavigateToSource(): Boolean { return psiElement is Navigatable } override fun update(): Boolean { var changes = super.update() val oldText = myHighlightedText myHighlightedText = CompositeAppearance() val element = psiElement as NavigatablePsiElement? if (element == null) { val invalidPrefix = IdeBundle.message("node.hierarchy.invalid") if (!myHighlightedText.text.startsWith(invalidPrefix)) { myHighlightedText.beginning.addText(invalidPrefix, HierarchyNodeDescriptor.getInvalidPrefixAttributes()) } return true } val presentation = element.presentation if (presentation != null) { myHighlightedText.ending.addText(presentation.presentableText) myHighlightedText.ending.addText(" " + presentation.locationString, HierarchyNodeDescriptor.getPackageNameAttributes()) icon = presentation.getIcon(false) } else { if (element is LuaLocalFuncDef) { myHighlightedText.ending.addText(element.name ?: "") myHighlightedText.ending.addText(" " + element.containingFile.name, HierarchyNodeDescriptor.getPackageNameAttributes()) icon = AllIcons.Nodes.Function } } myName = myHighlightedText.text if (!Comparing.equal(myHighlightedText, oldText)) { changes = true } return changes } }
src/main/java/com/tang/intellij/lua/hierarchy/call/LuaHierarchyNodeDescriptor.kt
3115358109
/* * Copyright (c) 2017. tangzx([email protected]) * * 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.tang.intellij.lua.stubs import com.intellij.psi.stubs.IndexSink import com.intellij.psi.stubs.StubElement import com.intellij.psi.stubs.StubInputStream import com.intellij.psi.stubs.StubOutputStream import com.tang.intellij.lua.comment.psi.LuaDocTagType import com.tang.intellij.lua.comment.psi.impl.LuaDocTagTypeImpl import com.tang.intellij.lua.psi.LuaElementType class LuaDocTagTypeType : LuaStubElementType<LuaDocTagTypeStub, LuaDocTagType>("DOC_TY"){ override fun indexStub(stub: LuaDocTagTypeStub, sink: IndexSink) { } override fun deserialize(inputStream: StubInputStream, stubElement: StubElement<*>?): LuaDocTagTypeStub { return LuaDocTagTypeStubImpl(stubElement) } override fun createPsi(stub: LuaDocTagTypeStub) = LuaDocTagTypeImpl(stub, this) override fun serialize(stub: LuaDocTagTypeStub, stubElement: StubOutputStream) { } override fun createStub(tagType: LuaDocTagType, stubElement: StubElement<*>?): LuaDocTagTypeStub { return LuaDocTagTypeStubImpl(stubElement) } } interface LuaDocTagTypeStub : StubElement<LuaDocTagType> class LuaDocTagTypeStubImpl(parent: StubElement<*>?) : LuaDocStubBase<LuaDocTagType>(parent, LuaElementType.TYPE_DEF), LuaDocTagTypeStub
src/main/java/com/tang/intellij/lua/stubs/LuaDocTagTypeStub.kt
2128128900
package eu.kanade.tachiyomi.extension.es.lectormanga import android.app.Activity import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import android.util.Log import kotlin.system.exitProcess /** * Springboard that accepts https://lectormanga.com/gotobook/:id intents and redirects them to * the main Tachiyomi process. */ class LectorMangaUrlActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val pathSegments = intent?.data?.pathSegments if (pathSegments != null && pathSegments.size > 1) { val id = pathSegments[1] val mainIntent = Intent().apply { action = "eu.kanade.tachiyomi.SEARCH" putExtra("query", "${LectorManga.PREFIX_ID_SEARCH}$id") putExtra("filter", packageName) } try { startActivity(mainIntent) } catch (e: ActivityNotFoundException) { Log.e("LectorMangaUrlActivity", e.toString()) } } else { Log.e("LectorMangaUrlActivity", "could not parse uri from intent $intent") } finish() exitProcess(0) } }
src/es/lectormanga/src/eu/kanade/tachiyomi/extension/es/lectormanga/LectorMangaUrlActivity.kt
2919511402
package protokola.transport import okhttp3.Cookie import okhttp3.CookieJar import okhttp3.HttpUrl import okhttp3.MediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import okio.Buffer import protokola.Message import protokola.MessageBus import protokola.of import protokola.transport.Transport.ClientRequest import protokola.transport.Transport.DolphinClientId import protokola.transport.Transport.SessionCookie import protokola.transport.Transport.ServerResponse import java.util.concurrent.ConcurrentHashMap fun main(args: Array<String>) { val bus = MessageBus() bus.subscribe { println(it.payload) } val channel = DolphinChannel() channel.dispatchTo(bus) val dolphinEndpointUrl = "http://localhost:8080/dolphin" val requestContext = ClientRequest(dolphinEndpointUrl, listOf( mapOf("id" to "CreateContext") ).toJson()) val requestController = ClientRequest(dolphinEndpointUrl, listOf( mapOf("id" to "CreateController", "n" to "FooController", "c_id" to null) ).toJson()) val requestLongPoll = ClientRequest(dolphinEndpointUrl, listOf( mapOf("id" to "StartLongPoll") ).toJson()) bus.dispatch(Message(requestContext)) bus.dispatch(Message(requestController)) bus.dispatch(Message(requestLongPoll)) } object Transport { data class ClientRequest(val url: String, val body: String?) data class ServerResponse(val status: Int, val body: String?) data class DolphinClientId(val value: String) data class SessionCookie(val value: String) } class DolphinChannel { private val okHttpClient = OkHttpClient.Builder() // .cookieJar(simpleCookieJar()) .build() private var dolphinClientId: DolphinClientId? = null private var sessionCookie: SessionCookie? = null fun dispatchTo(messageBus: MessageBus) { messageBus.subscribe { message -> when (message.payload) { is ClientRequest -> fetch(messageBus, message.of()) } } } private fun fetch(bus: MessageBus, clientRequest: Message<ClientRequest>) { val okHttpRequest = createRequest( clientRequest.payload, dolphinClientId, sessionCookie ) val okHttpCall = okHttpClient.newCall(okHttpRequest) okHttpCall.execute().use { okHttpResponse -> val dolphinClientIdValue = okHttpResponse.header(headerDolphinClientId) val sessionCookieValue = okHttpResponse.headers(headerSetCookieKey).firstOrNull() val serverResponse = Message(ServerResponse( okHttpResponse.code(), okHttpResponse.body()?.string() )) bus.dispatch(serverResponse) dolphinClientIdValue?.let { dolphinClientId = DolphinClientId(it) bus.dispatch(Message(dolphinClientId)) } sessionCookieValue?.let { sessionCookie = SessionCookie(it) bus.dispatch(Message(sessionCookie)) } } } } private val headerConnectionKey = "Connection" private val headerCookieKey = "Cookie" private val headerSetCookieKey = "Set-Cookie" private val headerDolphinClientId = "dolphin_platform_intern_dolphinClientId" private fun createRequest( clientRequest: ClientRequest, dolphinClientId: DolphinClientId?, sessionCookie: SessionCookie?): Request { val mediaType = MediaType.parse("application/json") return Request.Builder().apply { url(clientRequest.url) post(RequestBody.create(mediaType, clientRequest.body!!)) header(headerConnectionKey, "keep-alive") if (dolphinClientId != null) { header(headerDolphinClientId, dolphinClientId.value) } if (sessionCookie != null) { addHeader(headerCookieKey, sessionCookie.value) } }.build() } private fun List<*>.toJson() = toString() private fun Map<*, *>.toJson() = toString() private fun simpleCookieJar() = object : CookieJar { private val cookieMap = ConcurrentHashMap<String, List<Cookie>>() override fun saveFromResponse(url: HttpUrl, unmodifiableCookies: List<Cookie>) { cookieMap[url.host()] = unmodifiableCookies.toMutableList() } override fun loadForRequest(url: HttpUrl) = cookieMap[url.host()] ?: mutableListOf() } private fun RequestBody.string() = Buffer() .also { writeTo(it) } .readUtf8()
src/main/kotlin/protokola/transport/dolphinChannel.kt
2267679636
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2017-present Benoit 'BoD' Lubek ([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 org.jraf.android.cinetoday.dagger import dagger.Component import okhttp3.OkHttpClient import org.jraf.android.cinetoday.app.ApplicationModule import org.jraf.android.cinetoday.app.loadmovies.LoadMoviesHelper import org.jraf.android.cinetoday.app.main.MainActivity import org.jraf.android.cinetoday.app.movie.details.MovieDetailsActivity import org.jraf.android.cinetoday.app.movie.list.MovieListFragment import org.jraf.android.cinetoday.app.preferences.PreferencesFragment import org.jraf.android.cinetoday.app.theater.favorites.TheaterFavoritesFragment import org.jraf.android.cinetoday.app.theater.search.TheaterSearchLiveData import org.jraf.android.cinetoday.app.tile.MoviesTodayTile import org.jraf.android.cinetoday.network.NetworkModule import org.jraf.android.cinetoday.prefs.MainPrefs import javax.inject.Named import javax.inject.Singleton @Singleton @Component( modules = [ ApplicationModule::class, NetworkModule::class ] ) interface ApplicationComponent { val loadMoviesHelper: LoadMoviesHelper @get:Named("NotCachingOkHttpClient") val notCachingOkHttpClient: OkHttpClient val mainPrefs: MainPrefs fun inject(mainActivity: MainActivity) fun inject(preferencesFragment: PreferencesFragment) fun inject(theaterFavoritesFragment: TheaterFavoritesFragment) fun inject(movieListFragment: MovieListFragment) fun inject(movieDetailsActivity: MovieDetailsActivity) fun inject(theaterSearchLiveData: TheaterSearchLiveData) fun inject(moviesTodayTile: MoviesTodayTile) }
app/src/main/kotlin/org/jraf/android/cinetoday/dagger/ApplicationComponent.kt
2087562321
package de.fluchtwege.vocabulary.questions import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.view.* import de.fluchtwege.vocabulary.R import de.fluchtwege.vocabulary.Vocabulary import de.fluchtwege.vocabulary.addquestion.AddQuestionActivity import de.fluchtwege.vocabulary.databinding.FragmentQuestionsBinding import de.fluchtwege.vocabulary.lessons.LessonsRepository import de.fluchtwege.vocabulary.quiz.QuizActivity import io.reactivex.disposables.Disposable import javax.inject.Inject class QuestionsFragment : Fragment() { companion object { const val KEY_LESSON_NAME = "lesson_name" const val KEY_QUESTION_POSITION = "question_position" } @Inject lateinit var lessonsRepository: LessonsRepository lateinit var viewModel: QuestionsViewModel lateinit var questionsAdapter: QuestionsAdaper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) Vocabulary.appComponent.inject(this) val lessonName = activity.intent.getStringExtra(KEY_LESSON_NAME) viewModel = QuestionsViewModel(lessonName, lessonsRepository) questionsAdapter = QuestionsAdaper(viewModel, this::editQuestion, this::deleteQuestion ) } private var disposable: Disposable? = null override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val binding = FragmentQuestionsBinding.inflate(inflater!!) val layoutManager = LinearLayoutManager(context) binding.questions.adapter = questionsAdapter binding.questions.layoutManager = layoutManager binding.questions.addItemDecoration(DividerItemDecoration(context, layoutManager.orientation)) binding.viewModel = viewModel disposable = viewModel.loadQuestions(questionsAdapter::notifyDataSetChanged) return binding.root } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater?.inflate(R.menu.menu_questions, menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when(item?.itemId) { R.id.add_question -> addQuestion() R.id.quiz_questions -> startQuiz() } return true } private fun editQuestion(position: Int) { val openAddQuestion = Intent(context, AddQuestionActivity::class.java) openAddQuestion.putExtra(KEY_LESSON_NAME, viewModel.lessonName) openAddQuestion.putExtra(KEY_QUESTION_POSITION, position) startActivity(openAddQuestion) } private fun deleteQuestion(position: Int) { disposable = viewModel.deleteQuestion(position, questionsAdapter::notifyDataSetChanged) } private fun addQuestion() { val openAddQuestion = Intent(context, AddQuestionActivity::class.java) openAddQuestion.putExtra(KEY_LESSON_NAME, viewModel.lessonName) startActivity(openAddQuestion) } private fun startQuiz() { val openQuiz = Intent(context, QuizActivity::class.java) openQuiz.putExtra(KEY_LESSON_NAME, viewModel.lessonName) startActivity(openQuiz) } override fun onDestroy() { super.onDestroy() disposable?.dispose() } }
app/src/main/java/de/fluchtwege/vocabulary/questions/QuestionsFragment.kt
1757646854
package cz.richter.david.astroants.rest import cz.richter.david.astroants.model.ResultPath import cz.richter.david.astroants.model.ResultResponse import cz.richter.david.astroants.model.World /** * Interface used for getting [World] from REST endpoint * and putting [ResultPath] to REST endpoint */ interface RestClient { fun getWorld(): World fun putResult(id: String, result: ResultPath): ResultResponse }
src/main/kotlin/cz/richter/david/astroants/rest/RestClient.kt
2189490659
fun main(args: Array<String>): Unit { println("start") basic_run() classes_run() interfaces_run() generics_run() functions_run() reflection_run() println("finish") }
sandbox-kotlin/src/Launcher.kt
2585359170
package kotliquery import org.joda.time.chrono.ISOChronology import org.junit.Before import org.junit.Test import java.time.* import java.util.* import kotlin.test.assertEquals /* * Many popular DBs store "TIMESTAMP WITH TIME ZONE" as epoch time (8 bytes) without timezone info. * https://www.postgresql.org/docs/14/datatype-datetime.html * https://dev.mysql.com/doc/refman/8.0/en/datetime.html * * Opposite (where timezone is stored) also exist: * https://docs.oracle.com/cd/E11882_01/server.112/e10729/ch4datetime.htm#i1006081 * * This lib supports only epoch time without timezone info */ class DataTypesTest { @Before fun before() { sessionOf(testDataSource).use { session -> session.execute( queryOf( """ drop table session_test if exists; create table session_test ( val_tstz timestamp with time zone, val_ts timestamp, val_date date, val_time time, val_uuid uuid ); """.trimIndent() ) ) } } private fun insertAndAssert( tstz: Any? = null, ts: Any? = null, date: Any? = null, time: Any? = null, uuid: Any? = null, assertRowFn: (Row) -> Unit ) { sessionOf(testDataSource).use { session -> session.execute(queryOf("truncate table session_test;")) session.execute( queryOf( """ insert into session_test (val_tstz, val_ts, val_date, val_time, val_uuid) values (:tstz, :ts, :date, :time, :uuid); """.trimIndent(), mapOf( "tstz" to tstz, "ts" to ts, "date" to date, "time" to time, "uuid" to uuid ) ) ) session.single(queryOf("select * from session_test"), assertRowFn) } } @Test fun testZonedDateTime() { val value = ZonedDateTime.parse("2010-01-01T10:00:00.123456+01:00[Europe/Berlin]") insertAndAssert(tstz = value) { row -> assertEquals( value.withZoneSameInstant(ZoneId.systemDefault()), row.zonedDateTime("val_tstz") ) } val tstz2 = ZonedDateTime.parse("2010-06-01T10:00:00.234567-07:00[America/Los_Angeles]") // DST insertAndAssert(tstz = tstz2) { row -> assertEquals( tstz2.withZoneSameInstant(ZoneId.systemDefault()), row.zonedDateTime("val_tstz") ) } } @Test fun testOffsetDateTime() { val value = OffsetDateTime.parse("2010-01-01T10:00:00.123456+01:00") insertAndAssert(tstz = value) { row -> assertEquals( value.atZoneSameInstant(ZoneId.systemDefault()).toOffsetDateTime(), row.offsetDateTime("val_tstz") ) } val value2 = OffsetDateTime.parse("2010-06-01T10:00:00.234567-07:00") // DST insertAndAssert(tstz = value2) { row -> assertEquals( value2.atZoneSameInstant(ZoneId.systemDefault()).toOffsetDateTime(), row.offsetDateTime("val_tstz") ) } } @Test fun testInstant() { val value = Instant.parse("2010-01-01T10:00:00.123456Z") insertAndAssert(tstz = value) { row -> assertEquals(value, row.instant("val_tstz")) } } @Test fun testLocalDateTime() { val value = LocalDateTime.parse("2010-01-01T10:00:00.123456") insertAndAssert(ts = value) { row -> assertEquals(value, row.localDateTime("val_ts")) } } @Test fun testLocalDate() { val value = LocalDate.parse("2010-01-01") insertAndAssert(date = value) { row -> assertEquals(value, row.localDate("val_date")) } } @Test fun testLocalTime() { val value = LocalTime.parse("10:00:00") insertAndAssert(time = value) { row -> assertEquals(value, row.localTime("val_time")) } } @Test fun testJodaDateTime() { val value = org.joda.time.DateTime.parse("2010-01-01T10:00:00.123+01:00") insertAndAssert(tstz = value) { row -> assertEquals( org.joda.time.DateTime(value, ISOChronology.getInstance()), row.jodaDateTime("val_tstz") ) } val value2 = org.joda.time.DateTime.parse("2010-06-01T10:00:00.234-07:00") // DST insertAndAssert(tstz = value2) { row -> assertEquals( org.joda.time.DateTime(value2, ISOChronology.getInstance()), row.jodaDateTime("val_tstz") ) } } @Test fun testJodaLocalDateTime() { val value = org.joda.time.LocalDateTime.parse("2010-01-01T10:00:00.123456") insertAndAssert(ts = value) { row -> assertEquals(value, row.jodaLocalDateTime("val_ts")) } } @Test fun testJodaLocalDate() { val value = org.joda.time.LocalDate.parse("2010-01-01") insertAndAssert(date = value) { row -> assertEquals(value, row.jodaLocalDate("val_date")) } } @Test fun testJodaLocalTime() { val value = org.joda.time.LocalTime.parse("10:00:00") insertAndAssert(time = value) { row -> assertEquals(value, row.jodaLocalTime("val_time")) } } @Test fun testSqlTimestamp() { val value = java.sql.Timestamp.valueOf("2010-01-01 10:00:00.123456") insertAndAssert(tstz = value) { row -> assertEquals(value, row.sqlTimestamp("val_tstz")) } } @Test fun testSqlDate() { val value = java.sql.Date.valueOf("2010-01-01") insertAndAssert(date = value) { row -> assertEquals(value, row.sqlDate("val_date")) } } @Test fun testSqlTime() { val value = java.sql.Time.valueOf("10:00:00") insertAndAssert(time = value) { row -> assertEquals(value, row.sqlTime("val_time")) } } @Test fun testUuid() { val value = UUID.fromString("44ebc207-bb46-401c-8487-62504e1c3be2") insertAndAssert(uuid = value) { row -> assertEquals(value, row.uuid("val_uuid")) } } }
src/test/kotlin/kotliquery/DataTypesTest.kt
547579985
package com.habitrpg.wearos.habitica.models.tasks import com.habitrpg.shared.habitica.models.responses.TaskDirectionData import com.habitrpg.wearos.habitica.models.user.Buffs import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class BulkTaskScoringData { @Json(name="con") var constitution: Int? = null @Json(name="str") var strength: Int? = null @Json(name="per") var per: Int? = null @Json(name="int") var intelligence: Int? = null var buffs: Buffs? = null var points: Int? = null var lvl: Int? = null @Json(name="class") var habitClass: String? = null var gp: Double? = null var exp: Double? = null var mp: Double? = null var hp: Double? = null var tasks: List<TaskDirectionData> = listOf() }
wearos/src/main/java/com/habitrpg/wearos/habitica/models/tasks/BulkTaskScoringData.kt
3766918272
package de.westnordost.streetcomplete.quests.opening_hours.model import java.text.DateFormat import java.util.* /** A time range from [start,end). */ class TimeRange(minutesStart: Int, minutesEnd: Int, val isOpenEnded: Boolean = false) : CircularSection(minutesStart, minutesEnd) { override fun intersects(other: CircularSection): Boolean { if (other !is TimeRange) return false if (isOpenEnded && other.start >= start) return true if (other.isOpenEnded && start >= other.start) return true return loops && other.loops || if (loops || other.loops) other.end > start || other.start < end else other.end > start && other.start < end } fun toStringUsing(locale: Locale, range: String): String { val sb = StringBuilder() sb.append(timeOfDayToString(locale, start)) val displayEnd = if(end != 0) end else 60 * 24 if (start != end || !isOpenEnded) { sb.append(range) sb.append(timeOfDayToString(locale, displayEnd)) } if (isOpenEnded) sb.append("+") return sb.toString() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is TimeRange) return false return other.isOpenEnded == isOpenEnded && super.equals(other) } override fun hashCode() = super.hashCode() * 2 + if (isOpenEnded) 1 else 0 override fun toString() = toStringUsing(Locale.GERMANY, "-") private fun timeOfDayToString(locale: Locale, minutes: Int): String { val cal = GregorianCalendar() cal.set(Calendar.HOUR_OF_DAY, minutes / 60) cal.set(Calendar.MINUTE, minutes % 60) return DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(cal.time) } }
app/src/main/java/de/westnordost/streetcomplete/quests/opening_hours/model/TimeRange.kt
3392239186
package de.westnordost.streetcomplete.data.osm.osmquest import android.database.Cursor import android.database.sqlite.SQLiteDatabase.CONFLICT_IGNORE import android.database.sqlite.SQLiteOpenHelper import androidx.core.content.contentValuesOf import java.util.Date import javax.inject.Inject import de.westnordost.osmapi.map.data.BoundingBox import de.westnordost.osmapi.map.data.Element import de.westnordost.streetcomplete.data.* import de.westnordost.streetcomplete.data.osm.changes.StringMapChanges import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.CHANGES_SOURCE import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.ELEMENT_ID import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.ELEMENT_TYPE import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.LAST_UPDATE import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.QUEST_ID import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.QUEST_STATUS import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.QUEST_TYPE import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.TAG_CHANGES import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.NAME import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.NAME_MERGED_VIEW import de.westnordost.streetcomplete.data.quest.QuestStatus.* import de.westnordost.streetcomplete.data.osm.mapdata.ElementKey import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometryMapping import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometryTable import de.westnordost.streetcomplete.data.quest.QuestStatus import de.westnordost.streetcomplete.data.quest.QuestTypeRegistry import de.westnordost.streetcomplete.ktx.* import de.westnordost.streetcomplete.util.Serializer /** Stores OsmQuest objects - quests and answers to these for adding data to OSM. * * This is just a simple CRUD-like DAO, use OsmQuestController to access the data from the * application logic. * */ internal class OsmQuestDao @Inject constructor( private val dbHelper: SQLiteOpenHelper, private val mapping: OsmQuestMapping ) { private val db get() = dbHelper.writableDatabase fun add(quest: OsmQuest): Boolean { return addAll(listOf(quest)) == 1 } fun get(id: Long): OsmQuest? { return db.queryOne(NAME_MERGED_VIEW, null, "$QUEST_ID = $id") { mapping.toObject(it) } } fun update(quest: OsmQuest): Boolean { quest.lastUpdate = Date() return db.update(NAME, mapping.toUpdatableContentValues(quest), "$QUEST_ID = ${quest.id}", null) == 1 } fun updateAll(quests: List<OsmQuest>): Int { var rows = 0 db.transaction { quests.forEach { if (update(it)) rows++ } } return rows } fun delete(id: Long): Boolean { return db.delete(NAME, "$QUEST_ID = $id", null) == 1 } fun addAll(quests: Collection<OsmQuest>): Int { var addedRows = 0 db.transaction { for (quest in quests) { quest.lastUpdate = Date() val rowId = db.insertWithOnConflict(NAME, null, mapping.toContentValues(quest), CONFLICT_IGNORE) if (rowId != -1L) { quest.id = rowId addedRows++ } } } return addedRows } fun deleteAllIds(ids: Collection<Long>): Int { return db.delete(NAME, "$QUEST_ID IN (${ids.joinToString(",")})", null) } fun getLastSolved(): OsmQuest? { val qb = createQuery(statusIn = listOf(HIDDEN, ANSWERED, CLOSED)) return db.queryOne(NAME_MERGED_VIEW, null, qb, "$LAST_UPDATE DESC") { mapping.toObject(it) } } fun getAll( statusIn: Collection<QuestStatus>? = null, bounds: BoundingBox? = null, element: ElementKey? = null, questTypes: Collection<String>? = null, changedBefore: Long? = null ): List<OsmQuest> { val qb = createQuery(statusIn, bounds, element, questTypes, changedBefore) return db.query(NAME_MERGED_VIEW, null, qb) { mapping.toObject(it) }.filterNotNull() } fun getAllIds( statusIn: Collection<QuestStatus>? = null, bounds: BoundingBox? = null, element: ElementKey? = null, questTypes: Collection<String>? = null, changedBefore: Long? = null ): List<Long> { val qb = createQuery(statusIn, bounds, element, questTypes, changedBefore) return db.query(NAME_MERGED_VIEW, arrayOf(QUEST_ID), qb) { it.getLong(0) } } fun getCount( statusIn: Collection<QuestStatus>? = null, bounds: BoundingBox? = null, element: ElementKey? = null, questTypes: Collection<String>? = null, changedBefore: Long? = null ): Int { val qb = createQuery(statusIn, bounds, element, questTypes, changedBefore) return db.queryOne(NAME_MERGED_VIEW, arrayOf("COUNT(*)"), qb) { it.getInt(0) } ?: 0 } fun deleteAll( statusIn: Collection<QuestStatus>? = null, bounds: BoundingBox? = null, element: ElementKey? = null, questTypes: Collection<String>? = null, changedBefore: Long? = null ): Int { val qb = createQuery(statusIn, bounds, element, questTypes, changedBefore) return db.delete(NAME, qb.where, qb.args) } } private fun createQuery( statusIn: Collection<QuestStatus>? = null, bounds: BoundingBox? = null, element: ElementKey? = null, questTypes: Collection<String>? = null, changedBefore: Long? = null ) = WhereSelectionBuilder().apply { if (element != null) { add("$ELEMENT_TYPE = ?", element.elementType.name) add("$ELEMENT_ID = ?", element.elementId.toString()) } if (statusIn != null) { require(statusIn.isNotEmpty()) { "statusIn must not be empty if not null" } if (statusIn.size == 1) { add("$QUEST_STATUS = ?", statusIn.single().name) } else { val names = statusIn.joinToString(",") { "\"$it\"" } add("$QUEST_STATUS IN ($names)") } } if (questTypes != null) { require(questTypes.isNotEmpty()) { "questTypes must not be empty if not null" } if (questTypes.size == 1) { add("$QUEST_TYPE = ?", questTypes.single()) } else { val names = questTypes.joinToString(",") { "\"$it\"" } add("$QUEST_TYPE IN ($names)") } } if (bounds != null) { add( "(${ElementGeometryTable.Columns.LATITUDE} BETWEEN ? AND ?)", bounds.minLatitude.toString(), bounds.maxLatitude.toString() ) add( "(${ElementGeometryTable.Columns.LONGITUDE} BETWEEN ? AND ?)", bounds.minLongitude.toString(), bounds.maxLongitude.toString() ) } if (changedBefore != null) { add("$LAST_UPDATE < ?", changedBefore.toString()) } } class OsmQuestMapping @Inject constructor( private val serializer: Serializer, private val questTypeRegistry: QuestTypeRegistry, private val elementGeometryMapping: ElementGeometryMapping ) : ObjectRelationalMapping<OsmQuest?> { override fun toContentValues(obj: OsmQuest?) = obj?.let { toConstantContentValues(it) + toUpdatableContentValues(it) } ?: contentValuesOf() override fun toObject(cursor: Cursor): OsmQuest? { val questType = questTypeRegistry.getByName(cursor.getString(QUEST_TYPE)) ?: return null return OsmQuest( cursor.getLong(QUEST_ID), questType as OsmElementQuestType<*>, Element.Type.valueOf(cursor.getString(ELEMENT_TYPE)), cursor.getLong(ELEMENT_ID), valueOf(cursor.getString(QUEST_STATUS)), cursor.getBlobOrNull(TAG_CHANGES)?.let { serializer.toObject<StringMapChanges>(it) }, cursor.getStringOrNull(CHANGES_SOURCE), Date(cursor.getLong(LAST_UPDATE)), elementGeometryMapping.toObject(cursor) ) } fun toUpdatableContentValues(obj: OsmQuest) = contentValuesOf( QUEST_STATUS to obj.status.name, TAG_CHANGES to obj.changes?.let { serializer.toBytes(it) }, CHANGES_SOURCE to obj.changesSource, LAST_UPDATE to obj.lastUpdate.time ) private fun toConstantContentValues(obj: OsmQuest) = contentValuesOf( QUEST_ID to obj.id, QUEST_TYPE to obj.type.javaClass.simpleName, ELEMENT_TYPE to obj.elementType.name, ELEMENT_ID to obj.elementId ) }
app/src/main/java/de/westnordost/streetcomplete/data/osm/osmquest/OsmQuestDao.kt
1521735742
internal var sideEffects: String = "" internal class A { var prop: String = "" init { sideEffects += prop + "first" } constructor() {} constructor(x: String): this() { prop = x sideEffects += "#third" } init { sideEffects += prop + "#second" } constructor(x: Int): this(x.toString()) { prop += "#int" sideEffects += "#fourth" } } fun box(): String { val a1 = A("abc") if (a1.prop != "abc") return "fail1: ${a1.prop}" if (sideEffects != "first#second#third") return "fail1-sideEffects: ${sideEffects}" sideEffects = "" val a2 = A(123) if (a2.prop != "123#int") return "fail2: ${a2.prop}" if (sideEffects != "first#second#third#fourth") return "fail2-sideEffects: ${sideEffects}" sideEffects = "" val a3 = A() if (a3.prop != "") return "fail2: ${a3.prop}" if (sideEffects != "first#second") return "fail3-sideEffects: ${sideEffects}" return "OK" }
backend.native/tests/external/codegen/box/secondaryConstructors/basicNoPrimaryOneSink.kt
3393735904
package com.vmenon.mpo.system.framework.di.dagger interface SystemFrameworkComponentProvider { fun systemFrameworkComponent(): SystemFrameworkComponent }
system_framework/src/main/java/com/vmenon/mpo/system/framework/di/dagger/SystemFrameworkComponentProvider.kt
4064283775
package com.marknkamau.justjava.data.db import com.marknkamau.justjava.data.models.AppProduct import com.marknkamau.justjava.data.models.CartItem interface DbRepository { suspend fun saveItemToCart(product: AppProduct, quantity: Int) suspend fun getCartItems(): List<CartItem> suspend fun deleteItemFromCart(item: CartItem) suspend fun clearCart() }
app/src/main/java/com/marknkamau/justjava/data/db/DbRepository.kt
1702537970
// Copyright 2000-2017 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.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.openapi.util.io.FileUtil import com.intellij.util.* import com.intellij.util.containers.ContainerUtil import com.intellij.util.text.UniqueNameGenerator import org.jdom.Element import java.io.InputStream import java.util.* class SchemeManagerIprProvider(private val subStateTagName: String) : StreamProvider { private val nameToData = ContainerUtil.newConcurrentMap<String, ByteArray>() override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean { nameToData.get(PathUtilRt.getFileName(fileSpec))?.let(ByteArray::inputStream).let { consumer(it) } return true } override fun delete(fileSpec: String, roamingType: RoamingType): Boolean { nameToData.remove(PathUtilRt.getFileName(fileSpec)) return true } override fun processChildren(path: String, roamingType: RoamingType, filter: (String) -> Boolean, processor: (String, InputStream, Boolean) -> Boolean): Boolean { for ((name, data) in nameToData) { if (filter(name) && !data.inputStream().use { processor(name, it, false) }) { break } } return true } override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { LOG.assertTrue(content.isNotEmpty()) nameToData.put(PathUtilRt.getFileName(fileSpec), ArrayUtil.realloc(content, size)) } fun load(state: Element?, nameGetter: ((Element) -> String)? = null) { nameToData.clear() if (state == null) { return } val nameGenerator = UniqueNameGenerator() for (child in state.getChildren(subStateTagName)) { // https://youtrack.jetbrains.com/issue/RIDER-10052 // ignore empty elements if (child.isEmpty()) { continue } var name = nameGetter?.invoke(child) ?: child.getAttributeValue("name") if (name == null) { for (optionElement in child.getChildren("option")) { if (optionElement.getAttributeValue("name") == "myName") { name = optionElement.getAttributeValue("value") } } } if (name.isNullOrEmpty()) { continue } nameToData.put(nameGenerator.generateUniqueName("${FileUtil.sanitizeFileName(name, false)}.xml"), child.toByteArray()) } } fun writeState(state: Element, comparator: Comparator<String>? = null) { val names = nameToData.keys.toTypedArray() if (comparator == null) { names.sort() } else { names.sortWith(comparator) } for (name in names) { nameToData.get(name)?.let { state.addContent(loadElement(it.inputStream())) } } } }
platform/projectModel-impl/src/com/intellij/configurationStore/SchemeManagerIprProvider.kt
1607669396
package com.apollographql.apollo3.subscription /** * Represents a callback for subscription manager state changes. */ interface OnSubscriptionManagerStateChangeListener { /** * Called when subscription manager state changed. * * @param fromState previous subscription manager state * @param toState new subscription manager state */ fun onStateChange(fromState: SubscriptionManagerState?, toState: SubscriptionManagerState?) }
apollo-runtime/src/main/java/com/apollographql/apollo3/subscription/OnSubscriptionManagerStateChangeListener.kt
1799949315
/* * RenameTrackDialog.kt * Implements the RenameTrackDialog class * A RenameTrackDialog offers user to change name of track * * 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.dialogs import android.content.Context import android.text.InputType import android.view.LayoutInflater import android.widget.EditText import android.widget.TextView import com.google.android.material.dialog.MaterialAlertDialogBuilder import org.y20k.trackbook.R import org.y20k.trackbook.helpers.LogHelper /* * RenameTrackDialog class */ class RenameTrackDialog (private var renameTrackListener: RenameTrackListener) { /* Interface used to communicate back to activity */ interface RenameTrackListener { fun onRenameTrackDialog(textInput: String) { } } /* Define log tag */ private val TAG = LogHelper.makeLogTag(RenameTrackDialog::class.java.simpleName) /* Construct and show dialog */ fun show(context: Context, trackName: String) { // prepare dialog builder val builder: MaterialAlertDialogBuilder = MaterialAlertDialogBuilder(context, R.style.AlertDialogTheme) // get input field val inflater = LayoutInflater.from(context) val view = inflater.inflate(R.layout.dialog_rename_track, null) val inputField = view.findViewById<EditText>(R.id.dialog_rename_track_input_edit_text) // pre-fill with current track name inputField.setText(trackName, TextView.BufferType.EDITABLE) inputField.setSelection(trackName.length) inputField.inputType = InputType.TYPE_CLASS_TEXT // set dialog view builder.setView(view) // add "add" button builder.setPositiveButton(R.string.dialog_rename_track_button) { _, _ -> // hand text over to initiating activity inputField.text?.let { var newStationName: String = it.toString() if (newStationName.isEmpty()) newStationName = trackName renameTrackListener.onRenameTrackDialog(newStationName) } } // add cancel button builder.setNegativeButton(R.string.dialog_generic_button_cancel) { _, _ -> // listen for click on cancel button // do nothing } // display add dialog builder.show() } }
app/src/main/java/org/y20k/trackbook/dialogs/RenameTrackDialog.kt
3283862607
package info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.action import dagger.android.HasAndroidInjector import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.common.viewmodel.ActionViewModelBase import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger abstract class DeactivatePodViewModel( injector: HasAndroidInjector, logger: AAPSLogger, aapsSchedulers: AapsSchedulers ) : ActionViewModelBase(injector, logger, aapsSchedulers) { abstract fun discardPod() }
omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/deactivation/viewmodel/action/DeactivatePodViewModel.kt
1706437369
package abi42_0_0.expo.modules.notifications.service.delegates import android.app.AlarmManager import android.content.Context import android.util.Log import androidx.core.app.AlarmManagerCompat import expo.modules.notifications.notifications.interfaces.SchedulableNotificationTrigger import expo.modules.notifications.notifications.model.Notification import expo.modules.notifications.notifications.model.NotificationRequest import abi42_0_0.expo.modules.notifications.service.NotificationsService import abi42_0_0.expo.modules.notifications.service.interfaces.SchedulingDelegate import java.io.IOException import java.io.InvalidClassException class ExpoSchedulingDelegate(protected val context: Context) : SchedulingDelegate { protected val store = SharedPreferencesNotificationsStore(context) protected val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager override fun setupScheduledNotifications() { store.allNotificationRequests.forEach { try { scheduleNotification(it) } catch (e: Exception) { Log.w("expo-notifications", "Notification ${it.identifier} could not have been scheduled: ${e.message}") e.printStackTrace() } } } override fun getAllScheduledNotifications(): Collection<NotificationRequest> = store.allNotificationRequests override fun getScheduledNotification(identifier: String): NotificationRequest? = try { store.getNotificationRequest(identifier) } catch (e: IOException) { null } catch (e: ClassNotFoundException) { null } catch (e: NullPointerException) { null } override fun scheduleNotification(request: NotificationRequest) { // If the trigger is empty, handle receive immediately and return. if (request.trigger == null) { NotificationsService.receive(context, Notification(request)) return } if (request.trigger !is SchedulableNotificationTrigger) { throw IllegalArgumentException("Notification request \"${request.identifier}\" does not have a schedulable trigger (it's ${request.trigger}). Refusing to schedule.") } (request.trigger as SchedulableNotificationTrigger).nextTriggerDate().let { nextTriggerDate -> if (nextTriggerDate == null) { Log.d("expo-notifications", "Notification request \"${request.identifier}\" will not trigger in the future, removing.") NotificationsService.removeScheduledNotification(context, request.identifier) } else { store.saveNotificationRequest(request) AlarmManagerCompat.setExactAndAllowWhileIdle( alarmManager, AlarmManager.RTC_WAKEUP, nextTriggerDate.time, NotificationsService.createNotificationTrigger(context, request.identifier) ) } } } override fun triggerNotification(identifier: String) { try { val notificationRequest: NotificationRequest = store.getNotificationRequest(identifier)!! NotificationsService.receive(context, Notification(notificationRequest)) NotificationsService.schedule(context, notificationRequest) } catch (e: ClassNotFoundException) { Log.e("expo-notifications", "An exception occurred while triggering notification " + identifier + ", removing. " + e.message) e.printStackTrace() NotificationsService.removeScheduledNotification(context, identifier) } catch (e: InvalidClassException) { Log.e("expo-notifications", "An exception occurred while triggering notification " + identifier + ", removing. " + e.message) e.printStackTrace() NotificationsService.removeScheduledNotification(context, identifier) } catch (e: NullPointerException) { Log.e("expo-notifications", "An exception occurred while triggering notification " + identifier + ", removing. " + e.message) e.printStackTrace() NotificationsService.removeScheduledNotification(context, identifier) } } override fun removeScheduledNotifications(identifiers: Collection<String>) { identifiers.forEach { alarmManager.cancel(NotificationsService.createNotificationTrigger(context, it)) store.removeNotificationRequest(it) } } override fun removeAllScheduledNotifications() { store.removeAllNotificationRequests().forEach { alarmManager.cancel(NotificationsService.createNotificationTrigger(context, it)) } } }
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/notifications/service/delegates/ExpoSchedulingDelegate.kt
2188493456
// Code generated by Wire protocol buffer compiler, do not edit. // Source: squareup.geology.javainteropkotlin.Period in period_java_interop_kotlin.proto package com.squareup.wire.proto2.geology.javainteropkotlin import com.squareup.wire.EnumAdapter import com.squareup.wire.ProtoAdapter import com.squareup.wire.Syntax.PROTO_2 import com.squareup.wire.WireEnum import kotlin.Int import kotlin.jvm.JvmField import kotlin.jvm.JvmStatic public enum class Period( public override val `value`: Int, ) : WireEnum { /** * 145.5 million years ago — 66.0 million years ago. */ CRETACEOUS(1), /** * 201.3 million years ago — 145.0 million years ago. */ JURASSIC(2), /** * 252.17 million years ago — 201.3 million years ago. */ TRIASSIC(3), ; public companion object { @JvmField public val ADAPTER: ProtoAdapter<Period> = object : EnumAdapter<Period>( Period::class, PROTO_2, null ) { public override fun fromValue(`value`: Int): Period? = Period.fromValue(value) } @JvmStatic public fun fromValue(`value`: Int): Period? = when (value) { 1 -> CRETACEOUS 2 -> JURASSIC 3 -> TRIASSIC else -> null } } }
wire-library/wire-moshi-adapter/src/test/java/com/squareup/wire/proto2/geology/javainteropkotlin/Period.kt
1672499883
package com.prateekj.snooper.networksnooper.database import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import com.prateekj.snooper.database.SnooperDbHelper import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_DATE import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_ERROR import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_HEADER_ID import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_HEADER_NAME import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_HEADER_TYPE import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_HEADER_VALUE import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_HTTP_CALL_RECORD_ID import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_METHOD import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_PAYLOAD import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_RESPONSE_BODY import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_STATUSCODE import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_STATUSTEXT import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_URL import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HEADER_TABLE_NAME import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HEADER_VALUE_TABLE_NAME import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_GET_BY_ID import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_GET_NEXT_SORT_BY_DATE_WITH_SIZE import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_GET_SORT_BY_DATE import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_GET_SORT_BY_DATE_WITH_SIZE import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_SEARCH import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_TABLE_NAME import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_HEADER_GET_BY_CALL_ID import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_HEADER_VALUE_GET_BY_HEADER_ID import com.prateekj.snooper.networksnooper.model.HttpCallRecord import com.prateekj.snooper.networksnooper.model.HttpHeader import com.prateekj.snooper.networksnooper.model.HttpHeaderValue import java.util.ArrayList class SnooperRepo(context: Context) { private val dbWriteHelper: SnooperDbHelper = SnooperDbHelper.create(context) private val dbReadHelper: SnooperDbHelper = SnooperDbHelper.create(context) fun save(httpCallRecord: HttpCallRecord): Long { val database = dbWriteHelper.writableDatabase val values = ContentValues() values.put(COLUMN_URL, httpCallRecord.url) values.put(COLUMN_PAYLOAD, httpCallRecord.payload) values.put(COLUMN_RESPONSE_BODY, httpCallRecord.responseBody) values.put(COLUMN_METHOD, httpCallRecord.method) values.put(COLUMN_STATUSCODE, httpCallRecord.statusCode) values.put(COLUMN_STATUSTEXT, httpCallRecord.statusText) values.put(COLUMN_DATE, httpCallRecord.date!!.time) values.put(COLUMN_ERROR, httpCallRecord.error) val httpCallRecordId = database.insert(HTTP_CALL_RECORD_TABLE_NAME, null, values) try { database.beginTransaction() saveHeaders(database, httpCallRecordId, httpCallRecord.requestHeaders!!, "req") saveHeaders(database, httpCallRecordId, httpCallRecord.responseHeaders!!, "res") database.setTransactionSuccessful() } finally { database.endTransaction() database.close() } return httpCallRecordId } fun findAllSortByDate(): List<HttpCallRecord> { val httpCallRecords = ArrayList<HttpCallRecord>() val cursorParser = HttpCallRecordCursorParser() val database = dbReadHelper.readableDatabase val cursor = database.rawQuery(HTTP_CALL_RECORD_GET_SORT_BY_DATE, null) while (cursor.moveToNext()) { httpCallRecords.add(cursorParser.parse(cursor)) } cursor.close() database.close() return httpCallRecords } fun searchHttpRecord(text: String): List<HttpCallRecord> { val httpCallRecords = ArrayList<HttpCallRecord>() val cursorParser = HttpCallRecordCursorParser() val database = dbReadHelper.readableDatabase val cursor = database.rawQuery( HTTP_CALL_RECORD_SEARCH, arrayOf(likeParam(text), likeParam(text), likeParam(text), likeParam(text)) ) while (cursor.moveToNext()) { httpCallRecords.add(cursorParser.parse(cursor)) } cursor.close() database.close() return httpCallRecords } private fun likeParam(text: String): String { return "%$text%" } fun findAllSortByDateAfter(id: Long, pageSize: Int): MutableList<HttpCallRecord> { val httpCallRecords = ArrayList<HttpCallRecord>() val cursorParser = HttpCallRecordCursorParser() val database = dbReadHelper.readableDatabase val cursor: Cursor cursor = if (id == -1L) { database.rawQuery( HTTP_CALL_RECORD_GET_SORT_BY_DATE_WITH_SIZE, arrayOf(pageSize.toString()) ) } else { database.rawQuery( HTTP_CALL_RECORD_GET_NEXT_SORT_BY_DATE_WITH_SIZE, arrayOf(id.toString(), pageSize.toString()) ) } while (cursor.moveToNext()) { httpCallRecords.add(cursorParser.parse(cursor)) } cursor.close() database.close() return httpCallRecords } fun findById(id: Long): HttpCallRecord { val database = dbReadHelper.readableDatabase val cursorParser = HttpCallRecordCursorParser() val cursor = database.rawQuery(HTTP_CALL_RECORD_GET_BY_ID, arrayOf(java.lang.Long.toString(id))) cursor.moveToNext() val httpCallRecord = cursorParser.parse(cursor) httpCallRecord.requestHeaders = findHeader(database, httpCallRecord.id, "req") httpCallRecord.responseHeaders = findHeader(database, httpCallRecord.id, "res") database.close() return httpCallRecord } fun deleteAll() { val database = dbWriteHelper.writableDatabase try { database.beginTransaction() database.delete(HTTP_CALL_RECORD_TABLE_NAME, null, null) database.setTransactionSuccessful() } finally { database.endTransaction() database.close() } } private fun findHeader( database: SQLiteDatabase, callId: Long, headerType: String ): List<HttpHeader> { val httpHeaders = ArrayList<HttpHeader>() val cursorParser = HttpHeaderCursorParser() val cursor = database.rawQuery( HTTP_HEADER_GET_BY_CALL_ID, arrayOf(callId.toString(), headerType) ) while (cursor.moveToNext()) { val httpHeader = cursorParser.parse(cursor) httpHeader.values = findHeaderValue(database, httpHeader.id) httpHeaders.add(httpHeader) } cursor.close() return httpHeaders } private fun findHeaderValue(database: SQLiteDatabase, headerId: Int): List<HttpHeaderValue> { val httpHeaderValues = ArrayList<HttpHeaderValue>() val cursorParser = HttpHeaderValueCursorParser() val cursor = database.rawQuery( HTTP_HEADER_VALUE_GET_BY_HEADER_ID, arrayOf(Integer.toString(headerId)) ) while (cursor.moveToNext()) { httpHeaderValues.add(cursorParser.parse(cursor)) } cursor.close() return httpHeaderValues } private fun saveHeaders( database: SQLiteDatabase, httpCallRecordId: Long, requestHeaders: List<HttpHeader>, headerType: String ) { for (httpHeader in requestHeaders) { saveHeader(database, httpHeader, httpCallRecordId, headerType) } } private fun saveHeader( database: SQLiteDatabase, httpHeader: HttpHeader, httpCallRecordId: Long, headerType: String ) { val values = ContentValues() values.put(COLUMN_HEADER_NAME, httpHeader.name) values.put(COLUMN_HEADER_TYPE, headerType) values.put(COLUMN_HTTP_CALL_RECORD_ID, httpCallRecordId) val headerId = database.insert(HEADER_TABLE_NAME, null, values) for (httpHeaderValue in httpHeader.values) { saveHeaderValue(database, httpHeaderValue, headerId) } } private fun saveHeaderValue(database: SQLiteDatabase, value: HttpHeaderValue, headerId: Long) { val values = ContentValues() values.put(COLUMN_HEADER_VALUE, value.value) values.put(COLUMN_HEADER_ID, headerId) database.insert(HEADER_VALUE_TABLE_NAME, null, values) } }
Snooper/src/main/java/com/prateekj/snooper/networksnooper/database/SnooperRepo.kt
2403132853
package com.maximebertheau.emoji data class SkinVariation( val types: List<SkinVariationType>, val unified: String ) { val unicode get() = unified.unicode }
src/main/java/com/maximebertheau/emoji/SkinVariation.kt
3795870689
/** * @author rinp * @since 2015/10/22 */ package xxx.jq.service import org.junit.Before import org.junit.Test import org.junit.runner.JUnitCore import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.SpringApplicationConfiguration import org.springframework.security.core.userdetails.UserDetails import org.springframework.test.annotation.Rollback import org.springframework.test.context.junit4.SpringJUnit4ClassRunner import org.springframework.transaction.annotation.Transactional import xxx.jq.AccountRepository import xxx.jq.Application import xxx.jq.entity.Account import java.util.* import kotlin.test.assertEquals /** * @author rinp * @since 2015/10/08 */ @SpringApplicationConfiguration(classes = arrayOf(Application::class)) @RunWith(SpringJUnit4ClassRunner::class) @Rollback @Transactional open class AccountServiceTest { companion object { @JvmStatic fun main(args: Array<String>) { JUnitCore.main(AccountServiceTest::class.java.name); } } @Autowired lateinit var service: AccountService; @Autowired lateinit var repo: AccountRepository; val a1 = Account(mail = "[email protected]", accountId = "testA", password = "passA") val a2 = Account(mail = "[email protected]", accountId = "testB", password = "passB") val a3 = Account(mail = "[email protected]", accountId = "testC", password = "passC") val a4 = Account(mail = "[email protected]", accountId = "testD", password = "passD") @Before fun setUp() { repo.save(listOf(a1, a2, a3, a4)) } @Test fun loadUserByUsernameTest() { val t1: UserDetails = service.loadUserByUsername("testA") val actual: UserDetails? = repo.findAll().find { it.accountId == "testA" } assertEquals(t1, actual) } @Test fun findOneTest() { val target: Account = repo.findAll().find { it.accountId == "testC" } ?: throw NoSuchElementException("Collection is empty.") val one = service.findOne(target.id!!) assertEquals(one, target) } @Test fun findByAccountIdTest() { val target: Account = repo.findAll().find { it.username == "testD" } ?: throw NoSuchElementException("Collection is empty.") val account = service.findByAccountId(target.accountId) assertEquals(account, target) } @Test fun countByAccountIdTest() { val n = service.countByAccountId("testD") assertEquals(n, 1) val n2 = service.countByAccountId("AAAAAtestD") assertEquals(n2, 0) } // @Test // fun saveTest() { // // } // // @Throws(UsernameNotFoundException::class) // override fun loadUserByUsername(username: String): UserDetails { // // return repo.findByAccountId(username) ?: throw UsernameNotFoundException("no get user details") // } // // fun save(account: Account): Account { // return repo.save(account) // } }
src/test/kotlin/xxx/jq/service/AccountServiceTest.kt
2471143762
// 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.inspections.blockingCallsDetection import com.intellij.codeInspection.blockingCallsDetection.ContextType import com.intellij.codeInspection.blockingCallsDetection.ContextType.* import com.intellij.codeInspection.blockingCallsDetection.ElementContext import com.intellij.codeInspection.blockingCallsDetection.NonBlockingContextChecker import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiRecursiveElementVisitor import com.intellij.psi.util.parentsOfType import com.intellij.util.castSafelyTo import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.builtins.getReceiverTypeFromFunctionType import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType import org.jetbrains.kotlin.builtins.isSuspendFunctionType import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.receiverValue import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.BLOCKING_EXECUTOR_ANNOTATION import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.COROUTINE_CONTEXT import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.COROUTINE_SCOPE import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.DEFAULT_DISPATCHER_FQN import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.FLOW_PACKAGE_FQN import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.IO_DISPATCHER_FQN import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.MAIN_DISPATCHER_FQN import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.NONBLOCKING_EXECUTOR_ANNOTATION import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.findFlowOnCall import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypes import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument import org.jetbrains.kotlin.resolve.calls.checkers.isRestrictsSuspensionReceiver import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver import org.jetbrains.kotlin.types.KotlinType class CoroutineNonBlockingContextChecker : NonBlockingContextChecker { override fun isApplicable(file: PsiFile): Boolean { if (file !is KtFile) return false val languageVersionSettings = getLanguageVersionSettings(file) return languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines) } override fun computeContextType(elementContext: ElementContext): ContextType { val element = elementContext.element if (element !is KtCallExpression) return Unsure val containingLambda = element.parents .filterIsInstance<KtLambdaExpression>() .firstOrNull() val containingArgument = containingLambda?.getParentOfType<KtValueArgument>(true, KtCallableDeclaration::class.java) if (containingArgument != null) { val callExpression = containingArgument.getStrictParentOfType<KtCallExpression>() ?: return Blocking val call = callExpression.resolveToCall(BodyResolveMode.PARTIAL) ?: return Blocking val blockingFriendlyDispatcherUsed = checkBlockingFriendlyDispatcherUsed(call, callExpression) if (blockingFriendlyDispatcherUsed.isDefinitelyKnown) return blockingFriendlyDispatcherUsed val parameterForArgument = call.getParameterForArgument(containingArgument) ?: return Blocking val type = parameterForArgument.returnType ?: return Blocking if (type.isBuiltinFunctionalType) { val hasRestrictSuspensionAnnotation = type.getReceiverTypeFromFunctionType()?.isRestrictsSuspensionReceiver() ?: false return if (!hasRestrictSuspensionAnnotation && type.isSuspendFunctionType) NonBlocking.INSTANCE else Blocking } } if (containingLambda == null) { val isInSuspendFunctionBody = element.parentsOfType<KtNamedFunction>() .take(2) .firstOrNull { function -> function.nameIdentifier != null } ?.hasModifier(KtTokens.SUSPEND_KEYWORD) ?: false return if (isInSuspendFunctionBody) NonBlocking.INSTANCE else Blocking } val containingPropertyOrFunction: KtCallableDeclaration? = containingLambda.getParentOfTypes(true, KtProperty::class.java, KtNamedFunction::class.java) if (containingPropertyOrFunction?.typeReference?.hasModifier(KtTokens.SUSPEND_KEYWORD) == true) return NonBlocking.INSTANCE return if (containingPropertyOrFunction?.hasModifier(KtTokens.SUSPEND_KEYWORD) == true) NonBlocking.INSTANCE else Blocking } private fun checkBlockingFriendlyDispatcherUsed( call: ResolvedCall<out CallableDescriptor>, callExpression: KtCallExpression ): ContextType { return union( { checkBlockFriendlyDispatcherParameter(call) }, { checkFunctionWithDefaultDispatcher(callExpression) }, { checkFlowChainElementWithIODispatcher(call, callExpression) } ) } private fun getLanguageVersionSettings(psiElement: PsiElement): LanguageVersionSettings = psiElement.module?.languageVersionSettings ?: psiElement.project.languageVersionSettings private fun ResolvedCall<*>.getFirstArgument(): KtExpression? = valueArgumentsByIndex?.firstOrNull()?.arguments?.firstOrNull()?.getArgumentExpression() private fun KotlinType.isCoroutineContext(): Boolean = (this.constructor.supertypes + this).any { it.fqName?.asString() == COROUTINE_CONTEXT } private fun checkBlockFriendlyDispatcherParameter(call: ResolvedCall<*>): ContextType { val argumentDescriptor = call.getFirstArgument()?.resolveToCall()?.resultingDescriptor ?: return Unsure return argumentDescriptor.isBlockFriendlyDispatcher() } private fun checkFunctionWithDefaultDispatcher(callExpression: KtCallExpression): ContextType { val classDescriptor = callExpression.receiverValue().castSafelyTo<ImplicitClassReceiver>()?.classDescriptor ?: return Unsure if (classDescriptor.typeConstructor.supertypes.none { it.fqName?.asString() == COROUTINE_SCOPE }) return Unsure val propertyDescriptor = classDescriptor .unsubstitutedMemberScope .getContributedDescriptors(DescriptorKindFilter.VARIABLES) .filterIsInstance<PropertyDescriptor>() .singleOrNull { it.isOverridableOrOverrides && it.type.isCoroutineContext() } ?: return Unsure val initializer = propertyDescriptor.findPsi().castSafelyTo<KtProperty>()?.initializer ?: return Unsure return initializer.hasBlockFriendlyDispatcher() } private fun checkFlowChainElementWithIODispatcher( call: ResolvedCall<out CallableDescriptor>, callExpression: KtCallExpression ): ContextType { val isInsideFlow = call.resultingDescriptor.fqNameSafe.asString().startsWith(FLOW_PACKAGE_FQN) if (!isInsideFlow) return Unsure val flowOnCall = callExpression.findFlowOnCall() ?: return NonBlocking.INSTANCE return checkBlockFriendlyDispatcherParameter(flowOnCall) } private fun KtExpression.hasBlockFriendlyDispatcher(): ContextType { class RecursiveExpressionVisitor : PsiRecursiveElementVisitor() { var allowsBlocking: ContextType = Unsure override fun visitElement(element: PsiElement) { if (element is KtExpression) { val callableDescriptor = element.getCallableDescriptor() val allowsBlocking = callableDescriptor.castSafelyTo<DeclarationDescriptor>() ?.isBlockFriendlyDispatcher() if (allowsBlocking != null && allowsBlocking != Unsure) { this.allowsBlocking = allowsBlocking return } } super.visitElement(element) } } return RecursiveExpressionVisitor().also(this::accept).allowsBlocking } private fun DeclarationDescriptor?.isBlockFriendlyDispatcher(): ContextType { if (this == null) return Unsure val returnTypeDescriptor = this.castSafelyTo<CallableDescriptor>()?.returnType val typeConstructor = returnTypeDescriptor?.constructor?.declarationDescriptor if (isTypeOrUsageAnnotatedWith(returnTypeDescriptor, typeConstructor, BLOCKING_EXECUTOR_ANNOTATION)) return Blocking if (isTypeOrUsageAnnotatedWith(returnTypeDescriptor, typeConstructor, NONBLOCKING_EXECUTOR_ANNOTATION)) return NonBlocking.INSTANCE val fqnOrNull = fqNameOrNull()?.asString() ?: return NonBlocking.INSTANCE return when(fqnOrNull) { IO_DISPATCHER_FQN -> Blocking MAIN_DISPATCHER_FQN, DEFAULT_DISPATCHER_FQN -> NonBlocking.INSTANCE else -> Unsure } } private fun isTypeOrUsageAnnotatedWith(type: KotlinType?, typeConstructor: ClassifierDescriptor?, annotationFqn: String): Boolean { val fqName = FqName(annotationFqn) return when { type?.annotations?.hasAnnotation(fqName) == true -> true typeConstructor?.annotations?.hasAnnotation(fqName) == true -> true else -> false } } private fun union(vararg checks: () -> ContextType): ContextType { for (check in checks) { val iterationResult = check() if (iterationResult != Unsure) return iterationResult } return Unsure } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/blockingCallsDetection/CoroutineNonBlockingContextChecker.kt
3686848105
package com.bajdcc.LALR1.interpret.module import com.bajdcc.LALR1.grammar.Grammar import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage import com.bajdcc.util.ResourceLoader /** * 【模块】LISP * * @author bajdcc */ class ModuleLisp : IInterpreterModule { private var runtimeCodePage: RuntimeCodePage? = null override val moduleName: String get() = "module.lisp" override val moduleCode: String get() = ResourceLoader.load(javaClass) override val codePage: RuntimeCodePage @Throws(Exception::class) get() { if (runtimeCodePage != null) return runtimeCodePage!! val base = ResourceLoader.load(javaClass) val grammar = Grammar(base) val page = grammar.codePage runtimeCodePage = page return page } companion object { val instance = ModuleLisp() } }
src/main/kotlin/com/bajdcc/LALR1/interpret/module/ModuleLisp.kt
2669605974
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.lang.documentation.ide.impl import com.intellij.codeInsight.documentation.DocumentationManager import com.intellij.codeInsight.lookup.LookupElement import com.intellij.lang.documentation.DocumentationTarget import com.intellij.lang.documentation.ide.IdeDocumentationTargetProvider import com.intellij.lang.documentation.psi.psiDocumentationTarget import com.intellij.lang.documentation.symbol.impl.symbolDocumentationTargets import com.intellij.model.Pointer import com.intellij.model.Symbol import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.component1 import com.intellij.openapi.util.component2 import com.intellij.psi.PsiFile import com.intellij.util.castSafelyTo open class IdeDocumentationTargetProviderImpl(private val project: Project) : IdeDocumentationTargetProvider { override fun documentationTarget(editor: Editor, file: PsiFile, lookupElement: LookupElement): DocumentationTarget? { val symbolTargets = (lookupElement.`object` as? Pointer<*>) ?.dereference() ?.castSafelyTo<Symbol>() ?.let { symbolDocumentationTargets(file.project, listOf(it)) } if (!symbolTargets.isNullOrEmpty()) { return symbolTargets.first() } val sourceElement = file.findElementAt(editor.caretModel.offset) val targetElement = DocumentationManager.getElementFromLookup(project, editor, file, lookupElement) ?: return null return psiDocumentationTarget(targetElement, sourceElement) } override fun documentationTargets(editor: Editor, file: PsiFile, offset: Int): List<DocumentationTarget> { val symbolTargets = symbolDocumentationTargets(file, offset) if (symbolTargets.isNotEmpty()) { return symbolTargets } val documentationManager = DocumentationManager.getInstance(project) val (targetElement, sourceElement) = documentationManager.findTargetElementAndContext(editor, offset, file) ?: return emptyList() return listOf(psiDocumentationTarget(targetElement, sourceElement)) } }
platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/IdeDocumentationTargetProviderImpl.kt
2396182300
/* * 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.action.internal import com.intellij.codeInsight.daemon.impl.HintRenderer import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.VisualPosition import com.maddyhome.idea.vim.api.lineLength import com.maddyhome.idea.vim.api.visualLineToBufferLine import com.maddyhome.idea.vim.helper.VimNlsSafe import com.maddyhome.idea.vim.newapi.vim import java.util.* import kotlin.math.max class AddInlineInlaysAction : AnAction() { companion object { private val random = Random() } override fun actionPerformed(e: AnActionEvent) { val dataContext = e.dataContext val editor = getEditor(dataContext) ?: return val vimEditor = editor.vim val inlayModel = editor.inlayModel val currentVisualLine = editor.caretModel.primaryCaret.visualPosition.line var i = random.nextInt(10) val lineLength = vimEditor.lineLength(vimEditor.visualLineToBufferLine(currentVisualLine)) while (i < lineLength) { val relatesToPrecedingText = random.nextInt(10) > 7 @VimNlsSafe val text = "a".repeat(max(1, random.nextInt(7))) val offset = editor.visualPositionToOffset(VisualPosition(currentVisualLine, i)) // We don't need a custom renderer, just use the standard parameter hint renderer inlayModel.addInlineElement( offset, relatesToPrecedingText, HintRenderer(if (relatesToPrecedingText) ":$text" else "$text:") ) // Every 20 chars +/- 5 chars i += 20 + (random.nextInt(10) - 5) } } private fun getEditor(dataContext: DataContext): Editor? { return CommonDataKeys.EDITOR.getData(dataContext) } }
src/main/java/com/maddyhome/idea/vim/action/internal/AddInlineInlaysAction.kt
2715361175
/* * 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.action.macro 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.Argument import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.VimActionHandler import com.maddyhome.idea.vim.helper.vimStateMachine class ToggleRecordingAction : VimActionHandler.SingleExecution() { override val type: Command.Type = Command.Type.OTHER_READONLY override val argumentType: Argument.Type = Argument.Type.CHARACTER override fun execute(editor: VimEditor, context: ExecutionContext, cmd: Command, operatorArguments: OperatorArguments): Boolean { return if (!editor.vimStateMachine.isRecording) { val argument = cmd.argument ?: return false val reg = argument.character injector.registerGroup.startRecording(editor, reg) } else { injector.registerGroup.finishRecording(editor) true } } }
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/macro/ToggleRecordingAction.kt
4110773825
package info.shibafu528.spermaster.activity import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MenuItem import info.shibafu528.spermaster.fragment.AchievementListFragment /** * Created by shibafu on 15/07/20. */ public class AchievementActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar?.setDisplayHomeAsUpEnabled(true) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(android.R.id.content, AchievementListFragment()) .commit() } } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item!!.itemId == android.R.id.home) { finish() return true } return super.onOptionsItemSelected(item) } }
app/src/main/kotlin/info/shibafu528/spermaster/activity/AchievementActivity.kt
2850851680
package io.sledge.deployer.common import com.github.ajalt.clikt.output.TermUi import io.sledge.deployer.core.exception.SledgeCommandException class SledgeConsoleReporter { fun writeSledgeCommandExceptionInfo(se: SledgeCommandException) { TermUi.echo("Sledge request failed. Reason: " + se.localizedMessage) TermUi.echo("-----------------------------------------------") TermUi.echo("Error information:") TermUi.echo("Request url: ${se.requestUrl}") TermUi.echo("Response code: ${se.responseCode}") TermUi.echo("Response body: ${se.responseBody}") TermUi.echo("-----------------------------------------------\n") } }
src/main/kotlin/io/sledge/deployer/common/SledgeConsoleReporter.kt
1987345606
package org.hexworks.zircon.internal.modifier import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.modifier.TextureTransformModifier data class TileCoordinate(val position: Position) : TextureTransformModifier { override val cacheKey: String get() = "Internal.Modifier.TileCoordinate(x=${position.x},y=${position.y})" }
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/modifier/TileCoordinate.kt
2293217975
package com.github.xiaofei_dev.ninegrid.extensions import android.content.Context import android.content.Intent import android.net.Uri import android.widget.Toast /** * Created by xiaofei on 2017/7/19. */ object ToastUtil { private var toast: Toast? = null fun showToast(context: Context, content: String) { if (toast == null) { toast = Toast.makeText(context, content, Toast.LENGTH_LONG) } else { toast!!.setText(content) } toast!!.show() } fun showToast(context: Context, content: Int) { if (toast == null) { toast = Toast.makeText(context, content, Toast.LENGTH_LONG) } else { toast!!.setText(content) } toast!!.show() } } object OpenUtil { fun openApplicationMarket(appPackageName: String, marketPackageName: String?, context: Context) { try { val url = "market://details?id=" + appPackageName val localIntent = Intent(Intent.ACTION_VIEW) if (marketPackageName != null) { localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) localIntent.`package` = marketPackageName } openLink(context, localIntent, url, true) } catch (e: Exception) { e.printStackTrace() openApplicationMarketForLinkBySystem(appPackageName, context) } } fun openApplicationMarketForLinkBySystem(packageName: String, context: Context) { val url = "http://www.coolapk.com/apk/" + packageName val intent = Intent(Intent.ACTION_VIEW) openLink(context, intent, url, false) } fun openLink(context: Context, intent: Intent?, link: String, isThrowException: Boolean) { var intent = intent if (intent == null) { intent = Intent(Intent.ACTION_VIEW) } try { intent.data = Uri.parse(link) context.startActivity(intent) } catch (e: Exception) { if (isThrowException) { throw e } else { e.printStackTrace() Toast.makeText(context, "打开失败", Toast.LENGTH_SHORT).show() } } } //打开自己的支付宝付款链接 fun alipayDonate(context: Context) { val intent = Intent() intent.action = "android.intent.action.VIEW" //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); val payUrl = "https://qr.alipay.com/FKX06496G2PCRYR0LXR7BC" intent.data = Uri.parse("alipayqr://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=" + payUrl) if (intent.resolveActivity(context.packageManager) != null) { context.startActivity(intent) } else { intent.data = Uri.parse(payUrl) context.startActivity(intent) } } }
app/src/main/java/com/github/xiaofei_dev/ninegrid/extensions/util.kt
1195418463
package org.wordpress.android.ui.stats.refresh.lists import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView data class StatsListItemDecoration( val horizontalSpacing: Int, val topSpacing: Int, val bottomSpacing: Int, val firstSpacing: Int, val lastSpacing: Int, val columnCount: Int ) : RecyclerView.ItemDecoration() { override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { super.getItemOffsets(outRect, view, parent, state) val isFirst = parent.getChildAdapterPosition(view) == 0 val isLast = parent.adapter?.let { parent.getChildAdapterPosition(view) == it.itemCount - 1 } ?: false outRect.set( if (columnCount == 1) 2 * horizontalSpacing else horizontalSpacing, if (isFirst) firstSpacing else topSpacing, if (columnCount == 1) 2 * horizontalSpacing else horizontalSpacing, if (isLast) lastSpacing else bottomSpacing ) } }
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/StatsListItemDecoration.kt
1991089246
package org.wordpress.android.imageeditor.preview import android.text.TextUtils import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import org.wordpress.android.imageeditor.ImageEditor import org.wordpress.android.imageeditor.ImageEditor.EditorAction.EditorFinishedEditing import org.wordpress.android.imageeditor.ImageEditor.EditorAction.EditorShown import org.wordpress.android.imageeditor.ImageEditor.EditorAction.PreviewCropMenuClicked import org.wordpress.android.imageeditor.ImageEditor.EditorAction.PreviewImageSelected import org.wordpress.android.imageeditor.ImageEditor.EditorAction.PreviewInsertImagesClicked import org.wordpress.android.imageeditor.R import org.wordpress.android.imageeditor.preview.PreviewImageFragment.Companion.EditImageData.InputData import org.wordpress.android.imageeditor.preview.PreviewImageFragment.Companion.EditImageData.OutputData import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageLoadToFileState.ImageLoadToFileFailedState import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageLoadToFileState.ImageLoadToFileIdleState import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageLoadToFileState.ImageLoadToFileSuccessState import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageLoadToFileState.ImageStartLoadingToFileState import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageUiState.ImageDataStartLoadingUiState import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageUiState.ImageInHighResLoadFailedUiState import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageUiState.ImageInHighResLoadSuccessUiState import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageUiState.ImageInLowResLoadFailedUiState import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageUiState.ImageInLowResLoadSuccessUiState import org.wordpress.android.imageeditor.viewmodel.Event import java.net.URI import java.util.Locale import java.util.UUID class PreviewImageViewModel : ViewModel() { private val _uiState: MutableLiveData<UiState> = MutableLiveData() val uiState: LiveData<UiState> = _uiState private val _loadIntoFile = MutableLiveData<Event<ImageLoadToFileState>>(Event(ImageLoadToFileIdleState)) val loadIntoFile: LiveData<Event<ImageLoadToFileState>> = _loadIntoFile private val _navigateToCropScreenWithFileInfo = MutableLiveData<Event<Triple<String, String?, Boolean>>>() val navigateToCropScreenWithFileInfo: LiveData<Event<Triple<String, String?, Boolean>>> = _navigateToCropScreenWithFileInfo private val _finishAction = MutableLiveData<Event<List<OutputData>>>() val finishAction: LiveData<Event<List<OutputData>>> = _finishAction private lateinit var imageEditor: ImageEditor var selectedPosition: Int = 0 private set var numberOfImages = 0 private set fun onCreateView(imageDataList: List<InputData>, imageEditor: ImageEditor) { this.imageEditor = imageEditor this.numberOfImages = imageDataList.size if (uiState.value == null) { imageEditor.onEditorAction(EditorShown(numberOfImages)) val newImageUiStates = createViewPagerItemsInitialUiStates( convertInputDataToImageData(imageDataList) ) val currentUiState = UiState( newImageUiStates, thumbnailsTabLayoutVisible = !newImageUiStates.hasSingleElement() ) updateUiState(currentUiState) } } private fun convertInputDataToImageData(imageDataList: List<InputData>): List<ImageData> { return imageDataList .map { (highRes, lowRes, extension) -> ImageData( highResImageUrl = highRes, lowResImageUrl = lowRes, outputFileExtension = extension ) } } fun onLoadIntoImageViewSuccess(imageUrlAtPosition: String, position: Int) { val newImageUiState = createNewImageUiState(imageUrlAtPosition, position, loadSuccess = true) val newImageUiStates = updateViewPagerItemsUiStates(newImageUiState, position) val currentUiState = uiState.value as UiState val imageStateAtPosition = currentUiState.viewPagerItemsStates[position] if (currentUiState.viewPagerItemsStates.hasSingleElement() && canLoadToFile(newImageUiState)) { updateLoadIntoFileState( ImageStartLoadingToFileState( imageUrlAtPosition = imageStateAtPosition.data.highResImageUrl, position = position ) ) } val enableEditActions = if (position == selectedPosition) { shouldEnableEditActionsForImageState(newImageUiState) } else { currentUiState.editActionsEnabled } updateUiState( currentUiState.copy( viewPagerItemsStates = newImageUiStates, editActionsEnabled = enableEditActions ) ) } fun onLoadIntoImageViewFailed(imageUrlAtPosition: String, position: Int) { val newImageUiState = createNewImageUiState(imageUrlAtPosition, position, loadSuccess = false) val newImageUiStates = updateViewPagerItemsUiStates(newImageUiState, position) val currentUiState = uiState.value as UiState updateUiState(currentUiState.copy(viewPagerItemsStates = newImageUiStates)) } fun onLoadIntoFileSuccess(inputFilePathAtPosition: String, position: Int) { val imageStateAtPosition = (uiState.value as UiState).viewPagerItemsStates[position] val outputFileExtension = imageStateAtPosition.data.outputFileExtension updateLoadIntoFileState(ImageLoadToFileSuccessState(inputFilePathAtPosition, position)) val currentUiState = uiState.value as UiState _navigateToCropScreenWithFileInfo.value = Event( Triple( inputFilePathAtPosition, outputFileExtension, !currentUiState.viewPagerItemsStates.hasSingleElement() ) ) } fun onLoadIntoFileFailed(exception: Exception?) { updateLoadIntoFileState( ImageLoadToFileFailedState( exception?.message, R.string.error_failed_to_load_into_file ) ) } fun onCropMenuClicked() { imageEditor.onEditorAction(PreviewCropMenuClicked) val highResImageUrl = getHighResImageUrl(selectedPosition) if (isFileUrl(highResImageUrl)) { onLoadIntoFileSuccess( inputFilePathAtPosition = URI(highResImageUrl).path as String, position = selectedPosition ) } else { updateLoadIntoFileState( ImageStartLoadingToFileState( imageUrlAtPosition = highResImageUrl, position = selectedPosition ) ) } } fun onPageSelected(selectedPosition: Int) { this.selectedPosition = selectedPosition imageEditor.onEditorAction(PreviewImageSelected(getHighResImageUrl(selectedPosition), selectedPosition)) val currentUiState = uiState.value as UiState val imageStateAtPosition = currentUiState.viewPagerItemsStates[selectedPosition] updateUiState( currentUiState.copy( editActionsEnabled = shouldEnableEditActionsForImageState(imageStateAtPosition) ) ) } private fun onLoadIntoImageViewRetry(selectedImageUrl: String, selectedPosition: Int) { val newImageUiState = createNewImageUiState( imageUrlAtPosition = selectedImageUrl, position = selectedPosition, loadSuccess = false, retry = true ) val newImageUiStates = updateViewPagerItemsUiStates(newImageUiState, selectedPosition) val currentUiState = uiState.value as UiState updateUiState(currentUiState.copy(viewPagerItemsStates = newImageUiStates)) } fun onCropResult(outputFilePath: String) { val imageStateAtPosition = (uiState.value as UiState).viewPagerItemsStates[selectedPosition] // Update urls with cache file path val newImageData = imageStateAtPosition.data.copy( lowResImageUrl = outputFilePath, highResImageUrl = outputFilePath ) val newImageUiState = ImageDataStartLoadingUiState(newImageData) val newImageUiStates = updateViewPagerItemsUiStates(newImageUiState, selectedPosition) val currentUiState = uiState.value as UiState updateUiState(currentUiState.copy(viewPagerItemsStates = newImageUiStates)) } private fun createViewPagerItemsInitialUiStates( data: List<ImageData> ): List<ImageUiState> = data.map { createImageLoadStartUiState(it) } private fun updateViewPagerItemsUiStates( newImageUiState: ImageUiState, position: Int ): List<ImageUiState> { val currentUiState = uiState.value as UiState val items = currentUiState.viewPagerItemsStates.toMutableList() items[position] = newImageUiState return items } private fun createNewImageUiState( imageUrlAtPosition: String, position: Int, loadSuccess: Boolean, retry: Boolean = false ): ImageUiState { val currentUiState = uiState.value as UiState val imageStateAtPosition = currentUiState.viewPagerItemsStates[position] val imageDataAtPosition = imageStateAtPosition.data return when { loadSuccess -> createImageLoadSuccessUiState(imageUrlAtPosition, imageStateAtPosition) retry -> createImageLoadStartUiState(imageDataAtPosition) else -> createImageLoadFailedUiState(imageUrlAtPosition, imageStateAtPosition, position) } } private fun createImageLoadStartUiState( imageData: ImageData ): ImageUiState { return ImageDataStartLoadingUiState(imageData) } private fun createImageLoadSuccessUiState( imageUrl: String, imageState: ImageUiState ): ImageUiState { val imageData = imageState.data return if (imageData.hasValidLowResImageUrlEqualTo(imageUrl)) { val isHighResImageAlreadyLoaded = imageState is ImageInHighResLoadSuccessUiState if (!isHighResImageAlreadyLoaded) { val isRetryShown = imageState is ImageInHighResLoadFailedUiState ImageInLowResLoadSuccessUiState(imageData, isRetryShown) } else { imageState } } else { ImageInHighResLoadSuccessUiState(imageData) } } private fun createImageLoadFailedUiState( imageUrlAtPosition: String, imageStateAtPosition: ImageUiState, position: Int ): ImageUiState { val imageDataAtPosition = imageStateAtPosition.data val imageUiState = if (imageDataAtPosition.hasValidLowResImageUrlEqualTo(imageUrlAtPosition)) { val isRetryShown = imageStateAtPosition is ImageInHighResLoadFailedUiState ImageInLowResLoadFailedUiState(imageDataAtPosition, isRetryShown) } else { ImageInHighResLoadFailedUiState(imageDataAtPosition) } imageUiState.onItemTapped = { onLoadIntoImageViewRetry(imageUrlAtPosition, position) } return imageUiState } private fun updateUiState(state: UiState) { _uiState.value = state } private fun updateLoadIntoFileState(fileState: ImageLoadToFileState) { _loadIntoFile.value = Event(fileState) } private fun shouldEnableEditActionsForImageState(imageState: ImageUiState) = imageState is ImageInHighResLoadSuccessUiState // TODO: revisit @Suppress("ForbiddenComment") private fun canLoadToFile(imageState: ImageUiState) = imageState is ImageInHighResLoadSuccessUiState private fun List<ImageUiState>.hasSingleElement() = this.size == 1 fun onInsertClicked() { with(imageEditor) { onEditorAction(PreviewInsertImagesClicked(getOutputData())) onEditorAction(EditorFinishedEditing(getOutputData())) } _finishAction.value = Event(getOutputData()) } fun getThumbnailImageUrl(position: Int): String { return uiState.value?.viewPagerItemsStates?.get(position)?.data?.let { imageData -> return if (TextUtils.isEmpty(imageData.lowResImageUrl)) { imageData.highResImageUrl } else { imageData.lowResImageUrl as String } } ?: "" } fun getHighResImageUrl(position: Int): String = uiState.value?.viewPagerItemsStates?.get(position)?.data?.highResImageUrl ?: "" private fun getOutputData() = (uiState.value?.viewPagerItemsStates?.map { OutputData(it.data.highResImageUrl) } ?: emptyList()) private fun isFileUrl(url: String): Boolean = url.lowercase(Locale.ROOT).startsWith(FILE_BASE) data class ImageData( val id: Long = UUID.randomUUID().hashCode().toLong(), val lowResImageUrl: String?, val highResImageUrl: String, val outputFileExtension: String? ) { fun hasValidLowResImageUrlEqualTo(imageUrl: String): Boolean { val hasValidLowResImageUrl = this.lowResImageUrl?.isNotEmpty() == true && this.lowResImageUrl != this.highResImageUrl val isGivenUrlEqualToLowResImageUrl = imageUrl == this.lowResImageUrl return hasValidLowResImageUrl && isGivenUrlEqualToLowResImageUrl } } data class UiState( val viewPagerItemsStates: List<ImageUiState>, val editActionsEnabled: Boolean = false, val thumbnailsTabLayoutVisible: Boolean = true ) sealed class ImageUiState( val data: ImageData, val progressBarVisible: Boolean = false, val retryLayoutVisible: Boolean ) { var onItemTapped: (() -> Unit)? = null data class ImageDataStartLoadingUiState(val imageData: ImageData) : ImageUiState( data = imageData, progressBarVisible = true, retryLayoutVisible = false ) // Continue displaying progress bar on low res image load success data class ImageInLowResLoadSuccessUiState(val imageData: ImageData, val isRetryShown: Boolean = false) : ImageUiState( data = imageData, progressBarVisible = !isRetryShown, retryLayoutVisible = isRetryShown ) data class ImageInLowResLoadFailedUiState(val imageData: ImageData, val isRetryShown: Boolean = false) : ImageUiState( data = imageData, progressBarVisible = true, retryLayoutVisible = false ) data class ImageInHighResLoadSuccessUiState(val imageData: ImageData) : ImageUiState( data = imageData, progressBarVisible = false, retryLayoutVisible = false ) // Display retry only when high res image load failed data class ImageInHighResLoadFailedUiState(val imageData: ImageData) : ImageUiState( data = imageData, progressBarVisible = false, retryLayoutVisible = true ) } sealed class ImageLoadToFileState { object ImageLoadToFileIdleState : ImageLoadToFileState() data class ImageStartLoadingToFileState(val imageUrlAtPosition: String, val position: Int) : ImageLoadToFileState() data class ImageLoadToFileSuccessState(val filePathAtPosition: String, val position: Int) : ImageLoadToFileState() data class ImageLoadToFileFailedState(val errorMsg: String?, val errorResId: Int) : ImageLoadToFileState() } companion object { private const val FILE_BASE = "file:" } }
libs/image-editor/src/main/kotlin/org/wordpress/android/imageeditor/preview/PreviewImageViewModel.kt
3385524171
package com.android.mdl.app.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import androidx.annotation.DrawableRes import com.android.mdl.app.R class ColorAdapter( context: Context, ) : BaseAdapter() { private val inflater = LayoutInflater.from(context) private val labels = context.resources.getStringArray(R.array.document_color) override fun getCount(): Int = labels.size override fun getItem(position: Int): String = labels[position] override fun getItemId(position: Int): Long = labels[position].hashCode().toLong() override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val view = convertView ?: inflater.inflate(R.layout.color_dropdown_item, null, true) view.findViewById<TextView>(R.id.label).text = getItem(position) view.findViewById<View>(R.id.color_preview).setBackgroundResource(backgroundFor(position)) return view } @DrawableRes private fun backgroundFor(position: Int): Int { return when (position) { 1 -> R.drawable.yellow_gradient 2 -> R.drawable.blue_gradient else -> R.drawable.green_gradient } } }
appholder/src/main/java/com/android/mdl/app/adapter/ColorAdapter.kt
3393474691
package com.kelsos.mbrc.commands.visual import com.fasterxml.jackson.databind.node.ObjectNode import com.kelsos.mbrc.events.bus.RxBus import com.kelsos.mbrc.events.ui.TrackMoved import com.kelsos.mbrc.interfaces.ICommand import com.kelsos.mbrc.interfaces.IEvent import javax.inject.Inject class UpdateNowPlayingTrackMoved @Inject constructor(private val bus: RxBus) : ICommand { override fun execute(e: IEvent) { bus.post(TrackMoved(e.data as ObjectNode)) } }
app/src/main/kotlin/com/kelsos/mbrc/commands/visual/UpdateNowPlayingTrackMoved.kt
2112372071
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInsight.template.Template import com.intellij.codeInsight.template.TemplateBuilderImpl import com.intellij.codeInsight.template.TemplateEditingAdapter import com.intellij.codeInsight.template.TemplateManager import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.idea.codeinsight.utils.ChooseStringExpression import org.jetbrains.kotlin.idea.core.getOrCreateValueParameterList import org.jetbrains.kotlin.idea.refactoring.changeSignature.* import org.jetbrains.kotlin.idea.refactoring.resolveToExpectedDescriptorIfPossible import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference class ConvertReceiverToParameterIntention : SelfTargetingOffsetIndependentIntention<KtTypeReference>( KtTypeReference::class.java, KotlinBundle.lazyMessage("convert.receiver.to.parameter") ), LowPriorityAction { override fun isApplicableTo(element: KtTypeReference): Boolean = (element.parent as? KtNamedFunction)?.receiverTypeReference == element private fun configureChangeSignature(newName: String? = null): KotlinChangeSignatureConfiguration = object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor = originalDescriptor.modify { it.receiver = null if (newName != null) { it.parameters.first().name = newName } } override fun performSilently(affectedFunctions: Collection<PsiElement>) = true } override fun startInWriteAction() = false override fun applyTo(element: KtTypeReference, editor: Editor?) { val function = element.parent as? KtNamedFunction ?: return val descriptor = function.resolveToExpectedDescriptorIfPossible() as FunctionDescriptor val project = function.project if (editor != null && !isUnitTestMode()) { val receiverNames = suggestReceiverNames(project, descriptor) val defaultReceiverName = receiverNames.first() val receiverTypeRef = function.receiverTypeReference!! val psiFactory = KtPsiFactory(element) val newParameter = psiFactory.createParameter("$defaultReceiverName: Dummy").apply { typeReference!!.replace(receiverTypeRef) } project.executeWriteCommand(text) { function.setReceiverTypeReference(null) val addedParameter = function.getOrCreateValueParameterList().addParameterAfter(newParameter, null) with(PsiDocumentManager.getInstance(project)) { commitDocument(editor.document) doPostponedOperationsAndUnblockDocument(editor.document) } editor.caretModel.moveToOffset(function.startOffset) val templateBuilder = TemplateBuilderImpl(function) templateBuilder.replaceElement(addedParameter.nameIdentifier!!, ChooseStringExpression(receiverNames)) TemplateManager.getInstance(project).startTemplate( editor, templateBuilder.buildInlineTemplate(), object : TemplateEditingAdapter() { private fun revertChanges() { runWriteAction { function.setReceiverTypeReference(addedParameter.typeReference) function.valueParameterList!!.removeParameter(addedParameter) } } override fun templateFinished(template: Template, brokenOff: Boolean) { val newName = addedParameter.name revertChanges() if (!brokenOff) { runChangeSignature( element.project, editor, function.resolveToExpectedDescriptorIfPossible() as FunctionDescriptor, configureChangeSignature(newName), function.receiverTypeReference!!, text ) } } override fun templateCancelled(template: Template?) { revertChanges() } } ) } } else { runChangeSignature(element.project, editor, descriptor, configureChangeSignature(), element, text) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertReceiverToParameterIntention.kt
1557253459
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import org.jetbrains.deft.annotations.Open @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class SoftLinkReferencedChildImpl : SoftLinkReferencedChild, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(EntityWithSoftLinks::class.java, SoftLinkReferencedChild::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val parentEntity: EntityWithSoftLinks get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: SoftLinkReferencedChildData?) : ModifiableWorkspaceEntityBase<SoftLinkReferencedChild>(), SoftLinkReferencedChild.Builder { constructor() : this(SoftLinkReferencedChildData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity SoftLinkReferencedChild is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field SoftLinkReferencedChild#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field SoftLinkReferencedChild#parentEntity should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as SoftLinkReferencedChild this.entitySource = dataSource.entitySource if (parents != null) { this.parentEntity = parents.filterIsInstance<EntityWithSoftLinks>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var parentEntity: EntityWithSoftLinks get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as EntityWithSoftLinks } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as EntityWithSoftLinks } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override fun getEntityData(): SoftLinkReferencedChildData = result ?: super.getEntityData() as SoftLinkReferencedChildData override fun getEntityClass(): Class<SoftLinkReferencedChild> = SoftLinkReferencedChild::class.java } } class SoftLinkReferencedChildData : WorkspaceEntityData<SoftLinkReferencedChild>() { override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SoftLinkReferencedChild> { val modifiable = SoftLinkReferencedChildImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): SoftLinkReferencedChild { val entity = SoftLinkReferencedChildImpl() entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return SoftLinkReferencedChild::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return SoftLinkReferencedChild(entitySource) { this.parentEntity = parents.filterIsInstance<EntityWithSoftLinks>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(EntityWithSoftLinks::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as SoftLinkReferencedChildData if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as SoftLinkReferencedChildData return true } override fun hashCode(): Int { var result = entitySource.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SoftLinkReferencedChildImpl.kt
2222807463
package test object Test { @JvmStatic fun main(args: Array<String>) { println() // Comment foo() // Comment1 // Comment2 .indexOf("s") } fun foo(): String { return "" } }
plugins/kotlin/j2k/new/tests/testData/newJ2k/comments/commentInsideCall.kt
862377764
package instep.dao.sql import instep.dao.DaoException import java.sql.SQLException class SQLPlanExecutionException(e: SQLException?, override val message: String = "") : DaoException(message, e) { constructor(e: SQLException) : this(e, e.message ?: "") constructor(message: String) : this(null, message) }
dao/src/main/kotlin/instep/dao/sql/SQLPlanExecutionException.kt
2786918733
package co.uproot.unplug import javafx.beans.property.SimpleStringProperty import javafx.beans.property.SimpleListProperty import javafx.beans.property.SimpleObjectProperty import javafx.collections.ObservableList import org.fxmisc.easybind.EasyBind import java.util.HashMap import javafx.collections.FXCollections import javafx.beans.property.SimpleBooleanProperty import java.util.LinkedList import com.eclipsesource.json.JsonObject import javafx.scene.image.Image import javafx.beans.property.SimpleLongProperty data class UserState(val id: String) { val typing = SimpleBooleanProperty(false) val present = SimpleBooleanProperty(false) val displayName = SimpleStringProperty(""); val avatarURL = SimpleStringProperty(""); val lastActiveAgo = SimpleLongProperty(java.lang.Long.MAX_VALUE) private val SECONDS_PER_YEAR = (60L*60L*24L*365L) private val SECONDS_PER_DECADE = (10L * SECONDS_PER_YEAR) val weight = EasyBind.combine(typing, present, lastActiveAgo, { t, p, la -> val laSec = Math.min(la.toLong() / 1000, SECONDS_PER_DECADE) var result = (1 + (SECONDS_PER_DECADE - laSec )).toInt() if (t) { result *= 2 } if (p) { result *= 2 } result }) override fun toString() = "$id ${typing.get()} ${present.get()} ${weight.get()}" } class RoomState(val id:String, val aliases: MutableList<String>) // TODO: Avoid storing entire user state for every room. Instead have a common store and a lookup table class AppState() { val currRoomId = SimpleStringProperty("") val currChatMessageList = SimpleObjectProperty<ObservableList<Message>>() val currUserList = SimpleObjectProperty<ObservableList<UserState>>() val roomStateList = SimpleListProperty<RoomState>(FXCollections.observableArrayList()) val roomNameList = EasyBind.map(roomStateList, { room: RoomState -> room.aliases.firstOrNull() ?: room.id }) private final val roomChatMessageStore = HashMap<String, ObservableList<Message>>() private final val roomUserStore = HashMap<String, ObservableList<UserState>>() synchronized fun processSyncResult(result: SyncResult, api:API) { result.rooms.stream().forEach { room -> val existingRoomState = roomStateList.firstOrNull { it.id == room.id } if (existingRoomState == null) { roomStateList.add(RoomState(room.id, LinkedList(room.aliases))) } else { existingRoomState.aliases.addAll(room.aliases) } getRoomChatMessages(room.id).setAll(room.chatMessages()) val users = getRoomUsers(room.id) room.states.forEach { state: State -> when (state.type) { "m.room.member" -> { if (state.content.getString("membership", "") == "join") { val us = UserState(state.userId) val displayName = state.content.getStringOrElse("displayname", state.userId) us.displayName.setValue(displayName) us.avatarURL.setValue(api.getAvatarThumbnailURL(state.content.getStringOrElse("avatar_url",""))) users.add(us) } else { users.removeFirstMatching { it.id == state.userId } } } "m.room.aliases" -> { // TODO } "m.room.power_levels" -> { // TODO } "m.room.join_rules" -> { // TODO } "m.room.create" -> { // TODO } "m.room.topic" -> { // TODO } "m.room.name" -> { // TODO } "m.room.config" -> { // TODO } else -> { System.err.println("Unhandled state type: " + state.type) System.err.println(Thread.currentThread().getStackTrace().take(2).joinToString("\n")) System.err.println() } } } } result.presence.forEach { p -> if (p.type == "m.presence") { roomUserStore.values().forEach { users -> val userId = p.content.getString("user_id", null) users.firstOrNull { it.id == userId }?.let { it.present.set(p.content.getString("presence", "") == "online") it.lastActiveAgo.set(p.content.getLong("last_active_ago", java.lang.Long.MAX_VALUE)) } } } } roomUserStore.values().forEach { users -> FXCollections.sort(users, { a, b -> b.weight.get() - a.weight.get()}) } } fun processEventsResult(eventResult: EventResult, api:API) { eventResult.messages.forEach { message -> when (message.type) { "m.typing" -> { val usersTyping = message.content.getArray("user_ids").map { it.asString() } roomUserStore.values().forEach { users -> users.forEach { it.typing.set(usersTyping.contains(it.id)) } } } "m.presence" -> { roomUserStore.values().forEach { users -> val userId = message.content.getString("user_id", null) users.firstOrNull { it.id == userId }?.let { it.present.set(message.content.getString("presence", "") == "online") it.lastActiveAgo.set(message.content.getLong("last_active_ago", java.lang.Long.MAX_VALUE)) } } } "m.room.message" -> { if (message.roomId != null) { getRoomChatMessages(message.roomId).add(message) } } "m.room.member" -> { if (message.roomId != null) { val users = getRoomUsers(message.roomId) getRoomChatMessages(message.roomId).add(message) if (message.content.getString("membership", "") == "join") { val existingUser = users.firstOrNull { it.id == message.userId } val displayName = message.content.get("displayname")?.let { if (it.isString()) it.asString() else null } ?: message.userId val avatarURL = api.getAvatarThumbnailURL(message.content.getStringOrElse("avatar_url", "")) val user = if (existingUser == null) { val us = UserState(message.userId) users.add(us) us } else { existingUser } user.displayName.set(displayName) user.avatarURL.set(avatarURL) } else { users.removeFirstMatching { it.id == message.userId } } } } else -> { println("Unhandled message: " + message) } } } roomUserStore.values().forEach { users -> FXCollections.sort(users, { a, b -> b.weight.get() - a.weight.get()}) } } synchronized private fun getRoomChatMessages(roomId: String): ObservableList<Message> { return getOrCreate(roomChatMessageStore, roomId, { FXCollections.observableArrayList<Message>() }) } synchronized private fun getRoomUsers(roomId: String): ObservableList<UserState> { return getOrCreate(roomUserStore, roomId, { FXCollections.observableArrayList<UserState>({ userState -> array(userState.present, userState.displayName, userState.avatarURL, userState.typing, userState.weight) }) }) } init { EasyBind.subscribe(currRoomId, { id: String? -> if (id != null && !id.isEmpty()) { currChatMessageList.set(getRoomChatMessages(id)) currUserList.set(getRoomUsers(id)) } else { currChatMessageList.set(SimpleListProperty<Message>()) currUserList.set(SimpleListProperty<UserState>()) } }) } synchronized private fun getOrCreate<T>(store: HashMap<String, ObservableList<T>>, roomId: String, creator: () -> ObservableList<T>): ObservableList<T> { val messages = store.get(roomId) if (messages == null) { val newList = SimpleListProperty(creator()) store.put(roomId, newList) return newList } else { return messages } } } fun <T> ObservableList<T>.removeFirstMatching(predicate: (T) -> Boolean) { for ((index,value) in this.withIndex()) { if (predicate(value)) { this.remove(index) break; } } } fun JsonObject.getStringOrElse(name:String, elseValue:String):String { return get(name)?.let { if (it.isString()) it.asString() else null } ?: elseValue }
src/co/uproot/unplug/common.kt
1382305931
// FIR_IDENTICAL interface A { fun foo() } interface B : A { fun bar() } interface C interface D : A fun test(a: A?) { if (a != null && a is B?) { <info descr="Smart cast to B" tooltip="Smart cast to B">a</info>.bar() } if (a is B && a is C) { <info descr="Smart cast to B" tooltip="Smart cast to B">a</info>.foo() } if (a is B? && a is C?) { <info descr="Smart cast to B?" tooltip="Smart cast to B?">a</info><info>?.</info>bar() } a<info>?.</info>foo() if (a is B? && a is C?) { a<info>?.</info>foo() } if (a is B && a is D) { //when it's resolved, the message should be 'Smart cast to A' <info>a</info>.<error>foo</error> } }
plugins/kotlin/idea/tests/testData/checker/infos/SmartCastsWithSafeAccess.kt
113493579
package baz import foo.A import foo.J import foo.JConstr import foo.O import foo.O.objectExtensionMember2 import foo.Y import foo.YConstr import foo.classExtension import foo.companionExtension import foo.objectExtension import foo.topLevel fun test() { A().classMember() A().classExtension() O.objectMember1() O.objectMember2() O.objectExtension() A.companionMember() A.companionExtension() J().javaClassMember() J.javaClassStaticMember() topLevel() with(O) { 1.objectExtensionMember1() } 1.objectExtensionMember2() with(A) { 1.companionExtensionMember() } A()::classMember A::classMember A()::classExtension A::classExtension O::objectMember1 O::objectMember2 O::objectExtension A.Companion::companionMember (A)::companionMember A.Companion::companionExtension (A)::companionExtension J()::javaClassMember J::javaClassMember J::javaClassStaticMember ::topLevel ::Y ::YConstr Y::YY ::J ::JConstr J::JJ with(A()) { classMember() this.classMember() classExtension() this.classExtension() this::classMember this::classExtension } with(J()) { javaClassMember() this.javaClassMember() this::javaClassMember } }
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/callsAndCallableRefs/internalUsages/differentSourceAndTargetWithImports/after/baz/Test.kt
4008612897
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jetbrains.packagesearch.intellij.plugin.maven.dependency.analyzer import com.intellij.buildsystem.model.unified.UnifiedCoordinates import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerView import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.module.Module import com.jetbrains.packagesearch.intellij.plugin.dependency.analyzer.DependencyAnalyzerGoToPackageSearchAction import org.jetbrains.idea.maven.project.actions.getParentModule import org.jetbrains.idea.maven.project.actions.getUnifiedCoordinates import org.jetbrains.idea.maven.utils.MavenUtil.SYSTEM_ID class MavenDependencyAnalyzerGoToPackageSearchAction : DependencyAnalyzerGoToPackageSearchAction() { override val systemId: ProjectSystemId = SYSTEM_ID override fun getModule(e: AnActionEvent): Module? { val project = e.getData(CommonDataKeys.PROJECT) ?: return null val dependency = e.getData(DependencyAnalyzerView.DEPENDENCY) ?: return null return getParentModule(project, dependency) } override fun getUnifiedCoordinates(e: AnActionEvent): UnifiedCoordinates? { val dependency = e.getData(DependencyAnalyzerView.DEPENDENCY) ?: return null return getUnifiedCoordinates(dependency) } }
plugins/package-search/maven/src/com/jetbrains/packagesearch/intellij/plugin/maven/dependency/analyzer/MavenDependencyAnalyzerGoToPackageSearchAction.kt
3832420906
/* * Copyright (c) 2016 by Todd Ginsberg */ package com.ginsberg.advent2016.utils import java.math.BigInteger // -- Hex Conversions fun ByteArray.toHex(): String = String.format("%032x", BigInteger(1, this)) fun Int.toHex(): String = String.format("%X", this) // -- Char/Digit Conversions fun Char.asDigit(): Int = if(this.isDigit()) this-'0' else throw IllegalArgumentException()
src/main/kotlin/com/ginsberg/advent2016/utils/Extensions.kt
2176125062
fun test() { (consume(listOf(1, 2, 3))) } fun <T> consume(list: List<T>) {}
plugins/kotlin/code-insight/postfix-templates/testData/expansion/par/call.after.kt
705358789
/** * Doc comment * <selection>@pa<caret>ram a The description of a.</selection> */ fun foo(a: Int) { }
plugins/kotlin/idea/tests/testData/wordSelection/DocCommentTagName/3.kt
4294830917
package com.onyx.interactors.query.impl.collectors import com.onyx.descriptor.EntityDescriptor import com.onyx.interactors.record.data.Reference import com.onyx.lang.map.OptimisticLockingMap import com.onyx.persistence.IManagedEntity import com.onyx.persistence.context.SchemaContext import com.onyx.persistence.query.Query import kotlin.collections.HashMap /** * Get a single result when executing selection functions that require aggregation without grouping */ class FlatFunctionSelectionQueryCollector( query: Query, context: SchemaContext, descriptor: EntityDescriptor ) : BaseQueryCollector<Any?>(query, context, descriptor) { private var result = OptimisticLockingMap(HashMap<String, Any?>()) private val otherSelections = selections.filter { it.function?.type?.isGroupFunction != true } private val selectionFunctions = selections.filter { it.function?.type?.isGroupFunction == true } override fun collect(reference: Reference, entity: IManagedEntity?) { super.collect(reference, entity) if(entity == null) return selectionFunctions.forEach { val selectionValue = comparator.getAttribute(it, entity, context) if(it.function?.preProcess(query, selectionValue) == true) { otherSelections.forEach { selection -> val resultAttribute = if (selection.function == null) comparator.getAttribute(selection, entity, context) else selection.function.execute(comparator.getAttribute(selection, entity, context)) resultLock.perform { result[selection.selection] = resultAttribute } } } } } override fun finalizeResults() { if(!isFinalized) { repeat(selections.size) { selectionFunctions.forEach { it.function?.postProcess(query) result[it.selection] = it.function?.getFunctionValue() } } results = arrayListOf(HashMap(result)) numberOfResults.set(1) isFinalized = true } } }
onyx-database/src/main/kotlin/com/onyx/interactors/query/impl/collectors/FlatFunctionSelectionQueryCollector.kt
1413235967
package com.kondroid.sampleproject.viewmodel import android.content.Context import android.databinding.ObservableField import com.kondroid.sampleproject.helper.RxUtils import com.kondroid.sampleproject.helper.makeWeak import com.kondroid.sampleproject.helper.validation.Validation import com.kondroid.sampleproject.model.RoomsModel import com.kondroid.sampleproject.request.RoomRequest import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.observers.DisposableObserver import io.reactivex.rxkotlin.Observables import io.reactivex.rxkotlin.combineLatest import io.reactivex.schedulers.Schedulers import java.lang.ref.WeakReference /** * Created by kondo on 2017/10/05. */ class AddRoomViewModel(context: Context) : BaseViewModel(context) { var nameText: ObservableField<String> = ObservableField("") var themeText: ObservableField<String> = ObservableField("") var nameValidationText: ObservableField<String> = ObservableField("") var themeValidationText: ObservableField<String> = ObservableField("") var createButtonEnabled: ObservableField<Boolean> = ObservableField(false) val roomModel = RoomsModel() lateinit var onTapCreate: () -> Unit override fun initVM() { super.initVM() //Validation val weakSelf = makeWeak(this) val nameValid = RxUtils.toObservable(nameText) .map { return@map Validation.textLength(context.get(), it, 1, 20) } .share() val d1 = nameValid.subscribe { weakSelf.get()?.nameValidationText?.set(it) } val themeValid = RxUtils.toObservable(themeText) .map { return@map Validation.textLength(context.get(), it, 1, 20) } .share() val d2 = themeValid.subscribe { weakSelf.get()?.themeValidationText?.set(it) } val createButtonValid = Observables.combineLatest(nameValid, themeValid, {name, theme -> return@combineLatest name == "" && theme == "" }).share() val d3 = createButtonValid.subscribe { weakSelf.get()?.createButtonEnabled?.set(it) } compositeDisposable.addAll(d1, d2, d3) } fun createRoom(onSuccess: () -> Unit, onFailed: (e: Throwable) -> Unit) { if (requesting) return requesting = true val weakSelf = makeWeak(this) val params = RoomRequest.CreateParams(nameText.get(), themeText.get()) val observable = roomModel.createRoom(params) val d = observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({t -> weakSelf.get()?.requesting = false onSuccess() },{e -> weakSelf.get()?.requesting = false onFailed(e) },{ weakSelf.get()?.requesting = false }) compositeDisposable.add(d) } fun tapCreate() { if (requesting) return onTapCreate() } }
app/src/main/java/com/kondroid/sampleproject/viewmodel/AddRoomViewModel.kt
655435023
/* * Copyright 2000-2014 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.icons.AllIcons import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkModificator import com.intellij.openapi.projectRoots.SdkType import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.io.FileUtil import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.LayeredIcon import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.TitledSeparator import com.intellij.util.ui.JBUI import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.sdk.flavors.PythonSdkFlavor import com.jetbrains.python.sdk.pipenv.PIPENV_ICON import com.jetbrains.python.sdk.pipenv.isPipEnv import java.awt.Component import javax.swing.Icon import javax.swing.JList /** * @author vlan */ open class PySdkListCellRenderer(private val sdkModifiers: Map<Sdk, SdkModificator>?) : ColoredListCellRenderer<Any>() { override fun getListCellRendererComponent(list: JList<out Any>?, value: Any?, index: Int, selected: Boolean, hasFocus: Boolean): Component = when (value) { SEPARATOR -> TitledSeparator(null).apply { border = JBUI.Borders.empty() } else -> super.getListCellRendererComponent(list, value, index, selected, hasFocus) } override fun customizeCellRenderer(list: JList<out Any>, value: Any?, index: Int, selected: Boolean, hasFocus: Boolean) { when (value) { is Sdk -> { appendName(value) icon = customizeIcon(value) } is String -> append(value) null -> append("<No interpreter>") } } private fun appendName(sdk: Sdk) { val name = sdkModifiers?.get(sdk)?.name ?: sdk.name when { PythonSdkType.isInvalid(sdk) || PythonSdkType.hasInvalidRemoteCredentials(sdk) -> append("[invalid] $name", SimpleTextAttributes.ERROR_ATTRIBUTES) PythonSdkType.isIncompleteRemote(sdk) -> append("[incomplete] $name", SimpleTextAttributes.ERROR_ATTRIBUTES) !LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) -> append("[unsupported] $name", SimpleTextAttributes.ERROR_ATTRIBUTES) else -> append(name) } if (sdk.isPipEnv) { sdk.versionString?.let { append(" $it", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES) } } val homePath = sdk.homePath val relHomePath = homePath?.let { FileUtil.getLocationRelativeToUserHome(it) } if (relHomePath != null && homePath !in name && relHomePath !in name) { append(" $relHomePath", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES) } } companion object { const val SEPARATOR: String = "separator" private fun customizeIcon(sdk: Sdk): Icon? { val flavor = PythonSdkFlavor.getPlatformIndependentFlavor(sdk.homePath) val icon = if (flavor != null) flavor.icon else (sdk.sdkType as? SdkType)?.icon ?: return null return when { PythonSdkType.isInvalid(sdk) || PythonSdkType.isIncompleteRemote(sdk) || PythonSdkType.hasInvalidRemoteCredentials(sdk) || !LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) -> wrapIconWithWarningDecorator(icon) sdk is PyDetectedSdk -> IconLoader.getTransparentIcon(icon) // XXX: We cannot provide pipenv SDK flavor by path since it's just a regular virtualenv. Consider // adding the SDK flavor based on the `Sdk` object itself // TODO: Refactor SDK flavors so they can actually provide icons for SDKs in all cases sdk.isPipEnv -> PIPENV_ICON else -> icon } } private fun wrapIconWithWarningDecorator(icon: Icon): LayeredIcon = LayeredIcon(2).apply { setIcon(icon, 0) setIcon(AllIcons.Actions.Cancel, 1) } } }
python/src/com/jetbrains/python/sdk/PySdkListCellRenderer.kt
2968789251
package co.timecrypt.android.helpers import android.text.Editable import android.text.TextWatcher /** * Implements all methods from the [TextWatcher] interface. */ open class TextWatcherAdapter : TextWatcher { override fun afterTextChanged(text: Editable) {} override fun beforeTextChanged(text: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(text: CharSequence, start: Int, before: Int, count: Int) {} }
Android/app/src/main/java/co/timecrypt/android/helpers/TextWatcherAdapter.kt
225712343
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("unused", "UNUSED_PARAMETER") package io.ktor.tests.hosts import com.typesafe.config.* import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.config.* import io.ktor.server.engine.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.testing.* import io.ktor.util.* import kotlinx.coroutines.* import org.slf4j.helpers.* import kotlin.reflect.* import kotlin.reflect.jvm.* import kotlin.test.* class ApplicationEngineEnvironmentReloadingTests { @Test fun `top level extension function as module function`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf(Application::topLevelExtensionFunction.fqName) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("topLevelExtensionFunction", application.attributes[TestKey]) environment.stop() } @Test fun `top level extension function as module function reloading stress`() { val environment = applicationEngineEnvironment { config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.deployment.watch" to listOf("ktor-server-host-common"), "ktor.application.modules" to listOf(Application::topLevelExtensionFunction.fqName) ) ) ) } environment.start() repeat(100) { (environment as ApplicationEngineEnvironmentReloading).reload() } environment.stop() } @Test fun `top level non-extension function as module function`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf<KFunction0<Unit>>(::topLevelFunction).map { it.fqName } ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("topLevelFunction", application.attributes[TestKey]) environment.stop() } @Test fun `companion object extension function as module function`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf( Companion::class.jvmName + "." + "companionObjectExtensionFunction" ) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("companionObjectExtensionFunction", application.attributes[TestKey]) environment.stop() } @Test fun `companion object non-extension function as module function`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf( Companion::class.functionFqName("companionObjectFunction") ) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("companionObjectFunction", application.attributes[TestKey]) environment.stop() } @Test fun `companion object jvmstatic extension function as module function`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf( Companion::class.jvmName + "." + "companionObjectJvmStaticExtensionFunction" ) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("companionObjectJvmStaticExtensionFunction", application.attributes[TestKey]) environment.stop() } @Test fun `companion object jvmstatic non-extension function as module function`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf( Companion::class.functionFqName("companionObjectJvmStaticFunction") ) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("companionObjectJvmStaticFunction", application.attributes[TestKey]) environment.stop() } @Test fun `object holder extension function as module function`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf( ObjectModuleFunctionHolder::class.jvmName + "." + "objectExtensionFunction" ) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("objectExtensionFunction", application.attributes[TestKey]) environment.stop() } @Test fun `object holder non-extension function as module function`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf( ObjectModuleFunctionHolder::class.functionFqName("objectFunction") ) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("objectFunction", application.attributes[TestKey]) environment.stop() } @Test fun `class holder extension function as module function`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf( ClassModuleFunctionHolder::class.jvmName + "." + "classExtensionFunction" ) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("classExtensionFunction", application.attributes[TestKey]) environment.stop() } @Test fun `class holder non-extension function as module function`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf(ClassModuleFunctionHolder::classFunction.fqName) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("classFunction", application.attributes[TestKey]) environment.stop() } @Test fun `no-arg module function`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf(NoArgModuleFunction::class.functionFqName("main")) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals(1, NoArgModuleFunction.result) environment.stop() } @Test fun `multiple module functions`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf(MultipleModuleFunctions::class.jvmName + ".main") ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("best function called", application.attributes[TestKey]) environment.stop() } @Test fun `multiple static module functions`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf(MultipleStaticModuleFunctions::class.jvmName + ".main") ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("best function called", application.attributes[TestKey]) environment.stop() } @Test fun `top level module function with default arg`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf( ApplicationEngineEnvironmentReloadingTests::class.jvmName + "Kt.topLevelWithDefaultArg" ) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("topLevelWithDefaultArg", application.attributes[TestKey]) environment.stop() } @Test fun `static module function with default arg`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf(Companion::class.jvmName + ".functionWithDefaultArg") ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("functionWithDefaultArg", application.attributes[TestKey]) environment.stop() } @Test fun `top level module function with jvm overloads`() { val environment = applicationEngineEnvironment { developmentMode = false config = HoconApplicationConfig( ConfigFactory.parseMap( mapOf( "ktor.deployment.environment" to "test", "ktor.application.modules" to listOf( ApplicationEngineEnvironmentReloadingTests::class.jvmName + "Kt.topLevelWithJvmOverloads" ) ) ) ) } environment.start() val application = environment.application assertNotNull(application) assertEquals("topLevelWithJvmOverloads", application.attributes[TestKey]) environment.stop() } object NoArgModuleFunction { var result = 0 fun main() { result++ } } object MultipleModuleFunctions { fun main() { } fun main(app: Application) { app.attributes.put(TestKey, "best function called") } } object MultipleStaticModuleFunctions { @JvmStatic fun main() { } @JvmStatic fun main(app: Application) { app.attributes.put(TestKey, "best function called") } } class ClassModuleFunctionHolder { @Suppress("UNUSED") fun Application.classExtensionFunction() { attributes.put(TestKey, "classExtensionFunction") } fun classFunction(app: Application) { app.attributes.put(TestKey, "classFunction") } } object ObjectModuleFunctionHolder { @Suppress("UNUSED") fun Application.objectExtensionFunction() { attributes.put(TestKey, "objectExtensionFunction") } fun objectFunction(app: Application) { app.attributes.put(TestKey, "objectFunction") } } companion object { val TestKey = AttributeKey<String>("test-key") private val KFunction<*>.fqName: String get() = javaMethod!!.declaringClass.name + "." + name private fun KClass<*>.functionFqName(name: String) = "$jvmName.$name" @Suppress("UNUSED") fun Application.companionObjectExtensionFunction() { attributes.put(TestKey, "companionObjectExtensionFunction") } fun companionObjectFunction(app: Application) { app.attributes.put(TestKey, "companionObjectFunction") } @Suppress("UNUSED") @JvmStatic fun Application.companionObjectJvmStaticExtensionFunction() { attributes.put(TestKey, "companionObjectJvmStaticExtensionFunction") } @JvmStatic fun companionObjectJvmStaticFunction(app: Application) { app.attributes.put(TestKey, "companionObjectJvmStaticFunction") } @JvmStatic fun Application.functionWithDefaultArg(test: Boolean = false) { attributes.put(TestKey, "functionWithDefaultArg") } } @Test fun `application is available before environment start`() { val env = dummyEnv() val app = env.application env.start() assertEquals(app, env.application) } @Test fun `completion handler is invoked when attached before environment start`() { val env = dummyEnv() var invoked = false env.application.coroutineContext[Job]?.invokeOnCompletion { invoked = true } env.start() env.stop() assertTrue(invoked, "On completion handler wasn't invoked") } @Test fun `interceptor is invoked when added before environment start`() { val engine = TestApplicationEngine(createTestEnvironment()) engine.application.intercept(ApplicationCallPipeline.Plugins) { call.response.header("Custom", "Value") } engine.start() try { engine.apply { application.routing { get("/") { call.respondText { "Hello" } } } assertEquals("Value", handleRequest(HttpMethod.Get, "/").response.headers["Custom"]) } } catch (cause: Throwable) { fail("Failed with an exception: ${cause.message}") } finally { engine.stop(0L, 0L) } } private fun dummyEnv() = ApplicationEngineEnvironmentReloading( classLoader = this::class.java.classLoader, log = NOPLogger.NOP_LOGGER, config = MapApplicationConfig(), connectors = emptyList(), modules = emptyList() ) } fun Application.topLevelExtensionFunction() { attributes.put(ApplicationEngineEnvironmentReloadingTests.TestKey, "topLevelExtensionFunction") } fun topLevelFunction(app: Application) { app.attributes.put(ApplicationEngineEnvironmentReloadingTests.TestKey, "topLevelFunction") } @Suppress("unused") fun topLevelFunction() { error("Shouldn't be invoked") } fun Application.topLevelWithDefaultArg(testing: Boolean = false) { attributes.put(ApplicationEngineEnvironmentReloadingTests.TestKey, "topLevelWithDefaultArg") } @JvmOverloads fun Application.topLevelWithJvmOverloads(testing: Boolean = false) { attributes.put(ApplicationEngineEnvironmentReloadingTests.TestKey, "topLevelWithJvmOverloads") }
ktor-server/ktor-server-host-common/jvm/test/io/ktor/tests/hosts/ApplicationEngineEnvironmentReloadingTests.kt
216804855
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.js import io.ktor.client.engine.* import io.ktor.client.engine.js.compatibility.* import io.ktor.client.plugins.* import io.ktor.client.plugins.websocket.* import io.ktor.client.request.* import io.ktor.client.utils.* import io.ktor.http.* import io.ktor.util.* import io.ktor.util.date.* import kotlinx.coroutines.* import org.w3c.dom.* import org.w3c.dom.events.* import kotlin.coroutines.* internal class JsClientEngine( override val config: HttpClientEngineConfig ) : HttpClientEngineBase("ktor-js") { override val dispatcher = Dispatchers.Default override val supportedCapabilities = setOf(HttpTimeout, WebSocketCapability) init { check(config.proxy == null) { "Proxy unsupported in Js engine." } } @OptIn(InternalAPI::class) override suspend fun execute(data: HttpRequestData): HttpResponseData { val callContext = callContext() val clientConfig = data.attributes[CLIENT_CONFIG] if (data.isUpgradeRequest()) { return executeWebSocketRequest(data, callContext) } val requestTime = GMTDate() val rawRequest = data.toRaw(clientConfig, callContext) val rawResponse = commonFetch(data.url.toString(), rawRequest) val status = HttpStatusCode(rawResponse.status.toInt(), rawResponse.statusText) val headers = rawResponse.headers.mapToKtor() val version = HttpProtocolVersion.HTTP_1_1 val body = CoroutineScope(callContext).readBody(rawResponse) return HttpResponseData( status, requestTime, headers, version, body, callContext ) } // Adding "_capturingHack" to reduce chances of JS IR backend to rename variable, // so it can be accessed inside js("") function @Suppress("UNUSED_PARAMETER", "UnsafeCastFromDynamic", "UNUSED_VARIABLE", "LocalVariableName") private fun createWebSocket( urlString_capturingHack: String, headers: Headers ): WebSocket = if (PlatformUtils.IS_NODE) { val ws_capturingHack = js("eval('require')('ws')") val headers_capturingHack: dynamic = object {} headers.forEach { name, values -> headers_capturingHack[name] = values.joinToString(",") } js("new ws_capturingHack(urlString_capturingHack, { headers: headers_capturingHack })") } else { js("new WebSocket(urlString_capturingHack)") } private suspend fun executeWebSocketRequest( request: HttpRequestData, callContext: CoroutineContext ): HttpResponseData { val requestTime = GMTDate() val urlString = request.url.toString() val socket: WebSocket = createWebSocket(urlString, request.headers) try { socket.awaitConnection() } catch (cause: Throwable) { callContext.cancel(CancellationException("Failed to connect to $urlString", cause)) throw cause } val session = JsWebSocketSession(callContext, socket) return HttpResponseData( HttpStatusCode.OK, requestTime, Headers.Empty, HttpProtocolVersion.HTTP_1_1, session, callContext ) } } private suspend fun WebSocket.awaitConnection(): WebSocket = suspendCancellableCoroutine { continuation -> if (continuation.isCancelled) return@suspendCancellableCoroutine val eventListener = { event: Event -> when (event.type) { "open" -> continuation.resume(this) "error" -> { continuation.resumeWithException(WebSocketException(event.asString())) } } } addEventListener("open", callback = eventListener) addEventListener("error", callback = eventListener) continuation.invokeOnCancellation { removeEventListener("open", callback = eventListener) removeEventListener("error", callback = eventListener) if (it != null) { [email protected]() } } } private fun Event.asString(): String = buildString { append(JSON.stringify(this@asString, arrayOf("message", "target", "type", "isTrusted"))) } private fun org.w3c.fetch.Headers.mapToKtor(): Headers = buildHeaders { [email protected]().forEach { value: String, key: String -> append(key, value) } Unit } /** * Wrapper for javascript `error` objects. * @property origin: fail reason */ @Suppress("MemberVisibilityCanBePrivate") public class JsError(public val origin: dynamic) : Throwable("Error from javascript[$origin].")
ktor-client/ktor-client-core/js/src/io/ktor/client/engine/js/JsClientEngine.kt
2999800794
/* * Copyright © 2013 dvbviewer-controller 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 org.dvbviewer.controller.ui.base import android.content.Context import androidx.loader.content.AsyncTaskLoader import java.io.Closeable /** * Loader which extends AsyncTaskLoaders and handles caveats * as pointed out in http://code.google.com/p/android/issues/detail?id=14944. * * Based on CursorLoader.java in the Fragment compatibility package * * @param <D> mData type * @author RayBa * @date 07.04.2013 </D> */ abstract class AsyncLoader<D> /** * Instantiates a new async loader. * * @param context the context * @author RayBa * @date 07.04.2013 */ (context: Context) : AsyncTaskLoader<D>(context) { private var mData: D? = null /* (non-Javadoc) * @see android.support.v4.content.Loader#deliverResult(java.lang.Object) */ override fun deliverResult(data: D?) { if (isReset) { // An async query came in while the loader is stopped closeData(data) return } if (isStarted) { super.deliverResult(data) } val oldData = mData mData = data if (oldData !== mData) { closeData(oldData) } } override fun onCanceled(data: D?) { super.onCanceled(data) closeData(data) } /* (non-Javadoc) * @see android.support.v4.content.Loader#onStartLoading() */ override fun onStartLoading() { if (mData != null) { deliverResult(mData) } if (takeContentChanged() || mData == null) { forceLoad() } } /* (non-Javadoc) * @see android.support.v4.content.Loader#onStopLoading() */ override fun onStopLoading() { cancelLoad() } /* (non-Javadoc) * @see android.support.v4.content.Loader#onReset() */ override fun onReset() { super.onReset() // Ensure the loader is stopped onStopLoading() closeData(mData) mData = null } private fun closeData(data: D?) { if (data != null && data is Closeable) { val c = data as Closeable? c?.close() } } }
dvbViewerController/src/main/java/org/dvbviewer/controller/ui/base/AsyncLoader.kt
1396566934
package de.tarent.axon import de.tarent.axon.domain.TicTacToeGame import org.axonframework.common.jpa.EntityManagerProvider import org.axonframework.common.jpa.SimpleEntityManagerProvider import org.axonframework.common.transaction.TransactionManager import org.axonframework.eventsourcing.EventSourcingRepository import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore import org.axonframework.eventsourcing.eventstore.EventStore import org.axonframework.eventsourcing.eventstore.jpa.JpaEventStorageEngine import org.axonframework.spring.messaging.unitofwork.SpringTransactionManager import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.jpa.repository.config.EnableJpaRepositories import org.springframework.transaction.PlatformTransactionManager import javax.persistence.EntityManager @Configuration @EnableJpaRepositories open class AppConfiguration { @Bean open fun axonEntityManagerProvider(manager: EntityManager): EntityManagerProvider { return SimpleEntityManagerProvider(manager) } @Bean open fun axonTransactionManager(manager: PlatformTransactionManager): TransactionManager { return SpringTransactionManager(manager) } @Bean open fun eventBus(axonEntityManagerProvider: EntityManagerProvider, axonTransactionManager: TransactionManager): EventStore { return EmbeddedEventStore(JpaEventStorageEngine(axonEntityManagerProvider, axonTransactionManager)) } @Bean open fun taskRepository(eventBus: EventStore): EventSourcingRepository<TicTacToeGame> { return EventSourcingRepository(TicTacToeGame::class.java, eventBus) } }
src/main/kotlin/de/tarent/axon/AppConfiguration.kt
1886367920
package com.aswiatek.pricecomparator.buisinesslogic.screenvaluegetters import com.aswiatek.pricecomparator.buisinesslogic.screenmodes.ScreenMode class NumberValueGetter(private val anotherGetter: ScreenValueGetter) : ScreenValueGetter { private val mOnlyDigitsRegex: Regex = Regex("^[0-9]+\\.?[0-9]*$") override fun get(newValue: String, currentValue: String, mode: ScreenMode): String { if (mOnlyDigitsRegex.matches(newValue)) return mode.getValueAfterAdd(currentValue, newValue) return anotherGetter.get(newValue, currentValue, mode) } }
PriceComparator/app/src/main/java/com/aswiatek/pricecomparator/buisinesslogic/screenvaluegetters/NumberValueGetter.kt
3253337447
package com.neva.javarel.storage.database.impl import com.neva.javarel.foundation.api.JavarelConstants import com.neva.javarel.foundation.api.scanning.BundleScanner import com.neva.javarel.foundation.api.scanning.BundleWatcher import com.neva.javarel.foundation.api.scanning.ComponentScanBundleFilter import com.neva.javarel.storage.database.api.Database import com.neva.javarel.storage.database.api.DatabaseAdmin import com.neva.javarel.storage.database.api.DatabaseConnection import com.neva.javarel.storage.database.api.DatabaseException import com.neva.javarel.storage.database.impl.connection.DerbyEmbeddedDatabaseConnection import org.apache.felix.scr.annotations.* import org.apache.openjpa.persistence.PersistenceProviderImpl import org.osgi.framework.BundleContext import org.osgi.framework.BundleEvent import org.slf4j.LoggerFactory import java.util.Properties import javax.persistence.Entity import javax.persistence.EntityManager import javax.persistence.spi.PersistenceProvider import javax.persistence.spi.PersistenceUnitTransactionType @Component(immediate = true, metatype = true, label = "${JavarelConstants.SERVICE_PREFIX} Storage - Database Admin") @Service(DatabaseAdmin::class, BundleWatcher::class) class MultiDatabaseAdmin : DatabaseAdmin, BundleWatcher { companion object { val LOG = LoggerFactory.getLogger(MultiDatabaseAdmin::class.java) @Property(name = NAME_DEFAULT_PROP, value = DerbyEmbeddedDatabaseConnection.NAME_DEFAULT, label = "Default connection name") const val NAME_DEFAULT_PROP = "nameDefault" val ENTITY_FILTER = ComponentScanBundleFilter(setOf(Entity::class.java)) val ENTITY_MANAGER_CONFIG = mapOf<String, Any>( "openjpa.DynamicEnhancementAgent" to "true", "openjpa.RuntimeUnenhancedClasses" to "supported", "openjpa.jdbc.SynchronizeMappings" to "buildSchema(foreignKeys=true')", "openjpa.jdbc.MappingDefaults" to "ForeignKeyDeleteAction=restrict, JoinForeignKeyDeleteAction=restrict" ) } @Reference private lateinit var provider: PersistenceProvider @Reference private lateinit var bundleScanner: BundleScanner @Reference(referenceInterface = DatabaseConnection::class, cardinality = ReferenceCardinality.MANDATORY_MULTIPLE, policy = ReferencePolicy.DYNAMIC ) private var allConnections: MutableMap<String, DatabaseConnection> = mutableMapOf() private var allConnectedDatabases: MutableMap<String, Database> = mutableMapOf() private lateinit var context: BundleContext private lateinit var props: Map<String, Any> @Activate protected fun start(context: BundleContext, props: Map<String, Any>) { this.context = context this.props = props } override val connectionDefault: String get() = props[NAME_DEFAULT_PROP] as String override fun database(): Database { return database(connectionDefault) } @Synchronized override fun database(connectionName: String): Database { var database = allConnectedDatabases[connectionName] if (database == null || !database.connected) { database = connect(connectionByName(connectionName)) allConnectedDatabases.put(connectionName, database) } return database } override val connections: Set<DatabaseConnection> get() = allConnections.values.toSet() override val connectedDatabases: Set<Database> get() = allConnectedDatabases.values.toSet() private fun connectionByName(name: String): DatabaseConnection { return allConnections[name] ?: throw DatabaseException("Database connection named '$name' is not defined.") } private fun connect(connection: DatabaseConnection): Database { val props = Properties() props.put("openjpa.ConnectionFactory", connection.source) props.putAll(ENTITY_MANAGER_CONFIG) val info = BundlePersistenceInfo(context) info.persistenceProviderClassName = PersistenceProviderImpl::class.java.canonicalName info.persistenceUnitName = connection.name info.transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL info.setExcludeUnlistedClasses(false) val classes = bundleScanner.scan(ENTITY_FILTER) for (clazz in classes) { info.addManagedClassName(clazz.canonicalName) } connection.configure(info, props) val emf = provider.createContainerEntityManagerFactory(info, props) return ConnectedDatabase(connection, emf) } private fun check(connection: DatabaseConnection) { if (allConnections.contains(connection.name)) { LOG.warn("Database connection named '${connection.name}' of type '${connection.javaClass.canonicalName}' overrides '${allConnections[connection.name]!!.javaClass}'.") } } private fun disconnect(connection: DatabaseConnection) { if (allConnectedDatabases.contains(connection.name)) { LOG.info("Database connection named '${connection.name}' is being disconnected.") allConnectedDatabases.remove(connection.name) } } private fun bindAllConnections(connection: DatabaseConnection) { check(connection) allConnections.put(connection.name, connection) } private fun unbindAllConnections(connection: DatabaseConnection) { disconnect(connection) allConnections.remove(connection.name) } override fun <R> session(connectionName: String, callback: (EntityManager) -> R): R { return database(connectionName).session(callback) } override fun <R> session(callback: (EntityManager) -> R): R { return database().session(callback) } override fun watch(event: BundleEvent) { if (ENTITY_FILTER.filterBundle(event.bundle)) { allConnectedDatabases.clear() } } }
storage/database/src/main/kotlin/com/neva/javarel/storage/database/impl/MultiDatabaseAdmin.kt
594382788
package ru.bozaro.gitlfs.common.data import com.google.common.collect.ImmutableMap import org.testng.Assert import org.testng.annotations.Test import java.io.IOException import java.net.URI import java.net.URISyntaxException import java.text.ParseException /** * Test Meta deserialization. * * @author Artem V. Navrotskiy */ class ObjectResTest { @Test @Throws(IOException::class, ParseException::class, URISyntaxException::class) fun parse01() { val res: ObjectRes = SerializeTester.deserialize("object-res-01.json", ObjectRes::class.java) Assert.assertNotNull(res) val meta = res.meta!! Assert.assertNotNull(meta) Assert.assertEquals(meta.oid, "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b") Assert.assertEquals(meta.size, 130L) Assert.assertEquals(2, res.links.size) val self: Link = res.links[LinkType.Self]!! Assert.assertNotNull(self) Assert.assertEquals(self.href, URI("https://storage-server.com/info/lfs/objects/01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b")) Assert.assertTrue(self.header.isEmpty()) val link: Link = res.links[LinkType.Upload]!! Assert.assertNotNull(link) Assert.assertEquals(link.href, URI("https://storage-server.com/OID")) Assert.assertEquals(link.header, ImmutableMap.builder<Any?, Any?>() .put("Authorization", "Basic ...") .build() ) } @Test @Throws(IOException::class, ParseException::class, URISyntaxException::class) fun parse02() { val res: ObjectRes = SerializeTester.deserialize("object-res-02.json", ObjectRes::class.java) Assert.assertNotNull(res) Assert.assertNull(res.meta) Assert.assertEquals(1, res.links.size) val link: Link = res.links[LinkType.Upload]!! Assert.assertNotNull(link) Assert.assertEquals(link.href, URI("https://some-upload.com")) Assert.assertEquals(link.header, ImmutableMap.builder<Any?, Any?>() .put("Authorization", "Basic ...") .build() ) } }
gitlfs-common/src/test/kotlin/ru/bozaro/gitlfs/common/data/ObjectResTest.kt
3513896566
package com.neva.javarel.foundation.api.scanning interface BundleScanner { fun scan(filter: BundleFilter): Set<Class<*>> }
foundation/src/main/kotlin/com/neva/javarel/foundation/api/scanning/BundleScanner.kt
880404420
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.at import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.mcp.McpModuleType import com.intellij.extapi.psi.PsiFileBase import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.ModuleUtilCore import com.intellij.psi.FileViewProvider class AtFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, AtLanguage) { init { setup() } private fun setup() { if (ApplicationManager.getApplication().isUnitTestMode) { return } val vFile = viewProvider.virtualFile val module = ModuleUtilCore.findModuleForFile(vFile, project) ?: return val mcpModule = MinecraftFacet.getInstance(module, McpModuleType) ?: return mcpModule.addAccessTransformerFile(vFile) } override fun getFileType() = AtFileType override fun toString() = "Access Transformer File" override fun getIcon(flags: Int) = PlatformAssets.MCP_ICON }
src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/AtFile.kt
3795416653
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.statistics import com.intellij.internal.statistic.beans.UsageDescriptor import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.internal.statistic.utils.getBooleanUsage import com.intellij.internal.statistic.utils.getEnumUsage import com.intellij.openapi.project.Project import org.jetbrains.idea.maven.execution.MavenRunner import org.jetbrains.idea.maven.project.MavenProjectsManager class MavenSettingsCollector : ProjectUsagesCollector() { override fun getGroupId() = "statistics.build.maven.state" override fun getUsages(project: Project): Set<UsageDescriptor> { val manager = MavenProjectsManager.getInstance(project) if (!manager.isMavenizedProject) return emptySet() val usages = mutableSetOf<UsageDescriptor>() val generalSettings = manager.generalSettings usages.add(getEnumUsage("checksumPolicy", generalSettings.checksumPolicy)) usages.add(getEnumUsage("failureBehavior", generalSettings.failureBehavior)) usages.add(getBooleanUsage("alwaysUpdateSnapshots", generalSettings.isAlwaysUpdateSnapshots)) usages.add(getBooleanUsage("nonRecursive", generalSettings.isNonRecursive)) usages.add(getBooleanUsage("printErrorStackTraces", generalSettings.isPrintErrorStackTraces)) usages.add(getBooleanUsage("usePluginRegistry", generalSettings.isUsePluginRegistry)) usages.add(getBooleanUsage("workOffline", generalSettings.isWorkOffline)) usages.add(getEnumUsage("outputLevel", generalSettings.outputLevel)) usages.add(getEnumUsage("pluginUpdatePolicy", generalSettings.pluginUpdatePolicy)) usages.add(getEnumUsage("loggingLevel", generalSettings.loggingLevel)) val importingSettings = manager.importingSettings usages.add(getEnumUsage("generatedSourcesFolder", importingSettings.generatedSourcesFolder)) usages.add(getBooleanUsage("createModuleGroups", importingSettings.isCreateModuleGroups)) usages.add(getBooleanUsage("createModulesForAggregators", importingSettings.isCreateModulesForAggregators)) usages.add(getBooleanUsage("downloadDocsAutomatically", importingSettings.isDownloadDocsAutomatically)) usages.add(getBooleanUsage("downloadSourcesAutomatically", importingSettings.isDownloadSourcesAutomatically)) usages.add(getBooleanUsage("excludeTargetFolder", importingSettings.isExcludeTargetFolder)) usages.add(getBooleanUsage("importAutomatically", importingSettings.isImportAutomatically)) usages.add(getBooleanUsage("keepSourceFolders", importingSettings.isKeepSourceFolders)) usages.add(getBooleanUsage("lookForNested", importingSettings.isLookForNested)) usages.add(getBooleanUsage("useMavenOutput", importingSettings.isUseMavenOutput)) usages.add(UsageDescriptor("updateFoldersOnImportPhase." + importingSettings.updateFoldersOnImportPhase)) val runnerSettings = MavenRunner.getInstance(project).settings usages.add(getBooleanUsage("delegateBuildRun", runnerSettings.isDelegateBuildToMaven)); usages.add(getBooleanUsage("passParentEnv", runnerSettings.isPassParentEnv)); usages.add(getBooleanUsage("runMavenInBackground", runnerSettings.isRunMavenInBackground)); usages.add(getBooleanUsage("skipTests", runnerSettings.isSkipTests)); return usages } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/statistics/MavenSettingsCollector.kt
4089959552
package com.example.demoaerisproject.service import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.Intent import android.graphics.Color import android.widget.RemoteViews import androidx.appcompat.app.AppCompatActivity import androidx.core.app.NotificationCompat import com.aerisweather.aeris.logging.Logger import com.aerisweather.aeris.response.ForecastsResponse import com.aerisweather.aeris.response.ObservationResponse import com.aerisweather.aeris.util.FileUtil import com.example.demoaerisproject.BaseApplication import com.example.demoaerisproject.R import com.example.demoaerisproject.util.FormatUtil import com.example.demoaerisproject.view.weather.MainActivity class AerisNotification { private var builder: NotificationCompat.Builder? = null private var remoteViews: RemoteViews? = null var map = HashMap<String, Int>() get() { field["am_pcloudyr"] = R.drawable.mcloudyr field["am_showers"] = R.drawable.showers field["am_snowshowers"] = R.drawable.showers field["am_tstorm"] = R.drawable.tstorms field["blizzard"] = R.drawable.blizzard field["blizzardn"] = R.drawable.blizzard field["blowingsnow"] = R.drawable.snoww field["blowingsnown"] = R.drawable.snoww field["chancestorm"] = R.drawable.tstorms field["chancestormn"] = R.drawable.tstorms field["clear"] = R.drawable.sunny field["clearn"] = R.drawable.clearn field["clearw"] = R.drawable.wind field["clearwn"] = R.drawable.wind field["cloudy"] = R.drawable.cloudy field["cloudyn"] = R.drawable.cloudy field["cloudyw"] = R.drawable.wind field["cloudywn"] = R.drawable.wind field["drizzle"] = R.drawable.drizzle field["drizzlef"] = R.drawable.drizzle field["drizzlefn"] = R.drawable.drizzle field["drizzlen"] = R.drawable.drizzle field["dust"] = R.drawable.hazy field["dustn"] = R.drawable.hazyn field["fair"] = R.drawable.sunny field["fairn"] = R.drawable.clearn field["fairnw"] = R.drawable.wind field["fairnwn"] = R.drawable.wind field["fdrizzle"] = R.drawable.drizzle field["fdrizzlen"] = R.drawable.drizzle field["flurries"] = R.drawable.flurries field["flurriesn"] = R.drawable.flurries field["flurriesw"] = R.drawable.flurries field["flurrieswn"] = R.drawable.flurries field["fog"] = R.drawable.fog field["fogn"] = R.drawable.fog field["freezingrain"] = R.drawable.rain field["freezingrainn"] = R.drawable.rain field["hazy"] = R.drawable.hazy field["hazyn"] = R.drawable.hazyn field["mcloudy"] = R.drawable.mcloudy field["mcloudyn"] = R.drawable.mcloudyn field["mcloudyr"] = R.drawable.mcloudyr field["mcloudyrn"] = R.drawable.mcloudyrn field["mcloudyrw"] = R.drawable.mcloudyrw field["mcloudyrwn"] = R.drawable.mcloudyrwn field["mcloudys"] = R.drawable.mcloudys field["mcloudysfn"] = R.drawable.mcloudysn field["mcloudysfw"] = R.drawable.mcloudysw field["mcloudysfwn"] = R.drawable.mcloudyswn field["mcloudysn"] = R.drawable.mcloudysn field["mcloudysw"] = R.drawable.mcloudysw field["mcloudyswn"] = R.drawable.mcloudyswn field["mcloudyt"] = R.drawable.mcloudyt field["mcloudytn"] = R.drawable.mcloudytn field["mcloudytw"] = R.drawable.mcloudytw field["mcloudytwn"] = R.drawable.mcloudytwn field["mcloudyw"] = R.drawable.wind field["mcloudywn"] = R.drawable.wind field["pcloudy"] = R.drawable.pcloudy field["pcloudyn"] = R.drawable.pcloudyn field["pcloudyr"] = R.drawable.mcloudyr field["pcloudyrn"] = R.drawable.mcloudyrn field["pcloudyrw"] = R.drawable.mcloudyrw field["pcloudyrwn"] = R.drawable.mcloudyrwn field["pcloudys"] = R.drawable.mcloudys field["pcloudysf"] = R.drawable.mcloudys field["pcloudysfn"] = R.drawable.mcloudysn field["pcloudysfw"] = R.drawable.snoww field["pcloudysfwn"] = R.drawable.snoww field["pcloudysn"] = R.drawable.mcloudysn field["pcloudysw"] = R.drawable.mcloudysw field["pcloudyswn"] = R.drawable.mcloudyswn field["pcloudyt"] = R.drawable.mcloudyt field["pcloudytn"] = R.drawable.mcloudytn field["pcloudytw"] = R.drawable.mcloudytw field["pcloudytwn"] = R.drawable.mcloudytwn field["pcloudyw"] = R.drawable.wind field["pcloudywn"] = R.drawable.wind field["pm_pcloudy"] = R.drawable.pcloudy field["pm_pcloudyr"] = R.drawable.mcloudyr field["pm_showers"] = R.drawable.showers field["pm_snowshowers"] = R.drawable.snowshowers field["pm_tstorm"] = R.drawable.tstorms field["rain"] = R.drawable.rain field["rainn"] = R.drawable.rain field["rainandsnow"] = R.drawable.rainandsnow field["rainandsnown"] = R.drawable.rainandsnow field["raintosnow"] = R.drawable.rainandsnow field["raintosnown"] = R.drawable.rainandsnow field["rainw"] = R.drawable.rainw field["showers"] = R.drawable.showers field["showersn"] = R.drawable.showers field["showersw"] = R.drawable.showersw field["showerswn"] = R.drawable.showersw field["sleet"] = R.drawable.sleet field["sleetn"] = R.drawable.sleet field["sleetsnow"] = R.drawable.sleetsnow field["sleetsnown"] = R.drawable.sleetsnow field["smoke"] = R.drawable.hazy field["smoken"] = R.drawable.hazyn field["snow"] = R.drawable.snow field["snown"] = R.drawable.snow field["snowflurries"] = R.drawable.flurries field["snowflurriesn"] = R.drawable.flurries field["snowshowers"] = R.drawable.snowshowers field["snowshowersn"] = R.drawable.snowshowers field["snowshowersw"] = R.drawable.snowshowers field["snowshowerswn"] = R.drawable.snowshowersn field["snowtorain"] = R.drawable.rainandsnow field["snowtorainn"] = R.drawable.rainandsnown field["snoww"] = R.drawable.snoww field["snowwn"] = R.drawable.snoww field["sunny"] = R.drawable.sunny field["sunnyn"] = R.drawable.clearn field["sunnyw"] = R.drawable.wind field["sunnywn"] = R.drawable.wind field["tstorm"] = R.drawable.tstorms field["tstormn"] = R.drawable.tstorms field["tstormw"] = R.drawable.tstormsw field["tstormwn"] = R.drawable.tstormsw field["tstorms"] = R.drawable.tstorms field["tstormsn"] = R.drawable.tstorms field["tstormsw"] = R.drawable.tstormsw field["tstormswn"] = R.drawable.tstormsw field["wind"] = R.drawable.wind field["wintrymix"] = R.drawable.wintrymix field["wintrymixn"] = R.drawable.wintrymix return field } private set private val TAG = AerisNotification::class.java.simpleName /** * Sets the notification for the observation */ private val CHANNEL_ID = "channelID" private val CHANNEL_NAME = "channelName" fun setCustom( context: Context, isMetrics: Boolean, obResponse: ObservationResponse, fResponse: ForecastsResponse ) { createNotifChannel(context) Logger.d(TAG, "setCustomNotification()") val intent = Intent(context, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) val ob = obResponse.observation var printTemp = "" if (builder == null) { builder = NotificationCompat.Builder(context, CHANNEL_ID) .setContentTitle(context.resources.getString(R.string.app_name)) .setSmallIcon(getDrawableByName(obResponse.observation.icon)) .setOngoing(true) } if (remoteViews == null) { remoteViews = RemoteViews(context.packageName, R.layout.ntf_observation) builder?.setContent(remoteViews) } remoteViews?.apply { setImageViewResource( R.id.ivNtfIcon, FileUtil.getDrawableByName(ob.icon, context) ) setTextViewText(R.id.tvNtfDesc, ob.weather) printTemp = FormatUtil.printDegree(context, isMetrics, Pair(ob.tempC, ob.tempF)) builder?.setContentText(ob.weather.toString() + " " + printTemp) setTextViewText(R.id.tvNtfTemp, printTemp) val period = fResponse.getPeriod(0) // reverses order if isday is not true. val indexes = if (period.isDay) { listOf(0, 1) } else { listOf(1, 0) } fResponse.getPeriod(indexes[0]).let { setTextViewText( R.id.tvNtfHigh, FormatUtil.printDegree(context, isMetrics, Pair(it.maxTempC, it.maxTempF)) ) } fResponse.getPeriod(indexes[1]).let { setTextViewText( R.id.tvNtfLow, FormatUtil.printDegree(context, isMetrics, Pair(it.minTempC, it.minTempF)) ) } } // Create Notification Manager val notificationmanager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationmanager.notify( BaseApplication.PRIMARY_FOREGROUND_NOTIF_SERVICE_ID, builder?.build() ) } private fun createNotifChannel(context: Context) { val channel = NotificationChannel( CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT ).apply { lightColor = Color.BLUE enableLights(true) } val manager = context.getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager manager.createNotificationChannel(channel) } fun cancel(context: Context) { // Create Notification Manager val notificationmanager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Build Notification with Notification Manager //notificationmanager.cancel(WEATHER_NTF); notificationmanager.cancel(BaseApplication.PRIMARY_FOREGROUND_NOTIF_SERVICE_ID) remoteViews = null builder = null } /** * Gets the drawable by the string name. This is used in conjunction with * the icon field in many of the forecast, observation. Accesses the name * from the drawable folder. * * @param name name of the drawable * @return the int key of the drawable. */ private fun getDrawableByName(name: String?): Int { if (name == null) { return 0 } val iconName = name.substring(0, name.indexOf(".")) Logger.d( TAG, "getDrawableByName() - ObIcon: $iconName" ) return map[iconName] ?: if (iconName[iconName.length - 1] == 'n') { map[iconName.substring(0, iconName.length - 1)] ?: 0 } else 0 } }
Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/service/AerisNotification.kt
756795809
package org.wikipedia.widgets import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.ComponentName import android.content.Context import android.widget.RemoteViews import org.wikipedia.Constants.InvokeSource import org.wikipedia.R import org.wikipedia.search.SearchActivity import org.wikipedia.util.log.L class WidgetProviderSearch : AppWidgetProvider() { override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { val thisWidget = ComponentName(context, WidgetProviderSearch::class.java) val allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget) for (widgetId in allWidgetIds) { L.d("updating widget...") val remoteViews = RemoteViews(context.packageName, R.layout.widget_search) val pendingIntent = PendingIntent.getActivity(context, 0, SearchActivity.newIntent(context, InvokeSource.WIDGET, null), PendingIntent.FLAG_UPDATE_CURRENT) remoteViews.setOnClickPendingIntent(R.id.widget_container, pendingIntent) appWidgetManager.updateAppWidget(widgetId, remoteViews) } } }
app/src/main/java/org/wikipedia/widgets/WidgetProviderSearch.kt
2938626812
/* * 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.intellij.stats.completion import com.intellij.stats.validation.EventLine import com.intellij.stats.validation.InputSessionValidator import com.intellij.stats.validation.SessionValidationResult import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import java.io.File class ValidatorTest { private companion object { const val SESSION_ID = "ab47454a7283" } lateinit var validator: InputSessionValidator val sessionStatuses = hashMapOf<String, Boolean>() @Before fun setup() { sessionStatuses.clear() val result = object : SessionValidationResult { override fun addErrorSession(errorSession: List<EventLine>) { val sessionUid = errorSession.first().sessionUid ?: return sessionStatuses[sessionUid] = false } override fun addValidSession(validSession: List<EventLine>) { val sessionUid = validSession.first().sessionUid ?: return sessionStatuses[sessionUid] = true } } validator = InputSessionValidator(result) } private fun file(path: String): File { return File(javaClass.classLoader.getResource(path).file) } @Test fun testValidData() { val file = file("data/valid_data.txt") validator.validate(file.readLines()) assertThat(sessionStatuses[SESSION_ID]).isTrue() } @Test fun testDataWithAbsentFieldInvalid() { val file = file("data/absent_field.txt") validator.validate(file.readLines()) assertThat(sessionStatuses[SESSION_ID]).isFalse() } @Test fun testInvalidWithoutBacket() { val file = file("data/no_bucket.txt") validator.validate(file.readLines()) assertThat(sessionStatuses[SESSION_ID]).isFalse() } @Test fun testInvalidWithoutVersion() { val file = file("data/no_version.txt") validator.validate(file.readLines()) assertThat(sessionStatuses[SESSION_ID]).isFalse() } @Test fun testDataWithExtraFieldInvalid() { val file = file("data/extra_field.txt") validator.validate(file.readLines()) assertThat(sessionStatuses[SESSION_ID]).isFalse() } }
plugins/stats-collector/log-events/test/com/intellij/stats/completion/ValidatorTest.kt
2172301974
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.updateSettings.impl import com.intellij.openapi.components.BaseState import com.intellij.util.xmlb.annotations.CollectionBean import com.intellij.util.xmlb.annotations.OptionTag class UpdateOptions : BaseState() { @get:CollectionBean val pluginHosts by list<String>() @get:CollectionBean val ignoredBuildNumbers by list<String>() @get:CollectionBean val enabledExternalComponentSources by list<String>() @get:CollectionBean val knownExternalComponentSources by list<String>() @get:CollectionBean val externalUpdateChannels by map<String, String>() @get:OptionTag("CHECK_NEEDED") var isCheckNeeded by property(true) @get:OptionTag("LAST_TIME_CHECKED") var lastTimeChecked by property(0L) @get:OptionTag("LAST_BUILD_CHECKED") var lastBuildChecked by string() @get:OptionTag("UPDATE_CHANNEL_TYPE") var updateChannelType by string(ChannelStatus.RELEASE.code) @get:OptionTag("SECURE_CONNECTION") var isUseSecureConnection by property(true) @get:OptionTag("THIRD_PARTY_PLUGINS_ALLOWED") var isThirdPartyPluginsAllowed by property(false) }
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateOptions.kt
3322509366
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sharedtest.persistence.remote import android.net.Uri import com.google.android.ground.persistence.remote.RemoteStorageManager import com.google.android.ground.persistence.remote.TransferProgress import io.reactivex.Flowable import io.reactivex.Single import java.io.File import javax.inject.Inject class FakeRemoteStorageManager @Inject internal constructor() : RemoteStorageManager { override fun getDownloadUrl(remoteDestinationPath: String): Single<Uri> = Single.never() override fun uploadMediaFromFile( file: File, remoteDestinationPath: String ): Flowable<TransferProgress> = Flowable.never() }
sharedTest/src/main/java/com/sharedtest/persistence/remote/FakeRemoteStorageManager.kt
1986364053
package foo class <caret>Test(name: String) : TestBase(name)
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/protectedConstructorRefInSuperListEntry/before/foo/Test.kt
2828004802
package tripleklay.ui import klay.core.PaintClock import klay.core.Platform import klay.core.StubPlatform import org.junit.Test import react.Signal import tripleklay.ui.layout.AxisLayout import kotlin.test.assertTrue // import klay.java.JavaPlatform; class ElementTest { val frame = Signal<PaintClock>() internal open class TestGroup : Group(AxisLayout.vertical()) { var added: Int = 0 var removed: Int = 0 fun assertAdded(count: Int) { assertTrue(added == count && removed == count - 1) } fun assertRemoved(count: Int) { assertTrue(removed == count && added == count) } override fun wasAdded() { super.wasAdded() added++ } override fun wasRemoved() { super.wasRemoved() removed++ } } internal var iface = Interface(stub, frame) internal fun newRoot(): Root { return iface.createRoot(AxisLayout.vertical(), Stylesheet.builder().create()) } /** Tests the basic functionality of adding and removing elements and that the wasAdded * and wasRemoved members are called as expected. */ @Test fun testAddRemove() { val root = newRoot() val g1 = TestGroup() val g2 = TestGroup() g1.assertRemoved(0) root.add(g1) g1.assertAdded(1) g1.add(g2) g1.assertAdded(1) g2.assertAdded(1) g1.remove(g2) g1.assertAdded(1) g2.assertRemoved(1) root.remove(g1) g1.assertRemoved(1) g2.assertRemoved(1) g1.add(g2) g1.assertRemoved(1) g2.assertRemoved(1) root.add(g1) g1.assertAdded(2) g2.assertAdded(2) } /** Tests that a group may add a child into another group whilst being removed and that the * child receives the appropriate calls to wasAdded and wasRemoved. Similarly tests for * adding the child during its own add. */ @Test fun testChildTransfer() { class Pa : TestGroup() { var child1 = TestGroup() var child2 = TestGroup() var brother = TestGroup() override fun wasRemoved() { // hand off the children to brother brother.add(child1) super.wasRemoved() brother.add(child2) } override fun wasAdded() { // steal the children back from brother add(child1) super.wasAdded() add(child2) } } val root = newRoot() val pa = Pa() pa.assertRemoved(0) root.add(pa) pa.assertAdded(1) pa.child1.assertAdded(1) pa.child2.assertAdded(1) root.remove(pa) pa.assertRemoved(1) pa.child1.assertRemoved(1) pa.child2.assertRemoved(1) root.add(pa.brother) pa.child1.assertAdded(2) pa.child2.assertAdded(2) root.add(pa) pa.assertAdded(2) pa.child1.assertAdded(3) pa.child2.assertAdded(3) root.remove(pa) pa.assertRemoved(2) pa.child1.assertAdded(4) pa.child2.assertAdded(4) } /** Tests that a group may add a grandchild into another group whilst being removed and that * the grandchild receives the appropriate calls to wasAdded and wasRemoved. Similarly tests * for adding the grandchild during its own add. */ @Test fun testGrandchildTransfer() { class GrandPa : TestGroup() { var child = TestGroup() var grandchild1 = TestGroup() var grandchild2 = TestGroup() var brother = TestGroup() init { add(child) } override fun wasRemoved() { brother.add(grandchild1) super.wasRemoved() brother.add(grandchild2) } override fun wasAdded() { child.add(grandchild1) super.wasAdded() child.add(grandchild2) } } val root = newRoot() val pa = GrandPa() pa.assertRemoved(0) root.add(pa) pa.assertAdded(1) pa.grandchild1.assertAdded(1) pa.grandchild2.assertAdded(1) root.remove(pa) pa.assertRemoved(1) pa.grandchild1.assertRemoved(1) pa.grandchild2.assertRemoved(1) root.add(pa.brother) pa.grandchild1.assertAdded(2) pa.grandchild2.assertAdded(2) root.add(pa) pa.assertAdded(2) pa.grandchild1.assertAdded(3) pa.grandchild2.assertAdded(3) root.remove(pa) pa.assertRemoved(2) pa.grandchild1.assertAdded(4) pa.grandchild2.assertAdded(4) } companion object { // static { // JavaPlatform.Config config = new JavaPlatform.Config(); // config.headless = true; // JavaPlatform.register(config); // } var stub: Platform = StubPlatform() } }
tripleklay/src/test/kotlin/tripleklay/ui/ElementTest.kt
2180196516
// FIR_IDENTICAL // FIR_COMPARISON class Outer { class Nested { inner class Inner { fun String.foo() { takeHandler1 { takeHandler2({ takeHandler3 { this<caret> } }) } } } } } fun takeHandler1(handler: Int.() -> Unit){} fun takeHandler2(handler: Char.() -> Unit){} fun takeHandler3(handler: Char.() -> Unit){} // INVOCATION_COUNT: 1 // EXIST: { lookupString: "this", itemText: "this", tailText: null, typeText: "Char", attributes: "bold" } // ABSENT: "this@takeHandler3" // EXIST: { lookupString: "this@takeHandler2", itemText: "this", tailText: "@takeHandler2", typeText: "Char", attributes: "bold" } // EXIST: { lookupString: "this@takeHandler1", itemText: "this", tailText: "@takeHandler1", typeText: "Int", attributes: "bold" } // EXIST: { lookupString: "this@foo", itemText: "this", tailText: "@foo", typeText: "String", attributes: "bold" } // EXIST: { lookupString: "this@Inner", itemText: "this", tailText: "@Inner", typeText: "Outer.Nested.Inner", attributes: "bold" } // EXIST: { lookupString: "this@Nested", itemText: "this", tailText: "@Nested", typeText: "Outer.Nested", attributes: "bold" } // ABSENT: "this@Outer" // NOTHING_ELSE
plugins/kotlin/completion/tests/testData/keywords/This.kt
1327769823
package com.mikepenz.fastadapter.app.items import android.view.View import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.mikepenz.fastadapter.app.R import com.mikepenz.fastadapter.items.AbstractItem import com.mikepenz.fastadapter.ui.utils.StringHolder class SectionHeaderItem(text: String) : AbstractItem<SectionHeaderItem.ViewHolder>() { val text: StringHolder = StringHolder(text) override val type: Int get() = R.id.fastadapter_section_header_item override val layoutRes: Int get() = R.layout.section_header_item override fun bindView(holder: ViewHolder, payloads: List<Any>) { super.bindView(holder, payloads) text.applyTo(holder.text) } override fun unbindView(holder: ViewHolder) { holder.text.text = null } override fun getViewHolder(v: View): ViewHolder = ViewHolder(v) class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { var text: TextView = view.findViewById(R.id.text) } }
app/src/main/java/com/mikepenz/fastadapter/app/items/SectionHeaderItem.kt
115210856
// Copyright 2000-2021 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.util.indexing.snapshot import com.intellij.openapi.Forceable import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Comparing import com.intellij.util.indexing.ID import com.intellij.util.indexing.IndexInfrastructure import com.intellij.util.io.DataInputOutputUtil import com.intellij.util.io.IOUtil import com.intellij.util.io.KeyDescriptor import com.intellij.util.io.PersistentEnumerator import java.io.Closeable import java.io.DataInput import java.io.DataOutput import java.io.IOException private val LOG = logger<CompositeHashIdEnumerator>() internal class CompositeHashIdEnumerator(private val indexId: ID<*, *>): Closeable, Forceable { @Volatile private var enumerator = init() @Throws(IOException::class) override fun close() = enumerator.close() override fun isDirty(): Boolean = enumerator.isDirty override fun force() = enumerator.force() @Throws(IOException::class) fun clear() { try { close() } catch (e: IOException) { LOG.error(e) } finally { IOUtil.deleteAllFilesStartingWith(getBasePath()) init() } } fun enumerate(hashId: Int, subIndexerTypeId: Int) = enumerator.enumerate(CompositeHashId(hashId, subIndexerTypeId)) private fun getBasePath() = IndexInfrastructure.getIndexRootDir(indexId).resolve("compositeHashId") private fun init(): PersistentEnumerator<CompositeHashId> { enumerator = PersistentEnumerator(getBasePath(), CompositeHashIdDescriptor(), 64 * 1024) return enumerator } } private data class CompositeHashId(val baseHashId: Int, val subIndexerTypeId: Int) private class CompositeHashIdDescriptor : KeyDescriptor<CompositeHashId> { override fun getHashCode(value: CompositeHashId): Int { return value.hashCode() } override fun isEqual(val1: CompositeHashId, val2: CompositeHashId): Boolean { return Comparing.equal(val1, val2) } @Throws(IOException::class) override fun save(out: DataOutput, value: CompositeHashId) { DataInputOutputUtil.writeINT(out, value.baseHashId) DataInputOutputUtil.writeINT(out, value.subIndexerTypeId) } @Throws(IOException::class) override fun read(`in`: DataInput): CompositeHashId { return CompositeHashId(DataInputOutputUtil.readINT(`in`), DataInputOutputUtil.readINT(`in`)) } }
platform/lang-impl/src/com/intellij/util/indexing/snapshot/CompositeHashIdEnumerator.kt
458397754
fun test(n: Int): String { <caret>return when (n) { 1 -> "one" else -> "two" } }
plugins/kotlin/idea/tests/testData/intentions/branched/unfolding/returnToWhen/simpleWhen.kt
2486808849
package test annotation class IntAnno annotation class StringAnno annotation class DoubleAnno class Class { @[IntAnno] val Int.extension: Int get() = this @[StringAnno] val String.extension: String get() = this @[DoubleAnno] val Double.extension: Int get() = 42 }
plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/annotations/propertiesWithoutBackingFields/ExtensionsWithSameNameClass.kt
2218868688
/** MIT License Copyright (c) 2016 Shaun Reich <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import com.ore.infinium.OreWorld import org.junit.Ignore import org.junit.Test class WorldIOTest { internal var world = OreWorld(null, null, OreWorld.WorldInstanceType.Server, OreWorld.WorldSize.TestTiny) @Test @Ignore @Throws(Exception::class) fun saveWorld() { // val worldSize = OreWorld.WorldSize.TestTiny // //setup // for (x in 0 until worldSize.width) { // for (y in 0 until worldSize.height) { // world.setBlockType(x, y, OreBlock.BlockType.Diamond.oreValue) // } // } // // world.worldIO.saveWorld() // // //verify read back // for (x in 0 until worldSize.width) { // for (y in 0 until worldSize.height) { // assertEquals(OreBlock.BlockType.Diamond.oreValue, world.blockType(x, y), // "blocks array read back failed.") // } // } } //WorldGenerator.generateWorldAndOutputImage() }
core/test/WorldIOTest.kt
377069880
class B {}
java/ql/integration-tests/all-platforms/kotlin/extractor_crash/code/B.kt
1396505723
package cat.helm.basearchitecture.data.repository.tvshow.query import cat.helm.basearchitecture.data.repository.query.Query /** * Created by Borja on 6/6/17. */ interface GetTvShowByNameQuery : Query { companion object Parameters { val NAME_QUERY: String = "name" } }
data/src/main/java/cat/helm/basearchitecture/data/repository/tvshow/query/GetTvShowByNameQuery.kt
2468200011
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.version import com.demonwav.mcdev.platform.mcp.McpVersionPair import com.demonwav.mcdev.util.fromJson import com.demonwav.mcdev.util.getMajorVersion import com.demonwav.mcdev.util.sortVersions import com.google.gson.Gson import java.io.IOException import java.net.URL import java.util.ArrayList import kotlin.Int class McpVersion private constructor(private val map: Map<String, Map<String, List<Int>>>) { val versions: List<String> by lazy { sortVersions(map.keys) } data class McpVersionSet(val goodVersions: List<McpVersionPair>, val badVersions: List<McpVersionPair>) private fun getSnapshot(version: String): McpVersionSet { return get(version, "snapshot") } private fun getStable(version: String): McpVersionSet { return get(version, "stable") } private operator fun get(version: String, type: String): McpVersionSet { val good = ArrayList<McpVersionPair>() val bad = ArrayList<McpVersionPair>() val keySet = map.keys for (mcVersion in keySet) { val versions = map[mcVersion] if (versions != null) { versions[type]?.let { vers -> val pairs = vers.map { McpVersionPair("${type}_$it", mcVersion) } if (mcVersion.startsWith(version)) { good.addAll(pairs) } else { bad.addAll(pairs) } } } } return McpVersionSet(good, bad) } fun getMcpVersionList(version: String): List<McpVersionEntry> { val result = mutableListOf<McpVersionEntry>() val majorVersion = getMajorVersion(version) val stable = getStable(majorVersion) stable.goodVersions.asSequence().sortedWith(Comparator.reverseOrder()) .mapTo(result) { s -> McpVersionEntry(s) } val snapshot = getSnapshot(majorVersion) snapshot.goodVersions.asSequence().sortedWith(Comparator.reverseOrder()) .mapTo(result) { s -> McpVersionEntry(s) } // The "seconds" in the pairs are bad, but still available to the user // We will color them read stable.badVersions.asSequence().sortedWith(Comparator.reverseOrder()) .mapTo(result) { s -> McpVersionEntry(s, true) } snapshot.badVersions.asSequence().sortedWith(Comparator.reverseOrder()) .mapTo(result) { s -> McpVersionEntry(s, true) } return result } companion object { fun downloadData(): McpVersion? { try { val text = URL("http://export.mcpbot.bspk.rs/versions.json").readText() val map = Gson().fromJson<Map<String, Map<String, List<Int>>>>(text) val mcpVersion = McpVersion(map) mcpVersion.versions return mcpVersion } catch (ignored: IOException) { } return null } } }
src/main/kotlin/com/demonwav/mcdev/platform/mcp/version/McpVersion.kt
521114739
package asciitohex import tornadofx.FXEvent data class ConvertEvent( val conversion: AsciiConversion, val input: String ) : FXEvent() data class ClipboardEvent(val conversion: AsciiConversion) : FXEvent() object NewConversion : FXEvent()
kotlin/asciitohex/Events.kt
1808677571
package io.georocket.cli import de.undercouch.underline.InputReader import de.undercouch.underline.Option.ArgumentType import de.undercouch.underline.OptionDesc import de.undercouch.underline.UnknownAttributes import io.georocket.ImporterVerticle import io.georocket.constants.AddressConstants import io.georocket.index.PropertiesParser import io.georocket.index.TagsParser import io.georocket.tasks.ImportingTask import io.georocket.tasks.TaskRegistry import io.georocket.util.MimeTypeUtils import io.georocket.util.SizeFormat import io.georocket.util.formatUntilNow import io.vertx.core.buffer.Buffer import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import io.vertx.core.streams.WriteStream import io.vertx.kotlin.core.deploymentOptionsOf import io.vertx.kotlin.coroutines.await import kotlinx.coroutines.delay import org.antlr.v4.runtime.misc.ParseCancellationException import org.apache.commons.io.FilenameUtils import org.apache.commons.lang3.SystemUtils import org.apache.tools.ant.Project import org.apache.tools.ant.types.FileSet import org.bson.types.ObjectId import org.fusesource.jansi.AnsiConsole import org.slf4j.LoggerFactory import java.io.File import java.io.IOException import java.nio.file.Paths /** * Import one or more files into GeoRocket */ class ImportCommand : GeoRocketCommand() { companion object { private val log = LoggerFactory.getLogger(ImportCommand::class.java) } override val usageName = "import" override val usageDescription = "Import one or more files into GeoRocket" private data class Metrics(val bytesImported: Long) /** * The patterns of the files to import */ @set:UnknownAttributes("FILE PATTERN") var patterns = emptyList<String>() @set:OptionDesc(longName = "layer", shortName = "l", description = "absolute path to the destination layer", argumentName = "PATH", argumentType = ArgumentType.STRING) var layer: String? = null @set:OptionDesc(longName = "fallbackCRS", shortName = "c", description = "the CRS to use for indexing if the file does not specify one", argumentName = "CRS", argumentType = ArgumentType.STRING) var fallbackCRS: String? = null @set:OptionDesc(longName = "tags", shortName = "t", description = "comma-separated list of tags to attach to the file(s)", argumentName = "TAGS", argumentType = ArgumentType.STRING) var tags: String? = null @set:OptionDesc(longName = "properties", shortName = "props", description = "comma-separated list of properties (key:value) to attach to the file(s)", argumentName = "PROPERTIES", argumentType = ArgumentType.STRING) var properties: String? = null override fun checkArguments(): Boolean { if (patterns.isEmpty()) { error("no file pattern given. provide at least one file to import.") return false } if (tags != null) { try { TagsParser.parse(tags) } catch (e: ParseCancellationException) { error("Invalid tag syntax: ${e.message}") return false } } if (properties != null) { try { PropertiesParser.parse(properties) } catch (e: ParseCancellationException) { error("Invalid property syntax: ${e.message}") return false } } return super.checkArguments() } /** * Check if the given string contains a glob character ('*', '{', '?', or '[') * @param s the string * @return true if the string contains a glob character, false otherwise */ private fun hasGlobCharacter(s: String): Boolean { var i = 0 while (i < s.length) { val c = s[i] if (c == '\\') { ++i } else if (c == '*' || c == '{' || c == '?' || c == '[') { return true } ++i } return false } override suspend fun doRun(remainingArgs: Array<String>, reader: InputReader, out: WriteStream<Buffer>): Int { val start = System.currentTimeMillis() // resolve file patterns val files = ArrayList<String>() for (p in patterns) { // convert Windows backslashes to slashes (necessary for Files.newDirectoryStream()) val pattern = if (SystemUtils.IS_OS_WINDOWS) { FilenameUtils.separatorsToUnix(p) } else { p } // collect paths and glob patterns val roots = ArrayList<String>() val globs = ArrayList<String>() val parts = pattern.split("/") var rootParsed = false for (part in parts) { if (!rootParsed) { if (hasGlobCharacter(part)) { globs.add(part) rootParsed = true } else { roots.add(part) } } else { globs.add(part) } } if (globs.isEmpty()) { // string does not contain a glob pattern at all files.add(pattern) } else { // string contains a glob pattern if (roots.isEmpty()) { // there are no paths in the string. start from the current // working directory roots.add(".") } // add all files matching the pattern val root = roots.joinToString("/") val glob = globs.joinToString("/") val project = Project() val fs = FileSet() fs.dir = File(root) fs.setIncludes(glob) val ds = fs.getDirectoryScanner(project) ds.includedFiles.mapTo(files) { Paths.get(root, it).toString() } } } if (files.isEmpty()) { error("given pattern didn't match any files") return 1 } return try { val metrics = doImport(files) var m = "file" if (files.size > 1) { m += "s" } println("Successfully imported ${files.size} $m") println(" Total time: ${start.formatUntilNow()}") println(" Total data size: ${SizeFormat.format(metrics.bytesImported)}") 0 } catch (t: Throwable) { error(t.message) 1 } } /** * Determine the sizes of all given files * @param files the files * @return a list of pairs containing file names and sizes */ private suspend fun getFileSizes(files: List<String>): List<Pair<String, Long>> { val fs = vertx.fileSystem() return files.map { path -> val props = fs.props(path).await() Pair(path, props.size()) } } /** * Import files using a HTTP client and finally call a handler * @param files the files to import * @return an observable that will emit metrics when all files have been imported */ private suspend fun doImport(files: List<String>): Metrics { AnsiConsole.systemInstall() // launch importer verticle val importerVerticleId = vertx.deployVerticle(ImporterVerticle(), deploymentOptionsOf(config = config)).await() try { ImportProgressRenderer(vertx).use { progress -> progress.totalFiles = files.size val filesWithSizes = getFileSizes(files) val totalSize = filesWithSizes.sumOf { it.second } progress.totalSize = totalSize var bytesImported = 0L for (file in filesWithSizes.withIndex()) { val path = file.value.first val size = file.value.second val index = file.index progress.startNewFile(Paths.get(path).fileName.toString()) progress.index = index progress.size = size val m = importFile(path, size, progress) bytesImported += m.bytesImported } return Metrics(bytesImported) } } finally { vertx.undeploy(importerVerticleId).await() AnsiConsole.systemUninstall() } } /** * Try to detect the content type of a file with the given [filepath]. */ private suspend fun detectContentType(filepath: String): String { return vertx.executeBlocking<String> { f -> try { var mimeType = MimeTypeUtils.detect(File(filepath)) if (mimeType == null) { log.warn("Could not detect file type of $filepath. Falling back to " + "application/octet-stream.") mimeType = "application/octet-stream" } f.complete(mimeType) } catch (e: IOException) { f.fail(e) } }.await() } /** * Upload a file to GeoRocket * @param path the path to the file to import * @param fileSize the size of the file * @param progress a renderer that display the progress on the terminal * @return a metrics object */ private suspend fun importFile(path: String, fileSize: Long, progress: ImportProgressRenderer): Metrics { val detectedContentType = detectContentType(path).also { log.info("Guessed mime type '$it'.") } val correlationId = ObjectId().toString() val msg = JsonObject() .put("filepath", path) .put("layer", layer) .put("contentType", detectedContentType) .put("correlationId", correlationId) if (tags != null) { msg.put("tags", JsonArray(TagsParser.parse(tags))) } if (properties != null) { msg.put("properties", JsonObject(PropertiesParser.parse(properties))) } if (fallbackCRS != null) { msg.put("fallbackCRSString", fallbackCRS) } // run importer val taskId = vertx.eventBus().request<String>(AddressConstants.IMPORTER_IMPORT, msg).await().body() while (true) { val t = (TaskRegistry.getById(taskId) ?: break) as ImportingTask progress.current = t.bytesProcessed if (t.endTime != null) { break } delay(100) } progress.current = fileSize return Metrics(fileSize) } }
src/main/kotlin/io/georocket/cli/ImportCommand.kt
2087536486
// 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.stats.sender import com.intellij.ide.util.PropertiesComponent import java.text.SimpleDateFormat import java.util.* class DailyLimitSendingWatcher(private val dailyLimit: Int, private val info: SentDataInfo) { fun isLimitReached(): Boolean = info.sentToday(System.currentTimeMillis()) >= dailyLimit fun dataSent(size: Int) { info.dataSent(System.currentTimeMillis(), size) } abstract class SentDataInfo { companion object { private val FORMAT = SimpleDateFormat("yyyyMMdd") } fun sentToday(timestamp: Long): Int { if (!isSameDay(timestamp, latestSendingTimestamp)) { return 0 } return sentCount } fun dataSent(timestamp: Long, bytesCount: Int) { sentCount = sentToday(timestamp) + bytesCount latestSendingTimestamp = timestamp } private fun isSameDay(ts1: Long, ts2: Long): Boolean { fun Long.asString(): String = FORMAT.format(Date(this)) return ts1.asString() == ts2.asString() } protected abstract var sentCount: Int protected abstract var latestSendingTimestamp: Long class DumbInfo : SentDataInfo() { override var sentCount: Int = 0 override var latestSendingTimestamp: Long = 0 } } }
plugins/stats-collector/src/com/intellij/stats/sender/DailyLimitSendingWatcher.kt
883835692
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0 import org.apache.causeway.client.kroviz.snapshots.Response object SO_LIST_ALL_INVOKE : Response() { override val url = "http://localhost:8080/restful/services/simple.SimpleObjectMenu/actions/listAll/invoke" override val str = """{ "links": [ { "rel": "self", "href": "http://localhost:8080/restful/services/simple.SimpleObjectMenu/actions/listAll/invoke", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/action-result\"", "args": {} } ], "resulttype": "list", "result": { "value": [ { "rel": "urn:org.restfulobjects:rels/element", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/0", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Foo" }, { "rel": "urn:org.restfulobjects:rels/element", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/1", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Bar" }, { "rel": "urn:org.restfulobjects:rels/element", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/2", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Baz" }, { "rel": "urn:org.restfulobjects:rels/element", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/3", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Frodo" }, { "rel": "urn:org.restfulobjects:rels/element", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/4", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Froyo" }, { "rel": "urn:org.restfulobjects:rels/element", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/5", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Fizz" }, { "rel": "urn:org.restfulobjects:rels/element", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/6", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Bip" }, { "rel": "urn:org.restfulobjects:rels/element", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/7", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Bop" }, { "rel": "urn:org.restfulobjects:rels/element", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/8", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Bang" }, { "rel": "urn:org.restfulobjects:rels/element", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/9", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Boo" } ], "links": [ { "rel": "urn:org.restfulobjects:rels/return-type", "href": "http://localhost:8080/restful/domain-types/java.util.List", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/domain-type\"" } ], "extensions": {} } }""" }
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/SO_LIST_ALL_INVOKE.kt
265276313
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k.conversions import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.idea.base.psi.kotlinFqName import org.jetbrains.kotlin.j2k.ast.Nullability.NotNull import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.psi import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.JKClassType import org.jetbrains.kotlin.nj2k.types.JKJavaVoidType import org.jetbrains.kotlin.nj2k.types.updateNullability import org.jetbrains.kotlin.utils.addToStdlib.safeAs class JavaStandardMethodsConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKClass) return recurse(element) for (declaration in element.classBody.declarations) { if (declaration !is JKMethodImpl) continue if (fixToStringMethod(declaration)) continue if (fixFinalizeMethod(declaration, element)) continue if (fixCloneMethod(declaration)) { val cloneableClass = JavaPsiFacade.getInstance(context.project) .findClass("java.lang.Cloneable", GlobalSearchScope.allScope(context.project)) ?: continue val directlyImplementsCloneable = element.psi<PsiClass>()?.isInheritor(cloneableClass, false) ?: continue val hasCloneableInSuperClasses = declaration.psi<PsiMethod>() ?.findSuperMethods() ?.any { superMethod -> superMethod.containingClass?.kotlinFqName?.asString() != "java.lang.Object" } == true if (directlyImplementsCloneable && hasCloneableInSuperClasses) { val directCloneableSupertype = element.inheritance.implements.find { it.type.safeAs<JKClassType>()?.classReference?.fqName == "java.lang.Cloneable" } ?: continue element.inheritance.implements -= directCloneableSupertype } else if (!directlyImplementsCloneable && !hasCloneableInSuperClasses) { element.inheritance.implements += JKTypeElement( JKClassType( context.symbolProvider.provideClassSymbol("kotlin.Cloneable"), nullability = NotNull ) ) } } } return recurse(element) } private fun fixToStringMethod(method: JKMethodImpl): Boolean { if (method.name.value != "toString") return false if (method.parameters.isNotEmpty()) return false val type = (method.returnType.type as? JKClassType) ?.takeIf { it.classReference.name == "String" } ?.updateNullability(NotNull) ?: return false method.returnType = JKTypeElement(type, method.returnType::annotationList.detached()) return true } private fun fixCloneMethod(method: JKMethodImpl): Boolean { if (method.name.value != "clone") return false if (method.parameters.isNotEmpty()) return false val type = (method.returnType.type as? JKClassType) ?.takeIf { it.classReference.name == "Object" } ?.updateNullability(NotNull) ?: return false method.returnType = JKTypeElement(type, method.returnType::annotationList.detached()) return true } private fun fixFinalizeMethod(method: JKMethodImpl, containingClass: JKClass): Boolean { if (method.name.value != "finalize") return false if (method.parameters.isNotEmpty()) return false if (method.returnType.type != JKJavaVoidType) return false if (method.hasOtherModifier(OtherModifier.OVERRIDE)) { method.modality = if (containingClass.modality == Modality.OPEN) Modality.OPEN else Modality.FINAL method.otherModifierElements -= method.otherModifierElements.first { it.otherModifier == OtherModifier.OVERRIDE } } return true } }
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/JavaStandardMethodsConversion.kt
3321757908
package com.github.bumblebee.command.statistics.entity import java.time.LocalDate import javax.persistence.* @Entity @Table(name = "BB_STATISTICS") class Statistic { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null var postedDate: LocalDate? = null var messageCount: Int = 0 var chatId: Long = 0 var authorId: Long = 0 var authorName: String? = null @Suppress("unused") constructor() constructor(postedDate: LocalDate, messageCount: Int, chatId: Long, authorId: Long, authorName: String?) { this.postedDate = postedDate this.messageCount = messageCount this.chatId = chatId this.authorId = authorId this.authorName = authorName } override fun toString(): String { return "Statistic(id=$id, postedDate=$postedDate, messageCount=$messageCount, chatId=$chatId, authorId=$authorId, authorName=$authorName)" } }
telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/statistics/entity/Statistic.kt
3332158538
// 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.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.text.StringUtil import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.psi.psiUtil.startOffset class ToOrdinaryStringLiteralIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>( KtStringTemplateExpression::class.java, KotlinBundle.lazyMessage("to.ordinary.string.literal") ), LowPriorityAction { companion object { private val TRIM_INDENT_FUNCTIONS = listOf(FqName("kotlin.text.trimIndent"), FqName("kotlin.text.trimMargin")) } override fun isApplicableTo(element: KtStringTemplateExpression): Boolean { return element.text.startsWith("\"\"\"") } override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) { val startOffset = element.startOffset val endOffset = element.endOffset val currentOffset = editor?.caretModel?.currentCaret?.offset ?: startOffset val entries = element.entries val trimIndentCall = getTrimIndentCall(element, entries) val text = buildString { append("\"") if (trimIndentCall != null) { append(trimIndentCall.stringTemplateText) } else { entries.joinTo(buffer = this, separator = "") { if (it is KtLiteralStringTemplateEntry) it.text.escape() else it.text } } append("\"") } val replaced = (trimIndentCall?.qualifiedExpression ?: element).replaced(KtPsiFactory(element.project).createExpression(text)) val offset = when { currentOffset - startOffset < 2 -> startOffset endOffset - currentOffset < 2 -> replaced.endOffset else -> maxOf(currentOffset - 2, replaced.startOffset) } editor?.caretModel?.moveToOffset(offset) } private fun String.escape(escapeLineSeparators: Boolean = true): String { var text = this text = text.replace("\\", "\\\\") text = text.replace("\"", "\\\"") return if (escapeLineSeparators) text.escapeLineSeparators() else text } private fun String.escapeLineSeparators(): String { return StringUtil.convertLineSeparators(this, "\\n") } private fun getTrimIndentCall( element: KtStringTemplateExpression, entries: Array<KtStringTemplateEntry> ): TrimIndentCall? { val qualifiedExpression = element.getQualifiedExpressionForReceiver()?.takeIf { it.callExpression?.isCalling(TRIM_INDENT_FUNCTIONS) == true } ?: return null val marginPrefix = if (qualifiedExpression.calleeName == "trimMargin") { when (val arg = qualifiedExpression.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression()) { null -> "|" is KtStringTemplateExpression -> arg.entries.singleOrNull()?.takeIf { it is KtLiteralStringTemplateEntry }?.text else -> null } ?: return null } else { null } val stringTemplateText = entries .joinToString(separator = "") { if (it is KtLiteralStringTemplateEntry) it.text.escape(escapeLineSeparators = false) else it.text } .let { if (marginPrefix != null) it.trimMargin(marginPrefix) else it.trimIndent() } .escapeLineSeparators() return TrimIndentCall(qualifiedExpression, stringTemplateText) } private data class TrimIndentCall( val qualifiedExpression: KtQualifiedExpression, val stringTemplateText: String ) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ToOrdinaryStringLiteralIntention.kt
2211592380
package com.gimranov.zandy.app.view import com.gimranov.zandy.app.data.Item import com.gimranov.zandy.app.data.ItemCollection sealed class CardViewModel { } data class ItemViewModel(val item: Item) : CardViewModel() data class CollectionViewModel(val collection: ItemCollection) : CardViewModel()
src/main/java/com/gimranov/zandy/app/view/CardViewModel.kt
218977749
// 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.intentions.loopToCallChain import com.intellij.openapi.util.Key import com.intellij.openapi.util.Ref import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode import org.jetbrains.kotlin.cfg.pseudocode.PseudocodeUtil import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.loopToCallChain.result.* import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.* import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils.isSubtypeOfClass import org.jetbrains.kotlin.resolve.calls.smartcasts.ExplicitSmartCasts import org.jetbrains.kotlin.resolve.calls.smartcasts.ImplicitSmartCasts import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode object MatcherRegistrar { val matchers: Collection<TransformationMatcher> = listOf( FindTransformationMatcher, AddToCollectionTransformation.Matcher, CountTransformation.Matcher, SumTransformationBase.Matcher, MaxOrMinTransformation.Matcher, IntroduceIndexMatcher, FilterTransformationBase.Matcher, MapTransformation.Matcher, FlatMapTransformation.Matcher, ForEachTransformation.Matcher ) } data class MatchResult( val sequenceExpression: KtExpression, val transformationMatch: TransformationMatch.Result, val initializationStatementsToDelete: Collection<KtExpression> ) //TODO: loop which is already over Sequence fun match(loop: KtForExpression, useLazySequence: Boolean, reformat: Boolean): MatchResult? { val (inputVariable, indexVariable, sequenceExpression) = extractLoopData(loop) ?: return null var state = createInitialMatchingState(loop, inputVariable, indexVariable, useLazySequence, reformat) ?: return null // used just as optimization to avoid unnecessary checks val loopContainsEmbeddedBreakOrContinue = loop.containsEmbeddedBreakOrContinue() MatchLoop@ while (true) { state = state.unwrapBlock() val inputVariableUsed = state.inputVariable.hasUsages(state.statements) // drop index variable if it's not used anymore if (state.indexVariable != null && !state.indexVariable!!.hasUsages(state.statements)) { state = state.copy(indexVariable = null) } val restContainsEmbeddedBreakOrContinue = loopContainsEmbeddedBreakOrContinue && state.statements.any { it.containsEmbeddedBreakOrContinue() } MatchersLoop@ for (matcher in MatcherRegistrar.matchers) { if (state.indexVariable != null && !matcher.indexVariableAllowed) continue if (matcher.shouldUseInputVariables && !inputVariableUsed && state.indexVariable == null) continue val match = matcher.match(state) if (match != null) { when (match) { is TransformationMatch.Sequence -> { // check that old input variable is not needed anymore var newState = match.newState if (state.inputVariable != newState.inputVariable && state.inputVariable.hasUsages(newState.statements)) return null if (matcher.shouldUseInputVariables && !state.inputVariable.hasDifferentSetsOfUsages(state.statements, newState.statements) && state.indexVariable?.hasDifferentSetsOfUsages(state.statements, newState.statements) != true ) { // matched part of the loop uses neither input variable nor index variable continue@MatchersLoop } if (state.indexVariable != null && match.sequenceTransformations.any { it.affectsIndex }) { // index variable is still needed but index in the new sequence is different if (state.indexVariable!!.hasUsages(newState.statements)) return null newState = newState.copy(indexVariable = null) } if (restContainsEmbeddedBreakOrContinue && !matcher.embeddedBreakOrContinuePossible) { val countBefore = state.statements.sumOf { it.countEmbeddedBreaksAndContinues() } val countAfter = newState.statements.sumOf { it.countEmbeddedBreaksAndContinues() } if (countAfter != countBefore) continue@MatchersLoop // some embedded break or continue in the matched part } state.previousTransformations += match.sequenceTransformations state = newState continue@MatchLoop } is TransformationMatch.Result -> { if (restContainsEmbeddedBreakOrContinue && !matcher.embeddedBreakOrContinuePossible) continue@MatchersLoop state.previousTransformations += match.sequenceTransformations var result = TransformationMatch.Result(match.resultTransformation, state.previousTransformations) result = mergeTransformations(result, reformat) if (useLazySequence) { val sequenceTransformations = result.sequenceTransformations val resultTransformation = result.resultTransformation if (sequenceTransformations.isEmpty() && !resultTransformation.lazyMakesSense || sequenceTransformations.size == 1 && resultTransformation is AssignToListTransformation ) { return null // it makes no sense to use lazy sequence if no intermediate sequences produced } val asSequence = AsSequenceTransformation(loop) result = TransformationMatch.Result(resultTransformation, listOf(asSequence) + sequenceTransformations) } return MatchResult(sequenceExpression, result, state.initializationStatementsToDelete) .takeIf { checkSmartCastsPreserved(loop, it) } } } } } return null } } fun convertLoop(loop: KtForExpression, matchResult: MatchResult): KtExpression { val resultTransformation = matchResult.transformationMatch.resultTransformation val commentSavingRange = resultTransformation.commentSavingRange val commentSaver = CommentSaver(commentSavingRange) val commentSavingRangeHolder = CommentSavingRangeHolder(commentSavingRange) matchResult.initializationStatementsToDelete.forEach { commentSavingRangeHolder.add(it) } val callChain = matchResult.generateCallChain(loop, true) commentSavingRangeHolder.remove(loop.unwrapIfLabeled()) // loop will be deleted in all cases val result = resultTransformation.convertLoop(callChain, commentSavingRangeHolder) commentSavingRangeHolder.add(result) for (statement in matchResult.initializationStatementsToDelete) { commentSavingRangeHolder.remove(statement) statement.delete() } // we need to adjust indent of the result because in some cases it's made incorrect when moving statement closer to the loop commentSaver.restore(commentSavingRangeHolder.range, forceAdjustIndent = true) return result } data class LoopData( val inputVariable: KtCallableDeclaration, val indexVariable: KtCallableDeclaration?, val sequenceExpression: KtExpression ) private fun extractLoopData(loop: KtForExpression): LoopData? { val loopRange = loop.loopRange ?: return null val destructuringParameter = loop.destructuringDeclaration if (destructuringParameter != null && destructuringParameter.entries.size == 2) { val qualifiedExpression = loopRange as? KtDotQualifiedExpression if (qualifiedExpression != null) { val call = qualifiedExpression.selectorExpression as? KtCallExpression if (call != null && call.calleeExpression.isSimpleName(Name.identifier("withIndex")) && call.valueArguments.isEmpty()) { val receiver = qualifiedExpression.receiverExpression if (!isExpressionTypeSupported(receiver)) return null return LoopData(destructuringParameter.entries[1], destructuringParameter.entries[0], receiver) } } } if (!isExpressionTypeSupported(loopRange)) return null return LoopData(loop.loopParameter ?: return null, null, loopRange) } private fun createInitialMatchingState( loop: KtForExpression, inputVariable: KtCallableDeclaration, indexVariable: KtCallableDeclaration?, useLazySequence: Boolean, reformat: Boolean ): MatchingState? { val pseudocodeProvider: () -> Pseudocode = object : () -> Pseudocode { val pseudocode: Pseudocode by lazy { val declaration = loop.containingDeclarationForPseudocode!! val bindingContext = loop.analyze(BodyResolveMode.FULL) PseudocodeUtil.generatePseudocode(declaration, bindingContext) } override fun invoke() = pseudocode } return MatchingState( outerLoop = loop, innerLoop = loop, statements = listOf(loop.body ?: return null), inputVariable = inputVariable, indexVariable = indexVariable, lazySequence = useLazySequence, pseudocodeProvider = pseudocodeProvider, reformat = reformat ) } private fun isExpressionTypeSupported(expression: KtExpression): Boolean { val type = expression.analyze(BodyResolveMode.PARTIAL).getType(expression) ?: return false val builtIns = expression.builtIns return when { isSubtypeOfClass(type, builtIns.iterable) -> true isSubtypeOfClass(type, builtIns.array) -> true KotlinBuiltIns.isPrimitiveArray(type) -> true // TODO: support Sequence<T> else -> false } } private fun checkSmartCastsPreserved(loop: KtForExpression, matchResult: MatchResult): Boolean { val bindingContext = loop.analyze(BodyResolveMode.FULL) // we declare these keys locally to avoid possible race-condition problems if this code is executed in 2 threads simultaneously val SMARTCAST_KEY = Key<Ref<ExplicitSmartCasts>>("SMARTCAST_KEY") val IMPLICIT_RECEIVER_SMARTCAST_KEY = Key<Ref<ImplicitSmartCasts>>("IMPLICIT_RECEIVER_SMARTCAST") val storedUserData = mutableListOf<Ref<*>>() var smartCastCount = 0 try { loop.forEachDescendantOfType<KtExpression> { expression -> bindingContext[BindingContext.SMARTCAST, expression]?.let { explicitSmartCasts -> Ref(explicitSmartCasts).apply { expression.putCopyableUserData(SMARTCAST_KEY, this) storedUserData += this } smartCastCount++ } bindingContext[BindingContext.IMPLICIT_RECEIVER_SMARTCAST, expression]?.let { implicitSmartCasts -> Ref(implicitSmartCasts).apply { expression.putCopyableUserData(IMPLICIT_RECEIVER_SMARTCAST_KEY, this) storedUserData += this } smartCastCount++ } } if (smartCastCount == 0) return true // optimization val callChain = matchResult.generateCallChain(loop, false) val newBindingContext = callChain.analyzeAsReplacement(loop, bindingContext) var preservedSmartCastCount = 0 callChain.forEachDescendantOfType<KtExpression> { expression -> val smartCastType = expression.getCopyableUserData(SMARTCAST_KEY)?.get() if (smartCastType != null) { if (newBindingContext[BindingContext.SMARTCAST, expression] == smartCastType || newBindingContext.getType(expression) == smartCastType) { preservedSmartCastCount++ } } val implicitReceiverSmartCastType = expression.getCopyableUserData(IMPLICIT_RECEIVER_SMARTCAST_KEY)?.get() if (implicitReceiverSmartCastType != null) { if (newBindingContext[BindingContext.IMPLICIT_RECEIVER_SMARTCAST, expression] == implicitReceiverSmartCastType) { preservedSmartCastCount++ } } } if (preservedSmartCastCount == smartCastCount) return true // not all smart cast expressions has been found in the result or have the same type after conversion, perform more expensive check val expression = matchResult.transformationMatch.resultTransformation.generateExpressionToReplaceLoopAndCheckErrors(callChain) if (!tryChangeAndCheckErrors(loop) { it.replace(expression) }) return false return true } finally { storedUserData.forEach { it.set(null) } if (smartCastCount > 0) { loop.forEachDescendantOfType<KtExpression> { it.putCopyableUserData(SMARTCAST_KEY, null) it.putCopyableUserData(IMPLICIT_RECEIVER_SMARTCAST_KEY, null) } } } } private fun MatchResult.generateCallChain(loop: KtForExpression, reformat: Boolean): KtExpression { var sequenceTransformations = transformationMatch.sequenceTransformations var resultTransformation = transformationMatch.resultTransformation while (true) { val last = sequenceTransformations.lastOrNull() ?: break resultTransformation = resultTransformation.mergeWithPrevious(last, reformat) ?: break sequenceTransformations = sequenceTransformations.dropLast(1) } val chainCallCount = sequenceTransformations.sumOf { it.chainCallCount } + resultTransformation.chainCallCount val lineBreak = if (chainCallCount > 1) "\n" else "" var callChain = sequenceExpression val psiFactory = KtPsiFactory(loop.project) val chainedCallGenerator = object : ChainedCallGenerator { override val receiver: KtExpression get() = callChain override val reformat: Boolean get() = reformat override fun generate(pattern: String, vararg args: Any, receiver: KtExpression, safeCall: Boolean): KtExpression { val dot = if (safeCall) "?." else "." val newPattern = "$" + args.size + lineBreak + dot + pattern return psiFactory.createExpressionByPattern(newPattern, *args, receiver, reformat = reformat) } } for (transformation in sequenceTransformations) { callChain = transformation.generateCode(chainedCallGenerator) } callChain = resultTransformation.generateCode(chainedCallGenerator) return callChain } private fun mergeTransformations(match: TransformationMatch.Result, reformat: Boolean): TransformationMatch.Result { val transformations = (match.sequenceTransformations + match.resultTransformation).toMutableList() var anyChange: Boolean do { anyChange = false for (index in 0 until transformations.lastIndex) { val transformation = transformations[index] as SequenceTransformation val next = transformations[index + 1] val merged = next.mergeWithPrevious(transformation, reformat) ?: continue transformations[index] = merged transformations.removeAt(index + 1) anyChange = true break } } while (anyChange) @Suppress("UNCHECKED_CAST") return TransformationMatch.Result( transformations.last() as ResultTransformation, transformations.dropLast(1) as List<SequenceTransformation> ) } data class IntroduceIndexData( val indexVariable: KtCallableDeclaration, val initializationStatement: KtExpression, val incrementExpression: KtUnaryExpression ) fun matchIndexToIntroduce(loop: KtForExpression, reformat: Boolean): IntroduceIndexData? { if (loop.destructuringDeclaration != null) return null val (inputVariable, indexVariable) = extractLoopData(loop) ?: return null if (indexVariable != null) return null // loop is already with "withIndex" val state = createInitialMatchingState(loop, inputVariable, indexVariable = null, useLazySequence = false, reformat = reformat)?.unwrapBlock() ?: return null val match = IntroduceIndexMatcher.match(state) ?: return null assert(match.sequenceTransformations.isEmpty()) val newState = match.newState val initializationStatement = newState.initializationStatementsToDelete.single() val incrementExpression = newState.incrementExpressions.single() return IntroduceIndexData(newState.indexVariable!!, initializationStatement, incrementExpression) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/matchAndConvert.kt
2398242618
/* * Copyright (C) 2017 littlegnal * * 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.littlegnal.accounting import android.app.Application import com.facebook.flipper.android.AndroidFlipperClient import com.facebook.flipper.android.utils.FlipperUtils import com.facebook.flipper.plugins.inspector.DescriptorMapping import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin import com.facebook.soloader.SoLoader import com.facebook.stetho.Stetho import timber.log.Timber /** * Debug variant [Application],用于配置Debug模式下的工具,如*LeakCanary*,*Stetho*等 */ class DebugApp : App() { override fun onCreate() { super.onCreate() Stetho.initializeWithDefaults(this) Timber.plant(Timber.DebugTree()) if (BuildConfig.DEBUG && FlipperUtils.shouldEnableFlipper(this)) { SoLoader.init(this, false) val client = AndroidFlipperClient.getInstance(this) client.addPlugin(InspectorFlipperPlugin(this, DescriptorMapping.withDefaults())) client.start() } } }
app/src/debug/java/com/littlegnal/accounting/DebugApp.kt
1742487708
package org.stepik.android.view.injection.filter import androidx.lifecycle.ViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap import org.stepik.android.presentation.base.injection.ViewModelKey import org.stepik.android.presentation.filter.FiltersPresenter @Module abstract class FilterModule { @Binds @IntoMap @ViewModelKey(FiltersPresenter::class) internal abstract fun bindFiltersPresenter(filtersPresenter: FiltersPresenter): ViewModel }
app/src/main/java/org/stepik/android/view/injection/filter/FilterModule.kt
657556869