repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
andimage/PCBridge
src/main/kotlin/com/projectcitybuild/features/bans/Sanitizer.kt
1
641
package com.projectcitybuild.features.bans class Sanitizer { // private val ipPortPattern = Regex(":[0-9]+$") private val ipPortPattern = Regex("^.*:[0-9]+$") /** * Sanitizes an IP provided by a Spigot server by * stripping out slashes and the port if it exists * * eg. /127.0.0.1:1234 becomes 127.0.0.1 */ fun sanitizedIP(ip: String): String { var sanitized = ip.replace("/", "") if (sanitized.matches(ipPortPattern)) { val colonIndex = sanitized.indexOf(":") sanitized = sanitized.substring(0 until colonIndex) } return sanitized } }
mit
3981a3116db7956a6a051f33d5244cb6
25.708333
63
0.594384
3.95679
false
false
false
false
exponent/exponent
packages/expo-intent-launcher/android/src/main/java/expo/modules/intentlauncher/IntentLauncherModule.kt
2
4140
package expo.modules.intentlauncher import expo.modules.core.Promise import expo.modules.core.ExportedModule import expo.modules.core.ModuleRegistry import expo.modules.core.interfaces.ExpoMethod import expo.modules.core.ModuleRegistryDelegate import expo.modules.core.arguments.ReadableArguments import expo.modules.core.interfaces.ActivityProvider import expo.modules.core.interfaces.services.UIManager import expo.modules.core.interfaces.ActivityEventListener import expo.modules.core.errors.CurrentActivityNotFoundException import expo.modules.intentlauncher.exceptions.ActivityAlreadyStartedException import android.net.Uri import android.os.Bundle import android.app.Activity import android.content.Intent import android.content.ComponentName import android.content.ActivityNotFoundException import android.content.Context private const val NAME = "ExpoIntentLauncher" private const val REQUEST_CODE = 12 private const val ATTR_ACTION = "action" private const val ATTR_TYPE = "type" private const val ATTR_CATEGORY = "category" private const val ATTR_EXTRA = "extra" private const val ATTR_DATA = "data" private const val ATTR_FLAGS = "flags" private const val ATTR_PACKAGE_NAME = "packageName" private const val ATTR_CLASS_NAME = "className" class IntentLauncherModule( context: Context, private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate() ) : ExportedModule(context), ActivityEventListener { private var pendingPromise: Promise? = null private val uiManager: UIManager by moduleRegistry() private val activityProvider: ActivityProvider by moduleRegistry() private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>() override fun getName() = NAME override fun onCreate(moduleRegistry: ModuleRegistry) { moduleRegistryDelegate.onCreate(moduleRegistry) } @ExpoMethod fun startActivity(activityAction: String, params: ReadableArguments, promise: Promise) { if (pendingPromise != null) { promise.reject(ActivityAlreadyStartedException()) return } val activity = activityProvider.currentActivity if (activity == null) { promise.reject(CurrentActivityNotFoundException()) return } val intent = Intent(activityAction) if (params.containsKey(ATTR_CLASS_NAME)) { intent.component = if (params.containsKey(ATTR_PACKAGE_NAME)) ComponentName(params.getString(ATTR_PACKAGE_NAME), params.getString(ATTR_CLASS_NAME)) else ComponentName(context, params.getString(ATTR_CLASS_NAME)) } // `setData` and `setType` are exclusive, so we need to use `setDateAndType` in that case. if (params.containsKey(ATTR_DATA) && params.containsKey(ATTR_TYPE)) { intent.setDataAndType(Uri.parse(params.getString(ATTR_DATA)), params.getString(ATTR_TYPE)) } else { if (params.containsKey(ATTR_DATA)) { intent.data = Uri.parse(params.getString(ATTR_DATA)) } else if (params.containsKey(ATTR_TYPE)) { intent.type = params.getString(ATTR_TYPE) } } params.getArguments(ATTR_EXTRA)?.let { intent.putExtras(it.toBundle()) } params.getInt(ATTR_FLAGS)?.let { intent.addFlags(it) } params.getString(ATTR_CATEGORY)?.let { intent.addCategory(it) } uiManager.registerActivityEventListener(this) pendingPromise = promise try { activity.startActivityForResult(intent, REQUEST_CODE) } catch (e: ActivityNotFoundException) { promise.reject(e) pendingPromise = null } } //region ActivityEventListener override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, intent: Intent?) { if (requestCode != REQUEST_CODE) return val response = Bundle().apply { putInt("resultCode", resultCode) if (intent != null) { intent.data?.let { putString(ATTR_DATA, it.toString()) } intent.extras?.let { putBundle(ATTR_EXTRA, it) } } } pendingPromise?.resolve(response) pendingPromise = null uiManager.unregisterActivityEventListener(this) } override fun onNewIntent(intent: Intent) = Unit //endregion }
bsd-3-clause
95557eac960dcd3575eba4bfb46706a2
33.5
136
0.748068
4.418356
false
false
false
false
Code-Tome/hexameter
mixite.core/src/commonMain/kotlin/org/hexworks/mixite/core/internal/impl/HexagonImpl.kt
1
3830
package org.hexworks.mixite.core.internal.impl import org.hexworks.cobalt.datatypes.Maybe import org.hexworks.mixite.core.api.* import org.hexworks.mixite.core.api.contract.HexagonDataStorage import org.hexworks.mixite.core.api.contract.SatelliteData import org.hexworks.mixite.core.internal.GridData import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin /** * Default implementation of the [Hexagon] interface. */ class HexagonImpl<T : SatelliteData> internal constructor( private val sharedData: GridData, override val cubeCoordinate: CubeCoordinate, private val hexagonDataStorage: HexagonDataStorage<T>) : Hexagon<T> { override val vertices: List<Double> override val points: List<Point> override val externalBoundingBox: Rectangle override val internalBoundingBox: Rectangle override val center: Point = calculateCenter() override val id: String get() = cubeCoordinate.toAxialKey() override val gridX: Int get() = cubeCoordinate.gridX override val gridY: Int get() = cubeCoordinate.gridY override val gridZ: Int get() = cubeCoordinate.gridZ override val centerX = center.coordinateX override val centerY = center.coordinateY override val satelliteData: Maybe<T> get() = hexagonDataStorage.getSatelliteDataBy(cubeCoordinate) init { this.points = calculatePoints() val x1 = points[3].coordinateX val y1 = points[2].coordinateY val x2 = points[0].coordinateX val y2 = points[5].coordinateY externalBoundingBox = Rectangle(x1, y1, x2 - x1, y2 - y1) internalBoundingBox = Rectangle((center.coordinateX - 1.25 * sharedData.radius / 2), (center.coordinateY - 1.25 * sharedData.radius / 2), (1.25f * sharedData.radius), (1.25f * sharedData.radius)) this.vertices = ArrayList(12) for (point in points) { vertices.add(point.coordinateX) vertices.add(point.coordinateY) } } private fun calculateCenter(): Point { return if (HexagonOrientation.FLAT_TOP.equals(sharedData.orientation)) { Point.fromPosition( cubeCoordinate.gridX * sharedData.hexagonWidth + sharedData.radius, cubeCoordinate.gridZ * sharedData.hexagonHeight + cubeCoordinate.gridX * sharedData.hexagonHeight / 2 + sharedData.hexagonHeight / 2 ) } else { Point.fromPosition( cubeCoordinate.gridX * sharedData.hexagonWidth + cubeCoordinate.gridZ * sharedData.hexagonWidth / 2 + sharedData.hexagonWidth / 2, cubeCoordinate.gridZ * sharedData.hexagonHeight + sharedData.radius ) } } private fun calculatePoints(): List<Point> { val points = ArrayList<Point>(6) for (i in 0..5) { val angle = 2 * PI / 6 * (i + sharedData.orientation.coordinateOffset) val x = center.coordinateX + sharedData.radius * cos(angle) val y = center.coordinateY + sharedData.radius * sin(angle) points.add(Point.fromPosition(x, y)) } return points } override fun setSatelliteData(data: T) { this.hexagonDataStorage.addCoordinate(cubeCoordinate, data) } override fun clearSatelliteData() { this.hexagonDataStorage.clearDataFor(cubeCoordinate) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as HexagonImpl<*> if (cubeCoordinate != other.cubeCoordinate) return false return true } override fun hashCode(): Int { return cubeCoordinate.hashCode() } }
mit
b201fe99da733d09fd3a301d164bbf61
32.893805
152
0.652219
4.438007
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/PictureCollection.kt
1
1423
@file:JvmName("PictureCollectionUtils") package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.common.Entity import com.vimeo.networking2.enums.PictureType import com.vimeo.networking2.enums.asEnum /** * Collection of pictures. * * @param active Whether this picture is the active picture for its parent resource. * @param link The upload URL for the picture. This field appears when you create the picture resource for the first * time. * @param rawType The type of the picture. See [PictureCollection.type]. * @param resourceKey The picture's resource key string. * @param sizes An array containing reference information about all available image files. * @param uri The picture's URI. */ @JsonClass(generateAdapter = true) data class PictureCollection( @Json(name = "active") val active: Boolean? = null, @Json(name = "link") val link: String? = null, @Json(name = "type") val rawType: String? = null, @Json(name = "resource_key") val resourceKey: String? = null, @Json(name = "sizes") val sizes: List<Picture>? = null, @Json(name = "uri") val uri: String? = null ) : Entity { override val identifier: String? = resourceKey } /** * @see PictureCollection.rawType * @see PictureType */ val PictureCollection.type: PictureType get() = rawType.asEnum(PictureType.UNKNOWN)
mit
c17f24349c1de857692f38c9f6e45771
26.365385
116
0.714687
3.83558
false
false
false
false
AndroidX/androidx
compose/runtime/runtime/samples/src/main/java/androidx/compose/runtime/samples/ModelSamples.kt
3
1690
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime.samples import androidx.annotation.Sampled import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.foundation.text.BasicTextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue @OptIn(ExperimentalFoundationApi::class) @Sampled fun stateSample() { @Composable fun LoginScreen() { var username by remember { mutableStateOf("user") } var password by remember { mutableStateOf("pass") } fun login() = Api.login(username, password) BasicTextField( value = username, onValueChange = { username = it } ) BasicTextField( value = password, onValueChange = { password = it } ) Button(onClick = { login() }) { Text("Login") } } }
apache-2.0
6e0bd789ac2e3de127ec3cfd2ab7b50c
31.5
75
0.710651
4.617486
false
false
false
false
Tapchicoma/ultrasonic
ultrasonic/src/main/kotlin/org/moire/ultrasonic/subsonic/SubsonicImageLoaderProxy.kt
1
2381
package org.moire.ultrasonic.subsonic import android.view.View import android.widget.ImageView import org.moire.ultrasonic.R import org.moire.ultrasonic.domain.MusicDirectory import org.moire.ultrasonic.subsonic.loader.image.ImageRequest import org.moire.ultrasonic.subsonic.loader.image.SubsonicImageLoader import org.moire.ultrasonic.util.ImageLoader import org.moire.ultrasonic.util.LegacyImageLoader /** * Temporary proxy between new [SubsonicImageLoader] and [ImageLoader] interface and old * [LegacyImageLoader] implementation. * * Should be removed on [LegacyImageLoader] removal. */ class SubsonicImageLoaderProxy( legacyImageLoader: LegacyImageLoader, private val subsonicImageLoader: SubsonicImageLoader ) : ImageLoader by legacyImageLoader { override fun loadImage( view: View?, entry: MusicDirectory.Entry?, large: Boolean, size: Int, crossFade: Boolean, highQuality: Boolean ) { return loadImage(view, entry, large, size, crossFade, highQuality, -1) } override fun loadImage( view: View?, entry: MusicDirectory.Entry?, large: Boolean, size: Int, crossFade: Boolean, highQuality: Boolean, defaultResourceId: Int ) { val id = entry?.coverArt val unknownImageId = if (defaultResourceId == -1) R.drawable.unknown_album else defaultResourceId if (id != null && view != null && view is ImageView ) { val request = ImageRequest.CoverArt( id, view, placeHolderDrawableRes = unknownImageId, errorDrawableRes = unknownImageId ) subsonicImageLoader.load(request) } } override fun loadAvatarImage( view: View?, username: String?, large: Boolean, size: Int, crossFade: Boolean, highQuality: Boolean ) { if (username != null && view != null && view is ImageView ) { val request = ImageRequest.Avatar( username, view, placeHolderDrawableRes = R.drawable.ic_contact_picture, errorDrawableRes = R.drawable.ic_contact_picture ) subsonicImageLoader.load(request) } } }
gpl-3.0
71a53cb80a2d2f1c53613f834135d570
28.7625
88
0.620328
4.829615
false
false
false
false
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/ticket/activity/PaymentConfirmationActivity.kt
1
2252
package de.tum.`in`.tumcampusapp.component.ui.ticket.activity import android.content.Intent import android.graphics.drawable.Animatable import android.os.Bundle import android.view.MenuItem import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.other.generic.activity.BaseActivity import de.tum.`in`.tumcampusapp.utils.Const import kotlinx.android.synthetic.main.activity_payment_confirmation.* import java.util.* import kotlin.concurrent.schedule class PaymentConfirmationActivity : BaseActivity(R.layout.activity_payment_confirmation) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val eventId = intent.getIntExtra(Const.KEY_EVENT_ID, -1) if (eventId == -1) { finish() return } showTicketButton.setOnClickListener { val intent = Intent(this, ShowTicketActivity::class.java) intent.putExtra(Const.KEY_EVENT_ID, eventId) startActivity(intent); } doneButton.setOnClickListener { val intent = Intent(this, EventsActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) } startActivity(intent) finish() } runCheckmarkAnimation() } private fun runCheckmarkAnimation() { Timer().schedule(200) { runOnUiThread { val animatedCheckmark = imageView.drawable as? Animatable animatedCheckmark?.start() } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { handleOnBackPressed() true } else -> super.onOptionsItemSelected(item) } } override fun onBackPressed() { handleOnBackPressed() } private fun handleOnBackPressed() { // Go back to events and finish this activity to prevent the user from purchasing // another ticket. val intent = Intent(this, EventsActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) finish() } }
gpl-3.0
41433d102c2d42a7e6cee05a9409d6ce
29.432432
90
0.634991
4.791489
false
false
false
false
OpenConference/DroidconBerlin2017
businesslogic/schedule/src/main/java/de/droidcon/berlin2018/schedule/database/ContentValuesExtenstions.kt
1
471
package de.droidcon.berlin2018.schedule.database import android.content.ContentValues import org.threeten.bp.Instant /** * Checks if the value is null and either inserts null into content value or the real value */ fun ContentValues.putOrNull(key: String, value: String?) = if (value == null) putNull(key) else put(key, value) fun ContentValues.putOrNull(key: String, value: Instant?) = if (value == null) putNull(key) else put(key, value.toEpochMilli())
apache-2.0
d712c0af8bca6da183bdfd49816713ad
28.4375
91
0.740977
3.738095
false
false
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/vo/Entity.kt
3
3813
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.vo import androidx.room.compiler.processing.XType import androidx.room.migration.bundle.EntityBundle import androidx.room.compiler.processing.XTypeElement import androidx.room.migration.bundle.TABLE_NAME_PLACEHOLDER /** * A Pojo with a mapping SQLite table. */ open class Entity( element: XTypeElement, override val tableName: String, type: XType, fields: List<Field>, embeddedFields: List<EmbeddedField>, val primaryKey: PrimaryKey, val indices: List<Index>, val foreignKeys: List<ForeignKey>, constructor: Constructor?, val shadowTableName: String? ) : Pojo(element, type, fields, embeddedFields, emptyList(), constructor), HasSchemaIdentity, EntityOrView { open val createTableQuery by lazy { createTableQuery(tableName) } // a string defining the identity of this entity, which can be used for equality checks override fun getIdKey(): String { val identityKey = SchemaIdentityKey() identityKey.append(tableName) identityKey.append(primaryKey) identityKey.appendSorted(fields) identityKey.appendSorted(indices) identityKey.appendSorted(foreignKeys) return identityKey.hash() } private fun createTableQuery(tableName: String): String { val definitions = ( fields.map { val autoIncrement = primaryKey.autoGenerateId && primaryKey.fields.contains(it) it.databaseDefinition(autoIncrement) } + createPrimaryKeyDefinition() + createForeignKeyDefinitions() ).filterNotNull() return "CREATE TABLE IF NOT EXISTS `$tableName` (${definitions.joinToString(", ")})" } private fun createForeignKeyDefinitions(): List<String> { return foreignKeys.map { it.databaseDefinition() } } private fun createPrimaryKeyDefinition(): String? { return if (primaryKey.fields.isEmpty() || primaryKey.autoGenerateId) { null } else { val keys = primaryKey.columnNames.joinToString(", ") { "`$it`" } "PRIMARY KEY($keys)" } } fun shouldBeDeletedAfter(other: Entity): Boolean { return foreignKeys.any { it.parentTable == other.tableName && ( (!it.deferred && it.onDelete == ForeignKeyAction.NO_ACTION) || it.onDelete == ForeignKeyAction.RESTRICT ) } } open fun toBundle(): EntityBundle = EntityBundle( tableName, createTableQuery(TABLE_NAME_PLACEHOLDER), fields.map { it.toBundle() }, primaryKey.toBundle(), indices.map { it.toBundle() }, foreignKeys.map { it.toBundle() } ) fun isUnique(columns: List<String>): Boolean { return if (primaryKey.columnNames.size == columns.size && primaryKey.columnNames.containsAll(columns) ) { true } else { indices.any { index -> index.unique && index.fields.size == columns.size && index.columnNames.containsAll(columns) } } } }
apache-2.0
3e6c768c173632124b68c5fce4b9897a
33.044643
95
0.639916
4.796226
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/profile/media/LocalUserMediaListEntry.kt
2
2738
package me.proxer.app.profile.media import me.proxer.library.entity.ProxerIdItem import me.proxer.library.enums.MediaState import me.proxer.library.enums.Medium import me.proxer.library.enums.UserMediaProgress /** * @author Ruben Gees */ open class LocalUserMediaListEntry( override val id: String, open val name: String, open val episodeAmount: Int, open val medium: Medium, open val state: MediaState, open val commentId: String, open val commentContent: String, open val mediaProgress: UserMediaProgress, open val episode: Int, open val rating: Int ) : ProxerIdItem { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is LocalUserMediaListEntry) return false if (id != other.id) return false if (name != other.name) return false if (episodeAmount != other.episodeAmount) return false if (medium != other.medium) return false if (state != other.state) return false if (commentId != other.commentId) return false if (commentContent != other.commentContent) return false if (mediaProgress != other.mediaProgress) return false if (episode != other.episode) return false if (rating != other.rating) return false return true } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + name.hashCode() result = 31 * result + episodeAmount result = 31 * result + medium.hashCode() result = 31 * result + state.hashCode() result = 31 * result + commentId.hashCode() result = 31 * result + commentContent.hashCode() result = 31 * result + mediaProgress.hashCode() result = 31 * result + episode result = 31 * result + rating return result } override fun toString(): String { return "LocalUserMediaListEntry(id='$id', name='$name', episodeAmount=$episodeAmount, medium=$medium, " + "state=$state, commentId='$commentId', commentContent='$commentContent', mediaProgress=$mediaProgress, " + "episode=$episode, rating=$rating)" } data class Ucp( override val id: String, override val name: String, override val episodeAmount: Int, override val medium: Medium, override val state: MediaState, override val commentId: String, override val commentContent: String, override val mediaProgress: UserMediaProgress, override val episode: Int, override val rating: Int ) : LocalUserMediaListEntry( id, name, episodeAmount, medium, state, commentId, commentContent, mediaProgress, episode, rating ) }
gpl-3.0
fd764cbd66db7eb386233956afa90386
35.026316
118
0.652666
4.664395
false
false
false
false
mirjalal/MickiNet
app/src/main/kotlin/com/talmir/mickinet/screens/main/fragments/DevicesListAdapter.kt
1
3139
package com.talmir.mickinet.screens.main.fragments import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.talmir.mickinet.databinding.DevicesListItemBinding import com.talmir.mickinet.models.DeviceDetails /** * A adapter class that holds items for [RecyclerView]. */ class DevicesListAdapter : ListAdapter<DeviceDetails, DevicesListAdapter.ViewHolder>(DeviceDetailsDiffItemCallback) { /** * Called when recycler view request for the `layout` to show. */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder.from(parent) /** * Called just after the [onCreateViewHolder] invocation to bind * the data to pre-initialized view. */ override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(getItem(position)) /** * A standard view holder class to hold the views ~_~ */ class ViewHolder private constructor(private val binding: DevicesListItemBinding) : RecyclerView.ViewHolder(binding.root) { /** * Binds [deviceItemDetails] object to layout file properties */ fun bind(deviceItemDetails: DeviceDetails) { // sets the properties in the binding class binding.nearbyDeviceName = deviceItemDetails.name binding.nearbyDeviceMAC = deviceItemDetails.macAddress /** * causes the properties updates to execute immediately. * since I'm calling [bind] from [onBindViewHolder] having the bindings execute immediately. * as a practice can prevent the recycler view from having to perform extra calculations * when it figures out how to display the list. */ binding.executePendingBindings() } companion object { /** * Inflate required layout file and pass it to [ViewHolder] as view. */ fun from(parent: ViewGroup): ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val binding = DevicesListItemBinding.inflate(layoutInflater, parent, false) return ViewHolder(binding) } } } /** * Callback to calculate differences between two non-null items in a list. * * Used by [ListAdapter] to calculate the minimum number of changes between * and old list and a new list that's been passed to [submitList]. */ companion object DeviceDetailsDiffItemCallback : DiffUtil.ItemCallback<DeviceDetails>() { // I used referential equality operator - triple equal sign (===) - which returns // true if the object references are the same override fun areItemsTheSame(oldItem: DeviceDetails, newItem: DeviceDetails) = oldItem === newItem override fun areContentsTheSame(oldItem: DeviceDetails, newItem: DeviceDetails) = oldItem.macAddress == newItem.macAddress } }
gpl-3.0
4207182a1ed387555ffebacb93d6b95a
39.24359
117
0.675056
5.154351
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/psi/LuaPsiFile.kt
2
4140
/* * 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.psi import com.intellij.extapi.psi.PsiFileBase import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.util.Key import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.FileViewProvider import com.intellij.psi.PsiElement import com.intellij.psi.util.CachedValue import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.tang.intellij.lua.Constants import com.tang.intellij.lua.comment.psi.api.LuaComment import com.tang.intellij.lua.lang.LuaFileType import com.tang.intellij.lua.lang.LuaLanguage import com.tang.intellij.lua.project.LuaSettings import com.tang.intellij.lua.stubs.LuaFileStub import com.tang.intellij.lua.util.Strings /** * Created by tangzx on 2015/11/15. * Email:[email protected] */ open class LuaPsiFile(fileViewProvider: FileViewProvider) : PsiFileBase(fileViewProvider, LuaLanguage.INSTANCE), LuaTypeGuessable, LuaDeclarationScope { override fun getFileType(): FileType { return LuaFileType.INSTANCE } val uid: String get() { val stub = greenStub if (stub is LuaFileStub) return stub.uid val file = originalFile val contents = file.viewProvider.contents val hashCode = Strings.stringHashCode(contents, 0, contents.length) return "$name[$hashCode]" } val tooLarger: Boolean get() { val fileLimit = LuaSettings.instance.tooLargerFileThreshold * 1024 val fileSize = viewProvider.virtualFile.length return fileSize > fileLimit } override fun setName(name: String): PsiElement { return if (FileUtil.getNameWithoutExtension(name) == name) { super.setName("$name.${LuaFileType.INSTANCE.defaultExtension}") } else super.setName(name) } val moduleName: String? get() { val stub = stub as? LuaFileStub return if (stub != null) stub.module else findCachedModuleName() } /** * Lua language version */ val languageLevel get() = LuaSettings.instance.languageLevel private fun findCachedModuleName(): String? { return CachedValuesManager.getCachedValue(this, KEY_CACHED_MODULE_NAME) { CachedValueProvider.Result.create(findModuleName(), this) } } private fun findModuleName():String? { var child: PsiElement? = firstChild while (child != null) { if (child is LuaComment) { // ---@module name val name = child.moduleName if (name != null) return name } else if (child is LuaStatement) { val comment = child.comment if (comment != null) { val name = comment.moduleName if (name != null) return name } if (child is LuaExprStat) { // module("name") val callExpr = child.expr as? LuaCallExpr val expr = callExpr?.expr if (expr is LuaNameExpr && expr.textMatches(Constants.WORD_MODULE)) { val stringArg = callExpr.firstStringArg if (stringArg != null) return stringArg.text } } } child = child.nextSibling } return null } companion object { private val KEY_CACHED_MODULE_NAME = Key.create<CachedValue<String?>>("lua.file.module.name") } }
apache-2.0
592a3ff3e6ffacd89f84a859e320ae12
35.008696
152
0.649275
4.514722
false
false
false
false
DeKoServidoni/OMFM
omfm/src/main/java/com/dekoservidoni/omfm/utils/OneMoreFabValues.kt
1
4321
package com.dekoservidoni.omfm.utils import android.content.Context import android.graphics.drawable.Drawable import com.google.android.material.floatingactionbutton.FloatingActionButton import androidx.core.content.ContextCompat import android.util.AttributeSet import android.view.MenuInflater import android.widget.PopupMenu import com.dekoservidoni.omfm.R /** * Class responsible to hold all the necessary * parameters to build the menu, like heights, widths, animations * and etc * * @author Andrรฉ Servidoni */ internal data class OneMoreFabValues(private val context: Context) { var options = PopupMenu(context, null).menu var inflater = MenuInflater(context) // flags var closeOnClick = false var rotateMainButton = true var enableMainAsAction = false // initial state (collapsed) var state = OneMoreFabUtils.Direction.COLLAPSED // sizes var maxButtonWidth = 0 var maxButtonHeight = 0 var mainFabSize = -1 var secondaryFabSize = -1 // layout parameters val initialFabRightMargin = 20 val initialFabBottomMargin = 25 val initialFabSpacing = 35 var fabSpacing = 0 val labelSpacing = 20 val labelPadding = 8 val childElevation = 10f // background colors var labelBackgroundColor = -1 var labelTextColor = ContextCompat.getColor(context, R.color.omfm_label_text_black) var expandedBackgroundColor = ContextCompat.getColor(context, android.R.color.transparent) var colorMainButton = ContextCompat.getColor(context, R.color.omfm_default_color) var colorSecondaryButtons = ContextCompat.getColor(context, R.color.omfm_default_color) // drawables var labelBackgroundDrawable = R.drawable.omfm_label_rounded_corners var mainCollapsedDrawable: Drawable? = null var mainExpandedDrawable: Drawable? = null fun initializeValues(attrs: AttributeSet? = null) { val attributes = context.obtainStyledAttributes(attrs, R.styleable.OneMoreFabMenu) if (attributes.hasValue(R.styleable.OneMoreFabMenu_content_options)) { inflater.inflate(attributes.getResourceId(R.styleable.OneMoreFabMenu_content_options, 0), options) } else { throw Exception("OneMoreFabMenu need to have app:content_options with a resource menu!") } val mainButtonColor = attributes.getResourceId(R.styleable.OneMoreFabMenu_color_main_button, R.color.omfm_default_color) this.colorMainButton = ContextCompat.getColor(context, mainButtonColor) val secondaryButtonColor = attributes.getResourceId(R.styleable.OneMoreFabMenu_color_secondary_buttons, R.color.omfm_default_color) this.colorSecondaryButtons = ContextCompat.getColor(context, secondaryButtonColor) val backgroundColor = attributes.getResourceId(R.styleable.OneMoreFabMenu_expanded_background_color, android.R.color.transparent) this.expandedBackgroundColor = ContextCompat.getColor(context, backgroundColor) this.labelBackgroundColor = attributes.getColor(R.styleable.OneMoreFabMenu_label_background_color, -1) this.labelBackgroundDrawable = attributes.getResourceId(R.styleable.OneMoreFabMenu_label_background_drawable, R.drawable.omfm_label_rounded_corners) val labelTextColor = attributes.getResourceId(R.styleable.OneMoreFabMenu_label_text_color, R.color.omfm_label_text_black) this.labelTextColor = ContextCompat.getColor(context, labelTextColor) this.mainFabSize = attributes.getInt(R.styleable.OneMoreFabMenu_size_main_button, FloatingActionButton.SIZE_NORMAL) this.secondaryFabSize = attributes.getInt(R.styleable.OneMoreFabMenu_size_secondary_buttons, FloatingActionButton.SIZE_MINI) this.closeOnClick = attributes.getBoolean(R.styleable.OneMoreFabMenu_close_on_click, false) this.rotateMainButton = attributes.getBoolean(R.styleable.OneMoreFabMenu_rotate_main_button, true) this.enableMainAsAction = attributes.getBoolean(R.styleable.OneMoreFabMenu_enable_main_as_action, false) val mainExpandedDrawable = attributes.getResourceId(R.styleable.OneMoreFabMenu_main_action_drawable, -1) this.mainExpandedDrawable = if(mainExpandedDrawable != -1) ContextCompat.getDrawable(context, mainExpandedDrawable) else null attributes.recycle() } }
apache-2.0
b192913ffd618a60bcc0919793030c14
43.546392
156
0.763426
4.350453
false
false
false
false
Gnar-Team/Gnar-bot
src/main/kotlin/xyz/gnarbot/gnar/commands/music/dj/ForceSkipCommand.kt
1
908
//package xyz.gnarbot.gnar.commands.music.dj // //import xyz.gnarbot.gnar.commands.* //import xyz.gnarbot.gnar.commands.music.MusicCommandExecutor //import xyz.gnarbot.gnar.music.MusicManager // //@Command( // aliases = ["forceskip"], // description = "Skip the current music track forcefully." //) //@BotInfo( // id = 60, // category = Category.MUSIC, // scope = Scope.VOICE, // roleRequirement = "DJ" //) //class ForceSkipCommand : MusicCommandExecutor(false, false) { // override fun execute(context: Context, label: String, args: Array<String>, manager: MusicManager) { // context.send().error("Deprecated, use `_skip` instead.").queue() // return //// manager.scheduler.nextTrack() //// //// context.send().embed("Skip Current Track") { //// desc { "The track was skipped." } //// }.action().queue() // } //}
mit
383f617db882729210a7f98738e4ce02
32.62963
105
0.611233
3.721311
false
false
false
false
inorichi/tachiyomi-extensions
src/all/mango/src/eu/kanade/tachiyomi/extension/all/mango/Mango.kt
1
11890
package eu.kanade.tachiyomi.extension.all.mango import android.app.Application import android.content.SharedPreferences import android.text.InputType import android.widget.Toast import com.github.salomonbrys.kotson.fromJson import com.github.salomonbrys.kotson.get import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonSyntaxException import eu.kanade.tachiyomi.BuildConfig import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.ConfigurableSource import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import info.debatty.java.stringsimilarity.JaroWinkler import info.debatty.java.stringsimilarity.Levenshtein import okhttp3.FormBody import okhttp3.Headers import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import okhttp3.Response import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.io.IOException class Mango : ConfigurableSource, HttpSource() { override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/api/library", headersBuilder().build()) // Our popular manga are just our library of manga override fun popularMangaParse(response: Response): MangasPage { val result = try { gson.fromJson<JsonObject>(response.body!!.string()) } catch (e: JsonSyntaxException) { apiCookies = "" throw Exception("Login Likely Failed. Try Refreshing.") } val mangas = result["titles"].asJsonArray return MangasPage( mangas.asJsonArray.map { SManga.create().apply { url = "/book/" + it["id"].asString title = it["display_name"].asString thumbnail_url = baseUrl + it["cover_url"].asString } }, false ) } override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException("Not used") override fun latestUpdatesParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used") // Default is to just return the whole library for searching override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = popularMangaRequest(1) // Overridden fetch so that we use our overloaded method instead override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return client.newCall(searchMangaRequest(page, query, filters)) .asObservableSuccess() .map { response -> searchMangaParse(response, query) } } // Here the best we can do is just match manga based on their titles private fun searchMangaParse(response: Response, query: String): MangasPage { val queryLower = query.toLowerCase() val mangas = popularMangaParse(response).mangas val exactMatch = mangas.firstOrNull { it.title.toLowerCase() == queryLower } if (exactMatch != null) { return MangasPage(listOf(exactMatch), false) } // Text distance algorithms val textDistance = Levenshtein() val textDistance2 = JaroWinkler() // Take results that potentially start the same val results = mangas.filter { val title = it.title.toLowerCase() val query2 = queryLower.take(7) (title.startsWith(query2, true) || title.contains(query2, true)) }.sortedBy { textDistance.distance(queryLower, it.title.toLowerCase()) } // Take similar results val results2 = mangas.map { Pair(textDistance2.distance(it.title.toLowerCase(), query), it) } .filter { it.first < 0.3 }.sortedBy { it.first }.map { it.second } val combinedResults = results.union(results2) // Finally return the list return MangasPage(combinedResults.toList(), false) } // Stub override fun searchMangaParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used") override fun mangaDetailsRequest(manga: SManga): Request = GET(baseUrl + "/api" + manga.url, headers) // This will just return the same thing as the main library endpoint override fun mangaDetailsParse(response: Response): SManga { val result = try { gson.fromJson<JsonObject>(response.body!!.string()) } catch (e: JsonSyntaxException) { apiCookies = "" throw Exception("Login Likely Failed. Try Refreshing.") } return SManga.create().apply { url = "/book/" + result["id"].asString title = result["display_name"].asString thumbnail_url = baseUrl + result["cover_url"].asString } } override fun chapterListRequest(manga: SManga): Request = GET(baseUrl + "/api" + manga.url, headers) // The chapter url will contain how many pages the chapter contains for our page list endpoint override fun chapterListParse(response: Response): List<SChapter> { val result = try { gson.fromJson<JsonObject>(response.body!!.string()) } catch (e: JsonSyntaxException) { apiCookies = "" throw Exception("Login Likely Failed. Try Refreshing.") } return result["entries"].asJsonArray.mapIndexed { index, obj -> SChapter.create().apply { chapter_number = index + 1F name = "${chapter_number.toInt()} - ${obj["display_name"].asString}" url = "/page/${obj["title_id"].asString}/${obj["id"].asString}/${obj["pages"].asString}/" date_upload = 1000L * obj["mtime"].asLong } }.sortedByDescending { it.date_upload } } // Stub override fun pageListRequest(chapter: SChapter): Request = throw UnsupportedOperationException("Not used") // Overridden fetch so that we use our overloaded method instead override fun fetchPageList(chapter: SChapter): Observable<List<Page>> { val splitUrl = chapter.url.split("/").toMutableList() val numPages = splitUrl.removeAt(splitUrl.size - 2).toInt() val baseUrlChapter = splitUrl.joinToString("/") val pages = mutableListOf<Page>() for (i in 1..numPages) { pages.add( Page( index = i, imageUrl = "$baseUrl/api$baseUrlChapter$i" ) ) } return Observable.just(pages) } // Stub override fun pageListParse(response: Response): List<Page> = throw UnsupportedOperationException("Not used") override fun imageUrlParse(response: Response): String = "" override fun getFilterList(): FilterList = FilterList() override val name = "Mango" override val lang = "en" override val supportsLatest = false override val baseUrl by lazy { getPrefBaseUrl() } private val username by lazy { getPrefUsername() } private val password by lazy { getPrefPassword() } private val gson by lazy { Gson() } private var apiCookies: String = "" override fun headersBuilder(): Headers.Builder = Headers.Builder() .add("User-Agent", "Tachiyomi Mango v${BuildConfig.VERSION_NAME}") private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } override val client: OkHttpClient = network.client.newBuilder() .addInterceptor { authIntercept(it) } .build() private fun authIntercept(chain: Interceptor.Chain): Response { // Check that we have our username and password to login with val request = chain.request() if (username.isEmpty() || password.isEmpty()) { throw IOException("Missing username or password") } // Do the login if we have not gotten the cookies yet if (apiCookies.isEmpty() || !apiCookies.contains("mango-sessid-9000", true)) { doLogin(chain) } // Append the new cookie from the api val authRequest = request.newBuilder() .addHeader("Cookie", apiCookies) .build() return chain.proceed(authRequest) } private fun doLogin(chain: Interceptor.Chain) { // Try to login val formHeaders: Headers = headersBuilder() .add("ContentType", "application/x-www-form-urlencoded") .build() val formBody: RequestBody = FormBody.Builder() .addEncoded("username", username) .addEncoded("password", password) .build() val loginRequest = POST("$baseUrl/login", formHeaders, formBody) val response = chain.proceed(loginRequest) if (response.code != 200 || response.header("Set-Cookie") == null) { throw Exception("Login Failed. Check Address and Credentials") } // Save the cookies from the response apiCookies = response.header("Set-Cookie")!! response.close() } override fun setupPreferenceScreen(screen: androidx.preference.PreferenceScreen) { screen.addPreference(screen.editTextPreference(ADDRESS_TITLE, ADDRESS_DEFAULT, baseUrl)) screen.addPreference(screen.editTextPreference(USERNAME_TITLE, USERNAME_DEFAULT, username)) screen.addPreference(screen.editTextPreference(PASSWORD_TITLE, PASSWORD_DEFAULT, password, true)) } private fun androidx.preference.PreferenceScreen.editTextPreference(title: String, default: String, value: String, isPassword: Boolean = false): androidx.preference.EditTextPreference { return androidx.preference.EditTextPreference(context).apply { key = title this.title = title summary = value this.setDefaultValue(default) dialogTitle = title if (isPassword) { setOnBindEditTextListener { it.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD } } setOnPreferenceChangeListener { _, newValue -> try { val res = preferences.edit().putString(title, newValue as String).commit() Toast.makeText(context, "Restart Tachiyomi to apply new setting.", Toast.LENGTH_LONG).show() apiCookies = "" res } catch (e: Exception) { e.printStackTrace() false } } } } // We strip the last slash since we will append it above private fun getPrefBaseUrl(): String { var path = preferences.getString(ADDRESS_TITLE, ADDRESS_DEFAULT)!! if (path.isNotEmpty() && path.last() == '/') { path = path.substring(0, path.length - 1) } return path } private fun getPrefUsername(): String = preferences.getString(USERNAME_TITLE, USERNAME_DEFAULT)!! private fun getPrefPassword(): String = preferences.getString(PASSWORD_TITLE, PASSWORD_DEFAULT)!! companion object { private const val ADDRESS_TITLE = "Address" private const val ADDRESS_DEFAULT = "" private const val USERNAME_TITLE = "Username" private const val USERNAME_DEFAULT = "" private const val PASSWORD_TITLE = "Password" private const val PASSWORD_DEFAULT = "" } }
apache-2.0
4831a6241e1db02aa196fde7a66d00f0
39.03367
189
0.642557
4.874949
false
false
false
false
gildor/kotlin-coroutines-retrofit
src/test/kotlin/ru/gildor/coroutines/retrofit/util/MockedCall.kt
1
2757
/* * Copyright 2018 Andrey Mischenko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.gildor.coroutines.retrofit.util import okhttp3.MediaType import okhttp3.Protocol import okhttp3.Request import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Callback import retrofit2.HttpException import retrofit2.Response class MockedCall<T>( private val ok: T? = null, private val error: HttpException? = null, private val exception: Throwable? = null, private val autoStart: Boolean = true, private val cancelException: Throwable? = null ) : Call<T> { private var executed: Boolean = false private var cancelled: Boolean = false private lateinit var callback: Callback<T> override fun execute(): Response<T> { throw IllegalStateException("Not mocked") } override fun enqueue(callback: Callback<T>) { this.callback = callback if (autoStart) { start() } } fun start() { markAsExecuted() when { ok != null -> callback.onResponse(this, Response.success(ok)) error != null -> callback.onResponse(this, errorResponse(error.code())) exception != null -> callback.onFailure(this, exception) } } override fun isCanceled() = cancelled override fun isExecuted() = executed override fun clone(): Call<T> = throw IllegalStateException("Not mocked") override fun request(): Request = throw IllegalStateException("Not mocked") private fun markAsExecuted() { if (executed) throw IllegalStateException("Request already executed") executed = true } override fun cancel() { cancelled = true if (cancelException != null) { throw cancelException } } } fun <T> errorResponse( code: Int = 400, message: String = "Error response $code" ): Response<T> { return Response.error(code, ResponseBody.create(MediaType.parse("text/plain"), message)) } fun okHttpResponse(code: Int = 200): okhttp3.Response = okhttp3.Response.Builder() .code(code) .protocol(Protocol.HTTP_1_1) .message("mock response") .request(Request.Builder().url("http://localhost").build()) .build()
apache-2.0
307047bb3a302bcc91373546bf5c540e
28.655914
92
0.67646
4.37619
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/dashboard/mine/bean/NoticeListDataBean.kt
1
701
package com.intfocus.template.dashboard.mine.bean /** * Created by liuruilin on 2017/6/12. */ class NoticeListDataBean { /** * id : 42 * type : 1 * title : 123 * content : 1232 * readed : 0 * time : 2017-06-12 05:47:55 UTC */ var id: Int = 0 var type: Int = 0 var title: String? = null var abstracts: String? = null var see: Boolean = false var time: String? = null constructor(id: Int, type: Int, title: String?, abstracts: String?, see: Boolean, time: String?) { this.id = id this.type = type this.title = title this.abstracts = abstracts this.see = see this.time = time } }
gpl-3.0
2d6bf18d922f920d6f76369e0faf3c43
21.612903
102
0.557775
3.558376
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/LastPickedValuesStore.kt
1
2495
package de.westnordost.streetcomplete.quests import android.content.SharedPreferences import androidx.core.content.edit import java.util.LinkedList import javax.inject.Inject import de.westnordost.streetcomplete.Prefs import de.westnordost.streetcomplete.view.Item /** T must be a string or enum - something that distinctly converts toString. */ class LastPickedValuesStore<T> @Inject constructor(private val prefs: SharedPreferences) { fun add(key: String, newValues: Iterable<T>, max: Int = -1) { val values = get(key) for (value in newValues.map { it.toString() }) { values.remove(value) values.addFirst(value) } val lastValues = if (max != -1) values.subList(0, Math.min(values.size, max)) else values prefs.edit { putString(getKey(key), lastValues.joinToString(",")) } } fun add(key: String, value: T, max: Int = -1) { add(key, listOf(value), max) } fun moveLastPickedToFront(key: String, items: LinkedList<Item<T>>, itemPool: List<Item<T>>) { val lastPickedItems = find(get(key), itemPool) val reverseIt = lastPickedItems.descendingIterator() while (reverseIt.hasNext()) { val lastPicked = reverseIt.next() if (!items.remove(lastPicked)) items.removeLast() items.addFirst(lastPicked) } } fun get(key: String): LinkedList<String> { val result = LinkedList<String>() val values = prefs.getString(getKey(key), null) if(values != null) result.addAll(values.split(",")) return result } private fun getKey(key: String) = Prefs.LAST_PICKED_PREFIX + key private fun find(values: List<String>, itemPool: Iterable<Item<T>>): LinkedList<Item<T>> { val result = LinkedList<Item<T>>() for (value in values) { val item = find(value, itemPool) if(item != null) result.add(item) } return result } private fun find(value: String, itemPool: Iterable<Item<T>>): Item<T>? { for (item in itemPool) { val subItems = item.items // returns only items which are not groups themselves if (subItems != null) { val subItem = find(value, subItems.asIterable()) if (subItem != null) return subItem } else if (value == item.value.toString()) { return item } } return null } }
gpl-3.0
bcd0955dd0201353a900fc53362710dd
33.178082
97
0.608417
4.103618
false
false
false
false
laurentvdl/sqlbuilder
src/main/kotlin/sqlbuilder/pool/DataSourceImpl.kt
1
8543
package sqlbuilder.pool import org.slf4j.LoggerFactory import sqlbuilder.PersistenceException import java.io.PrintWriter import java.lang.reflect.Proxy import java.sql.Connection import java.sql.SQLException import java.util.Arrays import java.util.Collections import java.util.LinkedList import java.util.Timer import java.util.TimerTask import java.util.logging.Logger import javax.sql.DataSource import kotlin.concurrent.thread class DataSourceImpl(private val connectionProvider: ConnectionProvider) : DataSource { constructor(connectionConfigProvider: ConnectionConfigProvider) : this(ConfigurationConnectionProvider(connectionConfigProvider)) { this.identityPlugin = connectionConfigProvider.identityPlugin } private val logger = LoggerFactory.getLogger(javaClass) private val _idleConnections = LinkedList<TransactionalConnection>() private val _activeConnections = LinkedList<TransactionalConnection>() private var timer: Timer? = null private var active = true private var _logWriter: PrintWriter? = null private val lock = Object() var identityPlugin: IdentityPlugin? = null var preparedStatementInterceptor: PreparedStatementInterceptor? = null /** * Set the time a connection can be held without any invocations. After this time, the connection will be rolled back. * <br/>120000 by default * @param zombieTimeout in milliseconds * @return this for chaining */ var zombieTimeout = 300000 /** * Set the time a connection is held in a pool for reuse. * <br/>60000 by default * @param idleTimeout in milliseconds * @return this for chaining */ var idleTimeout = 60000 /** * Set the garbage collection interval of the background thread. * <br/> 10000 by default * <br/> used for testing * @param cleanupDelay in milliseconds * @return this for chaining */ var cleanupDelay = 10000 /** * Active recording of getConnection. Only use this when debugging as the cost is heavy. */ var recordStacks = false fun cleanIdles() { val currentTs = System.currentTimeMillis() synchronized(lock) { val iterator = _idleConnections.iterator() while (iterator.hasNext()) { val connection = iterator.next() if (currentTs - connection.lastModified > idleTimeout) { iterator.remove() connection.close(false) } } } if (_idleConnections.isEmpty() && _activeConnections.isEmpty()) { // not a single connection in use, we can free our Timer thread timer?.cancel() timer = null } } private fun findZombies() { val currentTs = System.currentTimeMillis() synchronized(lock) { val iterator = _activeConnections.iterator() while (iterator.hasNext()) { val connection = iterator.next() val diff = currentTs - connection.lastModified if (diff > zombieTimeout) { iterator.remove() logger.error("removed zombie (after $diff milliseconds) that was invoking ${connection.lastMethod?.declaringClass?.name}.${connection.lastMethod?.name}" + " with arguments ${connection.lastArguments.let { Arrays.toString(it) } ?: "[]"}" + (if (connection.lastCallstack == null) "" else " at ${connection.lastCallstack}")) // once it hits the fan, enable debugging recordStacks = true thread(name = "Close zombie connection $connection") { // if this blocks further down, do not block our connection pool (lock) connection.close(true) } } } } } @Throws(SQLException::class) override fun getConnection(): Connection { return Proxy.newProxyInstance(javaClass.classLoader, arrayOf<Class<*>>(Connection::class.java), obtainConnection()) as Connection } @Throws(SQLException::class) private fun newFysicalConnection(): Connection { return connectionProvider.connection } @Suppress("UNCHECKED_CAST") @Throws(SQLException::class) override fun <T> unwrap(iface: Class<T>): T { if (isWrapperFor(iface)) { return this as T } else { throw SQLException(javaClass.name + " does not implement " + iface.name) } } @Throws(SQLException::class) override fun isWrapperFor(iface: Class<*>): Boolean { return iface == javaClass } private fun obtainConnection(): TransactionalConnection { val connection = synchronized(lock) { if (!active) throw IllegalStateException("datasource is inactive") if (timer == null) { val timer = Timer(connectionProvider.identifier + " cleaner", true) timer.schedule(object : TimerTask() { override fun run() { cleanIdles() findZombies() } }, cleanupDelay.toLong(), cleanupDelay.toLong()) this.timer = timer } var connection: TransactionalConnection if (_idleConnections.isNotEmpty()) { connection = _idleConnections.pop() connection.ping() if (connection.target.isClosed) { connection = createNewConnection() } } else { connection = createNewConnection() } _activeConnections.add(connection) connection } identityPlugin?.let { // set username of actual user for tracing val traceUser = it.traceUsername if (traceUser != null) connection.setClientUser(traceUser) } return connection } private fun createNewConnection(): TransactionalConnection { try { val jdbcConnection = newFysicalConnection() return TransactionalConnection(jdbcConnection, this, preparedStatementInterceptor) } catch (e: SQLException) { throw PersistenceException(e.message, e) } } fun freeConnection(connection: TransactionalConnection) { synchronized(lock) { _activeConnections.remove(connection) if (active) { if (!_idleConnections.contains(connection)) { _idleConnections.add(connection) } } else { try { connection.target.close() } catch (ignore: Exception) { } } } } override fun getConnection(username: String?, password: String?): Connection? { return connection } fun stop() { synchronized(lock) { active = false if (timer != null) { timer!!.cancel() timer = null } for (transactionalConnection in _idleConnections) { try { transactionalConnection.target.close() } catch (ignore: SQLException) { } } _idleConnections.clear() } logger.info("stopped datasource ${connectionProvider.identifier}") } override fun getParentLogger(): Logger? { throw UnsupportedOperationException() } override fun getLogWriter(): PrintWriter? { return _logWriter } override fun setLogWriter(out: PrintWriter?) { _logWriter = out } override fun setLoginTimeout(seconds: Int) { throw UnsupportedOperationException() } override fun getLoginTimeout(): Int { throw UnsupportedOperationException() } override fun toString(): String { return "DataSourceImpl(idleConnections=$_idleConnections, activeConnections=$_activeConnections, active=$active, zombieTimeout=$zombieTimeout, idleTimeout=$idleTimeout, cleanupDelay=$cleanupDelay, recordStacks=$recordStacks)" } val idleConnections: List<TransactionalConnection> get() = Collections.unmodifiableList(_idleConnections) val activeConnections: List<TransactionalConnection> get() = Collections.unmodifiableList(_activeConnections) }
apache-2.0
acee2f884d87c8078d1e99f7b9594476
32.501961
233
0.601896
5.322741
false
false
false
false
robfletcher/orca
orca-qos/src/main/kotlin/com/netflix/spinnaker/orca/qos/ExecutionPromoter.kt
1
3825
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.qos import com.netflix.spectator.api.Registry import com.netflix.spinnaker.kork.annotations.VisibleForTesting import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.notifications.AbstractPollingNotificationAgent import com.netflix.spinnaker.orca.notifications.NotificationClusterLock import com.netflix.spinnaker.orca.pipeline.ExecutionLauncher import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import net.logstash.logback.argument.StructuredArguments.value import org.slf4j.LoggerFactory import org.springframework.beans.factory.BeanInitializationException /** * Marker interface if someone wants to override the default promoter. */ interface ExecutionPromoter class DefaultExecutionPromoter( private val executionLauncher: ExecutionLauncher, private val executionRepository: ExecutionRepository, private val policies: List<PromotionPolicy>, private val registry: Registry, private val pollingIntervalMs: Long, clusterLock: NotificationClusterLock ) : ExecutionPromoter, AbstractPollingNotificationAgent(clusterLock) { private val log = LoggerFactory.getLogger(ExecutionPromoter::class.java) private val elapsedTimeId = registry.createId("qos.promoter.elapsedTime") private val promotedId = registry.createId("qos.promoter.executionsPromoted") init { if (policies.isEmpty()) { throw NoPromotionPolicies("At least one PromotionPolicy must be defined") } } @VisibleForTesting public override fun tick() { registry.timer(elapsedTimeId).record { executionRepository.retrieveBufferedExecutions() .sortedByDescending { it.buildTime } .let { // TODO rz - This is all temporary mess and isn't meant to live long-term. I'd like to calculate until // result.finalized==true or the end of the list, then be able to pass all contributing source & reason pairs // into a log, with a zipped summary that would be saved into an execution's system notifications. var lastResult: PromotionResult? = null var candidates = it policies.forEach { policy -> val result = policy.apply(candidates) if (result.finalized) { return@let result } candidates = result.candidates lastResult = result } lastResult ?: PromotionResult( candidates = candidates, finalized = true, reason = "No promotion policy resulted in an action" ) } .also { result -> result.candidates.forEach { log.info("Promoting execution {} for work: {}", value("executionId", it.id), result.reason) executionRepository.updateStatus(it.type, it.id, NOT_STARTED) executionLauncher.start(it) } registry.counter(promotedId).increment(result.candidates.size.toLong()) } } } private class NoPromotionPolicies(message: String) : BeanInitializationException(message) override fun getPollingInterval() = pollingIntervalMs override fun getNotificationType(): String = this.javaClass.simpleName }
apache-2.0
36e6708886e4937c2c837d9714f127c5
39.691489
119
0.725229
4.745658
false
false
false
false
jiaminglu/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/ForLoopsLowering.kt
1
26954
/* * Copyright 2010-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 org.jetbrains.kotlin.backend.konan.lower import org.jetbrains.kotlin.backend.common.FileLoweringPass import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder import org.jetbrains.kotlin.backend.common.lower.createIrBuilder import org.jetbrains.kotlin.backend.common.lower.irIfThen import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrVariable import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.* import org.jetbrains.kotlin.ir.symbols.IrClassSymbol import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol import org.jetbrains.kotlin.ir.symbols.IrVariableSymbol import org.jetbrains.kotlin.ir.visitors.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.SimpleType import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.types.typeUtil.replaceArgumentsWithStarProjections import org.jetbrains.kotlin.util.OperatorNameConventions /** This lowering pass optimizes range-based for loops. */ internal class ForLoopsLowering(val context: Context) : FileLoweringPass { override fun lower(irFile: IrFile) { val transformer = ForLoopsTransformer(context) // Lower loops irFile.transformChildrenVoid(transformer) // Update references in break/continue. irFile.transformChildrenVoid(object: IrElementTransformerVoid() { override fun visitBreakContinue(jump: IrBreakContinue): IrExpression { transformer.oldLoopToNewLoop[jump.loop]?.let { jump.loop = it } return jump } }) } } private class ForLoopsTransformer(val context: Context) : IrElementTransformerVoidWithContext() { private val symbols = context.ir.symbols private val iteratorToLoopInfo = mutableMapOf<IrVariableSymbol, ForLoopInfo>() internal val oldLoopToNewLoop = mutableMapOf<IrLoop, IrLoop>() private val iteratorType = symbols.iterator.descriptor.defaultType.replaceArgumentsWithStarProjections() private val scopeOwnerSymbol get() = currentScope!!.scope.scopeOwnerSymbol private val progressionElementClasses: Set<IrClassSymbol> = mutableSetOf(symbols.char).apply { addAll(symbols.integerClasses) } private val progressionElementClassesTypes: Set<SimpleType> = mutableSetOf<SimpleType>().apply { progressionElementClasses.mapTo(this) { it.descriptor.defaultType } } //region Symbols for progression building functions ================================================================ private fun getProgressionBuildingMethods(name: String): Set<IrFunctionSymbol> = getMethodsForProgressionElements(name) { it.valueParameters.size == 1 && it.valueParameters[0].type in progressionElementClassesTypes } private fun getProgressionBuildingExtensions(name: String, pkg: FqName): Set<IrFunctionSymbol> = getExtensionsForProgressionElements(name, pkg) { it.extensionReceiverParameter?.type in progressionElementClassesTypes && it.valueParameters.size == 1 && it.valueParameters[0].type in progressionElementClassesTypes } private fun getMethodsForProgressionElements(name: String, filter: (SimpleFunctionDescriptor) -> Boolean): Set<IrFunctionSymbol> = mutableSetOf<IrFunctionSymbol>().apply { progressionElementClasses.flatMapTo(this) { receiver -> receiver.descriptor.unsubstitutedMemberScope .getContributedFunctions(Name.identifier(name), NoLookupLocation.FROM_BACKEND) .filter(filter).map { symbols.symbolTable.referenceFunction(it) } } } private fun getExtensionsForProgressionElements(name: String, pkg: FqName, filter: (SimpleFunctionDescriptor) -> Boolean): Set<IrFunctionSymbol> = mutableSetOf<IrFunctionSymbol>().apply { progressionElementClasses.flatMapTo(this) { receiver -> context.builtIns.builtInsModule.getPackage(pkg).memberScope .getContributedFunctions(Name.identifier(name), NoLookupLocation.FROM_BACKEND) .filter(filter).map { symbols.symbolTable.referenceFunction(it) } } } private val rangeToSymbols by lazy { getProgressionBuildingMethods("rangeTo") } private val untilSymbols by lazy { getProgressionBuildingExtensions("until", FqName("kotlin.ranges")) } private val downToSymbols by lazy { getProgressionBuildingExtensions("downTo", FqName("kotlin.ranges")) } private val stepSymbols by lazy { getExtensionsForProgressionElements("step", FqName("kotlin.ranges")) { it.extensionReceiverParameter?.type in symbols.progressionClassesTypes && it.valueParameters.size == 1 && (KotlinBuiltIns.isLong(it.valueParameters[0].type) || KotlinBuiltIns.isInt(it.valueParameters[0].type)) } } //endregion //region Util methods ============================================================================================== private fun IrExpression.castIfNecessary(progressionType: ProgressionType, castToChar: Boolean = true): IrExpression { assert(type in progressionElementClassesTypes) if (type == progressionType.elementType || (!castToChar && KotlinBuiltIns.isChar(progressionType.elementType))) { return this } return IrCallImpl(startOffset, endOffset, symbols.getFunction(progressionType.numberCastFunctionName, type)) .apply { dispatchReceiver = this@castIfNecessary } } private fun IrExpression.unaryMinus(): IrExpression = IrCallImpl(startOffset, endOffset, symbols.getUnaryOperator(OperatorNameConventions.UNARY_MINUS, type)).apply { dispatchReceiver = this@unaryMinus } private fun ProgressionInfo.defaultStep(startOffset: Int, endOffset: Int): IrExpression = progressionType.elementType.let { type -> val step = if (increasing) 1 else -1 when { KotlinBuiltIns.isInt(type) || KotlinBuiltIns.isChar(type) -> IrConstImpl.int(startOffset, endOffset, context.builtIns.intType, step) KotlinBuiltIns.isLong(type) -> IrConstImpl.long(startOffset, endOffset, context.builtIns.longType, step.toLong()) else -> throw IllegalArgumentException() } } private fun IrConst<*>.isOne() = when (kind) { IrConstKind.Long -> value as Long == 1L IrConstKind.Int -> value as Int == 1 else -> false } // Used only by the assert. private fun stepHasRightType(step: IrExpression, progressionType: ProgressionType) = ((progressionType.isCharProgression() || progressionType.isIntProgression()) && KotlinBuiltIns.isInt(step.type)) || (progressionType.isLongProgression() && KotlinBuiltIns.isLong(step.type)) private fun irCheckProgressionStep(progressionType: ProgressionType, step: IrExpression): Pair<IrExpression, Boolean> { if (step is IrConst<*> && ((step.kind == IrConstKind.Long && step.value as Long > 0) || (step.kind == IrConstKind.Int && step.value as Int > 0))) { return step to !step.isOne() } // The frontend checks if the step has a right type (Long for LongProgression and Int for {Int/Char}Progression) // so there is no need to cast it. assert(stepHasRightType(step, progressionType)) val symbol = symbols.checkProgressionStep[step.type] ?: throw IllegalArgumentException("Unknown progression element type: ${step.type}") return IrCallImpl(step.startOffset, step.endOffset, symbol).apply { putValueArgument(0, step) } to true } private fun irGetProgressionLast(progressionType: ProgressionType, first: IrVariableSymbol, lastExpression: IrExpression, step: IrVariableSymbol): IrExpression { val symbol = symbols.getProgressionLast[progressionType.elementType] ?: throw IllegalArgumentException("Unknown progression element type: ${lastExpression.type}") val startOffset = lastExpression.startOffset val endOffset = lastExpression.endOffset return IrCallImpl(startOffset, lastExpression.endOffset, symbol).apply { putValueArgument(0, IrGetValueImpl(startOffset, endOffset, first)) putValueArgument(1, lastExpression.castIfNecessary(progressionType)) putValueArgument(2, IrGetValueImpl(startOffset, endOffset, step)) } } //endregion //region Util classes ============================================================================================== // TODO: Replace with a cast when such support is added in the boxing lowering. private data class ProgressionType(val elementType: KotlinType, val numberCastFunctionName: Name) { fun isIntProgression() = KotlinBuiltIns.isInt(elementType) fun isLongProgression() = KotlinBuiltIns.isLong(elementType) fun isCharProgression() = KotlinBuiltIns.isChar(elementType) } private data class ProgressionInfo( val progressionType: ProgressionType, val first: IrExpression, val bound: IrExpression, val step: IrExpression? = null, val increasing: Boolean = true, var needLastCalculation: Boolean = false, val closed: Boolean = true) /** Contains information about variables used in the loop. */ private data class ForLoopInfo( val progressionInfo: ProgressionInfo, val inductionVariable: IrVariableSymbol, val bound: IrVariableSymbol, val last: IrVariableSymbol, val step: IrVariableSymbol, var loopVariable: IrVariableSymbol? = null) private inner class ProgressionInfoBuilder : IrElementVisitor<ProgressionInfo?, Nothing?> { val INT_PROGRESSION = ProgressionType(context.builtIns.intType, Name.identifier("toInt")) val LONG_PROGRESSION = ProgressionType(context.builtIns.longType, Name.identifier("toLong")) val CHAR_PROGRESSION = ProgressionType(context.builtIns.charType, Name.identifier("toChar")) private fun buildRangeTo(expression: IrCall, progressionType: ProgressionType) = ProgressionInfo(progressionType, expression.dispatchReceiver!!, expression.getValueArgument(0)!!) private fun buildUntil(expression: IrCall, progressionType: ProgressionType): ProgressionInfo = ProgressionInfo(progressionType, expression.extensionReceiver!!, expression.getValueArgument(0)!!, closed = false) private fun buildDownTo(expression: IrCall, progressionType: ProgressionType) = ProgressionInfo(progressionType, expression.extensionReceiver!!, expression.getValueArgument(0)!!, increasing = false) private fun buildStep(expression: IrCall, progressionType: ProgressionType) = expression.extensionReceiver!!.accept(this, null)?.let { val newStep = expression.getValueArgument(0)!! val (newStepCheck, needBoundCalculation) = irCheckProgressionStep(progressionType, newStep) val step = when { it.step == null -> newStepCheck // There were step calls before. Just add our check in the container or create a new one. it.step is IrStatementContainer -> { it.step.statements.add(newStepCheck) it.step } else -> IrCompositeImpl(expression.startOffset, expression.endOffset, newStep.type).apply { statements.add(it.step) statements.add(newStepCheck) } } ProgressionInfo(progressionType, it.first, it.bound, step, it.increasing, needBoundCalculation, it.closed) } override fun visitElement(element: IrElement, data: Nothing?): ProgressionInfo? = null override fun visitCall(expression: IrCall, data: Nothing?): ProgressionInfo? { val type = expression.type val progressionType = when { type.isSubtypeOf(symbols.charProgression.descriptor.defaultType) -> CHAR_PROGRESSION type.isSubtypeOf(symbols.intProgression.descriptor.defaultType) -> INT_PROGRESSION type.isSubtypeOf(symbols.longProgression.descriptor.defaultType) -> LONG_PROGRESSION else -> return null } // TODO: Process constructors and other factory functions. return when (expression.symbol) { in rangeToSymbols -> buildRangeTo(expression, progressionType) in untilSymbols -> buildUntil(expression, progressionType) in downToSymbols -> buildDownTo(expression, progressionType) in stepSymbols -> buildStep(expression, progressionType) else -> null } } } //endregion //region Lowering ================================================================================================== // Lower a loop header. private fun processHeader(variable: IrVariable, initializer: IrCall): IrStatement? { assert(variable.origin == IrDeclarationOrigin.FOR_LOOP_ITERATOR) val symbol = variable.symbol if (!variable.descriptor.type.isSubtypeOf(iteratorType)) { return null } assert(symbol !in iteratorToLoopInfo) val builder = context.createIrBuilder(scopeOwnerSymbol, variable.startOffset, variable.endOffset) // Collect loop info and form the loop header composite. val progressionInfo = initializer.dispatchReceiver?.accept(ProgressionInfoBuilder(), null) ?: return null with(builder) { with(progressionInfo) { val statements = mutableListOf<IrStatement>() /** * For this loop: * `for (i in a() .. b() step c() step d())` * We need to call functions in the following order: a, b, c, d. * So we call b() before step calculations and then call last element calculation function (if required). */ val inductionVariable = scope.createTemporaryVariable(first.castIfNecessary(progressionType), nameHint = "inductionVariable", isMutable = true, origin = IrDeclarationOrigin.FOR_LOOP_IMPLICIT_VARIABLE).also { statements.add(it) } val boundValue = scope.createTemporaryVariable(bound.castIfNecessary(progressionType), nameHint = "bound", origin = IrDeclarationOrigin.FOR_LOOP_IMPLICIT_VARIABLE) .also { statements.add(it) } val stepExpression = (if (increasing) step else step?.unaryMinus()) ?: defaultStep(startOffset, endOffset) val stepValue = scope.createTemporaryVariable(stepExpression, nameHint = "step", origin = IrDeclarationOrigin.FOR_LOOP_IMPLICIT_VARIABLE).also { statements.add(it) } // Calculate the last element of the progression // The last element can be: // boundValue, if step is 1 and the range is closed. // boundValue - 1, if step is 1 and the range is open. // getProgressionLast(inductionVariable, boundValue, step), if step != 1 and the range is closed. // getProgressionLast(inductionVariable, boundValue - 1, step), if step != 1 and the range is open. var lastExpression: IrExpression? = null if (!closed) { val decrementSymbol = symbols.getUnaryOperator(OperatorNameConventions.DEC, boundValue.descriptor.type) lastExpression = irCall(decrementSymbol).apply { dispatchReceiver = irGet(boundValue.symbol) } } if (needLastCalculation) { lastExpression = irGetProgressionLast(progressionType, inductionVariable.symbol, lastExpression ?: irGet(boundValue.symbol), stepValue.symbol) } val lastValue = if (lastExpression != null) { scope.createTemporaryVariable(lastExpression, nameHint = "last", origin = IrDeclarationOrigin.FOR_LOOP_IMPLICIT_VARIABLE).also { statements.add(it) } } else { boundValue } iteratorToLoopInfo[symbol] = ForLoopInfo(progressionInfo, inductionVariable.symbol, boundValue.symbol, lastValue.symbol, stepValue.symbol) return IrCompositeImpl(startOffset, endOffset, context.builtIns.unitType, null, statements) } } } // Lower getting a next induction variable value. private fun processNext(variable: IrVariable, initializer: IrCall): IrExpression? { assert(variable.origin == IrDeclarationOrigin.FOR_LOOP_VARIABLE || variable.origin == IrDeclarationOrigin.FOR_LOOP_IMPLICIT_VARIABLE) val irIteratorAccess = initializer.dispatchReceiver as? IrGetValue ?: throw AssertionError() val forLoopInfo = iteratorToLoopInfo[irIteratorAccess.symbol] ?: return null // If we didn't lower a corresponding header. val builder = context.createIrBuilder(scopeOwnerSymbol, initializer.startOffset, initializer.endOffset) val plusOperator = symbols.getBinaryOperator( OperatorNameConventions.PLUS, forLoopInfo.inductionVariable.descriptor.type, forLoopInfo.step.descriptor.type ) forLoopInfo.loopVariable = variable.symbol with(builder) { variable.initializer = irGet(forLoopInfo.inductionVariable) val increment = irSetVar(forLoopInfo.inductionVariable, irCallOp(plusOperator, irGet(forLoopInfo.inductionVariable), irGet(forLoopInfo.step))) return IrCompositeImpl(variable.startOffset, variable.endOffset, context.irBuiltIns.unit, IrStatementOrigin.FOR_LOOP_NEXT, listOf(variable, increment)) } } private fun DeclarationIrBuilder.buildMinValueCondition(forLoopInfo: ForLoopInfo): IrExpression { // Condition for a corner case: for (i in a until Int.MIN_VALUE) {}. // Check if forLoopInfo.bound > MIN_VALUE. val progressionType = forLoopInfo.progressionInfo.progressionType return irCall(context.irBuiltIns.gt0Symbol).apply { val minConst = when { progressionType.isIntProgression() -> IrConstImpl .int(startOffset,endOffset, context.builtIns.intType, Int.MIN_VALUE) progressionType.isCharProgression() -> IrConstImpl .char(startOffset, endOffset, context.builtIns.charType, 0.toChar()) progressionType.isLongProgression() -> IrConstImpl .long(startOffset, endOffset, context.builtIns.longType, Long.MIN_VALUE) else -> throw IllegalArgumentException("Unknown progression type") } val compareToCall = irCall(symbols.getBinaryOperator(OperatorNameConventions.COMPARE_TO, forLoopInfo.bound.descriptor.type, minConst.type)).apply { dispatchReceiver = irGet(forLoopInfo.bound) putValueArgument(0, minConst) } putValueArgument(0, compareToCall) } } // TODO: Eliminate the loop if we can prove that it will not be executed. private fun DeclarationIrBuilder.buildEmptyCheck(loop: IrLoop, forLoopInfo: ForLoopInfo): IrExpression { val increasing = forLoopInfo.progressionInfo.increasing val comparingBuiltIn = if (increasing) context.irBuiltIns.lteq0Symbol else context.irBuiltIns.gteq0Symbol // Check if inductionVariable <= last. val compareTo = symbols.getBinaryOperator(OperatorNameConventions.COMPARE_TO, forLoopInfo.inductionVariable.descriptor.type, forLoopInfo.last.descriptor.type) val check: IrExpression = irCall(comparingBuiltIn).apply { putValueArgument(0, irCallOp(compareTo, irGet(forLoopInfo.inductionVariable), irGet(forLoopInfo.last))) } // Process closed and open ranges in different manners. return if (forLoopInfo.progressionInfo.closed) { irIfThen(check, loop) // if (inductionVariable <= last) { loop } } else { // Take into account a corner case: for (i in a until Int.MIN_VALUE) {}. // if (inductionVariable <= last && bound > MIN_VALUE) { loop } return irIfThen(check, irIfThen(buildMinValueCondition(forLoopInfo), loop)) } } private fun DeclarationIrBuilder.buildNewCondition(oldCondition: IrExpression): Pair<IrExpression, ForLoopInfo>? { if (oldCondition !is IrCall || oldCondition.origin != IrStatementOrigin.FOR_LOOP_HAS_NEXT) { return null } val irIteratorAccess = oldCondition.dispatchReceiver as? IrGetValue ?: throw AssertionError() // Return null if we didn't lower a corresponding header. val forLoopInfo = iteratorToLoopInfo[irIteratorAccess.symbol] ?: return null assert(forLoopInfo.loopVariable != null) return irCall(context.irBuiltIns.booleanNotSymbol).apply { val eqeqCall = irCall(context.irBuiltIns.eqeqSymbol).apply { putValueArgument(0, irGet(forLoopInfo.loopVariable!!)) putValueArgument(1, irGet(forLoopInfo.last)) } putValueArgument(0, eqeqCall) } to forLoopInfo } /** * This loop * * for (i in first..last step foo) { ... } * * is represented in IR in such a manner: * * val it = (first..last step foo).iterator() * while (it.hasNext()) { * val i = it.next() * ... * } * * We transform it into the following loop: * * var it = first * if (it <= last) { // (it >= last if the progression is decreasing) * do { * val i = it++ * ... * } while (i != last) * } */ // TODO: Lower `for (i in a until b)` to loop with precondition: for (i = a; i < b; a++); override fun visitWhileLoop(loop: IrWhileLoop): IrExpression { if (loop.origin != IrStatementOrigin.FOR_LOOP_INNER_WHILE) { return super.visitWhileLoop(loop) } with(context.createIrBuilder(scopeOwnerSymbol, loop.startOffset, loop.endOffset)) { // Transform accesses to the old iterator (see visitVariable method). Store loopVariable in loopInfo. // Replace not transparent containers with transparent ones (IrComposite) val newBody = loop.body?.transform(this@ForLoopsTransformer, null)?.let { if (it is IrContainerExpression && !it.isTransparentScope) { with(it) { IrCompositeImpl(startOffset, endOffset, type, origin, statements) } } else { it } } val (newCondition, forLoopInfo) = buildNewCondition(loop.condition) ?: return super.visitWhileLoop(loop) val newLoop = IrDoWhileLoopImpl(loop.startOffset, loop.endOffset, loop.type, loop.origin).apply { label = loop.label condition = newCondition body = newBody } oldLoopToNewLoop[loop] = newLoop // Build a check for an empty progression before the loop. return buildEmptyCheck(newLoop, forLoopInfo) } } override fun visitVariable(declaration: IrVariable): IrStatement { val initializer = declaration.initializer if (initializer == null || initializer !is IrCall) { return super.visitVariable(declaration) } val result = when (initializer.origin) { IrStatementOrigin.FOR_LOOP_ITERATOR -> processHeader(declaration, initializer) IrStatementOrigin.FOR_LOOP_NEXT -> processNext(declaration, initializer) else -> null } return result ?: super.visitVariable(declaration) } //endregion }
apache-2.0
fb1297e83db1bd9848b09341a666173e
49.100372
131
0.626363
5.200463
false
false
false
false
spkingr/50-android-kotlin-projects-in-100-days
ProjectAsyncWorks/app/src/main/java/me/liuqingwen/android/projectasyncworks/MainActivity.kt
1
7808
package me.liuqingwen.android.projectasyncworks import android.graphics.Paint import android.net.Uri import android.os.* import android.support.v4.os.EnvironmentCompat import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.Toast import kotlinx.android.synthetic.main.layout_activity_main.* import okhttp3.OkHttpClient import okhttp3.Request import org.jetbrains.anko.toast import java.io.ByteArrayOutputStream import java.io.File import java.io.RandomAccessFile import java.net.HttpURLConnection import java.net.URI import java.net.URL import kotlin.concurrent.thread class MainActivity : AppCompatActivity() { private val client by lazy { OkHttpClient.Builder().build() } private var isRunning = false private val myHandler = MyHandler() private var downloadLink:String? = null private var downloadTask = DownloadTask() private var isDownloadSuccess = false private val buttonClickHandler = { view:View -> if (! this.downloadLink.isNullOrBlank()) { when(view.id) { R.id.buttonStart -> { if (this.downloadTask.isCanceled) { this.downloadTask = DownloadTask() this.downloadTask.execute(this.downloadLink!!) } else if (! this.isDownloadSuccess) { this.downloadTask.execute(this.downloadLink!!) } } R.id.buttonCancel -> { if (! this.isDownloadSuccess) { this.downloadTask.isCanceled = true } } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_activity_main) this.init() } private fun init() { this.labelUrlAddress.paintFlags = Paint.UNDERLINE_TEXT_FLAG or this.labelUrlAddress.paintFlags this.labelFileUrl.paintFlags = Paint.UNDERLINE_TEXT_FLAG or this.labelFileUrl.paintFlags this.buttonGetFileUrl.setOnClickListener { if (! this.isRunning) { this.isRunning = true thread(start = true, isDaemon = true) { val request = Request.Builder().get().url("http://liuqingwen.me/data/get-images-json.php?type=text").build() val response = this.client.newCall(request).execute() if (response.isSuccessful) { val body = response.body()?.string() val message = this.myHandler.obtainMessage() message.what = 101 message.obj = body this.myHandler.sendMessage(message) } response.close() this.isRunning = false } } } this.buttonStart.setOnClickListener(this.buttonClickHandler) this.buttonCancel.setOnClickListener(this.buttonClickHandler) } private fun toggleDownload() { this.downloadLink?.let { this.labelFileUrl.text = it this.buttonStart.isEnabled = true } } inner class MyHandler : Handler() { override fun handleMessage(msg: Message?) { super.handleMessage(msg) if (msg?.what == 101) { [email protected] = msg.obj as? String [email protected]() } } } inner class DownloadTask:AsyncTask<String, Int, DownloadResult>() { var isCanceled = false private var lastDownloadedSize = 0L private var fileName = "download_temp_file.apk" override fun onPreExecute() { super.onPreExecute() [email protected] = 0 [email protected] = View.VISIBLE [email protected] = true } override fun doInBackground(vararg params: String?): DownloadResult { val urlString = params[0]!! val request = Request.Builder().url(urlString).build() val response = [email protected](request).execute() val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path + this.fileName) this.lastDownloadedSize = if (file.exists()) file.length() else file.let { it.createNewFile(); 0L } if (response != null && response.isSuccessful) { val body = response.body() if (body == null) { return DownloadResult.FAILED } else { val totalFileSize = body.contentLength() if (this.lastDownloadedSize >= totalFileSize) { return DownloadResult.SUCCESS } else { val bytes = ByteArray(1024) val stream = body.byteStream() var length = stream.read(bytes) val outputFile = RandomAccessFile(file, "rw") outputFile.seek(this.lastDownloadedSize) while (length != -1) { outputFile.write(bytes, 0, length) this.lastDownloadedSize += length val progress = (this.lastDownloadedSize * 100L / totalFileSize).toInt() this.publishProgress(progress) if (this.isCanceled) { file.delete() return DownloadResult.CANCELED } length = stream.read(bytes) } return DownloadResult.SUCCESS } } } else { return DownloadResult.FAILED } } override fun onProgressUpdate(vararg values: Int?) { super.onProgressUpdate(*values) if([email protected] == View.INVISIBLE) { [email protected] = View.VISIBLE } [email protected] = values[0]!! } override fun onPostExecute(result: DownloadResult) { super.onPostExecute(result) if (result == DownloadResult.SUCCESS) { [email protected] = true [email protected] = View.INVISIBLE [email protected]("Download successfully!") } else if(result == DownloadResult.CANCELED) { [email protected]("Download Canceled!") }else { [email protected]("Download failed!") } } override fun onCancelled() { super.onCancelled() [email protected]("User canceled!") } } } enum class DownloadResult { SUCCESS, CANCELED, FAILED }
mit
a6b1085fdfb905c8be932338c265be96
34.171171
128
0.524334
5.613228
false
false
false
false
da1z/intellij-community
platform/script-debugger/backend/src/debugger/BreakpointBase.kt
9
2344
/* * 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 org.jetbrains.debugger import com.intellij.util.containers.ContainerUtil import org.jetbrains.concurrency.Promise abstract class BreakpointBase<L : Any>(override val target: BreakpointTarget, override var line: Int, override val column: Int, condition: String?, enabled: Boolean) : Breakpoint { val actualLocations: MutableList<L> = ContainerUtil.createLockFreeCopyOnWriteList<L>() /** * Whether the breakpoint data have changed with respect * to the JavaScript VM data */ protected @Volatile var dirty: Boolean = false override val isResolved: Boolean get() = !actualLocations.isEmpty() override var condition: String? = condition set(value) { if (field != value) { field = value dirty = true } } override var enabled: Boolean = enabled set(value) { if (value != field) { field = value dirty = true } } fun setActualLocations(value: List<L>?) { actualLocations.clear() if (!ContainerUtil.isEmpty(value)) { actualLocations.addAll(value!!) } } fun setActualLocation(value: L?) { actualLocations.clear() if (value != null) { actualLocations.add(value) } } abstract fun isVmRegistered(): Boolean override fun hashCode(): Int { var result = line result *= 31 + column result *= 31 + (if (enabled) 1 else 0) if (condition != null) { result *= 31 + condition!!.hashCode() } result *= 31 + target.hashCode() return result } abstract fun flush(breakpointManager: BreakpointManager): Promise<*> }
apache-2.0
85d1231f56d491f4f7cf7116681bd609
27.950617
88
0.634386
4.560311
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/Constants.kt
1
3569
package info.nightscout.androidaps import info.nightscout.androidaps.database.entities.ValueWithUnit import info.nightscout.androidaps.utils.T.Companion.mins /** * Created by mike on 07.06.2016. */ object Constants { const val MGDL = ValueWithUnit.MGDL // This is Nightscout's representation const val MMOL = ValueWithUnit.MMOL const val MMOLL_TO_MGDL = 18.0 // 18.0182; const val MGDL_TO_MMOLL = 1 / MMOLL_TO_MGDL const val defaultDIA = 5.0 const val REALLYHIGHBASALRATE = 1111111.0 const val REALLYHIGHPERCENTBASALRATE = 1111111 const val REALLYHIGHBOLUS = 1111111.0 const val REALLYHIGHCARBS = 1111111 const val REALLYHIGHIOB = 1111111.0 const val notificationID = 556677 // SMS COMMUNICATOR const val remoteBolusMinDistance = 15 * 60 * 1000L // Circadian Percentage Profile const val CPP_MIN_PERCENTAGE = 30 const val CPP_MAX_PERCENTAGE = 250 const val CPP_MIN_TIMESHIFT = -6 const val CPP_MAX_TIMESHIFT = 23 const val MAX_PROFILE_SWITCH_DURATION = (7 * 24 * 60 // [min] ~ 7 days ).toDouble() //DanaR const val dailyLimitWarning = 0.95 // Temp targets const val defaultActivityTTDuration = 90 // min const val defaultActivityTTmgdl = 140.0 const val defaultActivityTTmmol = 8.0 const val defaultEatingSoonTTDuration = 45 // min const val defaultEatingSoonTTmgdl = 90.0 const val defaultEatingSoonTTmmol = 5.0 const val defaultHypoTTDuration = 60 // min const val defaultHypoTTmgdl = 160.0 const val defaultHypoTTmmol = 8.0 const val MIN_TT_MGDL = 72.0 const val MAX_TT_MGDL = 180.0 const val MIN_TT_MMOL = 4.0 const val MAX_TT_MMOL = 10.0 //NSClientInternal const val MAX_LOG_LINES = 30 //Screen: Threshold for width/height to go into small width/height layout const val SMALL_WIDTH = 320 const val SMALL_HEIGHT = 480 //Autosens const val DEVIATION_TO_BE_EQUAL = 2.0 const val DEFAULT_MAX_ABSORPTION_TIME = 6.0 // Pump const val PUMP_MAX_CONNECTION_TIME_IN_SECONDS = 120 - 1 const val MIN_WATCHDOG_INTERVAL_IN_SECONDS = 12 * 60 //SMS Communicator val SMS_CONFIRM_TIMEOUT = mins(5L).msecs() //Storage [MB] const val MINIMUM_FREE_SPACE: Long = 200 // Overview const val LOWMARK = 76.0 const val HIGHMARK = 180.0 // STATISTICS const val STATS_TARGET_LOW_MMOL = 3.9 const val STATS_TARGET_HIGH_MMOL = 7.8 const val STATS_RANGE_VERY_LOW_MMOL = 3.1 const val STATS_RANGE_LOW_MMOL = 3.9 const val STATS_RANGE_HIGH_NIGHT_MMOL = 8.3 const val STATS_RANGE_HIGH_MMOL = 10.0 const val STATS_RANGE_VERY_HIGH_MMOL = 13.9 // Local profile const val LOCAL_PROFILE = "LocalProfile" // Local Alerts const val DEFAULT_PUMP_UNREACHABLE_THRESHOLD_MINUTES = 30 const val DEFAULT_MISSED_BG_READINGS_THRESHOLD_MINUTES = 30 // One Time Password /** * Size of generated key for TOTP Authenticator token, in bits * rfc6238 suggest at least 160 for SHA1 based TOTP, but it ts too weak * with 512 generated QRCode to provision authenticator is too detailed * 256 is chosen as both secure enough and small enough for easy-scannable QRCode */ const val OTP_GENERATED_KEY_LENGTH_BITS = 256 /** * How many old TOTP tokens still accept. * Each token is 30s valid, but copying and SMS transmission of it can take additional seconds, * so we add leeway to still accept given amount of older tokens */ const val OTP_ACCEPT_OLD_TOKENS_COUNT = 1 }
agpl-3.0
0b4b605d36b9af5c8376572889e14735
32.364486
99
0.689829
3.594159
false
false
false
false
exponentjs/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/screens/ScreenContainer.kt
2
14522
package versioned.host.exp.exponent.modules.api.screens import android.content.Context import android.content.ContextWrapper import android.view.View import android.view.ViewGroup import android.view.ViewParent import android.view.inputmethod.InputMethodManager import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction import com.facebook.react.ReactRootView import com.facebook.react.bridge.ReactContext import com.facebook.react.modules.core.ChoreographerCompat import com.facebook.react.modules.core.ReactChoreographer import versioned.host.exp.exponent.modules.api.screens.Screen.ActivityState open class ScreenContainer<T : ScreenFragment>(context: Context?) : ViewGroup(context) { @JvmField protected val mScreenFragments = ArrayList<T>() @JvmField protected var mFragmentManager: FragmentManager? = null private var mIsAttached = false private var mNeedUpdate = false private var mLayoutEnqueued = false private val mLayoutCallback: ChoreographerCompat.FrameCallback = object : ChoreographerCompat.FrameCallback() { override fun doFrame(frameTimeNanos: Long) { mLayoutEnqueued = false measure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) ) layout(left, top, right, bottom) } } private var mParentScreenFragment: ScreenFragment? = null override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { var i = 0 val size = childCount while (i < size) { getChildAt(i).layout(0, 0, width, height) i++ } } override fun removeView(view: View) { // The below block is a workaround for an issue with keyboard handling within fragments. Despite // Android handles input focus on the fragments that leave the screen, the keyboard stays open // in a number of cases. The issue can be best reproduced on Android 5 devices, before some // changes in Android's InputMethodManager have been introduced (specifically around dismissing // the keyboard in onDetachedFromWindow). However, we also noticed the keyboard issue happen // intermittently on recent versions of Android as well. The issue hasn't been previously // noticed as in React Native <= 0.61 there was a logic that'd trigger keyboard dismiss upon a // blur event (the blur even gets dispatched properly, the keyboard just stays open despite // that) โ€“ note the change in RN core here: // https://github.com/facebook/react-native/commit/e9b4928311513d3cbbd9d875827694eab6cfa932 // The workaround is to force-hide keyboard when the screen that has focus is dismissed (we // detect that in removeView as super.removeView causes the input view to un focus while keeping // the keyboard open). if (view === focusedChild) { (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } super.removeView(view) } override fun requestLayout() { super.requestLayout() @Suppress("SENSELESS_COMPARISON") // mLayoutCallback can be null here since this method can be called in init if (!mLayoutEnqueued && mLayoutCallback != null) { mLayoutEnqueued = true // we use NATIVE_ANIMATED_MODULE choreographer queue because it allows us to catch the current // looper loop instead of enqueueing the update in the next loop causing a one frame delay. ReactChoreographer.getInstance() .postFrameCallback( ReactChoreographer.CallbackType.NATIVE_ANIMATED_MODULE, mLayoutCallback ) } } val isNested: Boolean get() = mParentScreenFragment != null fun notifyChildUpdate() { performUpdatesNow() } protected open fun adapt(screen: Screen): T { @Suppress("UNCHECKED_CAST") return ScreenFragment(screen) as T } fun addScreen(screen: Screen, index: Int) { val fragment = adapt(screen) screen.fragment = fragment mScreenFragments.add(index, fragment) screen.container = this onScreenChanged() } open fun removeScreenAt(index: Int) { mScreenFragments[index].screen.container = null mScreenFragments.removeAt(index) onScreenChanged() } open fun removeAllScreens() { for (screenFragment in mScreenFragments) { screenFragment.screen.container = null } mScreenFragments.clear() onScreenChanged() } val screenCount: Int get() = mScreenFragments.size fun getScreenAt(index: Int): Screen { return mScreenFragments[index].screen } open val topScreen: Screen? get() { for (screenFragment in mScreenFragments) { if (getActivityState(screenFragment) === ActivityState.ON_TOP) { return screenFragment.screen } } return null } private fun setFragmentManager(fm: FragmentManager) { mFragmentManager = fm performUpdatesNow() } private fun setupFragmentManager() { var parent: ViewParent = this // We traverse view hierarchy up until we find screen parent or a root view while (!(parent is ReactRootView || parent is Screen) && parent.parent != null ) { parent = parent.parent } // If parent is of type Screen it means we are inside a nested fragment structure. // Otherwise we expect to connect directly with root view and get root fragment manager if (parent is Screen) { val screenFragment = parent.fragment check(screenFragment != null) { "Parent Screen does not have its Fragment attached" } mParentScreenFragment = screenFragment screenFragment.registerChildScreenContainer(this) setFragmentManager(screenFragment.childFragmentManager) return } // we expect top level view to be of type ReactRootView, this isn't really necessary but in // order to find root view we test if parent is null. This could potentially happen also when // the view is detached from the hierarchy and that test would not correctly indicate the root // view. So in order to make sure we indeed reached the root we test if it is of a correct type. // This allows us to provide a more descriptive error message for the aforementioned case. check(parent is ReactRootView) { "ScreenContainer is not attached under ReactRootView" } // ReactRootView is expected to be initialized with the main React Activity as a context but // in case of Expo the activity is wrapped in ContextWrapper and we need to unwrap it var context = parent.context while (context !is FragmentActivity && context is ContextWrapper) { context = context.baseContext } check(context is FragmentActivity) { "In order to use RNScreens components your app's activity need to extend ReactFragmentActivity or ReactCompatActivity" } setFragmentManager(context.supportFragmentManager) } protected fun createTransaction(): FragmentTransaction { val fragmentManager = requireNotNull(mFragmentManager, { "mFragmentManager is null when creating transaction" }) val transaction = fragmentManager.beginTransaction() transaction.setReorderingAllowed(true) return transaction } private fun attachScreen(transaction: FragmentTransaction, screenFragment: ScreenFragment) { transaction.add(id, screenFragment) } private fun detachScreen(transaction: FragmentTransaction, screenFragment: ScreenFragment) { transaction.remove(screenFragment) } private fun getActivityState(screenFragment: ScreenFragment): ActivityState? { return screenFragment.screen.activityState } open fun hasScreen(screenFragment: ScreenFragment?): Boolean { return mScreenFragments.contains(screenFragment) } override fun onAttachedToWindow() { super.onAttachedToWindow() mIsAttached = true setupFragmentManager() } /** Removes fragments from fragment manager that are attached to this container */ private fun removeMyFragments(fragmentManager: FragmentManager) { val transaction = fragmentManager.beginTransaction() var hasFragments = false for (fragment in fragmentManager.fragments) { if (fragment is ScreenFragment && fragment.screen.container === this ) { transaction.remove(fragment) hasFragments = true } } if (hasFragments) { transaction.commitNowAllowingStateLoss() } } override fun onDetachedFromWindow() { // if there are pending transactions and this view is about to get detached we need to perform // them here as otherwise fragment manager will crash because it won't be able to find container // view. We also need to make sure all the fragments attached to the given container are removed // from fragment manager as in some cases fragment manager may be reused and in such case it'd // attempt to reattach previously registered fragments that are not removed mFragmentManager?.let { if (!it.isDestroyed) { removeMyFragments(it) it.executePendingTransactions() } } mParentScreenFragment?.unregisterChildScreenContainer(this) mParentScreenFragment = null super.onDetachedFromWindow() mIsAttached = false // When fragment container view is detached we force all its children to be removed. // It is because children screens are controlled by their fragments, which can often have a // delayed lifecycle (due to transitions). As a result due to ongoing transitions the fragment // may choose not to remove the view despite the parent container being completely detached // from the view hierarchy until the transition is over. In such a case when the container gets // re-attached while the transition is ongoing, the child view would still be there and we'd // attempt to re-attach it to with a misconfigured fragment. This would result in a crash. To // avoid it we clear all the children here as we attach all the child fragments when the // container is reattached anyways. We don't use `removeAllViews` since it does not check if the // children are not already detached, which may lead to calling `onDetachedFromWindow` on them // twice. // We also get the size earlier, because we will be removing child views in `for` loop. val size = childCount for (i in size - 1 downTo 0) { removeViewAt(i) } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) var i = 0 val size = childCount while (i < size) { getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec) i++ } } private fun onScreenChanged() { // we perform update in `onBeforeLayout` of `ScreensShadowNode` by adding an UIBlock // which is called after updating children of the ScreenContainer. // We do it there because `onUpdate` logic requires all changes of children to be already // made in order to provide proper animation for fragment transition for ScreenStack // and this in turn makes nested ScreenContainers detach too early and disappear // before transition if also not dispatched after children updates. // The exception to this rule is `updateImmediately` which is triggered by actions // not connected to React view hierarchy changes, but rather internal events mNeedUpdate = true (context as? ReactContext)?.runOnUiQueueThread { // We schedule the update here because LayoutAnimations of `react-native-reanimated` // sometimes attach/detach screens after the layout block of `ScreensShadowNode` has // already run, and we want to update the container then too. In the other cases, // this code will do nothing since it will run after the UIBlock when `mNeedUpdate` // will already be false. performUpdates() } } protected fun performUpdatesNow() { // we want to update immediately when the fragment manager is set or native back button // dismiss is dispatched or Screen's activityState changes since it is not connected to React // view hierarchy changes and will not trigger `onBeforeLayout` method of `ScreensShadowNode` mNeedUpdate = true performUpdates() } fun performUpdates() { if (!mNeedUpdate || !mIsAttached || mFragmentManager == null || mFragmentManager?.isDestroyed == true) { return } mNeedUpdate = false onUpdate() notifyContainerUpdate() } open fun onUpdate() { createTransaction().let { // detach screens that are no longer active val orphaned: MutableSet<Fragment> = HashSet(requireNotNull(mFragmentManager, { "mFragmentManager is null when performing update in ScreenContainer" }).fragments) for (screenFragment in mScreenFragments) { if (getActivityState(screenFragment) === ActivityState.INACTIVE && screenFragment.isAdded ) { detachScreen(it, screenFragment) } orphaned.remove(screenFragment) } if (orphaned.isNotEmpty()) { val orphanedAry = orphaned.toTypedArray() for (fragment in orphanedAry) { if (fragment is ScreenFragment) { if (fragment.screen.container == null) { detachScreen(it, fragment) } } } } // if there is an "onTop" screen it means the transition has ended val transitioning = topScreen == null // attach newly activated screens var addedBefore = false val pendingFront: ArrayList<T> = ArrayList() for (screenFragment in mScreenFragments) { val activityState = getActivityState(screenFragment) if (activityState !== ActivityState.INACTIVE && !screenFragment.isAdded) { addedBefore = true attachScreen(it, screenFragment) } else if (activityState !== ActivityState.INACTIVE && addedBefore) { // we detach the screen and then reattach it later to make it appear on front detachScreen(it, screenFragment) pendingFront.add(screenFragment) } screenFragment.screen.setTransitioning(transitioning) } for (screenFragment in pendingFront) { attachScreen(it, screenFragment) } it.commitNowAllowingStateLoss() } } protected open fun notifyContainerUpdate() { topScreen?.fragment?.onContainerUpdate() } }
bsd-3-clause
04b162b8808fa5cbad86dcd89e7e8791
39.672269
168
0.718939
4.798414
false
false
false
false
square/wire
wire-library/wire-grpc-server-generator/src/test/golden/singleMethodService.kt
1
7914
package com.foo.bar import com.google.protobuf.DescriptorProtos import com.google.protobuf.Descriptors import io.grpc.BindableService import io.grpc.CallOptions import io.grpc.Channel import io.grpc.MethodDescriptor import io.grpc.ServerServiceDefinition import io.grpc.ServiceDescriptor import io.grpc.ServiceDescriptor.newBuilder import io.grpc.stub.AbstractStub import io.grpc.stub.ClientCalls import io.grpc.stub.ClientCalls.blockingUnaryCall import io.grpc.stub.ServerCalls import io.grpc.stub.ServerCalls.asyncUnaryCall import io.grpc.stub.StreamObserver import java.io.InputStream import java.lang.UnsupportedOperationException import java.util.concurrent.ExecutorService import kotlin.Array import kotlin.String import kotlin.Unit import kotlin.collections.Map import kotlin.collections.Set import kotlin.jvm.Volatile public object FooServiceWireGrpc { public val SERVICE_NAME: String = "foo.FooService" @Volatile private var serviceDescriptor: ServiceDescriptor? = null private val descriptorMap: Map<String, DescriptorProtos.FileDescriptorProto> = mapOf( "service.proto" to descriptorFor(arrayOf( "Cg1zZXJ2aWNlLnByb3RvEgNmb28iCQoHUmVxdWVzdCIKCghSZXNwb25zZTJYCgpGb29TZXJ2aWNlEiQK", "BUNhbGwxEgwuZm9vLlJlcXVlc3QaDS5mb28uUmVzcG9uc2USJAoFQ2FsbDISDC5mb28uUmVxdWVzdBoN", "LmZvby5SZXNwb25zZUINCgtjb20uZm9vLmJhcg==", )), ) @Volatile private var getCall1Method: MethodDescriptor<Request, Response>? = null @Volatile private var getCall2Method: MethodDescriptor<Request, Response>? = null private fun descriptorFor(`data`: Array<String>): DescriptorProtos.FileDescriptorProto { val str = data.fold(java.lang.StringBuilder()) { b, s -> b.append(s) }.toString() val bytes = java.util.Base64.getDecoder().decode(str) return DescriptorProtos.FileDescriptorProto.parseFrom(bytes) } private fun fileDescriptor(path: String, visited: Set<String>): Descriptors.FileDescriptor { val proto = descriptorMap[path]!! val deps = proto.dependencyList.filter { !visited.contains(it) }.map { fileDescriptor(it, visited + path) } return Descriptors.FileDescriptor.buildFrom(proto, deps.toTypedArray()) } public fun getServiceDescriptor(): ServiceDescriptor? { var result = serviceDescriptor if (result == null) { synchronized(FooServiceWireGrpc::class) { result = serviceDescriptor if (result == null) { result = newBuilder(SERVICE_NAME) .addMethod(getCall1Method()) .addMethod(getCall2Method()) .setSchemaDescriptor(io.grpc.protobuf.ProtoFileDescriptorSupplier { fileDescriptor("service.proto", emptySet()) }) .build() serviceDescriptor = result } } } return result } public fun getCall1Method(): MethodDescriptor<Request, Response> { var result: MethodDescriptor<Request, Response>? = getCall1Method if (result == null) { synchronized(FooServiceWireGrpc::class) { result = getCall1Method if (result == null) { getCall1Method = MethodDescriptor.newBuilder<Request, Response>() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( MethodDescriptor.generateFullMethodName( "foo.FooService", "Call1" ) ) .setSampledToLocalTracing(true) .setRequestMarshaller(FooServiceImplBase.RequestMarshaller()) .setResponseMarshaller(FooServiceImplBase.ResponseMarshaller()) .build() } } } return getCall1Method!! } public fun getCall2Method(): MethodDescriptor<Request, Response> { var result: MethodDescriptor<Request, Response>? = getCall2Method if (result == null) { synchronized(FooServiceWireGrpc::class) { result = getCall2Method if (result == null) { getCall2Method = MethodDescriptor.newBuilder<Request, Response>() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( MethodDescriptor.generateFullMethodName( "foo.FooService", "Call2" ) ) .setSampledToLocalTracing(true) .setRequestMarshaller(FooServiceImplBase.RequestMarshaller()) .setResponseMarshaller(FooServiceImplBase.ResponseMarshaller()) .build() } } } return getCall2Method!! } public fun newStub(channel: Channel): FooServiceStub = FooServiceStub(channel) public fun newBlockingStub(channel: Channel): FooServiceBlockingStub = FooServiceBlockingStub(channel) public abstract class FooServiceImplBase : BindableService { public open fun Call1(request: Request, response: StreamObserver<Response>): Unit = throw UnsupportedOperationException() public open fun Call2(request: Request, response: StreamObserver<Response>): Unit = throw UnsupportedOperationException() public override fun bindService(): ServerServiceDefinition = ServerServiceDefinition.builder(getServiceDescriptor()).addMethod( getCall1Method(), asyncUnaryCall(this@FooServiceImplBase::Call1) ).addMethod( getCall2Method(), asyncUnaryCall(this@FooServiceImplBase::Call2) ).build() public class RequestMarshaller : MethodDescriptor.Marshaller<Request> { public override fun stream(`value`: Request): InputStream = Request.ADAPTER.encode(value).inputStream() public override fun parse(stream: InputStream): Request = Request.ADAPTER.decode(stream) } public class ResponseMarshaller : MethodDescriptor.Marshaller<Response> { public override fun stream(`value`: Response): InputStream = Response.ADAPTER.encode(value).inputStream() public override fun parse(stream: InputStream): Response = Response.ADAPTER.decode(stream) } } public class FooServiceImplLegacyAdapter( private val streamExecutor: ExecutorService, private val Call1: () -> FooServiceCall1BlockingServer, private val Call2: () -> FooServiceCall2BlockingServer, ) : FooServiceImplBase() { public override fun Call1(request: Request, response: StreamObserver<Response>): Unit { response.onNext(Call1().Call1(request)) response.onCompleted() } public override fun Call2(request: Request, response: StreamObserver<Response>): Unit { response.onNext(Call2().Call2(request)) response.onCompleted() } } public class FooServiceStub : AbstractStub<FooServiceStub> { internal constructor(channel: Channel) : super(channel) internal constructor(channel: Channel, callOptions: CallOptions) : super(channel, callOptions) public override fun build(channel: Channel, callOptions: CallOptions) = FooServiceStub(channel, callOptions) public fun Call1(request: Request, response: StreamObserver<Response>): Unit { ClientCalls.asyncUnaryCall(channel.newCall(getCall1Method(), callOptions), request, response) } public fun Call2(request: Request, response: StreamObserver<Response>): Unit { ClientCalls.asyncUnaryCall(channel.newCall(getCall2Method(), callOptions), request, response) } } public class FooServiceBlockingStub : AbstractStub<FooServiceStub> { internal constructor(channel: Channel) : super(channel) internal constructor(channel: Channel, callOptions: CallOptions) : super(channel, callOptions) public override fun build(channel: Channel, callOptions: CallOptions) = FooServiceStub(channel, callOptions) public fun Call1(request: Request): Response = blockingUnaryCall(channel, getCall1Method(), callOptions, request) public fun Call2(request: Request): Response = blockingUnaryCall(channel, getCall2Method(), callOptions, request) } }
apache-2.0
fc24b67a9e6be0a379aff31e26663d4c
36.507109
99
0.712661
4.761733
false
false
false
false
Tandrial/Advent_of_Code
src/aoc2015/kot/Day01.kt
1
575
package aoc2015.kot import java.io.File object Day01 { fun partOne(input: String): Int = input.fold(0) { total, next -> total + if (next == '(') 1 else -1 } fun partTwo(input: String): Int { var pos = 0 for ((idx, c) in input.withIndex()) { if (pos == -1) return idx when (c) { '(' -> pos++ ')' -> pos-- } } return -1 } } fun main(args: Array<String>) { val input = File("./input/2015/Day01_input.txt").readText() println("Part One = ${Day01.partOne(input)}") println("Part Two = ${Day01.partTwo(input)}") }
mit
23f31ed255fa3f4380db36c2a71e8f8e
21.115385
103
0.551304
3.125
false
false
false
false
PolymerLabs/arcs
java/arcs/core/storage/RawEntityDereferencer.kt
1
3125
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.storage import arcs.core.crdt.CrdtEntity import arcs.core.data.EntityType import arcs.core.data.RawEntity import arcs.core.data.Schema import arcs.core.util.Scheduler import arcs.core.util.TaggedLog import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi /** * [Dereferencer] to use when de-referencing a [RawReference] to an [Entity]. * * [Handle] implementations should inject this into any [RawReference] objects they encounter. * * TODO(jasonwyatt): Use the [Scheduler] here when dereferencing. */ @OptIn(ExperimentalCoroutinesApi::class) class RawEntityDereferencer( private val schema: Schema, private val storageEndpointManager: StorageEndpointManager, private val referenceCheckFun: ((Schema, RawEntity?) -> Unit)? = null ) : Dereferencer<RawEntity> { // TODO(#5551): Consider including a hash of schema.names for easier tracking. private val log = TaggedLog { "RawEntityDereferencer" } override suspend fun dereference(rawReference: RawReference): RawEntity? { log.verbose { "De-referencing $rawReference" } val storageKey = rawReference.referencedStorageKey() val options = StoreOptions( storageKey, EntityType(schema) ) val deferred = CompletableDeferred<RawEntity?>() val store = storageEndpointManager.get<CrdtEntity.Data, CrdtEntity.Operation, CrdtEntity>( options ) { message -> when (message) { is ProxyMessage.ModelUpdate<*, *, *> -> { log.verbose { "modelUpdate Model: ${message.model}" } val model = (message.model as CrdtEntity.Data) .takeIf { it.versionMap.isNotEmpty() } deferred.complete(model?.toRawEntity()) } is ProxyMessage.SyncRequest -> Unit is ProxyMessage.Operations -> Unit } } return try { store.onProxyMessage(ProxyMessage.SyncRequest(null)) // Only return the item if we've actually managed to pull it out of storage, and // that it matches the schema we wanted. val entity = deferred.await()?.takeIf { it matches schema }?.copy(id = rawReference.id) referenceCheckFun?.invoke(schema, entity) entity } finally { store.close() } } } /* internal */ infix fun RawEntity.matches(schema: Schema): Boolean { // Only allow empty to match if the Schema is also empty. // TODO: Is this a correct assumption? if (singletons.isEmpty() && collections.isEmpty()) { return schema.fields.singletons.isEmpty() && schema.fields.collections.isEmpty() } // Return true if any of the RawEntity's fields are part of the Schema. return (singletons.isEmpty() || singletons.keys.any { it in schema.fields.singletons }) && (collections.isEmpty() || collections.keys.any { it in schema.fields.collections }) }
bsd-3-clause
4d9c37ec6e95e9bed08906e966da4f42
33.722222
96
0.70624
4.316298
false
false
false
false
shibafu528/SperMaster
app/src/main/kotlin/info/shibafu528/spermaster/fragment/SimpleAlertDialogFragment.kt
1
3514
package info.shibafu528.spermaster.fragment import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v7.app.AlertDialog /** * Created by shibafu on 14/02/18. */ public class SimpleAlertDialogFragment : DialogFragment(), DialogInterface.OnClickListener { public interface OnDialogChoseListener { public fun onDialogChose(requestCode: Int, extendCode: Long, which: Int) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val args = arguments val builder = AlertDialog.Builder(activity) args.getInt(PARAM_ICON, -1).let { if (it > -1 ) builder.setIcon(it) } args.getString(PARAM_TITLE)?.let { builder.setTitle(it) } args.getString(PARAM_MESSAGE)?.let { builder.setMessage(it) } args.getString(PARAM_POSITIVE)?.let { builder.setPositiveButton(it, this) } args.getString(PARAM_NEUTRAL)?.let { builder.setNeutralButton(it, this) } args.getString(PARAM_NEGATIVE)?.let { builder.setNegativeButton(it, this) } return builder.create() } override fun onClick(dialogInterface: DialogInterface, i: Int) { dismiss() val listener: OnDialogChoseListener? = when { parentFragment is OnDialogChoseListener -> parentFragment as OnDialogChoseListener targetFragment is OnDialogChoseListener -> targetFragment as OnDialogChoseListener activity is OnDialogChoseListener -> activity as OnDialogChoseListener else -> null } arguments?.let { listener?.onDialogChose( it.getInt(PARAM_REQUEST_CODE), it.getLong(PARAM_EXTEND_CODE), i) } } override fun onCancel(dialog: DialogInterface?) { onClick(dialog!!, DialogInterface.BUTTON_NEGATIVE) } companion object { private val PARAM_REQUEST_CODE: String = "requestcode" private val PARAM_EXTEND_CODE: String = "extendcode" private val PARAM_ICON: String = "icon" private val PARAM_TITLE: String = "title" private val PARAM_MESSAGE: String = "message" private val PARAM_POSITIVE: String = "positive" private val PARAM_NEUTRAL: String = "neutral" private val PARAM_NEGATIVE: String = "negative" public fun newInstance(requestCode: Int = 0, extendCode: Long = 0, iconId: Int? = null, title: String? = null, message: String? = null, positive: String? = null, neutral: String? = null, negative: String? = null): SimpleAlertDialogFragment { val fragment = SimpleAlertDialogFragment() val args = Bundle() args.putInt(PARAM_REQUEST_CODE, requestCode) args.putLong(PARAM_EXTEND_CODE, extendCode) iconId?.let { args.putInt(PARAM_ICON, it) } title?.let { args.putString(PARAM_TITLE, it) } message?.let { args.putString(PARAM_MESSAGE, it) } positive?.let { args.putString(PARAM_POSITIVE, it) } neutral?.let { args.putString(PARAM_NEUTRAL, it) } negative?.let { args.putString(PARAM_NEGATIVE, it) } fragment.arguments = args return fragment } } }
mit
2d925443a1e08532a9313a044d9b737e
39.390805
94
0.611838
4.648148
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/util/publicdata/WordPressPublicData.kt
1
1921
package org.wordpress.android.util.publicdata import org.wordpress.android.BuildConfig import org.wordpress.android.util.publicdata.WordPressPublicData.PackageName.Jalapeno import org.wordpress.android.util.publicdata.WordPressPublicData.PackageName.Vanilla import org.wordpress.android.util.publicdata.WordPressPublicData.PackageName.Wasabi import javax.inject.Inject class WordPressPublicData @Inject constructor(private val packageManagerWrapper: PackageManagerWrapper) { private sealed class PackageName(val type: String, val value: String) { object Jalapeno : PackageName("jalapeno", "org.wordpress.android.prealpha") object Vanilla : PackageName("vanilla", "org.wordpress.android") object Wasabi : PackageName("wasabi", "org.wordpress.android.beta") } fun currentPackageId(): String = when (BuildConfig.FLAVOR_buildType) { Jalapeno.type -> Jalapeno.value Vanilla.type -> Vanilla.value Wasabi.type -> Wasabi.value else -> throw IllegalArgumentException("Failed to get Jetpack package ID: build flavor not found.") } fun currentPackageVersion(): String? = packageManagerWrapper.getPackageInfo(currentPackageId())?.versionName fun nonSemanticPackageVersion(): String? { val rawVersion = currentPackageVersion() ?: return null // Clean app semantic versioning and keep ony major-minor version info. E.g 21.2-rc-3 turns to 21.2 val majorMinorRegex = "^(\\d*)(\\.(\\d*))".toRegex() val wordPressVersion = majorMinorRegex.find(rawVersion)?.value // Verify that the resulting version is supported by org.wordpress.android.util.helpers.Version.Version val versionIsSupportedForComparison = wordPressVersion !=null && Regex("[0-9]+(\\.[0-9]+)*").matchEntire(wordPressVersion) != null return if (versionIsSupportedForComparison) wordPressVersion else null } }
gpl-2.0
a8e7c550e13228afd72333080617bf98
47.025
112
0.733472
4.385845
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/JpsProjectLoadingListenerTest.kt
2
4939
// 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.workspaceModel.ide import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.util.Disposer import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.rules.ProjectModelRule import com.intellij.workspaceModel.ide.impl.JpsProjectLoadingManagerImpl import com.intellij.workspaceModel.ide.impl.WorkspaceModelCacheImpl import com.intellij.workspaceModel.ide.impl.jps.serialization.DelayedProjectSynchronizer import com.intellij.workspaceModel.ide.impl.jps.serialization.LoadedProjectData import com.intellij.workspaceModel.ide.impl.jps.serialization.copyAndLoadProject import com.intellij.workspaceModel.storage.EntityStorageSerializer import com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import kotlinx.coroutines.runBlocking import org.apache.commons.lang.RandomStringUtils import org.junit.* import org.junit.Assert.assertTrue import java.io.File class JpsProjectLoadingListenerTest { @Rule @JvmField val projectModel = ProjectModelRule(true) @Rule @JvmField var disposableRule = DisposableRule() private lateinit var virtualFileManager: VirtualFileUrlManager private lateinit var serializer: EntityStorageSerializer @Before fun setUp() { WorkspaceModelCacheImpl.forceEnableCaching(disposableRule.disposable) virtualFileManager = VirtualFileUrlManager.getInstance(projectModel.project) serializer = EntityStorageSerializerImpl(WorkspaceModelCacheImpl.PluginAwareEntityTypesResolver, virtualFileManager) } @After fun tearDown() { WorkspaceModelCacheImpl.testCacheFile = null } @Test fun `test executing delayed task`() { val projectData = prepareProject() var listenerCalled = false ApplicationManager.getApplication().messageBus.connect().subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectOpened(project: Project) { JpsProjectLoadingManager.getInstance(project).jpsProjectLoaded { listenerCalled = true } } }) runBlocking { loadProject(projectData.projectDir) } waitAndAssert(1_000, "Listener isn't called") { listenerCalled } } @Test fun `test listener right after project is loaded`() { val projectData = prepareProject() val project = runBlocking { loadProject(projectData.projectDir) } waitAndAssert(1_000, "Project is not loaded") { (JpsProjectLoadingManager.getInstance(project) as JpsProjectLoadingManagerImpl).isProjectLoaded() } var listenerCalled = false JpsProjectLoadingManager.getInstance(project).jpsProjectLoaded { listenerCalled = true } assertTrue(listenerCalled) } private fun prepareProject(): LoadedProjectData { val projectFile = projectFile("moduleAdded/after") val projectData = copyAndLoadProject(projectFile, virtualFileManager) val storage = projectData.storage val cacheFile = projectData.projectDir.resolve(cacheFileName()) cacheFile.createNewFile() WorkspaceModelCacheImpl.testCacheFile = cacheFile cacheFile.outputStream().use { serializer.serializeCache(it, storage) } return projectData } private suspend fun loadProject(projectDir: File): Project { val project = PlatformTestUtil.loadAndOpenProject(projectDir.toPath(), disposableRule.disposable) Disposer.register(disposableRule.disposable, Disposable { PlatformTestUtil.forceCloseProjectWithoutSaving(project) }) DelayedProjectSynchronizer.backgroundPostStartupProjectLoading(project) return project } companion object { @JvmField @ClassRule val appRule = ApplicationRule() private val testProjectBase = "platform/workspaceModel/jps/tests/testData/serialization/loadingFromCache" private val dirBasedProject = "$testProjectBase/directoryBased" private fun projectFile(path: String): File { return File(PathManagerEx.getCommunityHomePath(), "$dirBasedProject/$path") } private fun cacheFileName(): String { return "test_caching_" + RandomStringUtils.randomAlphabetic(5) + ".data" } private fun waitAndAssert(timeout: Int, message: String, action: () -> Boolean) { val initial = System.currentTimeMillis() while (System.currentTimeMillis() - initial < timeout) { if (action()) return } Assert.fail(message) } } }
apache-2.0
41b902d81f40f0dc33aed9f21ce07c5f
34.539568
126
0.77708
5.050102
false
true
false
false
GunoH/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/RepositoryManagementPanelProvider.kt
2
2430
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow import com.intellij.dependencytoolwindow.DependenciesToolWindowTabProvider import com.intellij.dependencytoolwindow.DependenciesToolWindowTabProvider.Subscription import com.intellij.openapi.components.Service import com.intellij.openapi.components.Service.Level import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.ui.content.Content import com.intellij.ui.content.ContentFactory import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.repositories.RepositoryManagementPanel import com.jetbrains.packagesearch.intellij.plugin.util.FeatureFlags import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.stateIn class RepositoryManagementPanelProvider : DependenciesToolWindowTabProvider { companion object : DependenciesToolWindowTabProvider.Id @Service(Level.PROJECT) private class PanelContainer(private val project: Project) { val packageManagementPanel by lazy { RepositoryManagementPanel(project).initialize(ContentFactory.getInstance()) } val isAvailableFlow = combine( project.packageSearchProjectService.projectModulesStateFlow.map { it.isNotEmpty() }, FeatureFlags.showRepositoriesTabFlow ) { isServiceReady, isFlagEnabled -> isServiceReady && isFlagEnabled } .stateIn(project.lifecycleScope, SharingStarted.Eagerly, false) } override val id: DependenciesToolWindowTabProvider.Id = Companion override fun provideTab(project: Project): Content = project.service<PanelContainer>().packageManagementPanel override fun isAvailable(project: Project) = project.service<PanelContainer>().isAvailableFlow.value override fun addIsAvailableChangesListener(project: Project, callback: (Boolean) -> Unit): Subscription { val job = project.service<PanelContainer>() .isAvailableFlow .onEach { callback(it) } .launchIn(project.lifecycleScope) return Subscription { job.cancel() } } }
apache-2.0
b7d9d4bb3d0caf46485b3c43a79f63ed
45.75
122
0.791358
5.083682
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SecondEntityWithPIdImpl.kt
2
6326
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.MutableEntityStorage import com.intellij.workspaceModel.storage.SymbolicEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId 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 org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class SecondEntityWithPIdImpl(val dataSource: SecondEntityWithPIdData) : SecondEntityWithPId, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val data: String get() = dataSource.data override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: SecondEntityWithPIdData?) : ModifiableWorkspaceEntityBase<SecondEntityWithPId, SecondEntityWithPIdData>( result), SecondEntityWithPId.Builder { constructor() : this(SecondEntityWithPIdData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity SecondEntityWithPId is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // 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 (!getEntityData().isDataInitialized()) { error("Field SecondEntityWithPId#data 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 SecondEntityWithPId if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.data != dataSource.data) this.data = dataSource.data if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData(true).data = value changedProperty.add("data") } override fun getEntityClass(): Class<SecondEntityWithPId> = SecondEntityWithPId::class.java } } class SecondEntityWithPIdData : WorkspaceEntityData.WithCalculableSymbolicId<SecondEntityWithPId>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<SecondEntityWithPId> { val modifiable = SecondEntityWithPIdImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): SecondEntityWithPId { return getCached(snapshot) { val entity = SecondEntityWithPIdImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun symbolicId(): SymbolicEntityId<*> { return SecondPId(data) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return SecondEntityWithPId::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return SecondEntityWithPId(data, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as SecondEntityWithPIdData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as SecondEntityWithPIdData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
56d1a50e455ff447fdca1e9892d49490
31.111675
128
0.732532
5.284879
false
false
false
false
googlecodelabs/android-dagger-to-hilt
app/src/main/java/com/example/android/dagger/registration/enterdetails/EnterDetailsViewModel.kt
1
1639
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.dagger.registration.enterdetails import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import javax.inject.Inject private const val MAX_LENGTH = 5 /** * EnterDetailsViewModel is the ViewModel that [EnterDetailsFragment] uses to * obtain to validate user's input data. */ class EnterDetailsViewModel @Inject constructor() { private val _enterDetailsState = MutableLiveData<EnterDetailsViewState>() val enterDetailsState: LiveData<EnterDetailsViewState> get() = _enterDetailsState fun validateInput(username: String, password: String) { when { username.length < MAX_LENGTH -> _enterDetailsState.value = EnterDetailsError("Username has to be longer than 4 characters") password.length < MAX_LENGTH -> _enterDetailsState.value = EnterDetailsError("Password has to be longer than 4 characters") else -> _enterDetailsState.value = EnterDetailsSuccess } } }
apache-2.0
da8b96204000ad13279feca3804a9491
36.25
80
0.724222
4.527624
false
false
false
false
walleth/kethereum
crypto_impl_spongycastle/src/main/kotlin/org/kethereum/crypto/impl/ec/EllipticCurveUtils.kt
2
1443
package org.kethereum.crypto.impl.ec import org.kethereum.crypto.api.ec.ECDSASignature private val HALF_CURVE_ORDER = CURVE_PARAMS.n.shiftRight(1) /** * Returns true if the S component is "low", that means it is below * [HALF_CURVE_ORDER]. See * [BIP62](https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#Low_S_values_in_signatures). */ private fun ECDSASignature.isCanonical() = s <= HALF_CURVE_ORDER /** * Will automatically adjust the S component to be less than or equal to half the curve * order, if necessary. This is required because for every signature (r,s) the signature * (r, -s (mod N)) is a valid signature of the same message. However, we dislike the * ability to modify the bits of a Bitcoin transaction after it's been signed, as that * violates various assumed invariants. Thus in future only one of those forms will be * considered legal and the other will be banned. */ fun ECDSASignature.canonicalise() = if (isCanonical()) { this } else { // The order of the curve is the number of valid points that exist on that curve. // If S is in the upper half of the number of valid points, then bring it back to // the lower half. Otherwise, imagine that // N = 10 // s = 8, so (-8 % 10 == 2) thus both (r, 8) and (r, 2) are valid solutions. // 10 - 8 == 2, giving us always the latter solution, which is canonical. ECDSASignature(r, CURVE_PARAMS.n.subtract(s)) }
mit
01ad077968285b6ced6fb496261812fd
45.548387
102
0.705475
3.545455
false
false
false
false
jk1/intellij-community
python/src/com/jetbrains/python/inspections/PyNamedTupleInspection.kt
4
4057
// 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.jetbrains.python.inspections import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import com.jetbrains.python.codeInsight.stdlib.PyNamedTupleTypeProvider import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.PyTargetExpression import java.util.* class PyNamedTupleInspection : PyInspection() { companion object { fun inspectFieldsOrder(cls: PyClass, callback: (PsiElement, String, ProblemHighlightType) -> Unit, filter: (PyTargetExpression) -> Boolean = { true }, hasAssignedValue: (PyTargetExpression) -> Boolean = PyTargetExpression::hasAssignedValue) { val fieldsProcessor = FieldsProcessor(filter, hasAssignedValue) cls.processClassLevelDeclarations(fieldsProcessor) registerErrorOnTargetsAboveBound(fieldsProcessor.lastFieldWithoutDefaultValue, fieldsProcessor.fieldsWithDefaultValue, "Fields with a default value must come after any fields without a default.", callback) } private fun registerErrorOnTargetsAboveBound(bound: PyTargetExpression?, targets: TreeSet<PyTargetExpression>, message: String, callback: (PsiElement, String, ProblemHighlightType) -> Unit) { if (bound != null) { targets .headSet(bound) .forEach { callback(it, message, ProblemHighlightType.GENERIC_ERROR) } } } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, session) private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) { override fun visitPyClass(node: PyClass?) { super.visitPyClass(node) if (node != null && LanguageLevel.forElement(node).isAtLeast(LanguageLevel.PYTHON36) && PyNamedTupleTypeProvider.isTypingNamedTupleDirectInheritor(node, myTypeEvalContext)) { inspectFieldsOrder(node, this::registerProblem) } } } private class FieldsProcessor(private val filter: (PyTargetExpression) -> Boolean, private val hasAssignedValue: (PyTargetExpression) -> Boolean) : PsiScopeProcessor { val lastFieldWithoutDefaultValue: PyTargetExpression? get() = lastFieldWithoutDefaultValueBox.result val fieldsWithDefaultValue: TreeSet<PyTargetExpression> private val lastFieldWithoutDefaultValueBox: MaxBy<PyTargetExpression> init { val offsetComparator = compareBy(PyTargetExpression::getTextOffset) lastFieldWithoutDefaultValueBox = MaxBy(offsetComparator) fieldsWithDefaultValue = TreeSet(offsetComparator) } override fun execute(element: PsiElement, state: ResolveState): Boolean { if (element is PyTargetExpression && filter(element)) { when { hasAssignedValue(element) -> fieldsWithDefaultValue.add(element) else -> lastFieldWithoutDefaultValueBox.apply(element) } } return true } } private class MaxBy<T>(private val comparator: Comparator<T>) { var result: T? = null private set fun apply(t: T) { if (result == null || comparator.compare(result, t) < 0) { result = t } } } }
apache-2.0
a1523ea07cb4ec5c2b7ceb71951806bd
39.178218
140
0.671186
5.431058
false
false
false
false
brianwernick/PlaylistCore
library/src/main/kotlin/com/devbrackets/android/playlistcore/components/mediacontrols/DefaultMediaControlsProvider.kt
1
2896
package com.devbrackets.android.playlistcore.components.mediacontrols import android.content.Context import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import com.devbrackets.android.playlistcore.data.MediaInfo open class DefaultMediaControlsProvider(protected val context: Context) : MediaControlsProvider { protected var enabled = true /** * Sets the volatile information for the remote views and controls. This information is expected to * change frequently. * * @param mediaInfo The information representing the current media item * @param mediaSession The [MediaSessionCompat] to update with the information from [mediaInfo] */ override fun update(mediaInfo: MediaInfo, mediaSession: MediaSessionCompat) { // Updates the available playback controls val playbackStateBuilder = PlaybackStateCompat.Builder() playbackStateBuilder.setActions(getPlaybackOptions(mediaInfo.mediaState)) playbackStateBuilder.setState(getPlaybackState(mediaInfo.mediaState), mediaInfo.playbackPositionMs, 1.0f) mediaSession.setPlaybackState(playbackStateBuilder.build()) if (enabled && !mediaSession.isActive) { mediaSession.isActive = true } } @PlaybackStateCompat.State protected open fun getPlaybackState(mediaState: MediaInfo.MediaState): Int { // NOTE: We should update this to properly include all of the information around playback to // set the stopped, error, etc. states as well return when { mediaState.isLoading -> PlaybackStateCompat.STATE_BUFFERING mediaState.isPlaying -> PlaybackStateCompat.STATE_PLAYING else -> PlaybackStateCompat.STATE_PAUSED } } @Deprecated( "This function is no longer used since it doesn't include the necessary information to correctly determine the state", replaceWith = ReplaceWith("getPlaybackState(mediaState)") ) @PlaybackStateCompat.State protected open fun getPlaybackState(isPlaying: Boolean): Int { return PlaybackStateCompat.STATE_NONE } /** * Determines the available playback commands supported for the current media state * * @param mediaState The current media playback state * @return The available playback options */ @PlaybackStateCompat.Actions protected open fun getPlaybackOptions(mediaState: MediaInfo.MediaState): Long { var availableActions = PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_PLAY_PAUSE if (mediaState.isNextEnabled) { availableActions = availableActions or PlaybackStateCompat.ACTION_SKIP_TO_NEXT } if (mediaState.isPreviousEnabled) { availableActions = availableActions or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS } availableActions = availableActions or PlaybackStateCompat.ACTION_SEEK_TO return availableActions } }
apache-2.0
a4964dfdc7fe58cf2ae1b311211dbd53
38.684932
135
0.775207
5.080702
false
false
false
false
jk1/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/VetoableTransformationSupport.kt
3
3849
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.transformations.impl import com.intellij.codeInsight.AnnotationUtil import com.intellij.psi.CommonClassNames import com.intellij.psi.PsiArrayType import com.intellij.psi.PsiModifier import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.DOCUMENTATION_DELEGATE_FQN import org.jetbrains.plugins.groovy.transformations.AstTransformationSupport import org.jetbrains.plugins.groovy.transformations.TransformationContext private val VETOABLE_FQN = "groovy.beans.Vetoable" private val VCL_FQN = "java.beans.VetoableChangeListener" private val VCS_FQN = "java.beans.VetoableChangeSupport" val ORIGIN_INFO: String = "via @Vetoable" class VetoableTransformationSupport : AstTransformationSupport { override fun applyTransformation(context: TransformationContext) { val clazz = context.codeClass if (!isApplicable(clazz)) return val methods = mutableListOf<GrLightMethodBuilder>() methods += context.memberBuilder.method("addVetoableChangeListener") { returnType = PsiType.VOID addParameter("propertyName", CommonClassNames.JAVA_LANG_STRING) addParameter("listener", VCL_FQN) } methods += context.memberBuilder.method("addVetoableChangeListener") { returnType = PsiType.VOID addParameter("listener", VCL_FQN) } methods += context.memberBuilder.method("removeVetoableChangeListener") { returnType = PsiType.VOID addParameter("propertyName", CommonClassNames.JAVA_LANG_STRING) addParameter("listener", VCL_FQN) } methods += context.memberBuilder.method("removeVetoableChangeListener") { returnType = PsiType.VOID addParameter("listener", VCL_FQN) } methods += context.memberBuilder.method("fireVetoableChange") { returnType = PsiType.VOID addParameter("propertyName", CommonClassNames.JAVA_LANG_STRING) addParameter("oldValue", CommonClassNames.JAVA_LANG_OBJECT) addParameter("newValue", CommonClassNames.JAVA_LANG_OBJECT) } val vclArrayType = PsiArrayType(TypesUtil.createType(VCL_FQN, context.codeClass)) methods += context.memberBuilder.method("getVetoableChangeListeners") { returnType = vclArrayType } methods += context.memberBuilder.method("getVetoableChangeListeners") { returnType = vclArrayType addParameter("propertyName", CommonClassNames.JAVA_LANG_STRING) } for (method in methods) { method.addModifier(PsiModifier.PUBLIC) method.originInfo = ORIGIN_INFO method.putUserData(DOCUMENTATION_DELEGATE_FQN, VCS_FQN) } context.addMethods(methods) } private fun isApplicable(clazz: GrTypeDefinition): Boolean { val annotation = AnnotationUtil.findAnnotation(clazz, true, VETOABLE_FQN) if (annotation != null) return true for (method in clazz.codeFields) { if (AnnotationUtil.findAnnotation(method, true, VETOABLE_FQN) != null) { return true } } return false } }
apache-2.0
34c0794cbcc34a550758598eca5fc09a
36.019231
87
0.752923
4.413991
false
false
false
false
jk1/intellij-community
platform/platform-impl/src/com/intellij/internal/performance/Latenciometer.kt
1
2176
// 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.internal.performance import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actionSystem.LatencyRecorder import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileTypes.FileType /** * @author yole */ class LatencyRecorderImpl : LatencyRecorder { override fun recordLatencyAwareAction(editor: Editor, actionId: String, timestampMs: Long) { (editor as? EditorImpl)?.recordLatencyAwareAction(actionId, timestampMs) } } class LatencyRecord { var totalKeysTyped: Int = 0 var totalLatency: Long = 0L var maxLatency: Long = 0L fun update(latencyInMS: Long) { totalKeysTyped++ totalLatency += latencyInMS if (latencyInMS > maxLatency) { maxLatency = latencyInMS } } val averageLatency: Long get() = totalLatency / totalKeysTyped } class FileTypeLatencyRecord(val fileType: FileType) { val totalLatency: LatencyRecord = LatencyRecord() val actionLatencyRecords: MutableMap<String, LatencyRecord> = mutableMapOf<String, LatencyRecord>() fun update(action: String, latencyInMS: Long) { totalLatency.update(latencyInMS) actionLatencyRecords.getOrPut(action) { LatencyRecord() }.update(latencyInMS) } } val latencyMap: MutableMap<FileType, FileTypeLatencyRecord> = mutableMapOf() fun recordTypingLatency(editor: Editor, action: String, latencyInMS: Long) { val fileType = FileDocumentManager.getInstance().getFile(editor.document)?.fileType ?: return val latencyRecord = latencyMap.getOrPut(fileType) { FileTypeLatencyRecord(fileType) } latencyRecord.update(getActionKey(action), latencyInMS) } fun getActionKey(action: String): String = if (action.length == 1) { when(action[0]) { in 'A'..'Z', in 'a'..'z', in '0'..'9' -> "Letter" ' ' -> "Space" '\n' -> "Enter" else -> action } } else action
apache-2.0
d9ba23dde1eaa5526054b27eb4c571e6
31
140
0.742188
3.920721
false
false
false
false
marius-m/wt4
components/src/main/java/lt/markmerkk/versioner/Changelog.kt
1
3104
package lt.markmerkk.versioner import java.lang.NumberFormatException data class Changelog( val version: Version, val contentAsString: String ) { data class Version( val asString: String, val major: Int = 0, val minor: Int = 0, val patch: Int = 0 ): Comparable<Version> { override fun compareTo(other: Version): Int { return when { major > other.major -> 1 major < other.major -> -1 else -> { when { minor > other.minor -> 1 minor < other.minor -> -1 else -> { when { patch > other.patch -> 1 patch < other.patch -> -1 else -> 0 } } } } } } override fun toString(): String { return "$major.$minor.$patch" } companion object { fun asEmpty(versionAsString: String): Version { return Version(versionAsString, 0, 0, 0) } } } companion object { private val changelogRegex = "Current: (.*)".toRegex() private val versionRegex = "([0-9])\\.*([0-9])?\\.*([0-9])?".toRegex() fun from(changelogAsString: String): Changelog { val changelogMatch = changelogRegex.find(changelogAsString) val changelogGroupAsString = if (changelogMatch != null && changelogMatch.groupValues.size >= 2) { changelogMatch.groupValues[1] } else { "" } return Changelog( version = versionFrom(changelogGroupAsString), contentAsString = changelogAsString ) } fun versionFrom(versionAsString: String): Version { val versionMatch = versionRegex.find(versionAsString) ?: return Version.asEmpty(versionAsString) val versionMajor = versionMatch.groupValues[1].toInt() val versionMinor = extractVersionOrZero(versionMatch.groupValues, 2) val versionPatch = extractVersionOrZero(versionMatch.groupValues, 3) return Version( versionAsString, versionMajor, versionMinor, versionPatch ) } private fun extractVersionOrZero(versionNumbers: List<String>, numberIndex: Int): Int { return if (versionNumbers.size >= 3 && versionNumbers[numberIndex].isNotEmpty()) { try { versionNumbers[numberIndex] .replace("\\.", "") .toInt() } catch (e: NumberFormatException) { 0 } } else { 0 } } } }
apache-2.0
5bf786ba37771cc4b340c85beaddeb0f
31.34375
108
0.459085
5.602888
false
false
false
false
linkedin/LiTr
litr-demo/src/main/java/com/linkedin/android/litr/demo/TranscodeAudioFragment.kt
1
3413
/* * Copyright 2019 LinkedIn Corporation * All Rights Reserved. * * Licensed under the BSD 2-Clause License (the "License"). See License in the project root for * license information. */ package com.linkedin.android.litr.demo import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import com.linkedin.android.litr.MediaTransformer import com.linkedin.android.litr.demo.data.SourceMedia import com.linkedin.android.litr.demo.data.TargetMedia import com.linkedin.android.litr.demo.data.TranscodingConfigPresenter import com.linkedin.android.litr.demo.data.TransformationPresenter import com.linkedin.android.litr.demo.data.TransformationState import com.linkedin.android.litr.demo.data.TrimConfig import com.linkedin.android.litr.demo.databinding.FragmentTranscodeAudioBinding import com.linkedin.android.litr.utils.TransformationUtil import java.io.File class TranscodeAudioFragment : BaseTransformationFragment(), MediaPickerListener { private lateinit var binding: FragmentTranscodeAudioBinding private lateinit var mediaTransformer: MediaTransformer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mediaTransformer = MediaTransformer(context!!.applicationContext) } override fun onDestroy() { super.onDestroy() mediaTransformer.release() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentTranscodeAudioBinding.inflate(inflater, container, false) val sourceMedia = SourceMedia() binding.sourceMedia = sourceMedia binding.sectionPickAudio.buttonPickAudio.setOnClickListener { pickAudio(this@TranscodeAudioFragment) } binding.transformationState = TransformationState() binding.transformationPresenter = TransformationPresenter(context!!, mediaTransformer) binding.tracks.layoutManager = LinearLayoutManager(context) val targetMedia = TargetMedia() val transcodingConfigPresenter = TranscodingConfigPresenter(this, targetMedia) binding.transcodingConfigPresenter = transcodingConfigPresenter binding.targetMedia = targetMedia binding.trimConfig = TrimConfig() return binding.root } override fun onMediaPicked(uri: Uri) { binding.sourceMedia?.let { sourceMedia -> updateSourceMedia(sourceMedia, uri) binding.trimConfig?.let { trimConfig -> updateTrimConfig(trimConfig, sourceMedia) } val targetFile = File(TransformationUtil.getTargetFileDirectory(requireContext().applicationContext), "transcoded_" + TransformationUtil.getDisplayName(context!!, sourceMedia.uri)) binding.targetMedia?.setTargetFile(targetFile) binding.targetMedia?.setTracks(sourceMedia.tracks) binding.transformationState?.setState(TransformationState.STATE_IDLE) binding.transformationState?.setStats(null) binding.tracks.adapter = MediaTrackAdapter( binding.transcodingConfigPresenter!!, sourceMedia, binding.targetMedia!!) binding.tracks.isNestedScrollingEnabled = false } } }
bsd-2-clause
cebeb6761cff6fc9f9ab4170a9b72eaa
40.120482
113
0.745092
4.924964
false
true
false
false
KDE/kdeconnect-android
src/org/kde/kdeconnect/UserInterface/About/AboutFragment.kt
1
4102
/* * SPDX-FileCopyrightText: 2021 Maxim Leshchenko <[email protected]> * * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ package org.kde.kdeconnect.UserInterface.About import android.annotation.SuppressLint import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import org.kde.kdeconnect.UserInterface.List.ListAdapter import org.kde.kdeconnect.UserInterface.MainActivity import org.kde.kdeconnect_tp.R import org.kde.kdeconnect_tp.databinding.FragmentAboutBinding class AboutFragment : Fragment() { private var binding: FragmentAboutBinding? = null private lateinit var aboutData: AboutData private var tapCount = 0 private var firstTapMillis: Long? = null companion object { @JvmStatic fun newInstance(aboutData: AboutData): Fragment { val fragment = AboutFragment() val args = Bundle(1) args.putParcelable("ABOUT_DATA", aboutData) fragment.arguments = args return fragment } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { if (activity != null) { (requireActivity() as MainActivity).supportActionBar?.setTitle(R.string.about) } aboutData = requireArguments().getParcelable("ABOUT_DATA")!! binding = FragmentAboutBinding.inflate(inflater, container, false) updateData() return binding!!.root } @SuppressLint("SetTextI18n") fun updateData() { // Update general info binding!!.appName.text = aboutData.name binding!!.appDescription.text = this.context?.let { aboutData.getDescriptionString(it) } + if (aboutData.copyrightStatement == null) "" else "\n\n" + aboutData.copyrightStatement binding!!.appIcon.setImageDrawable(this.context?.let { ContextCompat.getDrawable(it, aboutData.icon) }) binding!!.appVersion.text = this.context?.getString(R.string.version, aboutData.versionName) // Setup Easter Egg onClickListener binding!!.generalInfoCard.setOnClickListener { if (firstTapMillis == null) { firstTapMillis = System.currentTimeMillis() } if (++tapCount == 3) { tapCount = 0 if (firstTapMillis!! >= (System.currentTimeMillis() - 500)) { startActivity(Intent(context, EasterEggActivity::class.java)) } firstTapMillis = null } } // Update button onClickListeners setupInfoButton(aboutData.bugURL, binding!!.reportBugButton) setupInfoButton(aboutData.donateURL, binding!!.donateButton) setupInfoButton(aboutData.sourceCodeURL, binding!!.sourceCodeButton) binding!!.licensesButton.setOnClickListener { startActivity(Intent(context, LicensesActivity::class.java)) } binding!!.aboutKdeButton.setOnClickListener { startActivity(Intent(context, AboutKDEActivity::class.java)) } setupInfoButton(aboutData.websiteURL, binding!!.websiteButton) // Update authors binding!!.authorsList.adapter = ListAdapter(this.context, aboutData.authors.map { AboutPersonEntryItem(it) }, false) if (aboutData.authorsFooterText != null) { binding!!.authorsFooterText.text = context?.getString(aboutData.authorsFooterText!!) } } private fun setupInfoButton(url: String?, button: FrameLayout) { if (url == null) { button.visibility = View.GONE } else { button.setOnClickListener { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) } } } override fun onDestroyView() { super.onDestroyView() binding = null } }
gpl-2.0
0a71d5d465511c0b8632952950655205
33.478992
186
0.665041
4.709529
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mcp/util/McpConstants.kt
1
600
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.util object McpConstants { const val TEXT_FORMATTING = "net.minecraft.util.text.TextFormatting" const val ENTITY = "net.minecraft.entity.Entity" const val WORLD = "net.minecraft.world.World" const val ITEM_STACK = "net.minecraft.item.ItemStack" const val BLOCK = "net.minecraft.block.Block" const val ITEM = "net.minecraft.item.Item" const val MINECRAFT_SERVER = "net.minecraft.server.MinecraftServer" }
mit
932e01c9c7f4851713e791983d7dbd7a
26.272727
72
0.715
3.592814
false
false
false
false
jguerinet/MyMartlet-Android
app/src/main/java/util/service/ConfigDownloadService.kt
1
2795
/* * Copyright 2014-2019 Julien Guerinet * * 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.guerinet.mymartlet.util.service import android.content.Intent import androidx.core.app.JobIntentService import com.guerinet.mymartlet.util.Prefs import com.guerinet.mymartlet.util.retrofit.ConfigService import com.guerinet.suitcase.date.NullDatePref import com.guerinet.suitcase.date.extensions.rfc1123String import com.guerinet.suitcase.prefs.IntPref import com.guerinet.suitcase.util.extensions.isConnected import org.koin.android.ext.android.inject import org.threeten.bp.ZonedDateTime import retrofit2.Call import timber.log.Timber /** * Downloads the latest version of the config info from the server * @author Julien Guerinet * @since 2.4.0 */ class ConfigDownloadService : JobIntentService() { private val configService by inject<ConfigService>() private val imsConfigPref by inject<NullDatePref>(Prefs.IMS_CONFIG) private val minVersionPref by inject<IntPref>(Prefs.MIN_VERSION) override fun onHandleWork(intent: Intent) { if (!isConnected) { // If we're not connected to the internet, don't continue return } // Config val config = executeRequest(configService.config(getIMS(imsConfigPref)), imsConfigPref) config?.apply { minVersionPref.value = androidMinVersion } } /** * Returns the ims String based on the [pref] to use for the call */ private fun getIMS(pref: NullDatePref): String? = pref.date.rfc1123String /** * Executes the [call] and updates the [imsPref] if successful. Returns the response object, * null if there was an error */ private fun <T> executeRequest(call: Call<T>, imsPref: NullDatePref): T? { return try { val response = call.execute() if (response.isSuccessful) { imsPref.date = ZonedDateTime.now() } response.body() } catch (e: Exception) { Timber.e(e, "Error downloading config section") null } } /** * Config skeleton class */ class Config { /** * Minimum version of the app that the user needs */ var androidMinVersion = -1 } }
apache-2.0
3eb7e3c9b8af7b91fc08f39c4950dda5
30.761364
96
0.684794
4.24772
false
true
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/program/programindicatorengine/internal/ProgramIndicatorSQLExecutor.kt
1
7300
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.program.programindicatorengine.internal import dagger.Reusable import javax.inject.Inject import org.hisp.dhis.android.core.analytics.aggregated.DimensionItem import org.hisp.dhis.android.core.analytics.aggregated.MetadataItem import org.hisp.dhis.android.core.analytics.aggregated.internal.AnalyticsServiceEvaluationItem import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.AnalyticsEvaluatorHelper import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.ProgramIndicatorEvaluatorHelper import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore import org.hisp.dhis.android.core.arch.helpers.UidsHelper import org.hisp.dhis.android.core.common.AnalyticsType import org.hisp.dhis.android.core.constant.Constant import org.hisp.dhis.android.core.dataelement.DataElement import org.hisp.dhis.android.core.enrollment.EnrollmentTableInfo import org.hisp.dhis.android.core.event.EventTableInfo import org.hisp.dhis.android.core.parser.internal.expression.CommonExpressionVisitor import org.hisp.dhis.android.core.parser.internal.expression.CommonParser import org.hisp.dhis.android.core.parser.internal.expression.ExpressionItemMethod import org.hisp.dhis.android.core.parser.internal.expression.ParserUtils import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLUtils.enrollment import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLUtils.event import org.hisp.dhis.android.core.program.programindicatorengine.internal.literal.ProgramIndicatorSQLLiteral import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttribute import org.hisp.dhis.antlr.Parser @Reusable internal class ProgramIndicatorSQLExecutor @Inject constructor( private val constantStore: IdentifiableObjectStore<Constant>, private val dataElementStore: IdentifiableObjectStore<DataElement>, private val trackedEntityAttributeStore: IdentifiableObjectStore<TrackedEntityAttribute>, private val databaseAdapter: DatabaseAdapter ) { fun getProgramIndicatorValue( evaluationItem: AnalyticsServiceEvaluationItem, metadata: Map<String, MetadataItem> ): String? { val sqlQuery = getProgramIndicatorSQL(evaluationItem, metadata) return databaseAdapter.rawQuery(sqlQuery)?.use { c -> c.moveToFirst() c.getString(0) } } fun getProgramIndicatorSQL( evaluationItem: AnalyticsServiceEvaluationItem, metadata: Map<String, MetadataItem> ): String { val programIndicator = ProgramIndicatorEvaluatorHelper.getProgramIndicator(evaluationItem, metadata) val periodItems = evaluationItem.allDimensionItems.filterIsInstance<DimensionItem.PeriodItem>() val periods = AnalyticsEvaluatorHelper.getReportingPeriods(periodItems, metadata) if (programIndicator.expression() == null) { throw IllegalArgumentException("Program Indicator ${programIndicator.uid()} has empty expression.") } val targetTable = when (programIndicator.analyticsType()) { AnalyticsType.EVENT -> "${EventTableInfo.TABLE_INFO.name()} as $event" AnalyticsType.ENROLLMENT, null -> "${EnrollmentTableInfo.TABLE_INFO.name()} as $enrollment" } val contextWhereClause = when (programIndicator.analyticsType()) { AnalyticsType.EVENT -> ProgramIndicatorEvaluatorHelper.getEventWhereClause(programIndicator, evaluationItem, metadata) AnalyticsType.ENROLLMENT, null -> ProgramIndicatorEvaluatorHelper.getEnrollmentWhereClause(programIndicator, evaluationItem, metadata) } val context = ProgramIndicatorSQLContext( programIndicator = programIndicator, periods = periods ) val collector = ProgramIndicatorItemIdsCollector() Parser.listen(programIndicator.expression(), collector) val sqlVisitor = newVisitor(ParserUtils.ITEM_GET_SQL, context) sqlVisitor.itemIds = collector.itemIds.toSet() sqlVisitor.setExpressionLiteral(ProgramIndicatorSQLLiteral()) val aggregator = ProgramIndicatorEvaluatorHelper.getAggregator(evaluationItem, programIndicator) val selectExpression = CommonParser.visit(programIndicator.expression(), sqlVisitor) // TODO Include more cases that are expected to be evaluated as "1" val filterExpression = when (programIndicator.filter()?.trim()) { "true", "", null -> "1" else -> CommonParser.visit(programIndicator.filter(), sqlVisitor) } return "SELECT ${aggregator.sql}($selectExpression) " + "FROM $targetTable " + "WHERE $filterExpression " + "AND $contextWhereClause" } private fun constantMap(): Map<String, Constant> { val constants = constantStore.selectAll() return UidsHelper.mapByUid(constants) } private fun newVisitor( itemMethod: ExpressionItemMethod, context: ProgramIndicatorSQLContext ): CommonExpressionVisitor { return CommonExpressionVisitor.newBuilder() .withItemMap(ProgramIndicatorParserUtils.PROGRAM_INDICATOR_SQL_EXPRESSION_ITEMS) .withItemMethod(itemMethod) .withConstantMap(constantMap()) .withProgramIndicatorSQLContext(context) .withDataElementStore(dataElementStore) .withTrackedEntityAttributeStore(trackedEntityAttributeStore) .buildForProgramSQLIndicator() } }
bsd-3-clause
82f535cc606c42c068a221744931876a
49
116
0.752466
4.932432
false
false
false
false
ilya-g/intellij-markdown
src/org/intellij/markdown/lexer/MarkdownLexer.kt
1
2302
package org.intellij.markdown.lexer import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownTokenTypes import java.io.IOException public open class MarkdownLexer(private val baseLexer: GeneratedLexer) { public var type: IElementType? = null private set private var nextType: IElementType? = null public var originalText: CharSequence = "" private set public var bufferStart: Int = 0 private set public var bufferEnd: Int = 0 private set public var tokenStart: Int = 0 private set public var tokenEnd: Int = 0 private set public fun start(originalText: CharSequence, bufferStart: Int = 0, bufferEnd: Int = originalText.length) { this.originalText = originalText this.bufferStart = bufferStart this.bufferEnd = bufferEnd baseLexer.reset(originalText, bufferStart, bufferEnd, 0) type = advanceBase() tokenStart = baseLexer.getTokenStart() calcNextType() } public fun advance(): Boolean { return locateToken() } private fun locateToken(): Boolean { `type` = nextType tokenStart = tokenEnd if (`type` == null) { return false } calcNextType() return true } private fun calcNextType() { do { tokenEnd = baseLexer.getTokenEnd() nextType = advanceBase() } while (type.let { nextType == it && it != null && it in TOKENS_TO_MERGE }) } private fun advanceBase(): IElementType? { try { return baseLexer.advance() } catch (e: IOException) { e.printStackTrace() throw AssertionError("This could not be!") } } companion object { private val TOKENS_TO_MERGE = setOf( MarkdownTokenTypes.TEXT, MarkdownTokenTypes.WHITE_SPACE, MarkdownTokenTypes.CODE_LINE, MarkdownTokenTypes.LINK_ID, MarkdownTokenTypes.LINK_TITLE, MarkdownTokenTypes.URL, MarkdownTokenTypes.AUTOLINK, MarkdownTokenTypes.EMAIL_AUTOLINK, MarkdownTokenTypes.BAD_CHARACTER) } }
apache-2.0
ecf7ab5e3dd82616c6c944e450c3aa3a
26.73494
84
0.592963
4.993492
false
false
false
false
dahlstrom-g/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRListPanelFactory.kt
1
8990
// 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.plugins.github.pullrequest.ui.toolwindow import com.intellij.ide.DataManager import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.components.service import com.intellij.openapi.progress.util.ProgressWindow import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.components.ActionLink import com.intellij.ui.components.JBList import com.intellij.ui.components.panels.VerticalLayout import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBUI import com.intellij.util.ui.StatusText import com.intellij.util.ui.UIUtil import com.intellij.util.ui.scroll.BoundedRangeModelThresholdListener import com.intellij.vcs.log.ui.frame.ProgressStripe import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys import org.jetbrains.plugins.github.pullrequest.data.GHListLoader import org.jetbrains.plugins.github.pullrequest.data.GHPRListLoader import org.jetbrains.plugins.github.pullrequest.data.GHPRListUpdatesChecker import org.jetbrains.plugins.github.pullrequest.data.service.GHPRRepositoryDataService import org.jetbrains.plugins.github.pullrequest.ui.GHApiLoadingErrorHandler import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider import org.jetbrains.plugins.github.ui.component.GHHandledErrorPanelModel import org.jetbrains.plugins.github.ui.component.GHHtmlErrorPanel import java.awt.FlowLayout import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel import javax.swing.ScrollPaneConstants import javax.swing.event.ChangeEvent internal class GHPRListPanelFactory(private val project: Project, private val repositoryDataService: GHPRRepositoryDataService, private val listLoader: GHPRListLoader, private val listUpdatesChecker: GHPRListUpdatesChecker, private val account: GithubAccount, private val disposable: Disposable) { private val scope = MainScope().also { Disposer.register(disposable) { it.cancel() } } fun create(list: JBList<GHPullRequestShort>, avatarIconsProvider: GHAvatarIconsProvider): JComponent { val actionManager = ActionManager.getInstance() val historyModel = GHPRSearchHistoryModel(scope, project.service()) val searchVm = GHPRSearchPanelViewModel(scope, repositoryDataService, historyModel, avatarIconsProvider) scope.launch { searchVm.searchState.collectLatest { listLoader.searchQuery = it.toQuery() } } ListEmptyTextController(scope, listLoader, searchVm.searchState, list.emptyText, disposable) val searchPanel = GHPRSearchPanelFactory(searchVm).create(scope) val outdatedStatePanel = JPanel(FlowLayout(FlowLayout.LEFT, JBUIScale.scale(5), 0)).apply { background = UIUtil.getPanelBackground() border = JBUI.Borders.empty(4, 0) add(JLabel(GithubBundle.message("pull.request.list.outdated"))) add(ActionLink(GithubBundle.message("pull.request.list.refresh")) { listLoader.reset() }) isVisible = false } OutdatedPanelController(listLoader, listUpdatesChecker, outdatedStatePanel, disposable) val errorHandler = GHApiLoadingErrorHandler(project, account) { listLoader.reset() } val errorModel = GHHandledErrorPanelModel(GithubBundle.message("pull.request.list.cannot.load"), errorHandler).apply { error = listLoader.error } listLoader.addErrorChangeListener(disposable) { errorModel.error = listLoader.error } val errorPane = GHHtmlErrorPanel.create(errorModel) val controlsPanel = JPanel(VerticalLayout(0)).apply { isOpaque = false add(searchPanel) add(outdatedStatePanel) add(errorPane) } val listLoaderPanel = createListLoaderPanel(listLoader, list, disposable) return JBUI.Panels.simplePanel(listLoaderPanel).addToTop(controlsPanel).andTransparent().also { DataManager.registerDataProvider(it) { dataId -> if (GHPRActionKeys.SELECTED_PULL_REQUEST.`is`(dataId)) { if (list.isSelectionEmpty) null else list.selectedValue } else null } actionManager.getAction("Github.PullRequest.List.Reload").registerCustomShortcutSet(it, disposable) } } private fun createListLoaderPanel(loader: GHListLoader<*>, list: JComponent, disposable: Disposable): JComponent { val scrollPane = ScrollPaneFactory.createScrollPane(list, true).apply { isOpaque = false viewport.isOpaque = false horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED val model = verticalScrollBar.model val listener = object : BoundedRangeModelThresholdListener(model, 0.7f) { override fun onThresholdReached() { if (!loader.loading && loader.canLoadMore()) { loader.loadMore() } } } model.addChangeListener(listener) loader.addLoadingStateChangeListener(disposable) { if (!loader.loading) listener.stateChanged(ChangeEvent(loader)) } } loader.addDataListener(disposable, object : GHListLoader.ListDataListener { override fun onAllDataRemoved() { if (scrollPane.isShowing) loader.loadMore() } }) val progressStripe = ProgressStripe(scrollPane, disposable, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS).apply { if (loader.loading) startLoadingImmediately() else stopLoading() } loader.addLoadingStateChangeListener(disposable) { if (loader.loading) progressStripe.startLoading() else progressStripe.stopLoading() } return progressStripe } private class ListEmptyTextController(scope: CoroutineScope, private val listLoader: GHListLoader<*>, private val searchState: MutableStateFlow<GHPRListSearchValue>, private val emptyText: StatusText, listenersDisposable: Disposable) { init { listLoader.addLoadingStateChangeListener(listenersDisposable, ::update) scope.launch { searchState.collect { update() } } } private fun update() { emptyText.clear() if (listLoader.loading || listLoader.error != null) return val search = searchState.value if (search == GHPRListSearchValue.DEFAULT) { emptyText.appendText(GithubBundle.message("pull.request.list.no.matches")) .appendSecondaryText(GithubBundle.message("pull.request.list.reset.filters"), SimpleTextAttributes.LINK_ATTRIBUTES) { searchState.update { GHPRListSearchValue.EMPTY } } } else if (search.isEmpty) { emptyText.appendText(GithubBundle.message("pull.request.list.nothing.loaded")) } else { emptyText.appendText(GithubBundle.message("pull.request.list.no.matches")) .appendSecondaryText(GithubBundle.message("pull.request.list.reset.filters.to.default", GHPRListSearchValue.DEFAULT.toQuery().toString()), SimpleTextAttributes.LINK_ATTRIBUTES) { searchState.update { GHPRListSearchValue.DEFAULT } } } } } private class OutdatedPanelController(private val listLoader: GHListLoader<*>, private val listChecker: GHPRListUpdatesChecker, private val panel: JPanel, listenersDisposable: Disposable) { init { listLoader.addLoadingStateChangeListener(listenersDisposable, ::update) listLoader.addErrorChangeListener(listenersDisposable, ::update) listChecker.addOutdatedStateChangeListener(listenersDisposable, ::update) } private fun update() { panel.isVisible = listChecker.outdated && (!listLoader.loading && listLoader.error == null) } } }
apache-2.0
faacad02e21d9902387266f305b21049
42.858537
122
0.710234
5.011148
false
false
false
false
intellij-solidity/intellij-solidity
src/main/kotlin/me/serce/solidity/ide/settings/EvmDownloader.kt
1
1536
package me.serce.solidity.ide.settings import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.progress.ProgressManager import com.intellij.platform.templates.github.ZipUtil import com.intellij.util.download.DownloadableFileService import java.io.File import javax.swing.JComponent object EvmDownloader { private const val evmUrl = "https://bintray.com/ethereum/maven/download_file?file_path=org%2Fethereum%2Fethereumj-core%2F1.7.1-RELEASE%2Fethereumj-core-1.7.1-RELEASE.zip" private const val localName = "evm.zip" fun download(anchor: JComponent): String { val s = DownloadableFileService.getInstance() val createDownloader = s.createDownloader(listOf(s.createFileDescription(evmUrl, localName)), "EthereumJ VM bundle") val chooseFile = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor().withTitle("Select destination folder for EVM installation"), anchor, null, null) ?: return "" val downloaded = createDownloader.downloadWithProgress(chooseFile.path, null, anchor)?.first()?.first ?: return "" val zipArchive = File(downloaded.path.removeSuffix("!/")) ProgressManager.getInstance().runProcessWithProgressSynchronously({ ZipUtil.unzip(ProgressManager.getInstance().progressIndicator, File(chooseFile.path), zipArchive, null, null, true) }, "Unzipping", false, null) zipArchive.delete() return File(chooseFile.path, "lib").absolutePath } }
mit
a1eab49afbbd25287147019bdef32b80
47
172
0.783854
4.302521
false
false
false
false
TechzoneMC/SonarPet
core/src/main/kotlin/net/techcable/sonarpet/nms/entity/generators/CustomMotionPetGenerator.kt
1
2821
package net.techcable.sonarpet.nms.entity.generators import com.dsh105.echopet.compat.api.plugin.IEchoPetPlugin import com.google.common.collect.ImmutableList import net.techcable.sonarpet.nms.* import net.techcable.sonarpet.utils.Versioning.* import net.techcable.sonarpet.utils.invokeVirtual import net.techcable.sonarpet.utils.plus import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type import org.objectweb.asm.Type.* /** * Some entity specific logic is kept in the living update/motion method, like enderdragon destruction. * This generator overrides the default (entity-specific) update logic, with a minimalistic alternative. */ class CustomMotionPetGenerator(plugin: IEchoPetPlugin, currentType: Type, hookClass: Class<*>, entityClass: Class<*>) : EntityPetGenerator(plugin, currentType, hookClass, entityClass) { override val generatedMethods: ImmutableList<GeneratedMethod> get() = super.generatedMethods + GeneratedMethod(NMS_VERSION.livingUpdateMethod) { // TODO: Fix the bug with these pets not actually moving (maybe something to do with a missing setPosition?) // this.doTick() loadThis() invokeVirtual("doTick", ENTITY_LIVING_TYPE, VOID_TYPE) // this.moveStrafing *= 0.98 // this.moveForward *= 0.98 // this.moveUpwards *= 0.9 val movementUpdates = mutableMapOf( NMS_VERSION.sidewaysMotionField to 0.98f, NMS_VERSION.forwardMotionField to 0.98f ) // NOTE: Upwards motion is only present post 1.12 and is multiplied by 0.9 not 0.98 NMS_VERSION.upwardsMotionField?.let { movementUpdates.put(it, 0.9f) } for ((fieldName, coefficient) in movementUpdates) { loadThis() visitInsn(DUP) getField(ENTITY_LIVING_TYPE, fieldName, FLOAT_TYPE) visitLdcInsn(coefficient) visitInsn(FMUL) putField(ENTITY_LIVING_TYPE, fieldName, FLOAT_TYPE) } // this.move(this.moveStrafing, this.moveForward, this.moveUpwards), moveUpwards missing before 1.12 loadThis() visitInsn(DUP) getField(ENTITY_LIVING_TYPE, NMS_VERSION.sidewaysMotionField, FLOAT_TYPE) loadThis() getField(ENTITY_LIVING_TYPE, NMS_VERSION.forwardMotionField, FLOAT_TYPE) NMS_VERSION.upwardsMotionField?.let { loadThis() getField(ENTITY_LIVING_TYPE, it, FLOAT_TYPE) } invokeVirtual( name = NMS_VERSION.entityMoveMethodName, ownerType = ENTITY_LIVING_TYPE, parameterTypes = NMS_VERSION.entityMoveMethodParameters.toList() ) } }
gpl-3.0
7197d0f87de9ac6f920fad0e8669dc03
48.508772
185
0.64977
4.394081
false
false
false
false
securityfirst/Umbrella_android
app/src/main/java/org/secfirst/umbrella/component/AutoFitGridLayoutManager.kt
1
1190
package org.secfirst.umbrella.component import android.content.Context import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class AutoFitGridLayoutManager(context: Context, private var columnWidth: Int) : GridLayoutManager(context, columnWidth) { private var columnWidthChanged = true fun setColumnWidth(newColumnWidth: Int) { if (newColumnWidth > 0 && newColumnWidth != columnWidth) { columnWidth = newColumnWidth columnWidthChanged = true } } override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State) { if (columnWidthChanged && columnWidth > 0) { val totalSpace: Int = if (orientation == LinearLayoutManager.VERTICAL) { width - paddingRight - paddingLeft } else { height - paddingTop - paddingBottom } val spanCount = Math.max(1, totalSpace / columnWidth) setSpanCount(spanCount) columnWidthChanged = false } super.onLayoutChildren(recycler, state) } }
gpl-3.0
87780eff0d30559a8b31565a2327669e
34
122
0.678992
5.458716
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/ses/src/main/kotlin/com/example/ses/SendMessageEmail.kt
1
2761
// snippet-sourcedescription:[SendMessageEmail.kt demonstrates how to send an email message by using the Amazon Simple Email Service (Amazon SES).] // snippet-keyword:[Code Sample] // snippet-keyword:[Amazon Simple Email Service] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.ses // snippet-start:[ses.kotlin.sendmessage.import] import aws.sdk.kotlin.services.ses.SesClient import aws.sdk.kotlin.services.ses.model.Body import aws.sdk.kotlin.services.ses.model.Content import aws.sdk.kotlin.services.ses.model.Destination import aws.sdk.kotlin.services.ses.model.Message import aws.sdk.kotlin.services.ses.model.SendEmailRequest import kotlin.system.exitProcess // snippet-end:[ses.kotlin.sendmessage.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <sender> <recipient> <subject> Where: sender - An email address that represents the sender. recipient - An email address that represents the recipient. subject - The subject line. """ if (args.size != 3) { println(usage) exitProcess(0) } val sender = args[0] val recipient = args[1] val subject = args[2] // The HTML body of the email. val bodyHTML = ( "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>" + "<p> See the list of customers.</p>" + "</body>" + "</html>" ) send(sender, recipient, subject, bodyHTML) } // snippet-start:[ses.kotlin.sendmessage.main] suspend fun send( sender: String?, recipient: String, subjectVal: String?, bodyHTML: String? ) { val destinationOb = Destination { toAddresses = listOf(recipient) } val contentOb = Content { data = bodyHTML } val subOb = Content { data = subjectVal } val bodyOb = Body { html = contentOb } val msgOb = Message { subject = subOb body = bodyOb } val emailRequest = SendEmailRequest { destination = destinationOb message = msgOb source = sender } SesClient { region = "us-east-1" }.use { sesClient -> println("Attempting to send an email through Amazon SES using the AWS SDK for Kotlin...") sesClient.sendEmail(emailRequest) } } // snippet-end:[ses.kotlin.sendmessage.main]
apache-2.0
aab677b04328edb7afac97c2bbe205f2
25.888889
147
0.635639
3.888732
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Wrapper.kt
1
1354
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Type.* import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Method2 import java.lang.reflect.Modifier @DependsOn(DualNode::class) class Wrapper : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { Modifier.isAbstract(it.access) } .and { it.superType == type<DualNode>() } .and { it.instanceMethods.any { it.returnType == Any::class.type } } @MethodParameters() class get : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == Any::class.type } } @MethodParameters() class isSoft : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE } } class size : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == INT_TYPE } } }
mit
e3ac3e10a5e7e87092a051b25498ab76
37.714286
90
0.742984
4.10303
false
false
false
false
google/intellij-community
python/src/com/jetbrains/python/sdk/AddInterpreterActions.kt
5
4467
// 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. @file:JvmName("AddInterpreterActions") package com.jetbrains.python.sdk import com.intellij.execution.target.TargetCustomToolWizardStep import com.intellij.execution.target.TargetEnvironmentType import com.intellij.execution.target.TargetEnvironmentWizard import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.module.Module import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.jetbrains.python.PyBundle import com.jetbrains.python.configuration.PyConfigurableInterpreterList import com.jetbrains.python.run.PythonInterpreterTargetEnvironmentFactory import com.jetbrains.python.sdk.add.PyAddSdkDialog import com.jetbrains.python.sdk.add.target.PyAddTargetBasedSdkDialog import com.jetbrains.python.target.PythonLanguageRuntimeType import java.util.function.Consumer fun collectAddInterpreterActions(project: Project, module: Module?, onSdkCreated: Consumer<Sdk>): List<AnAction> = listOf(AddLocalInterpreterAction(project, module, onSdkCreated::accept)) + collectNewInterpreterOnTargetActions(project, onSdkCreated::accept) private fun collectNewInterpreterOnTargetActions(project: Project, onSdkCreated: Consumer<Sdk>): List<AnAction> = PythonInterpreterTargetEnvironmentFactory.EP_NAME.extensionList .filter { it.getTargetType().isSystemCompatible() } .map { AddInterpreterOnTargetAction(project, it.getTargetType(), onSdkCreated) } private class AddLocalInterpreterAction(private val project: Project, private val module: Module?, private val onSdkCreated: Consumer<Sdk>) : AnAction(PyBundle.messagePointer("python.sdk.action.add.local.interpreter.text"), AllIcons.Nodes.HomeFolder), DumbAware { override fun actionPerformed(e: AnActionEvent) { val model = PyConfigurableInterpreterList.getInstance(project).model PyAddTargetBasedSdkDialog.show( project, module, model.sdks.asList(), Consumer { if (it != null && model.findSdk(it.name) == null) { model.addSdk(it) model.apply() onSdkCreated.accept(it) } } ) } } private class AddInterpreterOnTargetAction(private val project: Project, private val targetType: TargetEnvironmentType<*>, private val onSdkCreated: Consumer<Sdk>) : AnAction(PyBundle.messagePointer("python.sdk.action.add.interpreter.based.on.target.text", targetType.displayName), targetType.icon), DumbAware { override fun actionPerformed(e: AnActionEvent) { val wizard = TargetEnvironmentWizard.createWizard(project, targetType, PythonLanguageRuntimeType.getInstance()) if (wizard != null && wizard.showAndGet()) { val model = PyConfigurableInterpreterList.getInstance(project).model val sdk = (wizard.currentStepObject as? TargetCustomToolWizardStep)?.customTool as? Sdk if (sdk != null && model.findSdk(sdk.name) == null) { model.addSdk(sdk) model.apply() onSdkCreated.accept(sdk) } } } } class AddInterpreterAction(val project: Project, val module: Module, val currentSdk: Sdk?) : DumbAwareAction(PyBundle.messagePointer("python.sdk.popup.add.interpreter")) { override fun actionPerformed(e: AnActionEvent) { val model = PyConfigurableInterpreterList.getInstance(project).model PyAddSdkDialog.show( project, module, model.sdks.asList(), Consumer { if (it != null && model.findSdk(it.name) == null) { model.addSdk(it) model.apply() switchToSdk(module, it, currentSdk) } } ) } } fun switchToSdk(module: Module, sdk: Sdk, currentSdk: Sdk?) { val project = module.project (sdk.sdkType as PythonSdkType).setupSdkPaths(sdk) removeTransferredRootsFromModulesWithInheritedSdk(project, currentSdk) project.pythonSdk = sdk transferRootsToModulesWithInheritedSdk(project, sdk) removeTransferredRoots(module, currentSdk) module.pythonSdk = sdk transferRoots(module, sdk) }
apache-2.0
e60f2c1b3d2770acc5b8219ec31b015b
39.990826
158
0.734497
4.576844
false
false
false
false
google/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/JpsCompilationRunner.kt
1
19713
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet", "HardCodedStringLiteral") package org.jetbrains.intellij.build.impl import com.intellij.diagnostic.telemetry.use import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.openapi.diagnostic.DefaultLogger import com.intellij.openapi.diagnostic.Logger import com.intellij.util.containers.MultiMap import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.groovy.compiler.rt.GroovyRtConstants import org.jetbrains.intellij.build.CompilationContext import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.jps.api.CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope import org.jetbrains.jps.api.GlobalOptions import org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter import org.jetbrains.jps.build.Standalone import org.jetbrains.jps.builders.BuildTarget import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType import org.jetbrains.jps.gant.Log4jFileLoggerFactory import org.jetbrains.jps.incremental.MessageHandler import org.jetbrains.jps.incremental.artifacts.ArtifactBuildTargetType import org.jetbrains.jps.incremental.artifacts.impl.ArtifactSorter import org.jetbrains.jps.incremental.artifacts.impl.JpsArtifactUtil import org.jetbrains.jps.incremental.dependencies.DependencyResolvingBuilder import org.jetbrains.jps.incremental.groovy.JpsGroovycRunner import org.jetbrains.jps.incremental.messages.* import org.jetbrains.jps.model.artifact.JpsArtifact import org.jetbrains.jps.model.artifact.JpsArtifactService import org.jetbrains.jps.model.artifact.elements.JpsModuleOutputPackagingElement import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.module.JpsModule import java.beans.Introspector import java.nio.file.Files import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit import java.util.function.BiConsumer internal class JpsCompilationRunner(private val context: CompilationContext) { private val compilationData = context.compilationData companion object { init { // Unset 'groovy.target.bytecode' which was possibly set by outside context // to get target bytecode version from corresponding java compiler settings System.clearProperty(GroovyRtConstants.GROOVY_TARGET_BYTECODE) setSystemPropertyIfUndefined(GlobalOptions.COMPILE_PARALLEL_OPTION, "true") setSystemPropertyIfUndefined(DependencyResolvingBuilder.RESOLUTION_PARALLELISM_PROPERTY, Runtime.getRuntime().availableProcessors().toString()) setSystemPropertyIfUndefined(GlobalOptions.USE_DEFAULT_FILE_LOGGING_OPTION, "false") setSystemPropertyIfUndefined(JpsGroovycRunner.GROOVYC_IN_PROCESS, "true") setSystemPropertyIfUndefined(GroovyRtConstants.GROOVYC_ASM_RESOLVING_ONLY, "false") // https://youtrack.jetbrains.com/issue/IDEA-269280 System.setProperty("aether.connector.resumeDownloads", "false") // Produces Kotlin compiler incremental cache which can be reused later. // Unrelated to force rebuild controlled by JPS. setSystemPropertyIfUndefined("kotlin.incremental.compilation", "true") // Required for JPS Portable Caches setSystemPropertyIfUndefined(JavaBackwardReferenceIndexWriter.PROP_KEY, "true") } } init { setSystemPropertyIfUndefined(DependencyResolvingBuilder.RESOLUTION_RETRY_ENABLED_PROPERTY, (context.options.resolveDependenciesMaxAttempts > 1).toString()) setSystemPropertyIfUndefined(DependencyResolvingBuilder.RESOLUTION_RETRY_DELAY_MS_PROPERTY, context.options.resolveDependenciesDelayMs.toString()) setSystemPropertyIfUndefined(DependencyResolvingBuilder.RESOLUTION_RETRY_MAX_ATTEMPTS_PROPERTY, context.options.resolveDependenciesMaxAttempts.toString()) setSystemPropertyIfUndefined(DependencyResolvingBuilder.RESOLUTION_RETRY_BACKOFF_LIMIT_MS_PROPERTY, TimeUnit.MINUTES.toMillis(15).toString()) } fun buildModules(modules: List<JpsModule>) { val names = LinkedHashSet<String>() spanBuilder("collect dependencies") .setAttribute(AttributeKey.longKey("moduleCount"), modules.size.toLong()) .use { span -> val requiredDependencies = ArrayList<String>() for (module in modules) { requiredDependencies.clear() for (dependency in getModuleDependencies(module = module, includeTests = false)) { if (names.add(dependency)) { requiredDependencies.add(dependency) } } if (!requiredDependencies.isEmpty()) { span.addEvent("required dependencies", Attributes.of( AttributeKey.stringKey("module"), module.name, AttributeKey.stringArrayKey("module"), java.util.List.copyOf(requiredDependencies) )) } } } runBuild(moduleSet = names, allModules = false, artifactNames = emptyList(), includeTests = false, resolveProjectDependencies = false) } fun buildModulesWithoutDependencies(modules: Collection<JpsModule>, includeTests: Boolean) { runBuild(moduleSet = modules.map { it.name }, allModules = false, artifactNames = emptyList(), includeTests = includeTests, resolveProjectDependencies = false) } fun resolveProjectDependencies() { runBuild(moduleSet = emptyList(), allModules = false, artifactNames = emptyList(), includeTests = false, resolveProjectDependencies = true) } fun buildModuleTests(module: JpsModule) { runBuild(getModuleDependencies(module = module, includeTests = true), allModules = false, artifactNames = emptyList(), includeTests = true, resolveProjectDependencies = false) } fun buildAll() { runBuild(moduleSet = emptyList(), allModules = true, artifactNames = emptyList(), includeTests = true, resolveProjectDependencies = false) } fun buildProduction() { runBuild(moduleSet = emptyList(), allModules = true, artifactNames = emptyList(), includeTests = false, resolveProjectDependencies = false) } @Deprecated("use {@link #buildArtifacts(java.util.Set, boolean)} instead") fun buildArtifacts(artifactNames: Set<String>) { buildArtifacts(artifactNames = artifactNames, buildIncludedModules = true) } fun buildArtifacts(artifactNames: Set<String>, buildIncludedModules: Boolean) { val artifacts = getArtifactsWithIncluded(artifactNames) val modules = if (buildIncludedModules) getModulesIncludedInArtifacts(artifacts) else emptyList() runBuild(moduleSet = modules, allModules = false, artifactNames = artifacts.map { it.name }, includeTests = false, resolveProjectDependencies = false) } fun getModulesIncludedInArtifacts(artifactNames: Collection<String>): Collection<String> = getModulesIncludedInArtifacts(getArtifactsWithIncluded(artifactNames)) private fun getModulesIncludedInArtifacts(artifacts: Collection<JpsArtifact>): Set<String> { val modulesSet: MutableSet<String> = LinkedHashSet() for (artifact in artifacts) { JpsArtifactUtil.processPackagingElements(artifact.rootElement) { element -> if (element is JpsModuleOutputPackagingElement) { modulesSet.addAll(getModuleDependencies(context.findRequiredModule(element.moduleReference.moduleName), false)) } true } } return modulesSet } private fun getArtifactsWithIncluded(artifactNames: Collection<String>): Set<JpsArtifact> { val artifacts = JpsArtifactService.getInstance().getArtifacts(context.project).filter { it.name in artifactNames } return ArtifactSorter.addIncludedArtifacts(artifacts) } private fun setupAdditionalBuildLogging(compilationData: JpsCompilationData) { val categoriesWithDebugLevel = compilationData.categoriesWithDebugLevel val buildLogFile = compilationData.buildLogFile try { val factory = Log4jFileLoggerFactory(buildLogFile.toFile(), categoriesWithDebugLevel) AntLoggerFactory.fileLoggerFactory = factory context.messages.info("Build log (${if (categoriesWithDebugLevel.isEmpty()) "info" else "debug level for $categoriesWithDebugLevel"}) " + "will be written to $buildLogFile") } catch (t: Throwable) { context.messages.warning("Cannot setup additional logging to $buildLogFile.absolutePath: ${t.message}") } } private fun runBuild(moduleSet: Collection<String>, allModules: Boolean, artifactNames: Collection<String>, includeTests: Boolean, resolveProjectDependencies: Boolean) { messageHandler = AntMessageHandler(context) if (context.options.compilationLogEnabled) { setupAdditionalBuildLogging(compilationData) } Logger.setFactory(AntLoggerFactory::class.java) val forceBuild = !context.options.incrementalCompilation val scopes = ArrayList<TargetTypeBuildScope>() for (type in JavaModuleBuildTargetType.ALL_TYPES) { if (includeTests || !type.isTests) { val namesToCompile = if (allModules) context.project.modules.mapTo(mutableListOf()) { it.name } else moduleSet.toMutableList() if (type.isTests) { namesToCompile.removeAll(compilationData.compiledModuleTests) compilationData.compiledModuleTests.addAll(namesToCompile) } else { namesToCompile.removeAll(compilationData.compiledModules) compilationData.compiledModules.addAll(namesToCompile) } if (namesToCompile.isEmpty()) { continue } val builder = TargetTypeBuildScope.newBuilder().setTypeId(type.typeId).setForceBuild(forceBuild) if (allModules) { scopes.add(builder.setAllTargets(true).build()) } else { scopes.add(builder.addAllTargetId(namesToCompile).build()) } } } if (resolveProjectDependencies && !compilationData.projectDependenciesResolved) { scopes.add(TargetTypeBuildScope.newBuilder().setTypeId("project-dependencies-resolving") .setForceBuild(false).setAllTargets(true).build()) compilationData.projectDependenciesResolved = true } val artifactsToBuild = artifactNames - compilationData.builtArtifacts if (!artifactsToBuild.isEmpty()) { val builder = TargetTypeBuildScope.newBuilder().setTypeId(ArtifactBuildTargetType.INSTANCE.typeId).setForceBuild(forceBuild) scopes.add(builder.addAllTargetId(artifactsToBuild).build()) compilationData.builtArtifacts.addAll(artifactsToBuild) } val compilationStart = System.nanoTime() val messageHandler = messageHandler!! spanBuilder("compilation") .setAttribute("scope", "${if (allModules) "all" else moduleSet.size} modules") .setAttribute("includeTests", includeTests) .setAttribute("artifactsToBuild", artifactsToBuild.size.toLong()) .setAttribute("resolveProjectDependencies", resolveProjectDependencies) .setAttribute("modules", moduleSet.joinToString(separator = ", ")) .setAttribute("incremental", context.options.incrementalCompilation) .setAttribute("includeTests", includeTests) .setAttribute("cacheDir", compilationData.dataStorageRoot.toString()) .useWithScope { Standalone.runBuild({ context.projectModel }, compilationData.dataStorageRoot.toFile(), messageHandler, scopes, false) } if (!messageHandler.errorMessagesByCompiler.isEmpty) { for ((key, value) in messageHandler.errorMessagesByCompiler.entrySet()) { @Suppress("UNCHECKED_CAST") context.messages.compilationErrors(key, value as List<String>) } throw RuntimeException("Compilation failed") } else if (!compilationData.statisticsReported) { messageHandler.printPerModuleCompilationStatistics(compilationStart) context.messages.reportStatisticValue("Compilation time, ms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - compilationStart).toString()) compilationData.statisticsReported = true } } } internal class AntLoggerFactory : Logger.Factory { companion object { var fileLoggerFactory: Logger.Factory? = null } override fun getLoggerInstance(category: String): Logger = BackedLogger(category, fileLoggerFactory?.getLoggerInstance(category)) } private class AntMessageHandler(private val context: CompilationContext) : MessageHandler { val errorMessagesByCompiler = MultiMap.createConcurrent<String, String>() private val compilationStartTimeForTarget = ConcurrentHashMap<String, Long>() private val compilationFinishTimeForTarget = ConcurrentHashMap<String, Long>() private var progress = -1.0.toFloat() override fun processMessage(message: BuildMessage) { val text = message.messageText when (message.kind) { BuildMessage.Kind.ERROR -> { val compilerName: String val messageText: String if (message is CompilerMessage) { compilerName = message.compilerName val sourcePath = message.sourcePath messageText = if (sourcePath != null) { """ $sourcePath${if (message.line != -1L) ":" + message.line else ""}: $text """.trimIndent() } else { text } } else { compilerName = "" messageText = text } errorMessagesByCompiler.putValue(compilerName, messageText) } BuildMessage.Kind.WARNING -> context.messages.warning(text) BuildMessage.Kind.INFO -> if (message is BuilderStatisticsMessage) { val buildKind = if (context.options.incrementalCompilation) " (incremental)" else "" context.messages.reportStatisticValue("Compilation time '${message.builderName}'$buildKind, ms", message.elapsedTimeMs.toString()) val sources = message.numberOfProcessedSources context.messages.reportStatisticValue("Processed files by '${message.builderName}'$buildKind", sources.toString()) if (!context.options.incrementalCompilation && sources > 0) { context.messages.reportStatisticValue("Compilation time per file for '${message.builderName}', ms", String.format(Locale.US, "%.2f", message.elapsedTimeMs.toDouble() / sources)) } } else if (!text.isEmpty()) { context.messages.info(text) } BuildMessage.Kind.PROGRESS -> if (message is ProgressMessage) { progress = message.done message.currentTargets?.let { reportProgress(it.targets, message.messageText) } } else if (message is BuildingTargetProgressMessage) { val targets = message.targets val target = targets.first() val targetId = "$target.id${if (targets.size > 1) " and ${targets.size} more" else ""} ($target.targetType.typeId)" if (message.eventType == BuildingTargetProgressMessage.Event.STARTED) { reportProgress(targets, "") compilationStartTimeForTarget.put(targetId, System.nanoTime()) } else { compilationFinishTimeForTarget.put(targetId, System.nanoTime()) } } else -> { // ignore } } } fun printPerModuleCompilationStatistics(compilationStart: Long) { if (compilationStartTimeForTarget.isEmpty()) { return } Files.newBufferedWriter(context.paths.buildOutputDir.resolve("log/compilation-time.csv")).use { out -> compilationFinishTimeForTarget.forEach(BiConsumer { k, v -> val startTime = compilationStartTimeForTarget.get(k)!! - compilationStart val finishTime = v - compilationStart out.write("$k,$startTime,$finishTime\n") }) } val buildMessages = context.messages buildMessages.info("Compilation time per target:") val compilationTimeForTarget = compilationFinishTimeForTarget.entries.map { it.key to (it.value - compilationStartTimeForTarget.get(it.key)!!) } buildMessages.info(" average: ${String.format("%.2f", ((compilationTimeForTarget.sumOf { it.second }.toDouble()) / compilationTimeForTarget.size) / 1000000)}ms") val topTargets = compilationTimeForTarget.sortedBy { it.second }.asReversed().take(10) buildMessages.info(" top ${topTargets.size} targets by compilation time:") for (entry in topTargets) { buildMessages.info(" ${entry.first}: ${TimeUnit.NANOSECONDS.toMillis(entry.second)}ms") } } private fun reportProgress(targets: Collection<BuildTarget<*>>, targetSpecificMessage: String) { val targetsString = targets.joinToString(separator = ", ") { Introspector.decapitalize(it.presentableName) } val progressText = if (progress >= 0) " (${(100 * progress).toInt()}%)" else "" val targetSpecificText = if (targetSpecificMessage.isEmpty()) "" else ", $targetSpecificMessage" context.messages.progress("Compiling$progressText: $targetsString$targetSpecificText") } } private class BackedLogger constructor(category: String?, private val fileLogger: Logger?) : DefaultLogger(category) { override fun error(@Nls message: @NonNls String?, t: Throwable?, vararg details: String) { if (t == null) { messageHandler!!.processMessage(CompilerMessage(COMPILER_NAME, BuildMessage.Kind.ERROR, message)) } else { messageHandler!!.processMessage(CompilerMessage.createInternalBuilderError(COMPILER_NAME, t)) } fileLogger?.error(message, t, *details) } override fun warn(message: @NonNls String?, t: Throwable?) { messageHandler!!.processMessage(CompilerMessage(COMPILER_NAME, BuildMessage.Kind.WARNING, message)) fileLogger?.warn(message, t) } override fun info(message: String) { fileLogger?.info(message) } override fun info(message: String, t: Throwable?) { fileLogger?.info(message, t) } override fun isDebugEnabled(): Boolean { return fileLogger != null && fileLogger.isDebugEnabled } override fun debug(message: String) { fileLogger?.debug(message) } override fun debug(t: Throwable?) { fileLogger?.debug(t) } override fun debug(message: String, t: Throwable?) { fileLogger?.debug(message, t) } override fun isTraceEnabled(): Boolean { return fileLogger != null && fileLogger.isTraceEnabled } override fun trace(message: String) { fileLogger?.trace(message) } override fun trace(t: Throwable?) { fileLogger?.trace(t) } } private var messageHandler: AntMessageHandler? = null @Nls private const val COMPILER_NAME = "build runner" private fun setSystemPropertyIfUndefined(name: String, value: String) { if (System.getProperty(name) == null) { System.setProperty(name, value) } } private fun getModuleDependencies(module: JpsModule, includeTests: Boolean): Set<String> { var enumerator = JpsJavaExtensionService.dependencies(module).recursively() if (!includeTests) { enumerator = enumerator.productionOnly() } return enumerator.modules.mapTo(HashSet()) { it.name } }
apache-2.0
ae2f53ccc20bc6b6d097aaa90ca314cd
42.615044
165
0.711307
4.789359
false
true
false
false
RuneSuite/client
api/src/main/java/org/runestar/client/api/game/Username.kt
1
448
package org.runestar.client.api.game import org.runestar.client.raw.access.XUsername inline class Username(val accessor: XUsername) : Comparable<Username> { val name: String get() = accessor.name0 val cleanName: String? get() = accessor.cleanName override fun compareTo(other: Username) = accessor.compareTo0(other.accessor) override fun toString(): String { return "Username(name=$name, cleanName=$cleanName)" } }
mit
8ed04c9d24240085c8b060999895fb76
27.0625
81
0.725446
3.929825
false
false
false
false
google/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/outputs/NotebookOutputInlayController.kt
1
12860
package org.jetbrains.plugins.notebooks.visualization.outputs import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorCustomElementRenderer import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.util.Disposer import com.intellij.util.castSafelyTo import com.intellij.util.messages.Topic import org.jetbrains.plugins.notebooks.visualization.NotebookCellInlayController import org.jetbrains.plugins.notebooks.visualization.NotebookCellLines import org.jetbrains.plugins.notebooks.visualization.SwingClientProperty import org.jetbrains.plugins.notebooks.visualization.notebookAppearance import org.jetbrains.plugins.notebooks.visualization.outputs.NotebookOutputComponentFactory.Companion.gutterPainter import org.jetbrains.plugins.notebooks.visualization.outputs.impl.CollapsingComponent import org.jetbrains.plugins.notebooks.visualization.outputs.impl.InnerComponent import org.jetbrains.plugins.notebooks.visualization.outputs.impl.SurroundingComponent import org.jetbrains.plugins.notebooks.visualization.ui.addComponentInlay import org.jetbrains.plugins.notebooks.visualization.ui.yOffsetFromEditor import java.awt.Graphics import java.awt.Rectangle import java.awt.Toolkit import javax.swing.JComponent private const val DEFAULT_INLAY_HEIGHT = 200 // ToDo: merge with NotebookOutputListener interface OutputListener { fun beforeOutputCreated(editor: Editor, line: Int) {} fun outputCreated(editor: Editor, line: Int) {} fun outputSizeUpdated(editor: Editor, line: Int?) {} } val OUTPUT_LISTENER: Topic<OutputListener> = Topic.create("OutputAdded", OutputListener::class.java) val EditorCustomElementRenderer.notebookInlayOutputComponent: JComponent? get() = castSafelyTo<JComponent>()?.components?.firstOrNull()?.castSafelyTo<SurroundingComponent>() val EditorCustomElementRenderer.notebookCellOutputComponents: List<JComponent>? get() = notebookInlayOutputComponent?.components?.firstOrNull()?.castSafelyTo<JComponent>()?.components?.map { it as JComponent } /** * Shows outputs for intervals using [NotebookOutputDataKeyExtractor] and [NotebookOutputComponentFactory]. */ class NotebookOutputInlayController private constructor( override val factory: NotebookCellInlayController.Factory, private val editor: EditorImpl, private val lines: IntRange, ) : NotebookCellInlayController { private companion object { private val key = NotebookOutputInlayController::class.qualifiedName!! fun JComponent.addDisposable(disposable: Disposable) { putClientProperty(key, disposable) } fun JComponent.disposeComponent() { (getClientProperty(key) as? Disposable)?.let(Disposer::dispose) } } private val innerComponent = InnerComponent(editor) private val outerComponent = SurroundingComponent.create(editor, innerComponent) override val inlay: Inlay<*> = editor.addComponentInlay( outerComponent, isRelatedToPrecedingText = true, showAbove = false, priority = editor.notebookAppearance.NOTEBOOK_OUTPUT_INLAY_PRIORITY, offset = editor.document.getLineEndOffset(lines.last), ) init { innerComponent.maxHeight = if (!ApplicationManager.getApplication().isUnitTestMode) { (Toolkit.getDefaultToolkit().screenSize.height * 0.3).toInt() } else { DEFAULT_INLAY_HEIGHT } Disposer.register(inlay) { for (disposable in innerComponent.mainComponents) { disposable.disposeComponent() } } } override fun paintGutter(editor: EditorImpl, g: Graphics, r: Rectangle, interval: NotebookCellLines.Interval) { val yOffset = innerComponent.yOffsetFromEditor(editor) ?: return val bounds = Rectangle() val oldClip = g.clipBounds g.clip = Rectangle(oldClip.x, yOffset, oldClip.width, innerComponent.height).intersection(oldClip) for (collapsingComponent in innerComponent.components) { val mainComponent = (collapsingComponent as CollapsingComponent).mainComponent collapsingComponent.paintGutter(editor, yOffset, g) mainComponent.gutterPainter?.let { painter -> mainComponent.yOffsetFromEditor(editor)?.let { yOffset -> bounds.setBounds(r.x, yOffset, r.width, mainComponent.height) painter.paintGutter(editor, g, bounds) } } } g.clip = oldClip } private fun rankCompatibility(outputDataKeys: List<NotebookOutputDataKey>): Int = getComponentsWithFactories().zip(outputDataKeys).sumBy { (pair, outputDataKey) -> val (component, factory) = pair when (factory.matchWithTypes(component, outputDataKey)) { NotebookOutputComponentFactory.Match.NONE -> 0 NotebookOutputComponentFactory.Match.COMPATIBLE -> 1 NotebookOutputComponentFactory.Match.SAME -> 1000 } } private fun getComponentsWithFactories() = mutableListOf<Pair<JComponent, NotebookOutputComponentFactory<*, *>>>().also { for (component in innerComponent.mainComponents) { val factory = component.outputComponentFactory if (factory != null) { it += component to factory } } } private fun <C : JComponent, K : NotebookOutputDataKey> NotebookOutputComponentFactory<C, K>.matchWithTypes( component: JComponent, outputDataKey: NotebookOutputDataKey, ) = when { !componentClass.isAssignableFrom(component.javaClass) -> NotebookOutputComponentFactory.Match.NONE // TODO Is the method right? !outputDataKeyClass.isAssignableFrom(outputDataKey.javaClass) -> NotebookOutputComponentFactory.Match.NONE else -> @Suppress("UNCHECKED_CAST") match(component as C, outputDataKey as K) } private fun updateData(newDataKeys: List<NotebookOutputDataKey>): Boolean { val newDataKeyIterator = newDataKeys.iterator() val oldComponentsWithFactories = getComponentsWithFactories().iterator() var isFilled = false for ((idx, pair1) in newDataKeyIterator.zip(oldComponentsWithFactories).withIndex()) { val (newDataKey, pair2) = pair1 val (oldComponent: JComponent, oldFactory: NotebookOutputComponentFactory<*, *>) = pair2 isFilled = when (oldFactory.matchWithTypes(oldComponent, newDataKey)) { NotebookOutputComponentFactory.Match.NONE -> { innerComponent.remove(idx) oldComponent.disposeComponent() val newComponent = createOutputGuessingFactory(newDataKey) if (newComponent != null) { addIntoInnerComponent(newComponent, idx) true } else false } NotebookOutputComponentFactory.Match.COMPATIBLE -> { @Suppress("UNCHECKED_CAST") (oldFactory as NotebookOutputComponentFactory<JComponent, NotebookOutputDataKey>) oldFactory.updateComponent(editor, oldComponent, newDataKey) oldComponent.parent.castSafelyTo<CollapsingComponent>()?.updateStubIfCollapsed() true } NotebookOutputComponentFactory.Match.SAME -> true } || isFilled } for (ignored in oldComponentsWithFactories) { val idx = innerComponent.componentCount - 1 val old = innerComponent.getComponent(idx).let { if (it is CollapsingComponent) it.mainComponent else it } innerComponent.remove(idx) //Must be JComponent because of ``createComponent`` signature (old as JComponent).disposeComponent() } for (outputDataKey in newDataKeyIterator) { val newComponent = createOutputGuessingFactory(outputDataKey) if (newComponent != null) { isFilled = true addIntoInnerComponent(newComponent) } } return isFilled } private fun addIntoInnerComponent(newComponent: NotebookOutputComponentFactory.CreatedComponent<*>, pos: Int = -1) { newComponent.apply { disposable?.let { component.addDisposable(it) } } val collapsingComponent = CollapsingComponent( editor, newComponent.component, newComponent.resizable, newComponent.collapsedTextSupplier, ) innerComponent.add( collapsingComponent, InnerComponent.Constraint(newComponent.widthStretching, newComponent.limitHeight), pos, ) // DS-1972 Without revalidation, the component would be just invalidated, and would be rendered only after anything else requests // for repainting the editor. newComponent.component.revalidate() } private fun <K : NotebookOutputDataKey> createOutputGuessingFactory(outputDataKey: K): NotebookOutputComponentFactory.CreatedComponent<*>? = NotebookOutputComponentFactoryGetter.instance.list.asSequence() .filter { factory -> factory.outputDataKeyClass.isAssignableFrom(outputDataKey.javaClass) } .mapNotNull { factory -> createOutput(@Suppress("UNCHECKED_CAST") (factory as NotebookOutputComponentFactory<*, K>), outputDataKey) } .firstOrNull() private fun <K : NotebookOutputDataKey> createOutput(factory: NotebookOutputComponentFactory<*, K>, outputDataKey: K): NotebookOutputComponentFactory.CreatedComponent<*>? { ApplicationManager.getApplication().messageBus.syncPublisher(OUTPUT_LISTENER).beforeOutputCreated(editor, lines.last) val result = factory.createComponent(editor, outputDataKey)?.also { it.component.outputComponentFactory = factory it.component.gutterPainter = it.gutterPainter } ApplicationManager.getApplication().messageBus.syncPublisher(OUTPUT_LISTENER).outputCreated(editor, lines.last) return result } class Factory : NotebookCellInlayController.Factory { override fun compute( editor: EditorImpl, currentControllers: Collection<NotebookCellInlayController>, intervalIterator: ListIterator<NotebookCellLines.Interval>, ): NotebookCellInlayController? { val interval = intervalIterator.next() if (interval.type != NotebookCellLines.CellType.CODE) return null val outputDataKeys = NotebookOutputDataKeyExtractor.EP_NAME.extensionList.asSequence() .mapNotNull { it.extract(editor, interval) } .firstOrNull() ?.takeIf { it.isNotEmpty() } ?: return null val controller = currentControllers .filterIsInstance<NotebookOutputInlayController>() .maxByOrNull { it.rankCompatibility(outputDataKeys) } ?: NotebookOutputInlayController(this, editor, interval.lines) return controller.takeIf { it.updateData(outputDataKeys) } } } } @Service private class NotebookOutputComponentFactoryGetter : Disposable, Runnable { var list: List<NotebookOutputComponentFactory<*, *>> = emptyList() get() = field.ifEmpty { field = makeValidatedList() field } private set init { NotebookOutputComponentFactory.EP_NAME.addChangeListener(this, this) } override fun run() { list = emptyList() } override fun dispose(): Unit = Unit private fun makeValidatedList(): MutableList<NotebookOutputComponentFactory<*, *>> { val newList = mutableListOf<NotebookOutputComponentFactory<*, *>>() for (extension in NotebookOutputComponentFactory.EP_NAME.extensionList) { val collidingExtension = newList .firstOrNull { ( it.componentClass.isAssignableFrom(extension.componentClass) || extension.componentClass.isAssignableFrom(it.componentClass) ) && ( it.outputDataKeyClass.isAssignableFrom(extension.outputDataKeyClass) || extension.outputDataKeyClass.isAssignableFrom(it.outputDataKeyClass) ) } if (collidingExtension != null) { LOG.error("Can't register $extension: it clashes with $collidingExtension by using similar component and data key classes.") } else { newList += extension } } return newList } companion object { private val LOG = logger<NotebookOutputComponentFactoryGetter>() @JvmStatic val instance: NotebookOutputComponentFactoryGetter get() = service() } } private fun <A, B> Iterator<A>.zip(other: Iterator<B>): Iterator<Pair<A, B>> = object : Iterator<Pair<A, B>> { override fun hasNext(): Boolean = [email protected]() && other.hasNext() override fun next(): Pair<A, B> = [email protected]() to other.next() } private var JComponent.outputComponentFactory: NotebookOutputComponentFactory<*, *>? by SwingClientProperty("outputComponentFactory")
apache-2.0
bb31e27e14c0d565d3f03cf6c3736a94
39.1875
142
0.72535
5.039185
false
false
false
false
google/intellij-community
plugins/git4idea/src/git4idea/commands/GitHttpLoginDialog.kt
4
6963
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.commands import com.google.common.annotations.VisibleForTesting import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.NlsSafe import com.intellij.ui.UIBundle import com.intellij.ui.components.* import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.dsl.builder.EMPTY_LABEL import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.bind import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.layout.* import com.intellij.util.AuthData import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import git4idea.i18n.GitBundle import git4idea.remote.InteractiveGitHttpAuthDataProvider import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.JComponent class GitHttpLoginDialog @JvmOverloads constructor(project: Project, url: @NlsSafe String, rememberPassword: Boolean = true, username: @NlsSafe String? = null, editableUsername: Boolean = true, private val showActionForCredHelper: Boolean = false) : DialogWrapper(project, true) { private val usernameField = JBTextField(username, 20).apply { isEditable = editableUsername } private val passwordField = JBPasswordField() private val rememberCheckbox = JBCheckBox(UIBundle.message("auth.remember.cb"), rememberPassword) private val additionalProvidersButton = JBOptionButton(null, null).apply { isVisible = false } private var useCredentialHelper = false private lateinit var dialogPanel: DialogPanel companion object { const val USE_CREDENTIAL_HELPER_CODE = NEXT_USER_EXIT_CODE } var externalAuthData: AuthData? = null private set init { title = GitBundle.message("login.dialog.label.login.to.url", url) setOKButtonText(GitBundle.message("login.dialog.button.login")) init() } override fun createCenterPanel(): JComponent { if (!showActionForCredHelper) { dialogPanel = panel { row(GitBundle.message("login.dialog.prompt.enter.credentials")) {} buildCredentialsPanel() } } else { dialogPanel = panel { buttonsGroup { lateinit var rbCredentials: JBRadioButton row { rbCredentials = radioButton(GitBundle.message("login.dialog.select.login.way.credentials"), false) .component } indent{ buildCredentialsPanel() }.enabledIf(rbCredentials.selected) row { radioButton(GitBundle.message("login.dialog.select.login.way.use.helper"), true).also { it.component.addActionListener { isOKActionEnabled = true } } } }.bind(::useCredentialHelper) } } return dialogPanel } private fun Panel.buildCredentialsPanel() { row(GitBundle.message("login.dialog.username.label")) { cell(usernameField).horizontalAlign(HorizontalAlign.FILL) } row(GitBundle.message("login.dialog.password.label")) { cell(passwordField).horizontalAlign(HorizontalAlign.FILL) } row(EMPTY_LABEL) { cell(rememberCheckbox) } } override fun doOKAction() { dialogPanel.apply() if (useCredentialHelper) { close(USE_CREDENTIAL_HELPER_CODE, false) return } super.doOKAction() } override fun doValidateAll(): List<ValidationInfo> { dialogPanel.apply() if (useCredentialHelper) { return emptyList() } return listOfNotNull( if (username.isBlank()) ValidationInfo(GitBundle.message("login.dialog.error.username.cant.be.empty"), usernameField) else null, if (passwordField.password.isEmpty()) ValidationInfo(GitBundle.message("login.dialog.error.password.cant.be.empty"), passwordField) else null ) } override fun createSouthAdditionalPanel(): Wrapper = Wrapper(additionalProvidersButton) .apply { border = JBUI.Borders.emptyRight(UIUtil.DEFAULT_HGAP) } override fun getPreferredFocusedComponent(): JComponent = if (username.isBlank()) usernameField else passwordField fun setInteractiveDataProviders(providers: Map<String, InteractiveGitHttpAuthDataProvider>) { if (providers.isEmpty()) return val actions: List<AbstractAction> = providers.map { object : AbstractAction(GitBundle.message("login.dialog.login.with.selected.provider", it.key)) { override fun actionPerformed(e: ActionEvent?) { val authData = it.value.getAuthData([email protected]) if (authData != null) { if (authData.password != null) { externalAuthData = authData [email protected](0, true) } else { usernameField.text = authData.login } } } } } additionalProvidersButton.action = actions.first() if (actions.size > 1) { additionalProvidersButton.options = actions.subList(1, actions.size).toTypedArray() } additionalProvidersButton.isVisible = true } @set:VisibleForTesting var username: String get() = usernameField.text internal set(value) { usernameField.text = value } @set:VisibleForTesting var password: String get() = String(passwordField.password!!) internal set(value) { passwordField.text = value } @set:VisibleForTesting var rememberPassword: Boolean get() = rememberCheckbox.isSelected internal set(value) { rememberCheckbox.isSelected = value } } @Suppress("HardCodedStringLiteral") class TestGitHttpLoginDialogAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { e.project?.let { val gitHttpLoginDialog = GitHttpLoginDialog(it, "http://google.com", showActionForCredHelper = true) gitHttpLoginDialog.show() if (gitHttpLoginDialog.exitCode == GitHttpLoginDialog.USE_CREDENTIAL_HELPER_CODE) { Messages.showMessageDialog(e.project,"Credential selected", "Git login test", null) } else { Messages.showMessageDialog(e.project, "Regular login", "Git login test", null) } } } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } }
apache-2.0
e20fb91ae0c5cac968f2fbfb8d500e36
35.455497
140
0.686917
4.629654
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromUsageFix.kt
1
15690
// 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.quickfix.createFromUsage.createCallable import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.ide.util.EditorHelper import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassifierDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.quickfix.KotlinCrossLanguageQuickFixAction import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.* import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.isAbstract import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.descriptorUtil.classValueType import org.jetbrains.kotlin.types.typeUtil.isTypeParameter import java.lang.ref.WeakReference class CreateExtensionCallableFromUsageFix<E : KtElement>( originalExpression: E, private val callableInfosFactory: (E) -> List<CallableInfo>? ) : CreateCallableFromUsageFixBase<E>(originalExpression, true), LowPriorityAction { init { init() } override val callableInfos: List<CallableInfo> get() = element?.let { callableInfosFactory(it) } ?: emptyList() } class CreateCallableFromUsageFix<E : KtElement>( originalExpression: E, private val callableInfosFactory: (E) -> List<CallableInfo>? ) : CreateCallableFromUsageFixBase<E>(originalExpression, false) { init { init() } override val callableInfos: List<CallableInfo> get() = element?.let { callableInfosFactory(it) } ?: emptyList() } abstract class AbstractCreateCallableFromUsageFixWithTextAndFamilyName<E : KtElement>( providedText: String, @Nls private val familyName: String, originalExpression: E ): CreateCallableFromUsageFixBase<E>(originalExpression, false) { override val calculatedText: String = providedText override fun getFamilyName(): String = familyName } abstract class CreateCallableFromUsageFixBase<E : KtElement>( originalExpression: E, val isExtension: Boolean ) : KotlinCrossLanguageQuickFixAction<E>(originalExpression) { private var callableInfoReference: WeakReference<List<CallableInfo>>? = null protected open val callableInfos: List<CallableInfo> get() = listOfNotNull(callableInfo) protected open val callableInfo: CallableInfo? get() = throw UnsupportedOperationException() private fun callableInfos(): List<CallableInfo> = callableInfoReference?.get() ?: callableInfos.also { callableInfoReference = WeakReference(it) } private fun notEmptyCallableInfos() = callableInfos().takeIf { it.isNotEmpty() } private var initialized: Boolean = false protected open val calculatedText: String by lazy(fun(): String { val element = element ?: return "" val callableInfos = notEmptyCallableInfos() ?: return "" val callableInfo = callableInfos.first() val receiverTypeInfo = callableInfo.receiverTypeInfo val renderedCallablesByKind = callableInfos.groupBy({ it.kind }, valueTransform = { buildString { if (it.name.isNotEmpty()) { val receiverType = if (!receiverTypeInfo.isOfThis) { CallableBuilderConfiguration(callableInfos, element, isExtension = isExtension) .createBuilder() .computeTypeCandidates(receiverTypeInfo) .firstOrNull { candidate -> if (it.isAbstract) candidate.theType.isAbstract() else true } ?.theType } else null val staticContextRequired = receiverTypeInfo.staticContextRequired if (receiverType != null) { if (isExtension && !staticContextRequired) { val receiverTypeText = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(receiverType) val isFunctionType = receiverType.constructor.declarationDescriptor is FunctionClassDescriptor append(if (isFunctionType) "($receiverTypeText)" else receiverTypeText).append('.') } else { receiverType.constructor.declarationDescriptor?.let { val companionText = if (staticContextRequired && it !is JavaClassDescriptor) ".Companion" else "" val receiverText = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderClassifierName(it) + companionText append(receiverText).append('.') } } } append(it.name) } } }) return buildString { append(KotlinBundle.message("text.create")) append(' ') val isAbstract = callableInfos.any { it.isAbstract } if (!isAbstract) { if (isExtension) { append(KotlinBundle.message("text.extension")) append(' ') } else if (receiverTypeInfo != TypeInfo.Empty) { append(KotlinBundle.message("text.member")) append(' ') } } else { append(KotlinBundle.message("text.abstract")) append(' ') } renderedCallablesByKind.entries.joinTo(this) { val kind = it.key val names = it.value.filter { name -> name.isNotEmpty() } val pluralIndex = if (names.size > 1) 2 else 1 val kindText = when(kind) { CallableKind.FUNCTION -> KotlinBundle.message("text.function.0", pluralIndex) CallableKind.CONSTRUCTOR -> KotlinBundle.message("text.secondary.constructor") CallableKind.PROPERTY -> KotlinBundle.message("text.property.0", pluralIndex) else -> throw AssertionError("Unexpected callable info: $it") } if (names.isEmpty()) kindText else "$kindText ${names.joinToString { name -> "'$name'" }}" } } }) protected open val calculatedAvailableImpl: Boolean by lazy(fun(): Boolean { val element = element ?: return false val callableInfos = notEmptyCallableInfos() ?: return false val callableInfo = callableInfos.first() val receiverInfo = callableInfo.receiverTypeInfo if (receiverInfo == TypeInfo.Empty) { if (callableInfos.any { it is PropertyInfo && it.possibleContainers.isEmpty() }) return false return !isExtension } val callableBuilder = CallableBuilderConfiguration(callableInfos, element, isExtension = isExtension).createBuilder() val receiverTypeCandidates = callableBuilder.computeTypeCandidates(receiverInfo) val propertyInfo = callableInfos.firstOrNull { it is PropertyInfo } as PropertyInfo? val isFunction = callableInfos.any { it.kind == CallableKind.FUNCTION } return receiverTypeCandidates.any { val declaration = getDeclarationIfApplicable(element.project, it, receiverInfo.staticContextRequired) val insertToJavaInterface = declaration is PsiClass && declaration.isInterface when { !isExtension && propertyInfo != null && insertToJavaInterface && (!receiverInfo.staticContextRequired || propertyInfo.writable) -> false isFunction && insertToJavaInterface && receiverInfo.staticContextRequired -> false !isExtension && declaration is KtTypeParameter -> false propertyInfo != null && !propertyInfo.isAbstract && declaration is KtClass && declaration.isInterface() -> false else -> declaration != null } } }) /** * Has to be invoked manually from final class ctor (as all final class properties have to be initialized) */ protected fun init() { check(!initialized) { "${javaClass.simpleName} is already initialized" } this.element ?: return val callableInfos = callableInfos() if (callableInfos.size > 1) { val receiverSet = callableInfos.mapTo(HashSet()) { it.receiverTypeInfo } if (receiverSet.size > 1) throw AssertionError("All functions must have common receiver: $receiverSet") val possibleContainerSet = callableInfos.mapTo(HashSet()) { it.possibleContainers } if (possibleContainerSet.size > 1) throw AssertionError("All functions must have common containers: $possibleContainerSet") } initializeLazyProperties() } @Suppress("UNUSED_VARIABLE") private fun initializeLazyProperties() { // enforce lazy properties be calculated as QuickFix is created on a bg thread val text = calculatedText val availableImpl = calculatedAvailableImpl initialized = true } private fun getDeclaration(descriptor: ClassifierDescriptor, project: Project): PsiElement? { if (descriptor is FunctionClassDescriptor) { val contextElement = element ?: error("Context element is not found") val psiFactory = KtPsiFactory(project) val syntheticClass = psiFactory.createClass(IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(descriptor)) return psiFactory.createFile("${descriptor.name.asString()}.kt", "").add(syntheticClass) } return DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) } private fun getDeclarationIfApplicable(project: Project, candidate: TypeCandidate, staticContextRequired: Boolean): PsiElement? { val descriptor = candidate.theType.constructor.declarationDescriptor ?: return null if (isExtension && staticContextRequired && descriptor is JavaClassDescriptor) return null val declaration = getDeclaration(descriptor, project) ?: return null if (declaration !is KtClassOrObject && declaration !is KtTypeParameter && declaration !is PsiClass) return null return if ((isExtension && !staticContextRequired) || declaration.canRefactor()) declaration else null } private fun checkIsInitialized() { check(initialized) { "${javaClass.simpleName} is not initialized" } } override fun getText(): String { checkIsInitialized() element ?: return "" return calculatedText } override fun getFamilyName(): String = KotlinBundle.message("fix.create.from.usage.family") override fun startInWriteAction(): Boolean = false override fun isAvailableImpl(project: Project, editor: Editor?, file: PsiFile): Boolean { checkIsInitialized() element ?: return false return calculatedAvailableImpl } override fun invokeImpl(project: Project, editor: Editor?, file: PsiFile) { checkIsInitialized() val element = element ?: return val callableInfos = callableInfos() val callableInfo = callableInfos.first() val fileForBuilder = element.containingKtFile val editorForBuilder = EditorHelper.openInEditor(element) if (editorForBuilder != editor) { NavigationUtil.activateFileWithPsiElement(element) } val callableBuilder = CallableBuilderConfiguration(callableInfos, element as KtElement, fileForBuilder, editorForBuilder, isExtension).createBuilder() fun runBuilder(placement: () -> CallablePlacement) { project.executeCommand(text) { callableBuilder.placement = placement() callableBuilder.build() } } if (callableInfo is ConstructorInfo) { runBuilder { CallablePlacement.NoReceiver(callableInfo.targetClass) } } val popupTitle = KotlinBundle.message("choose.target.class.or.interface") val receiverTypeInfo = callableInfo.receiverTypeInfo val receiverTypeCandidates = callableBuilder.computeTypeCandidates(receiverTypeInfo).let { if (callableInfo.isAbstract) it.filter { it.theType.isAbstract() } else if (!isExtension && receiverTypeInfo != TypeInfo.Empty) it.filter { !it.theType.isTypeParameter() } else it } if (receiverTypeCandidates.isNotEmpty()) { val staticContextRequired = receiverTypeInfo.staticContextRequired val containers = receiverTypeCandidates .mapNotNull { candidate -> getDeclarationIfApplicable(project, candidate, staticContextRequired)?.let { candidate to it } } chooseContainerElementIfNecessary(containers, editorForBuilder, popupTitle, false, { it.second }) { runBuilder { val receiverClass = it.second as? KtClass if (staticContextRequired && receiverClass?.isWritable == true) { val hasCompanionObject = receiverClass.companionObjects.isNotEmpty() val companionObject = runWriteAction { val companionObject = receiverClass.getOrCreateCompanionObject() if (!hasCompanionObject && [email protected]) companionObject.body?.delete() companionObject } val classValueType = (companionObject.descriptor as? ClassDescriptor)?.classValueType val receiverTypeCandidate = if (classValueType != null) TypeCandidate(classValueType) else it.first CallablePlacement.WithReceiver(receiverTypeCandidate) } else { CallablePlacement.WithReceiver(it.first) } } } } else { assert(receiverTypeInfo == TypeInfo.Empty) { "No receiver type candidates: ${element.text} in ${file.text}" } chooseContainerElementIfNecessary(callableInfo.possibleContainers, editorForBuilder, popupTitle, true) { val container = if (it is KtClassBody) it.parent as KtClassOrObject else it runBuilder { CallablePlacement.NoReceiver(container) } } } } }
apache-2.0
25b83cf88088f803feab71d991d61294
45.976048
158
0.654621
5.726277
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/highlight/HaskellHighlighter.kt
1
5914
package org.jetbrains.haskell.highlight import com.intellij.lang.annotation.HighlightSeverity import com.intellij.lexer.Lexer import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.openapi.options.OptionsBundle import com.intellij.openapi.util.Pair import com.intellij.psi.StringEscapesTokenTypes import com.intellij.psi.tree.IElementType import gnu.trove.THashMap import org.jetbrains.haskell.parser.lexer.* import org.jetbrains.haskell.parser.HaskellTokenType import java.awt.* import org.jetbrains.haskell.parser.token.* import org.jetbrains.grammar.HaskellLexerTokens open class HaskellHighlighter : SyntaxHighlighterBase() { companion object { val HASKELL_BRACKETS: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_BRACKETS", DefaultLanguageHighlighterColors.BRACES) val HASKELL_CLASS: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_CLASS") val HASKELL_CONSTRUCTOR: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_CONSTRUCTOR") val HASKELL_CURLY: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_CURLY", DefaultLanguageHighlighterColors.BRACES) val HASKELL_DOUBLE_COLON: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_DOUBLE_COLON") val HASKELL_EQUAL: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_EQUAL", DefaultLanguageHighlighterColors.IDENTIFIER) val HASKELL_KEYWORD: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD) val HASKELL_PARENTHESIS: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_PARENTHESIS", DefaultLanguageHighlighterColors.PARENTHESES) val HASKELL_STRING_LITERAL: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_STRING_LITERAL", DefaultLanguageHighlighterColors.STRING) val HASKELL_SIGNATURE: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_SIGNATURE") val HASKELL_COMMENT: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT) val HASKELL_PRAGMA: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_PAGMA", DefaultLanguageHighlighterColors.LINE_COMMENT) val HASKELL_NUMBER: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_NUMBER", DefaultLanguageHighlighterColors.NUMBER) val HASKELL_TYPE: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_TYPE") val HASKELL_OPERATOR: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_OPERATOR", DefaultLanguageHighlighterColors.IDENTIFIER) val HASKELL_IDENTIFIER: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HASKELL_IDENTIFIER", DefaultLanguageHighlighterColors.IDENTIFIER) } override fun getHighlightingLexer(): Lexer { return HaskellLexer() } override fun getTokenHighlights(tokenType: IElementType?): Array<TextAttributesKey> { return SyntaxHighlighterBase.pack(keys1.get(tokenType)) } private val keys1: MutableMap<IElementType, TextAttributesKey> val DISPLAY_NAMES: MutableMap<TextAttributesKey, Pair<String, HighlightSeverity>> = THashMap<TextAttributesKey, Pair<String, HighlightSeverity>>(4) init { keys1 = THashMap<IElementType, TextAttributesKey>() keys1.put(END_OF_LINE_COMMENT, HASKELL_COMMENT) keys1.put(BLOCK_COMMENT, HASKELL_COMMENT) for (keyword in org.jetbrains.haskell.parser.token.KEYWORDS) { keys1.put(keyword, HASKELL_KEYWORD) } keys1.put(PRAGMA, HASKELL_PRAGMA) // PARENTHESIS keys1.put(HaskellLexerTokens.OPAREN, HASKELL_PARENTHESIS) keys1.put(HaskellLexerTokens.CPAREN, HASKELL_PARENTHESIS) keys1.put(HaskellLexerTokens.OCURLY, HASKELL_CURLY) keys1.put(HaskellLexerTokens.CCURLY, HASKELL_CURLY) keys1.put(HaskellLexerTokens.OBRACK, HASKELL_BRACKETS) keys1.put(HaskellLexerTokens.CBRACK, HASKELL_BRACKETS) keys1.put(HaskellLexerTokens.DCOLON, HASKELL_DOUBLE_COLON) keys1.put(HaskellLexerTokens.EQUAL, HASKELL_EQUAL) keys1.put(HaskellLexerTokens.AT, HASKELL_IDENTIFIER) keys1.put(HaskellLexerTokens.UNDERSCORE, HASKELL_IDENTIFIER) keys1.put(HaskellLexerTokens.VARID, HASKELL_IDENTIFIER) keys1.put(HaskellLexerTokens.QVARID, HASKELL_IDENTIFIER) keys1.put(HaskellLexerTokens.CONID, HASKELL_CONSTRUCTOR) keys1.put(HaskellLexerTokens.QCONID, HASKELL_CONSTRUCTOR) keys1.put(HaskellLexerTokens.CONSYM, HASKELL_CONSTRUCTOR) keys1.put(HaskellLexerTokens.COLON, HASKELL_CONSTRUCTOR) keys1.put(HaskellLexerTokens.VARSYM, HASKELL_OPERATOR) keys1.put(HaskellLexerTokens.MINUS, HASKELL_OPERATOR) keys1.put(HaskellLexerTokens.STRING, HASKELL_STRING_LITERAL) keys1.put(HaskellLexerTokens.CHAR, HASKELL_STRING_LITERAL) keys1.put(HaskellLexerTokens.INTEGER, HASKELL_NUMBER) keys1.put(HaskellLexerTokens.DARROW, HASKELL_CLASS) } init { DISPLAY_NAMES.put(HASKELL_KEYWORD, Pair<String, HighlightSeverity>("Property value", null)) DISPLAY_NAMES.put(HASKELL_COMMENT, Pair<String, HighlightSeverity>("Comment", null)) } }
apache-2.0
44b1c7ae4b76c28d221dffae69fadeb8
46.693548
151
0.745181
5.085125
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/idea/ApplicationLoader.kt
1
17164
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("ApplicationLoader") @file:Internal @file:Suppress("ReplacePutWithAssignment") package com.intellij.idea import com.intellij.diagnostic.* import com.intellij.history.LocalHistory import com.intellij.icons.AllIcons import com.intellij.ide.* import com.intellij.ide.plugins.* import com.intellij.ide.plugins.marketplace.statistics.PluginManagerUsageCollector import com.intellij.ide.plugins.marketplace.statistics.enums.DialogAcceptanceResultEnum import com.intellij.ide.ui.IconMapLoader import com.intellij.ide.ui.LafManager import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.application.impl.RawSwingDispatcher import com.intellij.openapi.components.service import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl import com.intellij.openapi.extensions.impl.findByIdOrFromInstance import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.updateSettings.impl.UpdateSettings import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.SystemPropertyBean import com.intellij.openapi.util.io.OSAgnosticPathUtil import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.ManagingFS import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager import com.intellij.ui.AnimatedIcon import com.intellij.ui.AppIcon import com.intellij.util.PlatformUtils import com.intellij.util.io.URLUtil import com.intellij.util.io.createDirectories import com.intellij.util.lang.ZipFilePool import com.intellij.util.ui.AsyncProcessIcon import kotlinx.coroutines.* import net.miginfocom.layout.PlatformDefaults import org.jetbrains.annotations.ApiStatus.Internal import org.jetbrains.annotations.VisibleForTesting import java.io.IOException import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.concurrent.* import java.util.concurrent.CancellationException import java.util.function.BiFunction import kotlin.system.exitProcess @Suppress("SSBasedInspection") private val LOG = Logger.getInstance("#com.intellij.idea.ApplicationLoader") fun initApplication(rawArgs: List<String>, appDeferred: Deferred<Any>) { runBlocking(rootTask()) { doInitApplication(rawArgs, appDeferred) } } private suspend fun doInitApplication(rawArgs: List<String>, appDeferred: Deferred<Any>) { val initAppActivity = StartUpMeasurer.appInitPreparationActivity!!.endAndStart("app initialization") val pluginSet = initAppActivity.runChild("plugin descriptor init waiting") { PluginManagerCore.getInitPluginFuture().await() } val (app, initLafJob) = initAppActivity.runChild("app waiting") { @Suppress("UNCHECKED_CAST") appDeferred.await() as Pair<ApplicationImpl, Job?> } initAppActivity.runChild("app component registration") { app.registerComponents(modules = pluginSet.getEnabledModules(), app = app, precomputedExtensionModel = null, listenerCallbacks = null) } withContext(Dispatchers.IO) { initConfigurationStore(app) } val loadIconMapping: Job = if (app.isHeadlessEnvironment) { CompletableDeferred(value = Unit) } else { app.coroutineScope.launchAndMeasure("icon mapping loading", Dispatchers.IO) { try { service<IconMapLoader>().preloadIconMapping() } catch (e: CancellationException) { throw e } catch (e: Throwable) { LOG.error(e) } } } coroutineScope { // LaF must be initialized before app init because icons maybe requested and as result, // scale must be already initialized (especially important for Linux) runActivity("init laf waiting") { initLafJob?.join() } // executed in main thread launch { loadIconMapping.join() val lafManagerDeferred = launch(CoroutineName("laf initialization") + RawSwingDispatcher) { // don't wait for result - we just need to trigger initialization if not yet created app.getServiceAsync(LafManager::class.java) } if (!app.isHeadlessEnvironment) { // preload only when LafManager is ready lafManagerDeferred.join() app.getServiceAsync(EditorColorsManager::class.java) } } withContext(Dispatchers.Default) { val args = processProgramArguments(rawArgs) val deferredStarter = runActivity("app starter creation") { createAppStarterAsync(args) } initApplicationImpl(args = args, initAppActivity = initAppActivity, pluginSet = pluginSet, app = app, deferredStarter = deferredStarter) } } } private suspend fun initApplicationImpl(args: List<String>, initAppActivity: Activity, pluginSet: PluginSet, app: ApplicationImpl, deferredStarter: Deferred<ApplicationStarter>) { val appInitializedListeners = coroutineScope { preloadCriticalServices(app) app.preloadServices(modules = pluginSet.getEnabledModules(), activityPrefix = "", syncScope = this) launch { initAppActivity.runChild("old component init task creating", app::createInitOldComponentsTask)?.let { loadComponentInEdtTask -> val placeOnEventQueueActivity = initAppActivity.startChild("place on event queue") withContext(RawSwingDispatcher) { placeOnEventQueueActivity.end() loadComponentInEdtTask() } } StartUpMeasurer.setCurrentState(LoadingState.COMPONENTS_LOADED) } runActivity("app init listener preload") { getAppInitializedListeners(app) } } val asyncScope = app.coroutineScope coroutineScope { initAppActivity.runChild("app initialized callback") { callAppInitialized(appInitializedListeners, asyncScope) } // doesn't block app start-up asyncScope.runPostAppInitTasks(app) } initAppActivity.end() asyncScope.launch { addActivateAndWindowsCliListeners() } val starter = deferredStarter.await() if (starter.requiredModality == ApplicationStarter.NOT_IN_EDT) { if (starter is ModernApplicationStarter) { starter.start(args) } else { // todo https://youtrack.jetbrains.com/issue/IDEA-298594 CompletableFuture.runAsync { starter.main(args) } } } else { withContext(Dispatchers.EDT) { (TransactionGuard.getInstance() as TransactionGuardImpl).performUserActivity { starter.main(args) } } } // no need to use pool once started ZipFilePool.POOL = null } fun CoroutineScope.preloadCriticalServices(app: ApplicationImpl) { launch { // LocalHistory wants ManagingFS, it should be fixed somehow, but for now, to avoid thread contention, preload it in a controlled manner app.getServiceAsync(ManagingFS::class.java).join() // PlatformVirtualFileManager also wants ManagingFS launch { app.getServiceAsync(VirtualFileManager::class.java) } launch { app.getServiceAsyncIfDefined(LocalHistory::class.java) } } launch { // required for indexing tasks (see JavaSourceModuleNameIndex for example) // FileTypeManager by mistake uses PropertiesComponent instead of own state - it should be fixed someday app.getServiceAsync(PropertiesComponent::class.java).join() app.getServiceAsync(FileTypeManager::class.java).join() // ProjectJdkTable wants FileTypeManager launch { // and VirtualFilePointerManager app.getServiceAsync(VirtualFilePointerManager::class.java).join() app.getServiceAsync(ProjectJdkTable::class.java) } // wants PropertiesComponent launch { app.getServiceAsync(DebugLogManager::class.java) } } } fun getAppInitializedListeners(app: Application): List<ApplicationInitializedListener> { val extensionArea = app.extensionArea as ExtensionsAreaImpl val point = extensionArea.getExtensionPoint<ApplicationInitializedListener>("com.intellij.applicationInitializedListener") val result = point.extensionList point.reset() return result } private fun CoroutineScope.runPostAppInitTasks(app: ApplicationImpl) { launch(CoroutineName("create locator file") + Dispatchers.IO) { createAppLocatorFile() } if (!AppMode.isLightEdit()) { // this functionality should be used only by plugin functionality that is used after start-up launch(CoroutineName("system properties setting")) { SystemPropertyBean.initSystemProperties() } } launch { val noteAccepted = PluginManagerCore.isThirdPartyPluginsNoteAccepted() if (noteAccepted == true) { UpdateSettings.getInstance().isThirdPartyPluginsAllowed = true PluginManagerUsageCollector.thirdPartyAcceptanceCheck(DialogAcceptanceResultEnum.ACCEPTED) } else if (noteAccepted == false) { PluginManagerUsageCollector.thirdPartyAcceptanceCheck(DialogAcceptanceResultEnum.DECLINED) } } if (app.isHeadlessEnvironment) { return } launch(CoroutineName("icons preloading") + Dispatchers.IO) { if (app.isInternal) { IconLoader.setStrictGlobally(true) } AsyncProcessIcon("") AnimatedIcon.Blinking(AllIcons.Ide.FatalError) AnimatedIcon.FS() } launch { // IDEA-170295 PlatformDefaults.setLogicalPixelBase(PlatformDefaults.BASE_FONT_SIZE) } if (!app.isUnitTestMode && System.getProperty("enable.activity.preloading", "true").toBoolean()) { val extensionPoint = app.extensionArea.getExtensionPoint<PreloadingActivity>("com.intellij.preloadingActivity") val isDebugEnabled = LOG.isDebugEnabled ExtensionPointName<PreloadingActivity>("com.intellij.preloadingActivity").processExtensions { preloadingActivity, pluginDescriptor -> launch { executePreloadActivity(preloadingActivity, pluginDescriptor, isDebugEnabled) } } extensionPoint.reset() } } // `ApplicationStarter` is an extension, so to find a starter, extensions must be registered first private fun CoroutineScope.createAppStarterAsync(args: List<String>): Deferred<ApplicationStarter> { val first = args.firstOrNull() // first argument maybe a project path if (first == null) { return async { IdeStarter() } } else if (args.size == 1 && OSAgnosticPathUtil.isAbsolute(first)) { return async { createDefaultAppStarter() } } val starter = findStarter(first) ?: createDefaultAppStarter() if (AppMode.isHeadless() && !starter.isHeadless) { @Suppress("DEPRECATION") val commandName = starter.commandName val message = IdeBundle.message( "application.cannot.start.in.a.headless.mode", when { starter is IdeStarter -> 0 commandName != null -> 1 else -> 2 }, commandName, starter.javaClass.name, if (args.isEmpty()) 0 else 1, args.joinToString(" ") ) StartupErrorReporter.showMessage(IdeBundle.message("main.startup.error"), message, true) exitProcess(AppExitCodes.NO_GRAPHICS) } // must be executed before container creation starter.premain(args) return CompletableDeferred(value = starter) } private fun createDefaultAppStarter(): ApplicationStarter { return if (PlatformUtils.getPlatformPrefix() == "LightEdit") IdeStarter.StandaloneLightEditStarter() else IdeStarter() } @VisibleForTesting internal fun createAppLocatorFile() { val locatorFile = Path.of(PathManager.getSystemPath(), ApplicationEx.LOCATOR_FILE_NAME) try { locatorFile.parent?.createDirectories() Files.writeString(locatorFile, PathManager.getHomePath(), StandardCharsets.UTF_8) } catch (e: IOException) { LOG.warn("Can't store a location in '$locatorFile'", e) } } private fun addActivateAndWindowsCliListeners() { addExternalInstanceListener { rawArgs -> LOG.info("External instance command received") val (args, currentDirectory) = if (rawArgs.isEmpty()) emptyList<String>() to null else rawArgs.subList(1, rawArgs.size) to rawArgs[0] @Suppress("DEPRECATION") ApplicationManager.getApplication().coroutineScope.async { handleExternalCommand(args, currentDirectory).future.await() } } EXTERNAL_LISTENER = BiFunction { currentDirectory, args -> LOG.info("External Windows command received") runBlocking(Dispatchers.Default) { val result = handleExternalCommand(args.asList(), currentDirectory) try { result.future.await().exitCode } catch (e: Exception) { AppExitCodes.ACTIVATE_ERROR } } } ApplicationManager.getApplication().messageBus.simpleConnect().subscribe(AppLifecycleListener.TOPIC, object : AppLifecycleListener { override fun appWillBeClosed(isRestart: Boolean) { addExternalInstanceListener { CompletableDeferred(CliResult(AppExitCodes.ACTIVATE_DISPOSING, IdeBundle.message("activation.shutting.down"))) } EXTERNAL_LISTENER = BiFunction { _, _ -> AppExitCodes.ACTIVATE_DISPOSING } } }) } private suspend fun handleExternalCommand(args: List<String>, currentDirectory: String?): CommandLineProcessorResult { if (args.isNotEmpty() && args[0].contains(URLUtil.SCHEME_SEPARATOR)) { val result = CommandLineProcessorResult(project = null, result = CommandLineProcessor.processProtocolCommand(args[0])) withContext(Dispatchers.EDT) { if (!result.showErrorIfFailed()) { CommandLineProcessor.findVisibleFrame()?.let { frame -> AppIcon.getInstance().requestFocus(frame) } } } return result } else { return CommandLineProcessor.processExternalCommandLine(args, currentDirectory, focusApp = true) } } fun findStarter(key: String): ApplicationStarter? { @Suppress("DEPRECATION") return ApplicationStarter.EP_NAME.findByIdOrFromInstance(key) { it.commandName } } fun initConfigurationStore(app: ApplicationImpl) { var activity = StartUpMeasurer.startActivity("beforeApplicationLoaded") val configPath = PathManager.getConfigDir() for (listener in ApplicationLoadListener.EP_NAME.lazySequence()) { try { (listener ?: break).beforeApplicationLoaded(app, configPath) } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { LOG.error(e) } } activity = activity.endAndStart("init app store") // we set it after beforeApplicationLoaded call, because the app store can depend on stream provider state app.stateStore.setPath(configPath) StartUpMeasurer.setCurrentState(LoadingState.CONFIGURATION_STORE_INITIALIZED) activity.end() } /** * The method looks for `-Dkey=value` program arguments and stores some of them in system properties. * We should use it for a limited number of safe keys; one of them is a list of required plugins. */ @Suppress("SpellCheckingInspection") private fun processProgramArguments(args: List<String>): List<String> { if (args.isEmpty()) { return emptyList() } // no need to have it as a file-level constant - processProgramArguments called at most once. val safeJavaEnvParameters = arrayOf(JetBrainsProtocolHandler.REQUIRED_PLUGINS_KEY) val arguments = mutableListOf<String>() for (arg in args) { if (arg.startsWith("-D")) { val keyValue = arg.substring(2).split('=') if (keyValue.size == 2 && safeJavaEnvParameters.contains(keyValue[0])) { System.setProperty(keyValue[0], keyValue[1]) continue } } if (!CommandLineArgs.isKnownArgument(arg)) { arguments.add(arg) } } return arguments } fun CoroutineScope.callAppInitialized(listeners: List<ApplicationInitializedListener>, asyncScope: CoroutineScope) { for (listener in listeners) { launch { listener.execute(asyncScope) } } } private suspend fun executePreloadActivity(activity: PreloadingActivity, descriptor: PluginDescriptor?, isDebugEnabled: Boolean) { val measureActivity = if (descriptor == null) { null } else { StartUpMeasurer.startActivity(activity.javaClass.name, ActivityCategory.PRELOAD_ACTIVITY, descriptor.pluginId.idString) } try { activity.execute() if (isDebugEnabled) { LOG.debug("${activity.javaClass.name} finished") } } catch (e: CancellationException) { throw e } catch (e: Throwable) { LOG.error("cannot execute preloading activity ${activity.javaClass.name}", e) } finally { measureActivity?.end() } }
apache-2.0
469887bd38d20f9fba09aa8717b428c2
34.46281
148
0.728735
4.630159
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/data/mobile_tiers/repository/LightSkuRepositoryImpl.kt
1
1915
package org.stepik.android.data.mobile_tiers.repository import io.reactivex.Single import org.stepik.android.data.billing.source.BillingRemoteDataSource import org.stepik.android.data.mobile_tiers.source.LightSkuCacheDataSource import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.mobile_tiers.model.LightSku import org.stepik.android.domain.mobile_tiers.repository.LightSkuRepository import ru.nobird.android.domain.rx.doCompletableOnSuccess import javax.inject.Inject class LightSkuRepositoryImpl @Inject constructor( private val lightSkuCacheDataSource: LightSkuCacheDataSource, private val billingRemoteDataSource: BillingRemoteDataSource ) : LightSkuRepository { override fun getLightInventory(productType: String, skuIds: List<String>, dataSourceType: DataSourceType): Single<List<LightSku>> { val remote = remoteAction(productType, skuIds) val cache = lightSkuCacheDataSource .getLightInventory(skuIds) return when (dataSourceType) { DataSourceType.REMOTE -> remote .onErrorResumeNext(cache) DataSourceType.CACHE -> cache.flatMap { cachedItems -> val newIds = (skuIds.toList() - cachedItems.map { it.id }) remoteAction(productType, newIds) .map { remoteItems -> (cachedItems + remoteItems) } } else -> throw IllegalArgumentException("Unsupported source type = $dataSourceType") } } private fun remoteAction(productType: String, skuIds: List<String>): Single<List<LightSku>> = billingRemoteDataSource .getInventory(productType, skuIds) .map { inventory -> inventory.map { LightSku(it.sku, it.price) } } .doCompletableOnSuccess(lightSkuCacheDataSource::saveLightInventory) }
apache-2.0
279df57e9a13fca63971ca2bb3019275
40.652174
135
0.693995
4.848101
false
false
false
false
zaviyalov/intellij-cleaner
src/main/kotlin/com/github/zaviyalov/intellijcleaner/model/Edition.kt
1
1128
/* * Copyright (c) 2016 Anton Zaviyalov */ package com.github.zaviyalov.intellijcleaner.model import javafx.beans.property.SimpleStringProperty import java.util.* @Suppress("unused") class Edition(name: String, path: String) { private val _name = SimpleStringProperty() var name: String get() = _name.get() set(value) { _name.set(value) } private val _path = SimpleStringProperty() var path: String get() = _path.get() set(value) { _path.set(value) } init { this.name = name this.path = path } fun nameProperty() = _name fun pathProperty() = _path override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Edition if (name != other.name) return false if (path != other.path) return false return true } override fun hashCode(): Int { var result = Objects.hashCode(name) result = 31 * result + Objects.hashCode(path) return result } }
mit
a87359a5ce7b1ba1fbd65f817d67b36d
21.56
55
0.583333
4.086957
false
false
false
false
dagi12/eryk-android-common
src/main/java/pl/edu/amu/wmi/erykandroidcommon/recycler/grouping/GroupingService.kt
1
3620
package pl.edu.amu.wmi.erykandroidcommon.recycler.grouping import android.content.Context import pl.edu.amu.wmi.erykandroidcommon.R import pl.edu.amu.wmi.erykandroidcommon.helper.DateUtils import java.util.* internal class GroupingService(private val context: Context) { private val groupingDayEnumMap: EnumMap<GroupingDay, String> = EnumMap(GroupingDay::class.java) private fun getDayOfWeekLabel(dayOfWeek: Int, context: Context): String? = when (dayOfWeek) { Calendar.MONDAY -> context.getString(R.string.monday) Calendar.TUESDAY -> context.getString(R.string.tuesday) Calendar.WEDNESDAY -> context.getString(R.string.wednesday) Calendar.THURSDAY -> context.getString(R.string.thursday) Calendar.FRIDAY -> context.getString(R.string.friday) Calendar.SATURDAY -> context.getString(R.string.saturday) Calendar.SUNDAY -> context.getString(R.string.sunday) else -> null } private fun getGroupingDayFromDayDifference(dayDifference: Int): GroupingDay = when (dayDifference) { 0 -> GroupingDay.TODAY 1 -> GroupingDay.YESTERDAY 2 -> GroupingDay.GD2AGO 3 -> GroupingDay.GD3AGO 4 -> GroupingDay.GD4AGO 5 -> GroupingDay.GD5AGO else -> GroupingDay.BEFORE } private fun eKeylistToTree(timestampHolders: List<TimestampHolder>): EnumMap<GroupingDay, MutableList<TimestampHolder>> { val groupingDayListEnumMap = EnumMap<GroupingDay, MutableList<TimestampHolder>>(GroupingDay::class.java) for (timestampHolder in timestampHolders) { val dayDifference = DateUtils.dayDifferenceToday(timestampHolder.timestamp) add(groupingDayListEnumMap, timestampHolder, getGroupingDayFromDayDifference(dayDifference)) } return groupingDayListEnumMap } private fun add(map: EnumMap<GroupingDay, MutableList<TimestampHolder>>, timestampHolder: TimestampHolder, groupingDay: GroupingDay) = map[groupingDay]!!.add(timestampHolder) private fun treeToListItemList(groupingDayListEnumMap: EnumMap<GroupingDay, MutableList<TimestampHolder>>, groupingDayEnumMap: EnumMap<GroupingDay, String>): List<ListItem> { val mItems = ArrayList<ListItem>() for ((key, value) in groupingDayListEnumMap) { val header = HeaderItem(groupingDayEnumMap[key]!!) mItems.add(header) mItems.addAll(value) } return mItems } private fun init() { val calendar = Calendar.getInstance() groupingDayEnumMap.put(GroupingDay.TODAY, context.getString(R.string.today)) groupingDayEnumMap.put(GroupingDay.BEFORE, context.getString(R.string.before)) groupingDayEnumMap.put(GroupingDay.YESTERDAY, context.getString(R.string.yesterday)) calendar.add(Calendar.DATE, -2) groupingDayEnumMap.put(GroupingDay.GD2AGO, getDayOfWeekLabel(calendar.get(Calendar.DAY_OF_WEEK), context)) calendar.add(Calendar.DATE, -1) groupingDayEnumMap.put(GroupingDay.GD3AGO, getDayOfWeekLabel(calendar.get(Calendar.DAY_OF_WEEK), context)) calendar.add(Calendar.DATE, -1) groupingDayEnumMap.put(GroupingDay.GD4AGO, getDayOfWeekLabel(calendar.get(Calendar.DAY_OF_WEEK), context)) calendar.add(Calendar.DATE, -1) groupingDayEnumMap.put(GroupingDay.GD5AGO, getDayOfWeekLabel(calendar.get(Calendar.DAY_OF_WEEK), context)) } fun process(list: List<TimestampHolder>): List<ListItem> { init() val enumMap = eKeylistToTree(list) return treeToListItemList(enumMap, groupingDayEnumMap) } }
apache-2.0
82d2d497688bd0a7bd50f7b5952997d9
46.012987
178
0.716851
4.175317
false
false
false
false
JetBrains/teamcity-dnx-plugin
plugin-dotnet-server/src/main/kotlin/jetbrains/buildServer/dotnet/commands/NugetDeleteCommandType.kt
1
1470
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"). * See LICENSE in the project root for license information. */ package jetbrains.buildServer.dotnet.commands import jetbrains.buildServer.dotnet.DotnetCommandType import jetbrains.buildServer.dotnet.DotnetConstants import jetbrains.buildServer.serverSide.InvalidProperty /** * Provides parameters for dotnet nuget delete command. */ class NugetDeleteCommandType : DotnetType() { override val name: String = DotnetCommandType.NuGetDelete.id override val description: String = name.replace('-', ' ') override val editPage: String = "editNugetDeleteParameters.jsp" override val viewPage: String = "viewNugetDeleteParameters.jsp" override fun validateProperties(properties: Map<String, String>) = sequence { DotnetConstants.PARAM_NUGET_PACKAGE_ID.let { if (properties[it].isNullOrBlank()) { yield(InvalidProperty(it, DotnetConstants.VALIDATION_EMPTY)) } } DotnetConstants.PARAM_NUGET_PACKAGE_SOURCE.let { if (properties[it].isNullOrBlank()) { yield(InvalidProperty(it, DotnetConstants.VALIDATION_EMPTY)) } } DotnetConstants.PARAM_NUGET_API_KEY.let { if (properties[it].isNullOrBlank()) { yield(InvalidProperty(it, DotnetConstants.VALIDATION_EMPTY)) } } } }
apache-2.0
e5c9aadfcd2a6269a6959bc29c88bc87
31.666667
81
0.680952
4.681529
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/util/ui/cloneDialog/RepositoryUrlCloneDialogExtension.kt
1
4869
// 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.util.ui.cloneDialog import com.intellij.icons.AllIcons import com.intellij.openapi.application.ModalityState import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.CheckoutProvider import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.ui.VcsCloneComponent import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtension import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.layout.* import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.BorderLayout import java.awt.event.ItemEvent import java.util.* import javax.swing.DefaultComboBoxModel import javax.swing.Icon import javax.swing.JComponent import javax.swing.JPanel class RepositoryUrlCloneDialogExtension : VcsCloneDialogExtension { private val tooltip = CheckoutProvider.EXTENSION_POINT_NAME.extensions .map { it.vcsName } .joinToString { it.replace("_".toRegex(), "") } override fun getIcon(): Icon = AllIcons.Welcome.FromVCS override fun getName() = VcsBundle.message("clone.dialog.repository.url.item") override fun getTooltip(): String? { return tooltip } override fun createMainComponent(project: Project): VcsCloneDialogExtensionComponent { throw AssertionError("Shouldn't be called") } override fun createMainComponent(project: Project, modalityState: ModalityState): VcsCloneDialogExtensionComponent { return RepositoryUrlMainExtensionComponent(project, modalityState) } class RepositoryUrlMainExtensionComponent(private val project: Project, private val modalityState: ModalityState) : VcsCloneDialogExtensionComponent() { override fun onComponentSelected() { dialogStateListener.onOkActionNameChanged(getCurrentVcsComponent()?.getOkButtonText() ?: VcsBundle.message("clone.dialog.clone.button")) dialogStateListener.onOkActionEnabled(true) getCurrentVcsComponent()?.onComponentSelected(dialogStateListener) } private val vcsComponents = HashMap<CheckoutProvider, VcsCloneComponent>() private val mainPanel = JPanel(BorderLayout()) private val centerPanel = Wrapper() private val comboBox: ComboBox<CheckoutProvider> = ComboBox<CheckoutProvider>().apply { renderer = SimpleListCellRenderer.create<CheckoutProvider>("") { it.vcsName.removePrefix("_") } } init { val northPanel = panel { row(VcsBundle.message("vcs.common.labels.version.control")) { comboBox() } } val insets = UIUtil.PANEL_REGULAR_INSETS northPanel.border = JBUI.Borders.empty(insets.top, insets.left, 0, insets.right) mainPanel.add(northPanel, BorderLayout.NORTH) mainPanel.add(centerPanel, BorderLayout.CENTER) val providers = CheckoutProvider.EXTENSION_POINT_NAME.extensions val selectedByDefaultProvider: CheckoutProvider? = if (providers.isNotEmpty()) providers[0] else null providers.sortWith(CheckoutProvider.CheckoutProviderComparator()) comboBox.model = DefaultComboBoxModel(providers).apply { selectedItem = null } comboBox.addItemListener { e: ItemEvent -> if (e.stateChange == ItemEvent.SELECTED) { val provider = e.item as CheckoutProvider centerPanel.setContent(vcsComponents.getOrPut(provider, { val cloneComponent = provider.buildVcsCloneComponent(project, modalityState) Disposer.register(this, cloneComponent) cloneComponent }).getView()) centerPanel.revalidate() centerPanel.repaint() onComponentSelected() } } comboBox.selectedItem = selectedByDefaultProvider } override fun getView() = mainPanel fun openForVcs(clazz: Class<out CheckoutProvider>): RepositoryUrlMainExtensionComponent { comboBox.selectedItem = CheckoutProvider.EXTENSION_POINT_NAME.findExtension(clazz) return this } override fun doClone(checkoutListener: CheckoutProvider.Listener) { getCurrentVcsComponent()?.doClone(project, checkoutListener) } override fun doValidateAll(): List<ValidationInfo> { return getCurrentVcsComponent()?.doValidateAll() ?: emptyList() } override fun getPreferredFocusedComponent(): JComponent? = getCurrentVcsComponent()?.getPreferredFocusedComponent() private fun getCurrentVcsComponent() = vcsComponents[comboBox.selectedItem as CheckoutProvider] } }
apache-2.0
ec49e078752559c4ddb95b01660f0663
40.262712
142
0.750051
5.056075
false
false
false
false
HTWDD/HTWDresden
app/src/main/java/de/htwdd/htwdresden/utils/extensions/StringExtension.kt
1
1364
package de.htwdd.htwdresden.utils.extensions import android.graphics.Color import java.security.MessageDigest import java.text.SimpleDateFormat import java.util.* val String?.nullWhenEmpty: String? get() { this.guard { return null } return if (isNullOrBlank()) { null } else { this!! } } fun String?.defaultWhenNull(default: String): String { this.nullWhenEmpty.guard { return default } return this!! } fun String.toDate(withFormat: String = "yyyy-MM-dd"): Date? { return try { val sdf = SimpleDateFormat(withFormat, Locale.US) sdf.parse(this) } catch (e: Exception) { error(e) null } } fun String.toSHA256(): String { val digest = MessageDigest.getInstance("SHA-256").digest(toByteArray()) return digest.fold("", { str, byte -> str + "%02x".format(byte) }) } private fun String.toMD5(): String { val digest = MessageDigest.getInstance("MD5").digest(toByteArray()) return digest.fold("", { str, byte -> str + "%02x".format(byte) }) } val String.uid: String get() = this.toMD5().mapIndexed { index, c -> if (index % 8 == 0 && index != 0) { "$c-" } else { "$c" } }.joinToString("") fun String.toColor() = Color.parseColor(if (startsWith("#")) { this } else { "#$this" })
mit
257172e805f282e2398df762ff6772de
25.25
88
0.594575
3.788889
false
false
false
false
intellij-purescript/intellij-purescript
src/test/kotlin/org/purescript/psi/imports/PSImportDeclarationImplTest.kt
1
7297
package org.purescript.psi.imports import com.intellij.testFramework.fixtures.BasePlatformTestCase import junit.framework.TestCase import org.purescript.getImportDeclaration import org.purescript.getImportDeclarations import org.purescript.getModule class PSImportDeclarationImplTest : BasePlatformTestCase() { fun `test resolve to module in root directory`() { val module = myFixture.addFileToProject( "Main.purs", """ module Main where import Foo """.trimIndent() ).getModule() myFixture.addFileToProject( "Foo.purs", """ module Foo where """.trimIndent() ) val psImportDeclaration = module.getImportDeclarationByName("Foo")!! val psModule = psImportDeclaration.reference.resolve()!! TestCase.assertEquals("Foo", psModule.name) } fun `test dont crash if module not found`() { val module = myFixture.addFileToProject( "Main.purs", """ module Main where import Foo """.trimIndent() ).getModule() val psImportDeclaration = module.getImportDeclarationByName("Foo")!! val psModule = psImportDeclaration.reference.resolve() TestCase.assertNull(psModule) } fun `test resolve to module in subdirectory`() { val module = myFixture.addFileToProject( "Main.purs", """ module Main where import Bar.Foo """.trimIndent() ).getModule() myFixture.addFileToProject( "Bar/Foo.purs", """ module Bar.Foo where """.trimIndent() ) val psImportDeclaration = module.getImportDeclarationByName("Bar.Foo")!! val psModule = psImportDeclaration.reference.resolve()!! TestCase.assertEquals("Bar.Foo", psModule.name) } fun `test resolve to module with correct module name when there is competing files`() { val module = myFixture.addFileToProject( "Main.purs", """ module Main where import Bar.Foo """.trimIndent() ).getModule() myFixture.addFileToProject( "Bar/Foo.purs", """ module Bar.Foo where """.trimIndent() ) myFixture.addFileToProject( "Foo.purs", """ module Foo where """.trimIndent() ) val psImportDeclaration = module.getImportDeclarationByName("Bar.Foo")!! val resolve = psImportDeclaration.reference.resolve() val psModule = resolve!! TestCase.assertEquals("Bar.Foo", psModule.name) } fun `test knows about imported names`() { val module = myFixture.addFileToProject( "Main.purs", """ module Main where import Foo hiding (x) import Bar import Buz (x) import Fuz (hiding) """.trimIndent() ).getModule() val foo = module.getImportDeclarationByName("Foo")!! assertTrue(foo.isHiding) assertContainsElements(foo.namedImports, "x") val bar = module.getImportDeclarationByName("Bar")!! assertFalse(bar.isHiding) assertDoesntContain(bar.namedImports, "x") val buz = module.getImportDeclarationByName("Buz")!! assertFalse(buz.isHiding) assertContainsElements(buz.namedImports, "x") val fuz = module.getImportDeclarationByName("Fuz")!! assertFalse(fuz.isHiding) assertContainsElements(fuz.namedImports, "hiding") } fun `test parses import declaration children`() { val importDeclarations = myFixture.configureByText( "Foo.purs", """ module Foo where import Adam import Adam.Nested import Adam.Aliased as A import Bertil () import Bertil.Nested () import Bertil.Aliased () as B import Caesar hiding () import Caesar.Nested hiding () import Caesar.Aliased hiding () as C """.trimIndent() ).getImportDeclarations() // import Adam importDeclarations[0].run { assertEquals("Adam", moduleName!!.name) assertNull(importList) assertFalse(isHiding) assertNull(importAlias) } // import Adam.Nested importDeclarations[1].run { assertEquals("Adam.Nested", moduleName!!.name) assertNull(importList) assertFalse(isHiding) assertNull(importAlias) } // import Adam.Aliased as A importDeclarations[2].run { assertEquals("Adam.Aliased", moduleName!!.name) assertNull(importList) assertFalse(isHiding) assertEquals("A", importAlias!!.name) } // import Bertil (b) importDeclarations[3].run { assertEquals("Bertil", moduleName!!.name) assertNotNull(importList) assertFalse(isHiding) assertNull(importAlias) } // import Bertil.Nested (b) importDeclarations[4].run { assertEquals("Bertil.Nested", moduleName!!.name) assertNotNull(importList) assertFalse(isHiding) assertNull(importAlias) } // import Bertil.Aliased (b) as B importDeclarations[5].run { assertEquals("Bertil.Aliased", moduleName!!.name) assertNotNull(importList) assertFalse(isHiding) assertEquals("B", importAlias!!.name) } // import Caesar hiding (c) importDeclarations[6].run { assertEquals("Caesar", moduleName!!.name) assertNotNull(importList) assertTrue(isHiding) assertNull(importAlias) } // import Caesar.Nested hiding (c) importDeclarations[7].run { assertEquals("Caesar.Nested", moduleName!!.name) assertNotNull(importList) assertTrue(isHiding) assertNull(importAlias) } // import Caesar.Aliased hiding (c) as C importDeclarations[8].run { assertEquals("Caesar.Aliased", moduleName!!.name) assertNotNull(importList) assertTrue(isHiding) assertEquals("C", importAlias!!.name) } } fun `test uses alias name if exists`() { val importDeclaration = myFixture.configureByText( "Foo.purs", """ module Foo where import Foo.Bar as FB """.trimIndent() ).getImportDeclaration() assertEquals("FB", importDeclaration.name) } fun `test module name if alias doesn't exist`() { val importDeclaration = myFixture.configureByText( "Foo.purs", """ module Foo where import Foo.Bar """.trimIndent() ).getImportDeclaration() assertEquals("Foo.Bar", importDeclaration.name) } }
bsd-3-clause
dca6a19250c6e246fec1ced346cc27c0
29.531381
91
0.560504
5.260995
false
true
false
false
peterLaurence/TrekAdvisor
app/src/main/java/com/peterlaurence/trekme/ui/mapview/components/CompassView.kt
1
2111
package com.peterlaurence.trekme.ui.mapview.components import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.util.AttributeSet import com.google.android.material.floatingactionbutton.FloatingActionButton import com.peterlaurence.mapview.ReferentialData import com.peterlaurence.mapview.ReferentialOwner import com.peterlaurence.trekme.R import kotlin.math.max class CompassView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FloatingActionButton(context, attrs, defStyleAttr), ReferentialOwner { private val compass = context.getDrawable(R.drawable.compass)!! private val squareDim = max(compass.intrinsicWidth, compass.intrinsicHeight) private var bitmap: Bitmap? = null private val defaultPaint = Paint().apply { isAntiAlias = true isFilterBitmap = true } init { prepareBitmap() } private fun prepareBitmap() { /* Draw the vector drawable into a square bitmap */ bitmap = Bitmap.createBitmap(squareDim, squareDim, Bitmap.Config.ARGB_8888).also { val c = Canvas(it) compass.bounds = Rect(squareDim / 2 - compass.intrinsicWidth / 2, squareDim / 2 - compass.intrinsicHeight / 2, squareDim / 2 + compass.intrinsicWidth / 2, squareDim / 2 + compass.intrinsicHeight / 2) compass.draw(c) } } override var referentialData: ReferentialData = ReferentialData(false, 0f, 1f, 0.0, 0.0) set(value) { field = value invalidate() } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) if (referentialData.rotationEnabled) { canvas?.rotate(referentialData.angle, width / 2f, height / 2f) } bitmap?.also { canvas?.drawBitmap(it, width / 2f - squareDim / 2f, height / 2f - squareDim / 2f, defaultPaint) } } }
gpl-3.0
c193a670f9378dae41849a22615e08e7
34.79661
139
0.657035
4.481953
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/WithAttributesPresentation.kt
2
2101
// 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 com.intellij.codeInsight.hints.presentation import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.markup.TextAttributes import java.awt.Graphics2D class WithAttributesPresentation(presentation: InlayPresentation, val textAttributesKey: TextAttributesKey, private val editor: Editor, val flags: AttributesFlags = AttributesFlags() ) : StaticDelegatePresentation(presentation) { override fun paint(g: Graphics2D, attributes: TextAttributes) { val other = editor.colorsScheme.getAttributes(textAttributesKey) ?: TextAttributes() if (flags.skipEffects) { other.effectType = null } if (flags.skipBackground) { other.backgroundColor = null } if (!flags.isDefault) { super.paint(g, other) } else { val result = attributes.clone() if (result.foregroundColor == null) { result.foregroundColor = other.foregroundColor } if (result.backgroundColor == null) { result.backgroundColor = other.backgroundColor } if (result.effectType == null) { result.effectType = other.effectType } if (result.effectColor == null) { result.effectColor = other.effectColor } super.paint(g, result) } } class AttributesFlags { var skipEffects: Boolean = false var skipBackground: Boolean = false var isDefault: Boolean = false fun withSkipEffects(skipEffects: Boolean): AttributesFlags { this.skipEffects = skipEffects return this } fun withSkipBackground(skipBackground: Boolean): AttributesFlags { this.skipBackground = skipBackground return this } fun withIsDefault(isDefault: Boolean): AttributesFlags { this.isDefault = isDefault return this } } }
apache-2.0
b6074fbf9db7f4337c1f39358ec1eabb
32.365079
158
0.673489
4.731982
false
false
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/images/ConfigureImageDialog.kt
3
4047
// 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.intellij.plugins.markdown.editor.images import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.NlsContexts import com.intellij.ui.layout.* import org.intellij.plugins.markdown.MarkdownBundle import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.NonNls import javax.swing.JComponent @ApiStatus.Internal class ConfigureImageDialog( private val project: Project?, @NlsContexts.DialogTitle title: String, path: String? = null, width: String? = null, height: String? = null, linkTitle: String? = null, linkDescriptionText: String? = null, private var shouldConvertToHtml: Boolean = false ) : DialogWrapper(project, true) { private var pathFieldText = path ?: "" private var widthFieldText = width ?: "" private var heightFieldText = height ?: "" private var titleFieldText = linkTitle ?: "" private var descriptionFieldText = linkDescriptionText ?: "" private var onOk: ((MarkdownImageData) -> Unit)? = null init { super.init() this.title = title isResizable = false } fun show(onOk: ((MarkdownImageData) -> Unit)?) { this.onOk = onOk show() } override fun createCenterPanel(): JComponent = panel { fullRow { label(MarkdownBundle.message("markdown.configure.image.dialog.path.label")).sizeGroup(ALWAYS_VISIBLE_FIRST_COLUMN_LABELS_SIZE_GROUP) textFieldWithBrowseButton( ::pathFieldText, MarkdownBundle.message("markdown.configure.image.dialog.browse.image.title"), project, FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor() ).focused() } fullRow { val widthLabel = label(MarkdownBundle.message("markdown.configure.image.dialog.width.label")) .sizeGroup(ALWAYS_VISIBLE_FIRST_COLUMN_LABELS_SIZE_GROUP) val widthField = textField(::widthFieldText, 8) val heightLabel = label(MarkdownBundle.message("markdown.configure.image.dialog.height.label")) val heightField = textField(::heightFieldText, 8) checkBox( MarkdownBundle.message("markdown.configure.image.dialog.convert.to.html.label"), ::shouldConvertToHtml ).withLargeLeftGap().apply { widthLabel.enableIf(selected) widthField.enableIf(selected) heightLabel.enableIf(selected) heightField.enableIf(selected) } } hideableRow(MarkdownBundle.message("markdown.configure.image.dialog.screen.reader.text.panel.title")) { fullRow { label(MarkdownBundle.message("markdown.configure.image.dialog.title.label")).sizeGroup(HIDEABLE_FIRST_COLUMN_LABELS_SIZE_GROUP) textField(::titleFieldText) } fullRow { label(MarkdownBundle.message("markdown.configure.image.dialog.description.label")) .sizeGroup(HIDEABLE_FIRST_COLUMN_LABELS_SIZE_GROUP) textArea(::descriptionFieldText, rows = 4) } } } override fun doOKAction() { super.doOKAction() onOk?.invoke(MarkdownImageData( path = processInput(pathFieldText), width = processInput(widthFieldText), height = processInput(heightFieldText), title = processInput(titleFieldText), description = processInput(descriptionFieldText), shouldConvertToHtml = shouldConvertToHtml )) } private fun processInput(text: String): String { return text.trim() } override fun getDimensionServiceKey() = DIMENSION_KEY companion object { private const val DIMENSION_KEY: @NonNls String = "Markdown.Configure.Image.Dialog.DimensionServiceKey" private const val ALWAYS_VISIBLE_FIRST_COLUMN_LABELS_SIZE_GROUP = "ALWAYS_VISIBLE_FIRST_COLUMN_LABELS_SIZE_GROUP" private const val HIDEABLE_FIRST_COLUMN_LABELS_SIZE_GROUP = "HIDEABLE_FIRST_COLUMN_LABELS_SIZE_GROUP" } }
apache-2.0
6d3092924e45b4deb85fbd43ad9e2fb9
36.82243
158
0.725723
4.360991
false
true
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/export/project/ProjectLoaderV11.kt
1
8165
package com.cout970.modeler.core.export.project import com.cout970.modeler.api.model.IModel import com.cout970.modeler.api.model.ITransformation import com.cout970.modeler.api.model.`object`.IGroupRef import com.cout970.modeler.api.model.`object`.IObject import com.cout970.modeler.api.model.`object`.MutableGroupTree import com.cout970.modeler.api.model.`object`.RootGroupRef import com.cout970.modeler.api.model.material.IMaterial import com.cout970.modeler.api.model.material.IMaterialRef import com.cout970.modeler.api.model.mesh.IFaceIndex import com.cout970.modeler.api.model.mesh.IMesh import com.cout970.modeler.api.model.selection.IObjectRef import com.cout970.modeler.core.export.* import com.cout970.modeler.core.model.Model import com.cout970.modeler.core.model.TRSTransformation import com.cout970.modeler.core.model.`object`.* import com.cout970.modeler.core.model.material.MaterialNone import com.cout970.modeler.core.model.material.TexturedMaterial import com.cout970.modeler.core.model.mesh.FaceIndex import com.cout970.modeler.core.model.mesh.Mesh import com.cout970.modeler.core.model.toImmutable import com.cout970.modeler.core.project.ProjectProperties import com.cout970.modeler.core.resource.ResourcePath import com.cout970.vector.api.IQuaternion import com.cout970.vector.api.IVector2 import com.cout970.vector.api.IVector3 import com.google.gson.GsonBuilder import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import kotlinx.collections.immutable.ImmutableMap import java.lang.reflect.Type import java.net.URI import java.util.* import java.util.zip.ZipFile object ProjectLoaderV11 { const val VERSION = "1.1" val gson = GsonBuilder() .setExclusionStrategies(ProjectExclusionStrategy()) .setPrettyPrinting() .enableComplexMapKeySerialization() .registerTypeAdapter(UUID::class.java, UUIDSerializer()) .registerTypeAdapter(IVector3::class.java, Vector3Serializer()) .registerTypeAdapter(IVector2::class.java, Vector2Serializer()) .registerTypeAdapter(IQuaternion::class.java, QuaternionSerializer()) .registerTypeAdapter(IGroupRef::class.java, GroupRefSerializer()) .registerTypeAdapter(IMaterialRef::class.java, MaterialRefSerializer()) .registerTypeAdapter(IObjectRef::class.java, ObjectRefSerializer()) .registerTypeAdapter(ITransformation::class.java, TransformationSerializer()) .registerTypeAdapter(BiMultimap::class.java, BiMultimapSerializer()) .registerTypeAdapter(ImmutableMap::class.java, ImmutableMapSerializer()) .registerTypeAdapter(IModel::class.java, ModelSerializer()) .registerTypeAdapter(IMaterial::class.java, MaterialSerializer()) .registerTypeAdapter(IObject::class.java, ObjectSerializer()) .registerTypeAdapter(IMesh::class.java, MeshSerializer()) .registerTypeAdapter(IFaceIndex::class.java, FaceSerializer()) .create()!! fun loadProject(zip: ZipFile, path: String): ProgramSave { val properties = zip.load<ProjectProperties>("project.json", gson) ?: throw IllegalStateException("Missing file 'project.json' inside '$path'") val model = zip.load<IModel>("model.json", gson) ?: throw IllegalStateException("Missing file 'model.json' inside '$path'") checkIntegrity(listOf(model.objectMap, model.materialMap, model.groupMap, model.tree)) return ProgramSave(VERSION, properties, model, emptyList()) } class ModelSerializer : JsonDeserializer<IModel> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IModel { val obj = json.asJsonObject val objectMap = context.deserializeT<Map<IObjectRef, IObject>>(obj["objectMap"]) val materialMap = context.deserializeT<Map<IMaterialRef, IMaterial>>(obj["materialMap"]) return Model.of( objectMap = objectMap, materialMap = materialMap, groupTree = MutableGroupTree(RootGroupRef, objectMap.keys.toMutableList()).toImmutable() ) } } class MaterialSerializer : JsonDeserializer<IMaterial> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IMaterial { val obj = json.asJsonObject return when { obj["name"].asString == "noTexture" -> MaterialNone else -> { val id = context.deserialize<UUID>(obj["id"], UUID::class.java) TexturedMaterial(obj["name"].asString, ResourcePath(URI(obj["path"].asString)), id) } } } } class ObjectSerializer : JsonDeserializer<IObject> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IObject { val obj = json.asJsonObject return when (obj["class"].asString) { "ObjectCube" -> { ObjectCube( name = context.deserialize(obj["name"], String::class.java), transformation = context.deserialize(obj["transformation"], TRSTransformation::class.java), material = context.deserialize(obj["material"], IMaterialRef::class.java), textureOffset = context.deserialize(obj["textureOffset"], IVector2::class.java), textureSize = context.deserialize(obj["textureSize"], IVector2::class.java), mirrored = context.deserialize(obj["mirrored"], Boolean::class.java), visible = context.deserialize(obj["visible"], Boolean::class.java), id = context.deserialize(obj["id"], UUID::class.java) ) } "Object" -> Object( name = context.deserialize(obj["name"], String::class.java), mesh = context.deserialize(obj["mesh"], IMesh::class.java), material = context.deserialize(obj["material"], IMaterialRef::class.java), visible = context.deserialize(obj["visible"], Boolean::class.java), id = context.deserialize(obj["id"], UUID::class.java) ) else -> throw IllegalStateException("Unknown Class: ${obj["class"]}") } } } class MeshSerializer : JsonDeserializer<IMesh> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IMesh { val obj = json.asJsonObject return Mesh( pos = context.deserializeT(obj["pos"]), tex = context.deserializeT(obj["tex"]), faces = context.deserializeT(obj["faces"]) ) } } class FaceSerializer : JsonDeserializer<IFaceIndex> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IFaceIndex { val obj = json.asJsonObject return FaceIndex.from( pos = context.deserializeT(obj["pos"]), tex = context.deserializeT(obj["tex"]) ) } } class BiMultimapSerializer : JsonDeserializer<BiMultimap<IGroupRef, IObjectRef>> { data class Aux(val key: IGroupRef, val value: List<IObjectRef>) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): BiMultimap<IGroupRef, IObjectRef> { if (json.isJsonNull || (json.isJsonArray && json.asJsonArray.size() == 0)) return emptyBiMultimap() val array = json.asJsonArray val list = array.map { context.deserialize(it, Aux::class.java) as Aux } return biMultimapOf(*list.map { it.key to it.value }.toTypedArray()) } } }
gpl-3.0
e628ba0ba8ae27a0ddf41cdd69baaf47
45.931034
140
0.652786
4.811432
false
false
false
false
Flank/flank
integration_tests/src/test/kotlin/integration/AllTestFilteredIT.kt
1
2475
package integration import FlankCommand import com.google.common.truth.Truth.assertThat import integration.config.AndroidTest import integration.config.IosTest import org.junit.Test import org.junit.experimental.categories.Category import run import utils.CONFIGS_PATH import utils.FLANK_JAR_PATH import utils.androidRunCommands import utils.asOutputReport import utils.assertExitCode import utils.assertNoOutcomeSummary import utils.findTestDirectoryFromOutput import utils.iosRunCommands import utils.json import utils.removeUnicode import utils.toOutputReportFile class AllTestFilteredIT { private val name = this::class.java.simpleName @Category(AndroidTest::class) @Test fun `filter all tests - android`() { val name = "$name-android" val result = FlankCommand( flankPath = FLANK_JAR_PATH, ymlPath = "$CONFIGS_PATH/all_test_filtered_android.yml", params = androidRunCommands ).run( workingDirectory = "./", testSuite = name ) assertExitCode(result, 3) val resOutput = result.output.removeUnicode() val outputReport = resOutput.findTestDirectoryFromOutput().toOutputReportFile().json().asOutputReport() assertNoOutcomeSummary(resOutput) assertThat(outputReport.error).contains("There are no Android tests to run.") assertThat(outputReport.cost).isNull() assertThat(outputReport.testResults).isEmpty() assertThat(outputReport.weblinks).isEmpty() } @Category(IosTest::class) @Test fun `filter all tests - ios`() { val name = "$name-ios" val result = FlankCommand( flankPath = FLANK_JAR_PATH, ymlPath = "$CONFIGS_PATH/all_test_filtered_ios.yml", params = iosRunCommands ).run( workingDirectory = "./", testSuite = name ) assertExitCode(result, 1) val resOutput = result.output.removeUnicode() assertNoOutcomeSummary(resOutput) val outputReport = resOutput.findTestDirectoryFromOutput().toOutputReportFile().json().asOutputReport() assertNoOutcomeSummary(resOutput) assertThat(outputReport.error).contains("Empty shards. Cannot match any method to [nonExisting/Class]") assertThat(outputReport.cost).isNull() assertThat(outputReport.testResults).isEmpty() assertThat(outputReport.weblinks).isEmpty() } }
apache-2.0
716753ec68bfb89c3dab0073b56185f2
29.9375
111
0.690101
4.52468
false
true
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/lang/KslExpressionBit.kt
1
6805
package de.fabmax.kool.modules.ksl.lang import de.fabmax.kool.modules.ksl.generator.KslGenerator import de.fabmax.kool.modules.ksl.model.KslMutatedState abstract class KslExpressionBit<T: KslNumericType>( val left: KslExpression<*>, val right: KslExpression<*>, val operator: KslBitOperator, override val expressionType: T) : KslExpression<T> { override fun collectStateDependencies(): Set<KslMutatedState> = left.collectStateDependencies() + right.collectStateDependencies() override fun generateExpression(generator: KslGenerator): String = generator.bitExpression(this) override fun toPseudoCode(): String = "(${left.toPseudoCode()} ${operator.opString} ${right.toPseudoCode()})" } enum class KslBitOperator(val opString: String) { And("&"), Or("|"), Xor("^"), Shl("<<"), Shr(">>") } class KslExpressionBitScalar<S>( left: KslExpression<*>, right: KslExpression<*>, operator: KslBitOperator, expressionType: S ) : KslExpressionBit<S>(left, right, operator, expressionType), KslScalarExpression<S> where S: KslIntType, S: KslScalar class KslExpressionBitVector<V, S>( left: KslExpression<*>, right: KslExpression<*>, operator: KslBitOperator, expressionType: V ) : KslExpressionBit<V>(left, right, operator, expressionType), KslVectorExpression<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar // scalar & scalar infix fun <S> KslScalarExpression<S>.and(right: KslScalarExpression<S>): KslExpressionBitScalar<S> where S: KslIntType, S: KslScalar { return KslExpressionBitScalar(this, right, KslBitOperator.And, expressionType) } // vector & vector infix fun <V, S> KslVectorExpression<V, S>.and(right: KslVectorExpression<V, S>): KslExpressionBitVector<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar { return KslExpressionBitVector(this, right, KslBitOperator.And, expressionType) } // vector & scalar infix fun <V, S> KslVectorExpression<V, S>.and(right: KslScalarExpression<S>): KslExpressionBitVector<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar { return KslExpressionBitVector(this, right, KslBitOperator.And, expressionType) } // scalar | scalar infix fun <S> KslScalarExpression<S>.or(right: KslScalarExpression<S>): KslExpressionBitScalar<S> where S: KslIntType, S: KslScalar { return KslExpressionBitScalar(this, right, KslBitOperator.Or, expressionType) } // vector | vector infix fun <V, S> KslVectorExpression<V, S>.or(right: KslVectorExpression<V, S>): KslExpressionBitVector<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar { return KslExpressionBitVector(this, right, KslBitOperator.Or, expressionType) } // vector | scalar infix fun <V, S> KslVectorExpression<V, S>.or(right: KslScalarExpression<S>): KslExpressionBitVector<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar { return KslExpressionBitVector(this, right, KslBitOperator.Or, expressionType) } // scalar ^ scalar infix fun <S> KslScalarExpression<S>.xor(right: KslScalarExpression<S>): KslExpressionBitScalar<S> where S: KslIntType, S: KslScalar { return KslExpressionBitScalar(this, right, KslBitOperator.Xor, expressionType) } // vector ^ vector infix fun <V, S> KslVectorExpression<V, S>.xor(right: KslVectorExpression<V, S>): KslExpressionBitVector<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar { return KslExpressionBitVector(this, right, KslBitOperator.Xor, expressionType) } // vector ^ scalar infix fun <V, S> KslVectorExpression<V, S>.xor(right: KslScalarExpression<S>): KslExpressionBitVector<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar { return KslExpressionBitVector(this, right, KslBitOperator.Xor, expressionType) } // scalar << scalar infix fun <S> KslScalarExpression<S>.shl(right: KslScalarExpression<S>): KslExpressionBitScalar<S> where S: KslIntType, S: KslScalar { return KslExpressionBitScalar(this, right, KslBitOperator.Shl, expressionType) } // vector << vector infix fun <V, S> KslVectorExpression<V, S>.shl(right: KslVectorExpression<V, S>): KslExpressionBitVector<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar { return KslExpressionBitVector(this, right, KslBitOperator.Shl, expressionType) } // vector << scalar infix fun <V, S> KslVectorExpression<V, S>.shl(right: KslScalarExpression<S>): KslExpressionBitVector<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar { return KslExpressionBitVector(this, right, KslBitOperator.Shl, expressionType) } // scalar >> scalar infix fun <S> KslScalarExpression<S>.shr(right: KslScalarExpression<S>): KslExpressionBitScalar<S> where S: KslIntType, S: KslScalar { return KslExpressionBitScalar(this, right, KslBitOperator.Shr, expressionType) } // vector >> vector infix fun <V, S> KslVectorExpression<V, S>.shr(right: KslVectorExpression<V, S>): KslExpressionBitVector<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar { return KslExpressionBitVector(this, right, KslBitOperator.Shr, expressionType) } // vector >> scalar infix fun <V, S> KslVectorExpression<V, S>.shr(right: KslScalarExpression<S>): KslExpressionBitVector<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar { return KslExpressionBitVector(this, right, KslBitOperator.Shr, expressionType) } class KslIntScalarComplement<S>(val expr: KslScalarExpression<S>) : KslScalarExpression<S> where S: KslIntType, S: KslScalar { override val expressionType = expr.expressionType override fun collectStateDependencies(): Set<KslMutatedState> = expr.collectStateDependencies() override fun generateExpression(generator: KslGenerator): String = generator.intComplementExpression(this) override fun toPseudoCode(): String = "~(${expr.toPseudoCode()})" } fun <S> KslScalarExpression<S>.inv() where S: KslIntType, S: KslScalar = KslIntScalarComplement(this) class KslIntVectorComplement<V, S>(val expr: KslVectorExpression<V, S>) : KslVectorExpression<V, S> where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar { override val expressionType = expr.expressionType override fun collectStateDependencies(): Set<KslMutatedState> = expr.collectStateDependencies() override fun generateExpression(generator: KslGenerator): String = generator.intComplementExpression(this) override fun toPseudoCode(): String = "~(${expr.toPseudoCode()})" } fun <V, S> KslVectorExpression<V, S>.inv() where V: KslIntType, V: KslVector<S>, S: KslIntType, S: KslScalar = KslIntVectorComplement(this)
apache-2.0
6cfea235e48203036f4c35716cf7c290
44.986486
139
0.732697
3.704409
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/test/kotlin/com/vrem/wifianalyzer/wifi/predicate/SecurityPredicateTest.kt
1
2561
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[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 com.vrem.wifianalyzer.wifi.predicate import com.vrem.wifianalyzer.wifi.model.* import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class SecurityPredicateTest { @Test fun testSecurityPredicateWithFoundWPAValue() { // setup val wiFiDetail = wiFiDetail() val fixture = Security.WPA.predicate() // execute val actual = fixture(wiFiDetail) // validate assertTrue(actual) } @Test fun testSecurityPredicateWithFoundWEPValue() { // setup val wiFiDetail = wiFiDetail() val fixture = Security.WEP.predicate() // execute val actual = fixture(wiFiDetail) // validate assertTrue(actual) } @Test fun testSecurityPredicateWithFoundNoneValue() { // setup val wiFiDetail = wiFiDetailWithNoSecurity() val fixture = Security.NONE.predicate() // execute val actual = fixture(wiFiDetail) // validate assertTrue(actual) } @Test fun testSecurityPredicateWithNotFoundValue() { // setup val wiFiDetail = wiFiDetail() val fixture = Security.WPA2.predicate() // execute val actual = fixture(wiFiDetail) // validate assertFalse(actual) } private fun wiFiDetail(): WiFiDetail = WiFiDetail( WiFiIdentifier("ssid", "bssid"), "ess-wep-wpa", WiFiSignal(2455, 2455, WiFiWidth.MHZ_20, 1, true)) private fun wiFiDetailWithNoSecurity(): WiFiDetail = WiFiDetail( WiFiIdentifier("ssid", "bssid"), "ess", WiFiSignal(2455, 2455, WiFiWidth.MHZ_20, 1, true)) }
gpl-3.0
037d70bad56421b280c3cddf4324c71b
30.243902
90
0.637251
4.485114
false
true
false
false
leafclick/intellij-community
plugins/settings-repository/src/IcsBundle.kt
1
1286
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.DynamicBundle import org.jetbrains.annotations.PropertyKey private const val BUNDLE: String = "messages.IcsBundle" object IcsBundle : DynamicBundle(BUNDLE) { @JvmStatic fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params) @JvmStatic fun lazyMessage(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): java.util.function.Supplier<String> = getLazyMessage(key, *params) } fun icsMessage(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any?): String { return IcsBundle.message(key, params) }
apache-2.0
2d89607d1d21e6385b40696bb95b28c3
36.852941
119
0.750389
4.202614
false
false
false
false
dpisarenko/econsim-tr01
src/main/java/cc/altruix/econsimtr01/PlTransformation.kt
1
3019
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01 import org.joda.time.DateTime import org.slf4j.LoggerFactory import java.util.* /** * Created by pisarenko on 19.04.2016. */ open class PlTransformation(val id:String, val agentId:String, val inputAmount:Double, val inputResourceId:String, val outputAmount:Double, val outputResourceId:String, val timeTriggerFunction: (DateTime) -> Boolean) : IAction { val LOGGER = LoggerFactory.getLogger(PlTransformation::class.java) val subscribers : MutableList<IActionSubscriber> = LinkedList() lateinit var agents:List<IAgent> override fun timeToRun(time: DateTime): Boolean = timeTriggerFunction(time) override fun run(time: DateTime) { if (inputAmount == null) { LOGGER.error("Input amount is null") return } if (outputAmount == null) { LOGGER.error("Output amount is null") return } val agent = findAgent() if (agent == null) { LOGGER.error("Can't find agent '$agentId'") return } if (agent !is IResourceStorage) { LOGGER.error("Agent '$agentId' isn't a resource storage") return } val availableAmount = agent.amount(inputResourceId) if (!agent.isInfinite(inputResourceId) && (availableAmount < inputAmount)) { LOGGER.error("Quantity of $inputResourceId at $agentId ($availableAmount) is less than required amount of $inputAmount") } else { agent.remove(inputResourceId, inputAmount) agent.put(outputResourceId, outputAmount) } } open internal fun findAgent() = findAgent(agentId, agents) override fun notifySubscribers(time: DateTime) { this.subscribers.forEach { it.actionOccurred(this, time) } } override fun subscribe(subscriber: IActionSubscriber) { this.subscribers.add(subscriber) } }
gpl-3.0
247f50de3bdc89bc70f43e9c6c5305fc
31.12766
132
0.644584
4.388081
false
false
false
false
google/android-fhir
workflow/src/main/java/com/google/android/fhir/workflow/FhirOperator.kt
1
9269
/* * Copyright 2022 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.workflow import ca.uhn.fhir.context.FhirContext import ca.uhn.fhir.context.FhirVersionEnum import com.google.android.fhir.FhirEngine import java.util.function.Supplier import org.hl7.fhir.instance.model.api.IBaseParameters import org.hl7.fhir.r4.model.Bundle import org.hl7.fhir.r4.model.CarePlan import org.hl7.fhir.r4.model.Coding import org.hl7.fhir.r4.model.Endpoint import org.hl7.fhir.r4.model.IdType import org.hl7.fhir.r4.model.Library import org.hl7.fhir.r4.model.MeasureReport import org.hl7.fhir.r4.model.Parameters import org.opencds.cqf.cql.engine.data.CompositeDataProvider import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverterFactory import org.opencds.cqf.cql.engine.fhir.model.R4FhirModelResolver import org.opencds.cqf.cql.evaluator.CqlOptions import org.opencds.cqf.cql.evaluator.activitydefinition.r4.ActivityDefinitionProcessor import org.opencds.cqf.cql.evaluator.builder.Constants import org.opencds.cqf.cql.evaluator.builder.CqlEvaluatorBuilder import org.opencds.cqf.cql.evaluator.builder.EndpointConverter import org.opencds.cqf.cql.evaluator.builder.ModelResolverFactory import org.opencds.cqf.cql.evaluator.builder.data.DataProviderFactory import org.opencds.cqf.cql.evaluator.builder.data.FhirModelResolverFactory import org.opencds.cqf.cql.evaluator.builder.data.TypedRetrieveProviderFactory import org.opencds.cqf.cql.evaluator.builder.library.LibrarySourceProviderFactory import org.opencds.cqf.cql.evaluator.builder.library.TypedLibrarySourceProviderFactory import org.opencds.cqf.cql.evaluator.builder.terminology.TerminologyProviderFactory import org.opencds.cqf.cql.evaluator.builder.terminology.TypedTerminologyProviderFactory import org.opencds.cqf.cql.evaluator.cql2elm.util.LibraryVersionSelector import org.opencds.cqf.cql.evaluator.engine.model.CachingModelResolverDecorator import org.opencds.cqf.cql.evaluator.expression.ExpressionEvaluator import org.opencds.cqf.cql.evaluator.fhir.adapter.r4.AdapterFactory import org.opencds.cqf.cql.evaluator.library.CqlFhirParametersConverter import org.opencds.cqf.cql.evaluator.library.LibraryProcessor import org.opencds.cqf.cql.evaluator.measure.r4.R4MeasureProcessor import org.opencds.cqf.cql.evaluator.plandefinition.r4.OperationParametersParser import org.opencds.cqf.cql.evaluator.plandefinition.r4.PlanDefinitionProcessor class FhirOperator(fhirContext: FhirContext, fhirEngine: FhirEngine) { // Initialize the measure processor private val fhirEngineTerminologyProvider = FhirEngineTerminologyProvider(fhirContext, fhirEngine) private val adapterFactory = AdapterFactory() private val libraryContentProvider = FhirEngineLibraryContentProvider(adapterFactory) private val fhirTypeConverter = FhirTypeConverterFactory().create(FhirVersionEnum.R4) private val fhirEngineRetrieveProvider = FhirEngineRetrieveProvider(fhirEngine).apply { terminologyProvider = fhirEngineTerminologyProvider isExpandValueSets = true } private val dataProvider = CompositeDataProvider( CachingModelResolverDecorator(R4FhirModelResolver()), fhirEngineRetrieveProvider ) private val fhirEngineDal = FhirEngineDal(fhirEngine) private val measureProcessor = R4MeasureProcessor( fhirEngineTerminologyProvider, libraryContentProvider, dataProvider, fhirEngineDal ) // Initialize the plan definition processor private val cqlFhirParameterConverter = CqlFhirParametersConverter(fhirContext, adapterFactory, fhirTypeConverter) private val libraryContentProviderFactory = LibrarySourceProviderFactory( fhirContext, adapterFactory, hashSetOf<TypedLibrarySourceProviderFactory>( object : TypedLibrarySourceProviderFactory { override fun getType() = Constants.HL7_FHIR_FILES override fun create(url: String?, headers: MutableList<String>?) = libraryContentProvider } ), LibraryVersionSelector(adapterFactory) ) private val fhirModelResolverFactory = FhirModelResolverFactory() private val dataProviderFactory = DataProviderFactory( fhirContext, hashSetOf<ModelResolverFactory>(fhirModelResolverFactory), hashSetOf<TypedRetrieveProviderFactory>( object : TypedRetrieveProviderFactory { override fun getType() = Constants.HL7_FHIR_FILES override fun create(url: String?, headers: MutableList<String>?) = fhirEngineRetrieveProvider } ) ) private val terminologyProviderFactory = TerminologyProviderFactory( fhirContext, hashSetOf<TypedTerminologyProviderFactory>( object : TypedTerminologyProviderFactory { override fun getType() = Constants.HL7_FHIR_FILES override fun create(url: String?, headers: MutableList<String>?) = fhirEngineTerminologyProvider } ) ) private val endpointConverter = EndpointConverter(adapterFactory) private val evaluatorBuilderSupplier = Supplier { CqlEvaluatorBuilder() .withLibrarySourceProvider(libraryContentProvider) .withCqlOptions(CqlOptions.defaultOptions()) .withTerminologyProvider(fhirEngineTerminologyProvider) } private val libraryProcessor = LibraryProcessor( fhirContext, cqlFhirParameterConverter, libraryContentProviderFactory, dataProviderFactory, terminologyProviderFactory, endpointConverter, fhirModelResolverFactory, evaluatorBuilderSupplier ) private val expressionEvaluator = ExpressionEvaluator( fhirContext, cqlFhirParameterConverter, libraryContentProviderFactory, dataProviderFactory, terminologyProviderFactory, endpointConverter, fhirModelResolverFactory, evaluatorBuilderSupplier ) private val activityDefinitionProcessor = ActivityDefinitionProcessor(fhirContext, fhirEngineDal, libraryProcessor) private val operationParametersParser = OperationParametersParser(adapterFactory, fhirTypeConverter) private val planDefinitionProcessor = PlanDefinitionProcessor( fhirContext, fhirEngineDal, libraryProcessor, expressionEvaluator, activityDefinitionProcessor, operationParametersParser ) fun loadLib(lib: Library) { if (lib.url != null) { fhirEngineDal.libs[lib.url] = lib } if (lib.name != null) { libraryContentProvider.libs[lib.name] = lib } } fun loadLibs(libBundle: Bundle) { for (entry in libBundle.entry) { loadLib(entry.resource as Library) } } /** * The function evaluates a FHIR library against a patient's records. * @param libraryUrl the url of the Library to evaluate * @param patientId the Id of the patient to be evaluated * @param expressions names of expressions in the Library to evaluate. * @return a Parameters resource that contains an evaluation result for each expression requested */ fun evaluateLibrary( libraryUrl: String, patientId: String, expressions: Set<String> ): IBaseParameters { val dataEndpoint = Endpoint() .setAddress("localhost") .setConnectionType(Coding().setCode(Constants.HL7_FHIR_FILES)) return libraryProcessor.evaluate( libraryUrl, patientId, null, null, null, dataEndpoint, null, expressions ) } fun evaluateMeasure( measureUrl: String, start: String, end: String, reportType: String, subject: String?, practitioner: String?, lastReceivedOn: String? ): MeasureReport { return measureProcessor.evaluateMeasure( measureUrl, start, end, reportType, subject, practitioner, lastReceivedOn, /* contentEndpoint= */ null, /* terminologyEndpoint= */ null, /* dataEndpoint= */ null, /* additionalData= */ null ) } fun generateCarePlan(planDefinitionId: String, patientId: String, encounterId: String): CarePlan { return planDefinitionProcessor.apply( IdType("PlanDefinition", planDefinitionId), patientId, encounterId, /* practitionerId= */ null, /* organizationId= */ null, /* userType= */ null, /* userLanguage= */ null, /* userTaskContext= */ null, /* setting= */ null, /* settingContext= */ null, /* mergeNestedCarePlans= */ null, /* parameters= */ Parameters(), /* useServerData= */ null, /* bundle= */ null, /* prefetchData= */ null, /* dataEndpoint= */ null, /* contentEndpoint*/ null, /* terminologyEndpoint= */ null ) } }
apache-2.0
ecc72d9ccea2f7258941c7244018ecd4
34.377863
100
0.743446
4.432807
false
false
false
false
nadraliev/DsrWeatherApp
app/src/main/java/soutvoid/com/DsrWeatherApp/ui/util/DialogUtils.kt
1
1747
package soutvoid.com.DsrWeatherApp.ui.util import android.app.Dialog import android.content.Context import android.support.annotation.StringRes import android.support.v7.app.AlertDialog import android.widget.ArrayAdapter import soutvoid.com.DsrWeatherApp.R import soutvoid.com.DsrWeatherApp.ui.screen.newLocation.NewLocationActivityView object DialogUtils { fun createSimpleListDialog(context: Context, @StringRes titleId: Int = -1, items: List<String>, listener: (position: Int) -> Unit) : Dialog { val dialogBuilder = AlertDialog.Builder(context) if (titleId != -1) dialogBuilder.setTitle(titleId) dialogBuilder.setAdapter( ArrayAdapter(context, android.R.layout.simple_list_item_1, items) ) { dialogInterface, i -> listener(i) } return dialogBuilder.create() } fun showSimpleListDialog(context: Context, @StringRes titleId: Int = -1, items: List<String>, listener: (position: Int) -> Unit) { createSimpleListDialog(context, titleId, items, listener).show() } fun showNoLocationsDialog(context: Context) { val message = context.getString(R.string.add_location) showSimpleListDialog(context, items = listOf(message)) { NewLocationActivityView.start(context) } } fun showLocationsDialog(context: Context, locationsNames: List<String>, listener: (position: Int) -> Unit) { showSimpleListDialog(context, items = locationsNames, listener = listener) } }
apache-2.0
1fd9a5a78ec57be383332265d371e8a1
37
106
0.615341
4.893557
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/buffer/EncryptedBufferStream.kt
1
4000
package com.onyx.buffer import com.onyx.extension.common.instance import com.onyx.extension.withBuffer import com.onyx.persistence.ManagedEntity import com.onyx.persistence.context.SchemaContext import java.nio.ByteBuffer /** * @author Tim Osborn * @since 2.2.0 * * It overrides the default implementation to encrypt and decrypt the managed entities. */ class EncryptedBufferStream(buffer: ByteBuffer) : BufferStream(buffer) { constructor() : this(BufferPool.allocateAndLimit(ExpandableByteBuffer.BUFFER_ALLOCATION)) /** * Put a managed entity. Encrypt the buffer before putting it. * * @param entity Entity to serialize in an encrypted format * @param context Needed to get encryption method and entity metadata * @since 2.2.0 */ override fun putEntity(entity: ManagedEntity, context: SchemaContext?) { val bufferToEncrypt = BufferStream() entity.write(bufferToEncrypt, context) val encryptedBuffer = (bufferToEncrypt.byteBuffer.flip() as ByteBuffer).encrypt(context) putInt(encryptedBuffer.remaining()) expandableByteBuffer!!.ensureSize(encryptedBuffer.remaining()) expandableByteBuffer!!.buffer.put(encryptedBuffer) } /** * Returns the decrypted entity * * @return entity in a decrypted format * @since 2.2.0 */ override val entity: ManagedEntity get() { val bufferLength = int val encryptedByteArray = ByteArray(bufferLength) expandableByteBuffer!!.buffer.get(encryptedByteArray) val decryptedByteBuffer = ByteBuffer.wrap(encryptedByteArray).decrypt(context) val encryptedBufferStream = BufferStream(decryptedByteBuffer) val serializerId = encryptedBufferStream.expandableByteBuffer!!.buffer.int encryptedBufferStream.expandableByteBuffer!!.buffer.position(encryptedBufferStream.expandableByteBuffer!!.buffer.position() - Integer.BYTES) val systemEntity = context!!.getSystemEntityById(serializerId) val entity: ManagedEntity = systemEntity!!.type.instance() entity.read(encryptedBufferStream, context) return entity } /** * Takes an encrypted entity and formats it into a key value map * * @param context Schema context used for decryption * @return Key value map of decrypted entity * @since 2.2.0 * */ override fun toMap(context: SchemaContext): Map<String, Any?> { byte int val results = HashMap<String, Any?>() withBuffer(this.expandableByteBuffer!!.buffer) { this.expandableByteBuffer!!.buffer = this.expandableByteBuffer!!.buffer.decrypt(context) val systemEntity = context.getSystemEntityById(int)!! for ((name) in systemEntity.attributes) results[name] = value } return results } } /** * Extension Method to encrypt a byte buffer * * @param context Schema context * @return Encrypted byte buffer * * @since 2.2.0 */ fun ByteBuffer.encrypt(context: SchemaContext?): ByteBuffer { context?.encryption ?: return this val bytes = ByteArray(this.remaining()) get(bytes) BufferPool.recycle(this) val encryptedBytes = context.encryption!!.encrypt(bytes)!! val newBuffer = BufferPool.allocateAndLimit(encryptedBytes.size) newBuffer.put(encryptedBytes) newBuffer.rewind() return newBuffer } /** * Extension Method to decrypt a byte buffer * * @param context Schema context * @return Decrypted byte buffer * * @since 2.2.0 */ fun ByteBuffer.decrypt(context: SchemaContext?): ByteBuffer { context?.encryption ?: return this val bytes = ByteArray(this.remaining()) get(bytes) BufferPool.recycle(this) val decryptedBytes = context.encryption!!.decrypt(bytes) val newBuffer = BufferPool.allocateAndLimit(decryptedBytes.size) newBuffer.put(decryptedBytes) newBuffer.rewind() return newBuffer }
agpl-3.0
54937d4edb25fd8cab419a7afc6eedb5
32.898305
152
0.69375
4.61361
false
false
false
false
GunoH/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/BreakpointsUsageCollector.kt
8
1887
// 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.xdebugger.impl.breakpoints import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.xdebugger.breakpoints.XBreakpoint import com.intellij.xdebugger.breakpoints.XBreakpointType class BreakpointsUsageCollector : CounterUsagesCollector() { companion object { private val GROUP = EventLogGroup("debugger.breakpoints.usage", 4) private val WITHIN_SESSION_FIELD = EventFields.Boolean("within_session") val TYPE_FIELD = EventFields.StringValidatedByCustomRule("type", BreakpointsUtilValidator::class.java) private val BREAKPOINT_ADDED = GROUP.registerVarargEvent("breakpoint.added", WITHIN_SESSION_FIELD, EventFields.PluginInfo, TYPE_FIELD) private val BREAKPOINT_VERIFIED = GROUP.registerEvent("breakpoint.verified", EventFields.Long("time")) @JvmStatic fun reportNewBreakpoint(breakpoint: XBreakpoint<*>, type: XBreakpointType<*, *>, withinSession: Boolean) { if (breakpoint is XBreakpointBase<*, *, *>) { val data = mutableListOf<EventPair<*>>() data.addAll(getType(type)) data.add(WITHIN_SESSION_FIELD.with(withinSession)) BREAKPOINT_ADDED.log(breakpoint.project, data) } } @JvmStatic fun reportBreakpointVerified(breakpoint: XBreakpoint<*>, time: Long) { if (breakpoint is XBreakpointBase<*, *, *>) { BREAKPOINT_VERIFIED.log(breakpoint.project, time) } } } override fun getGroup(): EventLogGroup = GROUP }
apache-2.0
3c2fddcd1c948950cf4e71f28e19ca42
47.410256
140
0.732379
4.765152
false
false
false
false
knes1/kotao
src/main/kotlin/io/github/knes1/kotao/brew/services/Paginator.kt
1
830
package io.github.knes1.kotao.brew.services /** * @author knesek * Created on: 10/16/16 */ data class Paginator ( val totalElements: Long, val pageSize: Long, val totalPages: Long = (totalElements / pageSize) + 1, val currentPage: Long ) { fun isFirst(): Boolean = currentPage == 1L fun isLast(): Boolean = !hasNext() fun hasNext(): Boolean = currentPage < totalPages fun next(): Long = currentPage + 1 fun prev(): Long = currentPage - 1 fun pageIndicesAround(pagesAround: Int = 2, anchorPage: Int = currentPage.toInt()): List<Int> { val total = pagesAround * 2 + 1 val startIndex = Math.max(1, anchorPage - pagesAround) val endIndex = Math.min(totalPages.toInt(), startIndex + total) return (startIndex..endIndex).toList() } }
mit
4307cd5b677f59be0885bd0edfc65705
25.806452
99
0.63012
4.04878
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SimplifyNestedEachInScopeFunctionInspection.kt
3
12889
// 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 import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.getReceiverTypeFromFunctionType import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall 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.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingContext.REFERENCE_TARGET import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.types.KotlinType class SimplifyNestedEachInScopeFunctionInspection : AbstractKotlinInspection() { private companion object { private val scopeFunctions = mapOf("also" to listOf(FqName("kotlin.also")), "apply" to listOf(FqName("kotlin.apply"))) private val iterateFunctions = mapOf( "forEach" to listOf(FqName("kotlin.collections.forEach"), FqName("kotlin.text.forEach")), "onEach" to listOf(FqName("kotlin.collections.onEach"), FqName("kotlin.text.onEach")) ) private fun KtCallExpression.getCallingShortNameOrNull(shortNamesToFqNames: Map<String, List<FqName>>): String? { val shortName = calleeExpression?.text ?: return null val names = shortNamesToFqNames[shortName] ?: return null val call = this.resolveToCall() ?: return null return if (names.any(call::isCalling)) shortName else null } private fun KtCallExpression.singleLambdaExpression(): KtLambdaExpression? = this.valueArguments.singleOrNull()?.getArgumentExpression()?.unpackLabelAndLambdaExpression()?.second private fun KtExpression.unpackLabelAndLambdaExpression(): Pair<KtLabeledExpression?, KtLambdaExpression?> = when (this) { is KtLambdaExpression -> null to this is KtLabeledExpression -> this to baseExpression?.unpackLabelAndLambdaExpression()?.second is KtAnnotatedExpression -> baseExpression?.unpackLabelAndLambdaExpression() ?: (null to null) else -> null to null } private fun KtCallExpression.getReceiverType(context: BindingContext): KotlinType? { val callee = calleeExpression as? KtNameReferenceExpression ?: return null val calleeDescriptor = context[REFERENCE_TARGET, callee] as? CallableMemberDescriptor ?: return null return (calleeDescriptor.dispatchReceiverParameter ?: calleeDescriptor.extensionReceiverParameter)?.type } // Ignores type parameters private fun KotlinType.isAssignableFrom(subtype: KotlinType) = constructor in subtype.allSupertypes().map(KotlinType::constructor) private fun KotlinType.allSupertypes(): Set<KotlinType> = constructor.supertypes.flatMapTo(HashSet()) { it.allSupertypes() } + this private abstract class ReferenceTreeVisitor : KtTreeVisitorVoid() { var referenced = false protected set } private class LabelReferenceVisitor(val labelName: String) : ReferenceTreeVisitor() { override fun visitExpressionWithLabel(expression: KtExpressionWithLabel) { if (expression.getLabelName() == labelName) referenced = true } } private class ParameterReferenceTreeVisitor(name: String?) : ReferenceTreeVisitor() { val name = name ?: "it" override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { if (expression.getReferencedName() == name) referenced = true } override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) { // Do not parse reference when name is shadowed in lambda if (lambdaExpression.valueParameters.none { it.name == name }) super.visitLambdaExpression(lambdaExpression) } } private class ImplicitThisReferenceVisitor( val matchType: KotlinType, val context: BindingContext, val thisTypes: List<KotlinType> = emptyList() ) : ReferenceTreeVisitor() { fun KotlinType.typeMatchesOutermostThis(): Boolean { if (!this.isAssignableFrom(matchType)) return false return thisTypes.none { this.isAssignableFrom(it) } } override fun visitThisExpression(expression: KtThisExpression) { if (expression.labelQualifier == null) referenced = true // Be safe to prevent false positives } override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) { run label@{ val thisExpression = expression.receiverExpression as? KtThisExpression ?: return@label val callExpression = expression.selectorExpression as? KtCallExpression ?: return@label if (thisExpression.labelQualifier != null) return@label if (callExpression.getReceiverType(context)?.typeMatchesOutermostThis() == true) return } super.visitDotQualifiedExpression(expression) } override fun visitCallExpression(expression: KtCallExpression) { if (expression.getStrictParentOfType<KtDotQualifiedExpression>() == null) { if (expression.getReceiverType(context)?.typeMatchesOutermostThis() == true) referenced = true } expression.singleLambdaExpression()?.let { lambdaExpression -> val lambdaReceiverType = lambdaExpression.getType(context)?.getReceiverTypeFromFunctionType() val visitor = ImplicitThisReferenceVisitor( matchType, context, thisTypes.let { if (lambdaReceiverType != null) it.plus(lambdaReceiverType) else it } ) lambdaExpression.bodyExpression?.acceptChildren(visitor) if (visitor.referenced) referenced = true } ?: super.visitCallExpression(expression) } } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(callExpression) { val scopeFunctionShortName = callExpression.getCallingShortNameOrNull(scopeFunctions) ?: return val arg = callExpression.valueArguments.singleOrNull() ?: return val (labelExpression, lambdaExpression) = when (arg) { is KtLambdaArgument -> arg.getArgumentExpression()?.unpackLabelAndLambdaExpression() ?: return else -> return } val innerExpression = lambdaExpression?.bodyExpression?.statements?.singleOrNull() ?: return val innerCallExpression = when (innerExpression) { is KtDotQualifiedExpression -> innerExpression.selectorExpression as? KtCallExpression ?: return is KtCallExpression -> innerExpression else -> return } val innerCallShortName = innerCallExpression.getCallingShortNameOrNull(iterateFunctions) ?: return val context = callExpression.analyze() val lambdaType = callExpression.getResolvedCall(context)?.getParameterForArgument(arg)?.type?.arguments?.first()?.type ?: return val forEachLambda = innerCallExpression.singleLambdaExpression() val visitors: List<ReferenceTreeVisitor> = listOfNotNull( LabelReferenceVisitor(labelExpression?.getLabelName() ?: scopeFunctionShortName), when (scopeFunctionShortName) { "also" -> { if (innerExpression !is KtDotQualifiedExpression) return val receiverExpression = innerExpression.receiverExpression if (receiverExpression !is KtReferenceExpression) return val parameterName = lambdaExpression.valueParameters.singleOrNull()?.name ?: "it" if (!receiverExpression.textMatches(parameterName)) return if (forEachLambda != null && (forEachLambda.valueParameters.singleOrNull()?.name ?: "it") == parameterName) null // Parameter from outer lambda is shadowed else ParameterReferenceTreeVisitor(parameterName) } "apply" -> { val receiverType = innerCallExpression.getReceiverType(context) ?: return if (!receiverType.isAssignableFrom(lambdaType)) return if (innerExpression is KtDotQualifiedExpression) { val receiverExpression = innerExpression.receiverExpression if (receiverExpression !is KtThisExpression) return val labelName = receiverExpression.getLabelName() if (labelName != null && labelName != (labelExpression?.getLabelName() ?: scopeFunctionShortName)) return } ImplicitThisReferenceVisitor(lambdaType, context) } else -> return } ) innerCallExpression.singleLambdaExpression()?.bodyExpression?.let { visitors.forEach(it::accept) } if (visitors.any(ReferenceTreeVisitor::referenced)) return holder.registerProblem( callExpression.calleeExpression ?: return, KotlinBundle.message("nested.1.call.in.0.could.be.simplified.to.2", scopeFunctionShortName, innerCallShortName, "onEach"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, NestedForEachFix(innerCallShortName) ) }) private class NestedForEachFix(val forEachCall: String) : LocalQuickFix { override fun getName() = KotlinBundle.message("simplify.call.fix.text", forEachCall, "onEach") override fun getFamilyName() = KotlinBundle.message("replace.0.with.1", "nested calls", "onEach") private class ReplaceLabelVisitor(val factory: KtPsiFactory) : KtTreeVisitorVoid() { override fun visitExpressionWithLabel(expression: KtExpressionWithLabel) { if (expression.getLabelName() != "forEach") return val expressionText = expression.text expression.replace( factory.createExpression( expressionText.replaceRange( expressionText.indexOf('@') + 1, expressionText.length, "onEach" ) ) ) } } override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val callExpression = descriptor.psiElement.parent as? KtCallExpression ?: return val outerBlock = callExpression.valueArguments.singleOrNull() ?: return val (label, lambda) = outerBlock.getArgumentExpression()?.unpackLabelAndLambdaExpression() ?: return val eachCall = when (val statement = lambda?.bodyExpression?.statements?.singleOrNull()) { is KtDotQualifiedExpression -> statement.selectorExpression as? KtCallExpression ?: return is KtCallExpression -> statement else -> return } val factory = KtPsiFactory(project) val innerBlock = eachCall.valueArguments.singleOrNull() ?: return if (label?.labelQualifier == null && eachCall.calleeExpression?.text == "forEach") { innerBlock.accept(ReplaceLabelVisitor(factory)) } val innerBlockExpression = innerBlock.getArgumentExpression() if (innerBlockExpression != null && KtPsiUtil.deparenthesize(innerBlockExpression) is KtCallableReferenceExpression) { callExpression.replace(factory.createExpressionByPattern("onEach($0)", innerBlockExpression)) } else { outerBlock.replace(innerBlock) descriptor.psiElement.replace(factory.createExpression("onEach")) } } } }
apache-2.0
ba0c3cb0d7b965ea87caa971fdfa9f2a
52.708333
158
0.658701
6.082586
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/codeVision/ClassUsages.kt
12
447
// MODE: usages <# block [ 5 Usages] #> open class SomeClass {} class SomeOtherClass : SomeClass {} // <== (1): class extension class SomeYetOtherClass : SomeClass { // <== (2): class extension <# block [ 1 Usage] #> fun acceptsClass(param: SomeClass) {} // <== (3): parameter type fun returnsInterface(): SomeClass {} // <== (4): return type fun main() = acceptsClass(object : SomeClass {}) // <== (5): anonymous class instance }
apache-2.0
52d7936cf7031e829015d8996e59052e
39.727273
89
0.624161
4.027027
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/checker/NestedObjects.kt
13
412
package nestedObjects object A { val b = B val d = A.B.A object B { val a = A val e = B.A object A { val a = A val b = B val x = nestedObjects.A.B.A val y = this<error>@A</error> } } } object B { val b = B val c = A.B } val a = A val b = B val c = A.B val d = A.B.A val e = B.<error>A</error>.<error>B</error>
apache-2.0
2532e24bc0fa82f2ade981b4d2bb2337
13.714286
45
0.43932
2.861111
false
false
false
false
philipw1988/MagicCarpet
src/main/kotlin/uk/co/agware/carpet/change/tasks/Task.kt
1
849
package uk.co.agware.carpet.change.tasks import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonSubTypes.Type import com.fasterxml.jackson.annotation.JsonTypeInfo import uk.co.agware.carpet.database.DatabaseConnector @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes( Type(value = FileTask::class, name = "FileTask"), Type(value = ScriptTask::class, name = "ScriptTask") ) interface Task : Comparable<Task> { var taskName: String var taskOrder: Int val query: String /** * Execute the task on the database * @param databaseConnector the connection to the database */ fun performTask(databaseConnector: DatabaseConnector) override fun compareTo(other: Task): Int { return this.taskOrder.compareTo(other.taskOrder) } }
apache-2.0
64790721ffc30c8d979cab2ded69056f
27.3
59
0.770318
3.628205
false
false
false
false
ThiagoGarciaAlves/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUSimpleNameReferenceExpression.kt
3
2489
/* * 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 org.jetbrains.uast.java import com.intellij.psi.* import org.jetbrains.uast.UElement import org.jetbrains.uast.USimpleNameReferenceExpression import org.jetbrains.uast.UTypeReferenceExpression class JavaUSimpleNameReferenceExpression( override val psi: PsiElement?, override val identifier: String, givenParent: UElement?, val reference: PsiReference? = null ) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression { override fun resolve() = (reference ?: psi as? PsiReference)?.resolve() override val resolvedName: String? get() = ((reference ?: psi as? PsiReference)?.resolve() as? PsiNamedElement)?.name override fun getPsiParentForLazyConversion(): PsiElement? { val parent = super.getPsiParentForLazyConversion() if (parent is PsiReferenceExpression && parent.parent is PsiMethodCallExpression) { return parent.parent } return parent } override fun convertParent(): UElement? = super.convertParent().let(this::unwrapCompositeQualifiedReference) } class JavaUTypeReferenceExpression( override val psi: PsiTypeElement, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UTypeReferenceExpression { override val type: PsiType get() = psi.type } class LazyJavaUTypeReferenceExpression( override val psi: PsiElement, givenParent: UElement?, private val typeSupplier: () -> PsiType ) : JavaAbstractUExpression(givenParent), UTypeReferenceExpression { override val type: PsiType by lz { typeSupplier() } } class JavaClassUSimpleNameReferenceExpression( override val identifier: String, val ref: PsiJavaReference, override val psi: PsiElement, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression { override fun resolve() = ref.resolve() override val resolvedName: String? get() = (ref.resolve() as? PsiNamedElement)?.name }
apache-2.0
5490bc35595d836a58753cff48d62cec
34.571429
110
0.765769
4.88998
false
false
false
false
dreampany/framework
frame/src/main/kotlin/com/dreampany/framework/util/DataUtilKt.kt
1
4612
package com.dreampany.framework.util import androidx.core.util.PatternsCompat import com.dreampany.framework.misc.Constants import com.google.common.base.Strings import java.util.* import kotlin.collections.ArrayList /** * Created by Roman-372 on 7/25/2019 * Copyright (c) 2019 bjit. All rights reserved. * [email protected] * Last modified $file.lastModified */ class DataUtilKt { companion object { fun getRandId() :String { return UUID.randomUUID().toString() } fun isEmpty(item: String?): Boolean { return item.isNullOrEmpty() } fun isEmpty(vararg items: String): Boolean { if (items.isEmpty()) { return true } for (item in items) { if (!Strings.isNullOrEmpty(item)) { return false } } return true } fun isAnyEmpty(vararg items: String?): Boolean { if (items.isEmpty()) { return true } for (item in items) { if (Strings.isNullOrEmpty(item)) { return true } } return false } fun join(vararg items: Int): String { val builder = StringBuilder() for (item in items) { builder.append(item) } return builder.toString() } fun join(vararg items: String): String { val builder = StringBuilder() for (item in items) { builder.append(item) } return builder.toString() } fun getFirstPart(value: String, sep: String): String { return value.split(sep).first() } fun isValidUrl(url: String): Boolean { return PatternsCompat.WEB_URL.matcher(url).matches() } fun isValidImageUrl(url: String): Boolean { val pattern = Constants.Pattern.IMAGE_PATTERN return pattern.matcher(url).matches() } fun joinPrefixIf(url: String, prefix: String): String { return if (!url.startsWith(prefix)) prefix.plus(url) else url } fun formatReadableSize(value: Long): String { return formatReadableSize(value, false) } fun formatReadableSize(value: Long, si: Boolean): String { val unit = if (si) 1000 else 1024 if (value < unit) return "$value B" val exp = (Math.log(value.toDouble()) / Math.log(unit.toDouble())).toInt() val pre = (if (si) "kMGTPE" else "KMGTPE")[exp - 1] + if (si) "" else "" return String.format( Locale.ENGLISH, "%.1f %sB", value / Math.pow(unit.toDouble(), exp.toDouble()), pre ) } /* fun isEmpty(collection: Collection<*>?): Boolean { return collection == null || collection.isEmpty() }*/ fun <T> sub(list: MutableList<T>?, count: Int): MutableList<T>? { var count = count if (list.isNullOrEmpty()) { return null } count = if (list.size < count) list.size else count return ArrayList(list.subList(0, count)) } fun <T> takeFirst(list: MutableList<T>?, count: Int): MutableList<T>? { if (list.isNullOrEmpty()) { return null } val result = sub(list, count) removeAll(list, result) return result } fun <T> takeFirst(list: ArrayList<String>?) : String? { return list?.first() } fun <T> takeRandom(list: ArrayList<String>?) : String? { return list?.random() } fun <T> removeAll(list: MutableList<T>, sub: MutableList<T>?): MutableList<T>? { sub?.run { list.removeAll(this) } return list } /* fun formatReadableSize(value: Long, si: Boolean): String { val unit = if (si) 1000 else 1024 if (value < unit) return value.toString() val exp = (Math.log(value.toDouble()) / Math.log(unit.toDouble())).toInt() val pre = (if (si) "kMGTPE" else "KMGTPE")[exp - 1] + if (si) "" else "i" return String.format( Locale.ENGLISH, "%.1f %s", value / Math.pow(unit.toDouble(), exp.toDouble()), pre ) }*/ } }
apache-2.0
52a281177b9619328fcca09df1fc1cff
29.549669
88
0.506938
4.530452
false
false
false
false
gajwani/kotlin-base
src/test/kotlin/com/example/project/SpekTest.kt
1
1730
package com.example.project import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import junit.framework.TestCase.assertEquals import org.jetbrains.spek.api.dsl.context //import org.jetbrains.spek.api.Spek //import org.jetbrains.spek.api.dsl.describe //import org.jetbrains.spek.api.dsl.it //import org.junit.jupiter.api.Assertions.assertEquals // //class SpekTest : Spek({ // describe("a calculator") { // val calculator = CalculatorKotlin() // // it("should return the result of adding the first number to the second number") { // val sum = calculator.add(2, 4) // assertEquals(6, sum) // } // // it("should return the result of subtracting the second number from the first number") { // val subtract = calculator.subtract(4, 2) // assertEquals(2, subtract) // } // } //}) object SpekTest: Spek({ class Calculator { fun sum(a: Int, b: Int): Int { return a + b } fun subtract(a: Int, b: Int): Int { return a - b } } describe("a calculator") { val calculator = Calculator() context("addition") { val sum = calculator.sum(4, 2) it("should return the result of adding the first number to the second number") { assertEquals(6, sum) } } context("subtraction") { val subtract = calculator.subtract(4, 2) it("should return the result of subtracting the second number from the first number") { assertEquals(2, subtract) } } } })
apache-2.0
bca10bdd0e6e1c260cf2cb46c1b09ad1
26.919355
99
0.59711
3.977011
false
false
false
false
kerubistan/kerub
src/main/kotlin/com/github/kerubistan/kerub/host/KeyPairFactory.kt
2
828
package com.github.kerubistan.kerub.host import com.github.kerubistan.kerub.utils.emptyString import io.github.kerubistan.kroki.io.resource import java.security.KeyPair import java.security.KeyStore import java.security.PrivateKey class KeyPairFactory { var keyStorePath: String = "keystore.jks" var keyStorePassword = emptyString var certificatePassword = emptyString var alias = "kerub" fun createKeyPair(): KeyPair { val keyStore = KeyStore.getInstance("JKS") resource(keyStorePath).use { if (it == null) { throw IllegalArgumentException("Keystore $keyStorePath not found") } keyStore.load(it, keyStorePassword.toCharArray()) } val key = keyStore.getKey(alias, certificatePassword.toCharArray()) val cert = keyStore.getCertificate(alias) return KeyPair(cert.publicKey, key as PrivateKey) } }
apache-2.0
50dcab454d6ae6c775f03ed69b578667
29.703704
70
0.774155
3.869159
false
false
false
false
slisson/intellij-community
platform/built-in-server/src/org/jetbrains/io/fastCgi/FastCgiDecoder.kt
9
4786
package org.jetbrains.io.fastCgi import com.intellij.util.Consumer import gnu.trove.TIntObjectHashMap import gnu.trove.TIntObjectProcedure import io.netty.buffer.ByteBuf import io.netty.buffer.CompositeByteBuf import io.netty.channel.ChannelHandlerContext import io.netty.util.CharsetUtil import org.jetbrains.io.Decoder class FastCgiDecoder(private val errorOutputConsumer: Consumer<String>, private val responseHandler: FastCgiService) : Decoder(), Decoder.FullMessageConsumer<Void> { private enum class State { HEADER, CONTENT } private var state = State.HEADER private enum class ProtocolStatus { REQUEST_COMPLETE, CANT_MPX_CONN, OVERLOADED, UNKNOWN_ROLE } object RecordType { val END_REQUEST = 3 val STDOUT = 6 val STDERR = 7 } private var type: Int = 0 private var id: Int = 0 private var contentLength: Int = 0 private var paddingLength: Int = 0 private val dataBuffers = TIntObjectHashMap<ByteBuf>() override fun messageReceived(context: ChannelHandlerContext, input: ByteBuf) { while (true) { when (state) { FastCgiDecoder.State.HEADER -> { if (paddingLength > 0) { if (input.readableBytes() > paddingLength) { input.skipBytes(paddingLength) paddingLength = 0 } else { paddingLength -= input.readableBytes() input.skipBytes(input.readableBytes()) return } } val buffer = getBufferIfSufficient(input, FastCgiConstants.HEADER_LENGTH, context) ?: return decodeHeader(buffer) state = State.CONTENT if (contentLength > 0) { readContent(input, context, contentLength, this) } state = State.HEADER } FastCgiDecoder.State.CONTENT -> { if (contentLength > 0) { readContent(input, context, contentLength, this) } state = State.HEADER } } } } override fun channelInactive(context: ChannelHandlerContext) { try { if (!dataBuffers.isEmpty()) { dataBuffers.forEachEntry(object : TIntObjectProcedure<ByteBuf> { override fun execute(a: Int, buffer: ByteBuf): Boolean { try { buffer.release() } catch (e: Throwable) { LOG.error(e) } return true } }) dataBuffers.clear() } } finally { super<Decoder>.channelInactive(context) } } private fun decodeHeader(buffer: ByteBuf) { buffer.skipBytes(1) type = buffer.readUnsignedByte().toInt() id = buffer.readUnsignedShort() contentLength = buffer.readUnsignedShort() paddingLength = buffer.readUnsignedByte().toInt() buffer.skipBytes(1) } override fun contentReceived(buffer: ByteBuf, context: ChannelHandlerContext, isCumulateBuffer: Boolean): Void? { when (type) { RecordType.END_REQUEST -> { val appStatus = buffer.readInt() val protocolStatus = buffer.readUnsignedByte().toInt() if (appStatus != 0 || protocolStatus != ProtocolStatus.REQUEST_COMPLETE.ordinal()) { LOG.warn("Protocol status $protocolStatus") dataBuffers.remove(id) responseHandler.responseReceived(id, null) } else if (protocolStatus == ProtocolStatus.REQUEST_COMPLETE.ordinal()) { responseHandler.responseReceived(id, dataBuffers.remove(id)) } } RecordType.STDOUT -> { var data = dataBuffers.get(id) val sliced = if (isCumulateBuffer) buffer else buffer.slice(buffer.readerIndex(), contentLength) if (data == null) { dataBuffers.put(id, sliced) } else if (data is CompositeByteBuf) { data.addComponent(sliced) data.writerIndex(data.writerIndex() + sliced.readableBytes()) } else { if (sliced is CompositeByteBuf) { data = sliced.addComponent(0, data) data.writerIndex(data.writerIndex() + data.readableBytes()) } else { data = context.alloc().compositeBuffer(Decoder.DEFAULT_MAX_COMPOSITE_BUFFER_COMPONENTS).addComponents(data, sliced) data.writerIndex(data.writerIndex() + data.readableBytes() + sliced.readableBytes()) } dataBuffers.put(id, data) } sliced.retain() } RecordType.STDERR -> { try { errorOutputConsumer.consume(buffer.toString(buffer.readerIndex(), contentLength, CharsetUtil.UTF_8)) } catch (e: Throwable) { LOG.error(e) } } else -> LOG.error("Unknown type " + type) } return null } }
apache-2.0
c5a6a0ad4b50b9c0a37e6b96d5516c28
28.91875
165
0.613456
4.571156
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/db/entity/SavedSearch.kt
1
426
package com.orgzly.android.db.entity import androidx.room.* @Entity( tableName = "searches" ) data class SavedSearch( @PrimaryKey(autoGenerate = true) val id: Long, val name: String, val query: String, val position: Int ) { fun areContentsTheSame(that: SavedSearch): Boolean { return name == that.name && query == that.query && position == that.position } }
gpl-3.0
f34c5b29e9bfc73013f999f9b6a88199
19.333333
84
0.617371
4.176471
false
false
false
false
dtretyakov/teamcity-rust
plugin-rust-agent/src/main/kotlin/jetbrains/buildServer/rust/CargoRunnerBuildService.kt
1
6479
/* * Copyright 2000-2021 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"). * See LICENSE in the project root for license information. */ package jetbrains.buildServer.rust import com.github.zafarkhaja.semver.Version import jetbrains.buildServer.RunBuildException import jetbrains.buildServer.agent.BuildFinishedStatus import jetbrains.buildServer.agent.BuildRunnerContextEx import jetbrains.buildServer.agent.ToolCannotBeFoundException import jetbrains.buildServer.agent.inspections.InspectionReporter import jetbrains.buildServer.agent.runner.BuildServiceAdapter import jetbrains.buildServer.agent.runner.ProcessListener import jetbrains.buildServer.agent.runner.ProgramCommandLine import jetbrains.buildServer.rust.cargo.* import jetbrains.buildServer.rust.inspections.ClippyInspectionsParser import jetbrains.buildServer.rust.inspections.ClippyListener import jetbrains.buildServer.rust.logging.BlockListener import jetbrains.buildServer.rust.logging.CargoLoggerFactory import jetbrains.buildServer.rust.logging.CargoLoggingListener import jetbrains.buildServer.util.OSType import jetbrains.buildServer.util.StringUtil /** * Cargo runner service. */ class CargoRunnerBuildService( private val runnerContext: BuildRunnerContextEx, private val inspectionReporter: InspectionReporter, private val clippyInspectionsParser: ClippyInspectionsParser ) : BuildServiceAdapter() { private val myCargoWithStdErrVersion = Version.forIntegers(0, 13) private val myArgumentsProviders = mapOf( CargoConstants.COMMAND_BENCH to BenchArgumentsProvider(), CargoConstants.COMMAND_BUILD to BuildArgumentsProvider(), CargoConstants.COMMAND_CLEAN to CleanArgumentsProvider(), CargoConstants.COMMAND_CLIPPY to ClippyArgumentsProvider(), CargoConstants.COMMAND_DOC to DocArgumentsProvider(), CargoConstants.COMMAND_LOGIN to LoginArgumentsProvider(), CargoConstants.COMMAND_PACKAGE to PackageArgumentsProvider(), CargoConstants.COMMAND_PUBLISH to PublishArgumentsProvider(), CargoConstants.COMMAND_RUN to RunArgumentsProvider(), CargoConstants.COMMAND_RUSTC to RustcArgumentsProvider(), CargoConstants.COMMAND_RUSTDOC to RustDocArgumentsProvider(), CargoConstants.COMMAND_TEST to TestArgumentsProvider(), CargoConstants.COMMAND_UPDATE to UpdateArgumentsProvider(), CargoConstants.COMMAND_YANK to YankArgumentsProvider() ) override fun getRunResult(exitCode: Int): BuildFinishedStatus { if (exitCode == 0) { return BuildFinishedStatus.FINISHED_SUCCESS } val commandName = runnerParameters[CargoConstants.PARAM_COMMAND] val argumentsProvider = myArgumentsProviders[commandName] if (argumentsProvider == null) { val buildException = RunBuildException("Unable to construct arguments for cargo command $commandName") buildException.isLogStacktrace = false throw buildException } return if (argumentsProvider.shouldFailBuildIfCommandFailed()) { BuildFinishedStatus.FINISHED_FAILED } else { BuildFinishedStatus.FINISHED_SUCCESS } } override fun makeProgramCommandLine(): ProgramCommandLine { val parameters = runnerParameters val commandName = parameters[CargoConstants.PARAM_COMMAND] if (StringUtil.isEmpty(commandName)) { val buildException = RunBuildException("Cargo command name is empty") buildException.isLogStacktrace = false throw buildException } val argumentsProvider = myArgumentsProviders[commandName] if (argumentsProvider == null) { val buildException = RunBuildException("Unable to construct arguments for cargo command $commandName") buildException.isLogStacktrace = false throw buildException } val toolchainVersion = parameters[CargoConstants.PARAM_TOOLCHAIN]?.trim() ?: "" val (toolPath, arguments) = if (toolchainVersion.isNotEmpty()) { val rustupPath = getPath(CargoConstants.RUSTUP_CONFIG_NAME) rustupPath to argumentsProvider.getArguments(runnerContext).toMutableList().apply { addAll(0, arrayListOf("run", toolchainVersion, "cargo")) } } else { getPath(CargoConstants.CARGO_CONFIG_NAME) to argumentsProvider.getArguments(runnerContext) } runnerContext.configParameters[CargoConstants.CARGO_CONFIG_NAME]?.let { if (Version.valueOf(it).greaterThanOrEqualTo(myCargoWithStdErrVersion)) { return when (runnerContext.virtualContext.targetOSType) { OSType.WINDOWS -> { createProgramCommandline("cmd.exe", arrayListOf("/c", "2>&1", toolPath).apply { addAll(arguments) }) } OSType.UNIX -> { createProgramCommandline("sh", arrayListOf("-c", "$toolPath ${arguments.joinToString(" ")} 2>&1")) } else -> { createProgramCommandline("bash", arrayListOf("-c", "$toolPath ${arguments.joinToString(" ")} 2>&1")) } } } } return createProgramCommandline(toolPath, arguments) } private fun getPath(toolName: String): String { try { return getToolPath(toolName) } catch (e: ToolCannotBeFoundException) { val buildException = RunBuildException(e) buildException.isLogStacktrace = false throw buildException } } override fun isCommandLineLoggingEnabled() = false override fun getListeners(): List<ProcessListener> { val loggerFactory = CargoLoggerFactory(logger) val command = runnerParameters[CargoConstants.PARAM_COMMAND] val blockName = "cargo $command" val listeners = mutableListOf( CargoLoggingListener(loggerFactory), BlockListener(blockName, logger) ) if (command == CargoConstants.COMMAND_CLIPPY) { listeners.add( ClippyListener(inspectionReporter, clippyInspectionsParser) ) } return listeners } }
apache-2.0
640d4d9c57604014534058b284d44b7d
41.346405
124
0.679117
5.490678
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/sql/SqlJsonGeneImpact.kt
1
3515
package org.evomaster.core.search.impact.impactinfocollection.sql import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.sql.SqlJSONGene import org.evomaster.core.search.impact.impactinfocollection.* import org.evomaster.core.search.impact.impactinfocollection.value.ObjectGeneImpact /** * created by manzh on 2019-09-29 */ class SqlJsonGeneImpact( sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo, val geneImpact: ObjectGeneImpact) : GeneImpact(sharedImpactInfo, specificImpactInfo){ constructor(id : String, sqlJSONGene: SqlJSONGene) : this(SharedImpactInfo(id), SpecificImpactInfo() ,geneImpact = ImpactUtils.createGeneImpact(sqlJSONGene.objectGene, id) as? ObjectGeneImpact?:throw IllegalStateException("geneImpact of SqlJSONImpact should be ObjectGeneImpact")) override fun copy(): SqlJsonGeneImpact { return SqlJsonGeneImpact( shared.copy(), specific.copy(), geneImpact.copy()) } override fun clone(): SqlJsonGeneImpact { return SqlJsonGeneImpact( shared.clone(),specific.clone(), geneImpact.clone() ) } override fun countImpactWithMutatedGeneWithContext(gc: MutatedGeneWithContext, noImpactTargets: Set<Int>, impactTargets: Set<Int>, improvedTargets: Set<Int>, onlyManipulation: Boolean){ countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene) if (gc.current !is SqlJSONGene) throw IllegalStateException("gc.current (${gc.current::class.java.simpleName}) should be SqlJSONGene") if (gc.previous == null && impactTargets.isNotEmpty()) return if (gc.previous == null){ val mutatedGeneWithContext = MutatedGeneWithContext( previous = null, current = gc.current.objectGene, numOfMutatedGene = gc.numOfMutatedGene ) geneImpact.countImpactWithMutatedGeneWithContext(mutatedGeneWithContext, noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation) return } if ( gc.previous !is SqlJSONGene){ throw IllegalStateException("gc.previous (${gc.previous::class.java.simpleName}) should be SqlJSONGene") } val mutatedGeneWithContext = MutatedGeneWithContext( previous = gc.previous.objectGene, current = gc.current.objectGene, numOfMutatedGene = gc.numOfMutatedGene ) geneImpact.countImpactWithMutatedGeneWithContext(mutatedGeneWithContext, noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation) } override fun validate(gene: Gene): Boolean = gene is SqlJSONGene override fun flatViewInnerImpact(): Map<String, Impact> { return mutableMapOf("${getId()}-${geneImpact.getId()}" to geneImpact).plus(geneImpact.flatViewInnerImpact().map { "${getId()}-${it.key}" to it.value }) } override fun innerImpacts(): List<Impact> { return listOf(geneImpact) } override fun syncImpact(previous: Gene?, current: Gene) { check(previous,current) geneImpact.syncImpact((previous as SqlJSONGene).objectGene, (current as SqlJSONGene).objectGene) } }
lgpl-3.0
177a98568f65ca7bbb7de2ee85886c5e
49.956522
284
0.713229
5.123907
false
false
false
false
EMResearch/EvoMaster
e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/boottimetargets/BootTimeTargetsRest.kt
1
1324
package com.foo.rest.examples.spring.openapi.v3.boottimetargets import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import java.time.LocalDateTime @RestController @RequestMapping(path = ["/api/boottimetargets"]) class BootTimeTargetsRest { private val startupTime = LocalDateTime.now() private var startupInfo : String init { startupInfo = "${branchTarget()}:$startupTime" println("startupInfo:$startupInfo") } companion object{ // TODO targets for lines 24 and 25 seems to be skipped, need a further check once class initializer is instrumented private const val SKIPPED_LINE = "SKIPPED?" init { println("Hello $SKIPPED_LINE") } } @GetMapping open fun getData() : ResponseEntity<String> { return ResponseEntity.status(200) .contentType(MediaType.APPLICATION_JSON) .body("$startupTime;${LocalDateTime.now()}") } private fun branchTarget() : String{ return if (startupTime.second % 2 == 0) "EVEN" else "ODD" } }
lgpl-3.0
81995e3f1d95e3a43d9319bc095500fb
27.804348
124
0.679758
4.518771
false
false
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/internal/interceptor/RateLimitInterceptor.kt
2
4766
package me.proxer.library.internal.interceptor import com.squareup.moshi.Moshi import com.squareup.moshi.Types import me.proxer.library.ProxerException.ServerErrorType.RATE_LIMIT import me.proxer.library.internal.ProxerResponse import me.proxer.library.util.ProxerUrls import okhttp3.Cache import okhttp3.Interceptor import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Protocol import okhttp3.Request import okhttp3.Response import okhttp3.ResponseBody.Companion.toResponseBody import java.util.Date internal class RateLimitInterceptor(private val moshi: Moshi, private val cache: Cache?) : Interceptor { private companion object { private const val WAIT_THRESHOLD = 2_000 private val errorMediaType = "application/json".toMediaTypeOrNull() private val responseType = Types.newParameterizedType(ProxerResponse::class.java, Unit::class.java) private val limits = mapOf( "anime" to Limit(20, 360_000), "apps" to Limit(100, 30_000), // Not enforced by api. "chat" to Limit(30, 30_000), "comment" to Limit(100, 30_000), // Not enforced by api. "files" to Limit(30, 100_000), "forum" to Limit(100, 30_000), // Not enforced by api. "info" to Limit(60, 360_000), "list" to Limit(60, 60_000), "manga" to Limit(10, 300_000), "media" to Limit(100, 30_000), // Not enforced by api. "messenger" to Limit(100, 50_000), "misc" to Limit(100, 30_000), // Not enforced by api. "notifications" to Limit(100, 30_000), // Not enforced by api. "ucp" to Limit(40, 60_000), "user" to Limit(40, 360_000), "users" to Limit(40, 360_000), "wiki" to Limit(100, 30_000) // Not enforced by api. ) } private var state = limits.mapValues { State(0, null) } @Suppress("ReturnCount") override fun intercept(chain: Interceptor.Chain): Response { val oldRequest = chain.request() if (oldRequest.url.host != ProxerUrls.apiBase.host) { return chain.proceed(oldRequest) } val apiClass = oldRequest.url.pathSegments.getOrNull(2) val limit = limits[apiClass] if (apiClass == null || limit == null) { return chain.proceed(oldRequest) } return intercept(apiClass, limit, chain, oldRequest) } @Suppress("ReturnCount") private fun intercept( apiClass: String, limit: Limit, chain: Interceptor.Chain, oldRequest: Request ): Response { synchronized(limit) { val (requests, firstRequest) = state.getValue(apiClass) val timeDifferenceMillis = if (firstRequest != null) Date().time - firstRequest.time else null if (timeDifferenceMillis == null || timeDifferenceMillis > limit.millis) { state = state.update(apiClass, 1, Date()) return chain.proceed(oldRequest) } else if (requests + 2 >= limit.maxRequests) { // Do nothing if the request is in the cache. if (cache?.urls()?.asSequence()?.contains(oldRequest.url.toString()) == true) { return chain.proceed(oldRequest) } return if ((limit.millis - timeDifferenceMillis) < WAIT_THRESHOLD) { Thread.sleep(timeDifferenceMillis) intercept(chain) } else { val errorBody = moshi .adapter<ProxerResponse<Unit?>>(responseType) .toJson(ProxerResponse(true, "Rate limit", RATE_LIMIT.code, null)) Response.Builder() .body(errorBody.toResponseBody(errorMediaType)) .protocol(Protocol.HTTP_1_1) .request(oldRequest) .code(200) .message("") .build() } } else { val response = chain.proceed(oldRequest) // Only increment on responses not coming from cache. if (response.networkResponse != null) { state = state.update(apiClass, requests + 1, firstRequest) } return response } } } private fun Map<String, State>.update(apiClass: String, requests: Int, firstRequest: Date?): Map<String, State> { return toMutableMap().apply { put(apiClass, State(requests, firstRequest)) } } private data class Limit(val maxRequests: Int, val millis: Int) private data class State(val requests: Int, val firstRequest: Date?) }
gpl-3.0
33f16584a3115259dc0bcc3f4f5f6643
37.747967
117
0.587914
4.470919
false
false
false
false
EdenYoon/LifeLogging
src/com/humanebyte/lifelogging/AccessibilityEventCaptureService.kt
1
14888
package com.humanebyte.lifelogging /** * Created by edenyoon on 2016. 2. 16.. */ import android.accessibilityservice.AccessibilityService import android.accessibilityservice.AccessibilityServiceInfo import android.app.AlertDialog import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.* import android.hardware.camera2.CameraManager import android.os.Handler import android.os.Message import android.util.Log import android.view.KeyEvent import android.view.WindowManager import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityNodeInfo import android.widget.Toast abstract class AccessibilityEventCaptureService : AccessibilityService() { private var mReceiver: BroadcastReceiver? = null private var forceSpeakIntentReceiver: BroadcastReceiver? = null private var musicIntentReceiver: BroadcastReceiver? = null private var isEatKeyEvent: Boolean = true private val FOR_MEDIA = 1 private val FORCE_NONE = 0 private val FORCE_SPEAKER = 1 private val setForceUse = Class.forName("android.media.AudioSystem").getMethod("setForceUse", Integer.TYPE, Integer.TYPE) private var cameraManager: CameraManager? = null private val LONG_PRESS_PERIOD: Long = 400 private val BUTTON_PRESS_INTERVAL: Long = 200 private var timeKeyDown: Long = 0 private var timeKeyUp: Long = 0 private var clickSequence: String = "" private val eventKeyUp = 1001 private val handlerKeyUp = object : Handler() { override fun handleMessage(msg: Message) { when (msg.what) { eventKeyUp -> { handleClickSequence(clickSequence) clickSequence = "" } } } private fun handleClickSequence(seq: String) { if (seq == "SS") { Log.d(TAG, "~~~~ Camera Torch Mode On/Off. Will ${!torchMode}") if (cameraManager != null) { cameraManager!!.setTorchMode(cameraManager!!.cameraIdList[0], !torchMode) } else { torchMode = false } } } } private var messageKeyUp: Message? = null private var torchMode: Boolean = false private val callbackTorch = object: CameraManager.TorchCallback() { override fun onTorchModeChanged(cameraId: String?, enabled: Boolean) { if (cameraManager != null && cameraManager!!.cameraIdList[0] == cameraId) torchMode = enabled super.onTorchModeChanged(cameraId, enabled) } override fun onTorchModeUnavailable(cameraId: String?) { torchMode = false super.onTorchModeUnavailable(cameraId) } } public override fun onKeyEvent(event: KeyEvent): Boolean { val action = event.action val keyCode = event.keyCode //Log.d(TAG, "action: ${getActionName(action)}, keyCode: ${KeyEvent.keyCodeToString(keyCode)}") if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK) { if (action === KeyEvent.ACTION_DOWN) { handlerKeyUp.removeMessages(eventKeyUp) timeKeyDown = System.currentTimeMillis() } else if (action == KeyEvent.ACTION_UP) { timeKeyUp = System.currentTimeMillis() if (timeKeyUp - timeKeyDown < LONG_PRESS_PERIOD) clickSequence += "S" else clickSequence += "L" messageKeyUp = handlerKeyUp.obtainMessage(eventKeyUp) handlerKeyUp.sendMessageDelayed(messageKeyUp, BUTTON_PRESS_INTERVAL) //notify() } if (isEatKeyEvent) return true } return super.onKeyEvent(event) } private fun getActionName(type: Int): String { when (type) { KeyEvent.ACTION_DOWN -> return "KeyEvent.ACTION_DOWN" KeyEvent.ACTION_UP -> return "KeyEvent.ACTION_UP" KeyEvent.ACTION_MULTIPLE -> return "KeyEvent.ACTION_MULTIPLE" } return "KeyEvent.Unknown" } private fun notify() { val pendingIntent = PendingIntent.getActivity(this, 0, Intent(this, AccessibilityEventCaptureService::class.java), PendingIntent.FLAG_UPDATE_CURRENT) val builder = Notification.Builder(this) // ์ž‘์€ ์•„์ด์ฝ˜ ์ด๋ฏธ์ง€. builder.setSmallIcon(R.drawable.ic_launcher) // ์•Œ๋ฆผ์ด ์ถœ๋ ฅ๋  ๋•Œ ์ƒ๋‹จ์— ๋‚˜์˜ค๋Š” ๋ฌธ๊ตฌ. builder.setTicker("๋ฏธ๋ฆฌ๋ณด๊ธฐ ์ž…๋‹ˆ๋‹ค.") // ์•Œ๋ฆผ ์ถœ๋ ฅ ์‹œ๊ฐ„. builder.setWhen(System.currentTimeMillis()) // ์•Œ๋ฆผ ์ œ๋ชฉ. builder.setContentTitle("๋‚ด์šฉ๋ณด๋‹ค ์กฐ๊ธˆ ํฐ ์ œ๋ชฉ!") // ์•Œ๋ฆผ ๋‚ด์šฉ. builder.setContentText("์ œ๋ชฉ ํ•˜๋‹จ์— ์ถœ๋ ฅ๋  ๋‚ด์šฉ!") // ์•Œ๋ฆผ์‹œ ์‚ฌ์šด๋“œ, ์ง„๋™, ๋ถˆ๋น›์„ ์„ค์ • ๊ฐ€๋Šฅ. builder.setDefaults(Notification.DEFAULT_LIGHTS) // ์•Œ๋ฆผ ํ„ฐ์น˜์‹œ ๋ฐ˜์‘. builder.setContentIntent(pendingIntent) // ์•Œ๋ฆผ ํ„ฐ์น˜์‹œ ๋ฐ˜์‘ ํ›„ ์•Œ๋ฆผ ์‚ญ์ œ ์—ฌ๋ถ€. builder.setAutoCancel(true) // ์šฐ์„ ์ˆœ์œ„. builder.setPriority(Notification.PRIORITY_MAX) // ๊ณ ์œ ID๋กœ ์•Œ๋ฆผ์„ ์ƒ์„ฑ. val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager nm.notify(123456, builder.build()) } override fun onAccessibilityEvent(event: AccessibilityEvent) { val eventText = getTypeName(event.eventType) + "====" + event.contentDescription Log.e("------------------------", "-------------------------") Log.d("PackageName", event.packageName.toString()) Log.d("EventName", eventText) traverseNode(rootInActiveWindow) Log.e("------------------------", "-------------------------") if (hasMessage(event) == false) { return } val eventType = event.eventType val sourcePackageName = event.packageName as String val messages = event.text val message = messages[0] if (eventType == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) { val sendingIntent = Intent(ACTION_CAPTURE_NOTIFICATION) val parcelable = event.parcelableData if (parcelable is Notification) { sendingIntent.putExtra(EXTRA_NOTIFICATION_TYPE, EXTRA_TYPE_NOTIFICATION) } else { sendingIntent.putExtra(EXTRA_NOTIFICATION_TYPE, EXTRA_TYPE_OTHERS) } sendingIntent.putExtra(EXTRA_PACKAGE_NAME, sourcePackageName) sendingIntent.putExtra(EXTRA_MESSAGE, message) applicationContext.sendBroadcast(sendingIntent) } } protected fun setTag(tag: String) { AccessibilityEventCaptureService.TAG = tag } override fun onServiceConnected() { Log.e("---------ServiceConnected--------------", "------------ServiceConnected------------") val info = AccessibilityServiceInfo() info.packageNames = arrayOf("com.android.mms") info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK info.notificationTimeout = 100 info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN info.flags = AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS serviceInfo = info mReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val isEat:Boolean = intent.getBooleanExtra("eat", true) isEatKeyEvent = isEat } } this.registerReceiver(mReceiver, IntentFilter("com.humanebyte.lifelogging.eat_keyevent")) forceSpeakIntentReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val force_speaker:Boolean = intent.getBooleanExtra("force_speaker", true) if (force_speaker) { setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER) } else { setForceUse.invoke(null, FOR_MEDIA, FORCE_NONE) } } } this.registerReceiver(forceSpeakIntentReceiver, IntentFilter("com.humanebyte.lifelogging.force_speaker")) musicIntentReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) { val state = intent.getIntExtra("state", -1) if (state == 1) { displayHeadphoneAlert() } else if (state == 0) { setForceUse.invoke(null, FOR_MEDIA, FORCE_NONE) } } } } registerReceiver(musicIntentReceiver, IntentFilter(Intent.ACTION_HEADSET_PLUG)) cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager cameraManager?.registerTorchCallback(callbackTorch, null) } override fun onDestroy() { this.unregisterReceiver(this.mReceiver) this.unregisterReceiver(this.forceSpeakIntentReceiver) this.unregisterReceiver(this.musicIntentReceiver) cameraManager = null } private fun displayHeadphoneAlert() { val builder = AlertDialog.Builder(this) builder.setMessage("Is it headphone?").setCancelable(false).setPositiveButton("Yes", object : DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface, id: Int) { setForceUse.invoke(null, FOR_MEDIA, FORCE_NONE) dialog.cancel() } }).setNegativeButton("No", object : DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface, id: Int) { setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER) dialog.cancel() } }) val alert = builder.create() alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); alert.show() } public override fun onGesture(gestureId: Int): Boolean { Log.v("THEIA", String.format("onGesture: [type] %s", gIdToString(gestureId))) return false } override fun onInterrupt() { Log.e("---------Interrupt--------------", "------------Interrupt------------") } private fun traverseNode(node: AccessibilityNodeInfo?) { if (null == node) return val count = node.childCount if (count > 0) { for (i in 0..count - 1) { val childNode = node.getChild(i) traverseNode(childNode) } } else { val text = node.text Log.d("test", "Node text = " + text) } } private fun getTypeName(type: Int): String { when (type) { AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START -> return "TYPE_TOUCH_EXPLORATION_GESTURE_START" AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END -> return "TYPE_TOUCH_EXPLORATION_GESTURE_END" AccessibilityEvent.TYPE_TOUCH_INTERACTION_START -> return "TYPE_TOUCH_INTERACTION_START" AccessibilityEvent.TYPE_TOUCH_INTERACTION_END -> return "TYPE_TOUCH_INTERACTION_END" AccessibilityEvent.TYPE_GESTURE_DETECTION_START -> return "TYPE_GESTURE_DETECTION_START" AccessibilityEvent.TYPE_GESTURE_DETECTION_END -> return "TYPE_GESTURE_DETECTION_END" AccessibilityEvent.TYPE_VIEW_HOVER_ENTER -> return "TYPE_VIEW_HOVER_ENTER" AccessibilityEvent.TYPE_VIEW_HOVER_EXIT -> return "TYPE_VIEW_HOVER_EXIT" AccessibilityEvent.TYPE_VIEW_SCROLLED -> return "TYPE_VIEW_SCROLLED" AccessibilityEvent.TYPE_VIEW_CLICKED -> return "TYPE_VIEW_CLICKED" AccessibilityEvent.TYPE_VIEW_LONG_CLICKED -> return "TYPE_VIEW_LONG_CLICKED" AccessibilityEvent.TYPE_VIEW_FOCUSED -> return "TYPE_VIEW_FOCUSED" AccessibilityEvent.TYPE_VIEW_SELECTED -> return "TYPE_VIEW_SELECTED" AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED -> return "TYPE_VIEW_ACCESSIBILITY_FOCUSED" AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED -> return "TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED" AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> return "TYPE_WINDOW_STATE_CHANGED" AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED -> return "TYPE_NOTIFICATION_STATE_CHANGED" AccessibilityEvent.TYPE_ANNOUNCEMENT -> return "TYPE_ANNOUNCEMENT" AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED -> return "TYPE_WINDOW_CONTENT_CHANGED" AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED -> return "TYPE_VIEW_TEXT_CHANGED" AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED -> return "TYPE_VIEW_TEXT_SELECTION_CHANGED" AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY -> return "TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY" } return "Unknown" } private fun gIdToString(gID: Int): String { when (gID) { 1 -> return "GESTURE_SWIPE_UP" 2 -> return "GESTURE_SWIPE_DOWN" 3 -> return "GESTURE_SWIPE_LEFT" 4 -> return "GESTURE_SWIPE_RIGHT" 5 -> return "GESTURE_SWIPE_LEFT_AND_RIGHT" 6 -> return "GESTURE_SWIPE_RIGHT_AND_LEFT" 7 -> return "GESTURE_SWIPE_UP_AND_DOWN" 8 -> return "GESTURE_SWIPE_DOWN_AND_UP" 9 -> return "GESTURE_SWIPE_LEFT_AND_UP" 10 -> return "GESTURE_SWIPE_LEFT_AND_DOWN" 11 -> return "GESTURE_SWIPE_RIGHT_AND_UP" 12 -> return "GESTURE_SWIPE_RIGHT_AND_DOWN" 13 -> return "GESTURE_SWIPE_UP_AND_LEFT" 14 -> return "GESTURE_SWIPE_UP_AND_RIGHT" 15 -> return "GESTURE_SWIPE_DOWN_AND_LEFT" 16 -> return "GESTURE_SWIPE_DOWN_AND_RIGHT" } return "UNKNOWN" } private fun hasMessage(event: AccessibilityEvent?): Boolean { return event != null && event.text.size > 0 } companion object { val ACTION_CAPTURE_NOTIFICATION = "action_capture_notification" val EXTRA_NOTIFICATION_TYPE = "extra_notification_type" val EXTRA_PACKAGE_NAME = "extra_package_name" val EXTRA_MESSAGE = "extra_message" val EXTRA_TYPE_NOTIFICATION = 0x19 val EXTRA_TYPE_OTHERS = EXTRA_TYPE_NOTIFICATION + 1 var TAG = AccessibilityEventCaptureService::class.java.simpleName } }
mit
fb300b29257ad7fc1e2acaee540a33c7
38.961853
157
0.613937
4.563161
false
false
false
false
googlecodelabs/display-nearby-places-ar-android
starter/app/src/main/java/com/google/codelabs/findnearbyplacesar/ar/PlaceNode.kt
2
2134
// 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.codelabs.findnearbyplacesar.ar import android.content.Context import android.view.View import android.widget.TextView import com.google.ar.sceneform.Node import com.google.ar.sceneform.rendering.ViewRenderable import com.google.codelabs.findnearbyplacesar.R import com.google.codelabs.findnearbyplacesar.model.Place class PlaceNode( val context: Context, val place: Place? ) : Node() { private var placeRenderable: ViewRenderable? = null private var textViewPlace: TextView? = null override fun onActivate() { super.onActivate() if (scene == null) { return } if (placeRenderable != null) { return } ViewRenderable.builder() .setView(context, R.layout.place_view) .build() .thenAccept { renderable -> setRenderable(renderable) placeRenderable = renderable place?.let { textViewPlace = renderable.view.findViewById(R.id.placeName) textViewPlace?.text = it.name } } } fun showInfoWindow() { // Show text textViewPlace?.let { it.visibility = if (it.visibility == View.VISIBLE) View.GONE else View.VISIBLE } // Hide text for other nodes this.parent?.children?.filter { it is PlaceNode && it != this }?.forEach { (it as PlaceNode).textViewPlace?.visibility = View.GONE } } }
apache-2.0
2eb182e5649f488822c30c846141037f
29.070423
90
0.635895
4.43659
false
false
false
false
terracotta-ko/Android_Treasure_House
MVP/app/src/main/java/com/ko/mvp/base/MvpPresenter.kt
1
1424
package com.ko.mvp.base import com.ko.common.coroutines.CoroutinesDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext internal class MvpPresenter( private val interactor: MvpContract.Interactor, private val modelMapper: MvpModelMapper, private val dispatcher: CoroutinesDispatcher ) : MvpContract.Presenter, CoroutineScope { private val job = Job() override val coroutineContext: CoroutineContext get() = dispatcher.threadUI + job private var view: MvpContract.View? = null override fun bindView(view: MvpContract.View) { this.view = view } override fun unbindView() { this.view = null job.cancel() } override fun onViewCreated() { launch(dispatcher.threadUI) { val model = withContext(dispatcher.threadIO) { modelMapper.toModel(interactor.fetch()) } view?.updateView(model.users) } } override fun onAddButtonClick() { view?.gotoAddActivity() } override fun onAddSucceeded() { launch(dispatcher.threadUI) { val model = withContext(dispatcher.threadIO) { modelMapper.toModel(interactor.fetch()) } view?.updateView(model.users) } } }
mit
913f5e3801acb3a471d2ad75c2ab6085
26.384615
58
0.662921
4.810811
false
false
false
false
googlecodelabs/android-compose-codelabs
MigrationCodelab/app/src/main/java/com/google/samples/apps/sunflower/adapters/PlantAdapter.kt
1
2925
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.sunflower.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.findNavController import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.google.samples.apps.sunflower.HomeViewPagerFragmentDirections import com.google.samples.apps.sunflower.PlantListFragment import com.google.samples.apps.sunflower.data.Plant import com.google.samples.apps.sunflower.databinding.ListItemPlantBinding /** * Adapter for the [RecyclerView] in [PlantListFragment]. */ class PlantAdapter : ListAdapter<Plant, RecyclerView.ViewHolder>(PlantDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return PlantViewHolder( ListItemPlantBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val plant = getItem(position) (holder as PlantViewHolder).bind(plant) } class PlantViewHolder( private val binding: ListItemPlantBinding ) : RecyclerView.ViewHolder(binding.root) { init { binding.setClickListener { binding.plant?.let { plant -> navigateToPlant(plant, it) } } } private fun navigateToPlant( plant: Plant, view: View ) { val direction = HomeViewPagerFragmentDirections.actionViewPagerFragmentToPlantDetailFragment( plant.plantId ) view.findNavController().navigate(direction) } fun bind(item: Plant) { binding.apply { plant = item executePendingBindings() } } } } private class PlantDiffCallback : DiffUtil.ItemCallback<Plant>() { override fun areItemsTheSame(oldItem: Plant, newItem: Plant): Boolean { return oldItem.plantId == newItem.plantId } override fun areContentsTheSame(oldItem: Plant, newItem: Plant): Boolean { return oldItem == newItem } }
apache-2.0
922a71f38fbf4f8c110cdd05d989f9e2
31.865169
96
0.678291
4.949239
false
false
false
false
FWDekker/intellij-randomness
src/main/kotlin/com/fwdekker/randomness/ui/JNumberSpinners.kt
1
4031
package com.fwdekker.randomness.ui import java.text.DecimalFormatSymbols import java.util.Locale import javax.swing.JComponent import javax.swing.JSpinner import javax.swing.SpinnerNumberModel /** * An abstract [JSpinner] for numbers that contains common logic for its subclasses. * * @param T the type of number * @param value the default value * @param minValue the smallest number that may be represented, or `null` if there is no limit * @param maxValue the largest number that may be represented, or `null` if there is no limit * @param stepSize the default value to increment and decrement by */ abstract class JNumberSpinner<T>(value: T, minValue: T?, maxValue: T?, stepSize: T) : JSpinner(SpinnerNumberModel(value, minValue, maxValue, stepSize)) where T : Number, T : Comparable<T> { /** * Transforms a [Number] into a [T]. */ abstract val numberToT: (Number) -> T /** * A helper function to return the super class's model as an instance of [SpinnerNumberModel]. */ private val numberModel: SpinnerNumberModel get() = super.getModel() as SpinnerNumberModel /** * The component that can be used to edit the spinner. */ val editorComponent: JComponent? get() = editor.getComponent(0) as? JComponent /** * Returns the current value of the spinner. * * @return the current value of the spinner */ override fun getValue(): T = numberToT(numberModel.number) /** * Sets the value of the spinner. * * @param value the new value of the spinner */ override fun setValue(value: Any) { numberModel.value = value } /** * Holds constants. */ companion object { /** * The default number format used to display numbers. */ val DEFAULT_FORMAT = DecimalFormatSymbols(Locale.US) } } /** * A [JNumberSpinner] for doubles. * * Note that setting `minValue` or `maxValue` to a very large number may cause the parent component's width to be overly * large. * * @param value the default value * @param minValue the smallest number that may be represented * @param maxValue the largest number that may be represented * @param stepSize the default value to increment and decrement by */ class JDoubleSpinner( value: Double = 0.0, minValue: Double? = null, maxValue: Double? = null, stepSize: Double = 0.1 ) : JNumberSpinner<Double>(value, minValue, maxValue, stepSize) { override val numberToT: (Number) -> Double get() = { it.toDouble() } init { this.editor = NumberEditor(this).also { it.format.decimalFormatSymbols = DEFAULT_FORMAT } } } /** * A [JNumberSpinner] for longs. * * @param value the default value * @param minValue the smallest number that may be represented * @param maxValue the largest number that may be represented * @param stepSize the default value to increment and decrement by */ class JLongSpinner( value: Long = 0L, minValue: Long = Long.MIN_VALUE, maxValue: Long = Long.MAX_VALUE, stepSize: Long = 1L ) : JNumberSpinner<Long>(value, minValue, maxValue, stepSize) { override val numberToT: (Number) -> Long get() = { it.toLong() } init { this.editor = NumberEditor(this).also { it.format.decimalFormatSymbols = DEFAULT_FORMAT } } } /** * A [JNumberSpinner] for integers. * * @param value the default value * @param minValue the smallest number that may be represented * @param maxValue the largest number that may be represented * @param stepSize the default value to increment and decrement by */ class JIntSpinner( value: Int = 0, minValue: Int = Int.MIN_VALUE, maxValue: Int = Int.MAX_VALUE, stepSize: Int = 1 ) : JNumberSpinner<Int>(value, minValue, maxValue, stepSize) { override val numberToT: (Number) -> Int get() = { it.toInt() } init { this.editor = NumberEditor(this).also { it.format.decimalFormatSymbols = DEFAULT_FORMAT } } }
mit
93032d91caa3ea2709efac4117ab0416
27.792857
120
0.670305
4.100712
false
false
false
false