repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Deanveloper/Overcraft | src/main/java/com/deanveloper/overcraft/util/OcItem.kt | 1 | 1210 | package com.deanveloper.overcraft.util
import org.bukkit.Material
import org.bukkit.inventory.ItemStack
/**
* @author Dean
*/
class OcItem(mat: Material, count: Int, damage: Short) : ItemStack(mat, count, damage) {
constructor(
mat: Material,
name: String = "",
lore: List<String> = emptyList(),
isUnbreakable: Boolean = true
) : this(mat, 1, 0) {
this.name = name
this.lore = lore
this.isUnbreakable = isUnbreakable
}
constructor(mat: Material, damage: Short) : this(mat, 1, damage)
var name: String
get() = itemMeta?.displayName ?: ""
set(value) {
itemMeta = itemMeta?.apply {
displayName = if(value.isEmpty()) null else value
}
}
var lore: List<String>
get() = itemMeta?.lore ?: emptyList()
set(value) {
itemMeta = itemMeta?.apply {
lore = value
}
}
var isUnbreakable: Boolean
get() = itemMeta?.spigot()?.isUnbreakable ?: false
set(value) {
itemMeta = itemMeta?.apply {
spigot()?.isUnbreakable = value
}
}
} | mit | 79e20f45a097e02f91dcedcd1ab15087 | 25.326087 | 88 | 0.533058 | 4.4 | false | false | false | false |
jcam3ron/cassandra-migration | src/main/java/com/builtamont/cassandra/migration/internal/info/MigrationInfoImpl.kt | 1 | 10244 | /**
* File : MigrationInfoImpl.kt
* License :
* Original - Copyright (c) 2010 - 2016 Boxfuse GmbH
* Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd
*
* 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.builtamont.cassandra.migration.internal.info
import com.builtamont.cassandra.migration.api.MigrationInfo
import com.builtamont.cassandra.migration.api.MigrationState
import com.builtamont.cassandra.migration.api.MigrationType
import com.builtamont.cassandra.migration.api.MigrationVersion
import com.builtamont.cassandra.migration.api.resolver.ResolvedMigration
import com.builtamont.cassandra.migration.internal.metadatatable.AppliedMigration
import java.util.*
/**
* Default implementation of MigrationInfoService.
*
* @param resolvedMigration The resolved migration to aggregate the info from.
* @param appliedMigration The applied migration to aggregate the info from.
* @param context The current context.
*/
class MigrationInfoImpl(
val resolvedMigration: ResolvedMigration?,
val appliedMigration: AppliedMigration?,
private val context: MigrationInfoContext
) : MigrationInfo {
/**
* The type of migration (CQL, Java, ...)
*/
override val type: MigrationType
get() {
if (appliedMigration != null) {
return appliedMigration.type!!
}
return resolvedMigration?.type!!
}
/**
* The target version of this migration.
*/
override val checksum: Int?
get() {
if (appliedMigration != null) {
return appliedMigration.checksum
}
return resolvedMigration!!.checksum
}
/**
* The schema version after the migration is complete.
*/
override val version: MigrationVersion
get() {
if (appliedMigration != null) {
return appliedMigration.version!!
}
return resolvedMigration!!.version!!
}
/**
* The description of the migration.
*/
override val description: String
get() {
if (appliedMigration != null) {
return appliedMigration.description!!
}
return resolvedMigration!!.description!!
}
/**
* The name of the script to execute for this migration, relative to its classpath or filesystem location.
*/
override val script: String
get() {
if (appliedMigration != null) {
return appliedMigration.script!!
}
return resolvedMigration!!.script!!
}
/**
* The state of the migration (PENDING, SUCCESS, ...)
*/
override val state: MigrationState
get() {
if (appliedMigration == null) {
if (resolvedMigration!!.version!!.compareTo(context.baseline) < 0) {
return MigrationState.BELOW_BASELINE
}
if (resolvedMigration.version!!.compareTo(context.target) > 0) {
return MigrationState.ABOVE_TARGET
}
if (resolvedMigration.version!!.compareTo(context.lastApplied) < 0 && !context.outOfOrder) {
return MigrationState.IGNORED
}
return MigrationState.PENDING
}
if (resolvedMigration == null) {
if (MigrationType.SCHEMA === appliedMigration.type) {
return MigrationState.SUCCESS
}
if (MigrationType.BASELINE === appliedMigration.type) {
return MigrationState.BASELINE
}
if (version.compareTo(context.lastResolved) < 0) {
if (appliedMigration.isSuccess) {
return MigrationState.MISSING_SUCCESS
}
return MigrationState.MISSING_FAILED
}
if (version.compareTo(context.lastResolved) > 0) {
if (appliedMigration.isSuccess) {
return MigrationState.FUTURE_SUCCESS
}
return MigrationState.FUTURE_FAILED
}
}
if (appliedMigration.isSuccess) {
if (appliedMigration.versionRank == appliedMigration.installedRank) {
return MigrationState.SUCCESS
}
return MigrationState.OUT_OF_ORDER
}
return MigrationState.FAILED
}
/**
* The timestamp when this migration was installed. (Only for applied migrations)
*/
override val installedOn: Date?
get() {
if (appliedMigration != null) {
return appliedMigration.installedOn
}
return null
}
/**
* The execution time (in millis) of this migration. (Only for applied migrations)
*/
override val executionTime: Int?
get() {
if (appliedMigration != null) {
return appliedMigration.executionTime
}
return null
}
/**
* Validates this migrationInfo for consistency.
*
* @return The error message, or {@code null} if everything is fine.
*/
fun validate(): String? {
if (!context.pendingOrFuture
&& resolvedMigration == null
&& appliedMigration!!.type !== MigrationType.SCHEMA
&& appliedMigration!!.type !== MigrationType.BASELINE) {
return "Detected applied migration not resolved locally: " + version
}
if (!context.pendingOrFuture && MigrationState.PENDING === state || MigrationState.IGNORED === state) {
return "Detected resolved migration not applied to database: " + version
}
if (resolvedMigration != null && appliedMigration != null) {
if (version.compareTo(context.baseline) > 0) {
if (resolvedMigration.type !== appliedMigration.type) {
return createMismatchMessage("Type", appliedMigration.version!!,
appliedMigration.type!!, resolvedMigration.type!!)
}
if (!com.builtamont.cassandra.migration.internal.util.ObjectUtils.nullSafeEquals(resolvedMigration.checksum, appliedMigration.checksum)) {
return createMismatchMessage("Checksum", appliedMigration.version!!,
appliedMigration.checksum!!, resolvedMigration.checksum!!)
}
if (resolvedMigration.description != appliedMigration.description) {
return createMismatchMessage("Description", appliedMigration.version!!,
appliedMigration.description!!, resolvedMigration.description!!)
}
}
}
return null
}
/**
* Creates a message for a mismatch.
*
* @param mismatch The type of mismatch.
* @param version The offending version.
* @param applied The applied value.
* @param resolved The resolved value.
* @return The message.
*/
private fun createMismatchMessage(mismatch: String, version: MigrationVersion, applied: Any, resolved: Any): String {
val message = "Migration $mismatch mismatch for migration $version\n-> Applied to database : $applied\n-> Resolved locally : $resolved"
return String.format(message)
}
/**
* @return The computed info instance hash value.
*/
override fun hashCode(): Int {
var result = resolvedMigration?.hashCode() ?: 0
result = 31 * result + (appliedMigration?.hashCode() ?: 0)
result = 31 * result + context.hashCode()
return result
}
/**
* @return {@code true} if this info instance is the same as the given object.
*/
@SuppressWarnings("SimplifiableIfStatement")
override fun equals(other: Any?): Boolean {
/**
* @return {@code true} if this version instance is not the same as the given object.
*/
fun isNotSame(): Boolean {
return other == null || javaClass != other.javaClass
}
/**
* @return {@code true} if this context instance applied migration property is not the same as the given object applied migration property.
*/
fun isNotSameAppliedMigration(that: MigrationInfoImpl): Boolean {
return if (appliedMigration != null) appliedMigration != that.appliedMigration else that.appliedMigration != null
}
/**
* @return {@code true} if this context instance resolved migration property is not the same as the given object resolved migration property.
*/
fun isNotSameResolvedMigration(that: MigrationInfoImpl): Boolean {
return if (resolvedMigration != null) resolvedMigration != that.resolvedMigration else that.resolvedMigration != null
}
val that = other as MigrationInfoImpl? ?: return false
return when {
this === other -> true
isNotSame() -> false
isNotSameAppliedMigration(that) -> false
context != that.context -> false
else -> !isNotSameResolvedMigration(that) // Note the double negative
}
}
/**
* @return {@code true} if this info instance is comparable to the given object.
*/
@SuppressWarnings("NullableProblems")
override fun compareTo(other: MigrationInfo): Int {
return version.compareTo(other.version)
}
}
| apache-2.0 | 98c462e02423885825132dc908070dc2 | 36.52381 | 154 | 0.594787 | 5.522372 | false | false | false | false |
mikelangley/lighthouse | common/src/main/java/lighthouse/files/DirectoryWatcher.kt | 2 | 4151 | package lighthouse.files
import com.sun.nio.file.SensitivityWatchEventModifier
import lighthouse.threading.AffinityExecutor
import lighthouse.utils.ThreadBox
import org.slf4j.LoggerFactory
import java.io.IOException
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds.ENTRY_CREATE
import java.nio.file.StandardWatchEventKinds.ENTRY_DELETE
import java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY
import java.nio.file.StandardWatchEventKinds.OVERFLOW
import java.nio.file.WatchEvent
import java.time.Duration
import java.util.concurrent.ScheduledFuture
import kotlin.concurrent.thread
/**
* The Java directory watching API is very low level, almost a direct translation of the underlying OS API's, so we
* wrap it here to make it more digestable. One of the things this does is buffer up rapid sequences of notifications
* that can be caused by file copy tools like scp.
*/
public object DirectoryWatcher {
private val log = LoggerFactory.getLogger(DirectoryWatcher::class.java)
@Suppress("UNCHECKED_CAST") @JvmStatic
public fun watch(directory: Path, executor: AffinityExecutor.ServiceAffinityExecutor, onChanged: (Path, WatchEvent.Kind<Path>) -> Unit): Thread {
return thread(start = true, daemon = true, name = "Directory watcher for $directory") {
log.info("Starting directory watch service for $directory")
// Apply a short delay to collapse rapid sequences of notifications together.
class Pending(val kind: WatchEvent.Kind<Path>, val future: ScheduledFuture<*>)
val dupeMap = ThreadBox(hashMapOf<Path, Pending>())
try {
val watcher = FileSystems.getDefault().newWatchService()
directory.register(watcher, arrayOf(ENTRY_DELETE, ENTRY_CREATE, ENTRY_MODIFY), SensitivityWatchEventModifier.HIGH)
while (!Thread.currentThread().isInterrupted) {
val key = watcher.take()
for (event in key.pollEvents()) {
val kind = event.kind()
if (kind === OVERFLOW) {
continue
}
val ev = event as WatchEvent<Path>
val filename = (key.watchable() as Path).resolve(ev.context())
val handler = {
dupeMap.useWith { remove(filename) }
onChanged(filename, ev.kind())
}
dupeMap.use { map ->
val pending: Pending? = map[filename]
fun addToMap() {
map[filename] = Pending(ev.kind(), executor.executeIn(Duration.ofSeconds(1), handler))
}
if (pending == null) {
addToMap()
} else {
if (ev.kind() == ENTRY_MODIFY && pending.kind == ENTRY_CREATE) {
// We do nothing here, as the onChanged event will prefer to see a CREATE and not
// the subsequent modifies.
} else if (ev.kind() == ENTRY_DELETE && pending.kind == ENTRY_CREATE) {
// A file created and deleted so fast can just be ignored.
pending.future.cancel(false)
} else {
// Otherwise let it override the previous pending event.
pending.future.cancel(false)
addToMap()
}
}
}
}
if (!key.reset())
break
}
} catch (e: IOException) {
e.printStackTrace()
} catch (e: InterruptedException) {
// Shutting down ...
}
}
}
}
| apache-2.0 | fad38d68b4aedf8afef3bdae728425df | 45.640449 | 149 | 0.535775 | 5.454665 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/reference/LatexGlossaryReference.kt | 1 | 1784 | package nl.hannahsten.texifyidea.reference
import com.intellij.psi.*
import com.intellij.util.containers.toArray
import nl.hannahsten.texifyidea.index.LatexGlossaryEntryIndex
import nl.hannahsten.texifyidea.lang.commands.LatexGlossariesCommand
import nl.hannahsten.texifyidea.psi.LatexParameterText
/**
* This reference allows refactoring of glossary entries. A glossary reference command (e.g. \gls) references the label
* parameter of a glossary entry command (e.g. \newglossaryentry).
*/
class LatexGlossaryReference(element: LatexParameterText) : PsiReferenceBase<LatexParameterText>(element),
PsiPolyVariantReference {
init {
rangeInElement = ElementManipulators.getValueTextRange(element)
}
override fun isReferenceTo(element: PsiElement): Boolean {
return multiResolve(false).any { it.element == element }
}
override fun resolve(): PsiElement? {
val resolveResults = multiResolve(false)
return if (resolveResults.size == 1) resolveResults[0].element else null
}
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
val glossaryEntries = LatexGlossaryEntryIndex.getItemsInFileSet(myElement.containingFile.originalFile)
return glossaryEntries
.filter { LatexGlossariesCommand.extractGlossaryLabel(it) == myElement.name }
.toSet()
.mapNotNull {
PsiElementResolveResult(
LatexGlossariesCommand.extractGlossaryLabelElement(it) ?: return@mapNotNull null
)
}
.toList()
.toArray(emptyArray())
}
override fun handleElementRename(newElementName: String): PsiElement {
myElement.setName(newElementName)
return myElement
}
}
| mit | 796b119ef22b12c6af7beaf8ca312cbc | 36.957447 | 119 | 0.711883 | 5.126437 | false | false | false | false |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/preference/LiveSharePreference.kt | 2 | 1839 | package org.worshipsongs.preference;
import android.app.AlertDialog
import android.content.Context
import android.content.SharedPreferences
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.EditText
import androidx.preference.DialogPreference
import androidx.preference.PreferenceManager
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
/**
* @author Madasamy
* @since 3.3
*/
class LiveSharePreference(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs) {
private var defaultSharedPreferences: SharedPreferences? = null
private var liveSharePath: String? = null
init {
defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
liveSharePath = defaultSharedPreferences!!.getString(CommonConstants.LIVE_SHARE_PATH_KEY, "")
}
override fun onClick() {
val customDialogView = LayoutInflater.from(context).inflate(R.layout.live_share_preference,
null)
val liveSharePathEditText = customDialogView.findViewById<EditText>(R.id.live_share_path_edit_text)
liveSharePathEditText.setText(liveSharePath)
val dialogBuilder = AlertDialog.Builder(context)
.setView(customDialogView)
.setTitle(context.getString(R.string.live_share_title));
dialogBuilder.setPositiveButton(R.string.ok) { dialog, which ->
setLiveSharePath(liveSharePathEditText)
dialog.cancel()
}
dialogBuilder.show()
}
private fun setLiveSharePath(liveSharePathEditText: EditText) {
liveSharePath = liveSharePathEditText.text.toString()
defaultSharedPreferences!!.edit().putString(CommonConstants.LIVE_SHARE_PATH_KEY,
liveSharePathEditText.text.toString()).apply()
}
}
| gpl-3.0 | 8204c01060d684ceb03af9683d2eb37c | 37.3125 | 107 | 0.735726 | 5.066116 | false | false | false | false |
cedardevs/onestop | buildSrc/src/main/kotlin/GitLabAPI.kt | 1 | 3948 | import khttp.responses.Response
import org.json.JSONArray
import org.json.JSONObject
// TODO: We currently aren't using GitLab as a container registry, but for our publishing rules and cleanup to work
// properly, we will need to work out the details here and conditionally call these methods instead of DockerHub.
// We would also need to ensure the same `git` commands (to retrieve active branches, for example) are also working
class GitLabAPI : ContainerRegistryInterface {
override val url: String
get() = "https://gitlab.com/api/v4"
override fun tags(publish: Publish): JSONArray {
val (projectId, repositoryId) = this.projectAndRepositoryIds(publish)
if(projectId > -1 && repositoryId > -1) {
val urlTags = "${this.url}/projects/$projectId/registry/repositories/${repositoryId}/tags"
val responseTags: Response = khttp.get(urlTags)
val jsonResponse: JSONArray = responseTags.jsonArray
return this.tagNamesFromResponseArray(jsonResponse, "name")
}
return JSONArray()
}
override fun token(publish: Publish): String? {
return System.getenv("GITLAB_ACCESS_TOKEN")
}
override fun deleteTags(publish: Publish, tagsToDelete: List<String>): Boolean {
val successes = mutableListOf<String>()
val failures = mutableListOf<String>()
val (projectId, repositoryId) = this.projectAndRepositoryIds(publish)
if(projectId > -1 && repositoryId > -1) {
val accessToken: String? = this.token(publish)
tagsToDelete.forEach { tagToDelete ->
val urlDelete = "${this.url}/projects/${projectId}/registry/repositories/${repositoryId}/tags/${tagToDelete}"
val response: Response = khttp.delete(
url = urlDelete,
headers = mapOf(Pair("PRIVATE-TOKEN", "${accessToken ?: ""}"))
)
val successfulDelete = response.statusCode == 200
if (successfulDelete) successes.add(tagToDelete) else failures.add(tagToDelete)
}
}
else {
println("Failed to retrieve project ID and repository ID from GitLab API!")
}
println("Cleaning GitLab -> Successfully deleted tags:${successes.joinToString(prefix = "\n- ", separator = "\n- ", postfix = "\n")}")
println("Cleaning GitLab -> Failed to delete tags:${failures.joinToString(prefix = "\n- ", separator = "\n- ", postfix = "\n")}")
return failures.size == 0
}
data class GitLabIds(val projectId: Int, val repositoryId: Int)
private fun projectAndRepositoryIds(publish: Publish): GitLabIds {
// retrieve project ID by project name
var projectId: Int = -1
val urlProject = "${this.url}/users/${publish.vendor}/projects?search=${publish.project}"
val responseProject: Response = khttp.get(urlProject)
val jsonProjects: JSONArray = responseProject.jsonArray
if (jsonProjects.length() > 0) {
val jsonProject: JSONObject = jsonProjects.getJSONObject(0)
projectId = jsonProject.getInt("id")
}
// retrieve repository ID with knowledge of project ID
var repositoryId: Int = -1
if(projectId > -1) {
val urlRepositories = "${this.url}/projects/${projectId}/registry/repositories"
val responseRepositories: Response = khttp.get(urlRepositories)
val jsonRepositories: JSONArray = responseRepositories.jsonArray
val jsonRepository: JSONObject? = jsonRepositories.find { r ->
val repo: JSONObject = r as JSONObject
repo.get("name") == publish.title
} as JSONObject
if (jsonRepository !== null) {
repositoryId = jsonRepository.getInt("id")
}
}
return GitLabIds(projectId, repositoryId)
}
} | gpl-2.0 | e2a5d1577ec75ad3ac2b59edfc14fb52 | 46.578313 | 142 | 0.633232 | 4.838235 | false | false | false | false |
thm-projects/arsnova-backend | gateway/src/main/kotlin/de/thm/arsnova/service/httpgateway/filter/RequestRateLimiter.kt | 1 | 4176 | package de.thm.arsnova.service.httpgateway.filter
import de.thm.arsnova.service.httpgateway.config.HttpGatewayProperties
import io.github.bucket4j.Bandwidth
import io.github.bucket4j.Bucket
import io.github.bucket4j.Bucket4j
import io.github.bucket4j.ConsumptionProbe
import io.github.bucket4j.Refill
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.cloud.gateway.filter.ratelimit.AbstractRateLimiter
import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter
import org.springframework.cloud.gateway.support.ConfigurationService
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono
import java.time.Duration
import java.util.concurrent.ConcurrentHashMap
@Component
class RequestRateLimiter(
private val httpGatewayProperties: HttpGatewayProperties,
private val configurationService: ConfigurationService
) : AbstractRateLimiter<RequestRateLimiter.Config>(Config::class.java, CONFIGURATION_PROPERTY_NAME, configurationService) {
companion object {
private const val CONFIGURATION_PROPERTY_NAME = "rate-limiter"
private const val QUERY_BUCKET_PREFIX = "QUERY_"
private const val COMMAND_BUCKET_PREFIX = "COMMAND_"
private val queryMethods = arrayOf("GET", "OPTIONS")
}
private val logger: Logger = LoggerFactory.getLogger(this::class.java)
private val defaultConfig = Config(httpGatewayProperties)
private val ipBucketMap: MutableMap<String, Bucket> = ConcurrentHashMap()
/*
The id is the key extracted from the KeyResolver configured in GatewayConfig.
Format: <HTTPMethod>,<IP>
Example: GET,172.18.0.18
*/
override fun isAllowed(routeId: String, id: String): Mono<RateLimiter.Response> {
logger.trace("Checking rate limit for {} from {}.", routeId, id)
var routeConfig: Config? = config[routeId]
if (routeConfig == null) {
routeConfig = defaultConfig
}
val httpMethod = id.split(",")[0]
val ipAddr = id.split(",")[1]
val isQuery = queryMethods.any { it == httpMethod }
if (ipAddr in httpGatewayProperties.gateway.rateLimit.whitelistedIps) {
return Mono.just(RateLimiter.Response(true, mapOf("RateLimit-Remaining" to "infinite")))
}
val bucket: Bucket = if (isQuery) {
ipBucketMap.computeIfAbsent(QUERY_BUCKET_PREFIX + ipAddr) { _: String ->
val refill: Refill = Refill.intervally(routeConfig.queryTokensPerTimeframe, routeConfig.duration)
val limit: Bandwidth = Bandwidth.classic(routeConfig.queryBurstCapacity, refill)
Bucket4j.builder().addLimit(limit).build()
}
} else {
ipBucketMap.computeIfAbsent(COMMAND_BUCKET_PREFIX + ipAddr) { _: String ->
val refill: Refill = Refill.intervally(routeConfig.commandTokensPerTimeframe, routeConfig.duration)
val limit: Bandwidth = Bandwidth.classic(routeConfig.commandBurstCapacity, refill)
Bucket4j.builder().addLimit(limit).build()
}
}
if (bucket.availableTokens in 1..10) {
// Check early so logs don't get spammed
logger.info("Rate limit nearly exceeded for {} by {}.", routeId, id)
}
// tryConsume returns false immediately if no tokens available with the bucket
val probe: ConsumptionProbe = bucket.tryConsumeAndReturnRemaining(1)
return if (probe.isConsumed) {
// the limit is not exceeded
Mono.just(RateLimiter.Response(true, mapOf("RateLimit-Remaining" to probe.remainingTokens.toString())))
} else {
// limit is exceeded
Mono.just(RateLimiter.Response(false, mapOf("RateLimit-Remaining" to "none")))
}
}
class Config(
private val httpGatewayProperties: HttpGatewayProperties
) {
val queryTokensPerTimeframe: Long = httpGatewayProperties.gateway.rateLimit.queryTokensPerTimeframe
val queryBurstCapacity: Long = httpGatewayProperties.gateway.rateLimit.queryBurstCapacity
val commandTokensPerTimeframe: Long = httpGatewayProperties.gateway.rateLimit.commandTokensPerTimeframe
val commandBurstCapacity: Long = httpGatewayProperties.gateway.rateLimit.commandBurstCapacity
// the time window
val duration: Duration = httpGatewayProperties.gateway.rateLimit.duration
}
}
| gpl-3.0 | b939db3d7a81442981c6301c454d7e6c | 42.051546 | 123 | 0.755268 | 4.480687 | false | true | false | false |
hotpodata/Blockelganger | app/src/main/java/com/hotpodata/blockelganger/AnalyticsMaster.kt | 1 | 1567 | package com.hotpodata.blockelganger
import android.content.Context
import com.google.android.gms.analytics.GoogleAnalytics
import com.google.android.gms.analytics.Tracker
import com.hotpodata.common.interfaces.IAnalyticsProvider
/**
* Created by jdrotos on 11/18/15.
*/
object AnalyticsMaster : IAnalyticsProvider{
//SCREENS
val SCREEN_SINGLE_PLAYER = "SinglePlayerGameScreen"
val SCREEN_LANDING = "LandingScreen"
//CATEGORIES
val CATEGORY_ACTION = "Action"
//ACTIONS
val ACTION_START_GAME = "StartGame"
val ACTION_GAME_OVER = "GameOver"
val ACTION_PAUSE = "Pause"
val ACTION_RESUME = "Resume"
val ACTION_START_OVER = "StartOver"
val ACTION_HELP = "Help"
val ACTION_UPDATE_FRAG = "UpdateFragment"
val ACTION_OPEN_DRAWER = "OpenDrawer"
val ACTION_SIGN_IN = "SignInClicked"
val ACTION_ACHIEVEMENTS = "AchievementsClicked"
val ACTION_LEADERBOARD = "LeaderBoardClicked"
val ACTION_LEVEL_COMPLETE = "LevelComplete"
val ACTION_EARLY_SMASH = "EarlySmash"
//Labels
val LABEL_LEVEL = "Level"
val LABEL_LAUNCH_COUNT = "LaunchCount"
val LABEL_SECONDS_REMAINING = "SecondsRemaining"
private var tracker: Tracker? = null
public override fun getTracker(context: Context): Tracker {
val t = tracker ?:
GoogleAnalytics.getInstance(context).newTracker(R.xml.global_tracker).apply {
enableExceptionReporting(true)
enableAdvertisingIdCollection(true)
}
tracker = t
return t
}
} | apache-2.0 | e887a433edee12546622ff74f252ad8f | 30.36 | 93 | 0.684748 | 4.112861 | false | false | false | false |
rcgroot/open-gpstracker-ng | studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/trackedit/TrackEditPresenter.kt | 1 | 4292 | /*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) 2016 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker 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.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.ng.features.trackedit
import android.net.Uri
import androidx.annotation.WorkerThread
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.INVALID_POSITION
import android.widget.ImageView
import android.widget.TextView
import nl.sogeti.android.gpstracker.ng.features.FeatureConfiguration
import nl.sogeti.android.gpstracker.ng.features.summary.SummaryManager
import nl.sogeti.android.gpstracker.ng.features.util.AbstractTrackPresenter
import nl.sogeti.android.gpstracker.service.util.readName
import nl.sogeti.android.gpstracker.service.util.updateName
import javax.inject.Inject
class TrackEditPresenter : AbstractTrackPresenter() {
@Inject
lateinit var summaryManager: SummaryManager
val viewModel = TrackEditModel()
val onItemSelectedListener: AdapterView.OnItemSelectedListener by lazy {
object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
viewModel.selectedPosition.set(position)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
viewModel.selectedPosition.set(INVALID_POSITION)
}
}
}
init {
FeatureConfiguration.featureComponent.inject(this)
}
@WorkerThread
override fun onChange() {
viewModel.trackUri.set(trackUri)
loadTrackTypePosition(trackUri)
loadTrackName(trackUri)
}
fun ok(trackUri: Uri, trackName: String) {
saveTrackName(trackUri, trackName)
saveTrackTypePosition(trackUri)
summaryManager.removeFromCache(trackUri)
viewModel.dismissed.set(true)
}
fun cancel() {
viewModel.dismissed.set(true)
}
private fun loadTrackName(trackUri: Uri?) {
if (trackUri != null) {
val trackName = trackUri.readName()
viewModel.name.set(trackName)
} else {
viewModel.name.set("")
}
}
private fun loadTrackTypePosition(trackUri: Uri?) {
if (trackUri != null) {
val trackType = trackUri.readTrackType()
val position = viewModel.trackTypes.indexOfFirst { it == trackType }
viewModel.selectedPosition.set(position)
} else {
viewModel.selectedPosition.set(INVALID_POSITION)
}
}
private fun saveTrackName(trackUri: Uri, trackName: String) {
trackUri.updateName(trackName)
}
private fun saveTrackTypePosition(trackUri: Uri) {
val trackType = viewModel.trackTypes[viewModel.selectedPosition.get()]
trackUri.saveTrackType(trackType)
}
data class ViewHolder(val imageView: ImageView, val textView: TextView)
}
| gpl-3.0 | b08bdc475c902f2e9d3340b3f929ac49 | 36.982301 | 104 | 0.650513 | 4.905143 | false | false | false | false |
NyaaPantsu/NyaaPantsu-android-app | app/src/main/java/cat/pantsu/nyaapantsu/util/Utils.kt | 1 | 3282 | package cat.pantsu.nyaapantsu.util
import android.Manifest
import android.app.Activity
import android.app.DownloadManager
import android.content.Context
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.support.design.widget.Snackbar
import android.util.Log
import android.view.View
import cat.pantsu.nyaapantsu.R
import org.jetbrains.anko.toast
/**
* Created by ltype on 2017/7/16.
*/
class Utils {
companion object {
fun download(activity: Activity, parent: View, url: String, name: String) {
if (!mayRequestPermission(activity, parent, Manifest.permission.WRITE_EXTERNAL_STORAGE, 10)) {
if (isExternalStorageWritable()) {
Log.d("download", "URL: " + url)
val request = DownloadManager.Request(Uri.parse(url))
request.setDescription("Download a torrent file")
request.setTitle(name + " - NyaaPantsu")
// in order for this if to run, you must use the android 3.2 to compile your app
request.allowScanningByMediaScanner()
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name + ".torrent")
Log.d("download", "request")
// get download service and enqueue file
val manager = activity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
manager.enqueue(request)
} else {
activity.toast(activity.getString(R.string.external_storage_not_available))
}
}
}
fun mayRequestPermission(activity: Activity, parent: View, permission: String, code: Int): Boolean {
val c = parent.context
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return false
}
if (c.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
return false
}
if (activity.shouldShowRequestPermissionRationale(permission)) {
Snackbar.make(parent, R.string.permission_required, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, { _ -> activity.requestPermissions(arrayOf(permission), code) })
.show()
} else {
activity.requestPermissions(arrayOf(permission), code)
}
return true
}
fun isExternalStorageWritable(): Boolean {
val state = Environment.getExternalStorageState()
if (Environment.MEDIA_MOUNTED == state) {
return true
}
return false
}
fun playVoice(c: Context) {
//TODO support sukebei mode, maybe need a application context for hold player
val player = MediaPlayer.create(c, R.raw.nyanpass)
player.setOnCompletionListener {
player.release()
}
player.start()
}
}
} | mit | 96f39ce1b1e8edac634ebccef0743c5e | 38.083333 | 120 | 0.606033 | 5.096273 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/parser/SvnServerWriter.kt | 1 | 3798 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.parser
import svnserver.parser.token.*
import java.io.BufferedOutputStream
import java.io.Closeable
import java.io.IOException
import java.io.OutputStream
import java.nio.charset.StandardCharsets
/**
* Интерфейс для записи данных в поток.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class SvnServerWriter constructor(stream: OutputStream) : Closeable {
private val stream: OutputStream
private var depth: Int = 0
@Throws(IOException::class)
fun listBegin(): SvnServerWriter {
return write(ListBeginToken.instance)
}
@Throws(IOException::class)
fun listEnd(): SvnServerWriter {
return write(ListEndToken.instance)
}
@Throws(IOException::class)
fun word(c: Char): SvnServerWriter {
return word(c.toString())
}
@Throws(IOException::class)
fun word(word: String): SvnServerWriter {
WordToken.write(stream, word)
if (depth == 0) stream.flush()
return this
}
@Throws(IOException::class)
fun stringNullable(text: String?): SvnServerWriter {
listBegin()
if (text != null) string(text)
listEnd()
return this
}
@Throws(IOException::class)
fun string(text: String): SvnServerWriter {
return binary(text.toByteArray(StandardCharsets.UTF_8))
}
@Throws(IOException::class)
fun binary(data: ByteArray, offset: Int = 0, length: Int = data.size): SvnServerWriter {
StringToken.write(stream, data, offset, length)
if (depth == 0) stream.flush()
return this
}
@Throws(IOException::class)
fun number(number: Long): SvnServerWriter {
NumberToken.write(stream, number)
if (depth == 0) stream.flush()
return this
}
@Throws(IOException::class)
fun separator(): SvnServerWriter {
stream.write('\n'.code)
return this
}
@Throws(IOException::class)
fun bool(value: Boolean): SvnServerWriter {
return word(if (value) "true" else "false")
}
@Throws(IOException::class)
fun write(token: SvnServerToken): SvnServerWriter {
token.write(stream)
if ((token == ListBeginToken.instance)) {
depth++
} else if ((token == ListEndToken.instance)) {
depth--
if (depth < 0) {
throw IllegalStateException("Too many closed lists.")
}
}
if (depth == 0) {
separator()
stream.flush()
}
return this
}
@JvmOverloads
@Throws(IOException::class)
fun writeMap(properties: Map<String, String?>?, nullableValues: Boolean = false): SvnServerWriter {
listBegin()
if (properties != null) {
for (entry: Map.Entry<String, String?> in properties.entries) {
listBegin()
string(entry.key)
if (nullableValues) {
stringNullable(entry.value)
} else {
string(entry.value!!)
}
listEnd()
}
}
listEnd()
return this
}
@Throws(IOException::class)
override fun close() {
stream.use { if (depth != 0) throw IllegalStateException("Unmatched parentheses") }
}
init {
this.stream = BufferedOutputStream(stream)
}
}
| gpl-2.0 | 7027d36de1e9433cab6b1bfbbc707504 | 27.330827 | 103 | 0.606953 | 4.361111 | false | false | false | false |
soywiz/korge | @old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/SpriterLibrary.kt | 1 | 1610 | package com.soywiz.korge.ext.spriter
import com.soywiz.korge.atlas.*
import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.*
import com.soywiz.korge.render.*
import com.soywiz.korge.view.*
import com.soywiz.korim.bitmap.*
import com.soywiz.korim.format.*
import com.soywiz.korio.file.*
import kotlin.collections.set
//e: java.lang.UnsupportedOperationException: Class literal annotation arguments are not yet supported: Factory
//@AsyncFactoryClass(SpriterLibrary.Loader::class)
class SpriterLibrary(val views: Views, val data: Data, val atlas: Map<String, TransformedTexture>) {
val entityNames = data.entities.map { it.name }
fun create(
entityName: String,
animationName1: String? = null,
animationName2: String? = animationName1
): SpriterView {
val entity = data.getEntity(entityName)
return SpriterView(
this,
entity!!,
animationName1 ?: entity.getAnimation(0).name,
animationName2 ?: entity.getAnimation(0).name
)
}
}
suspend fun VfsFile.readSpriterLibrary(views: Views): SpriterLibrary {
val file = this
val scmlContent = file.readString()
val reader = SCMLReader(scmlContent)
val data = reader.data
val textures = hashMapOf<String, TransformedTexture>()
for (atlasName in data.atlases) {
val atlas = file.parent[atlasName].readAtlas(views)
textures += atlas.textures
}
for (folder in data.folders) {
for (f in folder.files) {
if (f.name in textures) continue
val image = file.parent[f.name]
val bmpSlice = image.readBitmapSlice()
textures[f.name] = TransformedTexture(bmpSlice)
}
}
return SpriterLibrary(views, data, textures)
}
| apache-2.0 | 80188a62a93a70ff8b0f669afc116775 | 28.272727 | 111 | 0.748447 | 3.403805 | false | false | false | false |
dewarder/Android-Kotlin-Commons | akommons-bindings/src/main/java/com/dewarder/akommons/binding/StringBindings.kt | 1 | 5457 | /*
* Copyright (C) 2017 Artem Hluhovskyi
*
* 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.dewarder.akommons.binding
import android.app.Activity
import android.app.Dialog
import android.app.Fragment
import android.content.Context
import android.support.annotation.RestrictTo
import android.support.annotation.StringRes
import android.view.View
import com.dewarder.akommons.binding.util.contextProvider
import com.dewarder.akommons.binding.util.safeString
import com.dewarder.akommons.util.Optional
import com.dewarder.akommons.util.Required
import kotlin.properties.ReadOnlyProperty
/**
* View
*/
fun View.string(@StringRes stringRes: Int): ReadOnlyProperty<View, String>
= requiredString(contextProvider, stringRes)
fun View.stringOptional(@StringRes stringRes: Int): ReadOnlyProperty<View, String?>
= optionalString(contextProvider, stringRes)
fun View.strings(@StringRes vararg stringRes: Int): ReadOnlyProperty<View, List<String>>
= requiredStrings(contextProvider, stringRes)
fun View.stringsOptional(@StringRes vararg stringRes: Int): ReadOnlyProperty<View, List<String?>>
= optionalStrings(contextProvider, stringRes)
/**
* Activity
*/
fun Activity.string(@StringRes stringRes: Int): ReadOnlyProperty<Activity, String>
= requiredString(contextProvider, stringRes)
fun Activity.stringOptional(@StringRes stringRes: Int): ReadOnlyProperty<Activity, String?>
= optionalString(contextProvider, stringRes)
fun Activity.strings(@StringRes vararg stringRes: Int): ReadOnlyProperty<Activity, List<String>>
= requiredStrings(contextProvider, stringRes)
fun Activity.stringsOptional(@StringRes vararg stringRes: Int): ReadOnlyProperty<Activity, List<String?>>
= optionalStrings(contextProvider, stringRes)
/**
* Fragment
*/
fun Fragment.string(@StringRes stringRes: Int): ReadOnlyProperty<Fragment, String>
= requiredString(contextProvider, stringRes)
fun Fragment.stringOptional(@StringRes stringRes: Int): ReadOnlyProperty<Fragment, String?>
= optionalString(contextProvider, stringRes)
fun Fragment.strings(@StringRes vararg stringRes: Int): ReadOnlyProperty<Fragment, List<String>>
= requiredStrings(contextProvider, stringRes)
fun Fragment.stringsOptional(@StringRes vararg stringRes: Int): ReadOnlyProperty<Fragment, List<String?>>
= optionalStrings(contextProvider, stringRes)
/**
* Dialog
*/
fun Dialog.string(@StringRes stringRes: Int): ReadOnlyProperty<Dialog, String>
= requiredString(contextProvider, stringRes)
fun Dialog.stringOptional(@StringRes stringRes: Int): ReadOnlyProperty<Dialog, String?>
= optionalString(contextProvider, stringRes)
fun Dialog.strings(@StringRes vararg stringRes: Int): ReadOnlyProperty<Dialog, List<String>>
= requiredStrings(contextProvider, stringRes)
fun Dialog.stringsOptional(@StringRes vararg stringRes: Int): ReadOnlyProperty<Dialog, List<String?>>
= optionalStrings(contextProvider, stringRes)
/**
* ContextProvider
*/
fun ContextProvider.string(@StringRes stringRes: Int): ReadOnlyProperty<ContextProvider, String>
= requiredString(this::provideContext, stringRes)
fun ContextProvider.stringOptional(@StringRes stringRes: Int): ReadOnlyProperty<ContextProvider, String?>
= optionalString(this::provideContext, stringRes)
fun ContextProvider.strings(@StringRes vararg stringRes: Int): ReadOnlyProperty<ContextProvider, List<String>>
= requiredStrings(this::provideContext, stringRes)
fun ContextProvider.stringsOptional(@StringRes vararg stringRes: Int): ReadOnlyProperty<ContextProvider, List<String?>>
= optionalStrings(this::provideContext, stringRes)
/**
* Getters
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> requiredString(crossinline contextProvider: () -> Context,
@StringRes stringRes: Int): ReadOnlyProperty<R, String> {
return Required { contextProvider().getString(stringRes) }
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> optionalString(crossinline contextProvider: () -> Context,
@StringRes stringRes: Int): ReadOnlyProperty<R, String?> {
return Optional { contextProvider().safeString(stringRes) }
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> requiredStrings(crossinline contextProvider: () -> Context,
@StringRes stringRes: IntArray): ReadOnlyProperty<R, List<String>> {
return Required {
val context = contextProvider()
stringRes.map(context::getString)
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <R> optionalStrings(crossinline contextProvider: () -> Context,
@StringRes stringRes: IntArray): ReadOnlyProperty<R, List<String?>> {
return Required {
val context = contextProvider()
stringRes.map(context::safeString)
}
}
| apache-2.0 | 28bfca530bb37cd6f4fbea72c7e35dac | 36.895833 | 119 | 0.746564 | 4.916216 | false | false | false | false |
edvin/tornadofx | src/test/kotlin/tornadofx/testapps/ViewDockingApp.kt | 1 | 2006 | package tornadofx.testapps
import javafx.beans.property.SimpleIntegerProperty
import javafx.scene.Scene
import javafx.stage.Stage
import tornadofx.*
import java.util.concurrent.atomic.AtomicInteger
class ViewDockingApp : App(PrimaryDockingView::class)
open class PrimaryDockingView : View() {
companion object {
val instanceCounter = AtomicInteger()
}
val instanceId = instanceCounter.getAndIncrement()
val dockCounterProperty = SimpleIntegerProperty()
var dockCounter by dockCounterProperty
val undockCounterProperty = SimpleIntegerProperty()
var undockCounter by undockCounterProperty
init {
println("$tag.init()")
}
open val tag: String
get() = "PrimaryDockingView"
override val root = vbox {
form {
fieldset {
field("Instance ID") {
label(instanceId.toString())
}
field("Dock Counter") {
label(dockCounterProperty) {
style {
fontSize = 48.pt
}
}
}
field("Undock Counter") {
label(undockCounterProperty) {
style {
fontSize = 48.pt
}
}
}
}
}
}
override fun onDock() {
super.onDock()
dockCounter++
println("$tag.dockCounter: $dockCounter")
}
override fun onUndock() {
super.onUndock()
undockCounter++
println("$tag.undockCounter: $undockCounter")
}
}
class SecondaryDockingView : PrimaryDockingView() {
override val tag: String
get() = "SecondaryDockingView"
}
class NoPrimaryViewDockingApp : App() {
override fun start(stage: Stage) {
super.start(stage)
stage.scene = Scene(find<PrimaryDockingView>().root)
stage.show()
}
} | apache-2.0 | 1fe9b3d097eae277d0a9b5a5d1b65a4a | 24.405063 | 60 | 0.548853 | 5.223958 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/app/photo/AvatarPhotoActivity.kt | 1 | 4430 | package ffc.app.photo
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import com.sembozdemir.permissionskt.askPermissions
import com.sembozdemir.permissionskt.handlePermissionsResult
import ffc.android.load
import ffc.android.onClick
import ffc.android.sceneTransition
import ffc.app.FamilyFolderActivity
import ffc.app.R
import ffc.app.dev
import ffc.app.util.alert.handle
import ffc.app.util.alert.toast
import kotlinx.android.synthetic.main.photo_action_bar.choosePhoto
import kotlinx.android.synthetic.main.photo_action_bar.takePhoto
import kotlinx.android.synthetic.main.photo_avatar_activity.avatarView
import me.piruin.phototaker.PhotoSize
import me.piruin.phototaker.PhotoTaker
import me.piruin.phototaker.PhotoTakerListener
import org.jetbrains.anko.dip
import org.jetbrains.anko.indeterminateProgressDialog
import org.jetbrains.anko.intentFor
class AvatarPhotoActivity : FamilyFolderActivity() {
private val photoTaker by lazy {
PhotoTaker(this, PhotoSize(dip(1024), dip(1024))).apply {
setListener(object : PhotoTakerListener {
override fun onFinish(intent: Intent) {
photoUri = UriPhoto(intent.data!!)
avatarView.load(intent.data!!)
}
override fun onCancel(action: Int) {}
override fun onError(action: Int) {}
})
}
}
private var previousPhotoUrl: UrlPhoto? = null
var photoUri: Photo? = null
private val storage: PhotoStorage
get() = org!!.photoStorageFor(intent.photoType)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.photo_avatar_activity)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
intent.data?.let {
previousPhotoUrl = UrlPhoto(it.toString())
avatarView.load(it)
}
takePhoto.onClick {
askPermissions(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) {
onGranted {
photoTaker.captureImage()
}
}
}
choosePhoto.onClick {
askPermissions(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) {
onGranted {
photoTaker.pickImage()
}
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
handlePermissionsResult(requestCode, permissions, grantResults)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
photoTaker.onActivityResult(requestCode, resultCode, data)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> {
if (photoUri == null) finish()
photoUri?.let { photo -> upload(photo) }
}
}
return super.onOptionsItemSelected(item)
}
private fun upload(photo: Photo) {
val dialog = indeterminateProgressDialog("บันทึกภาพถ่าย").apply { show() }
storage.save(photo.uri) {
onComplete {
delete(previousPhotoUrl)
dialog.dismiss()
setResult(Activity.RESULT_OK, Intent().apply { data = it })
finish()
}
onFail {
handle(it)
}
}
}
private fun delete(photo: Photo?) {
photo?.let { photo ->
storage.delete(photo.uri) {
onComplete { dev { toast("Deleted ${photo.uri}") } }
onFail { handle(it) }
}
}
}
}
fun Activity.startAvatarPhotoActivity(
type: PhotoType,
url: String? = null,
avatarView: View? = null,
requestCode: Int = REQUEST_TAKE_PHOTO
) {
val intent = intentFor<AvatarPhotoActivity>()
intent.photoType = type
url?.let { intent.data = Uri.parse(it) }
val bundle = if (avatarView == null)
sceneTransition()
else
sceneTransition(avatarView to getString(R.string.transition_photo))
startActivityForResult(intent, requestCode, bundle)
}
| apache-2.0 | a6f90b1dde3009ba21cf8aa861dc6137 | 31.145985 | 119 | 0.636013 | 4.493878 | false | false | false | false |
GoogleChromeLabs/android-web-payment | SamplePay/app/src/main/java/com/example/android/samplepay/model/PaymentOptions.kt | 1 | 1574 | /*
* 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.example.android.samplepay.model
import android.os.Bundle
data class PaymentOptions(
val requestPayerName: Boolean,
val requestPayerPhone: Boolean,
val requestPayerEmail: Boolean,
val requestShipping: Boolean,
val shippingType: String
) {
companion object {
fun from(extras: Bundle?): PaymentOptions {
return PaymentOptions(
requestPayerName = extras?.getBoolean("requestPayerName", false) ?: false,
requestPayerPhone = extras?.getBoolean("requestPayerPhone", false) ?: false,
requestPayerEmail = extras?.getBoolean("requestPayerEmail", false) ?: false,
requestShipping = extras?.getBoolean("requestShipping", false) ?: false,
shippingType = extras?.getString("shippingType", "shipping") ?: "shipping"
)
}
}
val requireContact: Boolean
get() = requestPayerName || requestPayerPhone || requestPayerEmail
}
| apache-2.0 | 7998e8de49d9178b6e642d9bb9dfaf73 | 36.47619 | 92 | 0.68615 | 4.740964 | false | false | false | false |
vondear/RxTools | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityRxDataTool.kt | 1 | 5182 | package com.tamsiree.rxdemo.activity
import android.annotation.SuppressLint
import android.os.Bundle
import com.tamsiree.rxdemo.R
import com.tamsiree.rxkit.RxDataTool.Companion.cn2PY
import com.tamsiree.rxkit.RxDataTool.Companion.format2Decimals
import com.tamsiree.rxkit.RxDataTool.Companion.formatCard
import com.tamsiree.rxkit.RxDataTool.Companion.formatCardEnd4
import com.tamsiree.rxkit.RxDataTool.Companion.getAmountValue
import com.tamsiree.rxkit.RxDataTool.Companion.getAstro
import com.tamsiree.rxkit.RxDataTool.Companion.getPYAllFirstLetter
import com.tamsiree.rxkit.RxDataTool.Companion.getPYFirstLetter
import com.tamsiree.rxkit.RxDataTool.Companion.getRoundUp
import com.tamsiree.rxkit.RxDataTool.Companion.hideMobilePhone4
import com.tamsiree.rxkit.RxDataTool.Companion.isDouble
import com.tamsiree.rxkit.RxDataTool.Companion.isInteger
import com.tamsiree.rxkit.RxDataTool.Companion.isNullString
import com.tamsiree.rxkit.RxDataTool.Companion.isNumber
import com.tamsiree.rxkit.RxDataTool.Companion.lowerFirstLetter
import com.tamsiree.rxkit.RxDataTool.Companion.oneCn2ASCII
import com.tamsiree.rxkit.RxDataTool.Companion.oneCn2PY
import com.tamsiree.rxkit.RxDataTool.Companion.reverse
import com.tamsiree.rxkit.RxDataTool.Companion.stringToDouble
import com.tamsiree.rxkit.RxDataTool.Companion.stringToFloat
import com.tamsiree.rxkit.RxDataTool.Companion.stringToInt
import com.tamsiree.rxkit.RxDataTool.Companion.stringToLong
import com.tamsiree.rxkit.RxDataTool.Companion.toDBC
import com.tamsiree.rxkit.RxDataTool.Companion.toSBC
import com.tamsiree.rxkit.RxDataTool.Companion.upperFirstLetter
import com.tamsiree.rxkit.RxDeviceTool.setPortrait
import com.tamsiree.rxui.activity.ActivityBase
import kotlinx.android.synthetic.main.activity_rx_data_utils.*
/**
* @author tamsiree
*/
class ActivityRxDataTool : ActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rx_data_utils)
setPortrait(this)
}
@SuppressLint("SetTextI18n")
override fun initView() {
rx_title.setLeftFinish(mContext)
btn_null.setOnClickListener { tv_null.text = isNullString(editText.text.toString()).toString() }
btn_null_obj.setOnClickListener { tv_null_obj.text = isNullString(editText.text.toString()).toString() }
btn_is_integer.setOnClickListener { tv_is_integer.text = isInteger(editText.text.toString()).toString() }
btn_is_double.setOnClickListener { tv_is_double.text = isDouble(editText.text.toString()).toString() }
btn_is_number.setOnClickListener { tv_is_number.text = isNumber(editText.text.toString()).toString() }
btn_astro.setOnClickListener { tv_astro.text = getAstro(stringToInt(ed_month.text.toString()), stringToInt(ed_day.text.toString())) }
btn_hind_mobile.setOnClickListener { tv_hind_mobile.text = hideMobilePhone4(ed_mobile.text.toString()) }
btn_format_bank_card.setOnClickListener { tv_format_bank_card.text = formatCard(ed_bank_card.text.toString()) }
btn_format_bank_card_4.setOnClickListener { tv_format_bank_card_4.text = formatCardEnd4(ed_bank_card.text.toString()) }
btn_getAmountValue.setOnClickListener { tv_getAmountValue.text = getAmountValue(ed_money.text.toString()) }
btn_getRoundUp.setOnClickListener { tv_getRoundUp.text = getRoundUp(ed_money.text.toString(), 2) }
btn_string_to_int.setOnClickListener { tv_string_to_int.text = stringToInt(ed_text.text.toString()).toString() }
btn_string_to_long.setOnClickListener { tv_string_to_long.text = stringToLong(ed_text.text.toString()).toString() }
btn_string_to_double.setOnClickListener { tv_string_to_double.text = stringToDouble(ed_text.text.toString()).toString() }
btn_string_to_float.setOnClickListener { tv_string_to_float.text = stringToFloat(ed_text.text.toString()).toString() }
btn_string_to_two_number.setOnClickListener { tv_string_to_two_number.text = format2Decimals(ed_text.text.toString()) }
btn_upperFirstLetter.setOnClickListener { tv_upperFirstLetter.text = upperFirstLetter(ed_string.text.toString()) }
btn_lowerFirstLetter.setOnClickListener { tv_lowerFirstLetter.text = lowerFirstLetter(ed_string.text.toString()) }
btn_reverse.setOnClickListener { tv_reverse.text = reverse(ed_string.text.toString()) }
btn_toDBC.setOnClickListener { tv_toDBC.text = toDBC(ed_string.text.toString()) }
btn_toSBC.setOnClickListener { tv_toSBC.text = toSBC(ed_string.text.toString()) }
btn_oneCn2ASCII.setOnClickListener { tv_oneCn2ASCII.text = oneCn2ASCII(ed_string.text.toString()).toString() }
btn_oneCn2PY.setOnClickListener { tv_oneCn2PY.text = oneCn2PY(ed_string.text.toString()) }
btn_getPYFirstLetter.setOnClickListener { tv_getPYFirstLetter.text = getPYFirstLetter(ed_string.text.toString()) }
btn_getPYAllFirstLetter.setOnClickListener { tv_getPYAllFirstLetter.text = getPYAllFirstLetter(ed_string.text.toString()) }
btn_cn2PY.setOnClickListener { tv_cn2PY.text = cn2PY(ed_string.text.toString()) }
}
override fun initData() {
}
} | apache-2.0 | 5a79e988004a5470dc74a12fb85d1b3c | 62.987654 | 141 | 0.77364 | 3.907994 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/diff/EmptyLineSpan.kt | 1 | 1301 | package org.wikipedia.diff
import android.graphics.Canvas
import android.graphics.Paint
import android.text.style.LineBackgroundSpan
import androidx.annotation.ColorInt
import org.wikipedia.util.DimenUtil
class EmptyLineSpan(@ColorInt val fillColor: Int, @ColorInt val strokeColor: Int) : LineBackgroundSpan {
override fun drawBackground(canvas: Canvas, paint: Paint, left: Int, right: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence, start: Int, end: Int, lineNumber: Int) {
val prevColor = paint.color
val prevStyle = paint.style
val strokeAdjust = DimenUtil.dpToPx(0.5f)
val roundRadius = DimenUtil.dpToPx(8f)
paint.style = Paint.Style.FILL
paint.color = fillColor
canvas.drawRoundRect(left.toFloat() + strokeAdjust, top.toFloat() + strokeAdjust,
right.toFloat() - strokeAdjust, bottom.toFloat() + roundRadius / 2f, roundRadius, roundRadius, paint)
paint.style = Paint.Style.STROKE
paint.color = strokeColor
canvas.drawRoundRect(left.toFloat() + strokeAdjust, top.toFloat() + strokeAdjust,
right.toFloat() - strokeAdjust, bottom.toFloat() + roundRadius / 2f, roundRadius, roundRadius, paint)
paint.style = prevStyle
paint.color = prevColor
}
}
| apache-2.0 | bd03b1b3ae03a1363d438f64f61595a4 | 45.464286 | 183 | 0.700999 | 4.351171 | false | false | false | false |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/networking/DefaultIdentityRepository.kt | 1 | 9599 | package com.stripe.android.identity.networking
import android.util.Log
import androidx.annotation.VisibleForTesting
import com.stripe.android.camera.framework.time.Clock
import com.stripe.android.core.exception.APIConnectionException
import com.stripe.android.core.exception.APIException
import com.stripe.android.core.model.StripeFile
import com.stripe.android.core.model.StripeFileParams
import com.stripe.android.core.model.StripeFilePurpose
import com.stripe.android.core.model.StripeModel
import com.stripe.android.core.model.parsers.ModelJsonParser
import com.stripe.android.core.model.parsers.StripeErrorJsonParser
import com.stripe.android.core.model.parsers.StripeFileJsonParser
import com.stripe.android.core.networking.AnalyticsRequestV2
import com.stripe.android.core.networking.ApiRequest
import com.stripe.android.core.networking.StripeNetworkClient
import com.stripe.android.core.networking.StripeRequest
import com.stripe.android.core.networking.responseJson
import com.stripe.android.core.utils.urlEncode
import com.stripe.android.identity.networking.models.ClearDataParam
import com.stripe.android.identity.networking.models.ClearDataParam.Companion.createCollectedDataParamEntry
import com.stripe.android.identity.networking.models.CollectedDataParam
import com.stripe.android.identity.networking.models.CollectedDataParam.Companion.createCollectedDataParamEntry
import com.stripe.android.identity.networking.models.VerificationPage
import com.stripe.android.identity.networking.models.VerificationPageData
import com.stripe.android.identity.utils.IdentityIO
import kotlinx.serialization.KSerializer
import kotlinx.serialization.json.Json
import java.io.File
import javax.inject.Inject
internal class DefaultIdentityRepository @Inject constructor(
private val stripeNetworkClient: StripeNetworkClient,
private val identityIO: IdentityIO
) : IdentityRepository {
@VisibleForTesting
internal val json: Json = Json {
ignoreUnknownKeys = true
isLenient = true
encodeDefaults = true
}
private val stripeErrorJsonParser = StripeErrorJsonParser()
private val stripeFileJsonParser = StripeFileJsonParser()
private val apiRequestFactory = ApiRequest.Factory(
apiVersion = IDENTITY_STRIPE_API_VERSION_WITH_BETA_HEADER
)
override suspend fun retrieveVerificationPage(
id: String,
ephemeralKey: String
): VerificationPage = executeRequestWithKSerializer(
apiRequestFactory.createGet(
url = "$BASE_URL/$IDENTITY_VERIFICATION_PAGES/${urlEncode(id)}",
options = ApiRequest.Options(
apiKey = ephemeralKey
)
),
VerificationPage.serializer()
)
override suspend fun postVerificationPageData(
id: String,
ephemeralKey: String,
collectedDataParam: CollectedDataParam,
clearDataParam: ClearDataParam
): VerificationPageData = executeRequestWithKSerializer(
apiRequestFactory.createPost(
url = "$BASE_URL/$IDENTITY_VERIFICATION_PAGES/${urlEncode(id)}/$DATA",
options = ApiRequest.Options(
apiKey = ephemeralKey
),
params = mapOf(
collectedDataParam.createCollectedDataParamEntry(json),
clearDataParam.createCollectedDataParamEntry(json)
)
),
VerificationPageData.serializer()
)
override suspend fun postVerificationPageSubmit(
id: String,
ephemeralKey: String
): VerificationPageData = executeRequestWithKSerializer(
apiRequestFactory.createPost(
url = "$BASE_URL/$IDENTITY_VERIFICATION_PAGES/${urlEncode(id)}/$SUBMIT",
options = ApiRequest.Options(
apiKey = ephemeralKey
)
),
VerificationPageData.serializer()
)
override suspend fun uploadImage(
verificationId: String,
ephemeralKey: String,
imageFile: File,
filePurpose: StripeFilePurpose,
onSuccessExecutionTimeBlock: (Long) -> Unit
): StripeFile = executeRequestWithModelJsonParser(
request = IdentityFileUploadRequest(
fileParams = StripeFileParams(
file = imageFile,
purpose = filePurpose
),
options = ApiRequest.Options(
apiKey = ephemeralKey
),
verificationId = verificationId
),
responseJsonParser = stripeFileJsonParser,
onSuccessExecutionTimeBlock = onSuccessExecutionTimeBlock
)
override suspend fun downloadModel(modelUrl: String) = runCatching {
stripeNetworkClient.executeRequestForFile(
IdentityFileDownloadRequest(modelUrl),
identityIO.createTFLiteFile(modelUrl)
)
}.fold(
onSuccess = { response ->
if (response.isError) {
throw APIException(
requestId = response.requestId?.value,
statusCode = response.code,
message = "Downloading from $modelUrl returns error response"
)
} else {
response.body ?: run {
throw APIException(
message = "Downloading from $modelUrl returns a null body"
)
}
}
},
onFailure = {
throw APIConnectionException(
"Fail to download file at $modelUrl",
cause = it
)
}
)
override suspend fun downloadFile(fileUrl: String) = runCatching {
stripeNetworkClient.executeRequestForFile(
IdentityFileDownloadRequest(fileUrl),
identityIO.createCacheFile()
)
}.fold(
onSuccess = { response ->
if (response.isError) {
throw APIException(
requestId = response.requestId?.value,
statusCode = response.code,
message = "Downloading from $fileUrl returns error response"
)
} else {
response.body ?: run {
throw APIException(
message = "Downloading from $fileUrl returns a null body"
)
}
}
},
onFailure = {
throw APIConnectionException(
"Fail to download file at $fileUrl",
cause = it
)
}
)
override suspend fun sendAnalyticsRequest(analyticsRequestV2: AnalyticsRequestV2) {
runCatching {
stripeNetworkClient.executeRequest(analyticsRequestV2)
}.onFailure {
Log.e(TAG, "Exception while making analytics request")
}
}
private suspend fun <Response> executeRequestWithKSerializer(
request: StripeRequest,
responseSerializer: KSerializer<Response>
): Response = runCatching {
stripeNetworkClient.executeRequest(
request
)
}.fold(
onSuccess = { response ->
if (response.isError) {
// TODO(ccen) Parse the response code and throw different exceptions
throw APIException(
stripeError = stripeErrorJsonParser.parse(response.responseJson()),
requestId = response.requestId?.value,
statusCode = response.code
)
} else {
json.decodeFromString(
responseSerializer,
requireNotNull(response.body)
)
}
},
onFailure = {
throw APIConnectionException(
"Failed to execute $request",
cause = it
)
}
)
private suspend fun <Response : StripeModel> executeRequestWithModelJsonParser(
request: StripeRequest,
responseJsonParser: ModelJsonParser<Response>,
onSuccessExecutionTimeBlock: (Long) -> Unit = {}
): Response {
val started = Clock.markNow()
return runCatching {
stripeNetworkClient.executeRequest(
request
)
}.fold(
onSuccess = { response ->
if (response.isError) {
// TODO(ccen) Parse the response code and throw different exceptions
throw APIException(
stripeError = stripeErrorJsonParser.parse(response.responseJson()),
requestId = response.requestId?.value,
statusCode = response.code
)
} else {
responseJsonParser.parse(response.responseJson())?.let { response ->
onSuccessExecutionTimeBlock(started.elapsedSince().inMilliseconds.toLong())
response
} ?: run {
throw APIException(
message = "$responseJsonParser returns null for ${response.responseJson()}"
)
}
}
},
onFailure = {
throw APIConnectionException(
"Failed to execute $request",
cause = it
)
}
)
}
internal companion object {
const val SUBMIT = "submit"
const val DATA = "data"
val TAG: String = DefaultIdentityRepository::class.java.simpleName
}
}
| mit | 669223652dcd88cb080a9c75a160821a | 36.061776 | 111 | 0.609022 | 5.853049 | false | false | false | false |
peervalhoegen/SudoQ | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/solverGenerator/solution/LeftoverNoteDerivation.kt | 1 | 1042 | package de.sudoq.model.solverGenerator.solution
import de.sudoq.model.actionTree.Action
import de.sudoq.model.actionTree.NoteActionFactory
import de.sudoq.model.solvingAssistant.HintTypes
import de.sudoq.model.sudoku.Constraint
import de.sudoq.model.sudoku.Sudoku
import de.sudoq.model.sudoku.Utils
import de.sudoq.model.sudoku.getGroupShape
import java.util.*
/**
* Created by timo on 04.10.16.
*/
class LeftoverNoteDerivation(val constraint: Constraint, val note: Int) :
SolveDerivation(HintTypes.LeftoverNote) {
private val actionlist: MutableList<Action> = ArrayList()
val constraintShape: Utils.ConstraintShape
get() = getGroupShape(constraint)
override fun getActionList(sudoku: Sudoku): List<Action> {
val af = NoteActionFactory()
for (p in constraint) {
val f = sudoku.getCell(p)
if (f!!.isNoteSet(note) && f.isNotSolved) actionlist.add(af.createAction(note, f))
}
return actionlist
}
init {
hasActionListCapability = true
}
} | gpl-3.0 | 725ccc691aea1dcc8999254d4eb25e68 | 28.8 | 94 | 0.714012 | 3.94697 | false | false | false | false |
mhsjlw/AndroidSnap | app/src/main/java/me/keegan/snap/RecipientsActivity.kt | 1 | 7060 | package me.keegan.snap
import android.app.AlertDialog
import android.app.ListActivity
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.NavUtils
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.Window
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
import com.parse.FindCallback
import com.parse.ParseException
import com.parse.ParseFile
import com.parse.ParseObject
import com.parse.ParseQuery
import com.parse.ParseRelation
import com.parse.ParseUser
import com.parse.SaveCallback
import java.util.ArrayList
class RecipientsActivity : ListActivity() {
protected lateinit var mFriendsRelation: ParseRelation<ParseUser>
protected lateinit var mCurrentUser: ParseUser
protected lateinit var mFriends: List<ParseUser>
protected lateinit var mSendMenuItem: MenuItem
protected var mMediaUri: Uri? = null
protected var mFileType: String? = null
protected val recipientIds: ArrayList<String>
get() {
val recipientIds = ArrayList<String>()
for (i in 0 until listView.count) {
if (listView.isItemChecked(i)) {
recipientIds.add(mFriends[i].objectId)
}
}
return recipientIds
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS)
setContentView(R.layout.activity_recipients)
// Show the Up button in the action bar.
setupActionBar()
listView.choiceMode = ListView.CHOICE_MODE_MULTIPLE
mMediaUri = intent.data
mFileType = intent.extras!!.getString(ParseConstants.KEY_FILE_TYPE)
}
public override fun onResume() {
super.onResume()
mCurrentUser = ParseUser.getCurrentUser()
mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION)
setProgressBarIndeterminateVisibility(true)
val query = mFriendsRelation.query
query.addAscendingOrder(ParseConstants.KEY_USERNAME)
query.findInBackground { friends, e ->
setProgressBarIndeterminateVisibility(false)
if (e == null) {
mFriends = friends
val usernames = arrayOfNulls<String>(mFriends.size)
var i = 0
for (user in mFriends) {
usernames[i] = user.username
i++
}
val adapter = ArrayAdapter<String>(
listView.context,
android.R.layout.simple_list_item_checked,
usernames)
listAdapter = adapter
} else {
Log.e(TAG, e.message)
val builder = AlertDialog.Builder(this@RecipientsActivity)
builder.setMessage(e.message)
.setTitle(R.string.error_title)
.setPositiveButton(android.R.string.ok, null)
val dialog = builder.create()
dialog.show()
}
}
}
/**
* Set up the [android.app.ActionBar].
*/
private fun setupActionBar() {
actionBar!!.setDisplayHomeAsUpEnabled(true)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.recipients, menu)
mSendMenuItem = menu.getItem(0)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this)
return true
}
R.id.action_send -> {
val message = createMessage()
if (message == null) {
// error
val builder = AlertDialog.Builder(this)
builder.setMessage(R.string.error_selecting_file)
.setTitle(R.string.error_selecting_file_title)
.setPositiveButton(android.R.string.ok, null)
val dialog = builder.create()
dialog.show()
} else {
send(message)
finish()
}
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {
super.onListItemClick(l, v, position, id)
if (l.checkedItemCount > 0) {
mSendMenuItem.isVisible = true
} else {
mSendMenuItem.isVisible = false
}
}
protected fun createMessage(): ParseObject? {
val message = ParseObject(ParseConstants.CLASS_MESSAGES)
message.put(ParseConstants.KEY_SENDER_ID, ParseUser.getCurrentUser().objectId)
message.put(ParseConstants.KEY_SENDER_NAME, ParseUser.getCurrentUser().username)
message.put(ParseConstants.KEY_RECIPIENT_IDS, recipientIds)
message.put(ParseConstants.KEY_FILE_TYPE, mFileType!!)
var fileBytes = FileHelper.getByteArrayFromFile(this, mMediaUri!!)
if (fileBytes == null) {
return null
} else {
if (mFileType == ParseConstants.TYPE_IMAGE) {
fileBytes = FileHelper.reduceImageForUpload(fileBytes)
}
val fileName = FileHelper.getFileName(this, mMediaUri!!, mFileType!!)
val file = ParseFile(fileName, fileBytes)
message.put(ParseConstants.KEY_FILE, file)
return message
}
}
protected fun send(message: ParseObject?) {
message!!.saveInBackground { e ->
if (e == null) {
// success!
Toast.makeText(this@RecipientsActivity, R.string.success_message, Toast.LENGTH_LONG).show()
} else {
val builder = AlertDialog.Builder(this@RecipientsActivity)
builder.setMessage(R.string.error_sending_message)
.setTitle(R.string.error_selecting_file_title)
.setPositiveButton(android.R.string.ok, null)
val dialog = builder.create()
dialog.show()
}
}
}
companion object {
val TAG = RecipientsActivity::class.java.simpleName
}
}
| mit | 9d1de847d1f7d65f4e300961b71d0cb8 | 33.778325 | 107 | 0.594901 | 4.961349 | false | false | false | false |
charleskorn/batect | app/src/unitTest/kotlin/batect/docker/pull/DockerImageProgressSpec.kt | 1 | 4737 | /*
Copyright 2017-2020 Charles Korn.
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 batect.docker.pull
import batect.testutils.equalTo
import batect.testutils.given
import batect.testutils.on
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.startsWith
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object DockerImageProgressSpec : Spek({
describe("Docker image progress information") {
given("the image is downloading") {
val progress = DockerImageProgress("Downloading", 10, 100)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("formats the progress in the expected style") {
assertThat(display, equalTo("Downloading: 10 B of 100 B (10%)"))
}
}
}
given("the total size is not known and the download has not started") {
val progress = DockerImageProgress("Downloading", 0, 0)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("does not display the size and just shows the percentage") {
assertThat(display, equalTo("Downloading"))
}
}
}
given("the total size is not known and the download has started") {
val progress = DockerImageProgress("Downloading", 100, 0)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("does not display the size and just shows the percentage") {
assertThat(display, equalTo("Downloading: 100 B"))
}
}
}
given("the pull has not started") {
val progress = DockerImageProgress("Downloading", 0, 100)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("formats the progress in the expected style") {
assertThat(display, equalTo("Downloading: 0 B of 100 B (0%)"))
}
}
}
given("the pull has completed") {
val progress = DockerImageProgress("Downloading", 100, 100)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("formats the progress in the expected style") {
assertThat(display, equalTo("Downloading: 100 B of 100 B (100%)"))
}
}
}
mapOf(
10L to "10 B",
100L to "100 B",
999L to "999 B",
1000L to "1.0 KB",
1100L to "1.1 KB",
(1000L * 1000) - 1 to "1000.0 KB",
1000L * 1000 to "1.0 MB",
10L * 1000 * 1000 to "10.0 MB",
1000L * 1000 * 1000 to "1.0 GB",
2L * 1000 * 1000 * 1000 to "2.0 GB",
1000L * 1000 * 1000 * 1000 to "1.0 TB",
2L * 1000 * 1000 * 1000 * 1000 to "2.0 TB"
).forEach { (bytes, expectedBytesDisplay) ->
given("$bytes have been downloaded so far") {
val progress = DockerImageProgress("Downloading", bytes, 100)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("formats the progress in the expected style") {
assertThat(display, startsWith("Downloading: $expectedBytesDisplay of 100 B ("))
}
}
}
given("$bytes need to be downloaded in total") {
val progress = DockerImageProgress("Downloading", 100, bytes)
on("formatting it for display to a user") {
val display = progress.toStringForDisplay()
it("formats the progress in the expected style") {
assertThat(display, startsWith("Downloading: 100 B of $expectedBytesDisplay ("))
}
}
}
}
}
})
| apache-2.0 | 432a2559b54c85f8a69652d3d63537ef | 36.007813 | 104 | 0.563648 | 5.039362 | false | false | false | false |
jvalduvieco/blok | apps/Api/src/main/kotlin/com/blok/Common/Infrastructure/HTTP/BusRequestHandler.kt | 1 | 3608 | package com.blok
import com.blok.Common.Infrastructure.HTTP.ErrorPayload
import com.blok.Common.Infrastructure.toJson
import com.blok.common.Bus.CommandBus
import com.blok.common.Bus.QueryBus
import com.blok.handlers.RequestPayload.NoPayload
import com.blok.model.AbstractRepository
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import org.apache.http.HttpStatus
import spark.Request
import spark.Response
import spark.Route
import java.util.logging.Logger
abstract class BusRequestHandler<V : Any, B: Any>(private val valueClass: Class<V>, open protected val bus: B) : RequestHandler<V>, Route {
private val logger = Logger.getLogger(this.javaClass.canonicalName)
override fun process(value: V, urlParams: Map<String, String>, shouldReturnHtml: Boolean): Answer {
return try {
processImpl(value, urlParams, shouldReturnHtml)
} catch (e: IllegalArgumentException) {
Answer.badRequest(ErrorPayload("Exception: ${e.javaClass.canonicalName}: ${e.message}").toJson())
} catch (e: AbstractRepository.NotFound) {
Answer.notFound(ErrorPayload("Exception: ${e.javaClass.canonicalName}: ${e.message}").toJson())
}
}
protected abstract fun processImpl(value: V, urlParams: Map<String, String>, shouldReturnHtml: Boolean): Answer
@Throws(Exception::class)
override fun handle(request: Request, response: Response): String? {
try {
var value: V = castPayload(request)
val urlParams = request.params()
val answer = process(value, urlParams, shouldReturnHtml(request))
response.status(answer.code)
response.type(getRequestType(request))
response.body(answer.body)
return answer.body?: ""
} catch (e: JsonSyntaxException) {
val payload = ErrorPayload( "Bad request: [${request.url()}]" +
"[${request.body()}]" +
"[Message: ${e.message}]" +
"[${e.printStackTrace()}]")
logger.finer(payload.message)
response.status(HttpStatus.SC_BAD_REQUEST)
response.body(payload.toJson())
return payload.toJson()
} catch (e: Throwable) {
val payload = ErrorPayload("Internal server error: [${request.url()}]" +
"[${request.body()}]" +
"[Message: ${e.message}]" +
"[${e.printStackTrace()}]")
logger.severe(payload.message)
response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
response.body(payload.toJson())
return payload.toJson()
}
}
private fun getRequestType(request: Request): String {
return if (shouldReturnHtml(request)) {
"text/html"
} else {
"application/json"
}
}
private fun castPayload(request: Request): V {
return if (valueClass != NoPayload::class.java) {
Gson().fromJson(request.body(), valueClass)
} else NoPayload() as V
}
companion object {
private fun shouldReturnHtml(request: Request): Boolean {
val accept = request.headers("Accept")
return accept != null && accept.contains("text/html")
}
}
}
abstract class CommandRequestHandler<V : Any>(valueClass: Class<V>, override val bus: CommandBus): BusRequestHandler<V, CommandBus>(valueClass, bus)
abstract class QueryRequestHandler<V : Any>(valueClass: Class<V>, override val bus: QueryBus): BusRequestHandler<V, QueryBus>(valueClass, bus) | mit | 249a09baa173aee18f776abd8f7b996c | 38.659341 | 148 | 0.636641 | 4.544081 | false | false | false | false |
jonnyzzz/kotlin.xml.bind | jdom/src/main/kotlin/org/jonnyzzz/kotlin/xml/bind/jdom/impl/XProperties.kt | 1 | 1159 | package org.jonnyzzz.kotlin.xml.bind.jdom.impl
import kotlin.reflect.full.declaredMemberProperties
internal fun <T : Any> Class<T>.declaredPropertyNames(): Set<String> {
return this.kotlin.declaredMemberProperties.map { x -> x.name }.toSortedSet()
}
internal fun <T : Any, Y : Any> T.delegatedProperties(propertyDelegate: Class<Y>): List<Y> = scan(propertyDelegate, this)
private fun <T : Any, Y : Any> scan(propertyDelegate: Class<Y>, obj: T, clazz: Class<T> = obj.javaClass): List<Y> {
val names = clazz.declaredPropertyNames()
val declaredFields = arrayListOf<Y>()
for (it in clazz.declaredFields) {
val name = it.name ?: continue
if (!name.endsWith("\$delegate")) continue
if (!names.contains(name.split('$').first())) continue
it.type ?: continue
it.isAccessible = true
val value = it.get(obj)
if (!propertyDelegate.isInstance(value)) continue
declaredFields.add(propertyDelegate.cast(value)!!)
}
val sup = clazz.getSuperclass()
if (sup != null && sup != Any::class.java) {
return declaredFields + scan<Any, Y>(propertyDelegate, obj, sup as Class<Any>)
} else {
return declaredFields
}
}
| apache-2.0 | 1751076b72c047ab6c4a3664c0d5e2a2 | 33.088235 | 121 | 0.692839 | 3.8125 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/codeInsight/template/context/LuaCodeContextType.kt | 2 | 1704 | /*
* 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.codeInsight.template.context
import com.intellij.codeInsight.template.TemplateContextType
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiUtilCore
import com.tang.intellij.lua.comment.LuaCommentUtil
import com.tang.intellij.lua.lang.LuaFileType
import com.tang.intellij.lua.lang.LuaLanguage
import com.tang.intellij.lua.psi.LuaTypes
/**
* Created by tangzx on 2017/2/11.
*/
class LuaCodeContextType : TemplateContextType("LUA_CODE", "Lua") {
override fun isInContext(file: PsiFile, offset: Int): Boolean {
if (PsiUtilCore.getLanguageAtOffset(file, offset).isKindOf(LuaLanguage.INSTANCE)) {
val element = file.findElementAt(offset)
if (element == null || element is PsiWhiteSpace || LuaCommentUtil.isComment(element)) {
return false
}
if (element.node.elementType in arrayOf(LuaTypes.STRING, LuaTypes.NUMBER)) {
return false
}
}
return file.fileType === LuaFileType.INSTANCE
}
}
| apache-2.0 | 4c966065e9d0134b5500feff1b35adf5 | 36.043478 | 99 | 0.717136 | 4.176471 | false | false | false | false |
VKCOM/vk-android-sdk | core/src/main/java/com/vk/api/sdk/utils/ExponentialBackoff.kt | 1 | 2892 | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package com.vk.api.sdk.utils
import androidx.annotation.WorkerThread
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.min
/**
* @property minDelayMs
* @property maxDelayMs
* @property factor [onError] will multiply delay by this factor
* @property criticalFactor [onCriticalError] will multiply delay by this factor
* @property jitter
*/
open class ExponentialBackoff(
private val minDelayMs: Long = TimeUnit.MILLISECONDS.toMillis(100),
private val maxDelayMs: Long = TimeUnit.MINUTES.toMillis(5),
private val factor: Float = 2f,
private val criticalFactor: Float = 5f,
private val jitter: Float = 0.1f
) {
private val random = Random(System.currentTimeMillis())
@Volatile
var delayMs = minDelayMs
private set
@Volatile
var errorsCount = 0
private set
fun shouldWait() = errorsCount > 0
@WorkerThread
fun waitIfNeeded() {
if (shouldWait()) {
Thread.sleep(delayMs)
}
}
fun reset() {
delayMs = minDelayMs
errorsCount = 0
}
fun onError() = increase(factor)
fun onCriticalError() = increase(criticalFactor)
private fun increase(factor: Float) {
delayMs = min(delayMs * factor, maxDelayMs.toFloat()).toLong()
delayMs += variance(delayMs * jitter)
errorsCount++
}
private fun variance(std: Float) = (random.nextGaussian() * std).toLong()
companion object {
@JvmStatic
fun forNetworkWait() = ExponentialBackoff(minDelayMs = 500, maxDelayMs = 60000, factor = 1.5f)
}
} | mit | ad41dfcf560884c82bc2701f4fe21e44 | 32.252874 | 102 | 0.664246 | 4.597774 | false | false | false | false |
JetBrains-Research/big | src/main/kotlin/org/jetbrains/bio/Support.kt | 2 | 4303 | package org.jetbrains.bio
import com.google.common.base.Stopwatch
import com.google.common.collect.Iterators
import com.google.common.collect.UnmodifiableIterator
import com.google.common.math.IntMath
import com.google.common.math.LongMath
import org.slf4j.Logger
import java.io.BufferedReader
import java.math.RoundingMode
import java.nio.file.Files
import java.nio.file.OpenOption
import java.nio.file.Path
import java.util.zip.GZIPInputStream
import java.util.zip.ZipInputStream
import kotlin.reflect.KProperty
/**
* Various internal helpers.
*
* You shouldn't be using them outside of `big`.
*/
internal infix fun Int.divCeiling(other: Int): Int {
return IntMath.divide(this, other, RoundingMode.CEILING)
}
internal infix fun Long.divCeiling(other: Long): Long {
return LongMath.divide(this, other, RoundingMode.CEILING)
}
/**
* Computes the value n such that base^n <= this.
*/
internal infix fun Int.logCeiling(base: Int): Int {
require(this > 0) { "non-positive number" }
require(base > 1) { "base must be >1" }
var rem = this
var acc = 1
while (rem > base) {
rem = rem divCeiling base
acc++
}
return acc
}
internal inline fun <T> Logger.time(message: String, block: () -> T): T {
debug(message)
val stopwatch = Stopwatch.createStarted()
val res = block()
stopwatch.stop()
debug("Done in $stopwatch")
return res
}
/** A function which simply ignores a given [_value]. */
@Suppress("UNUSED_PARAMETER")
internal fun ignore(_value: Any?) {}
internal operator fun <T> ThreadLocal<T>.getValue(thisRef: Any?, property: KProperty<*>) = get()
internal operator fun <T> ThreadLocal<T>.setValue(thisRef: Any?, property: KProperty<*>, value: T) = set(value)
// XXX calling the 'Iterable<T>#map' leads to boxing.
internal inline fun <R> IntProgression.mapUnboxed(
crossinline transform: (Int) -> R): Sequence<R> {
val it = iterator()
return object : Iterator<R> {
override fun next() = transform(it.nextInt())
override fun hasNext() = it.hasNext()
}.asSequence()
}
internal abstract class CachingIterator<T>(reader: BufferedReader) : UnmodifiableIterator<T>() {
protected var lines = Iterators.peekingIterator(reader.lines().iterator())!!
private var cached: T? = null
override fun hasNext(): Boolean {
if (cached == null) {
cached = cache() // Got some?
}
return cached != null
}
override fun next(): T? {
check(hasNext())
val next = cached
cached = null
return next
}
protected abstract fun cache(): T?
}
/**
* Lazily groups elements of the sequence into sub-sequences based
* on the values produced by the key function [f].
*
* The user is responsible for consuming the resulting sub-sequences
* *in order*. Otherwise the implementation might yield unexpected
* results.
*
* No assumptions are made about the monotonicity of [f].
*/
internal fun <T : Any, K> Sequence<T>.groupingBy(f: (T) -> K): Sequence<Pair<K, Sequence<T>>> {
return Sequence {
object : Iterator<Pair<K, Sequence<T>>> {
private var cached: K? = null
private val it = Iterators.peekingIterator([email protected]())
override fun hasNext() = it.hasNext()
override fun next(): Pair<K, Sequence<T>> {
val target = f(it.peek())
assert(cached == null || cached != target) {
"group (key: $target) was not consumed fully"
}
cached = target
return target to generateSequence {
if (it.hasNext() && f(it.peek()) == cached) {
it.next()
} else {
null
}
}
}
}
}
}
internal fun Path.bufferedReader(vararg options: OpenOption): BufferedReader {
val inputStream = Files.newInputStream(this, *options).buffered()
return when (toFile().extension) {
"gz" -> GZIPInputStream(inputStream)
"zip" ->
// This only works for single-entry ZIP files.
ZipInputStream(inputStream).apply { nextEntry }
else -> inputStream
}.bufferedReader()
}
| mit | 06174557350875ae808adf0803b0ae5f | 28.472603 | 111 | 0.626772 | 4.117703 | false | false | false | false |
xdtianyu/CallerInfo | app/src/main/java/org/xdty/callerinfo/settings/dialog/EditDialog.kt | 1 | 1253 | package org.xdty.callerinfo.settings.dialog
import android.content.Context
import android.content.SharedPreferences
import android.text.InputType
import android.view.View
import android.widget.EditText
import org.xdty.callerinfo.R
class EditDialog(context: Context, sharedPreferences: SharedPreferences) : SettingsDialog(context, sharedPreferences) {
private lateinit var editText: EditText
override fun bindViews() {
val layout = View.inflate(context, R.layout.dialog_edit, null)
builder.setView(layout)
editText = layout.findViewById(R.id.text)
if (defaultText > 0) {
editText.setText(sharedPrefs.getString(key, context.getString(defaultText)))
} else {
editText.setText(sharedPrefs.getString(key, ""))
}
editText.setInputType(InputType.TYPE_CLASS_TEXT)
if (hint > 0) {
editText.setHint(hint)
}
}
override fun onConfirm() {
var value = editText.text.toString()
if (value.isEmpty() && defaultText != 0) {
value = context.getString(defaultText)
}
val editor = sharedPrefs.edit()
editor.putString(key, value)
editor.apply()
super.onConfirm(value)
}
} | gpl-3.0 | 4af5759a5f22d552a351440ed2555b55 | 28.857143 | 119 | 0.660814 | 4.491039 | false | false | false | false |
GlenKPeterson/TestUtils | src/main/java/org/organicdesign/testUtils/EqualsContract.kt | 1 | 7340 | // Copyright 2015-07-03 PlanBase Inc. & Glen Peterson
//
// 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.organicdesign.testUtils
/**
* Tests Reflexive, Symmetric, Transitive, Consistent, and non-nullity properties of the equals()
* contract. If you think this is confusing, realize that there is no way to implement a
* one-sided equals() correctly with inheritance - it's a broken concept, but it's still used so
* often that you have to do your best with it.
*
* I got the idea of contract-based testing from watching Bill Venners:
* https://www.youtube.com/watch?v=bCTZQi2dpl8
*/
object EqualsContract {
/**
* Apply the given function against all unique pairings of items in the list. Does this belong on Function2 instead
* of List?
*/
@JvmStatic
fun <T> permutations(
items: List<T>,
f: (T, T) -> Any?) {
for (i in items.indices) {
for (j in i + 1 until items.size) {
f.invoke(items[i], items[j])
}
}
}
/**
* Tests Reflexive, Symmetric, Transitive, Consistent, and non-nullity properties of the equals()
* contract. See note in class documentation.
*
* @param equiv1 First equivalent (but unique) object
* @param equiv2 Second equivalent (but unique) object (could be a different class)
* @param equiv3 Third equivalent (but unique) object (could be a different class)
* @param different Non-equivalent object with a (maybe) different hashCode (should be an otherwise compatible class)
* @param requireDistinctHashes if true, require that the fourth object have a different hashCode. Otherwise,
* require that it have the same hashCode.
* @param <S> The super-class of all these objects - an interface or super-class within which they should be equal.
</S> */
@JvmStatic
fun equalsHashCode(
equiv1: Any,
equiv2: Any,
equiv3: Any,
different: Any,
requireDistinctHashes: Boolean
) {
require(!(equiv1 === equiv2 ||
equiv1 === equiv3 ||
equiv1 === different ||
equiv2 === equiv3 ||
equiv2 === different ||
equiv3 === different)) { "You must provide four different (having different memory locations) but 3 equivalent objects" }
val equivs: List<Any> = listOf(equiv1, equiv2, equiv3)
if (different.equals(null)) {
throw AssertionError("The different param should not allow itself to equal null")
}
if (different.hashCode() != different.hashCode()) {
throw AssertionError("The different param must have the same hashCode as itself")
}
if (!different.equals(different)) {
throw AssertionError("The different param must equal itself")
}
var i = 0
// Reflexive
for (equiv in equivs) {
i++
if (equiv.hashCode() != equiv.hashCode()) {
throw AssertionError("Param $i must have the same hashCode as itself")
}
if (requireDistinctHashes) {
if (equiv.hashCode() == different.hashCode()) {
throw AssertionError("The hashCode of param " + i + " must not equal the" +
" hashCode of the different param. If you meant to do that, use equalsSameHashCode()" +
" instead.")
}
} else {
if (equiv.hashCode() != different.hashCode()) {
throw AssertionError("The hashCode of param " + i + " must equal the" +
" hashCode of the different param If you meant to do that, use equalsDistinctHashCode()" +
" instead.")
}
}
if (!equiv.equals(equiv)) {
throw AssertionError("Param $i must be equal to itself")
}
if (equiv.equals(different)) {
throw AssertionError("Param $i cannot be equal to the different param")
}
if (different.equals(equiv)) {
throw AssertionError("The different param cannot be equal to param $i")
}
// Check null
if (equiv.equals(null)) {
throw AssertionError("Param $i cannot allow itself to equal null")
}
}
// Symmetric (effectively covers Transitive as well)
permutations(equivs) { a: Any, b: Any ->
if (a.hashCode() != b.hashCode()) {
throw AssertionError("Found an unequal hashCode while inspecting permutations: a=$a b=$b")
}
if (!a.equals(b)) {
throw AssertionError("Failed equals while inspecting permutations: a=$a b=$b")
}
if (!b.equals(a)) {
throw AssertionError("Failed reflexive equals while inspecting permutations: a=$a b=$b")
}
}
}
/**
* Tests Reflexive, Symmetric, Transitive, Consistent, and non-nullity properties of the equals()
* contract. See note in class documentation.
*
* @param equiv1 First equivalent (but unique) object
* @param equiv2 Second equivalent (but unique) object (could be a different class)
* @param equiv3 Third equivalent (but unique) object (could be a different class)
* @param different Non-equivalent object with the same hashCode as the previous three
* @param <S> The super-class of all these objects - an interface or super-class within which they should be equal.
</S> */
@JvmStatic
fun equalsSameHashCode(
equiv1: Any,
equiv2: Any,
equiv3: Any,
different: Any
) {
equalsHashCode(equiv1, equiv2, equiv3, different, false)
}
/**
* Tests Reflexive, Symmetric, Transitive, Consistent, and non-nullity properties of the equals()
* contract. See note in class documentation.
*
* @param equiv1 First equivalent (but unique) object
* @param equiv2 Second equivalent (but unique) object (could be a different class)
* @param equiv3 Third equivalent (but unique) object (could be a different class)
* @param different Non-equivalent object with a different hashCode (should be an otherwise compatible class)
* @param <S> The super-class of all these objects - an interface or super-class within which they should be equal.
</S> */
@JvmStatic
fun equalsDistinctHashCode(
equiv1: Any,
equiv2: Any,
equiv3: Any,
different: Any
) {
equalsHashCode(equiv1, equiv2, equiv3, different, true)
}
} | apache-2.0 | 1d5cc271e513d783f6fa4494aae07afd | 42.958084 | 139 | 0.599183 | 4.675159 | false | false | false | false |
zlyne0/colonization | core/src/promitech/colonization/screen/debug/DebugConsole.kt | 1 | 3377 | package promitech.colonization.screen.debug
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.ui.TextField
import com.badlogic.gdx.utils.Align
import net.sf.freecol.common.model.Tile
import promitech.colonization.screen.map.hud.GUIGameController
import promitech.colonization.screen.map.hud.GUIGameModel
import promitech.colonization.GameResources
import promitech.colonization.ui.ClosableDialog
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.badlogic.gdx.Input.Keys
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.InputEvent
import net.sf.freecol.common.model.map.generator.MapGenerator
import net.sf.freecol.common.model.UnitIterator
import net.sf.freecol.common.model.Unit
import promitech.colonization.DI
class DebugConsole(val commands : Commands)
: ClosableDialog<DebugConsole>(), ConsoleOutput
{
private val dialogLayout = Table()
private val textField = TextField("", GameResources.instance.getUiSkin())
private val label = Label("", GameResources.instance.getUiSkin())
private val scrollPane = ScrollPane(label)
var keepOpenConsoleAfterExecute : Boolean = false
init {
label.setAlignment(Align.top or Align.left);
//label.setFillParent(true)
scrollPane.setForceScroll(false, false)
scrollPane.setFadeScrollBars(false)
scrollPane.setOverscroll(true, true)
scrollPane.setScrollBarPositions(false, true)
dialogLayout.add(scrollPane).expand().fill().row()
dialogLayout.add(textField).fillX().expandX()
getContentTable().add(dialogLayout)
dialog.addListener(object : InputListener() {
override fun keyDown(event: InputEvent, keycode: Int) : Boolean {
if (keycode == Keys.ENTER) {
executeCommand()
return true
}
if (keycode == Keys.TAB) {
hintCommand()
return true
}
return false
}
})
withHidingOnEsc();
}
fun executeCommand() {
var cmd = textField.getText()
textField.setText("")
out(cmd)
val executedCmd = commands.execute(cmd)
if (executedCmd != null && !keepOpenConsoleAfterExecute) {
hideWithFade()
}
keepOpenConsoleAfterExecute = false
}
fun hintCommand() {
var enteredCmd = textField.getText();
out(" hints: ")
val filteredCommands = commands.filterCommandsByPrefix(enteredCmd)
filteredCommands.forEach { cmdName ->
out(cmdName)
}
var enlargedCommand = commands.enlargeHintCommandToBetterMatch(enteredCmd)
textField.setText(enlargedCommand)
if (filteredCommands.size == 1) {
textField.setText(textField.getText() + " ")
}
textField.setCursorPosition(textField.getText().length)
}
override fun out(line: String) : ConsoleOutput {
if (label.getText().toString().equals("")) {
label.setText(line)
} else {
label.setText(label.getText().toString() + "\n" + line)
}
scrollPane.setScrollPercentY(100f)
scrollPane.layout()
return this
}
override fun keepOpen() : ConsoleOutput {
keepOpenConsoleAfterExecute = true
return this
}
override fun show(stage: Stage) {
getContentTable().getCell(dialogLayout)
.width(stage.getWidth() * 0.75f)
.height(stage.getHeight() * 0.75f)
super.show(stage)
stage.setKeyboardFocus(textField)
}
}
| gpl-2.0 | 400089e295f78d93b44ba73b46ee045a | 27.863248 | 78 | 0.747705 | 3.50675 | false | false | false | false |
Heiner1/AndroidAPS | openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/ui/OHFragment.kt | 1 | 2803 | package info.nightscout.androidaps.plugin.general.openhumans.ui
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.view.ContextThemeWrapper
import androidx.lifecycle.LiveData
import com.google.android.material.button.MaterialButton
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.plugin.general.openhumans.R
import info.nightscout.androidaps.plugin.general.openhumans.OpenHumansState
import info.nightscout.androidaps.plugin.general.openhumans.OpenHumansUploader
import javax.inject.Inject
class OHFragment : DaggerFragment() {
@Inject
internal lateinit var stateLiveData: LiveData<OpenHumansState?>
@Inject
internal lateinit var plugin: OpenHumansUploader
private lateinit var setup: MaterialButton
private lateinit var logout: MaterialButton
private lateinit var uploadNow: MaterialButton
private lateinit var info: TextView
private lateinit var memberId: TextView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val contextWrapper = ContextThemeWrapper(requireActivity(), R.style.OpenHumans)
val wrappedInflater = inflater.cloneInContext(contextWrapper)
val view = wrappedInflater.inflate(R.layout.fragment_open_humans_new, container, false)
setup = view.findViewById(R.id.setup)
setup.setOnClickListener { startActivity(Intent(context, OHLoginActivity::class.java)) }
logout = view.findViewById(R.id.logout)
logout.setOnClickListener { plugin.logout() }
info = view.findViewById(R.id.info)
memberId = view.findViewById(R.id.member_id)
uploadNow = view.findViewById(R.id.upload_now)
uploadNow.setOnClickListener { plugin.uploadNow() }
return view
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
stateLiveData.observe(this) { state ->
if (state == null) {
setup.visibility = View.VISIBLE
logout.visibility = View.GONE
memberId.visibility = View.GONE
uploadNow.visibility = View.GONE
info.setText(R.string.not_setup_info)
} else {
setup.visibility = View.GONE
logout.visibility = View.VISIBLE
memberId.visibility = View.VISIBLE
uploadNow.visibility = View.VISIBLE
memberId.text = getString(R.string.project_member_id, state.projectMemberId)
info.setText(R.string.setup_completed_info)
}
}
}
} | agpl-3.0 | 5e708312aeb03edf097107f9672b8bdf | 39.057143 | 96 | 0.703532 | 4.80789 | false | false | false | false |
maiconhellmann/pomodoro | app/src/main/kotlin/br/com/maiconhellmann/pomodoro/data/local/DatabaseHelper.kt | 1 | 3175 | package br.com.maiconhellmann.pomodoro.data.local
import android.content.ContentValues
import br.com.maiconhellmann.pomodoro.data.model.Pomodoro
import br.com.maiconhellmann.pomodoro.data.model.PomodoroStatus
import com.squareup.sqlbrite.BriteDatabase
import rx.Emitter
import rx.Observable
import timber.log.Timber
import java.sql.SQLException
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DatabaseHelper
@Inject constructor(val db: BriteDatabase) {
fun findAllPomodoro(): Observable<List<Pomodoro>>{
return db.createQuery(Db.PomodoroTable.TABLE_NAME,
"SELECT * FROM ${Db.PomodoroTable.TABLE_NAME}")
.mapToList<Pomodoro> {
Db.PomodoroTable.parseCursor(it)
}
}
fun savePomodoro(pomodoro: Pomodoro): Observable<Pomodoro> {
return Observable.create<Pomodoro>({emitter ->
val transaction = db.newTransaction()
try{
if(pomodoro.id != 0L){
db.update(Db.PomodoroTable.TABLE_NAME,
Db.PomodoroTable.toContentValues(pomodoro),
Db.PomodoroTable.COLUMN_ID+ " = ?",
pomodoro.id.toString())
}else{
val id = db.insert(Db.PomodoroTable.TABLE_NAME, Db.PomodoroTable.toContentValues(pomodoro))
pomodoro.id = id
}
transaction.markSuccessful()
emitter.onNext(pomodoro)
} catch (exception: SQLException) {
Timber.e(exception)
emitter.onError(exception)
}
transaction.end()
}, Emitter.BackpressureMode.BUFFER )
}
fun findRunningPomodoro(): Observable<Pomodoro>{
val sql = "SELECT * FROM ${Db.PomodoroTable.TABLE_NAME} " +
"where ${Db.PomodoroTable.COLUMN_STATUS} = ? " +
"order by ${Db.PomodoroTable.COLUMN_ID} desc " +
"limit 1 "
var cursor = db.createQuery(Db.PomodoroTable.TABLE_NAME, sql, PomodoroStatus.RUNNING.id.toString())
return cursor.mapToOne{Db.PomodoroTable.parseCursor(it)}
}
fun stopRunningPomodoro(pomodoro: Pomodoro): Observable<Unit>{
return Observable.create<Unit>({emitter ->
val transaction = db.newTransaction()
try{
val cv = ContentValues()
cv.put(Db.PomodoroTable.COLUMN_STATUS, PomodoroStatus.STOPPED.id)
cv.put(Db.PomodoroTable.COLUMN_END_TIME, System.currentTimeMillis())
db.update(Db.PomodoroTable.TABLE_NAME, cv,
"${Db.PomodoroTable.COLUMN_ID} =? ",
pomodoro.id.toString())
transaction.markSuccessful()
emitter.onCompleted()
} catch (exception: SQLException) {
Timber.e(exception)
emitter.onError(exception)
}
transaction.end()
}, Emitter.BackpressureMode.BUFFER )
}
}
| apache-2.0 | 392aa462fda6c931146d3e0753ee3aa2 | 34.079545 | 111 | 0.571654 | 4.892142 | false | false | false | false |
weitjong/Urho3D | android/launcher-app/src/main/java/com/github/urho3d/launcher/MainActivity.kt | 2 | 2101 | //
// Copyright (c) 2008-2020 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
package com.github.urho3d.launcher
import com.github.urho3d.UrhoActivity
class MainActivity : UrhoActivity() {
companion object {
const val argument = "argument"
}
private lateinit var arguments: List<String>
override fun getArguments() = arguments.toTypedArray()
override fun onLoadLibrary(libraryNames: MutableList<String>) {
// All runtime shared libraries must always be loaded if available
val regex = Regex("^(?:Urho3D|.+_shared)\$")
libraryNames.retainAll { regex.matches(it) }
// Parse the argument string
val argumentString = intent.getStringExtra(argument)
if (argumentString != null) arguments = argumentString.split(':')
else throw IllegalArgumentException("The MainActivity requires an argument to start")
// Must add the chosen sample library to the last of the list
libraryNames.add(arguments[0])
super.onLoadLibrary(libraryNames)
}
}
| mit | a3dccadf2d8ef6a2cafcdbbade1ff38f | 38.641509 | 93 | 0.727749 | 4.64823 | false | false | false | false |
duncte123/SkyBot | src/main/kotlin/ml/duncte123/skybot/commands/uncategorized/KickMeCommand.kt | 1 | 3763 | /*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32"
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot.commands.uncategorized
import me.duncte123.botcommons.messaging.MessageConfig
import me.duncte123.botcommons.messaging.MessageUtils
import ml.duncte123.skybot.objects.command.Command
import ml.duncte123.skybot.objects.command.CommandContext
import ml.duncte123.skybot.utils.ModerationUtils
import net.dv8tion.jda.api.Permission
import java.util.concurrent.TimeUnit
class KickMeCommand : Command() {
init {
this.name = "kickme"
this.help = "Kicks you off the server"
}
override fun execute(ctx: CommandContext) {
val prefix = ctx.prefix
val event = ctx.event
val args = ctx.args
val warningMsg = """**WARNING** this command will kick you from this server
|If you are sure that you want to kick yourself off this server use `$prefix$name YESIMSURE`
|By running `$prefix$name YESIMSURE` you agree that you are responsible for the consequences of this command.
|DuncteBot and any of it's developers are not responsible for your own kick by running this command
""".trimMargin()
if (args.isEmpty() || args[0] != "YESIMSURE") {
MessageUtils.sendMsg(ctx, warningMsg)
} else if (args.isNotEmpty() && args[0] == "YESIMSURE") {
// Check for perms
if (event.guild.selfMember.canInteract(ctx.member) && event.guild.selfMember.hasPermission(Permission.KICK_MEMBERS)) {
MessageUtils.sendSuccess(event.message)
// Kick the user
MessageUtils.sendMsg(
MessageConfig.Builder.fromCtx(ctx)
.setMessage("Your kick will commence in 20 seconds")
.setSuccessAction {
it.guild.kick(ctx.member)
.reason("${event.author.asTag} ran the kickme command and got kicked")
.queueAfter(20L, TimeUnit.SECONDS) {
ModerationUtils.modLog(
event.jda.selfUser,
event.author,
"kicked",
"Used the kickme command",
null,
ctx.guild
)
}
}
.build()
)
} else {
MessageUtils.sendMsg(
ctx,
"""I'm missing the permission to kick you.
|You got lucky this time ${ctx.member.asMention}.
""".trimMargin()
)
}
} else {
MessageUtils.sendMsg(ctx, warningMsg)
}
}
}
| agpl-3.0 | 75645eb015db394b5cda49992c6a8cf4 | 43.797619 | 133 | 0.557002 | 5.010652 | false | false | false | false |
DiUS/pact-jvm | core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/QueryMatcher.kt | 1 | 3293 | package au.com.dius.pact.core.matchers
import au.com.dius.pact.core.model.matchingrules.MatchingRules
import au.com.dius.pact.core.model.matchingrules.MatchingRulesImpl
import mu.KLogging
import org.atteo.evo.inflector.English
object QueryMatcher : KLogging() {
private fun compare(
parameter: String,
path: List<String>,
expected: String,
actual: String,
matchers: MatchingRules
): List<QueryMismatch> {
return if (Matchers.matcherDefined("query", listOf(parameter), matchers)) {
logger.debug { "compareQueryParameterValues: Matcher defined for query parameter '$parameter'" }
Matchers.domatch(matchers, "query", listOf(parameter), expected, actual, QueryMismatchFactory)
} else {
logger.debug { "compareQueryParameterValues: No matcher defined for query parameter '$parameter', using equality" }
if (expected == actual) {
emptyList()
} else {
listOf(QueryMismatch(parameter, expected, actual, "Expected '$expected' but received '$actual' " +
"for query parameter '$parameter'", parameter))
}
}
}
private fun compareQueryParameterValues(
parameter: String,
expected: List<String>,
actual: List<String>,
path: List<String>,
matchers: MatchingRules
): List<QueryMismatch> {
return expected.mapIndexed { index, value -> index to value }
.flatMap { (index, value) ->
when {
index < actual.size -> compare(parameter, path + index.toString(), value, actual[index], matchers)
!Matchers.matcherDefined("query", path, matchers) ->
listOf(QueryMismatch(parameter, expected.toString(), actual.toString(),
"Expected query parameter '$parameter' with value '$value' but was missing",
path.joinToString(".")))
else -> emptyList()
}
}
}
@JvmStatic
fun compareQuery(
parameter: String,
expected: List<String>,
actual: List<String>,
matchingRules: MatchingRules?
): List<QueryMismatch> {
val path = listOf(parameter)
val matchers = matchingRules ?: MatchingRulesImpl()
return if (Matchers.matcherDefined("query", path, matchers)) {
logger.debug { "compareQuery: Matcher defined for query parameter '$parameter'" }
Matchers.domatch(matchers, "query", path, expected, actual, QueryMismatchFactory) +
compareQueryParameterValues(parameter, expected, actual, path, matchers)
} else {
if (expected.isEmpty() && actual.isNotEmpty()) {
listOf(QueryMismatch(parameter, expected.toString(), actual.toString(),
"Expected an empty parameter List for '$parameter' but received $actual",
path.joinToString(".")))
} else {
val mismatches = mutableListOf<QueryMismatch>()
if (expected.size != actual.size) {
mismatches.add(QueryMismatch(parameter, expected.toString(), actual.toString(),
"Expected query parameter '$parameter' with ${expected.size} " +
"${English.plural("value", expected.size)} but received ${actual.size} " +
English.plural("value", actual.size),
path.joinToString(".")))
}
mismatches + compareQueryParameterValues(parameter, expected, actual, path, matchers)
}
}
}
}
| apache-2.0 | 464fce348e7c079995e39d7f5415f8d8 | 39.158537 | 121 | 0.658974 | 4.579972 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/adapters/AuthorSelectionAdapter.kt | 1 | 6415 | package org.wordpress.android.ui.posts.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import androidx.annotation.CallSuper
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.graphics.ColorUtils
import com.google.android.material.elevation.ElevationOverlayProvider
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.ui.posts.AuthorFilterListItemUIState
import org.wordpress.android.ui.posts.AuthorFilterSelection
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.GravatarUtils
import org.wordpress.android.util.extensions.getColorFromAttribute
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.util.image.ImageType.NO_PLACEHOLDER
import javax.inject.Inject
class AuthorSelectionAdapter(context: Context) : BaseAdapter() {
@Inject lateinit var imageManager: ImageManager
@Inject lateinit var uiHelpers: UiHelpers
private val items = mutableListOf<AuthorFilterListItemUIState>()
init {
(context.applicationContext as WordPress).component().inject(this)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
var view: View? = convertView
val holder: DropdownViewHolder
if (view == null) {
val inflater = LayoutInflater.from(parent.context)
view = inflater.inflate(R.layout.author_selection_dropdown, parent, false)
holder = DropdownViewHolder(view)
view.tag = holder
} else {
holder = view.tag as DropdownViewHolder
}
holder.bind(items[position], imageManager, uiHelpers)
return view!!
}
override fun getItemId(position: Int): Long = items[position].id
fun getIndexOfSelection(selection: AuthorFilterSelection): Int? {
for ((index, item) in items.withIndex()) {
if (item.id == selection.id) {
return index
}
}
return null
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var view: View? = convertView
val holder: NormalViewHolder
if (view == null) {
val inflater = LayoutInflater.from(parent.context)
view = inflater.inflate(R.layout.author_selection, parent, false)
holder = NormalViewHolder(view)
view.tag = holder
} else {
holder = view.tag as NormalViewHolder
}
holder.bind(items[position], imageManager, uiHelpers)
return view!!
}
override fun hasStableIds(): Boolean = true
override fun getItem(position: Int): Any = items[position]
override fun getCount(): Int = items.count()
fun updateItems(newItems: List<AuthorFilterListItemUIState>) {
items.clear()
items.addAll(newItems)
notifyDataSetChanged()
}
private open class NormalViewHolder(protected val itemView: View) {
protected val image: AppCompatImageView = itemView.findViewById(R.id.author_selection_image)
@CallSuper
open fun bind(
state: AuthorFilterListItemUIState,
imageManager: ImageManager,
uiHelpers: UiHelpers
) {
/**
* We can't use error/placeholder drawables as it causes an issue described here
* https://github.com/wordpress-mobile/WordPress-Android/issues/9745.
* It seems getView method always returns convertView == null when used with Spinner. When we invoke
* imageManager.load..(url..) in the view holder and the 'url' is empty or the requests fails
* an error/placeholder drawable is used. However, this results in another layout/measure phase
* -> getView(..) is called again. However, since the convertView == null we inflate a new view and
* imageManager.load..(..) is invoked again - this goes on forever.
* In order to prevent this issue we don't use placeholder/error drawables in this case.
* The cost of this solution is that an empty circle is shown if we don't have the avatar in the cache
* and the request fails.
*/
when (state) {
is AuthorFilterListItemUIState.Everyone -> {
imageManager.load(image, state.imageRes)
}
is AuthorFilterListItemUIState.Me -> {
val avatarSize = image.resources.getDimensionPixelSize(R.dimen.avatar_sz_small)
val url = GravatarUtils.fixGravatarUrl(state.avatarUrl, avatarSize)
imageManager.loadIntoCircle(image, NO_PLACEHOLDER, url)
}
}
}
}
private class DropdownViewHolder(itemView: View) : NormalViewHolder(itemView) {
private val text: AppCompatTextView = itemView.findViewById(R.id.author_selection_text)
override fun bind(
state: AuthorFilterListItemUIState,
imageManager: ImageManager,
uiHelpers: UiHelpers
) {
super.bind(state, imageManager, uiHelpers)
val context = itemView.context
// Because it's a custom popup list we need to manage colors of list items manually
val elevationOverlayProvider = ElevationOverlayProvider(context)
val appbarElevation = context.resources.getDimension(R.dimen.appbar_elevation)
val elevatedSurfaceColor = elevationOverlayProvider.compositeOverlayWithThemeSurfaceColorIfNeeded(
appbarElevation
)
val selectedColor = ColorUtils
.setAlphaComponent(
context.getColorFromAttribute(R.attr.colorOnSurface),
context.resources.getInteger(R.integer.custom_popup_selected_list_item_opacity_dec)
)
text.text = uiHelpers.getTextOfUiString(context, state.text)
if (state.isSelected) {
itemView.setBackgroundColor(selectedColor)
} else {
itemView.setBackgroundColor(elevatedSurfaceColor)
}
}
}
}
| gpl-2.0 | 1def5c286c80c592970dcdab83824c29 | 39.09375 | 114 | 0.656586 | 5.140224 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/mysite/ScanAndBackupSource.kt | 1 | 2639 | package org.wordpress.android.ui.mysite
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.ui.jetpack.JetpackCapabilitiesUseCase
import org.wordpress.android.ui.mysite.MySiteSource.MySiteRefreshSource
import org.wordpress.android.ui.mysite.MySiteUiState.PartialState.JetpackCapabilities
import org.wordpress.android.util.SiteUtils
import javax.inject.Inject
import javax.inject.Named
class ScanAndBackupSource @Inject constructor(
@param:Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher,
private val selectedSiteRepository: SelectedSiteRepository,
private val jetpackCapabilitiesUseCase: JetpackCapabilitiesUseCase
) : MySiteRefreshSource<JetpackCapabilities> {
override val refresh = MutableLiveData(false)
fun clear() {
jetpackCapabilitiesUseCase.clear()
}
override fun build(coroutineScope: CoroutineScope, siteLocalId: Int): LiveData<JetpackCapabilities> {
val result = MediatorLiveData<JetpackCapabilities>()
result.addSource(refresh) { result.refreshData(coroutineScope, siteLocalId, refresh.value) }
refresh()
return result
}
private fun MediatorLiveData<JetpackCapabilities>.refreshData(
coroutineScope: CoroutineScope,
siteLocalId: Int,
isRefresh: Boolean? = null
) {
when (isRefresh) {
null, true -> refreshData(coroutineScope, siteLocalId)
false -> Unit // Do nothing
}
}
private fun MediatorLiveData<JetpackCapabilities>.refreshData(
coroutineScope: CoroutineScope,
siteLocalId: Int
) {
val selectedSite = selectedSiteRepository.getSelectedSite()
if (selectedSite != null && selectedSite.id == siteLocalId) {
coroutineScope.launch(bgDispatcher) {
jetpackCapabilitiesUseCase.getJetpackPurchasedProducts(selectedSite.siteId).collect {
postState(
JetpackCapabilities(
scanAvailable = SiteUtils.isScanEnabled(it.scan, selectedSite),
backupAvailable = it.backup
)
)
}
}
} else {
postState(JetpackCapabilities(scanAvailable = false, backupAvailable = false))
}
}
}
| gpl-2.0 | 6134ddb77132db03c717a661a52c6f96 | 38.38806 | 105 | 0.694581 | 5.6875 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/ScriptTemplatesFromDependenciesProvider.kt | 1 | 10194 | // 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.script
import com.intellij.ProjectTopics
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.FileTypeIndex
import com.intellij.util.indexing.DumbModeAccessType
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.allScope
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionSourceAsContributor
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.core.script.loadDefinitionsFromTemplatesByPaths
import org.jetbrains.kotlin.scripting.definitions.SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.getEnvironment
import java.io.File
import java.nio.file.Path
import java.util.concurrent.Callable
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.script.experimental.host.ScriptingHostConfiguration
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
class ScriptTemplatesFromDependenciesProvider(private val project: Project) : ScriptDefinitionSourceAsContributor {
private val logger = Logger.getInstance(ScriptTemplatesFromDependenciesProvider::class.java)
override val id = "ScriptTemplatesFromDependenciesProvider"
override fun isReady(): Boolean = _definitions != null
override val definitions: Sequence<ScriptDefinition>
get() {
definitionsLock.withLock {
_definitions?.let { return it.asSequence() }
}
forceStartUpdate = false
asyncRunUpdateScriptTemplates()
return emptySequence()
}
init {
val connection = project.messageBus.connect()
connection.subscribe(
ProjectTopics.PROJECT_ROOTS,
object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
if (project.isInitialized) {
forceStartUpdate = true
asyncRunUpdateScriptTemplates()
}
}
},
)
}
private fun asyncRunUpdateScriptTemplates() {
definitionsLock.withLock {
if (!forceStartUpdate && _definitions != null) return
}
if (inProgress.compareAndSet(false, true)) {
loadScriptDefinitions()
}
}
@Volatile
private var _definitions: List<ScriptDefinition>? = null
private val definitionsLock = ReentrantLock()
private var oldTemplates: TemplatesWithCp? = null
private data class TemplatesWithCp(
val templates: List<String>,
val classpath: List<Path>,
)
private val inProgress = AtomicBoolean(false)
@Volatile
private var forceStartUpdate = false
private fun loadScriptDefinitions() {
if (project.isDefault) {
return onEarlyEnd()
}
if (logger.isDebugEnabled) {
logger.debug("async script definitions update started")
}
val task = object : Task.Backgroundable(
project, KotlinBundle.message("kotlin.script.lookup.definitions"), false
) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val pluginDisposable = KotlinPluginDisposable.getInstance(project)
val (templates, classpath) =
ReadAction.nonBlocking(Callable {
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode(ThrowableComputable {
val files = mutableSetOf<VirtualFile>()
FileTypeIndex.processFiles(ScriptDefinitionMarkerFileType, {
indicator.checkCanceled()
files.add(it)
true
}, project.allScope())
getTemplateClassPath(files, indicator)
})
})
.expireWith(pluginDisposable)
.wrapProgress(indicator)
.executeSynchronously() ?: return onEarlyEnd()
try {
indicator.checkCanceled()
if (pluginDisposable.disposed || !inProgress.get() || templates.isEmpty()) return onEarlyEnd()
val newTemplates = TemplatesWithCp(templates.toList(), classpath.toList())
if (!inProgress.get() || newTemplates == oldTemplates) return onEarlyEnd()
if (logger.isDebugEnabled) {
logger.debug("script templates found: $newTemplates")
}
oldTemplates = newTemplates
val hostConfiguration = ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration) {
getEnvironment {
mapOf(
"projectRoot" to (project.basePath ?: project.baseDir.canonicalPath)?.let(::File),
)
}
}
val newDefinitions = loadDefinitionsFromTemplatesByPaths(
templateClassNames = newTemplates.templates,
templateClasspath = newTemplates.classpath,
baseHostConfiguration = hostConfiguration,
)
indicator.checkCanceled()
if (logger.isDebugEnabled) {
logger.debug("script definitions found: ${newDefinitions.joinToString()}")
}
val needReload = definitionsLock.withLock {
if (newDefinitions != _definitions) {
_definitions = newDefinitions
return@withLock true
}
return@withLock false
}
if (needReload) {
ScriptDefinitionsManager.getInstance(project).reloadDefinitionsBy(this@ScriptTemplatesFromDependenciesProvider)
}
} finally {
inProgress.set(false)
}
}
}
ProgressManager.getInstance().runProcessWithProgressAsynchronously(
task,
BackgroundableProcessIndicator(task)
)
}
private fun onEarlyEnd() {
definitionsLock.withLock {
_definitions = emptyList()
}
inProgress.set(false)
}
// public for tests
fun getTemplateClassPath(files: Collection<VirtualFile>, indicator: ProgressIndicator): Pair<Collection<String>, Collection<Path>> {
val rootDirToTemplates: MutableMap<VirtualFile, MutableList<VirtualFile>> = hashMapOf()
for (file in files) {
val dir = file.parent?.parent?.parent?.parent?.parent ?: continue
rootDirToTemplates.getOrPut(dir) { arrayListOf() }.add(file)
}
val templates = linkedSetOf<String>()
val classpath = linkedSetOf<Path>()
rootDirToTemplates.forEach { (root, templateFiles) ->
if (logger.isDebugEnabled) {
logger.debug("root matching SCRIPT_DEFINITION_MARKERS_PATH found: ${root.path}")
}
val orderEntriesForFile = ProjectFileIndex.getInstance(project).getOrderEntriesForFile(root)
.filter {
indicator.checkCanceled()
if (it is ModuleSourceOrderEntry) {
if (ModuleRootManager.getInstance(it.ownerModule).fileIndex.isInTestSourceContent(root)) {
return@filter false
}
it.getFiles(OrderRootType.SOURCES).contains(root)
} else {
it is LibraryOrSdkOrderEntry && it.getFiles(OrderRootType.CLASSES).contains(root)
}
}
.takeIf { it.isNotEmpty() } ?: return@forEach
for (virtualFile in templateFiles) {
templates.add(virtualFile.name.removeSuffix(SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT))
}
// assuming that all libraries are placed into classes roots
// TODO: extract exact library dependencies instead of putting all module dependencies into classpath
// minimizing the classpath needed to use the template by taking cp only from modules with new templates found
// on the other hand the approach may fail if some module contains a template without proper classpath, while
// the other has properly configured classpath, so assuming that the dependencies are set correctly everywhere
for (orderEntry in orderEntriesForFile) {
for (virtualFile in OrderEnumerator.orderEntries(orderEntry.ownerModule).withoutSdk().classesRoots) {
indicator.checkCanceled()
val localVirtualFile = VfsUtil.getLocalFile(virtualFile)
localVirtualFile.fileSystem.getNioPath(localVirtualFile)?.let(classpath::add)
}
}
}
return templates to classpath
}
} | apache-2.0 | 8bc7cac9aa8bcca7f2ff88587c1c531f | 41.656904 | 158 | 0.616833 | 6.137267 | false | false | false | false |
mbrlabs/Mundus | editor/src/main/com/mbrlabs/mundus/editor/ui/modules/dialogs/ExportDialog.kt | 1 | 3699 | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.ui.modules.dialogs
import com.kotcrab.vis.ui.util.async.AsyncTaskListener
import com.kotcrab.vis.ui.widget.VisDialog
import com.kotcrab.vis.ui.widget.VisLabel
import com.kotcrab.vis.ui.widget.VisProgressBar
import com.mbrlabs.mundus.editor.Mundus
import com.mbrlabs.mundus.editor.core.kryo.KryoManager
import com.mbrlabs.mundus.editor.core.project.ProjectManager
import com.mbrlabs.mundus.editor.exporter.Exporter
import com.mbrlabs.mundus.editor.ui.UI
import com.mbrlabs.mundus.editor.utils.Log
import com.mbrlabs.mundus.editor.utils.Toaster
/**
* @author Marcus Brummer
* @version 26-12-2015
*/
class ExportDialog : VisDialog("Exporting") {
private var lastExport: Long = 0
private val label = VisLabel()
private val progressBar = VisProgressBar(0f, 100f, 1f, false)
private val projectManager: ProjectManager = Mundus.inject()
private val kryoManager: KryoManager = Mundus.inject()
init {
isModal = true
isMovable = false
contentTable.add(label).padBottom(UI.PAD_BOTTOM).padTop(UI.PAD_BOTTOM_X2).left().growX().row()
contentTable.add(progressBar).width(300f).left().growX().row()
}
fun export() {
// validate
val export = projectManager.current().settings?.export
if(export == null || export.outputFolder == null
|| export.outputFolder.path().isEmpty() || !export.outputFolder.exists()) {
UI.toaster.error("Export Error\nYou have to supply a output folder in the export settings." +
"\nWindow -> Settings -> Export Settings")
return
}
// prevent from exporting to fast which sometimes results in the export dialog not closing correctly
if(System.currentTimeMillis() - lastExport < 1000f) {
UI.toaster.error("Export pending")
return
}
show(UI)
Exporter(kryoManager, projectManager.current()).exportAsync(export.outputFolder, object: AsyncTaskListener {
private var error = false
override fun progressChanged(newProgressPercent: Int) {
progressBar.value = newProgressPercent.toFloat()
}
override fun finished() {
if(!error) {
UI.toaster.success("Project exported")
}
resetValues()
close()
lastExport = System.currentTimeMillis()
}
override fun messageChanged(message: String?) {
label.setText(message)
}
override fun failed(message: String?, exception: Exception?) {
Log.exception("Exporter", exception)
UI.toaster.sticky(Toaster.ToastType.ERROR, "Export failed: " + exception.toString())
error = true
resetValues()
close()
}
})
}
private fun resetValues() {
progressBar.value = 0f
label.setText("")
}
override fun close() {
super.close()
}
}
| apache-2.0 | 5e8e73078db9f840786c3d7ee24b644d | 32.627273 | 116 | 0.639362 | 4.445913 | false | false | false | false |
GunoH/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/text/SuppressionPattern.kt | 8 | 567 | package com.intellij.grazie.text
import com.intellij.grazie.GrazieConfig
class SuppressionPattern(errorText: CharSequence, sentenceText: String?) {
internal val errorText : String = normalize(errorText)
internal val sentenceText : String? = sentenceText?.let(::normalize)
internal val full : String = this.errorText + (if (sentenceText == null) "" else "|" + this.sentenceText)
private fun normalize(text: CharSequence) = text.replace(Regex("\\s+"), " ").trim()
fun isSuppressed(): Boolean = full in GrazieConfig.get().suppressingContext.suppressed
}
| apache-2.0 | 4bf6be08513734d918ce4687446e615b | 42.615385 | 107 | 0.742504 | 4.361538 | false | true | false | false |
jovr/imgui | core/src/main/kotlin/imgui/internal/api/generic context hooks.kt | 1 | 742 | package imgui.internal.api
import imgui.classes.Context
import imgui.classes.ContextHook
import imgui.classes.ContextHookType
// Generic context hooks
interface `generic context hooks` {
/** No specific ordering/dependency support, will see as needed */
fun addContextHook(ctx: Context, hook: ContextHook) {
val g = ctx
// assert(hook.callback != null)
g.hooks += hook
}
/** Call context hooks (used by e.g. test engine)
* We assume a small number of hooks so all stored in same array */
fun callContextHooks(ctx: Context, hookType: ContextHookType) {
val g = ctx
for (hook in g.hooks)
if (hook.type == hookType)
hook.callback!!(g, hook)
}
} | mit | d9a635d9ac77c92a84981624adb2d071 | 28.72 | 72 | 0.6469 | 4.010811 | false | false | false | false |
google/android-fhir | datacapture/src/test/java/com/google/android/fhir/datacapture/fhirpath/ExpressionEvaluatorTest.kt | 1 | 21399 | /*
* 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.datacapture.fhirpath
import com.google.android.fhir.datacapture.EXTENSION_CALCULATED_EXPRESSION_URL
import com.google.android.fhir.datacapture.EXTENSION_VARIABLE_URL
import com.google.android.fhir.datacapture.common.datatype.asStringValue
import com.google.android.fhir.datacapture.fhirpath.ExpressionEvaluator.detectExpressionCyclicDependency
import com.google.android.fhir.datacapture.fhirpath.ExpressionEvaluator.evaluateCalculatedExpressions
import com.google.android.fhir.datacapture.variableExpressions
import com.google.common.truth.Truth.assertThat
import java.util.Calendar
import java.util.Date
import kotlinx.coroutines.runBlocking
import org.hl7.fhir.r4.model.DateType
import org.hl7.fhir.r4.model.Expression
import org.hl7.fhir.r4.model.IntegerType
import org.hl7.fhir.r4.model.Quantity
import org.hl7.fhir.r4.model.Questionnaire
import org.hl7.fhir.r4.model.QuestionnaireResponse
import org.hl7.fhir.r4.model.Type
import org.junit.Assert.assertThrows
import org.junit.Test
class ExpressionEvaluatorTest {
@Test
fun `should return not null value with simple variable expression for questionnaire root level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "1"
}
)
}
}
val result =
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.first(),
questionnaire,
QuestionnaireResponse()
)
assertThat((result as Type).asStringValue()).isEqualTo("1")
}
@Test
fun `should return not null value with variables dependent on other variables for questionnaire root level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "1"
}
)
}
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "B"
language = "text/fhirpath"
expression = "%A + 1"
}
)
}
}
val result =
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.last(),
questionnaire,
QuestionnaireResponse()
)
assertThat((result as Type).asStringValue()).isEqualTo("2")
}
@Test
fun `should return not null value with variables dependent on other variables in parent for questionnaire item level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-group-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.GROUP
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "1"
}
)
}
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "an-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.TEXT
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "B"
language = "text/fhirpath"
expression = "%A + 1"
}
)
}
}
)
}
)
}
val result =
ExpressionEvaluator.evaluateQuestionnaireItemVariableExpression(
questionnaire.item[0].item[0].variableExpressions.last(),
questionnaire,
QuestionnaireResponse(),
mapOf(questionnaire.item[0].item[0] to questionnaire.item[0]),
questionnaire.item[0].item[0]
)
assertThat((result as Type).asStringValue()).isEqualTo("2")
}
@Test
fun `should return not null value with variables dependent on multiple variables for questionnaire root level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "1"
}
)
}
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "B"
language = "text/fhirpath"
expression = "2"
}
)
}
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "C"
language = "text/fhirpath"
expression = "%A + %B"
}
)
}
}
val result =
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.last(),
questionnaire,
QuestionnaireResponse()
)
assertThat((result as Type).asStringValue()).isEqualTo("3")
}
@Test
fun `should return null with variables dependent on missing variables for questionnaire root level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "%B + 1"
}
)
}
}
val result =
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.last(),
questionnaire,
QuestionnaireResponse()
)
assertThat(result).isEqualTo(null)
}
@Test
fun `should return not null value with variables dependent on other variables at origin for questionnaire item level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "an-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.TEXT
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "B"
language = "text/fhirpath"
expression = "1"
}
)
}
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "%B + 1"
}
)
}
}
)
}
val result =
ExpressionEvaluator.evaluateQuestionnaireItemVariableExpression(
questionnaire.item[0].variableExpressions.last(),
questionnaire,
QuestionnaireResponse(),
mapOf(),
questionnaire.item[0]
)
assertThat((result as Type).asStringValue()).isEqualTo("2")
}
@Test
fun `should return null with variables dependent on missing variables at origin for questionnaire item level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "an-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.TEXT
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "A"
language = "text/fhirpath"
expression = "%B + 1"
}
)
}
}
)
}
val result =
ExpressionEvaluator.evaluateQuestionnaireItemVariableExpression(
questionnaire.item[0].variableExpressions.last(),
questionnaire,
QuestionnaireResponse(),
mapOf(),
questionnaire.item[0]
)
assertThat(result).isEqualTo(null)
}
@Test
fun `should throw illegal argument exception with missing expression name for questionnaire variables`() {
assertThrows(IllegalArgumentException::class.java) {
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
language = "text/fhirpath"
expression = "%resource.repeat(item).where(linkId='an-item').answer.first().value"
}
)
}
}
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.first(),
questionnaire,
QuestionnaireResponse()
)
}
}
}
@Test
fun `should throw illegal argument exception with missing exception language for questionnaire variables`() {
assertThrows(IllegalArgumentException::class.java) {
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "X"
expression = "1"
}
)
}
}
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.first(),
questionnaire,
QuestionnaireResponse()
)
}
}
}
@Test
fun `should throw illegal argument exception with unsupported expression language for questionnaire variables`() {
assertThrows(IllegalArgumentException::class.java) {
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "X"
expression = "1"
language = "application/x-fhir-query"
}
)
}
}
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.first(),
questionnaire,
QuestionnaireResponse()
)
}
}
}
@Test
fun `should throw null pointer exception with missing expression for questionnaire variables`() {
assertThrows(NullPointerException::class.java) {
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "X"
language = "text/fhirpath"
}
)
}
}
ExpressionEvaluator.evaluateQuestionnaireVariableExpression(
questionnaire.variableExpressions.first(),
questionnaire,
QuestionnaireResponse()
)
}
}
}
@Test
fun `should return not null value with expression dependent on answers of items for questionnaire item level`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-group-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.GROUP
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "M"
language = "text/fhirpath"
expression =
"%resource.repeat(item).where(linkId='an-item').answer.first().value"
}
)
}
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "an-item"
text = "a question"
type = Questionnaire.QuestionnaireItemType.TEXT
}
)
}
)
}
val questionnaireResponse =
QuestionnaireResponse().apply {
id = "a-questionnaire-response"
addItem(
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
linkId = "an-item"
addAnswer(
QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply {
value = IntegerType(2)
}
)
}
)
}
val result =
ExpressionEvaluator.evaluateQuestionnaireItemVariableExpression(
questionnaire.item[0].variableExpressions.last(),
questionnaire,
questionnaireResponse,
mapOf(),
questionnaire.item[0]
)
assertThat((result as Type).asStringValue()).isEqualTo("2")
}
@Test
fun `evaluateCalculatedExpressions should return list of calculated values`() = runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-birthdate"
type = Questionnaire.QuestionnaireItemType.DATE
addExtension().apply {
url = EXTENSION_CALCULATED_EXPRESSION_URL
setValue(
Expression().apply {
this.language = "text/fhirpath"
this.expression =
"%resource.repeat(item).where(linkId='a-age-years' and answer.empty().not()).select(today() - answer.value)"
}
)
}
}
)
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-age-years"
type = Questionnaire.QuestionnaireItemType.QUANTITY
}
)
}
val questionnaireResponse =
QuestionnaireResponse().apply {
addItem(
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
linkId = "a-birthdate"
}
)
addItem(
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
linkId = "a-age-years"
answer =
listOf(
QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply {
this.value = Quantity(1).apply { unit = "year" }
}
)
}
)
}
val result =
evaluateCalculatedExpressions(
questionnaire.item.elementAt(1),
questionnaire,
questionnaireResponse,
emptyMap()
)
assertThat(result.first().second.first().asStringValue())
.isEqualTo(DateType(Date()).apply { add(Calendar.YEAR, -1) }.asStringValue())
}
@Test
fun `evaluateCalculatedExpressions should return list of calculated values with variables`() =
runBlocking {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addExtension().apply {
url = EXTENSION_VARIABLE_URL
setValue(
Expression().apply {
name = "AGE-YEARS"
language = "text/fhirpath"
expression =
"%resource.repeat(item).where(linkId='a-age-years' and answer.empty().not()).select(today() - answer.value)"
}
)
}
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-birthdate"
type = Questionnaire.QuestionnaireItemType.DATE
addExtension().apply {
url = EXTENSION_CALCULATED_EXPRESSION_URL
setValue(
Expression().apply {
this.language = "text/fhirpath"
this.expression = "%AGE-YEARS"
}
)
}
}
)
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-age-years"
type = Questionnaire.QuestionnaireItemType.QUANTITY
}
)
}
val questionnaireResponse =
QuestionnaireResponse().apply {
addItem(
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
linkId = "a-birthdate"
}
)
addItem(
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
linkId = "a-age-years"
answer =
listOf(
QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply {
this.value = Quantity(1).apply { unit = "year" }
}
)
}
)
}
val result =
evaluateCalculatedExpressions(
questionnaire.item.elementAt(1),
questionnaire,
questionnaireResponse,
emptyMap()
)
assertThat(result.first().second.first().asStringValue())
.isEqualTo(DateType(Date()).apply { add(Calendar.YEAR, -1) }.asStringValue())
}
@Test
fun `detectExpressionCyclicDependency() should throw illegal argument exception when item with calculated expression have cyclic dependency`() {
val questionnaire =
Questionnaire().apply {
id = "a-questionnaire"
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-birthdate"
type = Questionnaire.QuestionnaireItemType.DATE
addInitial(
Questionnaire.QuestionnaireItemInitialComponent(
DateType(Date()).apply { add(Calendar.YEAR, -2) }
)
)
addExtension().apply {
url = EXTENSION_CALCULATED_EXPRESSION_URL
setValue(
Expression().apply {
this.language = "text/fhirpath"
this.expression =
"%resource.repeat(item).where(linkId='a-age-years' and answer.empty().not()).select(today() - answer.value)"
}
)
}
}
)
addItem(
Questionnaire.QuestionnaireItemComponent().apply {
linkId = "a-age-years"
type = Questionnaire.QuestionnaireItemType.INTEGER
addExtension().apply {
url = EXTENSION_CALCULATED_EXPRESSION_URL
setValue(
Expression().apply {
this.language = "text/fhirpath"
this.expression =
"today().toString().substring(0, 4).toInteger() - %resource.repeat(item).where(linkId='a-birthdate').answer.value.toString().substring(0, 4).toInteger()"
}
)
}
}
)
}
val exception =
assertThrows(null, IllegalStateException::class.java) {
detectExpressionCyclicDependency(questionnaire.item)
}
assertThat(exception.message)
.isEqualTo("a-birthdate and a-age-years have cyclic dependency in expression based extension")
}
}
| apache-2.0 | 0e8f8957dc2a7aa3384a749d4beeb661 | 31.034431 | 173 | 0.538203 | 5.874005 | false | false | false | false |
dahlstrom-g/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyDataclassCompletionContributor.kt | 5 | 4224 | /*
* 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.codeInsight.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.icons.AllIcons
import com.intellij.openapi.project.DumbAware
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ProcessingContext
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.*
import com.jetbrains.python.extensions.afterDefInMethod
import com.jetbrains.python.extensions.inParameterList
import com.jetbrains.python.psi.PyParameter
import com.jetbrains.python.psi.PyParameterList
import com.jetbrains.python.psi.PySubscriptionExpression
import com.jetbrains.python.psi.PyTargetExpression
import com.jetbrains.python.psi.types.PyClassType
class PyDataclassCompletionContributor : CompletionContributor(), DumbAware {
override fun handleAutoCompletionPossibility(context: AutoCompletionContext): AutoCompletionDecision = autoInsertSingleItem(context)
init {
extend(CompletionType.BASIC, PlatformPatterns.psiElement().afterDefInMethod(), PostInitProvider)
extend(CompletionType.BASIC, PlatformPatterns.psiElement().inParameterList(), AttrsValidatorParameterProvider)
}
private object PostInitProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val cls = parameters.getPyClass() ?: return
val typeEvalContext = parameters.getTypeEvalContext()
val dataclassParameters = parseDataclassParameters(cls, typeEvalContext)
if (dataclassParameters == null || !dataclassParameters.init) return
if (dataclassParameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.STD) {
val postInitParameters = mutableListOf(PyNames.CANONICAL_SELF)
cls.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression && element.annotationValue != null) {
val name = element.name
val annotationValue = element.annotation?.value as? PySubscriptionExpression
if (name != null && annotationValue != null) {
val type = typeEvalContext.getType(element)
if (type is PyClassType && type.classQName == DATACLASSES_INITVAR_TYPE) {
val typeHint = annotationValue.indexExpression.let { if (it == null) "" else ": ${it.text}" }
postInitParameters.add(name + typeHint)
}
}
}
true
}
addMethodToResult(result, cls, typeEvalContext, DUNDER_POST_INIT, postInitParameters.joinToString(prefix = "(", postfix = ")"))
}
else if (dataclassParameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) {
addMethodToResult(result, cls, typeEvalContext, DUNDER_ATTRS_POST_INIT)
}
}
}
private object AttrsValidatorParameterProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val cls = parameters.getPyClass() ?: return
val parameterList = PsiTreeUtil.getParentOfType(parameters.position, PyParameterList::class.java) ?: return
val parameter = PsiTreeUtil.getParentOfType(parameters.position, PyParameter::class.java) ?: return
val index = parameterList.parameters.indexOf(parameter)
if (index != 1 && index != 2) return
val decorators = parameterList.containingFunction?.decoratorList ?: return
if (decorators.decorators.none { it.qualifiedName?.endsWith("validator") == true }) return
val typeEvalContext = parameters.getTypeEvalContext()
if (parseDataclassParameters(cls, typeEvalContext)?.type?.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) {
result.addElement(LookupElementBuilder.create(if (index == 1) "attribute" else "value").withIcon(AllIcons.Nodes.Parameter))
}
}
}
}
| apache-2.0 | ccec473e1b5f0a0d1eab63506800a74c | 45.417582 | 140 | 0.748106 | 5.214815 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/projectPropertyBased/InvokeFindUsages.kt | 4 | 6375 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.projectPropertyBased
import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction
import com.intellij.find.FindBundle
import com.intellij.find.FindManager
import com.intellij.find.findUsages.FindUsagesHandlerFactory
import com.intellij.find.findUsages.FindUsagesManager
import com.intellij.find.impl.FindManagerImpl
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task.Backgroundable
import com.intellij.openapi.progress.impl.ProgressManagerImpl
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.testFramework.propertyBased.ActionOnFile
import com.intellij.testFramework.propertyBased.MadTestingUtil
import com.intellij.usages.Usage
import com.intellij.util.Processors
import org.jetbrains.jetCheck.Generator
import org.jetbrains.jetCheck.ImperativeCommand
import org.jetbrains.kotlin.idea.findUsages.KotlinClassFindUsagesOptions
import org.jetbrains.kotlin.idea.findUsages.KotlinFunctionFindUsagesOptions
import org.jetbrains.kotlin.idea.findUsages.KotlinPropertyFindUsagesOptions
import org.jetbrains.kotlin.idea.util.isUnderKotlinSourceRootTypes
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.utils.addToStdlib.cast
import java.util.*
class InvokeFindUsages(file: PsiFile): ActionOnFile(file) {
override fun performCommand(env: ImperativeCommand.Environment) {
// ignore test data, and other resources
file.takeIf { it.isUnderKotlinSourceRootTypes() } ?: return
val project = project
val editor =
FileEditorManager.getInstance(project).openTextEditor(OpenFileDescriptor(project, virtualFile, 0), true)
?: error("Unable to open file $virtualFile")
// todo: it's suboptimal search
val (offset: Int, element: PsiElement) = run {
val attempts = env.generateValue(Generator.integers(10, 30), null)
for (attempt in 0 until attempts) {
val offset = generateDocOffset(env, null)
val element = when (GotoDeclarationAction.findElementToShowUsagesOf(editor, offset)) {
null -> GotoDeclarationAction.findTargetElement(project, editor, offset)
else -> GotoDeclarationAction.findElementToShowUsagesOf(editor, offset)
} ?: continue
if (element is KtElement) {
return@run (offset to element)
}
}
env.logMessage("Unable to look up element for find usage in $attempts attempts")
return
}
env.logMessage("Go to ${MadTestingUtil.getPositionDescription(offset, document)}")
env.logMessage("Command find usages is called on element '$element' of ${element.javaClass.name}")
val findUsagesManager = FindManager.getInstance(project).cast<FindManagerImpl>().findUsagesManager
val handler = findUsagesManager.getFindUsagesHandler(
element, FindUsagesHandlerFactory.OperationMode.USAGES_WITH_DEFAULT_OPTIONS
) ?: run {
env.logMessage("No find usage handler found for the element: '${element.text}'")
return
}
val findUsagesOptions = when (element) {
is KtFunction -> KotlinFunctionFindUsagesOptions(project).apply {
// TODO: randomize isOverridingMethods etc
isOverridingMethods = false
isImplementingMethods = false
isCheckDeepInheritance = true
isIncludeInherited = false
isIncludeOverloadUsages = false
isImplicitToString = true
isSearchForBaseMethod = true
isSkipImportStatements = false
isSearchForTextOccurrences = false
isUsages = true
searchExpected = true
}
is KtClassOrObject -> KotlinClassFindUsagesOptions(project).apply {
searchExpected = true
searchConstructorUsages = true
isMethodsUsages = false
isFieldsUsages = false
isDerivedClasses = false
isImplementingClasses = false
isDerivedInterfaces = false
isCheckDeepInheritance = true
isIncludeInherited = false
isSkipImportStatements = false
isSearchForTextOccurrences = true
isUsages = true
}
else -> KotlinPropertyFindUsagesOptions(project).apply {
searchExpected = true
isReadWriteAccess = true
searchOverrides = false
isReadAccess = true
isWriteAccess = true
isSearchForAccessors = false
isSearchInOverridingMethods = false
isSearchForBaseAccessors = false
isSkipImportStatements = false
isSearchForTextOccurrences = false
isUsages = true
}
}
val usages = mutableListOf<Usage>()
val processor = Processors.cancelableCollectProcessor(Collections.synchronizedList(usages))
val usageSearcher =
FindUsagesManager.createUsageSearcher(handler, handler.primaryElements, handler.secondaryElements, findUsagesOptions)
val task = object : Backgroundable(project, FindBundle.message("progress.title.finding.usages")) {
override fun run(indicator: ProgressIndicator) {
usageSearcher.generate(processor)
}
}
ProgressManager.getInstance().cast<ProgressManagerImpl>()
.runProcessWithProgressInCurrentThread(task, EmptyProgressIndicator(), ModalityState.defaultModalityState())
env.logMessage("Found ${usages.size} usages for element $element")
}
} | apache-2.0 | 0739cca0c0c3d94b5f16f669be680515 | 46.58209 | 129 | 0.685176 | 5.722621 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/lambdaExpression/identity.kt | 12 | 224 | val foo: (Int) -> Int = <warning descr="SSR">{ it -> it }</warning>
val foo2: (Int) -> Int = <warning descr="SSR">{ 1 }</warning>
var bar1: (Int) -> Unit = {}
val bar2: () -> Int = { 1 }
val bar3: (Int) -> Int = { it -> 1 }
| apache-2.0 | 5682520cde58a82b43b8691aa0cebfe1 | 43.8 | 67 | 0.513393 | 2.698795 | false | false | false | false |
cdietze/klay | klay-jvm/src/main/kotlin/klay/jvm/JavaInput.kt | 1 | 4442 | package klay.jvm
import euklid.f.Point
import klay.core.*
import java.util.concurrent.ConcurrentLinkedDeque
open class JavaInput(plat: JavaPlatform) : Input(plat) {
@Suppress("CanBePrimaryConstructorProperty")
override val plat: JavaPlatform = plat
// used for injecting keyboard evnets
private val kevQueue = ConcurrentLinkedDeque<Keyboard.Event>()
// these are used for touch emulation
private var mouseDown: Boolean = false
private var pivot: Point? = null
private var x: Float = 0.toFloat()
private var y: Float = 0.toFloat()
private var currentId: Int = 0
init {
// if touch emulation is configured, wire it up
if (plat.config.emulateTouch) emulateTouch()
}
/** Posts a key event received from elsewhere (i.e. a native UI component). This is useful for
* applications that are using GL in Canvas mode and sharing keyboard focus with other (non-GL)
* components. The event will be queued and dispatched on the next frame, after GL keyboard
* events.
* @param time the time (in millis since epoch) at which the event was generated, or 0 if N/A.
* *
* @param key the key that was pressed or released, or null for a char typed event
* *
* @param pressed whether the key was pressed or released, ignored if key is null
* *
* @param typedCh the character that was typed, ignored if key is not null
* *
* @param modFlags modifier key state flags (generated by [.modifierFlags])
*/
fun postKey(time: Long, key: Key?, pressed: Boolean, typedCh: Char, modFlags: Int) {
val event = if (key == null)
Keyboard.TypedEvent(0, time.toDouble(), typedCh)
else
Keyboard.KeyEvent(0, time.toDouble(), key, pressed)
event.setFlag(modFlags)
kevQueue.add(event)
}
protected fun emulateTouch() {
val pivotKey = plat.config.pivotKey
keyboardEvents.connect { event: Keyboard.Event ->
if (event is Keyboard.KeyEvent) {
val kevent = event
if (kevent.key === pivotKey && kevent.down) {
pivot = Point(x, y)
}
}
}
mouseEvents.connect { event: Mouse.Event ->
if (event is Mouse.ButtonEvent) {
val bevent = event
if (bevent.button === Mouse.ButtonEvent.Id.LEFT) {
mouseDown = bevent.down
if (mouseDown) {
currentId += 2 // skip an id in case of pivot
dispatchTouch(event, Touch.Event.Kind.START)
} else {
pivot = null
dispatchTouch(event, Touch.Event.Kind.END)
}
}
} else if (event is Mouse.MotionEvent) {
if (mouseDown) dispatchTouch(event, Touch.Event.Kind.MOVE)
// keep track of the current mouse position for pivot
x = event.x
y = event.y
}
}
// TODO: it's pesky that both mouse and touch events are dispatched when touch is emulated, it
// would be nice to throw away the mouse events and only have touch, but we rely on something
// generating the mouse events so we can't throw them away just yet... plus it could be useful
// to keep wheel events... blah
}
override val hasMouse = true
override val hasHardwareKeyboard = true
override val hasTouch: Boolean
get() = plat.config.emulateTouch
internal open fun update() {
// dispatch any queued keyboard events
while (true) {
val kev: Keyboard.Event = kevQueue.poll() ?: break
plat.dispatchEvent(keyboardEvents, kev)
}
}
private fun dispatchTouch(event: Mouse.Event, kind: Touch.Event.Kind) {
val ex = event.x
val ey = event.y
val main = toTouch(event.time, ex, ey, kind, 0)
val evs: Array<Touch.Event> = if (pivot == null)
arrayOf(main)
else
arrayOf(main, toTouch(event.time, 2 * pivot!!.x - ex, 2 * pivot!!.y - ey, kind, 1))
plat.dispatchEvent(touchEvents, evs)
}
private fun toTouch(time: Double, x: Float, y: Float, kind: Touch.Event.Kind, idoff: Int): Touch.Event {
return Touch.Event(0, time, x, y, kind, currentId + idoff)
}
}
| apache-2.0 | 7b80294a460d6306d05aa3944ca2187e | 36.644068 | 108 | 0.592076 | 4.367748 | false | false | false | false |
github/codeql | java/kotlin-extractor/src/main/kotlin/TrapWriter.kt | 1 | 15540 | package com.github.codeql
import com.github.codeql.KotlinUsesExtractor.LocallyVisibleFunctionLabels
import java.io.BufferedWriter
import java.io.File
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.path
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.IrVariable
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.util.SYNTHETIC_OFFSET
import com.semmle.extractor.java.PopulateFile
import com.semmle.util.unicode.UTF8Util
import org.jetbrains.kotlin.ir.expressions.IrCall
/**
* Each `.trap` file has a `TrapLabelManager` while we are writing it.
* It provides fresh TRAP label names, and maintains a mapping from keys
* (`@"..."`) to labels.
*/
class TrapLabelManager {
/** The next integer to use as a label name. */
private var nextInt: Int = 100
/** Returns a fresh label. */
fun <T: AnyDbType> getFreshLabel(): Label<T> {
return IntLabel(nextInt++)
}
/**
* A mapping from a key (`@"..."`) to the label defined to be that
* key, if any.
*/
val labelMapping: MutableMap<String, Label<*>> = mutableMapOf<String, Label<*>>()
val anonymousTypeMapping: MutableMap<IrClass, TypeResults> = mutableMapOf()
val locallyVisibleFunctionLabelMapping: MutableMap<IrFunction, LocallyVisibleFunctionLabels> = mutableMapOf()
/**
* The set of labels of generic specialisations that we have extracted
* in this TRAP file.
* We can't easily avoid duplication between TRAP files, as the labels
* contain references to other labels, so we just accept this
* duplication.
*/
val genericSpecialisationsExtracted = HashSet<String>()
}
/**
* A `TrapWriter` is used to write TRAP to a particular TRAP file.
* There may be multiple `TrapWriter`s for the same file, as different
* instances will have different additional state, but they must all
* share the same `TrapLabelManager` and `BufferedWriter`.
*/
// TODO lm was `protected` before anonymousTypeMapping and locallyVisibleFunctionLabelMapping moved into it. Should we re-protect it and provide accessors?
open class TrapWriter (protected val loggerBase: LoggerBase, val lm: TrapLabelManager, private val bw: BufferedWriter, val diagnosticTrapWriter: TrapWriter?) {
/**
* Returns the label that is defined to be the given key, if such
* a label exists, and `null` otherwise. Most users will want to use
* `getLabelFor` instead, which allows non-existent labels to be
* initialised.
*/
fun <T: AnyDbType> getExistingLabelFor(key: String): Label<T>? {
return lm.labelMapping.get(key)?.cast<T>()
}
/**
* Returns the label for the given key, if one exists.
* Otherwise, a fresh label is bound to that key, `initialise`
* is run on it, and it is returned.
*/
@JvmOverloads // Needed so Java can call a method with an optional argument
fun <T: AnyDbType> getLabelFor(key: String, initialise: (Label<T>) -> Unit = {}): Label<T> {
val maybeLabel: Label<T>? = getExistingLabelFor(key)
if(maybeLabel == null) {
val label: Label<T> = lm.getFreshLabel()
lm.labelMapping.put(key, label)
writeTrap("$label = $key\n")
initialise(label)
return label
} else {
return maybeLabel
}
}
/**
* Returns a label for a fresh ID (i.e. a new label bound to `*`).
*/
fun <T: AnyDbType> getFreshIdLabel(): Label<T> {
val label: Label<T> = lm.getFreshLabel()
writeTrap("$label = *\n")
return label
}
/**
* It is not easy to assign keys to local variables, so they get
* given `*` IDs. However, the same variable may be referred to
* from distant places in the IR, so we need a way to find out
* which label is used for a given local variable. This information
* is stored in this mapping.
*/
private val variableLabelMapping: MutableMap<IrVariable, Label<out DbLocalvar>> = mutableMapOf<IrVariable, Label<out DbLocalvar>>()
/**
* This returns the label used for a local variable, creating one
* if none currently exists.
*/
fun <T> getVariableLabelFor(v: IrVariable): Label<out DbLocalvar> {
val maybeLabel = variableLabelMapping.get(v)
if(maybeLabel == null) {
val label = getFreshIdLabel<DbLocalvar>()
variableLabelMapping.put(v, label)
return label
} else {
return maybeLabel
}
}
fun getExistingVariableLabelFor(v: IrVariable): Label<out DbLocalvar>? {
return variableLabelMapping.get(v)
}
/**
* This returns a label for the location described by its arguments.
* Typically users will not want to call this directly, but instead
* use `unknownLocation`, or overloads of this defined by subclasses.
*/
fun getLocation(fileId: Label<DbFile>, startLine: Int, startColumn: Int, endLine: Int, endColumn: Int): Label<DbLocation> {
return getLabelFor("@\"loc,{$fileId},$startLine,$startColumn,$endLine,$endColumn\"") {
writeLocations_default(it, fileId, startLine, startColumn, endLine, endColumn)
}
}
/**
* The label for the 'unknown' file ID.
* Users will want to use `unknownLocation` instead.
* This is lazy, as we don't want to define it in a TRAP file unless
* the TRAP file actually contains something in the 'unknown' file.
*/
protected val unknownFileId: Label<DbFile> by lazy {
val unknownFileLabel = "@\";sourcefile\""
getLabelFor(unknownFileLabel, {
writeFiles(it, "")
})
}
/**
* The label for the 'unknown' location.
* This is lazy, as we don't want to define it in a TRAP file unless
* the TRAP file actually contains something with an 'unknown'
* location.
*/
val unknownLocation: Label<DbLocation> by lazy {
getWholeFileLocation(unknownFileId)
}
/**
* Returns the label for the file `filePath`.
* If `populateFileTables` is true, then this also adds rows to the
* `files` and `folders` tables for this file.
*/
fun mkFileId(filePath: String, populateFileTables: Boolean): Label<DbFile> {
// If a file is in a jar, then the Kotlin compiler gives
// `<jar file>!/<path within jar>` as its path. We need to split
// it as appropriate, to make the right file ID.
val populateFile = PopulateFile(this)
val splitFilePath = filePath.split("!/")
if(splitFilePath.size == 1) {
return populateFile.getFileLabel(File(filePath), populateFileTables)
} else {
return populateFile.getFileInJarLabel(File(splitFilePath.get(0)), splitFilePath.get(1), populateFileTables)
}
}
/**
* If you have an ID for a file, then this gets a label for the
* location representing the whole of that file.
*/
fun getWholeFileLocation(fileId: Label<DbFile>): Label<DbLocation> {
return getLocation(fileId, 0, 0, 0, 0)
}
/**
* Write a raw string into the TRAP file. Users should call one of
* the wrapper functions instead.
*/
fun writeTrap(trap: String) {
bw.write(trap)
}
/**
* Write a comment into the TRAP file.
*/
fun writeComment(comment: String) {
writeTrap("// ${comment.replace("\n", "\n// ")}\n")
}
/**
* Flush the TRAP file.
*/
fun flush() {
bw.flush()
}
/**
* Escape a string so that it can be used in a TRAP string literal,
* i.e. with `"` escaped as `""`.
*/
fun escapeTrapString(str: String) = str.replace("\"", "\"\"")
/**
* TRAP string literals are limited to 1 megabyte.
*/
private val MAX_STRLEN = 1.shl(20)
/**
* Truncate a string, if necessary, so that it can be used as a TRAP
* string literal. TRAP string literals are limited to 1 megabyte.
*/
fun truncateString(str: String): String {
val len = str.length
val newLen = UTF8Util.encodablePrefixLength(str, MAX_STRLEN)
if (newLen < len) {
loggerBase.warn(diagnosticTrapWriter ?: this,
"Truncated string of length $len",
"Truncated string of length $len, starting '${str.take(100)}', ending '${str.takeLast(100)}'")
return str.take(newLen)
} else {
return str
}
}
/**
* Gets a FileTrapWriter like this one (using the same label manager,
* writer etc), but using the given `filePath` for locations.
*/
fun makeFileTrapWriter(filePath: String, populateFileTables: Boolean) =
FileTrapWriter(loggerBase, lm, bw, diagnosticTrapWriter, filePath, populateFileTables)
/**
* Gets a FileTrapWriter like this one (using the same label manager,
* writer etc), but using the given `IrFile` for locations.
*/
fun makeSourceFileTrapWriter(file: IrFile, populateFileTables: Boolean) =
SourceFileTrapWriter(loggerBase, lm, bw, diagnosticTrapWriter, file, populateFileTables)
}
/**
* A `FileTrapWriter` is used when we know which file we are extracting
* entities from, so we can at least give the right file as a location.
*
* An ID for the file will be created, and if `populateFileTables` is
* true then we will also add rows to the `files` and `folders` tables
* for it.
*/
open class FileTrapWriter (
loggerBase: LoggerBase,
lm: TrapLabelManager,
bw: BufferedWriter,
diagnosticTrapWriter: TrapWriter?,
val filePath: String,
populateFileTables: Boolean
): TrapWriter (loggerBase, lm, bw, diagnosticTrapWriter) {
/**
* The ID for the file that we are extracting from.
*/
val fileId = mkFileId(filePath, populateFileTables)
private fun offsetMinOf(default: Int, vararg options: Int?): Int {
if (default == UNDEFINED_OFFSET || default == SYNTHETIC_OFFSET) {
return default
}
var currentMin = default
for (option in options) {
if (option != null && option != UNDEFINED_OFFSET && option != SYNTHETIC_OFFSET && option < currentMin) {
currentMin = option
}
}
return currentMin
}
private fun getStartOffset(e: IrElement): Int {
return when (e) {
is IrCall -> {
// Calls have incorrect startOffset, so we adjust them:
val dr = e.dispatchReceiver?.let { getStartOffset(it) }
val er = e.extensionReceiver?.let { getStartOffset(it) }
offsetMinOf(e.startOffset, dr, er)
}
else -> e.startOffset
}
}
private fun getEndOffset(e: IrElement): Int {
return e.endOffset
}
/**
* Gets a label for the location of `e`.
*/
fun getLocation(e: IrElement): Label<DbLocation> {
return getLocation(getStartOffset(e), getEndOffset(e))
}
/**
* Gets a label for the location corresponding to `startOffset` and
* `endOffset` within this file.
*/
open fun getLocation(startOffset: Int, endOffset: Int): Label<DbLocation> {
// We don't have a FileEntry to look up the offsets in, so all
// we can do is return a whole-file location.
return getWholeFileLocation()
}
/**
* Gets the location of `e` as a human-readable string. Only used in
* log messages and exception messages.
*/
open fun getLocationString(e: IrElement): String {
// We don't have a FileEntry to look up the offsets in, so all
// we can do is return a whole-file location. We omit the
// `:0:0:0:0` so that it is easy to distinguish from a location
// where we have actually determined the start/end lines/columns
// to be 0.
return "file://$filePath"
}
/**
* Gets a label for the location representing the whole of this file.
*/
fun getWholeFileLocation(): Label<DbLocation> {
return getWholeFileLocation(fileId)
}
}
/**
* A `SourceFileTrapWriter` is used when not only do we know which file
* we are extracting entities from, but we also have an `IrFileEntry`
* (from an `IrFile`) which allows us to map byte offsets to line
* and column numbers.
*
* An ID for the file will be created, and if `populateFileTables` is
* true then we will also add rows to the `files` and `folders` tables
* for it.
*/
class SourceFileTrapWriter (
loggerBase: LoggerBase,
lm: TrapLabelManager,
bw: BufferedWriter,
diagnosticTrapWriter: TrapWriter?,
val irFile: IrFile,
populateFileTables: Boolean) :
FileTrapWriter(loggerBase, lm, bw, diagnosticTrapWriter, irFile.path, populateFileTables) {
/**
* The file entry for the file that we are extracting from.
* Used to map offsets to line/column numbers.
*/
private val fileEntry = irFile.fileEntry
override fun getLocation(startOffset: Int, endOffset: Int): Label<DbLocation> {
if (startOffset == UNDEFINED_OFFSET || endOffset == UNDEFINED_OFFSET) {
if (startOffset != endOffset) {
loggerBase.warn(this, "Location with inconsistent offsets (start $startOffset, end $endOffset)", null)
}
return getWholeFileLocation()
}
if (startOffset == SYNTHETIC_OFFSET || endOffset == SYNTHETIC_OFFSET) {
if (startOffset != endOffset) {
loggerBase.warn(this, "Location with inconsistent offsets (start $startOffset, end $endOffset)", null)
}
return getWholeFileLocation()
}
// If this is the location for a compiler-generated element, then it will
// be a zero-width location. QL doesn't support these, so we translate it
// into a one-width location.
val endColumnOffset = if (startOffset == endOffset) 1 else 0
return getLocation(
fileId,
fileEntry.getLineNumber(startOffset) + 1,
fileEntry.getColumnNumber(startOffset) + 1,
fileEntry.getLineNumber(endOffset) + 1,
fileEntry.getColumnNumber(endOffset) + endColumnOffset)
}
override fun getLocationString(e: IrElement): String {
if (e.startOffset == UNDEFINED_OFFSET || e.endOffset == UNDEFINED_OFFSET) {
if (e.startOffset != e.endOffset) {
loggerBase.warn(this, "Location with inconsistent offsets (start ${e.startOffset}, end ${e.endOffset})", null)
}
return "<unknown location while processing $filePath>"
}
if (e.startOffset == SYNTHETIC_OFFSET || e.endOffset == SYNTHETIC_OFFSET) {
if (e.startOffset != e.endOffset) {
loggerBase.warn(this, "Location with inconsistent offsets (start ${e.startOffset}, end ${e.endOffset})", null)
}
return "<synthetic location while processing $filePath>"
}
val startLine = fileEntry.getLineNumber(e.startOffset) + 1
val startColumn = fileEntry.getColumnNumber(e.startOffset) + 1
val endLine = fileEntry.getLineNumber(e.endOffset) + 1
val endColumn = fileEntry.getColumnNumber(e.endOffset)
return "file://$filePath:$startLine:$startColumn:$endLine:$endColumn"
}
}
| mit | 2f67b3b1b78510c166f991fcd5156a00 | 36.810219 | 159 | 0.641699 | 4.443809 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/mfm/MisskeySyntaxHighlighter.kt | 1 | 12180 | package jp.juggler.subwaytooter.mfm
import android.graphics.Color
import android.graphics.Typeface
import android.text.style.ForegroundColorSpan
import android.util.SparseBooleanArray
import jp.juggler.util.asciiPattern
import jp.juggler.util.firstNonNull
import jp.juggler.util.fontSpan
import jp.juggler.util.groupEx
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern
// ```code``` マークダウン内部ではプログラムっぽい何かの文法強調表示が行われる
object MisskeySyntaxHighlighter {
private val keywords = HashSet<String>().apply {
val _keywords = arrayOf(
"true",
"false",
"null",
"nil",
"undefined",
"void",
"var",
"const",
"let",
"mut",
"dim",
"if",
"then",
"else",
"switch",
"match",
"case",
"default",
"for",
"each",
"in",
"while",
"loop",
"continue",
"break",
"do",
"goto",
"next",
"end",
"sub",
"throw",
"try",
"catch",
"finally",
"enum",
"delegate",
"function",
"func",
"fun",
"fn",
"return",
"yield",
"async",
"await",
"require",
"include",
"import",
"imports",
"export",
"exports",
"from",
"as",
"using",
"use",
"internal",
"module",
"namespace",
"where",
"select",
"struct",
"union",
"new",
"delete",
"this",
"super",
"base",
"class",
"interface",
"abstract",
"static",
"public",
"private",
"protected",
"virtual",
"partial",
"override",
"extends",
"implements",
"constructor"
)
// lower
addAll(_keywords)
// UPPER
addAll(_keywords.map { it.uppercase() })
// Snake
addAll(_keywords.map { k -> k[0].uppercase() + k.substring(1) })
add("NaN")
// 識別子に対して既存の名前と一致するか調べるようになったので、もはやソートの必要はない
}
private val symbolMap = SparseBooleanArray().apply {
"=+-*/%~^&|><!?".forEach { put(it.code, true) }
}
// 文字列リテラルの開始文字のマップ
private val stringStart = SparseBooleanArray().apply {
"\"'`".forEach { put(it.code, true) }
}
private class Token(
val length: Int,
val color: Int = 0,
val italic: Boolean = false,
val comment: Boolean = false,
)
private class Env(
val source: String,
val start: Int,
val end: Int,
) {
// 出力先2
val spanList = SpanList()
fun push(start: Int, token: Token) {
val end = start + token.length
if (token.comment) {
spanList.addLast(start, end, ForegroundColorSpan(Color.BLACK or 0x808000))
} else {
var c = token.color
if (c != 0) {
if (c < 0x1000000) {
c = c or Color.BLACK
}
spanList.addLast(start, end, ForegroundColorSpan(c))
}
if (token.italic) {
spanList.addLast(
start,
end,
fontSpan(Typeface.defaultFromStyle(Typeface.ITALIC))
)
}
}
}
// スキャン位置
var pos: Int = start
fun remainMatcher(pattern: Pattern): Matcher =
MatcherCache.matcher(pattern, source, pos, end)
fun parse(): SpanList {
var i = start
var lastEnd = start
fun closeTextToken(textEnd: Int) {
val length = textEnd - lastEnd
if (length > 0) {
push(lastEnd, Token(length = length))
lastEnd = textEnd
}
}
while (i < end) {
pos = i
val token = elements.firstNonNull {
val t = this.it()
when {
t == null -> null // not match
i + t.length > end -> null // overrun detected
else -> t
}
}
if (token == null) {
++i
continue
}
closeTextToken(i)
push(i, token)
i += token.length
lastEnd = i
}
closeTextToken(end)
return spanList
}
}
private val reLineComment = """\A//.*"""
.asciiPattern()
private val reBlockComment = """\A/\*.*?\*/"""
.asciiPattern(Pattern.DOTALL)
private val reNumber = """\A[\-+]?[\d.]+"""
.asciiPattern()
private val reLabel = """\A@([A-Z_-][A-Z0-9_-]*)"""
.asciiPattern(Pattern.CASE_INSENSITIVE)
private val reKeyword = """\A([A-Z_-][A-Z0-9_-]*)([ \t]*\()?"""
.asciiPattern(Pattern.CASE_INSENSITIVE)
private val reContainsAlpha = """[A-Za-z_]"""
.asciiPattern()
private const val charH80 = 0x80.toChar()
private val elements = arrayOf<Env.() -> Token?>(
// マルチバイト文字をまとめて読み飛ばす
{
var s = pos
while (s < end && source[s] >= charH80) {
++s
}
when {
s > pos -> Token(length = s - pos)
else -> null
}
},
// 空白と改行をまとめて読み飛ばす
{
var s = pos
while (s < end && source[s] <= ' ') {
++s
}
when {
s > pos -> Token(length = s - pos)
else -> null
}
},
// comment
{
val match = remainMatcher(reLineComment)
when {
!match.find() -> null
else -> Token(length = match.end() - match.start(), comment = true)
}
},
// block comment
{
val match = remainMatcher(reBlockComment)
when {
!match.find() -> null
else -> Token(length = match.end() - match.start(), comment = true)
}
},
// string
{
val beginChar = source[pos]
if (!stringStart[beginChar.code]) return@arrayOf null
var i = pos + 1
while (i < end) {
val char = source[i++]
if (char == beginChar) {
break // end
} else if (char == '\n' || i >= end) {
i = 0 // not string literal
break
} else if (char == '\\' && i < end) {
++i // \" では閉じないようにする
}
}
when {
i <= pos -> null
else -> Token(length = i - pos, color = 0xe96900)
}
},
// regexp
{
if (source[pos] != '/') return@arrayOf null
val regexp = StringBuilder()
var i = pos + 1
while (i < end) {
val char = source[i++]
if (char == '/') {
break
} else if (char == '\n' || i >= end) {
i = 0 // not closed
break
} else {
regexp.append(char)
if (char == '\\' && i < end) {
regexp.append(source[i++])
}
}
}
when {
i == 0 -> null
regexp.isEmpty() -> null
regexp.first() == ' ' && regexp.last() == ' ' -> null
else -> Token(length = regexp.length + 2, color = 0xe9003f)
}
},
// label
{
// 直前に識別子があればNG
val prev = if (pos <= 0) null else source[pos - 1]
if (prev?.isLetterOrDigit() == true) return@arrayOf null
val match = remainMatcher(reLabel)
if (!match.find()) return@arrayOf null
val matchEnd = match.end()
when {
// @user@host のように直後に@が続くのはNG
matchEnd < end && source[matchEnd] == '@' -> null
else -> Token(length = match.end() - pos, color = 0xe9003f)
}
},
// number
{
val prev = if (pos <= 0) null else source[pos - 1]
if (prev?.isLetterOrDigit() == true) return@arrayOf null
val match = remainMatcher(reNumber)
when {
!match.find() -> null
else -> Token(length = match.end() - pos, color = 0xae81ff)
}
},
// method, property, keyword
{
// 直前の文字が識別子に使えるなら識別子の開始とはみなさない
val prev = if (pos <= 0) null else source[pos - 1]
if (prev?.isLetterOrDigit() == true || prev == '_') return@arrayOf null
val match = remainMatcher(reKeyword)
if (!match.find()) return@arrayOf null
val kw = match.groupEx(1)!!
val bracket = match.groupEx(2) // may null
when {
// 英数字や_を含まないキーワードは無視する
// -moz-foo- や __ はキーワードだが、 - や -- はキーワードではない
!reContainsAlpha.matcher(kw).find() -> null
// メソッド呼び出しは対象が変数かプロパティかに関わらずメソッドの色になる
bracket?.isNotEmpty() == true ->
Token(length = kw.length, color = 0x8964c1, italic = true)
// 変数や定数ではなくプロパティならプロパティの色になる
prev == '.' -> Token(length = kw.length, color = 0xa71d5d)
// 予約語ではない
// 強調表示しないが、識別子単位で読み飛ばす
!keywords.contains(kw) -> Token(length = kw.length)
else -> when (kw) {
// 定数
"true", "false", "null", "nil", "undefined", "NaN" ->
Token(length = kw.length, color = 0xae81ff)
// その他の予約語
else -> Token(length = kw.length, color = 0x2973b7)
}
}
},
// symbol
{
val c = source[pos]
when {
symbolMap.get(c.code, false) ->
Token(length = 1, color = 0x42b983)
c == '-' ->
Token(length = 1, color = 0x42b983)
else -> null
}
}
)
fun parse(source: String) = Env(source, 0, source.length).parse()
}
| apache-2.0 | 4a39926e4d229255b25b92db9f0a2622 | 26.656716 | 90 | 0.389583 | 4.5 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/sns/src/main/kotlin/com/kotlin/sns/PublishTextSMS.kt | 1 | 1848 | // snippet-sourcedescription:[PublishTextSMS.kt demonstrates how to send an Amazon Simple Notification Service (Amazon SNS) text message.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-keyword:[Amazon Simple Notification Service]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.sns
// snippet-start:[sns.kotlin.PublishTextSMS.import]
import aws.sdk.kotlin.services.sns.SnsClient
import aws.sdk.kotlin.services.sns.model.PublishRequest
import kotlin.system.exitProcess
// snippet-end:[sns.kotlin.PublishTextSMS.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:
<message> <phoneNumber>
Where:
message - The message text to send.
phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).
"""
if (args.size != 2) {
println(usage)
exitProcess(0)
}
val message = args[0]
val phoneNumber = args[1]
pubTextSMS(message, phoneNumber)
}
// snippet-start:[sns.kotlin.PublishTextSMS.main]
suspend fun pubTextSMS(messageVal: String?, phoneNumberVal: String?) {
val request = PublishRequest {
message = messageVal
phoneNumber = phoneNumberVal
}
SnsClient { region = "us-east-1" }.use { snsClient ->
val result = snsClient.publish(request)
println("${result.messageId} message sent.")
}
}
// snippet-end:[sns.kotlin.PublishTextSMS.main]
| apache-2.0 | c5d934bad36d74e9e686ab7a87e195e5 | 28.8 | 138 | 0.673701 | 4.061538 | false | false | false | false |
github/codeql | java/kotlin-extractor/src/main/kotlin/KotlinExtractorExtension.kt | 1 | 20598 | package com.github.codeql
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.config.KotlinCompilerVersion
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.IrElement
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.lang.management.*
import java.nio.file.Files
import java.nio.file.Paths
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import com.semmle.util.files.FileUtil
import kotlin.system.exitProcess
/*
* KotlinExtractorExtension is the main entry point of the CodeQL Kotlin
* extractor. When the jar is used as a kotlinc plugin, kotlinc will
* call the `generate` method.
*/
class KotlinExtractorExtension(
// The filepath for the invocation TRAP file.
// This TRAP file is for this invocation of the extractor as a
// whole, not tied to a particular source file. It contains
// information about which files this invocation compiled, and
// any warnings or errors encountered during the invocation.
private val invocationTrapFile: String,
// By default, if a TRAP file we want to generate for a source
// file already exists, then we will do nothing. If this is set,
// then we will instead generate the TRAP file, and give a
// warning if we would generate different TRAP to that which
// already exists.
private val checkTrapIdentical: Boolean,
// If non-null, then this is the number of milliseconds since
// midnight, January 1, 1970 UTC (as returned by Java's
// `System.currentTimeMillis()`. If this is given, then it is used
// to record the time taken to compile the source code, which is
// presumed to be the difference between this time and the time
// that this plugin is invoked.
private val compilationStartTime: Long?,
// Under normal conditions, the extractor runs during a build of
// the project, and kotlinc continues after the plugin has finished.
// If the plugin is being used independently of a build, then this
// can be set to true to make the plugin terminate the kotlinc
// invocation when it has finished. This means that kotlinc will not
// write any `.class` files etc.
private val exitAfterExtraction: Boolean)
: IrGenerationExtension {
// This is the main entry point to the extractor.
// It will be called by kotlinc with the IR for the files being
// compiled in `moduleFragment`, and `pluginContext` providing
// various utility functions.
override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
try {
runExtractor(moduleFragment, pluginContext)
// We catch Throwable rather than Exception, as we want to
// continue trying to extract everything else even if we get a
// stack overflow or an assertion failure in one file.
} catch(e: Throwable) {
// If we get an exception at the top level, then something's
// gone very wrong. Don't try to be too fancy, but try to
// log a simple message.
val msg = "[ERROR] CodeQL Kotlin extractor: Top-level exception."
// First, if we can find our log directory, then let's try
// making a log file there:
val extractorLogDir = System.getenv("CODEQL_EXTRACTOR_JAVA_LOG_DIR")
if (extractorLogDir != null && extractorLogDir != "") {
// We use a slightly different filename pattern compared
// to normal logs. Just the existence of a `-top` log is
// a sign that something's gone very wrong.
val logFile = File.createTempFile("kotlin-extractor-top.", ".log", File(extractorLogDir))
logFile.writeText(msg)
// Now we've got that out, let's see if we can append a stack trace too
logFile.appendText(e.stackTraceToString())
} else {
// We don't have much choice here except to print to
// stderr and hope for the best.
System.err.println(msg)
e.printStackTrace(System.err)
}
}
if (exitAfterExtraction) {
exitProcess(0)
}
}
private fun runExtractor(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
val startTimeMs = System.currentTimeMillis()
// This default should be kept in sync with com.semmle.extractor.java.interceptors.KotlinInterceptor.initializeExtractionContext
val trapDir = File(System.getenv("CODEQL_EXTRACTOR_JAVA_TRAP_DIR").takeUnless { it.isNullOrEmpty() } ?: "kotlin-extractor/trap")
val compression_env_var = "CODEQL_EXTRACTOR_JAVA_OPTION_TRAP_COMPRESSION"
val compression_option = System.getenv(compression_env_var)
val defaultCompression = Compression.GZIP
val (compression, compressionWarning) =
if (compression_option == null) {
Pair(defaultCompression, null)
} else {
try {
@OptIn(kotlin.ExperimentalStdlibApi::class) // Annotation required by kotlin versions < 1.5
val requested_compression = Compression.valueOf(compression_option.uppercase())
if (requested_compression == Compression.BROTLI) {
Pair(Compression.GZIP, "Kotlin extractor doesn't support Brotli compression. Using GZip instead.")
} else {
Pair(requested_compression, null)
}
} catch (e: IllegalArgumentException) {
Pair(defaultCompression,
"Unsupported compression type (\$$compression_env_var) \"$compression_option\". Supported values are ${Compression.values().joinToString()}")
}
}
// The invocation TRAP file will already have been started
// before the plugin is run, so we always use no compression
// and we open it in append mode.
FileOutputStream(File(invocationTrapFile), true).bufferedWriter().use { invocationTrapFileBW ->
val invocationExtractionProblems = ExtractionProblems()
val lm = TrapLabelManager()
val logCounter = LogCounter()
val loggerBase = LoggerBase(logCounter)
val tw = TrapWriter(loggerBase, lm, invocationTrapFileBW, null)
// The interceptor has already defined #compilation = *
val compilation: Label<DbCompilation> = StringLabel("compilation")
tw.writeCompilation_started(compilation)
tw.writeCompilation_info(compilation, "Kotlin Compiler Version", KotlinCompilerVersion.getVersion() ?: "<unknown>")
val extractor_name = this::class.java.getResource("extractor.name")?.readText() ?: "<unknown>"
tw.writeCompilation_info(compilation, "Kotlin Extractor Name", extractor_name)
if (compilationStartTime != null) {
tw.writeCompilation_compiler_times(compilation, -1.0, (System.currentTimeMillis()-compilationStartTime)/1000.0)
}
tw.flush()
val logger = Logger(loggerBase, tw)
logger.info("Extraction started")
logger.flush()
logger.info("Extraction for invocation TRAP file $invocationTrapFile")
logger.flush()
logger.info("Kotlin version ${KotlinCompilerVersion.getVersion()}")
logger.flush()
logPeakMemoryUsage(logger, "before extractor")
if (System.getenv("CODEQL_EXTRACTOR_JAVA_KOTLIN_DUMP") == "true") {
logger.info("moduleFragment:\n" + moduleFragment.dump())
}
if (compressionWarning != null) {
logger.warn(compressionWarning)
}
val primitiveTypeMapping = PrimitiveTypeMapping(logger, pluginContext)
// FIXME: FileUtil expects a static global logger
// which should be provided by SLF4J's factory facility. For now we set it here.
FileUtil.logger = logger
val srcDir = File(System.getenv("CODEQL_EXTRACTOR_JAVA_SOURCE_ARCHIVE_DIR").takeUnless { it.isNullOrEmpty() } ?: "kotlin-extractor/src")
srcDir.mkdirs()
val globalExtensionState = KotlinExtractorGlobalState()
moduleFragment.files.mapIndexed { index: Int, file: IrFile ->
val fileExtractionProblems = FileExtractionProblems(invocationExtractionProblems)
val fileTrapWriter = tw.makeSourceFileTrapWriter(file, true)
loggerBase.setFileNumber(index)
fileTrapWriter.writeCompilation_compiling_files(compilation, index, fileTrapWriter.fileId)
doFile(compression, fileExtractionProblems, invocationTrapFile, fileTrapWriter, checkTrapIdentical, loggerBase, trapDir, srcDir, file, primitiveTypeMapping, pluginContext, globalExtensionState)
fileTrapWriter.writeCompilation_compiling_files_completed(compilation, index, fileExtractionProblems.extractionResult())
}
loggerBase.printLimitedDiagnosticCounts(tw)
logPeakMemoryUsage(logger, "after extractor")
logger.info("Extraction completed")
logger.flush()
val compilationTimeMs = System.currentTimeMillis() - startTimeMs
tw.writeCompilation_finished(compilation, -1.0, compilationTimeMs.toDouble() / 1000, invocationExtractionProblems.extractionResult())
tw.flush()
loggerBase.close()
}
}
private fun logPeakMemoryUsage(logger: Logger, time: String) {
logger.info("Peak memory: Usage $time")
val beans = ManagementFactory.getMemoryPoolMXBeans()
var heap: Long = 0
var nonheap: Long = 0
for (bean in beans) {
val peak = bean.getPeakUsage().getUsed()
val kind = when (bean.getType()) {
MemoryType.HEAP -> { heap += peak; "heap" }
MemoryType.NON_HEAP -> { nonheap += peak; "non-heap" }
else -> "unknown"
}
logger.info("Peak memory: * Peak for $kind bean ${bean.getName()} is $peak")
}
logger.info("Peak memory: * Total heap peak: $heap")
logger.info("Peak memory: * Total non-heap peak: $nonheap")
}
}
class KotlinExtractorGlobalState {
// These three record mappings of classes, functions and fields that should be replaced wherever they are found.
// As of now these are only used to fix IR generated by the Gradle Android Extensions plugin, hence e.g. IrProperty
// doesn't have a map as that plugin doesn't generate them. If and when these are used more widely additional maps
// should be added here.
val syntheticToRealClassMap = HashMap<IrClass, IrClass?>()
val syntheticToRealFunctionMap = HashMap<IrFunction, IrFunction?>()
val syntheticToRealFieldMap = HashMap<IrField, IrField?>()
}
/*
The `ExtractionProblems` class is used to record whether this invocation
had any problems. It distinguish 2 kinds of problem:
* Recoverable problems: e.g. if we check something that we expect to be
non-null and find that it is null.
* Non-recoverable problems: if we catch an exception.
*/
open class ExtractionProblems {
private var recoverableProblem = false
private var nonRecoverableProblem = false
open fun setRecoverableProblem() {
recoverableProblem = true
}
open fun setNonRecoverableProblem() {
nonRecoverableProblem = true
}
fun extractionResult(): Int {
if(nonRecoverableProblem) {
return 2
} else if(recoverableProblem) {
return 1
} else {
return 0
}
}
}
/*
The `FileExtractionProblems` is analogous to `ExtractionProblems`,
except it records whether there were any problems while extracting a
particular source file.
*/
class FileExtractionProblems(val invocationExtractionProblems: ExtractionProblems): ExtractionProblems() {
override fun setRecoverableProblem() {
super.setRecoverableProblem()
invocationExtractionProblems.setRecoverableProblem()
}
override fun setNonRecoverableProblem() {
super.setNonRecoverableProblem()
invocationExtractionProblems.setNonRecoverableProblem()
}
}
/*
This function determines whether 2 TRAP files should be considered to be
equivalent. It returns `true` iff all of their non-comment lines are
identical.
*/
private fun equivalentTrap(r1: BufferedReader, r2: BufferedReader): Boolean {
r1.use { br1 ->
r2.use { br2 ->
while(true) {
val l1 = br1.readLine()
val l2 = br2.readLine()
if (l1 == null && l2 == null) {
return true
} else if (l1 == null || l2 == null) {
return false
} else if (l1 != l2) {
if (!l1.startsWith("//") || !l2.startsWith("//")) {
return false
}
}
}
}
}
}
private fun doFile(
compression: Compression,
fileExtractionProblems: FileExtractionProblems,
invocationTrapFile: String,
fileTrapWriter: FileTrapWriter,
checkTrapIdentical: Boolean,
loggerBase: LoggerBase,
dbTrapDir: File,
dbSrcDir: File,
srcFile: IrFile,
primitiveTypeMapping: PrimitiveTypeMapping,
pluginContext: IrPluginContext,
globalExtensionState: KotlinExtractorGlobalState) {
val srcFilePath = srcFile.path
val logger = FileLogger(loggerBase, fileTrapWriter)
logger.info("Extracting file $srcFilePath")
logger.flush()
val context = logger.loggerBase.extractorContextStack
if (!context.empty()) {
logger.warn("Extractor context was not empty. It thought:")
context.clear()
}
val srcFileRelativePath = srcFilePath.replace(':', '_')
val dbSrcFilePath = Paths.get("$dbSrcDir/$srcFileRelativePath")
val dbSrcDirPath = dbSrcFilePath.parent
Files.createDirectories(dbSrcDirPath)
val srcTmpFile = File.createTempFile(dbSrcFilePath.fileName.toString() + ".", ".src.tmp", dbSrcDirPath.toFile())
srcTmpFile.outputStream().use {
Files.copy(Paths.get(srcFilePath), it)
}
srcTmpFile.renameTo(dbSrcFilePath.toFile())
val trapFileName = "$dbTrapDir/$srcFileRelativePath.trap"
val trapFileWriter = getTrapFileWriter(compression, logger, trapFileName)
if (checkTrapIdentical || !trapFileWriter.exists()) {
trapFileWriter.makeParentDirectory()
try {
trapFileWriter.getTempWriter().use { trapFileBW ->
// We want our comments to be the first thing in the file,
// so start off with a mere TrapWriter
val tw = TrapWriter(loggerBase, TrapLabelManager(), trapFileBW, fileTrapWriter)
tw.writeComment("Generated by the CodeQL Kotlin extractor for kotlin source code")
tw.writeComment("Part of invocation $invocationTrapFile")
// Now elevate to a SourceFileTrapWriter, and populate the
// file information
val sftw = tw.makeSourceFileTrapWriter(srcFile, true)
val externalDeclExtractor = ExternalDeclExtractor(logger, invocationTrapFile, srcFilePath, primitiveTypeMapping, pluginContext, globalExtensionState, fileTrapWriter)
val linesOfCode = LinesOfCode(logger, sftw, srcFile)
val fileExtractor = KotlinFileExtractor(logger, sftw, linesOfCode, srcFilePath, null, externalDeclExtractor, primitiveTypeMapping, pluginContext, KotlinFileExtractor.DeclarationStack(), globalExtensionState)
fileExtractor.extractFileContents(srcFile, sftw.fileId)
externalDeclExtractor.extractExternalClasses()
}
if (checkTrapIdentical && trapFileWriter.exists()) {
if (equivalentTrap(trapFileWriter.getTempReader(), trapFileWriter.getRealReader())) {
trapFileWriter.deleteTemp()
} else {
trapFileWriter.renameTempToDifferent()
}
} else {
trapFileWriter.renameTempToReal()
}
// We catch Throwable rather than Exception, as we want to
// continue trying to extract everything else even if we get a
// stack overflow or an assertion failure in one file.
} catch (e: Throwable) {
logger.error("Failed to extract '$srcFilePath'. " + trapFileWriter.debugInfo(), e)
context.clear()
fileExtractionProblems.setNonRecoverableProblem()
}
}
}
enum class Compression { NONE, GZIP, BROTLI }
private fun getTrapFileWriter(compression: Compression, logger: FileLogger, trapFileName: String): TrapFileWriter {
return when (compression) {
Compression.NONE -> NonCompressedTrapFileWriter(logger, trapFileName)
Compression.GZIP -> GZipCompressedTrapFileWriter(logger, trapFileName)
Compression.BROTLI -> {
// Brotli should have been replaced with gzip earlier, but
// if we somehow manage to get here then keep going
logger.error("Impossible Brotli compression requested. Using Gzip instead.")
getTrapFileWriter(Compression.GZIP, logger, trapFileName)
}
}
}
private abstract class TrapFileWriter(val logger: FileLogger, trapName: String, val extension: String) {
private val realFile = File(trapName + extension)
private val parentDir = realFile.parentFile
lateinit private var tempFile: File
fun debugInfo(): String {
if (this::tempFile.isInitialized) {
return "Partial TRAP file location is $tempFile"
} else {
return "Temporary file not yet created."
}
}
fun makeParentDirectory() {
parentDir.mkdirs()
}
fun exists(): Boolean {
return realFile.exists()
}
abstract protected fun getReader(file: File): BufferedReader
abstract protected fun getWriter(file: File): BufferedWriter
fun getRealReader(): BufferedReader {
return getReader(realFile)
}
fun getTempReader(): BufferedReader {
return getReader(tempFile)
}
fun getTempWriter(): BufferedWriter {
if (this::tempFile.isInitialized) {
logger.error("Temp writer reinitialized for $realFile")
}
tempFile = File.createTempFile(realFile.getName() + ".", ".trap.tmp" + extension, parentDir)
return getWriter(tempFile)
}
fun deleteTemp() {
if (!tempFile.delete()) {
logger.warn("Failed to delete $tempFile")
}
}
fun renameTempToDifferent() {
val trapDifferentFile = File.createTempFile(realFile.getName() + ".", ".trap.different" + extension, parentDir)
if (tempFile.renameTo(trapDifferentFile)) {
logger.warn("TRAP difference: $realFile vs $trapDifferentFile")
} else {
logger.warn("Failed to rename $tempFile to $realFile")
}
}
fun renameTempToReal() {
if (!tempFile.renameTo(realFile)) {
logger.warn("Failed to rename $tempFile to $realFile")
}
}
}
private class NonCompressedTrapFileWriter(logger: FileLogger, trapName: String): TrapFileWriter(logger, trapName, "") {
override protected fun getReader(file: File): BufferedReader {
return file.bufferedReader()
}
override protected fun getWriter(file: File): BufferedWriter {
return file.bufferedWriter()
}
}
private class GZipCompressedTrapFileWriter(logger: FileLogger, trapName: String): TrapFileWriter(logger, trapName, ".gz") {
override protected fun getReader(file: File): BufferedReader {
return BufferedReader(InputStreamReader(GZIPInputStream(BufferedInputStream(FileInputStream(file)))))
}
override protected fun getWriter(file: File): BufferedWriter {
return BufferedWriter(OutputStreamWriter(GZIPOutputStream(BufferedOutputStream(FileOutputStream(file)))))
}
}
| mit | 6000fa4d582901c209c68f4f571b1d55 | 44.27033 | 223 | 0.658511 | 5.077151 | false | false | false | false |
milosmns/android-task-stack-example | app/src/main/kotlin/me/angrybyte/activitytasks/activities/GenericTaskActivity.kt | 1 | 7077 | package me.angrybyte.activitytasks.activities
import android.Manifest
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_layout.*
import me.angrybyte.activitytasks.R
import me.angrybyte.activitytasks.utils.*
/**
* Superclass of all app's activities. Displays everything that's needed on the UI,
* overriding activities only need to override stuff to provide detailed info about themselves.
*/
abstract class GenericTaskActivity : AppCompatActivity() {
private val PERMISSION_REQUEST_TASKS = 1
private val KEY_ORIGIN_NAME = "KEY_ORIGIN_NAME"
private val KEY_ORIGIN_ID = "KEY_ORIGIN_ID"
private val KEY_ORIGIN_TASK_ID = "KEY_ORIGIN_TASK_ID"
private var reInit: Boolean = false
/* Activity stuff */
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_layout)
@Suppress("DEPRECATION") // not true, this is a valid KitKat permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.GET_TASKS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.GET_TASKS), PERMISSION_REQUEST_TASKS)
} else {
setupActivity()
}
}
override fun onStart() {
super.onStart()
if (reInit) setupActivity()
}
override fun onStop() {
super.onStop()
reInit = true
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
PERMISSION_REQUEST_TASKS -> {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
finish()
} else {
setupActivity()
}
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
intent?.let {
outState.putString(KEY_ORIGIN_NAME, intent.getStringExtra(KEY_ORIGIN_NAME))
outState.putString(KEY_ORIGIN_ID, intent.getStringExtra(KEY_ORIGIN_ID))
outState.putString(KEY_ORIGIN_TASK_ID, intent.getStringExtra(KEY_ORIGIN_TASK_ID))
}
super.onSaveInstanceState(outState)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
setupActivity()
}
/**
* Initializes all views.
*/
private fun setupActivity() {
// update stack details from the current intent and task info
stackInfo.setHtml(getTaskStackHtml())
// update current activity info
val thisActTitle = getActivityTitle() // template already has 'Activity'
val thisActHash = "#${getId()}"
val thisTaskHash = "#${Utils.toHex(taskId)}"
val originActName = getOriginActivity().replace("Activity", "")
val originActHash = "#${getOriginActivityId()}"
val originTaskHash = "#${getOriginTaskId()}"
descriptionText.text = getString(R.string.description_template,
thisActTitle, thisActHash, thisTaskHash, originActName, originActHash, originTaskHash
)
// calculate colors and replace plain IDs with colored IDs
val launcherHash = "#${getString(R.string.activity_name_launcher)[0]}"
val originActColor = if (launcherHash == originActHash) 0xCCCCCC else Utils.parseHex(originActHash)
val originTaskColor = if (launcherHash == originTaskHash) 0xCCCCCC else Utils.parseHex(originTaskHash)
val replacements = arrayOf(thisActHash, thisTaskHash, originActHash, originTaskHash)
val colors = intArrayOf(hashCode(), taskId, originActColor, originTaskColor)
descriptionText.markText(replacements, colors)
// assign click listeners for buttons so that they open the correct activities
val classes = listOf(DefaultActivity::class.java, SingleTaskActivity::class.java, SingleTopActivity::class.java, SingleInstanceActivity::class.java)
listOf(start_default, start_single_task, start_single_top, start_single_instance).forEachIndexed {
i, iView ->
iView.setOnClickListener {
val intent = Intent(GenericTaskActivity@ this, classes[i])
intent.putExtra(KEY_ORIGIN_NAME, GenericTaskActivity@ this.javaClass.simpleName!!)
intent.putExtra(KEY_ORIGIN_ID, getId())
intent.putExtra(KEY_ORIGIN_TASK_ID, Utils.toHex(taskId))
startActivity(intent)
}
}
}
/* Important operations */
/**
* Searches through the current Intent to find the origin Activity name, if supplied.
*/
private fun getOriginActivity() = findInIntent(KEY_ORIGIN_NAME, getString(R.string.activity_name_launcher))
/**
* Searches through the current Intent to find the origin Activity ID, if supplied.
*/
private fun getOriginActivityId() = findInIntent(KEY_ORIGIN_ID, getString(R.string.activity_name_launcher)[0].toString())
/**
* Searches through the current Intent to find the origin Task ID, if supplied.
*/
private fun getOriginTaskId() = findInIntent(KEY_ORIGIN_TASK_ID, getString(R.string.activity_name_launcher)[0].toString())
/**
* Tries to find the current task stack, if possible. Outputs plain HTML text.
*/
private fun getTaskStackHtml(): String {
val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
@Suppress("DEPRECATION") // valid call, even with Lollipop limitations
val taskList = manager.getRunningTasks(10) // this may not work on Lollipop...
if (taskList.isEmpty()) {
return getString(R.string.stack_unknown)
}
val builder = StringBuilder(taskList.size)
for ((i, task) in taskList.withIndex()) {
val colorHash = Utils.toHex(task.id)
val taskId = "<font color=\"#$colorHash\"><b>#$colorHash</b></font>"
val baseName = task.baseActivity.shortClassName
val topName = task.topActivity.shortClassName
val taskDescription = getString(R.string.stack_item_template, taskId, baseName, topName, task.numActivities, task.numRunning)
builder.append("-")
builder.append(taskDescription.replace("\n", "<br>"))
// add new lines only on middle tasks
if (i < taskList.size - 1) {
builder.append("<br><br>")
}
}
return builder.toString()
}
/* Override these in sub-activities */
/**
* Gets the unique activity title from the implementation class.
*/
protected abstract fun getActivityTitle(): String
} | gpl-3.0 | f5e0c9bbd3085cb764472e49ea26bfc9 | 39.913295 | 156 | 0.666101 | 4.727455 | false | false | false | false |
FireZenk/Kartographer | sample/src/main/java/org/firezenk/kartographer/extensions/BottomNavigationViewExt.kt | 1 | 1040 | package org.firezenk.kartographer.extensions
import android.annotation.SuppressLint
import android.support.design.internal.BottomNavigationItemView
import android.support.design.internal.BottomNavigationMenuView
import android.support.design.widget.BottomNavigationView
@SuppressLint("RestrictedApi")
fun BottomNavigationView.disableShiftMode() {
val menuView = this.getChildAt(0) as BottomNavigationMenuView
try {
val shiftingMode = menuView.javaClass.getDeclaredField("mShiftingMode")
shiftingMode.isAccessible = true
shiftingMode.setBoolean(menuView, false)
shiftingMode.isAccessible = false
for (i in 0 until menuView.childCount) {
val item = menuView.getChildAt(i) as BottomNavigationItemView
item.setShiftingMode(false)
// set once again checked value, so view will be updated
item.setChecked(item.itemData.isChecked)
}
} catch (ignored: NoSuchFieldException) {
} catch (ignored: IllegalAccessException) {
}
} | mit | fcc418b685b4dc5d0097fa53dd0657a5 | 31.53125 | 79 | 0.735577 | 5.024155 | false | false | false | false |
outbrain/ob1k | ob1k-crud/src/main/java/com/outbrain/ob1k/crud/JsonUtils.kt | 1 | 2178 | package com.outbrain.ob1k.crud
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.outbrain.ob1k.crud.model.EntityField
internal fun JsonObject.with(name: String, value: Number?): JsonObject {
addProperty(name, value)
return this
}
internal fun JsonObject.with(name: String, value: String?): JsonObject {
addProperty(name, value)
return this
}
internal fun JsonObject.with(name: String, value: Boolean?): JsonObject {
addProperty(name, value)
return this
}
internal fun JsonObject.with(name: String, value: JsonArray?): JsonObject {
add(name, value)
return this
}
internal fun JsonObject.with(name: String, value: List<JsonObject>?): JsonObject {
value?.let {
val arr = JsonArray()
it.forEach { arr.add(it) }
add(name, arr)
}
return this
}
internal fun JsonObject.with(field: EntityField, value: Number?) = with(field.name, value)
internal fun JsonObject.with(field: EntityField, value: String?) = with(field.name, value)
internal fun JsonObject.with(field: EntityField, value: Boolean?) = with(field.name, value)
internal fun JsonObject.with(field: EntityField, value: JsonArray?) = with(field.name, value)
internal fun JsonObject.with(field: EntityField, value: List<JsonObject>?) = with(field.name, value)
internal fun JsonObject.getInt(field: EntityField) = getInt(field.name)
internal fun JsonObject.getLong(field: EntityField) = getLong(field.name)
internal fun JsonObject.getString(field: EntityField) = getString(field.name)
internal fun JsonObject.getBoolean(field: EntityField) = getBoolean(field.name)
internal fun JsonObject.getList(field: EntityField) = getList(field.name)
internal fun JsonObject.id() = getLong("id")
internal fun JsonObject.getInt(name: String) = get(name)?.asInt
internal fun JsonObject.getLong(name: String) = get(name)?.asLong
internal fun JsonObject.getString(name: String) = get(name)?.toString()
internal fun JsonObject.getBoolean(name: String) = get(name)?.asBoolean
internal fun JsonObject.getList(name: String): List<JsonObject>? {
val jsonArray = getAsJsonArray(name) ?: return null
return jsonArray.map { it.asJsonObject }
} | apache-2.0 | 8dcf0467c93dc5c826dcb58da61dccb2 | 37.910714 | 100 | 0.746556 | 3.917266 | false | false | false | false |
paplorinc/intellij-community | platform/configuration-store-impl/src/ComponentStoreWithExtraComponents.kt | 1 | 4198 | // 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.configurationStore
import com.intellij.openapi.components.SettingsSavingComponent
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.util.SmartList
import com.intellij.util.containers.ContainerUtil
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean
// A way to remove obsolete component data.
internal val OBSOLETE_STORAGE_EP = ExtensionPointName<ObsoleteStorageBean>("com.intellij.obsoleteStorage")
abstract class ComponentStoreWithExtraComponents : ComponentStoreImpl() {
@Suppress("DEPRECATION")
private val settingsSavingComponents = ContainerUtil.createLockFreeCopyOnWriteList<SettingsSavingComponent>()
private val asyncSettingsSavingComponents = ContainerUtil.createLockFreeCopyOnWriteList<com.intellij.configurationStore.SettingsSavingComponent>()
// todo do we really need this?
private val isSaveSettingsInProgress = AtomicBoolean()
override suspend fun save(forceSavingAllSettings: Boolean) {
if (!isSaveSettingsInProgress.compareAndSet(false, true)) {
LOG.warn("save call is ignored because another save in progress", Throwable())
return
}
try {
super.save(forceSavingAllSettings)
}
finally {
isSaveSettingsInProgress.set(false)
}
}
override fun initComponent(component: Any, isService: Boolean) {
@Suppress("DEPRECATION")
if (component is com.intellij.configurationStore.SettingsSavingComponent) {
asyncSettingsSavingComponents.add(component)
}
else if (component is SettingsSavingComponent) {
settingsSavingComponents.add(component)
}
super.initComponent(component, isService)
}
internal suspend fun saveSettingsSavingComponentsAndCommitComponents(result: SaveResult, forceSavingAllSettings: Boolean): SaveSessionProducerManager {
coroutineScope {
// expects EDT
launch(storeEdtCoroutineContext) {
@Suppress("Duplicates")
val errors = SmartList<Throwable>()
for (settingsSavingComponent in settingsSavingComponents) {
runAndCollectException(errors) {
settingsSavingComponent.save()
}
}
result.addErrors(errors)
}
launch {
val errors = SmartList<Throwable>()
for (settingsSavingComponent in asyncSettingsSavingComponents) {
runAndCollectException(errors) {
settingsSavingComponent.save()
}
}
result.addErrors(errors)
}
}
// SchemeManager (old settingsSavingComponent) must be saved before saving components (component state uses scheme manager in an ipr project, so, we must save it before)
// so, call sequentially it, not inside coroutineScope
return createSaveSessionManagerAndSaveComponents(result, forceSavingAllSettings)
}
override fun commitComponents(isForce: Boolean, session: SaveSessionProducerManager, errors: MutableList<Throwable>) {
// ensure that this task will not interrupt regular saving
LOG.runAndLogException {
commitObsoleteComponents(session, false)
}
super.commitComponents(isForce, session, errors)
}
internal open fun commitObsoleteComponents(session: SaveSessionProducerManager, isProjectLevel: Boolean) {
for (bean in OBSOLETE_STORAGE_EP.extensionList) {
if (bean.isProjectLevel != isProjectLevel) {
continue
}
val storage = (storageManager as StateStorageManagerImpl).getOrCreateStorage(bean.file ?: continue)
for (componentName in bean.components) {
session.getProducer(storage)?.setState(null, componentName, null)
}
}
}
}
private inline fun <T> runAndCollectException(errors: MutableList<Throwable>, runnable: () -> T): T? {
try {
return runnable()
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
errors.add(e)
return null
}
}
| apache-2.0 | 1ec21159f6d6615a142f9e4437fbac5e | 35.504348 | 173 | 0.74202 | 5.208437 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mcp/actions/GotoAtEntryAction.kt | 1 | 4764 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.actions
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.platform.mcp.srg.SrgManager
import com.demonwav.mcdev.platform.mixin.util.findFirstShadowTarget
import com.demonwav.mcdev.util.ActionData
import com.demonwav.mcdev.util.getDataFromActionEvent
import com.demonwav.mcdev.util.gotoTargetElement
import com.demonwav.mcdev.util.invokeLater
import com.demonwav.mcdev.util.qualifiedMemberReference
import com.demonwav.mcdev.util.simpleQualifiedMemberReference
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.wm.WindowManager
import com.intellij.psi.PsiField
import com.intellij.psi.PsiIdentifier
import com.intellij.psi.PsiManager
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.UsageSearchContext
import com.intellij.ui.LightColors
import com.intellij.ui.awt.RelativePoint
class GotoAtEntryAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val data = getDataFromActionEvent(e) ?: return showBalloon(e)
if (data.element !is PsiIdentifier) {
showBalloon(e)
return
}
val srgManager = data.instance.getModuleOfType(McpModuleType)?.srgManager
// Not all ATs are in MCP modules, fallback to this if possible
// TODO try to find SRG references for all modules if current module isn't found?
?: SrgManager.findAnyInstance(data.project) ?: return showBalloon(e)
srgManager.srgMap.onSuccess { srgMap ->
var parent = data.element.parent
if (parent is PsiMember) {
val shadowTarget = parent.findFirstShadowTarget()?.element
if (shadowTarget != null) {
parent = shadowTarget
}
}
when (parent) {
is PsiField -> {
val reference = srgMap.getSrgField(parent) ?: parent.simpleQualifiedMemberReference
?: return@onSuccess showBalloon(e)
searchForText(e, data, reference.name)
}
is PsiMethod -> {
val reference =
srgMap.getSrgMethod(parent) ?: parent.qualifiedMemberReference ?: return@onSuccess showBalloon(
e
)
searchForText(e, data, reference.name + reference.descriptor)
}
else ->
showBalloon(e)
}
}
}
private fun searchForText(e: AnActionEvent, data: ActionData, text: String) {
val manager = ModuleManager.getInstance(data.project)
manager.modules.asSequence()
.mapNotNull { MinecraftFacet.getInstance(it, McpModuleType) }
.flatMap { it.accessTransformers.asSequence() }
.forEach { virtualFile ->
val file = PsiManager.getInstance(data.project).findFile(virtualFile) ?: return@forEach
var found = false
PsiSearchHelper.getInstance(data.project)
.processElementsWithWord(
{ element, _ ->
gotoTargetElement(element, data.editor, data.file)
found = true
false
},
LocalSearchScope(file),
text,
UsageSearchContext.ANY,
true
)
if (found) {
return
}
}
showBalloon(e)
}
private fun showBalloon(e: AnActionEvent) {
val balloon = JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder("No access transformer entry found", null, LightColors.YELLOW, null)
.setHideOnAction(true)
.setHideOnClickOutside(true)
.setHideOnKeyOutside(true)
.createBalloon()
val project = e.project ?: return
val statusBar = WindowManager.getInstance().getStatusBar(project)
invokeLater { balloon.show(RelativePoint.getCenterOf(statusBar.component), Balloon.Position.atRight) }
}
}
| mit | 3c3592e69d4fd48ffe1394abff9a7259 | 36.809524 | 119 | 0.622796 | 5.16143 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/DynamicPluginEnabler.kt | 1 | 1980 | // 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.ide.plugins
import com.intellij.ide.feedback.kotlinRejecters.state.KotlinRejectersInfoService
import com.intellij.ide.plugins.marketplace.statistics.PluginManagerUsageCollector
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
@ApiStatus.Internal
internal class DynamicPluginEnabler : PluginEnabler {
override fun isDisabled(pluginId: PluginId): Boolean =
PluginEnabler.HEADLESS.isDisabled(pluginId)
override fun enable(descriptors: Collection<IdeaPluginDescriptor>): Boolean =
enable(descriptors, project = null)
fun enable(
descriptors: Collection<IdeaPluginDescriptor>,
project: Project? = null,
): Boolean {
PluginManagerUsageCollector.pluginsStateChanged(descriptors, enable = true, project)
PluginEnabler.HEADLESS.enable(descriptors)
return DynamicPlugins.loadPlugins(descriptors)
}
override fun disable(descriptors: Collection<IdeaPluginDescriptor>): Boolean =
disable(descriptors, project = null)
fun disable(
descriptors: Collection<IdeaPluginDescriptor>,
project: Project? = null,
parentComponent: JComponent? = null,
): Boolean {
PluginManagerUsageCollector.pluginsStateChanged(descriptors, enable = false, project)
recordKotlinPluginDisabling(descriptors)
PluginEnabler.HEADLESS.disable(descriptors)
return DynamicPlugins.unloadPlugins(descriptors, project, parentComponent)
}
private fun recordKotlinPluginDisabling(descriptors: Collection<IdeaPluginDescriptor>) {
// Kotlin Plugin + 4 plugin dependency
if (descriptors.size <= 5
&& descriptors.any { it.pluginId.idString == "org.jetbrains.kotlin" }) {
KotlinRejectersInfoService.getInstance().state.showNotificationAfterRestart = true
}
}
} | apache-2.0 | d5a2926b22a5bfa8072952b5c7fd750c | 36.377358 | 120 | 0.782323 | 5 | false | false | false | false |
square/okhttp | okhttp/src/jvmMain/kotlin/okhttp3/RequestBody.kt | 2 | 6823 | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import java.io.File
import java.io.FileDescriptor
import java.io.FileInputStream
import java.io.IOException
import okhttp3.internal.chooseCharset
import okhttp3.internal.commonContentLength
import okhttp3.internal.commonIsDuplex
import okhttp3.internal.commonIsOneShot
import okhttp3.internal.commonToRequestBody
import okio.BufferedSink
import okio.ByteString
import okio.FileSystem
import okio.GzipSink
import okio.Path
import okio.buffer
import okio.source
actual abstract class RequestBody {
actual abstract fun contentType(): MediaType?
@Throws(IOException::class)
actual open fun contentLength(): Long = commonContentLength()
@Throws(IOException::class)
actual abstract fun writeTo(sink: BufferedSink)
actual open fun isDuplex(): Boolean = commonIsDuplex()
actual open fun isOneShot(): Boolean = commonIsOneShot()
actual companion object {
/**
* Returns a new request body that transmits this string. If [contentType] is non-null and lacks
* a charset, this will use UTF-8.
*/
@JvmStatic
@JvmName("create")
actual fun String.toRequestBody(contentType: MediaType?): RequestBody {
val (charset, finalContentType) = contentType.chooseCharset()
val bytes = toByteArray(charset)
return bytes.toRequestBody(finalContentType, 0, bytes.size)
}
@JvmStatic
@JvmName("create")
actual fun ByteString.toRequestBody(contentType: MediaType?): RequestBody =
commonToRequestBody(contentType)
/** Returns a new request body that transmits this. */
@JvmStatic
@JvmName("create")
fun FileDescriptor.toRequestBody(contentType: MediaType? = null): RequestBody {
return object : RequestBody() {
override fun contentType() = contentType
override fun isOneShot(): Boolean = true
override fun writeTo(sink: BufferedSink) {
FileInputStream(this@toRequestBody).use {
sink.buffer.writeAll(it.source())
}
}
}
}
@JvmOverloads
@JvmStatic
@JvmName("create")
actual fun ByteArray.toRequestBody(
contentType: MediaType?,
offset: Int,
byteCount: Int
): RequestBody = commonToRequestBody(contentType, offset, byteCount)
/** Returns a new request body that transmits the content of this. */
@JvmStatic
@JvmName("create")
fun File.asRequestBody(contentType: MediaType? = null): RequestBody {
return object : RequestBody() {
override fun contentType() = contentType
override fun contentLength() = length()
override fun writeTo(sink: BufferedSink) {
source().use { source -> sink.writeAll(source) }
}
}
}
/** Returns a new request body that transmits the content of this. */
@JvmStatic
@JvmName("create")
fun Path.asRequestBody(fileSystem: FileSystem, contentType: MediaType? = null): RequestBody {
return object : RequestBody() {
override fun contentType() = contentType
override fun contentLength() = fileSystem.metadata(this@asRequestBody).size ?: -1
override fun writeTo(sink: BufferedSink) {
fileSystem.source(this@asRequestBody).use { source -> sink.writeAll(source) }
}
}
}
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "content.toRequestBody(contentType)",
imports = ["okhttp3.RequestBody.Companion.toRequestBody"]
),
level = DeprecationLevel.WARNING)
fun create(contentType: MediaType?, content: String): RequestBody = content.toRequestBody(contentType)
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "content.toRequestBody(contentType)",
imports = ["okhttp3.RequestBody.Companion.toRequestBody"]
),
level = DeprecationLevel.WARNING)
fun create(
contentType: MediaType?,
content: ByteString
): RequestBody = content.toRequestBody(contentType)
@JvmOverloads
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "content.toRequestBody(contentType, offset, byteCount)",
imports = ["okhttp3.RequestBody.Companion.toRequestBody"]
),
level = DeprecationLevel.WARNING)
fun create(
contentType: MediaType?,
content: ByteArray,
offset: Int = 0,
byteCount: Int = content.size
): RequestBody = content.toRequestBody(contentType, offset, byteCount)
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'file' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "file.asRequestBody(contentType)",
imports = ["okhttp3.RequestBody.Companion.asRequestBody"]
),
level = DeprecationLevel.WARNING)
fun create(contentType: MediaType?, file: File): RequestBody= file.asRequestBody(contentType)
/**
* Returns a gzip version of the RequestBody, with compressed payload.
* This is not automatic as not all servers support gzip compressed requests.
*
* ```
* val request = Request.Builder().url("...")
* .addHeader("Content-Encoding", "gzip")
* .post(uncompressedBody.gzip())
* .build()
* ```
*/
@JvmStatic
fun RequestBody.gzip(): RequestBody {
return object : RequestBody() {
override fun contentType(): MediaType? {
return [email protected]()
}
override fun contentLength(): Long {
return -1 // We don't know the compressed length in advance!
}
@Throws(IOException::class)
override fun writeTo(sink: BufferedSink) {
val gzipSink = GzipSink(sink).buffer()
[email protected](gzipSink)
gzipSink.close()
}
override fun isOneShot(): Boolean {
return [email protected]()
}
}
}
}
}
| apache-2.0 | 2b8ba006618483ecee6922ef00311887 | 31.961353 | 106 | 0.667595 | 4.852774 | false | false | false | false |
Leifzhang/AndroidRouter | Plugin/BasePlugin/src/main/java/com/kronos/plugin/base/TransformBuilder.kt | 1 | 784 | package com.kronos.plugin.base
import com.android.build.api.transform.TransformInvocation
/**
*
* @Author LiABao
* @Since 2021/6/30
*
*/
class TransformBuilder(val callBack: TransformCallBack) {
var transformInvocation: TransformInvocation? = null
var single: Boolean = false
var filter: ClassNameFilter? = null
var simpleScan = false
var deleteCallBack: DeleteCallBack? = null
fun build(): BaseTransform {
val transform = BaseTransform(transformInvocation, callBack, single)
transform.also {
it.filter = filter
}
if (simpleScan) {
transform.openSimpleScan()
}
deleteCallBack?.apply {
transform.setDeleteCallBack(this)
}
return transform
}
} | mit | 9f06003f7474b5bbf5566c4cc6c61ea9 | 20.805556 | 76 | 0.641582 | 4.531792 | false | false | false | false |
fancylou/FancyFilePicker | fancyfilepickerlibrary/src/main/java/net/muliba/fancyfilepickerlibrary/FilePicker.kt | 1 | 4560 | package net.muliba.fancyfilepickerlibrary
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.wugang.activityresult.library.ActivityResult
import net.muliba.fancyfilepickerlibrary.ui.FileActivity
import net.muliba.fancyfilepickerlibrary.util.Utils
/**
* Created by fancy on 2017/4/12.
*/
class FilePicker {
companion object {
@JvmStatic val FANCY_FILE_PICKER_ARRAY_LIST_RESULT_KEY @JvmName("FANCY_FILE_PICKER_ARRAY_LIST_RESULT_KEY")get() = "fancy_file_picker_array_result"
@JvmStatic val FANCY_FILE_PICKER_SINGLE_RESULT_KEY @JvmName("FANCY_FILE_PICKER_SINGLE_RESULT_KEY")get() = "fancy_file_picker_single_result"
@JvmStatic val FANCY_REQUEST_CODE @JvmName("FANCY_REQUEST_CODE")get() = 1024
//选择类型
@JvmStatic val CHOOSE_TYPE_MULTIPLE @JvmName("CHOOSE_TYPE_MULTIPLE")get() = 0
@JvmStatic val CHOOSE_TYPE_SINGLE @JvmName("CHOOSE_TYPE_SINGLE")get() = 1
}
private var requestCode: Int = FANCY_REQUEST_CODE
private var activity: Activity? = null
private var chooseType = CHOOSE_TYPE_MULTIPLE //默认多选
private var existingResults = ArrayList<String>()
fun withActivity(activity: Activity) : FilePicker {
this.activity = activity
return this
}
/**
* 设置选择类型
* @param type One of {@link #CHOOSE_TYPE_MULTIPLE}, {@link #CHOOSE_TYPE_SINGLE}.
*/
fun chooseType(type: Int = CHOOSE_TYPE_MULTIPLE): FilePicker {
if (type != CHOOSE_TYPE_SINGLE && type!= CHOOSE_TYPE_MULTIPLE) {
throw IllegalArgumentException("chooseType value is illegal , must be one of #FilePicker.CHOOSE_TYPE_MULTIPLE or #FilePicker.CHOOSE_TYPE_SINGLE ")
}
chooseType = type
return this
}
/**
* 定义requestCode
* @param requestCode
*/
@Deprecated(message = "4.0.0开始不再使用,用forResult直接返回结果,不需要onActivityResult接收结果")
fun requestCode(requestCode: Int): FilePicker {
this.requestCode = requestCode
return this
}
fun existingResults(results:ArrayList<String>): FilePicker {
this.existingResults.clear()
if (results.isNotEmpty()) {
this.existingResults.addAll(results)
}
return this
}
/**
* 启动选择器
*/
@Deprecated(message = "4.0.0开始不再使用,用forResult直接返回结果,不需要onActivityResult接收结果")
fun start() {
if (activity==null) {
throw RuntimeException("not found Activity, Please execute the function 'withActivity' ")
}
startFilePicker()
}
/**
* 4.0.0 新增
* 返回选择的结果 如果是单选 result[0]获取
* 不再需要到onActivityResult中去接收结果
*/
fun forResult(listener: (filePaths: List<String>) -> Unit) {
if (activity==null) {
throw RuntimeException("not found Activity, Please execute the function 'withActivity' ")
}
val bundle = Bundle()
bundle.putInt(Utils.CHOOSE_TYPE_KEY, chooseType)
bundle.putStringArrayList(Utils.MULIT_CHOOSE_BACK_RESULTS_KEY, existingResults)
ActivityResult.of(activity!!)
.className(FileActivity::class.java)
.params(bundle)
.greenChannel()
.forResult { resultCode, data ->
val result = ArrayList<String>()
if (resultCode == Activity.RESULT_OK) {
if (chooseType == CHOOSE_TYPE_SINGLE) {
val filePath = data?.getStringExtra(FANCY_FILE_PICKER_SINGLE_RESULT_KEY) ?: ""
if (filePath.isNotEmpty()) {
result.add(filePath)
}
}else {
val array = data?.getStringArrayListExtra(FANCY_FILE_PICKER_ARRAY_LIST_RESULT_KEY)
if (array !=null && array.isNotEmpty()) {
result.addAll(array)
}
}
}
listener(result)
}
}
private fun startFilePicker() {
val intent = Intent(activity, FileActivity::class.java)
intent.putExtra(Utils.CHOOSE_TYPE_KEY, chooseType)
intent.putExtra(Utils.MULIT_CHOOSE_BACK_RESULTS_KEY, existingResults)
activity?.startActivityForResult(intent, requestCode)
}
} | apache-2.0 | 0b83d062427f44fb1d764b04a539a6d9 | 35.173554 | 158 | 0.603748 | 4.41129 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/screen/SaveRemixScreen.kt | 2 | 6500 | package io.github.chrislo27.rhre3.screen
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.utils.Align
import io.github.chrislo27.rhre3.PreferenceKeys
import io.github.chrislo27.rhre3.RHRE3
import io.github.chrislo27.rhre3.RHRE3Application
import io.github.chrislo27.rhre3.RemixRecovery
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.sfxdb.GameMetadata
import io.github.chrislo27.rhre3.stage.GenericStage
import io.github.chrislo27.rhre3.stage.LoadingIcon
import io.github.chrislo27.rhre3.track.Remix
import io.github.chrislo27.rhre3.util.*
import io.github.chrislo27.toolboks.ToolboksScreen
import io.github.chrislo27.toolboks.i18n.Localization
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.registry.ScreenRegistry
import io.github.chrislo27.toolboks.ui.ImageLabel
import io.github.chrislo27.toolboks.ui.TextLabel
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class SaveRemixScreen(main: RHRE3Application)
: ToolboksScreen<RHRE3Application, SaveRemixScreen>(main) {
private val editorScreen: EditorScreen by lazy { ScreenRegistry.getNonNullAsType<EditorScreen>("editor") }
private val editor: Editor
get() = editorScreen.editor
override val stage: GenericStage<SaveRemixScreen> = GenericStage(main.uiPalette, null, main.defaultCamera)
@Volatile
private var isChooserOpen = false
set(value) {
field = value
stage.backButton.enabled = !isChooserOpen
}
@Volatile
private var isSaving: Boolean = false
private val mainLabel: TextLabel<SaveRemixScreen>
init {
stage.titleIcon.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_saveremix"))
stage.titleLabel.text = "screen.save.title"
stage.backButton.visible = true
stage.onBackButtonClick = {
if (!isChooserOpen) {
main.screen = ScreenRegistry.getNonNull("editor")
}
}
stage.centreStage.elements += object : LoadingIcon<SaveRemixScreen>(main.uiPalette, stage.centreStage) {
override var visible: Boolean = true
get() = field && isSaving
}.apply {
this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO
this.location.set(screenHeight = 0.125f, screenY = 0.125f / 2f)
}
val palette = main.uiPalette
stage.centreStage.elements += object : TextLabel<SaveRemixScreen>(palette, stage.centreStage,
stage.centreStage) {
override fun frameUpdate(screen: SaveRemixScreen) {
super.frameUpdate(screen)
this.visible = isChooserOpen
}
}.apply {
this.location.set(screenHeight = 0.25f)
this.textAlign = Align.center
this.isLocalizationKey = true
this.text = "closeChooser"
this.visible = false
}
mainLabel = TextLabel(palette, stage.centreStage, stage.centreStage).apply {
this.location.set(screenHeight = 0.75f, screenY = 0.25f)
this.textAlign = Align.center
this.isLocalizationKey = false
this.text = ""
}
stage.centreStage.elements += mainLabel
stage.updatePositions()
updateLabels(null)
}
override fun renderUpdate() {
super.renderUpdate()
if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE) || Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) {
stage.onBackButtonClick()
}
}
@Synchronized
private fun openPicker() {
if (!isChooserOpen) {
GlobalScope.launch {
isChooserOpen = true
val lastSaveFile = editor.lastSaveFile
val filter = TinyFDWrapper.FileExtFilter(Localization["screen.save.fileFilter"] + "(.${RHRE3.REMIX_FILE_EXTENSION})", "*.${RHRE3.REMIX_FILE_EXTENSION}")
TinyFDWrapper.saveFile(Localization["screen.save.fileChooserTitle"], lastSaveFile?.file() ?: lastSaveFile?.parent()?.file() ?: attemptRememberDirectory(main, PreferenceKeys.FILE_CHOOSER_SAVE) ?: getDefaultDirectory(), filter) { file ->
isChooserOpen = false
if (file != null) {
val newInitialDirectory = if (!file.isDirectory) file.parentFile else file
persistDirectory(main, PreferenceKeys.FILE_CHOOSER_SAVE, newInitialDirectory)
GlobalScope.launch {
try {
val correctFile = if (file.extension != RHRE3.REMIX_FILE_EXTENSION)
file.parentFile.resolve("${file.name}.${RHRE3.REMIX_FILE_EXTENSION}")
else
file
val remix = editor.remix
isSaving = true
Remix.saveTo(remix, correctFile, false)
val newfh = FileHandle(correctFile)
editor.setFileHandles(newfh)
RemixRecovery.cacheChecksumOfFile(newfh)
mainLabel.text = Localization["screen.save.success"]
Gdx.app.postRunnable(GameMetadata::persist)
} catch (t: Throwable) {
t.printStackTrace()
updateLabels(t)
}
isSaving = false
}
} else {
stage.onBackButtonClick()
}
}
}
}
}
private fun updateLabels(throwable: Throwable? = null) {
val label = mainLabel
if (throwable == null) {
label.text = ""
} else {
label.text = Localization["screen.save.failed", throwable::class.java.canonicalName]
}
}
override fun show() {
super.show()
openPicker()
updateLabels()
isSaving = false
}
override fun dispose() {
}
override fun tickUpdate() {
}
} | gpl-3.0 | e8bb538ef7374d1a7cf6fd74252ae8aa | 39.12963 | 251 | 0.594462 | 4.909366 | false | false | false | false |
allotria/intellij-community | platform/workspaceModel/ide/src/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsArtifactEntitiesSerializer.kt | 2 | 12501 | // 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 com.intellij.workspaceModel.ide.impl.jps.serialization
import com.intellij.openapi.util.JDOMUtil
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter
import com.intellij.util.xmlb.XmlSerializer
import com.intellij.workspaceModel.storage.impl.EntityDataDelegation
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jdom.Element
import org.jetbrains.jps.model.serialization.JDomSerializationUtil
import org.jetbrains.jps.model.serialization.artifact.ArtifactPropertiesState
import org.jetbrains.jps.model.serialization.artifact.ArtifactState
import org.jetbrains.jps.util.JpsPathUtil
internal class JpsArtifactsDirectorySerializerFactory(override val directoryUrl: String) : JpsDirectoryEntitiesSerializerFactory<ArtifactEntity> {
override val componentName: String
get() = ARTIFACT_MANAGER_COMPONENT_NAME
override val entityClass: Class<ArtifactEntity>
get() = ArtifactEntity::class.java
override fun createSerializer(fileUrl: String,
entitySource: JpsFileEntitySource.FileInDirectory,
virtualFileManager: VirtualFileUrlManager): JpsArtifactEntitiesSerializer {
return JpsArtifactEntitiesSerializer(virtualFileManager.fromUrl(fileUrl), entitySource, false, virtualFileManager)
}
override fun getDefaultFileName(entity: ArtifactEntity): String {
return entity.name
}
}
private const val ARTIFACT_MANAGER_COMPONENT_NAME = "ArtifactManager"
internal class JpsArtifactsFileSerializer(fileUrl: VirtualFileUrl, entitySource: JpsFileEntitySource, virtualFileManager: VirtualFileUrlManager)
: JpsArtifactEntitiesSerializer(fileUrl, entitySource, true, virtualFileManager), JpsFileEntityTypeSerializer<ArtifactEntity> {
override val isExternalStorage: Boolean
get() = false
override val additionalEntityTypes: List<Class<out WorkspaceEntity>>
get() = listOf(ArtifactsOrderEntity::class.java)
override fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter) {
writer.saveComponent(fileUrl, ARTIFACT_MANAGER_COMPONENT_NAME, null)
}
}
/**
* This entity stores order of artifacts in ipr file. This is needed to ensure that artifact tags are saved in the same order to avoid
* unnecessary modifications of ipr file.
*/
@Suppress("unused")
internal class ArtifactsOrderEntityData : WorkspaceEntityData<ArtifactsOrderEntity>() {
lateinit var orderOfArtifacts: List<String>
override fun createEntity(snapshot: WorkspaceEntityStorage): ArtifactsOrderEntity {
return ArtifactsOrderEntity(orderOfArtifacts).also { addMetaData(it, snapshot) }
}
}
internal class ArtifactsOrderEntity(
val orderOfArtifacts: List<String>
) : WorkspaceEntityBase()
internal class ModifiableArtifactsOrderEntity : ModifiableWorkspaceEntityBase<ArtifactsOrderEntity>() {
var orderOfArtifacts: List<String> by EntityDataDelegation()
}
internal open class JpsArtifactEntitiesSerializer(override val fileUrl: VirtualFileUrl,
override val internalEntitySource: JpsFileEntitySource,
private val preserveOrder: Boolean,
private val virtualFileManager: VirtualFileUrlManager) : JpsFileEntitiesSerializer<ArtifactEntity> {
override val mainEntityClass: Class<ArtifactEntity>
get() = ArtifactEntity::class.java
override fun loadEntities(builder: WorkspaceEntityStorageBuilder,
reader: JpsFileContentReader,
errorReporter: ErrorReporter,
virtualFileManager: VirtualFileUrlManager) {
val artifactListElement = reader.loadComponent(fileUrl.url, ARTIFACT_MANAGER_COMPONENT_NAME)
if (artifactListElement == null) return
val source = internalEntitySource
val orderOfItems = ArrayList<String>()
artifactListElement.getChildren("artifact").forEach {
val state = XmlSerializer.deserialize(it, ArtifactState::class.java)
val outputUrl = virtualFileManager.fromPath(state.outputPath)
val rootElement = loadPackagingElement(state.rootElement, source, builder)
val artifactEntity = builder.addArtifactEntity(state.name, state.artifactType, state.isBuildOnMake, outputUrl,
rootElement as CompositePackagingElementEntity, source)
for (propertiesState in state.propertiesList) {
builder.addArtifactPropertiesEntity(artifactEntity, propertiesState.id, JDOMUtil.write(propertiesState.options), source)
}
orderOfItems += state.name
}
if (preserveOrder) {
val entity = builder.entities(ArtifactsOrderEntity::class.java).firstOrNull()
if (entity != null) {
builder.modifyEntity(ModifiableArtifactsOrderEntity::class.java, entity) {
orderOfArtifacts = orderOfItems
}
}
else {
builder.addEntity(ModifiableArtifactsOrderEntity::class.java, source) {
orderOfArtifacts = orderOfItems
}
}
}
}
private fun loadPackagingElement(element: Element,
source: EntitySource,
builder: WorkspaceEntityStorageBuilder): PackagingElementEntity {
fun loadElementChildren() = element.children.mapTo(ArrayList()) { loadPackagingElement(it, source, builder) }
fun getAttribute(name: String) = element.getAttributeValue(name)!!
fun getOptionalAttribute(name: String) = element.getAttributeValue(name)
fun getPathAttribute(name: String) = virtualFileManager.fromPath(element.getAttributeValue(name)!!)
return when (val typeId = getAttribute("id")) {
"root" -> builder.addArtifactRootElementEntity(loadElementChildren(), source)
"directory" -> builder.addDirectoryPackagingElementEntity(getAttribute("name"), loadElementChildren(), source)
"archive" -> builder.addArchivePackagingElementEntity(getAttribute("name"), loadElementChildren(), source)
"dir-copy" -> builder.addDirectoryCopyPackagingElementEntity(getPathAttribute("path"), source)
"file-copy" -> builder.addFileCopyPackagingElementEntity(getPathAttribute("path"), getOptionalAttribute("output-file-name"), source)
"extracted-dir" -> builder.addExtractedDirectoryPackagingElementEntity(getPathAttribute("path"), getAttribute("path-in-jar"), source)
"artifact" -> builder.addArtifactOutputPackagingElementEntity(ArtifactId(getAttribute("artifact-name")), source)
"module-output" -> builder.addModuleOutputPackagingElementEntity(ModuleId(getAttribute("name")), source)
"module-test-output" -> builder.addModuleTestOutputPackagingElementEntity(ModuleId(getAttribute("name")), source)
"module-source" -> builder.addModuleSourcePackagingElementEntity(ModuleId(getAttribute("name")), source)
"library" -> {
val moduleName = getOptionalAttribute("module-name")
val level = getAttribute("level")
val name = getOptionalAttribute("name")
val parentId = when {
moduleName != null -> LibraryTableId.ModuleLibraryTableId(ModuleId(moduleName))
else -> levelToLibraryTableId(level)
}
builder.addLibraryFilesPackagingElementEntity(LibraryId(name!!, parentId), source)
}
else -> builder.addCustomPackagingElementEntity(typeId, JDOMUtil.write(element), source)
}
}
override fun saveEntities(mainEntities: Collection<ArtifactEntity>,
entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>,
storage: WorkspaceEntityStorage,
writer: JpsFileContentWriter) {
if (mainEntities.isEmpty()) return
val componentTag = JDomSerializationUtil.createComponentElement(ARTIFACT_MANAGER_COMPONENT_NAME)
val artifactsByName = mainEntities.groupByTo(HashMap()) { it.name }
val orderOfItems = if (preserveOrder) (entities[ArtifactsOrderEntity::class.java]?.firstOrNull() as? ArtifactsOrderEntity?)?.orderOfArtifacts else null
orderOfItems?.forEach { name ->
val artifacts = artifactsByName.remove(name)
artifacts?.forEach {
componentTag.addContent(saveArtifact(it))
}
}
artifactsByName.values.forEach {
it.forEach { artifact ->
componentTag.addContent(saveArtifact(artifact))
}
}
writer.saveComponent(fileUrl.url, ARTIFACT_MANAGER_COMPONENT_NAME, componentTag)
}
private fun saveArtifact(artifact: ArtifactEntity): Element {
val artifactState = ArtifactState()
artifactState.name = artifact.name
artifactState.artifactType = artifact.artifactType
artifactState.isBuildOnMake = artifact.includeInProjectBuild
artifactState.outputPath = JpsPathUtil.urlToPath(artifact.outputUrl.url)
val customProperties = artifact.customProperties.filter { it.entitySource == artifact.entitySource }
artifactState.propertiesList = customProperties.mapTo(ArrayList()) {
ArtifactPropertiesState().apply {
id = it.providerType
options = it.propertiesXmlTag?.let { JDOMUtil.load(it) }
}
}
artifactState.rootElement = savePackagingElement(artifact.rootElement)
return XmlSerializer.serialize(artifactState, SkipDefaultsSerializationFilter())
}
private fun savePackagingElement(element: PackagingElementEntity): Element {
val tag = Element("element")
fun setId(typeId: String) = tag.setAttribute("id", typeId)
fun setAttribute(name: String, value: String) = tag.setAttribute(name, value)
fun setPathAttribute(name: String, value: VirtualFileUrl) = tag.setAttribute(name, JpsPathUtil.urlToPath(value.url))
fun saveElementChildren(composite: CompositePackagingElementEntity) {
composite.children.forEach {
tag.addContent(savePackagingElement(it))
}
}
when (element) {
is ArtifactRootElementEntity -> {
setId("root")
saveElementChildren(element)
}
is DirectoryPackagingElementEntity -> {
setId("directory")
setAttribute("name", element.directoryName)
saveElementChildren(element)
}
is ArchivePackagingElementEntity -> {
setId("archive")
setAttribute("name", element.fileName)
saveElementChildren(element)
}
is DirectoryCopyPackagingElementEntity -> {
setId("dir-copy")
setPathAttribute("path", element.directory)
}
is FileCopyPackagingElementEntity -> {
setId("file-copy")
setPathAttribute("path", element.file)
element.renamedOutputFileName?.let { setAttribute("output-file-name", it) }
}
is ExtractedDirectoryPackagingElementEntity -> {
setId("extracted-dir")
setPathAttribute("path", element.archive)
setAttribute("path-in-jar", element.pathInArchive)
}
is ArtifactOutputPackagingElementEntity -> {
setId("artifact")
setAttribute("artifact-name", element.artifact.name)
}
is ModuleOutputPackagingElementEntity -> {
setId("module-output")
setAttribute("name", element.module.name)
}
is ModuleTestOutputPackagingElementEntity -> {
setId("module-test-output")
setAttribute("name", element.module.name)
}
is ModuleSourcePackagingElementEntity -> {
setId("module-source")
setAttribute("name", element.module.name)
}
is LibraryFilesPackagingElementEntity -> {
setId("library")
val tableId = element.library.tableId
setAttribute("level", tableId.level)
setAttribute("name", element.library.name)
if (tableId is LibraryTableId.ModuleLibraryTableId) {
setAttribute("module-name", tableId.moduleId.name)
}
}
}
return tag
}
override fun toString(): String = "${javaClass.simpleName.substringAfterLast('.')}($fileUrl)"
} | apache-2.0 | cd3ac82aecefc059b473a8dfd7fa048b | 47.27027 | 155 | 0.722582 | 5.563418 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/test/scheduling/LimitingCoroutineDispatcherStressTest.kt | 1 | 1550 | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.scheduling
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import org.junit.Test
import kotlin.coroutines.*
import kotlin.test.*
class LimitingCoroutineDispatcherStressTest : SchedulerTestBase() {
init {
corePoolSize = 3
}
private val blocking = blockingDispatcher(2)
private val cpuView = view(2)
private val cpuView2 = view(2)
private val concurrentWorkers = atomic(0)
private val iterations = 25_000 * stressTestMultiplierSqrt
@Test
fun testCpuLimitNotExtended() = runBlocking<Unit> {
val tasks = ArrayList<Deferred<*>>(iterations * 2)
repeat(iterations) {
tasks += task(cpuView, 3)
tasks += task(cpuView2, 3)
}
tasks.awaitAll()
}
@Test
fun testCpuLimitWithBlocking() = runBlocking<Unit> {
val tasks = ArrayList<Deferred<*>>(iterations * 2)
repeat(iterations) {
tasks += task(cpuView, 4)
tasks += task(blocking, 4)
}
tasks.awaitAll()
}
private fun task(ctx: CoroutineContext, maxLimit: Int): Deferred<Unit> = GlobalScope.async(ctx) {
try {
val currentlyExecuting = concurrentWorkers.incrementAndGet()
assertTrue(currentlyExecuting <= maxLimit, "Executing: $currentlyExecuting, max limit: $maxLimit")
} finally {
concurrentWorkers.decrementAndGet()
}
}
}
| apache-2.0 | c8c7a8f37c62473d98246ebc286d6cae | 27.181818 | 110 | 0.640645 | 4.441261 | false | true | false | false |
spring-projects/spring-framework | spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/server/RouterFunctionDsl.kt | 1 | 32040 | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.function.server
import org.springframework.core.io.Resource
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.HttpStatusCode
import org.springframework.http.MediaType
import reactor.core.publisher.Mono
import java.net.URI
import java.util.function.Supplier
/**
* Allow to create easily a WebFlux.fn [RouterFunction] with a [Reactive router Kotlin DSL][RouterFunctionDsl].
*
* Example:
*
* ```
* @Configuration
* class RouterConfiguration {
*
* @Bean
* fun mainRouter(userHandler: UserHandler) = router {
* accept(TEXT_HTML).nest {
* (GET("/user/") or GET("/users/")).invoke(userHandler::findAllView)
* GET("/users/{login}", userHandler::findViewById)
* }
* accept(APPLICATION_JSON).nest {
* (GET("/api/user/") or GET("/api/users/")).invoke(userHandler::findAll)
* POST("/api/users/", userHandler::create)
* }
* }
*
* }
* ```
* @author Sebastien Deleuze
* @see coRouter
* @since 5.0
*/
fun router(routes: RouterFunctionDsl.() -> Unit) = RouterFunctionDsl(routes).build()
/**
* Provide a WebFlux.fn [RouterFunction] Reactive Kotlin DSL created by [`router { }`][router] in order to be able to write idiomatic Kotlin code.
*
* @author Sebastien Deleuze
* @author Yevhenii Melnyk
* @author Arjen Poutsma
* @since 5.0
*/
class RouterFunctionDsl internal constructor (private val init: RouterFunctionDsl.() -> Unit) {
@PublishedApi
internal val builder = RouterFunctions.route()
/**
* Return a composed request predicate that tests against both this predicate AND
* the [other] predicate (String processed as a path predicate). When evaluating the
* composed predicate, if this predicate is `false`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.and
* @see RequestPredicates.path
*/
infix fun RequestPredicate.and(other: String): RequestPredicate = this.and(path(other))
/**
* Return a composed request predicate that tests against both this predicate OR
* the [other] predicate (String processed as a path predicate). When evaluating the
* composed predicate, if this predicate is `true`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.or
* @see RequestPredicates.path
*/
infix fun RequestPredicate.or(other: String): RequestPredicate = this.or(path(other))
/**
* Return a composed request predicate that tests against both this predicate (String
* processed as a path predicate) AND the [other] predicate. When evaluating the
* composed predicate, if this predicate is `false`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.and
* @see RequestPredicates.path
*/
infix fun String.and(other: RequestPredicate): RequestPredicate = path(this).and(other)
/**
* Return a composed request predicate that tests against both this predicate (String
* processed as a path predicate) OR the [other] predicate. When evaluating the
* composed predicate, if this predicate is `true`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.or
* @see RequestPredicates.path
*/
infix fun String.or(other: RequestPredicate): RequestPredicate = path(this).or(other)
/**
* Return a composed request predicate that tests against both this predicate AND
* the [other] predicate. When evaluating the composed predicate, if this
* predicate is `false`, then the [other] predicate is not evaluated.
* @see RequestPredicate.and
*/
infix fun RequestPredicate.and(other: RequestPredicate): RequestPredicate = this.and(other)
/**
* Return a composed request predicate that tests against both this predicate OR
* the [other] predicate. When evaluating the composed predicate, if this
* predicate is `true`, then the [other] predicate is not evaluated.
* @see RequestPredicate.or
*/
infix fun RequestPredicate.or(other: RequestPredicate): RequestPredicate = this.or(other)
/**
* Return a predicate that represents the logical negation of this predicate.
*/
operator fun RequestPredicate.not(): RequestPredicate = this.negate()
/**
* Route to the given router function if the given request predicate applies. This
* method can be used to create *nested routes*, where a group of routes share a
* common path (prefix), header, or other request predicate.
* @see RouterFunctions.nest
*/
fun RequestPredicate.nest(init: RouterFunctionDsl.() -> Unit) {
builder.nest(this, Supplier { RouterFunctionDsl(init).build() })
}
/**
* Route to the given router function if the given request predicate (String
* processed as a path predicate) applies. This method can be used to create
* *nested routes*, where a group of routes share a common path
* (prefix), header, or other request predicate.
* @see RouterFunctions.nest
* @see RequestPredicates.path
*/
fun String.nest(init: RouterFunctionDsl.() -> Unit) {
builder.path(this, Supplier { RouterFunctionDsl(init).build() })
}
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests.
* @since 5.3
*/
fun GET(f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.GET { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun GET(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.GET(pattern) { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun GET(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.GET(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun GET(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.GET(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `GET`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.GET
*/
fun GET(pattern: String): RequestPredicate = RequestPredicates.GET(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests.
* @since 5.3
*/
fun HEAD(f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.HEAD { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun HEAD(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.HEAD(pattern) { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun HEAD(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.HEAD(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun HEAD(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.HEAD(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `HEAD`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.HEAD
*/
fun HEAD(pattern: String): RequestPredicate = RequestPredicates.HEAD(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests.
* @since 5.3
*/
fun POST(f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.POST { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun POST(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.POST(pattern) { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun POST(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.POST(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun POST(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.POST(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `POST`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.POST
*/
fun POST(pattern: String): RequestPredicate = RequestPredicates.POST(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests.
* @since 5.3
*/
fun PUT(f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.PUT { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun PUT(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.PUT(pattern) { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun PUT(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.PUT(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun PUT(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.PUT(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `PUT`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.PUT
*/
fun PUT(pattern: String): RequestPredicate = RequestPredicates.PUT(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests.
* @since 5.3
*/
fun PATCH(f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.PATCH { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun PATCH(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.PATCH(pattern) { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun PATCH(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.PATCH(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun PATCH(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.PATCH(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `PATCH`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `PATCH` and if the given pattern
* matches against the request path
*/
fun PATCH(pattern: String): RequestPredicate = RequestPredicates.PATCH(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests.
* @since 5.3
*/
fun DELETE(f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.DELETE { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun DELETE(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.DELETE(pattern) { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun DELETE(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.DELETE(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun DELETE(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.DELETE(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `DELETE`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `DELETE` and if the given pattern
* matches against the request path
*/
fun DELETE(pattern: String): RequestPredicate = RequestPredicates.DELETE(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests.
* @since 5.3
*/
fun OPTIONS(f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.OPTIONS { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun OPTIONS(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.OPTIONS(pattern) { f(it).cast(ServerResponse::class.java) }
}
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun OPTIONS(predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.OPTIONS(predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun OPTIONS(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.OPTIONS(pattern, predicate, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) })
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `OPTIONS`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `OPTIONS` and if the given pattern
* matches against the request path
*/
fun OPTIONS(pattern: String): RequestPredicate = RequestPredicates.OPTIONS(pattern)
/**
* Route to the given handler function if the given accept predicate applies.
* @see RouterFunctions.route
*/
fun accept(mediaType: MediaType, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.add(RouterFunctions.route(RequestPredicates.accept(mediaType), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }))
}
/**
* Return a [RequestPredicate] that tests if the request's
* [accept][ServerRequest.Headers.accept] header is
* [compatible][MediaType.isCompatibleWith] with any of the given media types.
* @param mediaTypes the media types to match the request's accept header against
* @return a predicate that tests the request's accept header against the given media types
*/
fun accept(vararg mediaTypes: MediaType): RequestPredicate = RequestPredicates.accept(*mediaTypes)
/**
* Route to the given handler function if the given contentType predicate applies.
* @see RouterFunctions.route
*/
fun contentType(mediaTypes: MediaType, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.add(RouterFunctions.route(RequestPredicates.contentType(mediaTypes), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }))
}
/**
* Return a [RequestPredicate] that tests if the request's
* [content type][ServerRequest.Headers.contentType] is
* [included][MediaType.includes] by any of the given media types.
* @param mediaTypes the media types to match the request's content type against
* @return a predicate that tests the request's content type against the given media types
*/
fun contentType(vararg mediaTypes: MediaType): RequestPredicate = RequestPredicates.contentType(*mediaTypes)
/**
* Route to the given handler function if the given headers predicate applies.
* @see RouterFunctions.route
*/
fun headers(headersPredicate: (ServerRequest.Headers) -> Boolean, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.add(RouterFunctions.route(RequestPredicates.headers(headersPredicate), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }))
}
/**
* Return a [RequestPredicate] that tests the request's headers against the given headers predicate.
* @param headersPredicate a predicate that tests against the request headers
* @return a predicate that tests against the given header predicate
*/
fun headers(headersPredicate: (ServerRequest.Headers) -> Boolean): RequestPredicate =
RequestPredicates.headers(headersPredicate)
/**
* Route to the given handler function if the given method predicate applies.
* @see RouterFunctions.route
*/
fun method(httpMethod: HttpMethod, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.add(RouterFunctions.route(RequestPredicates.method(httpMethod), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }))
}
/**
* Return a [RequestPredicate] that tests against the given HTTP method.
* @param httpMethod the HTTP method to match to
* @return a predicate that tests against the given HTTP method
*/
fun method(httpMethod: HttpMethod): RequestPredicate = RequestPredicates.method(httpMethod)
/**
* Route to the given handler function if the given path predicate applies.
* @see RouterFunctions.route
*/
fun path(pattern: String, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.add(RouterFunctions.route(RequestPredicates.path(pattern), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }))
}
/**
* Return a [RequestPredicate] that tests the request path against the given path pattern.
* @see RequestPredicates.path
*/
fun path(pattern: String): RequestPredicate = RequestPredicates.path(pattern)
/**
* Route to the given handler function if the given pathExtension predicate applies.
* @see RouterFunctions.route
*/
fun pathExtension(extension: String, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.add(RouterFunctions.route(RequestPredicates.pathExtension(extension), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }))
}
/**
* Return a [RequestPredicate] that matches if the request's path has the given extension.
* @param extension the path extension to match against, ignoring case
* @return a predicate that matches if the request's path has the given file extension
*/
fun pathExtension(extension: String): RequestPredicate = RequestPredicates.pathExtension(extension)
/**
* Route to the given handler function if the given pathExtension predicate applies.
* @see RouterFunctions.route
*/
fun pathExtension(predicate: (String) -> Boolean, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.add(RouterFunctions.route(RequestPredicates.pathExtension(predicate), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }))
}
/**
* Return a [RequestPredicate] that matches if the request's path matches the given
* predicate.
* @see RequestPredicates.pathExtension
*/
fun pathExtension(predicate: (String) -> Boolean): RequestPredicate =
RequestPredicates.pathExtension(predicate)
/**
* Route to the given handler function if the given queryParam predicate applies.
* @see RouterFunctions.route
*/
fun queryParam(name: String, predicate: (String) -> Boolean, f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.add(RouterFunctions.route(RequestPredicates.queryParam(name, predicate), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }))
}
/**
* Return a [RequestPredicate] that tests the request's query parameter of the given name
* against the given predicate.
* @param name the name of the query parameter to test against
* @param predicate the predicate to test against the query parameter value
* @return a predicate that matches the given predicate against the query parameter of the given name
* @see ServerRequest#queryParam(String)
*/
fun queryParam(name: String, predicate: (String) -> Boolean): RequestPredicate =
RequestPredicates.queryParam(name, predicate)
/**
* Route to the given handler function if the given request predicate applies.
* @see RouterFunctions.route
*/
operator fun RequestPredicate.invoke(f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.add(RouterFunctions.route(this, HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }))
}
/**
* Route to the given handler function if the given predicate (String
* processed as a path predicate) applies.
* @see RouterFunctions.route
*/
operator fun String.invoke(f: (ServerRequest) -> Mono<out ServerResponse>) {
builder.add(RouterFunctions.route(RequestPredicates.path(this), HandlerFunction<ServerResponse> { f(it).cast(ServerResponse::class.java) }))
}
/**
* Route requests that match the given pattern to resources relative to the given root location.
* @see RouterFunctions.resources
*/
fun resources(path: String, location: Resource) {
builder.resources(path, location)
}
/**
* Route to resources using the provided lookup function. If the lookup function provides a
* [Resource] for the given request, it will be it will be exposed using a
* [HandlerFunction] that handles GET, HEAD, and OPTIONS requests.
*/
fun resources(lookupFunction: (ServerRequest) -> Mono<Resource>) {
builder.resources(lookupFunction)
}
/**
* Merge externally defined router functions into this one.
* @param routerFunction the router function to be added
* @since 5.2
*/
fun add(routerFunction: RouterFunction<ServerResponse>) {
builder.add(routerFunction)
}
/**
* Filters all routes created by this router with the given filter function. Filter
* functions are typically used to address cross-cutting concerns, such as logging,
* security, etc.
* @param filterFunction the function to filter all routes built by this router
* @since 5.2
*/
fun filter(filterFunction: (ServerRequest, (ServerRequest) -> Mono<ServerResponse>) -> Mono<ServerResponse>) {
builder.filter { request, next ->
filterFunction(request) {
next.handle(it)
}
}
}
/**
* Filter the request object for all routes created by this builder with the given request
* processing function. Filters are typically used to address cross-cutting concerns, such
* as logging, security, etc.
* @param requestProcessor a function that transforms the request
* @since 5.2
*/
fun before(requestProcessor: (ServerRequest) -> ServerRequest) {
builder.before(requestProcessor)
}
/**
* Filter the response object for all routes created by this builder with the given response
* processing function. Filters are typically used to address cross-cutting concerns, such
* as logging, security, etc.
* @param responseProcessor a function that transforms the response
* @since 5.2
*/
fun after(responseProcessor: (ServerRequest, ServerResponse) -> ServerResponse) {
builder.after(responseProcessor)
}
/**
* Filters all exceptions that match the predicate by applying the given response provider
* function.
* @param predicate the type of exception to filter
* @param responseProvider a function that creates a response
* @since 5.2
*/
fun onError(predicate: (Throwable) -> Boolean, responseProvider: (Throwable, ServerRequest) -> Mono<ServerResponse>) {
builder.onError(predicate, responseProvider)
}
/**
* Filters all exceptions that match the predicate by applying the given response provider
* function.
* @param E the type of exception to filter
* @param responseProvider a function that creates a response
* @since 5.2
*/
inline fun <reified E : Throwable> onError(noinline responseProvider: (Throwable, ServerRequest) -> Mono<ServerResponse>) {
builder.onError({it is E}, responseProvider)
}
/**
* Add an attribute with the given name and value to the last route built with this builder.
* @param name the attribute name
* @param value the attribute value
* @since 6.0
*/
fun withAttribute(name: String, value: Any) {
builder.withAttribute(name, value)
}
/**
* Manipulate the attributes of the last route built with the given consumer.
*
* The map provided to the consumer is "live", so that the consumer can be used
* to [overwrite][MutableMap.put] existing attributes,
* [remove][MutableMap.remove] attributes, or use any of the other
* [MutableMap] methods.
* @param attributesConsumer a function that consumes the attributes map
* @since 6.0
*/
fun withAttributes(attributesConsumer: (MutableMap<String, Any>) -> Unit) {
builder.withAttributes(attributesConsumer)
}
/**
* Return a composed routing function created from all the registered routes.
* @since 5.1
*/
internal fun build(): RouterFunction<ServerResponse> {
init()
return builder.build()
}
/**
* Create a builder with the status code and headers of the given response.
* @param other the response to copy the status and headers from
* @return the created builder
* @since 5.1
*/
fun from(other: ServerResponse): ServerResponse.BodyBuilder =
ServerResponse.from(other)
/**
* Create a builder with the given HTTP status.
* @param status the response status
* @return the created builder
* @since 5.1
*/
fun status(status: HttpStatusCode): ServerResponse.BodyBuilder =
ServerResponse.status(status)
/**
* Create a builder with the given HTTP status.
* @param status the response status
* @return the created builder
* @since 5.1
*/
fun status(status: Int): ServerResponse.BodyBuilder =
ServerResponse.status(status)
/**
* Create a builder with the status set to [200 OK][HttpStatus.OK].
* @return the created builder
* @since 5.1
*/
fun ok(): ServerResponse.BodyBuilder =
ServerResponse.ok()
/**
* Create a new builder with a [201 Created][HttpStatus.CREATED] status
* and a location header set to the given URI.
* @param location the location URI
* @return the created builder
* @since 5.1
*/
fun created(location: URI): ServerResponse.BodyBuilder =
ServerResponse.created(location)
/**
* Create a builder with an [202 Accepted][HttpStatus.ACCEPTED] status.
* @return the created builder
* @since 5.1
*/
fun accepted(): ServerResponse.BodyBuilder =
ServerResponse.accepted()
/**
* Create a builder with a [204 No Content][HttpStatus.NO_CONTENT] status.
* @return the created builder
* @since 5.1
*/
fun noContent(): ServerResponse.HeadersBuilder<*> =
ServerResponse.noContent()
/**
* Create a builder with a [303 See Other][HttpStatus.SEE_OTHER]
* status and a location header set to the given URI.
* @param location the location URI
* @return the created builder
* @since 5.1
*/
fun seeOther(location: URI): ServerResponse.BodyBuilder =
ServerResponse.seeOther(location)
/**
* Create a builder with a [307 Temporary Redirect][HttpStatus.TEMPORARY_REDIRECT]
* status and a location header set to the given URI.
* @param location the location URI
* @return the created builder
* @since 5.1
*/
fun temporaryRedirect(location: URI): ServerResponse.BodyBuilder =
ServerResponse.temporaryRedirect(location)
/**
* Create a builder with a [308 Permanent Redirect][HttpStatus.PERMANENT_REDIRECT]
* status and a location header set to the given URI.
* @param location the location URI
* @return the created builder
* @since 5.1
*/
fun permanentRedirect(location: URI): ServerResponse.BodyBuilder =
ServerResponse.permanentRedirect(location)
/**
* Create a builder with a [400 Bad Request][HttpStatus.BAD_REQUEST] status.
* @return the created builder
* @since 5.1
*/
fun badRequest(): ServerResponse.BodyBuilder =
ServerResponse.badRequest()
/**
* Create a builder with a [404 Not Found][HttpStatus.NOT_FOUND] status.
* @return the created builder
* @since 5.1
*/
fun notFound(): ServerResponse.HeadersBuilder<*> =
ServerResponse.notFound()
/**
* Create a builder with an
* [422 Unprocessable Entity][HttpStatus.UNPROCESSABLE_ENTITY] status.
* @return the created builder
* @since 5.1
*/
fun unprocessableEntity(): ServerResponse.BodyBuilder =
ServerResponse.unprocessableEntity()
}
| apache-2.0 | 010881f586fad6e6ee3042adbfb50e62 | 36.517564 | 159 | 0.728184 | 4.1098 | false | false | false | false |
zdary/intellij-community | platform/platform-tests/testSrc/com/intellij/serviceContainer/ConstructorInjectionTest.kt | 1 | 2173 | // 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.serviceContainer
import com.intellij.openapi.components.Service
import com.intellij.openapi.extensions.DefaultPluginDescriptor
import com.intellij.testFramework.PlatformTestUtil
import org.junit.Assert
import org.junit.Test
class ConstructorInjectionTest {
private val pluginDescriptor = DefaultPluginDescriptor("test")
@Test
fun `interface extension`() {
val componentManager = TestComponentManager(isGetComponentAdapterOfTypeCheckEnabled = false)
val area = componentManager.extensionArea
val point = area.registerPoint("bar", Bar::class.java, pluginDescriptor)
@Suppress("DEPRECATION")
point.registerExtension(BarImpl())
componentManager.instantiateClassWithConstructorInjection(Foo::class.java, Foo::class.java, pluginDescriptor.pluginId)
}
//@Test
//fun `resolve light service`() {
// val componentManager = TestComponentManager()
// componentManager.instantiateClassWithConstructorInjection(BarServiceClient::class.java, BarServiceClient::class.java.name, pluginDescriptor.pluginId)
//}
@Test
fun `light service getService() performance`() {
val componentManager = TestComponentManager()
Assert.assertNotNull(componentManager.getService(BarService::class.java))
PlatformTestUtil.startPerformanceTest("getService() must be fast for cached service", 1000) {
for (i in 0..30_000_000) {
Assert.assertNotNull(componentManager.getService(BarService::class.java))
}
}.assertTiming()
}
@Test
fun `constructor with bool`() {
val componentManager = TestComponentManager()
componentManager.registerService(ConstructorWithBoolean::class.java, ConstructorWithBoolean::class.java, testPluginDescriptor, false)
componentManager.getService(ConstructorWithBoolean::class.java)
}
}
private interface Bar
private class BarImpl : Bar
private class Foo(@Suppress("UNUSED_PARAMETER") bar: BarImpl)
@Service
private class BarService
//private class BarServiceClient(@Suppress("UNUSED_PARAMETER") bar: BarService) | apache-2.0 | 7ccd507792db87ec4f44d148dd854271 | 36.482759 | 155 | 0.777266 | 4.734205 | false | true | false | false |
leafclick/intellij-community | platform/workspaceModel-ide/src/com/intellij/workspace/legacyBridge/intellij/LegacyBridgeFilePointerProviderImpl.kt | 1 | 6848 | package com.intellij.workspace.legacyBridge.intellij
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.rd.attachChild
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Pair
import com.intellij.openapi.vfs.AsyncFileListener
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.openapi.vfs.pointers.VirtualFilePointerContainer
import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.MultiMap
import com.intellij.workspace.api.VirtualFileUrl
import com.intellij.workspace.virtualFileUrl
import org.jdom.Element
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
internal class LegacyBridgeFilePointerProviderImpl : LegacyBridgeFilePointerProvider, Disposable {
private var currentDisposable = nextDisposable()
private val filePointers: ConcurrentMap<VirtualFileUrl, VirtualFilePointer> = ContainerUtil.newConcurrentMap()
private val fileContainers: ConcurrentMap<LegacyBridgeFileContainer, VirtualFilePointerContainer> = ContainerUtil.newConcurrentMap()
private val fileContainerUrlsLock = ReentrantLock()
private val fileContainerUrls = MultiMap.create<VirtualFileUrl, LegacyBridgeFileContainer>()
init {
VirtualFileManager.getInstance().addAsyncFileListener(AsyncFileListener { events ->
val pointersToProcess = mutableSetOf<VirtualFileUrl>()
val containersToProcess = mutableSetOf<LegacyBridgeFileContainer>()
fileContainerUrlsLock.withLock {
fun handleUrl(url: VirtualFileUrl) {
pointersToProcess.add(url)
for (descriptor in fileContainerUrls.get(url)) {
containersToProcess.add(descriptor)
}
}
for (event in events) {
if (event is VFileMoveEvent) {
handleUrl(event.file.virtualFileUrl)
}
else if (event is VFilePropertyChangeEvent && event.isRename) {
handleUrl(event.file.virtualFileUrl)
}
}
}
object : AsyncFileListener.ChangeApplier {
override fun beforeVfsChange() {
pointersToProcess.forEach { filePointers.remove(it) }
containersToProcess.forEach { fileContainers.remove(it) }
}
}
}, this)
}
override fun dispose() = Unit
override fun getAndCacheFilePointer(url: VirtualFileUrl): VirtualFilePointer =
filePointers.getOrPut(url) {
VirtualFilePointerManager.getInstance().create(url.url, currentDisposable, object : VirtualFilePointerListener {
override fun validityChanged(pointers: Array<out VirtualFilePointer>) {
filePointers.remove(url)
}
})
}
override fun getAndCacheFileContainer(description: LegacyBridgeFileContainer): VirtualFilePointerContainer {
val existingContainer = fileContainers[description]
if (existingContainer != null) return existingContainer
val container = VirtualFilePointerManager.getInstance().createContainer(
currentDisposable,
object : VirtualFilePointerListener {
override fun validityChanged(pointers: Array<out VirtualFilePointer>) {
fileContainers.remove(description)
}
}
)
for (url in description.urls) {
container.add(url.url)
}
for (jarDirectory in description.jarDirectories) {
container.addJarDirectory(jarDirectory.directoryUrl.url, jarDirectory.recursive)
}
registerContainer(description, container)
return ReadonlyFilePointerContainer(container)
}
fun disposeAndClearCaches() {
ApplicationManager.getApplication().assertWriteAccessAllowed()
val oldDisposable = currentDisposable
currentDisposable = nextDisposable()
fileContainerUrlsLock.withLock { fileContainerUrls.clear() }
filePointers.clear()
fileContainers.clear()
Disposer.dispose(oldDisposable)
}
private fun registerContainer(description: LegacyBridgeFileContainer, container: VirtualFilePointerContainer) {
fileContainers[description] = container
fileContainerUrlsLock.withLock {
description.urls.forEach { fileContainerUrls.putValue(it, description) }
description.jarDirectories.forEach { fileContainerUrls.putValue(it.directoryUrl, description) }
}
}
private fun nextDisposable() = Disposer.newDisposable().also { this.attachChild(it) }
private class ReadonlyFilePointerContainer(val container: VirtualFilePointerContainer) : VirtualFilePointerContainer {
private fun throwReadonly(): Nothing = throw NotImplementedError("Read-Only File Pointer Container")
override fun getFiles(): Array<VirtualFile> = container.files
override fun getJarDirectories(): MutableList<Pair<String, Boolean>> = container.jarDirectories
override fun getUrls(): Array<String> = container.urls
override fun getDirectories(): Array<VirtualFile> = container.directories
override fun getList(): MutableList<VirtualFilePointer> = container.list
override fun clone(parent: Disposable): VirtualFilePointerContainer = container.clone(parent)
override fun clone(parent: Disposable, listener: VirtualFilePointerListener?): VirtualFilePointerContainer =
container.clone(parent, listener)
override fun findByUrl(url: String): VirtualFilePointer? = container.findByUrl(url)
override fun writeExternal(element: Element, childElementName: String, externalizeJarDirectories: Boolean) {
container.writeExternal(element, childElementName, externalizeJarDirectories)
}
override fun size(): Int = container.size()
override fun clear() = throwReadonly()
override fun addAll(that: VirtualFilePointerContainer) = throwReadonly()
override fun addJarDirectory(directoryUrl: String, recursively: Boolean) = throwReadonly()
override fun remove(pointer: VirtualFilePointer) = throwReadonly()
override fun removeJarDirectory(directoryUrl: String): Boolean = throwReadonly()
override fun moveUp(url: String) = throwReadonly()
override fun add(file: VirtualFile) = throwReadonly()
override fun add(url: String) = throwReadonly()
override fun readExternal(rootChild: Element, childElementName: String, externalizeJarDirectories: Boolean) =
throwReadonly()
override fun killAll() = throwReadonly()
override fun moveDown(url: String) = throwReadonly()
override fun isEmpty(): Boolean = container.isEmpty
}
}
| apache-2.0 | c36ea92f690d917a3a3f19ed2290c25d | 40.756098 | 134 | 0.764311 | 5.383648 | false | false | false | false |
JuliusKunze/kotlin-native | Interop/Indexer/src/main/kotlin/org/jetbrains/kotlin/native/interop/indexer/NativeIndex.kt | 1 | 8720 | /*
* 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.native.interop.indexer
enum class Language(val sourceFileExtension: String) {
C("c"),
OBJECTIVE_C("m")
}
interface HeaderInclusionPolicy {
/**
* Whether unused declarations from given header should be excluded.
*
* @param headerName header path relative to the appropriate include path element (e.g. `time.h` or `curl/curl.h`),
* or `null` for builtin declarations.
*/
fun excludeUnused(headerName: String?): Boolean
/**
* Whether all declarations from this header should be excluded.
*
* Note: the declarations from such headers can be actually present in the internal representation,
* but not included into the root collections.
*/
fun excludeAll(headerId: HeaderId): Boolean
// TODO: these methods should probably be combined into the only one, but it would require some refactoring.
}
data class NativeLibrary(val includes: List<String>,
val additionalPreambleLines: List<String>,
val compilerArgs: List<String>,
val headerToIdMapper: HeaderToIdMapper,
val language: Language,
val excludeSystemLibs: Boolean, // TODO: drop?
val excludeDepdendentModules: Boolean,
val headerInclusionPolicy: HeaderInclusionPolicy)
/**
* Retrieves the definitions from given C header file using given compiler arguments (e.g. defines).
*/
fun buildNativeIndex(library: NativeLibrary): NativeIndex = buildNativeIndexImpl(library)
/**
* This class describes the IR of definitions from C header file(s).
*/
abstract class NativeIndex {
abstract val structs: Collection<StructDecl>
abstract val enums: Collection<EnumDef>
abstract val objCClasses: Collection<ObjCClass>
abstract val objCProtocols: Collection<ObjCProtocol>
abstract val objCCategories: Collection<ObjCCategory>
abstract val typedefs: Collection<TypedefDef>
abstract val functions: Collection<FunctionDecl>
abstract val macroConstants: Collection<ConstantDef>
abstract val globals: Collection<GlobalDecl>
abstract val includedHeaders: Collection<HeaderId>
}
/**
* The (contents-based) header id.
* Its [value] remains valid across different runs of the indexer and the process,
* and thus can be used to 'serialize' the id.
*/
data class HeaderId(val value: String)
data class Location(val headerId: HeaderId)
interface TypeDeclaration {
val location: Location
}
/**
* C struct field.
*/
class Field(val name: String, val type: Type, val offset: Long, val typeAlign: Long)
val Field.isAligned: Boolean
get() = offset % (typeAlign * 8) == 0L
class BitField(val name: String, val type: Type, val offset: Long, val size: Int)
/**
* C struct declaration.
*/
abstract class StructDecl(val spelling: String) : TypeDeclaration {
abstract val def: StructDef?
}
/**
* C struct definition.
*
* @param hasNaturalLayout must be `false` if the struct has unnatural layout, e.g. it is `packed`.
* May be `false` even if the struct has natural layout.
*/
abstract class StructDef(val size: Long, val align: Int,
val decl: StructDecl,
val hasNaturalLayout: Boolean) {
abstract val fields: List<Field>
// TODO: merge two lists to preserve declaration order.
abstract val bitFields: List<BitField>
}
/**
* C enum value.
*/
class EnumConstant(val name: String, val value: Long, val isExplicitlyDefined: Boolean)
/**
* C enum definition.
*/
abstract class EnumDef(val spelling: String, val baseType: Type) : TypeDeclaration {
abstract val constants: List<EnumConstant>
}
sealed class ObjCContainer {
abstract val protocols: List<ObjCProtocol>
abstract val methods: List<ObjCMethod>
abstract val properties: List<ObjCProperty>
}
sealed class ObjCClassOrProtocol(val name: String) : ObjCContainer(), TypeDeclaration {
abstract val isForwardDeclaration: Boolean
}
data class ObjCMethod(
val selector: String, val encoding: String, val parameters: List<Parameter>, private val returnType: Type,
val isClass: Boolean, val nsConsumesSelf: Boolean, val nsReturnsRetained: Boolean,
val isOptional: Boolean, val isInit: Boolean
) {
fun returnsInstancetype(): Boolean = returnType is ObjCInstanceType
fun getReturnType(container: ObjCClassOrProtocol): Type = if (returnType is ObjCInstanceType) {
when (container) {
is ObjCClass -> ObjCObjectPointer(container, returnType.nullability, protocols = emptyList())
is ObjCProtocol -> ObjCIdType(returnType.nullability, protocols = listOf(container))
}
} else {
returnType
}
}
data class ObjCProperty(val name: String, val getter: ObjCMethod, val setter: ObjCMethod?) {
fun getType(container: ObjCClassOrProtocol): Type = getter.getReturnType(container)
}
abstract class ObjCClass(name: String) : ObjCClassOrProtocol(name) {
abstract val baseClass: ObjCClass?
}
abstract class ObjCProtocol(name: String) : ObjCClassOrProtocol(name)
abstract class ObjCCategory(val name: String, val clazz: ObjCClass) : ObjCContainer()
/**
* C function parameter.
*/
data class Parameter(val name: String?, val type: Type, val nsConsumed: Boolean)
/**
* C function declaration.
*/
class FunctionDecl(val name: String, val parameters: List<Parameter>, val returnType: Type, val binaryName: String,
val isDefined: Boolean, val isVararg: Boolean)
/**
* C typedef definition.
*
* ```
* typedef $aliased $name;
* ```
*/
class TypedefDef(val aliased: Type, val name: String, override val location: Location) : TypeDeclaration
abstract class ConstantDef(val name: String, val type: Type)
class IntegerConstantDef(name: String, type: Type, val value: Long) : ConstantDef(name, type)
class FloatingConstantDef(name: String, type: Type, val value: Double) : ConstantDef(name, type)
class GlobalDecl(val name: String, val type: Type, val isConst: Boolean)
/**
* C type.
*/
interface Type
interface PrimitiveType : Type
object CharType : PrimitiveType
object BoolType : PrimitiveType
data class IntegerType(val size: Int, val isSigned: Boolean, val spelling: String) : PrimitiveType
// TODO: floating type is not actually defined entirely by its size.
data class FloatingType(val size: Int, val spelling: String) : PrimitiveType
object VoidType : Type
data class RecordType(val decl: StructDecl) : Type
data class EnumType(val def: EnumDef) : Type
data class PointerType(val pointeeType: Type, val pointeeIsConst: Boolean = false) : Type
// TODO: refactor type representation and support type modifiers more generally.
data class FunctionType(val parameterTypes: List<Type>, val returnType: Type) : Type
interface ArrayType : Type {
val elemType: Type
}
data class ConstArrayType(override val elemType: Type, val length: Long) : ArrayType
data class IncompleteArrayType(override val elemType: Type) : ArrayType
data class Typedef(val def: TypedefDef) : Type
sealed class ObjCPointer : Type {
enum class Nullability {
Nullable, NonNull, Unspecified
}
abstract val nullability: Nullability
}
sealed class ObjCQualifiedPointer : ObjCPointer() {
abstract val protocols: List<ObjCProtocol>
}
data class ObjCObjectPointer(
val def: ObjCClass,
override val nullability: Nullability,
override val protocols: List<ObjCProtocol>
) : ObjCQualifiedPointer()
data class ObjCClassPointer(
override val nullability: Nullability,
override val protocols: List<ObjCProtocol>
) : ObjCQualifiedPointer()
data class ObjCIdType(
override val nullability: Nullability,
override val protocols: List<ObjCProtocol>
) : ObjCQualifiedPointer()
data class ObjCInstanceType(override val nullability: Nullability) : ObjCPointer()
data class ObjCBlockPointer(
override val nullability: Nullability,
val parameterTypes: List<Type>, val returnType: Type
) : ObjCPointer()
object UnsupportedType : Type | apache-2.0 | c9881a8413fb569208e889e1b78e9316 | 31.420074 | 119 | 0.716743 | 4.50646 | false | false | false | false |
blokadaorg/blokada | android5/app/wireguard-android/ui/src/main/java/com/wireguard/android/databinding/ObservableKeyedArrayList.kt | 1 | 1067 | /*
* Copyright © 2017-2021 WireGuard LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.wireguard.android.databinding
import androidx.databinding.ObservableArrayList
/**
* ArrayList that allows looking up elements by some key property. As the key property must always
* be retrievable, this list cannot hold `null` elements. Because this class places no
* restrictions on the order or duplication of keys, lookup by key, as well as all list modification
* operations, require O(n) time.
*/
open class ObservableKeyedArrayList<K, E : Keyed<out K>> : ObservableArrayList<E>() {
fun containsKey(key: K) = indexOfKey(key) >= 0
operator fun get(key: K): E? {
val index = indexOfKey(key)
return if (index >= 0) get(index) else null
}
open fun indexOfKey(key: K): Int {
val iterator = listIterator()
while (iterator.hasNext()) {
val index = iterator.nextIndex()
if (iterator.next()!!.key == key)
return index
}
return -1
}
}
| mpl-2.0 | 5f52a1a5c5e34c297a7ccb0f2bbdedd3 | 32.3125 | 100 | 0.65666 | 4.180392 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/arrays/kt950.kt | 2 | 205 | operator fun <K, V> MutableMap<K, V>.set(k : K, v : V) = put(k, v)
fun box() : String {
val map = HashMap<String,String>()
map["239"] = "932"
return if(map["239"] == "932") "OK" else "fail"
}
| apache-2.0 | 03d1ac9ab59e76c8728b8920f36dd338 | 28.285714 | 66 | 0.536585 | 2.594937 | false | false | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/test/TeslaCoreFluidsTestEntity.kt | 1 | 1881 | package net.ndrei.teslacorelib.test
import net.minecraft.item.EnumDyeColor
import net.minecraftforge.fluids.FluidRegistry
import net.minecraftforge.fluids.IFluidTank
import net.ndrei.teslacorelib.inventory.FluidTankType
import net.ndrei.teslacorelib.tileentities.ElectricMachine
/**
* Created by CF on 2017-06-27.
*/
class TeslaCoreFluidsTestEntity : ElectricMachine(-1) {
private lateinit var waterTank: IFluidTank
private lateinit var lavaTank: IFluidTank
private lateinit var tempTank: IFluidTank
private lateinit var outputTank: IFluidTank
//#region inventories methods
override fun initializeInventories() {
super.initializeInventories()
this.waterTank = this.addSimpleFluidTank(5000, "Water Tank", EnumDyeColor.BLUE,
43, 25, FluidTankType.INPUT, { it.fluid === FluidRegistry.WATER })
this.lavaTank = this.addSimpleFluidTank(5000, "Lava Tank", EnumDyeColor.RED,
43 + 18, 25, FluidTankType.INPUT, { it.fluid === FluidRegistry.LAVA })
this.tempTank = this.addSimpleFluidTank(5000, "Temp Tank", EnumDyeColor.LIME,
43+18+18, 25, FluidTankType.INPUT)
super.ensureFluidItems()
this.outputTank = this.addSimpleFluidTank(5000, "Output Tank", EnumDyeColor.WHITE,
43 + 18 + 18 + 18 + 18, 25, FluidTankType.OUTPUT)
}
//#endregion
override fun performWork(): Float {
arrayOf(this.waterTank, this.lavaTank, this.tempTank).forEach {
val drained = it.drain(100, false)
if ((drained != null) && (drained.amount > 0)) {
val filled = this.outputTank.fill(drained, false)
if (filled > 0) {
this.outputTank.fill(it.drain(filled, true), true)
return 1.0f
}
}
}
return 0.0f
}
}
| mit | ce4976e55455640e207c58c3fde54d34 | 33.833333 | 90 | 0.645401 | 4.405152 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/fleets/FleetExpandableStarListAdapter.kt | 1 | 7160 | package au.com.codeka.warworlds.client.game.fleets
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import au.com.codeka.warworlds.client.R
import au.com.codeka.warworlds.client.ctrl.ExpandableStarListAdapter
import au.com.codeka.warworlds.client.game.world.EmpireManager
import au.com.codeka.warworlds.client.game.world.ImageHelper
import au.com.codeka.warworlds.client.game.world.StarCollection
import au.com.codeka.warworlds.client.util.NumberFormatter.format
import au.com.codeka.warworlds.common.proto.Design
import au.com.codeka.warworlds.common.proto.Fleet
import au.com.codeka.warworlds.common.proto.Star
import au.com.codeka.warworlds.common.sim.DesignHelper
import com.google.common.base.Preconditions
import com.squareup.picasso.Picasso
import java.lang.RuntimeException
import java.util.*
/**
* Represents an [ExpandableStarListAdapter] which shows a list of fleets under each star.
*/
class FleetExpandableStarListAdapter(private val inflater: LayoutInflater, stars: StarCollection?)
: ExpandableStarListAdapter<Fleet?>(stars!!) {
private val myEmpireId: Long = EmpireManager.getMyEmpire().id
private var multiSelect = false
var selectedFleetId: Long? = null
private set
/**
* Returns the currently-selected star. This will be non-null if you have one or more fleets
* selected under the given star. If you have no fleets selected, or you have fleets selected
* under multiple stars, this will return null.
*
* @return The currently-selected [Star], or null.
*/
var selectedStar: Star? = null
private set
/** A list of fleets that are currently selected, contains more than one in multi-select mode. */
private val selectedFleetIds: MutableSet<Long> = HashSet()
/** A list of fleets which are currently disabled (you can't select them). */
private val disabledFleetIds: MutableSet<Long> = HashSet()
fun getSelectedFleetIds(): Collection<Long> {
return selectedFleetIds
}
/** Disable all fleets that match the given predicate. */
fun disableFleets(predicate: (Fleet) -> Boolean) {
disabledFleetIds.clear()
for (i in 0 until groupCount) {
val star = getStar(i)
for (fleet in star.fleets) {
if (fleet.empire_id == myEmpireId) {
if (predicate(fleet)) {
disabledFleetIds.add(fleet.id)
}
}
}
}
}
/** After disabling fleets, this will re-enable all fleets again. */
fun enableAllFleets() {
disabledFleetIds.clear()
}
/**
* Sets whether or not we'll allow multi-select.
*
*
* When in multi-select mode, [.getSelectedFleetId] will return the first
* selected fleet, and [.getSelectedFleetIds] will return all of them. When not in
* multi-select mode, [.getSelectedFleetIds] will return a list of the one selected fleet.
*/
fun setMultiSelect(multiSelect: Boolean) {
this.multiSelect = multiSelect
if (!multiSelect) {
selectedFleetIds.clear()
if (selectedFleetId != null) {
selectedFleetIds.add(selectedFleetId!!)
}
}
}
fun setSelectedFleetId(star: Star, fleetId: Long) {
selectedFleetId = fleetId
selectedStar = star
if (multiSelect) {
selectedFleetIds.add(fleetId)
} else {
selectedFleetIds.clear()
selectedFleetIds.add(fleetId)
}
notifyDataSetChanged()
}
fun onItemClick(groupPosition: Int, childPosition: Int) {
val star = getGroup(groupPosition)
val fleet = getChild(groupPosition, childPosition)
selectedStar = if (selectedStar == null || selectedStar!!.id == star.id) {
star
} else {
null
}
if (multiSelect) {
if (!selectedFleetIds.remove(fleet!!.id)) {
selectedFleetIds.add(fleet.id)
}
} else {
selectedFleetId = fleet!!.id
selectedFleetIds.clear()
selectedFleetIds.add(fleet.id)
}
notifyDataSetChanged()
}
public override fun getNumChildren(star: Star?): Int {
var numFleets = 0
for (i in star!!.fleets.indices) {
val empireID = star.fleets[i].empire_id
if (empireID == myEmpireId) {
numFleets++
}
}
return numFleets
}
public override fun getChild(star: Star?, index: Int): Fleet {
var fleetIndex = 0
for (i in star!!.fleets.indices) {
val empireID = star.fleets[i].empire_id
if (empireID == myEmpireId) {
if (fleetIndex == index) {
return star.fleets[i]
}
fleetIndex++
}
}
throw RuntimeException("TODO: shouldn't get here")
}
override fun getChildId(star: Star?, childPosition: Int): Long {
return star!!.fleets[childPosition].id
}
public override fun getStarView(star: Star?, convertView: View?, parent: ViewGroup?): View {
var view = convertView
if (view == null) {
view = inflater.inflate(R.layout.fleets_star_row, parent, false)
}
val starIcon = view!!.findViewById<ImageView>(R.id.star_icon)
val starName = view.findViewById<TextView>(R.id.star_name)
val starType = view.findViewById<TextView>(R.id.star_type)
val fightersTotal = view.findViewById<TextView>(R.id.fighters_total)
val nonFightersTotal = view.findViewById<TextView>(R.id.nonfighters_total)
if (star == null) {
starIcon.setImageBitmap(null)
starName.text = ""
starType.text = ""
fightersTotal.text = "..."
nonFightersTotal.text = "..."
} else {
Picasso.get()
.load(ImageHelper.getStarImageUrl(view.context, star, 16, 16))
.into(starIcon)
starName.text = star.name
starType.text = star.classification.toString()
val myEmpire = Preconditions.checkNotNull(EmpireManager.getMyEmpire())
var numFighters = 0.0f
var numNonFighters = 0.0f
for (fleet in star.fleets) {
if (fleet.empire_id != myEmpire.id) {
continue
}
if (fleet.design_type == Design.DesignType.FIGHTER) {
numFighters += fleet.num_ships
} else {
numNonFighters += fleet.num_ships
}
}
fightersTotal.text = String.format(Locale.ENGLISH, "%s", format(numFighters))
nonFightersTotal.text = String.format(Locale.ENGLISH, "%s", format(numNonFighters))
}
return view
}
public override fun getChildView(star: Star?, index: Int, convertView: View?, parent: ViewGroup?): View {
var view = convertView
if (view == null) {
view = inflater.inflate(R.layout.fleets_fleet_row, parent, false)
}
if (star != null) {
val fleet = getChild(star, index)
FleetListHelper.populateFleetRow(
view as ViewGroup?, fleet, DesignHelper.getDesign(fleet.design_type))
when {
disabledFleetIds.contains(fleet.id) -> {
view!!.setBackgroundResource(R.color.list_item_disabled)
}
selectedFleetIds.contains(fleet.id) -> {
view!!.setBackgroundResource(R.color.list_item_selected)
}
else -> {
view!!.setBackgroundResource(android.R.color.transparent)
}
}
}
return view!!
}
} | mit | 722a670c13dd83ea0986e4540a91bc25 | 31.55 | 107 | 0.669832 | 4.09611 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/nonInnerToTopLevelClass/before/test.kt | 26 | 917 | package test
inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
class A {
class B {
class X {
}
companion object {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
object O {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
class <caret>C {
fun test() {
X()
Y()
foo(bar)
//1.extFoo(1.extBar) // conflict
O.Y()
O.foo(O.bar)
with (O) {
Y()
foo(bar)
1.extFoo(1.extBar)
}
}
}
}
} | apache-2.0 | a374fa323fd58ae926ca10af6417d7a5 | 16 | 75 | 0.322792 | 4.225806 | false | false | false | false |
smmribeiro/intellij-community | platform/credential-store/src/keePass/BaseKeePassCredentialStore.kt | 14 | 2307 | // 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.credentialStore.keePass
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.CredentialStore
import com.intellij.credentialStore.Credentials
import com.intellij.credentialStore.SERVICE_NAME_PREFIX
import com.intellij.credentialStore.kdbx.KeePassDatabase
import com.intellij.util.text.nullize
internal const val ROOT_GROUP_NAME = SERVICE_NAME_PREFIX
abstract class BaseKeePassCredentialStore : CredentialStore {
protected abstract val db: KeePassDatabase
override fun get(attributes: CredentialAttributes): Credentials? {
val group = db.rootGroup.getGroup(ROOT_GROUP_NAME) ?: return null
val userName = attributes.userName.nullize()
// opposite to set, on get if user name is specified, find using specified username,
// otherwise, if for some reasons there are several matches by service name, incorrect result can be returned
// (on get we cannot punish/judge and better to return the most correct result if possible)
val entry = group.getEntry(attributes.serviceName, userName.nullize()) ?: return null
return Credentials(userName ?: entry.userName, entry.password?.get())
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
if (credentials == null) {
db.rootGroup.getGroup(ROOT_GROUP_NAME)?.removeEntry(attributes.serviceName, attributes.userName.nullize())
}
else {
val group = db.rootGroup.getOrCreateGroup(ROOT_GROUP_NAME)
val userName = attributes.userName.nullize() ?: credentials.userName
// should be the only credentials per service name - find without user name
var entry = group.getEntry(attributes.serviceName, if (attributes.serviceName == SERVICE_NAME_PREFIX) userName else null)
if (entry == null) {
entry = group.createEntry(attributes.serviceName, userName)
}
else {
entry.userName = userName
}
entry.password = if (attributes.isPasswordMemoryOnly || credentials.password == null) null else db.protectValue(credentials.password!!)
}
if (db.isDirty) {
markDirty()
}
}
protected abstract fun markDirty()
} | apache-2.0 | e6e2d36601e3ebf387f88acfec2c8ae4 | 45.16 | 141 | 0.747724 | 4.586481 | false | false | false | false |
kivensolo/UiUsingListView | module-Player/src/main/java/com/zeke/play/view/controller/BottomBarController.kt | 1 | 4087 | package com.zeke.play.view.controller
import android.text.TextUtils
import android.view.View
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import com.kingz.utils.ktx.getSystemTime
import com.module.tools.ViewUtils
import com.zeke.kangaroo.utils.TimeUtils
import com.zeke.module_player.R
import com.zeke.play.constants.PlayMode
/**
* author:KingZ
* date:2019/7/31
* description:底部工具栏Controller
* //TODO 直播时不能拖动
*
* 当前底部控制器,是包含了多种UI排列的效果,全部组件参见
* player_view_controller_basic_new.xml
*/
class BottomBarController(view: View) : BaseController() {
private var liveTipsView: TextView? = null
private var playPauseChk: CheckBox? = null
private var nextImg: ImageView? = null
private val seekBar: SeekBar
private val currentTimeView: TextView
private val durationTimeView: TextView
private var qualityTxt: TextView? = null
private var fullScreenImg: ImageView? = null
private var playMode = PlayMode.VOD
fun setPosition(position: Long) {
if (isLiveMode) {
seekBar.progress = 1
} else {
seekBar.progress = position.toInt()
currentTimeView.text = TimeUtils.generateTime(position)
}
}
fun setDuration(duration: Long) {
if (isLiveMode) {
durationTimeView.text = getSystemTime()
seekBar.max = 1
} else {
durationTimeView.text = TimeUtils.generateTime(duration)
seekBar.max = duration.toInt()
}
}
fun onProgressUpdate(position: Long,duration: Long){
setPosition(position)
setDuration(duration)
//TODO 增加功能:隐藏时,是否在播放器底部显示进度条
}
fun setPlayMode(@PlayMode mode: String) {
playMode = mode
}
fun showPlayState() {
playPauseChk?.isChecked = true
}
fun showPauseState() {
playPauseChk?.isChecked = false
}
@Deprecated("废弃")
val isInPlayState: Boolean
get() = playPauseChk?.isChecked?:false
fun setOnSeekBarChangeListener(listener: SeekBar.OnSeekBarChangeListener?) {
seekBar.setOnSeekBarChangeListener(listener)
}
fun setOnClickListener(listener: View.OnClickListener?) {
nextImg?.setOnClickListener(listener)
qualityTxt?.setOnClickListener(listener)
fullScreenImg?.setOnClickListener(listener)
liveTipsView?.setOnClickListener(listener)
playPauseChk?.setOnClickListener(listener)
}
override fun show() { // qualityTxt.setVisibility(View.GONE);
if (isLiveMode) {
liveTipsView?.visibility = View.VISIBLE
currentTimeView.visibility = View.GONE
} else {
liveTipsView?.visibility = View.GONE
currentTimeView.visibility = View.VISIBLE
}
nextImg?.visibility = View.GONE
if (ViewUtils.isLandScape(rootView)) {
fullScreenImg?.visibility = View.GONE
} else {
fullScreenImg?.visibility = View.VISIBLE
}
seekBar.visibility = View.VISIBLE
durationTimeView.visibility = View.VISIBLE
playPauseChk?.visibility = View.VISIBLE
rootView.visibility = View.VISIBLE
}
private val isLiveMode: Boolean
private get() = TextUtils.equals(playMode, PlayMode.LIVE)
init {
rootView = view.findViewById(R.id.player_bar_bottom)
liveTipsView = rootView.findViewById(R.id.live_flag)
playPauseChk = rootView.findViewById(R.id.play_pause)
nextImg = rootView.findViewById(R.id.play_next)
seekBar = rootView.findViewById(R.id.player_seekbar_progress)
currentTimeView = rootView.findViewById(R.id.player_txt_current_time)
durationTimeView = rootView.findViewById(R.id.player_txt_all_time)
qualityTxt = rootView.findViewById(R.id.tv_quality)
fullScreenImg = rootView.findViewById(R.id.fullscreen_icon)
}
} | gpl-2.0 | 8061bacce38912e7b7ab774e01e1f229 | 31.442623 | 80 | 0.673995 | 4.441077 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/nanovg/src/templates/kotlin/nanovg/templates/nanovg_bgfx.kt | 4 | 3282 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package nanovg.templates
import org.lwjgl.generator.*
import nanovg.*
import java.io.*
val nanovg_bgfx = "NanoVGBGFX".dependsOn(Module.BGFX)?.nativeClass(Module.NANOVG, prefix = "NVG", binding = object : SimpleBinding(Module.NANOVG, "BGFX.getLibrary()") {
override fun PrintWriter.generateFunctionSetup(nativeClass: NativeClass) {
generateFunctionsClass(nativeClass, "\n$t/** Contains the function pointers loaded from bgfx. */")
}
}) {
documentation = "Implementation of the NanoVG API using bgfx."
javaImport("static org.lwjgl.nanovg.NanoVG.*")
NVGcontext.p(
"Create",
"",
int32_tb("_edgeaa", ""),
MapToInt..ViewId("_viewId", ""),
nullable..AllocatorI("_allocator", "")
)
void(
"Delete",
"",
NVGcontext.p("_ctx", "")
)
void(
"SetViewId",
"",
NVGcontext.p("_ctx", ""),
MapToInt..ViewId("_viewId", "")
)
uint16_t(
"GetViewId",
"",
NVGcontext.p("_ctx", "")
)
NVGLUframebufferBGFX.p(
"luCreateFramebuffer",
"",
NVGcontext.p("_ctx", ""),
int32_t("_width", ""),
int32_t("_height", ""),
int32_t("imageFlags", "")
)
void(
"luBindFramebuffer",
"",
Input..nullable..NVGLUframebufferBGFX.p("_framebuffer", "")
)
void(
"luDeleteFramebuffer",
"",
Input..NVGLUframebufferBGFX.p("_framebuffer", "")
)
void(
"luSetViewFramebuffer",
"",
MapToInt..ViewId("_view_id", ""),
Input..NVGLUframebufferBGFX.p("_framebuffer", "")
)
void(
"CreateBgfxTexture",
"",
NVGcontext.p("_ctx", ""),
TextureHandle("_id", ""),
int("_width", ""),
int("_height", ""),
int("flags", "")
)
// BGFX/NanoVG integration
// 1. Make the bgfx back-end use LWJGL's allocation functions, which are also internally used by NanoVG.
// 2. Pass NanoVG's internal functions to the bgfx back-end.
private..void(
"org_lwjgl_nanovg_setup",
"",
opaque_p("realloc", ""),
opaque_p("free", ""),
opaque_p("nvgCreateInternal", ""),
opaque_p("nvgInternalParams", ""),
opaque_p("nvgDeleteInternal", ""),
noPrefix = true
)
customMethod("""
static {
MemoryAllocator allocator = getAllocator(Configuration.DEBUG_MEMORY_ALLOCATOR_INTERNAL.get(true));
org_lwjgl_nanovg_setup(
allocator.getRealloc(),
allocator.getFree(),
nvgCreateInternal,
nvgInternalParams,
nvgDeleteInternal
);
}""")
customMethod("""
private static class BGFX {
private static final SharedLibrary library;
static {
try {
library = (SharedLibrary)Class.forName("org.lwjgl.bgfx.BGFX").getMethod("getLibrary").invoke(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static SharedLibrary getLibrary() {
return library;
}
}
""")
} | bsd-3-clause | 1813cbe5cbb8170cd6dda42b9d4cc7cc | 22.45 | 168 | 0.540524 | 4.387701 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/vm/migrate/kvm/KvmMigrateVirtualMachine.kt | 2 | 3432 | package com.github.kerubistan.kerub.planner.steps.vm.migrate.kvm
import com.fasterxml.jackson.annotation.JsonTypeName
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.VirtualMachine
import com.github.kerubistan.kerub.model.expectations.NoMigrationExpectation
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.costs.ComputationCost
import com.github.kerubistan.kerub.planner.costs.Cost
import com.github.kerubistan.kerub.planner.costs.NetworkCost
import com.github.kerubistan.kerub.planner.costs.Risk
import com.github.kerubistan.kerub.planner.reservations.Reservation
import com.github.kerubistan.kerub.planner.reservations.UseHostReservation
import com.github.kerubistan.kerub.planner.reservations.VmReservation
import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStep
import com.github.kerubistan.kerub.planner.steps.InvertibleStep
import com.github.kerubistan.kerub.planner.steps.vm.migrate.MigrateVirtualMachine
import com.github.kerubistan.kerub.utils.any
import io.github.kerubistan.kroki.collections.update
import java.math.BigInteger
@JsonTypeName("kvm-migrate-vm")
data class KvmMigrateVirtualMachine(
override val vm: VirtualMachine,
override val source: Host,
override val target: Host
) : AbstractOperationalStep, MigrateVirtualMachine, InvertibleStep {
override fun isInverseOf(other: AbstractOperationalStep) =
other is KvmMigrateVirtualMachine && other.vm == vm && other.source == target && other.target == source
override fun reservations(): List<Reservation<*>> = listOf(
VmReservation(vm),
UseHostReservation(target),
UseHostReservation(source)
)
override fun take(state: OperationalState): OperationalState {
val vmDyn = requireNotNull(state.vms[vm.id]?.dynamic)
val targetHostDyn = requireNotNull(state.hosts[target.id]?.dynamic)
val sourceHostDyn = requireNotNull(state.hosts[source.id]?.dynamic)
return state.copy(
vms = state.vms.update(vm.id) {
it.copy(
dynamic = vmDyn.copy(
hostId = target.id
)
)
},
hosts = state.hosts
.update(target.id) {
it.copy(
dynamic = targetHostDyn.copy(
memFree = sourceHostDyn.memFree!! + vmDyn.memoryUsed,
memUsed = (sourceHostDyn.memUsed ?: BigInteger.ZERO - vmDyn.memoryUsed)
.coerceAtLeast(BigInteger.ZERO)
)
)
}
.update(source.id) {
it.copy(
dynamic = sourceHostDyn.copy(
memFree = sourceHostDyn.memFree!! + vmDyn.memoryUsed,
memUsed = (sourceHostDyn.memUsed ?: BigInteger.ZERO - vmDyn.memoryUsed)
.coerceAtLeast(BigInteger.ZERO)
)
)
}
)
}
override fun getCost(): List<Cost> = listOf(
/*
* TODO
* This calculates cost based on the max, which is pessimistic
* rather than realistic.
*/
NetworkCost(
hosts = listOf(source, target),
bytes = vm.memory.max.toLong()
),
ComputationCost(
host = target,
cycles = vm.memory.max.toLong()
),
ComputationCost(
host = source,
cycles = vm.memory.max.toLong()
)
) + if (vm.expectations.any<NoMigrationExpectation>()) {
// TODO: hmm, do I want to have this logic here? NoMigrationExpectationViolationDetector detects the problem
listOf(Risk(1000, comment = "broken no-migration rule"))
} else {
listOf<Cost>()
}
} | apache-2.0 | 3cbb0d5b21ddd176262c7104694b09c9 | 34.391753 | 110 | 0.725233 | 3.85618 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/generators/test/org/jetbrains/kotlin/testGenerator/generator/TestGenerator.kt | 1 | 4774 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.testGenerator.generator
import com.intellij.testFramework.TestDataPath
import org.jetbrains.kotlin.idea.artifacts.AdditionalKotlinArtifacts
import org.jetbrains.kotlin.test.*
import org.jetbrains.kotlin.testGenerator.model.*
import org.junit.runner.RunWith
import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.kotlin.idea.test.TestRoot
import java.io.File
import java.util.*
object TestGenerator {
private val commonImports = importsListOf(
TestDataPath::class,
JUnit3RunnerWithInners::class,
KotlinTestUtils::class,
TestMetadata::class,
TestRoot::class,
RunWith::class
)
fun write(workspace: TWorkspace) {
for (group in workspace.groups) {
for (suite in group.suites) {
write(suite, group)
}
}
}
private fun write(suite: TSuite, group: TGroup) {
val packageName = suite.generatedClassName.substringBeforeLast('.')
val rootModelName = suite.generatedClassName.substringAfterLast('.')
val content = buildCode {
appendCopyrightComment()
newLine()
appendLine("package $packageName;")
newLine()
appendImports(getImports(suite, group))
appendGeneratedComment()
appendAnnotation(TAnnotation<SuppressWarnings>("all"))
appendAnnotation(TAnnotation<TestRoot>(group.modulePath))
appendAnnotation(TAnnotation<TestDataPath>("\$CONTENT_ROOT"))
val singleModel = suite.models.singleOrNull()
if (singleModel != null) {
append(SuiteElement.create(group, suite, singleModel, rootModelName, isNested = false))
} else {
appendAnnotation(TAnnotation<RunWith>(JUnit3RunnerWithInners::class.java))
appendBlock("public abstract class $rootModelName extends ${suite.abstractTestClass.simpleName}") {
val children = suite.models
.map { SuiteElement.create(group, suite, it, it.testClassName, isNested = true) }
appendList(children, separator = "\n\n")
}
}
newLine()
}
val filePath = suite.generatedClassName.replace('.', '/') + ".java"
val file = File(group.testSourcesRoot, filePath)
write(file, postProcessContent(content))
}
private fun write(file: File, content: String) {
val oldContent = file.takeIf { it.isFile }?.readText() ?: ""
if (normalizeContent(content) != normalizeContent(oldContent)) {
file.writeText(content)
val path = file.toRelativeStringSystemIndependent(KotlinRoot.DIR)
println("Updated $path")
}
}
private fun normalizeContent(content: String): String = content.replace(Regex("\\R"), "\n")
private fun getImports(suite: TSuite, group: TGroup): List<String> {
val imports = (commonImports + suite.imports).toMutableList()
if (suite.models.any { it.targetBackend != TargetBackend.ANY }) {
imports += importsListOf(TargetBackend::class)
}
val superPackageName = suite.abstractTestClass.`package`.name
val selfPackageName = suite.generatedClassName.substringBeforeLast('.')
if (superPackageName != selfPackageName) {
imports += importsListOf(suite.abstractTestClass.kotlin)
}
if (group.isCompilerTestData) {
imports += "static ${AdditionalKotlinArtifacts::class.java.canonicalName}.${AdditionalKotlinArtifacts::compilerTestData.name}"
}
return imports
}
private fun postProcessContent(text: String): String {
return text.lineSequence()
.map { it.trimEnd() }
.joinToString(System.getProperty("line.separator"))
}
private fun Code.appendImports(imports: List<String>) {
if (imports.isNotEmpty()) {
imports.forEach { appendLine("import $it;") }
newLine()
}
}
private fun Code.appendCopyrightComment() {
val year = GregorianCalendar()[Calendar.YEAR]
appendLine("// Copyright 2000-$year JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.")
}
private fun Code.appendGeneratedComment() {
appendDocComment("""
This class is generated by {@link org.jetbrains.kotlin.testGenerator.generator.TestGenerator}.
DO NOT MODIFY MANUALLY.
""".trimIndent())
}
} | apache-2.0 | 920bf973f7c278c7026fe52e38eddea5 | 37.2 | 143 | 0.643486 | 5.133333 | false | true | false | false |
JetBrains/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/FinallyBlocksLowering.kt | 1 | 13554 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.lower.*
import org.jetbrains.kotlin.backend.common.*
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.impl.IrVariableImpl
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrReturnTargetSymbol
import org.jetbrains.kotlin.ir.symbols.IrReturnableBlockSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrReturnableBlockSymbolImpl
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.builders.irGet
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrVariableSymbolImpl
import org.jetbrains.kotlin.ir.types.IrSimpleType
import org.jetbrains.kotlin.ir.util.SYNTHETIC_OFFSET
import org.jetbrains.kotlin.ir.util.defaultType
import org.jetbrains.kotlin.ir.util.setDeclarationsParent
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.name.Name
internal class FinallyBlocksLowering(val context: Context): FileLoweringPass, IrElementTransformerVoidWithContext() {
private val symbols = context.ir.symbols
private interface HighLevelJump {
fun toIr(context: Context, startOffset: Int, endOffset: Int, value: IrExpression): IrExpression
}
private data class Return(val target: IrReturnTargetSymbol): HighLevelJump {
override fun toIr(context: Context, startOffset: Int, endOffset: Int, value: IrExpression)
= IrReturnImpl(startOffset, endOffset, context.irBuiltIns.nothingType, target, value)
}
private data class Break(val loop: IrLoop): HighLevelJump {
override fun toIr(context: Context, startOffset: Int, endOffset: Int, value: IrExpression)
= IrBlockImpl(startOffset, endOffset, context.irBuiltIns.nothingType, null,
statements = listOf(
value,
IrBreakImpl(startOffset, endOffset, context.irBuiltIns.nothingType, loop)
))
}
private data class Continue(val loop: IrLoop): HighLevelJump {
override fun toIr(context: Context, startOffset: Int, endOffset: Int, value: IrExpression)
= IrBlockImpl(startOffset, endOffset, context.irBuiltIns.nothingType, null,
statements = listOf(
value,
IrContinueImpl(startOffset, endOffset, context.irBuiltIns.nothingType, loop)
))
}
private abstract class Scope
private class ReturnableScope(val symbol: IrReturnTargetSymbol): Scope()
private class LoopScope(val loop: IrLoop): Scope()
private class TryScope(var expression: IrExpression,
val finallyExpression: IrExpression,
val irBuilder: IrBuilderWithScope): Scope() {
val jumps = mutableMapOf<HighLevelJump, IrReturnTargetSymbol>()
}
private val scopeStack = mutableListOf<Scope>()
private inline fun <S: Scope, R> using(scope: S, block: (S) -> R): R {
scopeStack.push(scope)
try {
return block(scope)
} finally {
scopeStack.pop()
}
}
override fun lower(irFile: IrFile) {
irFile.transformChildrenVoid(this)
}
override fun visitFunctionNew(declaration: IrFunction): IrStatement {
using(ReturnableScope(declaration.symbol)) {
return super.visitFunctionNew(declaration)
}
}
override fun visitContainerExpression(expression: IrContainerExpression): IrExpression {
if (expression !is IrReturnableBlock)
return super.visitContainerExpression(expression)
using(ReturnableScope(expression.symbol)) {
return super.visitContainerExpression(expression)
}
}
override fun visitLoop(loop: IrLoop): IrExpression {
using(LoopScope(loop)) {
return super.visitLoop(loop)
}
}
override fun visitBreak(jump: IrBreak): IrExpression {
val startOffset = jump.startOffset
val endOffset = jump.endOffset
val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset)
return performHighLevelJump(
targetScopePredicate = { it is LoopScope && it.loop == jump.loop },
jump = Break(jump.loop),
startOffset = startOffset,
endOffset = endOffset,
value = irBuilder.irGetObject(context.ir.symbols.unit)
) ?: jump
}
override fun visitContinue(jump: IrContinue): IrExpression {
val startOffset = jump.startOffset
val endOffset = jump.endOffset
val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset)
return performHighLevelJump(
targetScopePredicate = { it is LoopScope && it.loop == jump.loop },
jump = Continue(jump.loop),
startOffset = startOffset,
endOffset = endOffset,
value = irBuilder.irGetObject(context.ir.symbols.unit)
) ?: jump
}
override fun visitReturn(expression: IrReturn): IrExpression {
expression.transformChildrenVoid(this)
return performHighLevelJump(
targetScopePredicate = { it is ReturnableScope && it.symbol == expression.returnTargetSymbol },
jump = Return(expression.returnTargetSymbol),
startOffset = expression.startOffset,
endOffset = expression.endOffset,
value = expression.value
) ?: expression
}
private fun performHighLevelJump(targetScopePredicate: (Scope) -> Boolean,
jump: HighLevelJump,
startOffset: Int,
endOffset: Int,
value: IrExpression): IrExpression? {
val tryScopes = scopeStack.reversed()
.takeWhile { !targetScopePredicate(it) }
.filterIsInstance<TryScope>()
.toList()
if (tryScopes.isEmpty())
return null
return performHighLevelJump(tryScopes, 0, jump, startOffset, endOffset, value)
}
private val IrReturnTarget.returnType: IrType
get() = when (this) {
is IrConstructor -> context.irBuiltIns.unitType
is IrFunction -> returnType
is IrReturnableBlock -> type
else -> error("Unknown ReturnTarget: $this")
}
private fun performHighLevelJump(tryScopes: List<TryScope>,
index: Int,
jump: HighLevelJump,
startOffset: Int,
endOffset: Int,
value: IrExpression): IrExpression {
if (index == tryScopes.size)
return jump.toIr(context, startOffset, endOffset, value)
val currentTryScope = tryScopes[index]
currentTryScope.jumps.getOrPut(jump) {
val type = (jump as? Return)?.target?.owner?.returnType ?: value.type
val symbol = IrReturnableBlockSymbolImpl()
with(currentTryScope) {
irBuilder.run {
val inlinedFinally = irInlineFinally(symbol, type, expression, finallyExpression)
expression = performHighLevelJump(
tryScopes = tryScopes,
index = index + 1,
jump = jump,
startOffset = startOffset,
endOffset = endOffset,
value = inlinedFinally)
}
}
symbol
}.let {
return IrReturnImpl(
startOffset = startOffset,
endOffset = endOffset,
type = context.irBuiltIns.nothingType,
returnTargetSymbol = it,
value = value)
}
}
override fun visitTry(aTry: IrTry): IrExpression {
val finallyExpression = aTry.finallyExpression
?: return super.visitTry(aTry)
val startOffset = aTry.startOffset
val endOffset = aTry.endOffset
val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset)
val transformer = this
irBuilder.run {
val transformedTry = IrTryImpl(
startOffset = startOffset,
endOffset = endOffset,
type = context.irBuiltIns.nothingType
)
val transformedFinallyExpression = finallyExpression.transform(transformer, null)
val catchParameter =
IrVariableImpl(
startOffset, endOffset,
IrDeclarationOrigin.CATCH_PARAMETER,
IrVariableSymbolImpl(),
Name.identifier("t"),
symbols.throwable.owner.defaultType,
isVar = false,
isConst = false,
isLateinit = false
).apply {
parent = [email protected]
}
val syntheticTry = IrTryImpl(
startOffset = startOffset,
endOffset = endOffset,
type = context.irBuiltIns.nothingType,
tryResult = transformedTry,
catches = listOf(
irCatch(catchParameter, irBlock {
+copy(finallyExpression)
+irThrow(irGet(catchParameter))
})
),
finallyExpression = null
)
using(TryScope(syntheticTry, transformedFinallyExpression, this)) {
val fallThroughType = aTry.type
val fallThroughSymbol = IrReturnableBlockSymbolImpl()
val transformedResult = aTry.tryResult.transform(transformer, null)
transformedTry.tryResult = irReturn(fallThroughSymbol, transformedResult)
for (aCatch in aTry.catches) {
val transformedCatch = aCatch.transform(transformer, null)
transformedCatch.result = irReturn(fallThroughSymbol, transformedCatch.result)
transformedTry.catches.add(transformedCatch)
}
return irInlineFinally(fallThroughSymbol, fallThroughType, it.expression, it.finallyExpression)
}
}
}
private fun IrBuilderWithScope.irInlineFinally(symbol: IrReturnableBlockSymbol, type: IrType,
value: IrExpression,
finallyExpression: IrExpression): IrExpression {
val returnTypeClassifier = (type as? IrSimpleType)?.classifier
return when (returnTypeClassifier) {
symbols.unit, symbols.nothing -> irBlock(value, null, type) {
+irReturnableBlock(finallyExpression.startOffset, finallyExpression.endOffset, symbol, type) {
+value
}
+copy(finallyExpression)
}
else -> irBlock(value, null, type) {
val tmp = irTemporary(irReturnableBlock(finallyExpression.startOffset, finallyExpression.endOffset, symbol, type) {
+irReturn(symbol, value)
})
+copy(finallyExpression)
+irGet(tmp)
}
}
}
private inline fun <reified T : IrElement> IrBuilderWithScope.copy(element: T) =
element.deepCopyWithVariables().setDeclarationsParent(parent)
fun IrBuilderWithScope.irReturn(target: IrReturnTargetSymbol, value: IrExpression) =
IrReturnImpl(startOffset, endOffset, context.irBuiltIns.nothingType, target, value)
private inline fun IrBuilderWithScope.irReturnableBlock(startOffset: Int, endOffset: Int, symbol: IrReturnableBlockSymbol,
type: IrType, body: IrBlockBuilder.() -> Unit) =
IrReturnableBlockImpl(startOffset, endOffset, type, symbol, null,
IrBlockBuilder(context, scope, startOffset, endOffset, null, type)
.block(body).statements)
}
| apache-2.0 | da896935556a6ba59af2ee1732261e24 | 44.331104 | 131 | 0.592519 | 5.67113 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/tests/testData/highlighter/TypesAndAnnotations.kt | 1 | 811 | interface <info textAttributesKey="KOTLIN_TRAIT">TheInterface</info> {
}
class <info textAttributesKey="KOTLIN_CLASS">TheClass</info> : <info textAttributesKey="KOTLIN_TRAIT">TheInterface</info> {
}
<info textAttributesKey="KOTLIN_BUILTIN_ANNOTATION">annotation</info> class <info textAttributesKey="KOTLIN_ANNOTATION">magnificent</info>
<info textAttributesKey="KOTLIN_BUILTIN_ANNOTATION">annotation</info> class <info textAttributesKey="KOTLIN_ANNOTATION">Deprecated</info>
<info textAttributesKey="KOTLIN_ANNOTATION">@Deprecated</info>
<info textAttributesKey="KOTLIN_ANNOTATION">@magnificent</info> <info textAttributesKey="KOTLIN_BUILTIN_ANNOTATION">abstract</info> class <info textAttributesKey="KOTLIN_ABSTRACT_CLASS">AbstractClass</info><<info textAttributesKey="KOTLIN_TYPE_PARAMETER">T</info>> {
}
| apache-2.0 | 54e001bc50558e1dacf025956530baba | 66.583333 | 266 | 0.800247 | 4.407609 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/base/enums/lifecycle/FragmentLifecycle.kt | 1 | 545 | package com.sedsoftware.yaptalker.presentation.base.enums.lifecycle
import androidx.annotation.LongDef
class FragmentLifecycle {
companion object {
const val ATTACH = 0L
const val CREATE = 1L
const val START = 2L
const val RESUME = 3L
const val PAUSE = 4L
const val STOP = 5L
const val DESTROY = 6L
const val DETACH = 7L
}
@Retention(AnnotationRetention.SOURCE)
@LongDef(ATTACH, CREATE, START, RESUME, PAUSE, STOP, DESTROY, DETACH)
annotation class Event
}
| apache-2.0 | 7090cee44367395601e462889e551a28 | 24.952381 | 73 | 0.658716 | 4.160305 | false | false | false | false |
androidx/androidx | collection/collection/src/commonMain/kotlin/androidx/collection/SparseArray.kt | 3 | 3201 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.collection
import kotlin.DeprecationLevel.HIDDEN
/** Returns the number of key/value pairs in the collection. */
public inline val <T> SparseArrayCompat<T>.size: Int get() = size()
/** Returns true if the collection contains [key]. */
@Suppress("NOTHING_TO_INLINE")
public inline operator fun <T> SparseArrayCompat<T>.contains(key: Int): Boolean = containsKey(key)
/** Allows the use of the index operator for storing values in the collection. */
@Suppress("NOTHING_TO_INLINE")
public inline operator fun <T> SparseArrayCompat<T>.set(key: Int, value: T): Unit = put(key, value)
/** Creates a new collection by adding or replacing entries from [other]. */
public operator fun <T> SparseArrayCompat<T>.plus(
other: SparseArrayCompat<T>
): SparseArrayCompat<T> {
val new = SparseArrayCompat<T>(size() + other.size())
new.putAll(this)
new.putAll(other)
return new
}
/** Return the value corresponding to [key], or [defaultValue] when not present. */
@Suppress("NOTHING_TO_INLINE")
public inline fun <T> SparseArrayCompat<T>.getOrDefault(key: Int, defaultValue: T): T =
get(key, defaultValue)
/** Return the value corresponding to [key], or from [defaultValue] when not present. */
public inline fun <T> SparseArrayCompat<T>.getOrElse(key: Int, defaultValue: () -> T): T =
get(key) ?: defaultValue()
/** Return true when the collection contains elements. */
@Suppress("NOTHING_TO_INLINE")
public inline fun <T> SparseArrayCompat<T>.isNotEmpty(): Boolean = !isEmpty()
/** Removes the entry for [key] only if it is mapped to [value]. */
@Suppress("EXTENSION_SHADOWED_BY_MEMBER") // Binary API compatibility.
@Deprecated("Replaced with member function. Remove extension import!", level = HIDDEN)
public fun <T> SparseArrayCompat<T>.remove(key: Int, value: T): Boolean = remove(key, value)
/** Performs the given [action] for each key/value entry. */
public inline fun <T> SparseArrayCompat<T>.forEach(action: (key: Int, value: T) -> Unit) {
for (index in 0 until size()) {
action(keyAt(index), valueAt(index))
}
}
/** Return an iterator over the collection's keys. */
public fun <T> SparseArrayCompat<T>.keyIterator(): IntIterator = object : IntIterator() {
var index = 0
override fun hasNext() = index < size()
override fun nextInt() = keyAt(index++)
}
/** Return an iterator over the collection's values. */
public fun <T> SparseArrayCompat<T>.valueIterator(): Iterator<T> = object : Iterator<T> {
var index = 0
override fun hasNext() = index < size()
override fun next() = valueAt(index++)
}
| apache-2.0 | 0b3a3b391ce96d7bf84a31ae6f2371ee | 39.518987 | 99 | 0.709778 | 3.966543 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/BaseLayoutSpec.kt | 2 | 4351 | // 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")
package org.jetbrains.intellij.build.impl
sealed class BaseLayoutSpec(private val layout: BaseLayout) {
/**
* Register an additional module to be included into the plugin distribution. Module-level libraries from
* {@code moduleName} with scopes 'Compile' and 'Runtime' will be also copied to the 'lib' directory of the plugin.
*/
fun withModule(moduleName: String) {
layout.withModule(moduleName)
}
fun withModules(names: Iterable<String>) {
names.forEach(layout::withModule)
}
/**
* Register an additional module to be included into the plugin distribution. If {@code relativeJarPath} doesn't contain '/' (i.e. the
* JAR will be added to the plugin's classpath) this will also cause modules library from {@code moduleName} with scopes 'Compile' and
* 'Runtime' to be copied to the 'lib' directory of the plugin.
*
* @param relativeJarPath target JAR path relative to 'lib' directory of the plugin; different modules may be packed into the same JAR,
* but <strong>don't use this for new plugins</strong>; this parameter is temporary added to keep layout of old plugins.
*/
fun withModule(moduleName: String, relativeJarPath: String) {
layout.withModule(moduleName, relativeJarPath)
}
/**
* Include the project library to 'lib' directory or its subdirectory of the plugin distribution
* @param libraryName path relative to 'lib' plugin directory
*/
fun withProjectLibrary(libraryName: String) {
layout.withProjectLibrary(libraryName)
}
fun withProjectLibrary(libraryName: String, outPath: String) {
layout.includedProjectLibraries.add(ProjectLibraryData(libraryName = libraryName, packMode = LibraryPackMode.MERGED, outPath = outPath))
}
fun withProjectLibrary(libraryName: String, packMode: LibraryPackMode) {
layout.includedProjectLibraries.add(ProjectLibraryData(libraryName = libraryName, packMode = packMode))
}
fun withProjectLibrary(libraryName: String, outPath: String, packMode: LibraryPackMode) {
layout.includedProjectLibraries.add(ProjectLibraryData(libraryName = libraryName, packMode = packMode, outPath = outPath))
}
/**
* Include the module library to the plugin distribution. Please note that it makes sense to call this method only
* for additional modules which aren't copied directly to the 'lib' directory of the plugin distribution, because for ordinary modules
* their module libraries are included into the layout automatically.
* @param relativeOutputPath target path relative to 'lib' directory
*/
fun withModuleLibrary(libraryName: String, moduleName: String, relativeOutputPath: String) {
layout.withModuleLibrary(libraryName = libraryName, moduleName = moduleName, relativeOutputPath = relativeOutputPath)
}
/**
* Exclude the specified files when {@code moduleName} is packed into JAR file.
* <strong>This is a temporary method added to keep layout of some old plugins. If some files from a module shouldn't be included into the
* module JAR it's strongly recommended to move these files outside the module source roots.</strong>
* @param excludedPattern Ant-like pattern describing files to be excluded (relatively to the module output root); e.g. foo/**
* to exclude `foo` directory
*/
fun excludeFromModule(moduleName: String, excludedPattern: String) {
layout.excludeFromModule(moduleName, excludedPattern)
}
fun excludeFromModule(moduleName: String, excludedPatterns: List<String>) {
layout.excludeFromModule(moduleName, excludedPatterns)
}
/**
* Include an artifact output to the plugin distribution.
* @param artifactName name of the project configuration
* @param relativeOutputPath target path relative to 'lib' directory
*/
fun withArtifact(artifactName: String, relativeOutputPath: String) {
layout.includedArtifacts = layout.includedArtifacts.put(artifactName, relativeOutputPath)
}
/**
* Include contents of JARs of the project library {@code libraryName} into JAR {@code jarName}
*/
fun withProjectLibraryUnpackedIntoJar(libraryName: String, jarName: String) {
layout.withProjectLibraryUnpackedIntoJar(libraryName, jarName)
}
}
| apache-2.0 | 1c27f02f7fb4d4ccca7ea6125b0a9b8c | 46.813187 | 140 | 0.756838 | 4.899775 | false | false | false | false |
shogo4405/HaishinKit.java | haishinkit/src/main/java/com/haishinkit/media/Timestamp.kt | 1 | 587 | package com.haishinkit.media
internal data class Timestamp(
val scale: Long = 1L,
private var start: Long = DEFAULT_TIMESTAMP
) {
val duration: Long
get() = (nanoTime - start) / scale
var nanoTime: Long = DEFAULT_TIMESTAMP
set(value) {
if (0 < value && start == DEFAULT_TIMESTAMP) {
start = value
}
field = value
}
fun clear() {
nanoTime = DEFAULT_TIMESTAMP
start = DEFAULT_TIMESTAMP
}
companion object {
private const val DEFAULT_TIMESTAMP = -1L
}
}
| bsd-3-clause | afc03789e4e9ed5ff03f184f932cf98e | 21.576923 | 58 | 0.553663 | 4.480916 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/RepositoryModel.kt | 7 | 1487 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.intellij.openapi.util.NlsSafe
import com.jetbrains.packagesearch.intellij.plugin.extensibility.RepositoryDeclaration
import org.jetbrains.packagesearch.api.v2.ApiRepository
internal data class RepositoryModel(
val id: String?,
val name: String?,
val url: String?,
val usageInfo: List<RepositoryUsageInfo>,
val remoteInfo: ApiRepository
) {
@NlsSafe
val displayName = remoteInfo.friendlyName
fun isEquivalentTo(other: RepositoryDeclaration): Boolean {
if (id != null && id == other.id) return true
if (url != null && url == other.url) return true
return false
}
}
| apache-2.0 | e98d8ae4666b4b59ff8030985250dbfc | 37.128205 | 86 | 0.6577 | 4.750799 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/application/constraints/BaseConstrainedExecution.kt | 2 | 3394 | // 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.openapi.application.constraints
import com.intellij.openapi.application.constraints.ConstrainedExecution.ContextConstraint
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.containers.map2Array
import kotlinx.coroutines.Runnable
import org.jetbrains.annotations.ApiStatus
import java.util.function.BooleanSupplier
/**
* This class is responsible for running a task in a proper context defined using various builder methods of this class and it's
* implementations, like [com.intellij.openapi.application.AppUIExecutor.later], or generic [withConstraint].
*
* ## Implementation notes: ##
*
* The [scheduleWithinConstraints] starts checking the list of constraints, one by one, rescheduling and restarting itself
* for each unsatisfied constraint until at some point *all* of the constraints are satisfied *at once*.
*
* This ultimately ends up with [ContextConstraint.schedule] being called one by one for every constraint that needs to be scheduled.
* Finally, the runnable is called, executing the task in the properly arranged context.
*
* @author eldar
*/
abstract class BaseConstrainedExecution<E : ConstrainedExecution<E>>(protected val constraints: Array<ContextConstraint>)
: ConstrainedExecution<E>, ConstrainedExecutionScheduler {
protected abstract fun cloneWith(constraints: Array<ContextConstraint>): E
override fun withConstraint(constraint: ContextConstraint): E = cloneWith(constraints + constraint)
override fun asExecutor() = ConstrainedTaskExecutor(this, composeCancellationCondition(), composeExpiration())
override fun asCoroutineDispatcher() = createConstrainedCoroutineDispatcher(this, composeCancellationCondition(), composeExpiration())
protected open fun composeExpiration(): Expiration? = null
protected open fun composeCancellationCondition(): BooleanSupplier? = null
override fun scheduleWithinConstraints(runnable: Runnable, condition: BooleanSupplier?) =
scheduleWithinConstraints(runnable, condition, constraints)
companion object {
private val LOG = Logger.getInstance("#com.intellij.openapi.application.constraints.ConstrainedExecution")
@JvmStatic
@ApiStatus.Internal
fun scheduleWithinConstraints(runnable: Runnable, condition: BooleanSupplier?, constraints: Array<ContextConstraint>) {
val attemptChain = mutableListOf<ContextConstraint>()
fun inner() {
if (attemptChain.size > 3000) {
val lastCauses = attemptChain.takeLast(15)
LOG.error("Too many reschedule requests, probably constraints can't be satisfied all together",
*lastCauses.map2Array { it.toString() })
}
if (condition?.asBoolean == false) return
for (constraint in constraints) {
if (!constraint.isCorrectContext()) {
return constraint.schedule(Runnable {
if (!constraint.isCorrectContext()) {
LOG.error("ContextConstraint scheduled into incorrect context: $constraint",
*constraints.map2Array { it.toString() })
}
attemptChain.add(constraint)
inner()
})
}
}
runnable.run()
}
inner()
}
}
} | apache-2.0 | 5c8ad936efb1d29b31d3c35454d178cc | 44.878378 | 140 | 0.733353 | 5.17378 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/tests/test/org/jetbrains/kotlin/nj2k/AbstractNewJavaToKotlinConverterSingleFileTest.kt | 1 | 2937 | // 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.nj2k
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.LanguageLevelProjectExtension
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.codeStyle.JavaCodeStyleSettings
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.idea.test.withCustomCompilerOptions
import org.jetbrains.kotlin.j2k.AbstractJavaToKotlinConverterSingleFileTest
import org.jetbrains.kotlin.j2k.ConverterSettings
import org.jetbrains.kotlin.nj2k.postProcessing.NewJ2kPostProcessor
import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
abstract class AbstractNewJavaToKotlinConverterSingleFileTest : AbstractJavaToKotlinConverterSingleFileTest() {
override fun doTest(javaPath: String) {
val javaFile = File(javaPath)
withCustomCompilerOptions(javaFile.readText(), project, module) {
val directory = javaFile.parentFile
val expectedFileName = "${javaFile.nameWithoutExtension}.external"
val expectedFiles = directory.listFiles { _, name ->
name == "$expectedFileName.kt" || name == "$expectedFileName.java"
}!!.filterNotNull()
for (expectedFile in expectedFiles) {
addFile(expectedFile, dirName = null)
}
super.doTest(javaPath)
}
}
override fun compareResults(expectedFile: File, actual: String) {
KotlinTestUtils.assertEqualsToFile(expectedFile, actual)
}
override fun setUp() {
super.setUp()
JavaCodeStyleSettings.getInstance(project).USE_EXTERNAL_ANNOTATIONS = true
}
override fun tearDown() {
runAll(
ThrowableRunnable { JavaCodeStyleSettings.getInstance(project).USE_EXTERNAL_ANNOTATIONS = false },
ThrowableRunnable { super.tearDown() }
)
}
override fun fileToKotlin(text: String, settings: ConverterSettings, project: Project): String {
val file = createJavaFile(text)
return NewJavaToKotlinConverter(project, module, settings, IdeaJavaToKotlinServices)
.filesToKotlin(listOf(file), NewJ2kPostProcessor()).results.single()
}
override fun provideExpectedFile(javaPath: String): File =
File(javaPath.replace(".java", ".new.kt")).takeIf { it.exists() }
?: super.provideExpectedFile(javaPath)
private fun getLanguageLevel() =
if (testDataDirectory.toString().contains("newJavaFeatures")) LanguageLevel.HIGHEST else LanguageLevel.JDK_1_8
override fun getProjectDescriptor() = descriptorByFileDirective(File(testDataPath, fileName()), languageLevel = getLanguageLevel())
}
| apache-2.0 | 1d536f1581da320c0f5fe50b1e7bc340 | 44.184615 | 158 | 0.729656 | 5.072539 | false | true | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/python/testing/PyTestCustomOption.kt | 10 | 952 | // 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 com.jetbrains.python.testing
import com.jetbrains.python.PyBundle
import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant
import org.jetbrains.annotations.Nls
import java.util.*
import kotlin.reflect.KCallable
internal class PyTestCustomOption(property: KCallable<*>, vararg supportedTypes: PyRunTargetVariant) {
val name: String = property.name
val isBooleanType: Boolean = property.returnType.classifier == Boolean::class
@field:Nls
val localizedName: String
init {
localizedName = property.annotations.filterIsInstance<ConfigField>().firstOrNull()?.localizedName?.let {
PyBundle.message(it)
} ?: name
}
/**
* Types to display this option for
*/
val mySupportedTypes: EnumSet<PyRunTargetVariant> = EnumSet.copyOf(supportedTypes.asList())
}
| apache-2.0 | 9731057798d718face7cefc48503944a | 34.259259 | 140 | 0.771008 | 4.555024 | false | true | false | false |
GlobalTechnology/android-gto-support | gto-support-androidx-fragment/src/main/kotlin/org/ccci/gto/android/common/androidx/fragment/app/BaseDialogFragment.kt | 2 | 3005 | package org.ccci.gto.android.common.androidx.fragment.app
import android.os.Bundle
import android.view.LayoutInflater
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
abstract class BaseDialogFragment : DialogFragment() {
// region Lifecycle
override fun onGetLayoutInflater(savedInstanceState: Bundle?): LayoutInflater {
_dialogLifecycleOwner = FragmentDialogLifecycleOwner()
val inflater = super.onGetLayoutInflater(savedInstanceState)
initializeDialogLifecycleOwner()
return inflater
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
_dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
}
override fun onStart() {
super.onStart()
_dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_START)
}
override fun onResume() {
super.onResume()
_dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
}
override fun onPause() {
_dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
super.onPause()
}
override fun onStop() {
_dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
super.onStop()
}
override fun onDestroyView() {
_dialogLifecycleOwner?.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
super.onDestroyView()
_dialogLifecycleOwner = null
}
// endregion Lifecycle
// region DialogLifecycleOwner
private var _dialogLifecycleOwner: FragmentDialogLifecycleOwner? = null
val dialogLifecycleOwner: LifecycleOwner
get() = _dialogLifecycleOwner
?: throw IllegalStateException(
"Can't access the Fragment Dialog's LifecycleOwner when getDialog() is null " +
"i.e., before onCreateDialog() or after onDestroyView()"
)
private fun initializeDialogLifecycleOwner() {
when {
dialog != null -> _dialogLifecycleOwner!!.initialize()
_dialogLifecycleOwner!!.isInitialized ->
throw IllegalStateException("Called getDialogLifecycleOwner() but onCreateDialog() returned null")
else -> _dialogLifecycleOwner = null
}
}
// endregion DialogLifecycleOwner
}
internal class FragmentDialogLifecycleOwner : LifecycleOwner {
private var lifecycleRegistry: LifecycleRegistry? = null
internal fun initialize() {
if (lifecycleRegistry == null) {
lifecycleRegistry = LifecycleRegistry(this)
}
}
internal val isInitialized = lifecycleRegistry != null
override fun getLifecycle(): Lifecycle {
initialize()
return lifecycleRegistry!!
}
fun handleLifecycleEvent(event: Lifecycle.Event) = lifecycleRegistry!!.handleLifecycleEvent(event)
}
| mit | 7403f0934f6276aa64242210e858888d | 33.147727 | 114 | 0.700499 | 5.950495 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/extensions/IntentExtensions.kt | 1 | 1958 | package ch.rmy.android.framework.extensions
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.activity.result.ActivityResultLauncher
import androidx.core.app.ActivityOptionsCompat
import androidx.fragment.app.Fragment
import ch.rmy.android.framework.ui.IntentBuilder
import java.io.Serializable
inline fun createIntent(block: Intent.() -> Unit): Intent =
Intent().apply(block)
fun Intent.startActivity(activity: Activity) {
activity.startActivity(this)
}
fun Intent.startActivity(fragment: Fragment) {
fragment.startActivity(this)
}
fun Intent.startActivity(context: Context) {
when (context) {
is Activity -> startActivity(context)
else -> context.startActivity(this)
}
}
fun IntentBuilder.startActivity(activity: Activity) {
build(activity).startActivity(activity)
}
fun IntentBuilder.startActivity(fragment: Fragment) {
build(fragment.requireContext()).startActivity(fragment)
}
fun IntentBuilder.startActivity(context: Context) {
build(context).startActivity(context)
}
fun <T : Any?> ActivityResultLauncher<T>.launch(options: ActivityOptionsCompat? = null) {
launch(null, options)
}
@Suppress("DEPRECATION")
inline fun <reified T : Any?> Intent.getParcelable(key: String): T? =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) getParcelableExtra(key, T::class.java) else getParcelableExtra(key)
@Suppress("DEPRECATION")
inline fun <reified T : Any?> Intent.getParcelableList(key: String): List<T>? =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) getParcelableArrayListExtra(key, T::class.java) else getParcelableArrayListExtra(key)
@Suppress("DEPRECATION")
inline fun <reified T : Serializable?> Intent.getSerializable(key: String): T? =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) getSerializableExtra(key, T::class.java) else getSerializableExtra(key) as? T
| mit | 3ea30d5aa242a4c257c1c8f3b1463a4e | 33.350877 | 148 | 0.765066 | 4.020534 | false | false | false | false |
sg26565/hott-transmitter-config | HoTT-Voice/src/main/kotlin/de/treichels/hott/voice/VoiceData.kt | 1 | 3752 | package de.treichels.hott.voice
import org.apache.commons.io.IOUtils
import java.io.*
import java.nio.file.Files
import java.util.*
import javax.sound.sampled.*
import javax.sound.sampled.AudioFormat.Encoding
/**
* Representation of a single announcement in a voice data file (.vdf).
*
* @author [email protected]
*/
class VoiceData(name: String, val rawData: ByteArray) : Serializable, ObservableBase() {
companion object {
/** Default audio format 11 kHz 16-bit signed PCM mono */
private val audioFormat = AudioFormat(Encoding.PCM_SIGNED, 11025f, 16, 1, 2, 11025f, false)
fun forStream(sourceAudioStream: AudioInputStream, name: String, volume: Double = 1.0): VoiceData {
// read from stream
val sourceFormat = sourceAudioStream.format
val rate = sourceFormat.sampleRate
val channels = sourceFormat.channels
// convert to from MP3 or OGG to PCM
val pcmFormat = AudioFormat(Encoding.PCM_SIGNED, rate, 16, channels, channels * 2, rate, false)
val pcmAudioStream = if (sourceFormat.encoding === Encoding.PCM_SIGNED)
sourceAudioStream
else
AudioSystem.getAudioInputStream(pcmFormat, sourceAudioStream)
// convert sample rate and channels
val targetAudioStream = if (pcmFormat.matches(audioFormat))
pcmAudioStream
else
AudioSystem.getAudioInputStream(audioFormat, pcmAudioStream)
// encode to ADPCM
val encodedStream = ADPCMCodec.encode(targetAudioStream, volume)
return VoiceData(name, IOUtils.toByteArray(encodedStream))
}
fun forFile(soundFile: File, volume: Double = 1.0): VoiceData {
// read from file
val sourceAudioStream = AudioSystem.getAudioInputStream(soundFile)
val fileName = soundFile.name
val dot = fileName.lastIndexOf(".")
val name = fileName.substring(0, dot)
return forStream(sourceAudioStream, name, volume)
}
}
var name = name
set(name) {
field = if (name.length > 17) name.substring(0, 18) else name
invalidate()
}
val audioInputStream: AudioInputStream
get() = AudioInputStream(pcmInputStream, audioFormat, 2L * rawData.size.toLong())
val pcmData: ByteArray
get() = ADPCMCodec.decode(rawData)
val pcmInputStream: InputStream
get() = ADPCMCodec.decode(rawInputStream)
val rawInputStream: InputStream
get() = ByteArrayInputStream(rawData)
fun play() {
try {
Player.play(audioFormat, pcmInputStream)
} catch (e: LineUnavailableException) {
throw RuntimeException(e)
} catch (e: IOException) {
throw RuntimeException(e)
}
}
override fun toString(): String {
return String.format("VoiceData [name=%s]", this.name)
}
fun writeVox(voxFile: File) {
Files.write(voxFile.toPath(), rawData)
}
fun writeWav(wavFile: File) {
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, wavFile)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as VoiceData
if (!Arrays.equals(rawData, other.rawData)) return false
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
var result = Arrays.hashCode(rawData)
result = 31 * result + (name.hashCode())
return result
}
fun clone(): VoiceData = VoiceData(this.name, this.rawData)
}
| lgpl-3.0 | 7e30664f8e6d92a001fecb0a73eead77 | 31.626087 | 107 | 0.628998 | 4.626387 | false | false | false | false |
datawire/discovery | discovery-server/src/test/kotlin/io/datawire/discovery/auth/DiscoveryAuthHandlerTest.kt | 1 | 5237 | package io.datawire.discovery.auth
import io.datawire.discovery.DiscoveryTest
import io.vertx.core.AbstractVerticle
import io.vertx.core.DeploymentOptions
import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.ext.auth.jwt.JWTAuth
import io.vertx.ext.auth.jwt.JWTOptions
import io.vertx.ext.unit.TestContext
import io.vertx.ext.unit.junit.VertxUnitRunner
import io.vertx.ext.web.Router
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.net.ServerSocket
import java.util.*
/**
* Unit tests for [DiscoveryAuthHandler]. The DiscoveryAuthHandler only checks to see whether the provided
* Json Web Token (JWT) can be verified (signature match). It is not concerned with verifying any claims provided by
* the token.
*
* TODO: Enhance these test cases once more stringent claim validation is implemented.
*/
@RunWith(VertxUnitRunner::class)
class DiscoveryAuthHandlerTest : DiscoveryTest() {
lateinit private var validJsonWebToken: String
lateinit private var invalidJsonWebToken: String
lateinit private var authProvider: JWTAuth
lateinit private var vertx: Vertx
lateinit private var socket: ServerSocket
private var port: Int = 0
@Before
fun setup(context: TestContext) {
vertx = Vertx.vertx()
socket = ServerSocket(0)
port = socket.localPort
socket.close()
val jsonWebTokenKeyStoreConfig = buildJsonWebTokenKeyStoreConfig(
path = resourcePath("ks-hmac256-notasecret.jceks"),
password = "notasecret")
vertx.deployVerticle(
TestVerticle(),
DeploymentOptions().setConfig(JsonObject(mapOf(
"http.port" to port,
"auth.jwt" to jsonWebTokenKeyStoreConfig)
)),
context.asyncAssertSuccess())
authProvider = JWTAuth.create(vertx, jsonWebTokenKeyStoreConfig)
validJsonWebToken = authProvider.generateToken(JsonObject().put("aud", "VALID_AUDIENCE"), JWTOptions())
invalidJsonWebToken = makeInvalidToken("INVALID_AUDIENCE")
}
@After
fun teardown(context: TestContext) {
socket.close()
vertx.close(context.asyncAssertSuccess())
}
@Test
fun useTokenQueryParameterIfPresent(context: TestContext) {
val async = context.async()
val http = vertx.createHttpClient()
val request = http.post(port, "localhost", "/authenticated?token=$validJsonWebToken") { resp ->
resp.bodyHandler {
context.assertEquals(204, resp.statusCode())
http.close()
async.complete()
}
}
request.end()
}
@Test
fun useAuthorizationHeaderWithBearerTokenIfPresent(context: TestContext) {
val async = context.async()
val http = vertx.createHttpClient()
val request = http.post(port, "localhost", "/authenticated") { resp ->
resp.bodyHandler {
context.assertEquals(204, resp.statusCode())
http.close()
async.complete()
}
}
request.putHeader("Authorization", "Bearer $validJsonWebToken")
request.end()
}
@Test
fun useTokenQueryParameterBeforeAttemptingToUseAuthorizationHeaderWithBearerToken(context: TestContext) {
val async = context.async()
val http = vertx.createHttpClient()
val request = http.post(port, "localhost", "/authenticated?token=$validJsonWebToken") { resp ->
resp.bodyHandler {
context.assertEquals(204, resp.statusCode())
http.close()
async.complete()
}
}
// If the logic in the handler is not correct then the invalid token will be used.
request.putHeader("Authorization", "Bearer $invalidJsonWebToken")
request.end()
}
@Test
fun failIfTokenIsIncorrectlySigned(context: TestContext) {
val async = context.async()
val http = vertx.createHttpClient()
val request = http.post(port, "localhost", "/authenticated?token=$invalidJsonWebToken") { resp ->
resp.bodyHandler {
context.assertEquals(401, resp.statusCode())
http.close()
async.complete()
}
}
request.end()
}
private fun makeInvalidToken(aud: String): String {
val (header, claims, signature) = validJsonWebToken.split(".")
val decodedClaims = Base64.getUrlDecoder().decode(claims)
val typeFactory = objectMapper.typeFactory
val mapType = typeFactory.constructMapType(HashMap::class.java, String::class.java, String::class.java)
val claimsMap = objectMapper.readValue<HashMap<String, String>>(decodedClaims, mapType)
claimsMap["aud"] = aud
val falseClaims = objectMapper.writeValueAsBytes(claimsMap)
return listOf(header, Base64.getUrlEncoder().encodeToString(falseClaims), signature).joinToString(".")
}
class TestVerticle : AbstractVerticle() {
override fun start() {
val router = Router.router(this.vertx)
val authProvider = JWTAuth.create(this.vertx, config().getJsonObject("auth.jwt"))
router.post("/authenticated").handler(DiscoveryAuthHandler(authProvider, null))
router.post("/authenticated").handler { rc ->
rc.response().setStatusCode(204).end()
}
val server = this.vertx.createHttpServer()
server.requestHandler { router.accept(it) }.listen(config().getInteger("http.port"))
}
}
} | apache-2.0 | 24062ec85a7e3e494422e6129668e251 | 29.277457 | 116 | 0.707466 | 4.404542 | false | true | false | false |
bixlabs/bkotlin | bkotlin/src/main/java/com/bixlabs/bkotlin/Context.kt | 1 | 1597 | package com.bixlabs.bkotlin
import android.content.Context
import androidx.annotation.StringRes
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
/**
* Display the simple Toast message with the [Toast.LENGTH_SHORT] duration.
* @param message the message text.
*/
fun Context.shortToast(message: String) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
/**
* Display the simple Toast message with the [Toast.LENGTH_SHORT] duration.
* @param message the message text resource.
*/
fun Context.shortToast(@StringRes message: Int) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
/**
* Display the simple Toast message with the [Toast.LENGTH_LONG] duration.
* @param message the message text.
*/
fun Context.longToast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_LONG).show()
/**
* Display the simple Toast message with the [Toast.LENGTH_LONG] duration.
* @param message the message text resource.
*/
fun Context.longToast(@StringRes message: Int) = Toast.makeText(this, message, Toast.LENGTH_LONG).show()
/**
* Shortcut for LayoutInflater.from(this)
*/
fun Context.inflate(layoutResource: Int, parent: ViewGroup? = null, attachToRoot: Boolean = false) {
LayoutInflater.from(this).inflate(layoutResource, parent, attachToRoot)
}
/**
* get Height of status bar
* @return height of status bar
*/
fun Context.getStatusBarHeight(): Int {
val resourceId = this.resources.getIdentifier("status_bar_height", "dimen", "android")
return this.resources.getDimensionPixelSize(resourceId)
}
| apache-2.0 | f6f6d28b128f05aa06c278d9313768e2 | 32.270833 | 106 | 0.752661 | 3.94321 | false | false | false | false |
breadwallet/breadwallet-android | app-core/src/main/java/com/breadwallet/platform/entities/WalletInfoData.kt | 1 | 3765 | package com.breadwallet.platform.entities
import com.breadwallet.crypto.WalletManagerMode
import com.breadwallet.logger.logError
import com.platform.util.getIntOrDefault
import com.platform.util.getLongOrDefault
import com.platform.util.getStringOrNull
import org.json.JSONException
import org.json.JSONObject
/**
* BreadWallet
*
* Created by Mihail Gutan <[email protected]> on 6/22/17.
* Copyright (c) 2017 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
data class WalletInfoData(
val classVersion: Int = DEFAULT_CLASS_VERSION,
val creationDate: Long = DEFAULT_CREATION_DATE,
val name: String? = null,
val connectionModes: Map<String, WalletManagerMode> = emptyMap()
) {
companion object {
private const val NAME = "name"
private const val CLASS_VERSION = "classVersion"
private const val CREATION_DATE = "creationDate"
private const val CONNECTION_MODES = "connectionModes"
private const val DEFAULT_CLASS_VERSION = 3
private const val DEFAULT_CREATION_DATE = 0L
fun fromJsonObject(json: JSONObject): WalletInfoData = json.run {
WalletInfoData(
classVersion = getIntOrDefault(CLASS_VERSION, DEFAULT_CLASS_VERSION),
creationDate = getLongOrDefault(CREATION_DATE, DEFAULT_CREATION_DATE),
name = getStringOrNull(NAME),
connectionModes = getConnectionModes(this)
)
}
private fun getConnectionModes(json: JSONObject): Map<String, WalletManagerMode> {
val mutableModes = mutableMapOf<String, WalletManagerMode>()
val modes = json.optJSONArray(CONNECTION_MODES) ?: return mutableModes.toMap()
try {
var currencyId = ""
for (i in 0 until modes.length()) {
if (i % 2 == 0) currencyId = modes.getString(i)
else mutableModes[currencyId] =
WalletManagerMode.fromSerialization(modes.getInt(i))
}
} catch (ex: JSONException) {
logError("Malformed $CONNECTION_MODES array: $modes")
}
return mutableModes.toMap()
}
}
fun toJSON(): JSONObject {
val connectionModesList = mutableListOf<Any>()
connectionModes.entries.forEach {
connectionModesList.add(it.key)
connectionModesList.add(it.value.toSerialization())
}
return JSONObject(
mapOf(
CLASS_VERSION to classVersion,
CREATION_DATE to creationDate,
NAME to name,
CONNECTION_MODES to connectionModesList
)
)
}
}
| mit | 4d9d520f5ced2123287e50e7eb8887b2 | 39.483871 | 90 | 0.666135 | 4.895969 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/ui/original/AdBlockFragment.kt | 1 | 12905 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.adblock.ui.original
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.ActionMode
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.github.clans.fab.FloatingActionButton
import com.github.clans.fab.FloatingActionMenu
import jp.hazuki.yuzubrowser.adblock.R
import jp.hazuki.yuzubrowser.adblock.repository.original.AdBlock
import jp.hazuki.yuzubrowser.adblock.repository.original.AdBlockManager
import jp.hazuki.yuzubrowser.ui.extensions.applyIconColor
import jp.hazuki.yuzubrowser.ui.widget.recycler.DividerItemDecoration
import jp.hazuki.yuzubrowser.ui.widget.recycler.OnRecyclerListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.IOException
import java.io.PrintWriter
import java.util.*
class AdBlockFragment : Fragment(), OnRecyclerListener, AdBlockEditDialog.AdBlockEditDialogListener, AdBlockMenuDialog.OnAdBlockMenuListener, AdBlockItemDeleteDialog.OnBlockItemDeleteListener, ActionMode.Callback, DeleteSelectedDialog.OnDeleteSelectedListener, AdBlockDeleteAllDialog.OnDeleteAllListener {
private lateinit var provider: AdBlockManager.AdBlockItemProvider
private lateinit var adapter: AdBlockArrayRecyclerAdapter
private lateinit var layoutManager: LinearLayoutManager
private var listener: AdBlockFragmentListener? = null
private var actionMode: ActionMode? = null
private var type: Int = 0
private var isModified = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
setHasOptionsMenu(true)
return inflater.inflate(R.layout.fragment_ad_block_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val activity = activity ?: return
val arguments = arguments ?: return
type = arguments.getInt(ARG_TYPE)
listener!!.setFragmentTitle(type)
provider = AdBlockManager.getProvider(activity.applicationContext, type)
adapter = AdBlockArrayRecyclerAdapter(activity, provider.allItems, this)
layoutManager = LinearLayoutManager(activity)
val recyclerView: RecyclerView = view.findViewById(R.id.recyclerView)
val fabMenu: FloatingActionMenu = view.findViewById(R.id.fabMenu)
val addByEditFab: FloatingActionButton = view.findViewById(R.id.addByEditFab)
val addFromFileFab: FloatingActionButton = view.findViewById(R.id.addFromFileFab)
recyclerView.let {
it.layoutManager = layoutManager
it.addItemDecoration(DividerItemDecoration(activity))
it.adapter = adapter
}
addByEditFab.setOnClickListener {
AdBlockEditDialog(getString(R.string.add))
.show(childFragmentManager, "add")
fabMenu.close(true)
}
addFromFileFab.setOnClickListener {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "*/*"
startActivityForResult(Intent.createChooser(intent, null), REQUEST_SELECT_FILE)
fabMenu.close(false)
}
}
override fun onRecyclerItemClicked(v: View, position: Int) {
isModified = true
val adBlock = adapter[position]
adBlock.isEnable = !adBlock.isEnable
provider.update(adBlock)
adapter.notifyItemChanged(position)
}
override fun onRecyclerItemLongClicked(v: View, position: Int): Boolean {
if (!adapter.isMultiSelectMode) {
AdBlockMenuDialog(position, adapter[position].id)
.show(childFragmentManager, "menu")
}
return true
}
override fun onEdited(index: Int, id: Int, text: String) {
isModified = true
if (index >= 0 && index < adapter.itemCount) {
val adBlock = adapter[index]
adBlock.match = text
if (provider.update(adBlock)) {
adapter.notifyItemChanged(index)
} else {
adapter.remove(index)
provider.delete(adBlock.id)
}
} else {
if (id > -1) {
var i = 0
while (adapter.size() > i) {
val adBlock = adapter[i]
if (adBlock.id == id) {
adBlock.match = text
if (provider.update(adBlock)) {
adapter.notifyItemChanged(i)
} else {
adapter.remove(i)
provider.delete(adBlock.id)
}
break
}
i++
}
} else {
val adBlock = AdBlock(text)
if (provider.update(adBlock)) {
adapter.add(adBlock)
adapter.notifyDataSetChanged()
}
}
}
}
fun addAll(adBlocks: List<AdBlock>) {
isModified = true
provider.addAll(adBlocks)
adapter.clear()
adapter.addAll(provider.allItems)
adapter.notifyDataSetChanged()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQUEST_SELECT_FILE -> if (resultCode == Activity.RESULT_OK && data != null && data.data != null) {
listener!!.requestImport(data.data!!)
}
REQUEST_SELECT_EXPORT -> if (resultCode == Activity.RESULT_OK && data != null && data.data != null) {
GlobalScope.launch(Dispatchers.IO) {
try {
context?.run {
contentResolver.openOutputStream(data.data!!)!!.use { os ->
PrintWriter(os).use { pw ->
val adBlockList = provider.enableItems
for ((_, match) in adBlockList)
pw.println(match)
launch(Dispatchers.Main) {
Toast.makeText(context, R.string.pref_exported, Toast.LENGTH_SHORT).show()
}
}
}
}
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
}
override fun onAskDelete(index: Int, id: Int) {
AdBlockItemDeleteDialog(index, id, adapter[index].match)
.show(childFragmentManager, "delete")
}
override fun onDelete(index: Int, id: Int) {
val adBlock = getItem(index, id)
if (adBlock != null) {
isModified = true
adapter.remove(adBlock)
provider.delete(adBlock.id)
adapter.notifyDataSetChanged()
}
}
override fun onEdit(index: Int, id: Int) {
val adBlock = getItem(index, id)
if (adBlock != null) {
AdBlockEditDialog(getString(R.string.pref_edit), index, adBlock)
.show(childFragmentManager, "edit")
}
}
override fun startMultiSelect(index: Int) {
actionMode = (activity as AppCompatActivity).startSupportActionMode(this)
adapter.isMultiSelectMode = true
adapter.setSelect(index, true)
}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.ad_block_action_mode, menu)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu) = false
override fun onDeleteSelected() {
val items = adapter.selectedItems
Collections.sort(items, Collections.reverseOrder())
for (index in items) {
isModified = true
val (id) = adapter.remove(index)
provider.delete(id)
}
actionMode!!.finish()
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.delete -> {
actionMode = mode
DeleteSelectedDialog().show(childFragmentManager, "delete_selected")
return true
}
}
return false
}
override fun onDestroyActionMode(mode: ActionMode) {
adapter.isMultiSelectMode = false
}
private fun getItem(index: Int, id: Int): AdBlock? {
if (index < adapter.itemCount) {
val adBlock = adapter[index]
if (adBlock.id == id)
return adBlock
}
return getItemFromId(id)
}
private fun getItemFromId(id: Int) = adapter.items.firstOrNull { it.id == id }
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.ad_block_menu, menu)
applyIconColor(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val activity = activity ?: return false
when (item.itemId) {
android.R.id.home -> {
activity.onBackPressed()
return true
}
R.id.export -> {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
intent.type = "*/*"
intent.putExtra(Intent.EXTRA_TITLE, listener!!.getExportFileName(type))
startActivityForResult(intent, REQUEST_SELECT_EXPORT)
return true
}
R.id.deleteAll -> {
AdBlockDeleteAllDialog().show(childFragmentManager, "delete_all")
return true
}
R.id.sort_registration -> {
adapter.items.sortWith { m1, m2 -> m1.id.compareTo(m2.id) }
adapter.notifyDataSetChanged()
layoutManager.scrollToPosition(0)
return true
}
R.id.sort_registration_reverse -> {
adapter.items.sortWith { m1, m2 -> m2.id.compareTo(m1.id) }
adapter.notifyDataSetChanged()
layoutManager.scrollToPosition(0)
return true
}
R.id.sort_name -> {
adapter.items.sortWith { m1, m2 -> m1.match.compareTo(m2.match) }
adapter.notifyDataSetChanged()
layoutManager.scrollToPosition(0)
return true
}
R.id.sort_name_reverse -> {
adapter.items.sortWith { m1, m2 -> m2.match.compareTo(m1.match) }
adapter.notifyDataSetChanged()
layoutManager.scrollToPosition(0)
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onDeleteAll() {
isModified = true
provider.deleteAll()
adapter.clear()
adapter.notifyDataSetChanged()
}
override fun onAttach(context: Context) {
super.onAttach(context)
listener = activity as AdBlockFragmentListener
}
override fun onDestroy() {
super.onDestroy()
GlobalScope.launch(Dispatchers.IO) {
provider.updateCache()
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
interface AdBlockFragmentListener {
fun setFragmentTitle(type: Int)
fun requestImport(uri: Uri)
fun getExportFileName(type: Int): String
}
companion object {
private const val ARG_TYPE = "type"
private const val REQUEST_SELECT_FILE = 1
private const val REQUEST_SELECT_EXPORT = 2
operator fun invoke(type: Int): AdBlockFragment {
return AdBlockFragment().apply {
arguments = Bundle().apply {
putInt(ARG_TYPE, type)
}
}
}
}
}
| apache-2.0 | db5aa7a7736be503bf276b6ad229425c | 35.352113 | 305 | 0.591631 | 5.052858 | false | false | false | false |
AlexandrDrinov/kotlin-koans-edu | src/i_introduction/_2_Named_Arguments/NamedArguments.kt | 1 | 381 | package i_introduction._2_Named_Arguments
// default values for arguments:
fun bar(i: Int, s: String = "", b: Boolean = true) {}
fun usage() {
// named arguments:
bar(1, b = false)
}
fun todoTask2(collection: Collection<Int>): String = collection.joinToString(prefix="{", postfix="}")
fun task2(collection: Collection<Int>): String {
return todoTask2(collection)
}
| mit | 37dc030648f5cf27000d69e016f0bed1 | 24.4 | 101 | 0.67979 | 3.527778 | false | false | false | false |
AlmasB/Zephyria | src/main/kotlin/com/almasb/zeph/item/Weapon.kt | 1 | 3551 | package com.almasb.zeph.item
import com.almasb.fxgl.dsl.getUIFactoryService
import com.almasb.zeph.character.CharacterEntity
import com.almasb.zeph.combat.Stat
import javafx.beans.binding.Bindings
import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import javafx.beans.value.ChangeListener
import javafx.scene.paint.Color
import java.util.concurrent.Callable
enum class WeaponType(val range: Int, val aspdFactor: Float) {
ONE_H_SWORD(2, 0.85f), ONE_H_AXE(2, 0.95f), DAGGER(1, 1.25f), SPEAR(3, 0.85f), MACE(2, 1.0f), ROD(5, 0.9f), SHIELD(0, 0.9f), // 1H, shield only left-hand
TWO_H_SWORD(2, 0.7f), TWO_H_AXE(2, 0.65f), KATAR(1, 0.85f), BOW(5, 0.75f);
fun isTwoHanded() = this.ordinal >= TWO_H_SWORD.ordinal
}
/**
* Weapon item.
*
* @author Almas Baimagambetov ([email protected])
*/
class Weapon(private val data: WeaponData) : EquipItem(data.description, data.itemLevel, data.runes, data.essences) {
val element = SimpleObjectProperty(data.element)
val pureDamage = SimpleIntegerProperty()
val range
get() = data.type.range
val type
get() = data.type
private var damageListener: ChangeListener<Number>? = null
init {
pureDamage.bind(refineLevel.multiply(Bindings
.`when`(refineLevel.greaterThan(2))
.then(data.itemLevel.bonus + 1)
.otherwise(data.itemLevel.bonus))
.add(data.pureDamage))
dynamicDescription.bind(
SimpleStringProperty("")
.concat(description.name + "\n")
.concat(description.description + "\n")
.concat(element.asString("Element: %s").concat("\n"))
.concat(pureDamage.asString("Damage: %d").concat("\n"))
.concat(runes)
.concat(essences)
)
dynamicTextFlow.children.addAll(
getUIFactoryService().newText("", Color.WHITE, 14.0).also {
it.textProperty().bind(refineLevel.asString("Refinement Level: %d\n"))
},
getUIFactoryService().newText("Element: ", Color.WHITE, 14.0),
getUIFactoryService().newText("", 16.0).also {
it.fillProperty().bind(Bindings.createObjectBinding(Callable { element.value.color }, element))
it.textProperty().bind(element.asString("%s\n"))
},
getUIFactoryService().newText("Damage: ", Color.WHITE, 14.0),
getUIFactoryService().newText("", Color.WHITE, 16.0).also {
it.textProperty().bind(pureDamage.asString("%d\n"))
}
)
}
fun onAttack(attacker: CharacterEntity, target: CharacterEntity) {
data.onAttackScript.invoke(attacker, target)
}
override fun onEquip(char: CharacterEntity) {
super.onEquip(char)
char.addBonus(Stat.ATK, pureDamage.value)
// TODO: the same thing for Armor equipment
damageListener = ChangeListener<Number> { _, oldDamage, newDamage ->
char.addBonus(Stat.ATK, -oldDamage.toInt())
char.addBonus(Stat.ATK, newDamage.toInt())
}
pureDamage.addListener(damageListener)
}
override fun onUnEquip(char: CharacterEntity) {
super.onUnEquip(char)
char.addBonus(Stat.ATK, -pureDamage.value)
damageListener?.let {
pureDamage.removeListener(it)
}
}
}
| gpl-2.0 | 602cbb7dceb9e9c2da3f0e95c8cd8c87 | 34.158416 | 157 | 0.621233 | 4.021518 | false | false | false | false |
spinnaker/kork | kork-sql/src/test/kotlin/com/netflix/spinnaker/kork/sql/SpringStartupTests.kt | 3 | 2678 | /*
* 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.kork.sql
import com.netflix.spinnaker.kork.PlatformComponents
import com.netflix.spinnaker.kork.sql.config.DefaultSqlConfiguration
import com.netflix.spinnaker.kork.sql.health.SqlHealthIndicator
import org.jooq.DSLContext
import org.jooq.impl.DSL.field
import org.jooq.impl.DSL.table
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.getBeansOfType
import org.springframework.boot.actuate.health.HealthIndicator
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Import
import org.springframework.test.context.junit4.SpringRunner
import strikt.api.expectThat
import strikt.assertions.isA
import strikt.assertions.isEqualTo
import strikt.assertions.isNotNull
@RunWith(SpringRunner::class)
@SpringBootTest(
classes = [StartupTestApp::class],
properties = [
"sql.enabled=true",
"sql.migration.jdbcUrl=jdbc:h2:mem:test",
"sql.migration.dialect=H2",
"sql.connectionPool.jdbcUrl=jdbc:h2:mem:test",
"sql.connectionPool.dialect=H2"
]
)
internal class SpringStartupTests {
@Autowired
lateinit var dbHealthIndicator: HealthIndicator
@Autowired
lateinit var jooq: DSLContext
@Autowired
lateinit var applicationContext: ApplicationContext
@Test
fun `uses SqlHealthIndicator`() {
expectThat(dbHealthIndicator).isA<SqlHealthIndicator>()
expectThat(
jooq
.insertInto(table("healthcheck"), listOf(field("id")))
.values(true).execute()
).isEqualTo(1)
expectThat(applicationContext.getBeansOfType(DSLContext::class.java).size).isEqualTo(1)
expectThat(applicationContext.getBean("jooq")).isNotNull()
expectThat(applicationContext.getBean("liquibase")).isNotNull()
}
}
@SpringBootApplication
@Import(PlatformComponents::class, DefaultSqlConfiguration::class)
internal class StartupTestApp
| apache-2.0 | 1910fa7b80d06c928497d9d93db9b46f | 32.898734 | 91 | 0.786408 | 4.2848 | false | true | false | false |
paoloach/zdomus | temperature_monitor/app/src/main/java/it/achdjian/paolo/temperaturemonitor/graphic/GraphViewScale.kt | 1 | 1990 | package it.achdjian.paolo.temperaturemonitor.graphic
import android.content.Context
import android.util.Log
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
import it.achdjian.paolo.temperaturemonitor.domusEngine.DomusEngine
import org.joda.time.LocalDateTime
/**
* Created by Paolo Achdjian on 11/14/17.
*/
class GraphViewScale(val networkAddress:Int, context: Context, val domusEngine: DomusEngine) : View.OnTouchListener, ScaleGestureDetector.OnScaleGestureListener {
val scaleGestureDetector = ScaleGestureDetector(context, this)
var startSpanX = 0.0f;
var end = LocalDateTime()
var start = end.minusDays(1)
override fun onScaleBegin(detector: ScaleGestureDetector?): Boolean {
if (detector != null)
startSpanX = detector.currentSpanX;
return true;
}
override fun onScaleEnd(detector: ScaleGestureDetector?) {
if (detector != null) {
val factor = detector.getCurrentSpanX() / startSpanX
val period = (end.toDate().time - start.toDate().time)*factor
val toNow = LocalDateTime().toDate().time - end.toDate().time
if (toNow < period/2){
end= LocalDateTime()
start = end.minusMillis(period.toInt())
} else {
end = end.plusMillis((period/2).toInt())
start = start.minusMillis((period/2).toInt())
}
domusEngine.getTemperatureData(networkAddress, start, end)
Log.i("UI", "span: " + factor)
Log.i("UI", "start: " + start + ", end: " + end)
}
}
override fun onScale(detector: ScaleGestureDetector?): Boolean{
if (detector != null) {
Log.i("UI", "span: " + detector.getCurrentSpanX() / startSpanX)
}
return true;
}
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
return scaleGestureDetector.onTouchEvent(event);
}
} | gpl-2.0 | 5fb6ef66b7a18f0b6d608770ddb90f2f | 35.2 | 162 | 0.641709 | 4.502262 | false | false | false | false |
wuan/bo-android | app/src/main/java/org/blitzortung/android/map/overlay/ParticipantShape.kt | 1 | 1322 | /*
Copyright 2015 Andreas Würl
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.blitzortung.android.map.overlay
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.drawable.shapes.Shape
class ParticipantShape : Shape() {
private val rect: RectF = RectF()
private var color: Int = 0
init {
color = 0
}
override fun draw(canvas: Canvas, paint: Paint) {
paint.color = color
paint.alpha = 255
paint.style = Paint.Style.FILL
canvas.drawRect(rect, paint)
}
fun update(size: Float, color: Int) {
val halfSize = size / 2f
rect.set(-halfSize, -halfSize, halfSize, halfSize)
resize(rect.width(), rect.width())
this.color = color
}
}
| apache-2.0 | b507991927c2a616535994f2dd865532 | 25.959184 | 75 | 0.687358 | 4.26129 | false | false | false | false |
EMResearch/EvoMaster | e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/mutation/DataRepository.kt | 1 | 877 | package com.foo.graphql.mutation
import com.foo.graphql.mutation.type.Flower
import org.springframework.stereotype.Component
import java.util.concurrent.atomic.AtomicInteger
@Component
open class DataRepository {
private val flowers = mutableMapOf<Int?, Flower>()
private val counter = AtomicInteger(0)
init {
listOf(Flower(0, "Darcey", "Roses", "Red", 50),
Flower(1, "Candy Prince", "Tulips", "Pink", 18),
Flower(2, "Lily", "Lilies", "White", 30),
Flower(3, "Lavender", "Limonium", "Purple", 25)
).forEach { flowers[it.id] = it }
}
fun allFlowers(): Collection<Flower> = flowers.values
fun saveFlower(name: String?, type: String? , color: String?, price: Int?): Flower {
val id = counter.getAndIncrement()
return Flower(id, name, type, color, price)
}
}
| lgpl-3.0 | 4a3f082f9500323c045c71fcfc5e40ce | 23.361111 | 88 | 0.625998 | 3.669456 | false | false | false | false |
d9n/trypp.support | src/main/code/trypp/support/pattern/StateMachine.kt | 1 | 4844 | package trypp.support.pattern
import trypp.support.memory.Pool
import trypp.support.memory.Poolable
import trypp.support.pattern.observer.Event3
import trypp.support.pattern.observer.Event4
import java.util.*
/**
* Encapsulation of a finite state machine.
*
* You instantiate a state machine by registering a list of states and a list of events that it can
* accept in each state.
*
* You must [freeze] a state machine before you can start using it. Once frozen, you can't
* register any more states.
*
* @param S An enumeration type that represents the known states this machine can get into.
* @param E An enumeration type that represents the known events this machine can accept.
* @param initialState The first state this machine will start out in
*/
class StateMachine<S : Enum<S>, E : Enum<E>>(private val initialState: S) {
internal data class StateEventKey(var state: Any?, var event: Any?) : Poolable {
constructor() : this(null, null)
override fun reset() {
state = null
event = null
}
}
/**
* Method for handling a state transition. Given a state and an event, run some logic and then
* return the new state that the state machine should be in.
*/
interface EventHandler<S : Enum<S>, E : Enum<E>> {
fun run(state: S, event: E, eventData: Any?): S
}
var currentState = initialState
private set
/**
* Event that is triggered anytime a successful state transition occurs.
*
* S - oldState
* E - event
* S - newState
* Any? - eventData
*
* The event will be run on the same thread [handle] is called on.
*/
val onTransition = Event4<S, E, S, Any?>()
/**
* Method that is called anytime an event is unhandled. Often useful for logging.
*
* S - state
* E - event
* Any? - eventData
*
* The event will be run on the same thread [handle] is called on.
*/
val onUnhandled = Event3<S, E, Any?>()
private val eventHandlers = HashMap<StateEventKey, EventHandler<S, E>>()
private val keyPool = Pool.of(StateEventKey::class, capacity = 1)
var frozen = false
private set
/**
* Reset this state machine back to its initial state.
*/
fun reset() {
currentState = initialState
frozen = false
keyPool.freeAll()
eventHandlers.clear()
onTransition.clearListeners()
onUnhandled.clearListeners()
}
/**
* Register a state and a handler for whenever we receive an event in that state.
*
* The handler will be called on the same thread that [handle] is called on.
*
* @throws IllegalArgumentException if duplicate state/event pairs are registered
*/
fun registerTransition(state: S, event: E, handler: EventHandler<S, E>) {
if (frozen) {
throw IllegalStateException("Can't register transition on frozen state machine")
}
val key = StateEventKey(state, event)
if (eventHandlers.containsKey(key)) {
throw IllegalArgumentException(
"Duplicate registration of state+event pair: ${key.state}, ${key.event}.")
}
eventHandlers.put(key, handler)
}
/**
* Convenience method for [registerTransition] that takes a lambda for conciseness.
*/
fun registerTransition(state: S, event: E, handle: (S, E, Any?) -> S) {
registerTransition(state, event, object : EventHandler<S, E> {
override fun run(state: S, event: E, eventData: Any?): S {
return handle(state, event, eventData)
}
})
}
fun freeze() {
if (frozen) {
throw IllegalStateException("Can't freeze already frozen state machine")
}
frozen = true
}
/**
* Tell the state machine to handle the passed in event given the current state.
*/
fun handle(event: E): Boolean {
return handle(event, null)
}
/**
* Like [handle] but with some additional data that is related to the event.
*/
fun handle(event: E, eventData: Any?): Boolean {
if (!frozen) {
throw IllegalStateException("You must freeze this state machine before firing events")
}
val key = keyPool.grabNew()
key.state = currentState
key.event = event
val eventHandler = eventHandlers[key]
keyPool.free(key)
val prevState = currentState
if (eventHandler != null) {
currentState = eventHandler.run(prevState, event, eventData)
onTransition(prevState, event, currentState, eventData)
return true
}
else {
onUnhandled(currentState, event, eventData)
return false
}
}
}
| mit | d0f25dbb6f3f05c1e2d2a6cf7df6d11e | 29.658228 | 99 | 0.618084 | 4.481036 | false | false | false | false |
Subsets and Splits